content_type stringclasses 8 values | main_lang stringclasses 7 values | message stringlengths 1 50 | sha stringlengths 40 40 | patch stringlengths 52 962k | file_count int64 1 300 |
|---|---|---|---|---|---|
Text | Text | add alex good to credits (whoop!) | 72d72e4d3e497000bab8019151972b0e71f6957a | <ide><path>docs/topics/credits.md
<ide> The following people have helped make REST framework great.
<ide> * Alexander Lukanin - [alexanderlukanin13]
<ide> * Yamila Moreno - [yamila-moreno]
<ide> * Rob Hudson - [robhudson]
<add>* Alex Good - [alexjg]
<ide>
<ide> Many thanks to everyone who's contributed to the project.
<ide>
<ide> You can also contact [@_tomchristie][twitter] directly on twitter.
<ide> [alexanderlukanin13]: https://github.com/alexanderlukanin13
<ide> [yamila-moreno]: https://github.com/yamila-moreno
<ide> [robhudson]: https://github.com/robhudson
<add>[alexjg]: https://github.com/alexjg | 1 |
Python | Python | fix mypy issues in www/views.py | 7570dfbf51cd83e6ddae0abf29c52b81715d2811 | <ide><path>airflow/www/views.py
<ide> from functools import wraps
<ide> from json import JSONDecodeError
<ide> from operator import itemgetter
<del>from typing import Any, Callable, List, Optional, Set, Tuple, Union
<add>from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union
<ide> from urllib.parse import parse_qsl, unquote, urlencode, urlparse
<ide>
<ide> import lazy_object_proxy
<ide> class AirflowBaseView(BaseView):
<ide> }
<ide>
<ide> if not conf.getboolean('core', 'unit_test_mode'):
<del> extra_args['sqlite_warning'] = settings.Session.bind.dialect.name == 'sqlite'
<add> extra_args['sqlite_warning'] = settings.engine.dialect.name == 'sqlite'
<ide> extra_args['sequential_executor_warning'] = conf.get('core', 'executor') == 'SequentialExecutor'
<ide>
<ide> line_chart_attr = {
<ide> class ConnectionModelView(AirflowModelView):
<ide> edit_columns = add_columns.copy()
<ide>
<ide> # Initialized later by lazy_add_provider_discovered_options_to_connection_form
<del> extra_fields = []
<add> extra_fields: List[str] = []
<ide>
<ide> add_form = edit_form = ConnectionForm
<ide> add_template = 'airflow/conn_create.html'
<ide> def action_clear(self, drs: List[DagRun], session=None):
<ide> try:
<ide> count = 0
<ide> cleared_ti_count = 0
<del> dag_to_tis = {}
<add> dag_to_tis: Dict[DAG, List[TaskInstance]] = {}
<ide> for dr in session.query(DagRun).filter(DagRun.id.in_([dagrun.id for dagrun in drs])).all():
<ide> count += 1
<ide> dag = current_app.dag_bag.get_dag(dr.dag_id)
<ide> class DagDependenciesView(AirflowBaseView):
<ide> )
<ide> )
<ide> last_refresh = timezone.utcnow() - refresh_interval
<del> nodes = []
<del> edges = []
<add> nodes: List[Dict[str, Any]] = []
<add> edges: List[Dict[str, str]] = []
<ide>
<ide> @expose('/dag-dependencies')
<ide> @auth.has_access(
<ide> def list(self):
<ide>
<ide> def _calculate_graph(self):
<ide>
<del> nodes = []
<del> edges = []
<add> nodes: List[Dict[str, Any]] = []
<add> edges: List[Dict[str, str]] = []
<ide>
<ide> for dag, dependencies in SerializedDagModel.get_dag_dependencies().items():
<ide> dag_node_id = f"dag:{dag}" | 1 |
Ruby | Ruby | make `chown` recommendation consistent | ca5b7440c69a37b5f03f7b8949df27d8824d307d | <ide><path>Library/Homebrew/diagnostic.rb
<ide> def check_access_usr_local
<ide>
<ide> You should probably change the ownership and permissions of /usr/local
<ide> back to your user account.
<del> sudo chown -R $(whoami):admin /usr/local
<add> sudo chown -R $(whoami) /usr/local
<ide> EOS
<ide> end
<ide> end | 1 |
PHP | PHP | add test for cachemanager | b74e66b1588e6517f93a759c301246aaaa5135d0 | <ide><path>tests/Cache/CacheManagerTest.php
<ide>
<ide> use Illuminate\Cache\ArrayStore;
<ide> use Illuminate\Cache\CacheManager;
<add>use Illuminate\Cache\NullStore;
<ide> use Illuminate\Config\Repository;
<ide> use Illuminate\Container\Container;
<add>use Illuminate\Contracts\Events\Dispatcher;
<add>use Illuminate\Events\Dispatcher as Event;
<ide> use InvalidArgumentException;
<ide> use Mockery as m;
<ide> use PHPUnit\Framework\TestCase;
<ide> public function testCustomDriverClosureBoundObjectIsCacheManager()
<ide> $this->assertEquals($cacheManager, $cacheManager->store(__CLASS__));
<ide> }
<ide>
<add> public function testCustomDriverOverridesInternalDrivers()
<add> {
<add> $userConfig = [
<add> 'cache' => [
<add> 'stores' => [
<add> 'my_store' => [
<add> 'driver' => 'array',
<add> ],
<add> ],
<add> ],
<add> ];
<add>
<add> $app = $this->getApp($userConfig);
<add> $cacheManager = new CacheManager($app);
<add>
<add> $myArrayDriver = (object) ['flag' => 'mm(u_u)mm'];
<add> $cacheManager->extend('array', fn () => $myArrayDriver);
<add>
<add> $driver = $cacheManager->store('my_store');
<add>
<add> $this->assertEquals('mm(u_u)mm', $driver->flag);
<add> }
<add>
<add> public function testItMakesRepositoryWhenContainerHasNoDispatcher()
<add> {
<add> $userConfig = [
<add> 'cache' => [
<add> 'stores' => [
<add> 'my_store' => [
<add> 'driver' => 'array',
<add> ],
<add> ],
<add> ],
<add> ];
<add>
<add> $app = $this->getApp($userConfig);
<add> $this->assertFalse($app->bound(Dispatcher::class));
<add>
<add> $cacheManager = new CacheManager($app);
<add> $repo = $cacheManager->repository($theStore = new NullStore);
<add>
<add> $this->assertNull($repo->getEventDispatcher());
<add> $this->assertSame($theStore, $repo->getStore());
<add>
<add> // binding dispatcher after the repo's birth will have no effect.
<add> $app->bind(Dispatcher::class, fn () => new Event);
<add>
<add> $this->assertNull($repo->getEventDispatcher());
<add> $this->assertSame($theStore, $repo->getStore());
<add>
<add> $cacheManager = new CacheManager($app);
<add> $repo = $cacheManager->repository(new NullStore);
<add> // now that the $app has a Dispatcher, the newly born repository will also have one.
<add> $this->assertNotNull($repo->getEventDispatcher());
<add> }
<add>
<ide> public function testForgetDriver()
<ide> {
<ide> $cacheManager = m::mock(CacheManager::class)
<ide> public function testThrowExceptionWhenUnknownDriverIsUsed()
<ide> ],
<ide> ];
<ide>
<del> $app = Container::getInstance();
<del> $app->bind('config', function () use ($userConfig) {
<del> return new Repository($userConfig);
<del> });
<add> $app = $this->getApp($userConfig);
<ide>
<ide> $cacheManager = new CacheManager($app);
<ide>
<ide> public function testThrowExceptionWhenUnknownStoreIsUsed()
<ide> ],
<ide> ];
<ide>
<del> $app = Container::getInstance();
<del> $app->bind('config', function () use ($userConfig) {
<del> return new Repository($userConfig);
<del> });
<add> $app = $this->getApp($userConfig);
<ide>
<ide> $cacheManager = new CacheManager($app);
<ide>
<ide> $cacheManager->store('alien_store');
<ide> }
<add>
<add> protected function getApp(array $userConfig)
<add> {
<add> $app = Container::getInstance();
<add> $app->bind('config', fn () => new Repository($userConfig));
<add>
<add> return $app;
<add> }
<ide> } | 1 |
Java | Java | fix typos in log messages of nativeanimatedmodule | 3c6c5f057a78bed7e69b0834ca0894f3b5261149 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/animated/NativeAnimatedModule.java
<ide> public void disconnectAnimatedNodeFromView(
<ide> if (ANIMATED_MODULE_DEBUG) {
<ide> FLog.d(
<ide> NAME,
<del> "queue connectAnimatedNodeToView: disconnectAnimatedNodeFromView: "
<del> + animatedNodeTag
<del> + " viewTag: "
<del> + viewTag);
<add> "queue: disconnectAnimatedNodeFromView: " + animatedNodeTag + " viewTag: " + viewTag);
<ide> }
<ide>
<ide> decrementInFlightAnimationsForViewTag(viewTag);
<ide> public void execute(NativeAnimatedNodesManager animatedNodesManager) {
<ide> if (ANIMATED_MODULE_DEBUG) {
<ide> FLog.d(
<ide> NAME,
<del> "execute connectAnimatedNodeToView: disconnectAnimatedNodeFromView: "
<add> "execute: disconnectAnimatedNodeFromView: "
<ide> + animatedNodeTag
<ide> + " viewTag: "
<ide> + viewTag);
<ide> public void removeAnimatedEventFromView(
<ide> if (ANIMATED_MODULE_DEBUG) {
<ide> FLog.d(
<ide> NAME,
<del> "queue addAnimatedEventToView: removeAnimatedEventFromView: "
<add> "queue removeAnimatedEventFromView: viewTag: "
<ide> + viewTag
<ide> + " eventName: "
<ide> + eventName
<ide> public void execute(NativeAnimatedNodesManager animatedNodesManager) {
<ide> if (ANIMATED_MODULE_DEBUG) {
<ide> FLog.d(
<ide> NAME,
<del> "execute addAnimatedEventToView: removeAnimatedEventFromView: "
<add> "execute removeAnimatedEventFromView: viewTag: "
<ide> + viewTag
<ide> + " eventName: "
<ide> + eventName | 1 |
Javascript | Javascript | expose event statics | 9d324f0441688cef6b9403f2492e6d41cc6a2fc2 | <ide><path>lib/internal/event_target.js
<ide> class Event {
<ide> get bubbles() { return this.#bubbles; }
<ide> get composed() { return this.#composed; }
<ide> get eventPhase() {
<del> return this[kTarget] ? 2 : 0; // Equivalent to AT_TARGET or NONE
<add> return this[kTarget] ? Event.AT_TARGET : Event.NONE;
<ide> }
<ide> get cancelBubble() { return this.#propagationStopped; }
<ide> set cancelBubble(value) {
<ide> class Event {
<ide> stopPropagation() {
<ide> this.#propagationStopped = true;
<ide> }
<add>
<add> static NONE = 0;
<add> static CAPTURING_PHASE = 1;
<add> static AT_TARGET = 2;
<add> static BUBBLING_PHASE = 3;
<ide> }
<ide>
<ide> Object.defineProperty(Event.prototype, SymbolToStringTag, {
<ide><path>test/parallel/test-eventtarget.js
<ide> ok(EventTarget);
<ide> target.removeEventListener('foo', a, { capture: false });
<ide> target.dispatchEvent(new Event('foo'));
<ide> }
<del>
<ide> {
<ide> const target = new EventTarget();
<ide> strictEqual(target.toString(), '[object EventTarget]');
<ide> ok(EventTarget);
<ide> });
<ide> });
<ide> }
<add>
<add>{
<add> strictEqual(Event.NONE, 0);
<add> strictEqual(Event.CAPTURING_PHASE, 1);
<add> strictEqual(Event.AT_TARGET, 2);
<add> strictEqual(Event.BUBBLING_PHASE, 3);
<add> strictEqual(new Event('foo').eventPhase, Event.NONE);
<add> const target = new EventTarget();
<add> target.addEventListener('foo', common.mustCall((e) => {
<add> strictEqual(e.eventPhase, Event.AT_TARGET);
<add> }), { once: true });
<add> target.dispatchEvent(new Event('foo'));
<add>} | 2 |
Ruby | Ruby | handle the case where 64bit time_t won't overflow | 006cbb8fde3f20a684eabcfd11c53ae762cf8435 | <ide><path>activesupport/test/core_ext/time_ext_test.rb
<ide> def test_time_with_datetime_fallback
<ide> assert_equal Time.time_with_datetime_fallback(:utc, 2005), Time.utc(2005)
<ide> assert_equal Time.time_with_datetime_fallback(:utc, 2039), DateTime.civil(2039, 1, 1, 0, 0, 0, 0, 0)
<ide> assert_equal Time.time_with_datetime_fallback(:utc, 2005, 2, 21, 17, 44, 30, 1), Time.utc(2005, 2, 21, 17, 44, 30, 1) #with usec
<del> assert_equal Time.time_with_datetime_fallback(:utc, 2039, 2, 21, 17, 44, 30, 1), DateTime.civil(2039, 2, 21, 17, 44, 30, 0, 0)
<add> # This won't overflow on 64bit linux
<add> expected_to_overflow = Time.time_with_datetime_fallback(:utc, 2039, 2, 21, 17, 44, 30, 1)
<add> unless expected_to_overflow.is_a?(Time)
<add> assert_equal Time.time_with_datetime_fallback(:utc, 2039, 2, 21, 17, 44, 30, 1),
<add> DateTime.civil(2039, 2, 21, 17, 44, 30, 0, 0)
<add> end
<ide> assert_equal ::Date::ITALY, Time.time_with_datetime_fallback(:utc, 2039, 2, 21, 17, 44, 30, 1).start # use Ruby's default start value
<ide> end
<ide> | 1 |
Text | Text | fix typo in dns docs | 64b50468bbf04120980d6d46289131df421a693d | <ide><path>doc/api/dns.md
<ide> An independent resolver for DNS requests.
<ide> Note that creating a new resolver uses the default server settings. Setting
<ide> the servers used for a resolver using
<ide> [`resolver.setServers()`][`dns.setServers()`] does not affect
<del>other resolver:
<add>other resolvers:
<ide>
<ide> ```js
<ide> const { Resolver } = require('dns'); | 1 |
Go | Go | reduce the destroy timeout from 10 to 3 seconds | 28fd289b448164b77affd8103c0d96fd8110daf9 | <ide><path>runtime.go
<ide> func (runtime *Runtime) Destroy(container *Container) error {
<ide> return fmt.Errorf("Container %v not found - maybe it was already destroyed?", container.Id)
<ide> }
<ide>
<del> if err := container.Stop(10); err != nil {
<add> if err := container.Stop(3); err != nil {
<ide> return err
<ide> }
<ide> if mounted, err := container.Mounted(); err != nil {
<ide><path>server.go
<ide> func (srv *Server) ContainerAttach(name string, logs, stream, stdin, stdout, std
<ide> if container == nil {
<ide> return fmt.Errorf("No such container: %s", name)
<ide> }
<add>
<ide> //logs
<ide> if logs {
<ide> if stdout { | 2 |
Text | Text | discourage error event | cf5f6af8d68995abe28da236e5d16194fce76a75 | <ide><path>doc/api/events.md
<ide> target.addEventListener('foo', handler4, { once: true });
<ide> ### `EventTarget` error handling
<ide>
<ide> When a registered event listener throws (or returns a Promise that rejects),
<del>by default the error is forwarded to the `process.on('error')` event
<del>on `process.nextTick()`. Throwing within an event listener will *not* stop
<del>the other registered handlers from being invoked.
<add>by default the error is treated as an uncaught exception on
<add>`process.nextTick()`. This means uncaught exceptions in `EventTarget`s will
<add>terminate the Node.js process by default.
<ide>
<del>The `EventTarget` does not implement any special default handling for
<del>`'error'` type events.
<add>Throwing within an event listener will *not* stop the other registered handlers
<add>from being invoked.
<add>
<add>The `EventTarget` does not implement any special default handling for `'error'`
<add>type events like `EventEmitter`.
<add>
<add>Currently errors are first forwarded to the `process.on('error')` event
<add>before reaching `process.on('uncaughtException')`. This behavior is
<add>deprecated and will change in a future release to align `EventTarget` with
<add>other Node.js APIs. Any code relying on the `process.on('error')` event should
<add>be aligned with the new behavior.
<ide>
<ide> ### Class: `Event`
<ide> <!-- YAML | 1 |
Java | Java | allow async metadata in rsocketrequester | 996f7290cf97df2938287630ca956fe5ac35fdc8 | <ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/DefaultRSocketRequester.java
<ide> private DataBufferFactory bufferFactory() {
<ide>
<ide> private class DefaultRequestSpec implements RequestSpec {
<ide>
<del> private final MetadataEncoder metadataEncoder;
<add> private final MetadataEncoder metadataEncoder = new MetadataEncoder(metadataMimeType(), strategies);
<ide>
<ide> @Nullable
<del> private Mono<Payload> payloadMono = emptyPayload();
<add> private Mono<Payload> payloadMono;
<ide>
<ide> @Nullable
<del> private Flux<Payload> payloadFlux = null;
<add> private Flux<Payload> payloadFlux;
<ide>
<ide>
<ide> public DefaultRequestSpec(String route, Object... vars) {
<del> this.metadataEncoder = new MetadataEncoder(metadataMimeType(), strategies);
<ide> this.metadataEncoder.route(route, vars);
<ide> }
<ide>
<ide> public DefaultRequestSpec(Object metadata, @Nullable MimeType mimeType) {
<del> this.metadataEncoder = new MetadataEncoder(metadataMimeType(), strategies);
<ide> this.metadataEncoder.metadata(metadata, mimeType);
<ide> }
<ide>
<ide> else if (adapter != null) {
<ide> publisher = adapter.toPublisher(input);
<ide> }
<ide> else {
<del> this.payloadMono = Mono
<del> .fromCallable(() -> encodeData(input, ResolvableType.forInstance(input), null))
<del> .map(this::firstPayload)
<del> .doOnDiscard(Payload.class, Payload::release)
<del> .switchIfEmpty(emptyPayload());
<add> ResolvableType type = ResolvableType.forInstance(input);
<add> this.payloadMono = firstPayload(Mono.fromCallable(() -> encodeData(input, type, null)));
<ide> this.payloadFlux = null;
<ide> return;
<ide> }
<ide>
<ide> if (isVoid(elementType) || (adapter != null && adapter.isNoValue())) {
<del> this.payloadMono = Mono.when(publisher).then(emptyPayload());
<add> this.payloadMono = firstPayload(Mono.when(publisher).then(Mono.just(emptyDataBuffer)));
<ide> this.payloadFlux = null;
<ide> return;
<ide> }
<ide> else if (adapter != null) {
<ide> strategies.encoder(elementType, dataMimeType) : null;
<ide>
<ide> if (adapter != null && !adapter.isMultiValue()) {
<del> this.payloadMono = Mono.from(publisher)
<add> Mono<DataBuffer> data = Mono.from(publisher)
<ide> .map(value -> encodeData(value, elementType, encoder))
<del> .map(this::firstPayload)
<del> .switchIfEmpty(emptyPayload());
<add> .defaultIfEmpty(emptyDataBuffer);
<add> this.payloadMono = firstPayload(data);
<ide> this.payloadFlux = null;
<ide> return;
<ide> }
<ide>
<ide> this.payloadMono = null;
<ide> this.payloadFlux = Flux.from(publisher)
<ide> .map(value -> encodeData(value, elementType, encoder))
<add> .defaultIfEmpty(emptyDataBuffer)
<ide> .switchOnFirst((signal, inner) -> {
<ide> DataBuffer data = signal.get();
<ide> if (data != null) {
<del> return Mono.fromCallable(() -> firstPayload(data))
<add> return firstPayload(Mono.fromCallable(() -> data))
<ide> .concatWith(inner.skip(1).map(PayloadUtils::createPayload));
<ide> }
<ide> else {
<ide> return inner.map(PayloadUtils::createPayload);
<ide> }
<ide> })
<del> .doOnDiscard(Payload.class, Payload::release)
<del> .switchIfEmpty(emptyPayload());
<add> .doOnDiscard(Payload.class, Payload::release);
<ide> }
<ide>
<ide> @SuppressWarnings("unchecked")
<ide> private <T> DataBuffer encodeData(T value, ResolvableType elementType, @Nullable
<ide> value, bufferFactory(), elementType, dataMimeType, EMPTY_HINTS);
<ide> }
<ide>
<del> private Payload firstPayload(DataBuffer data) {
<del> DataBuffer metadata;
<del> try {
<del> metadata = this.metadataEncoder.encode();
<del> }
<del> catch (Throwable ex) {
<del> DataBufferUtils.release(data);
<del> throw ex;
<del> }
<del> return PayloadUtils.createPayload(data, metadata);
<del> }
<del>
<del> private Mono<Payload> emptyPayload() {
<del> return Mono.fromCallable(() -> firstPayload(emptyDataBuffer));
<add> /**
<add> * Create the 1st request payload with encoded data and metadata.
<add> * @param encodedData the encoded payload data; expected to not be empty!
<add> */
<add> private Mono<Payload> firstPayload(Mono<DataBuffer> encodedData) {
<add> return Mono.zip(encodedData, this.metadataEncoder.encode())
<add> .map(tuple -> PayloadUtils.createPayload(tuple.getT1(), tuple.getT2()))
<add> .doOnDiscard(DataBuffer.class, DataBufferUtils::release)
<add> .doOnDiscard(Payload.class, Payload::release);
<ide> }
<ide>
<ide> @Override
<ide> public Mono<Void> send() {
<del> Assert.state(this.payloadMono != null, "No RSocket interaction model for one-way send with Flux");
<del> return this.payloadMono.flatMap(rsocket::fireAndForget);
<add> return getPayloadMonoRequired().flatMap(rsocket::fireAndForget);
<add> }
<add>
<add> private Mono<Payload> getPayloadMonoRequired() {
<add> Assert.state(this.payloadFlux == null, "No RSocket interaction model for Flux request to Mono response.");
<add> return this.payloadMono != null ? this.payloadMono : firstPayload(Mono.just(emptyDataBuffer));
<ide> }
<ide>
<ide> @Override
<ide> public <T> Flux<T> retrieveFlux(ParameterizedTypeReference<T> dataTypeRef) {
<ide>
<ide> @SuppressWarnings("unchecked")
<ide> private <T> Mono<T> retrieveMono(ResolvableType elementType) {
<del> Assert.notNull(this.payloadMono, "No RSocket interaction model for Flux request to Mono response.");
<del> Mono<Payload> payloadMono = this.payloadMono.flatMap(rsocket::requestResponse);
<add> Mono<Payload> payloadMono = getPayloadMonoRequired().flatMap(rsocket::requestResponse);
<ide>
<ide> if (isVoid(elementType)) {
<ide> return (Mono<T>) payloadMono.then();
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/DefaultRSocketRequesterBuilder.java
<ide> import io.rsocket.transport.netty.client.WebsocketClientTransport;
<ide> import reactor.core.publisher.Mono;
<ide>
<add>import org.springframework.core.ReactiveAdapter;
<ide> import org.springframework.core.ResolvableType;
<ide> import org.springframework.core.codec.Decoder;
<ide> import org.springframework.core.codec.Encoder;
<ide> final class DefaultRSocketRequesterBuilder implements RSocketRequester.Builder {
<ide>
<ide> private static final Map<String, Object> HINTS = Collections.emptyMap();
<ide>
<add> private static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
<add>
<ide>
<ide> @Nullable
<ide> private MimeType dataMimeType;
<ide> private Mono<RSocketRequester> doConnect(ClientTransport transport) {
<ide> factory.dataMimeType(dataMimeType.toString());
<ide> factory.metadataMimeType(metaMimeType.toString());
<ide>
<del> Payload setupPayload = getSetupPayload(dataMimeType, metaMimeType, rsocketStrategies);
<del> if (setupPayload != null) {
<del> factory.setupPayload(setupPayload);
<del> }
<del>
<del> return factory.transport(transport)
<del> .start()
<del> .map(rsocket -> new DefaultRSocketRequester(
<del> rsocket, dataMimeType, metaMimeType, rsocketStrategies));
<del> }
<del>
<del> @Nullable
<del> private Payload getSetupPayload(MimeType dataMimeType, MimeType metaMimeType, RSocketStrategies strategies) {
<del> DataBuffer metadata = null;
<del> if (this.setupRoute != null || !CollectionUtils.isEmpty(this.setupMetadata)) {
<del> metadata = new MetadataEncoder(metaMimeType, strategies)
<del> .metadataAndOrRoute(this.setupMetadata, this.setupRoute, this.setupRouteVars)
<del> .encode();
<del> }
<del> DataBuffer data = null;
<del> if (this.setupData != null) {
<del> try {
<del> ResolvableType type = ResolvableType.forClass(this.setupData.getClass());
<del> Encoder<Object> encoder = strategies.encoder(type, dataMimeType);
<del> Assert.notNull(encoder, () -> "No encoder for " + dataMimeType + ", " + type);
<del> data = encoder.encodeValue(this.setupData, strategies.dataBufferFactory(), type, dataMimeType, HINTS);
<del> }
<del> catch (Throwable ex) {
<del> if (metadata != null) {
<del> DataBufferUtils.release(metadata);
<del> }
<del> throw ex;
<del> }
<del> }
<del> if (metadata == null && data == null) {
<del> return null;
<del> }
<del> metadata = metadata != null ? metadata : emptyBuffer(strategies);
<del> data = data != null ? data : emptyBuffer(strategies);
<del> return PayloadUtils.createPayload(data, metadata);
<del> }
<del>
<del> private DataBuffer emptyBuffer(RSocketStrategies strategies) {
<del> return strategies.dataBufferFactory().wrap(new byte[0]);
<add> return getSetupPayload(dataMimeType, metaMimeType, rsocketStrategies)
<add> .doOnNext(factory::setupPayload)
<add> .then(Mono.defer(() ->
<add> factory.transport(transport)
<add> .start()
<add> .map(rsocket -> new DefaultRSocketRequester(
<add> rsocket, dataMimeType, metaMimeType, rsocketStrategies))
<add> ));
<ide> }
<ide>
<ide> private RSocketStrategies getRSocketStrategies() {
<ide> private static MimeType getMimeType(Decoder<?> decoder) {
<ide> return mimeType.getParameters().isEmpty() ? mimeType : new MimeType(mimeType, Collections.emptyMap());
<ide> }
<ide>
<add> private Mono<Payload> getSetupPayload(
<add> MimeType dataMimeType, MimeType metaMimeType, RSocketStrategies strategies) {
<add>
<add> Object data = this.setupData;
<add> boolean hasMetadata = (this.setupRoute != null || !CollectionUtils.isEmpty(this.setupMetadata));
<add> if (!hasMetadata && data == null) {
<add> return Mono.empty();
<add> }
<add>
<add> Mono<DataBuffer> dataMono = Mono.empty();
<add> if (data != null) {
<add> ReactiveAdapter adapter = strategies.reactiveAdapterRegistry().getAdapter(data.getClass());
<add> Assert.isTrue(adapter == null || !adapter.isMultiValue(), "Expected single value: " + data);
<add> Mono<?> mono = (adapter != null ? Mono.from(adapter.toPublisher(data)) : Mono.just(data));
<add> dataMono = mono.map(value -> {
<add> ResolvableType type = ResolvableType.forClass(value.getClass());
<add> Encoder<Object> encoder = strategies.encoder(type, dataMimeType);
<add> Assert.notNull(encoder, () -> "No encoder for " + dataMimeType + ", " + type);
<add> return encoder.encodeValue(value, strategies.dataBufferFactory(), type, dataMimeType, HINTS);
<add> });
<add> }
<add>
<add> Mono<DataBuffer> metaMono = Mono.empty();
<add> if (hasMetadata) {
<add> metaMono = new MetadataEncoder(metaMimeType, strategies)
<add> .metadataAndOrRoute(this.setupMetadata, this.setupRoute, this.setupRouteVars)
<add> .encode();
<add> }
<add>
<add> Mono<DataBuffer> emptyBuffer = Mono.fromCallable(() ->
<add> strategies.dataBufferFactory().wrap(EMPTY_BYTE_ARRAY));
<add>
<add> dataMono = dataMono.switchIfEmpty(emptyBuffer);
<add> metaMono = metaMono.switchIfEmpty(emptyBuffer);
<add>
<add> return Mono.zip(dataMono, metaMono)
<add> .map(tuple -> PayloadUtils.createPayload(tuple.getT1(), tuple.getT2()))
<add> .doOnDiscard(DataBuffer.class, DataBufferUtils::release)
<add> .doOnDiscard(Payload.class, Payload::release);
<add> }
<add>
<ide> }
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/MetadataEncoder.java
<ide> */
<ide> package org.springframework.messaging.rsocket;
<ide>
<add>import java.util.ArrayList;
<ide> import java.util.Collections;
<del>import java.util.LinkedHashMap;
<add>import java.util.List;
<ide> import java.util.Map;
<ide> import java.util.regex.Matcher;
<ide> import java.util.regex.Pattern;
<ide> import io.rsocket.metadata.CompositeMetadataFlyweight;
<ide> import io.rsocket.metadata.TaggingMetadataFlyweight;
<ide> import io.rsocket.metadata.WellKnownMimeType;
<add>import reactor.core.publisher.Mono;
<ide>
<add>import org.springframework.core.ReactiveAdapter;
<ide> import org.springframework.core.ResolvableType;
<ide> import org.springframework.core.codec.Encoder;
<ide> import org.springframework.core.io.buffer.DataBuffer;
<ide> final class MetadataEncoder {
<ide> /** For route variable replacement. */
<ide> private static final Pattern VARS_PATTERN = Pattern.compile("\\{([^/]+?)}");
<ide>
<add> private static final Object NO_VALUE = new Object();
<add>
<ide>
<ide> private final MimeType metadataMimeType;
<ide>
<ide> final class MetadataEncoder {
<ide> @Nullable
<ide> private String route;
<ide>
<del> private final Map<Object, MimeType> metadata = new LinkedHashMap<>(4);
<add> private final List<MetadataEntry> metadataEntries = new ArrayList<>(4);
<add>
<add> private boolean hasAsyncValues;
<ide>
<ide>
<ide> MetadataEncoder(MimeType metadataMimeType, RSocketStrategies strategies) {
<ide> private static String expand(String route, Object... routeVars) {
<ide>
<ide> private void assertMetadataEntryCount() {
<ide> if (!this.isComposite) {
<del> int count = this.route != null ? this.metadata.size() + 1 : this.metadata.size();
<add> int count = this.route != null ? this.metadataEntries.size() + 1 : this.metadataEntries.size();
<ide> Assert.isTrue(count < 2, "Composite metadata required for multiple metadata entries.");
<ide> }
<ide> }
<ide> else if (mimeType == null) {
<ide> mimeType = this.metadataMimeType;
<ide> }
<ide> else if (!this.metadataMimeType.equals(mimeType)) {
<del> throw new IllegalArgumentException("Mime type is optional (may be null) " +
<del> "but was provided and does not match the connection metadata mime type.");
<add> throw new IllegalArgumentException(
<add> "Mime type is optional when not using composite metadata, but it was provided " +
<add> "and does not match the connection metadata mime type '" + this.metadataMimeType + "'.");
<ide> }
<del> this.metadata.put(metadata, mimeType);
<add> ReactiveAdapter adapter = this.strategies.reactiveAdapterRegistry().getAdapter(metadata.getClass());
<add> if (adapter != null) {
<add> Assert.isTrue(!adapter.isMultiValue(), "Expected single value: " + metadata);
<add> metadata = Mono.from(adapter.toPublisher(metadata)).defaultIfEmpty(NO_VALUE);
<add> this.hasAsyncValues = true;
<add> }
<add> this.metadataEntries.add(new MetadataEntry(metadata, mimeType));
<ide> assertMetadataEntryCount();
<ide> return this;
<ide> }
<ide> public MetadataEncoder metadataAndOrRoute(@Nullable Map<Object, MimeType> metada
<ide> * Encode the collected metadata entries to a {@code DataBuffer}.
<ide> * @see PayloadUtils#createPayload(DataBuffer, DataBuffer)
<ide> */
<del> public DataBuffer encode() {
<add> public Mono<DataBuffer> encode() {
<add> return this.hasAsyncValues ?
<add> resolveAsyncMetadata().map(this::encodeEntries) :
<add> Mono.fromCallable(() -> encodeEntries(this.metadataEntries));
<add> }
<add>
<add> private DataBuffer encodeEntries(List<MetadataEntry> entries) {
<ide> if (this.isComposite) {
<ide> CompositeByteBuf composite = this.allocator.compositeBuffer();
<ide> try {
<ide> if (this.route != null) {
<ide> CompositeMetadataFlyweight.encodeAndAddMetadata(composite, this.allocator,
<ide> WellKnownMimeType.MESSAGE_RSOCKET_ROUTING, encodeRoute());
<ide> }
<del> this.metadata.forEach((value, mimeType) -> {
<del> ByteBuf metadata = (value instanceof ByteBuf ?
<del> (ByteBuf) value : PayloadUtils.asByteBuf(encodeEntry(value, mimeType)));
<add> entries.forEach(entry -> {
<add> Object value = entry.value();
<ide> CompositeMetadataFlyweight.encodeAndAddMetadata(
<del> composite, this.allocator, mimeType.toString(), metadata);
<add> composite, this.allocator, entry.mimeType().toString(),
<add> value instanceof ByteBuf ? (ByteBuf) value : PayloadUtils.asByteBuf(encodeEntry(entry)));
<ide> });
<ide> return asDataBuffer(composite);
<ide> }
<ide> public DataBuffer encode() {
<ide> }
<ide> }
<ide> else if (this.route != null) {
<del> Assert.isTrue(this.metadata.isEmpty(), "Composite metadata required for route and other entries");
<add> Assert.isTrue(entries.isEmpty(), "Composite metadata required for route and other entries");
<ide> String routingMimeType = WellKnownMimeType.MESSAGE_RSOCKET_ROUTING.getString();
<ide> return this.metadataMimeType.toString().equals(routingMimeType) ?
<ide> asDataBuffer(encodeRoute()) :
<ide> encodeEntry(this.route, this.metadataMimeType);
<ide> }
<ide> else {
<del> Assert.isTrue(this.metadata.size() == 1, "Composite metadata required for multiple entries");
<del> Map.Entry<Object, MimeType> entry = this.metadata.entrySet().iterator().next();
<del> if (!this.metadataMimeType.equals(entry.getValue())) {
<add> Assert.isTrue(entries.size() == 1, "Composite metadata required for multiple entries");
<add> MetadataEntry entry = entries.get(0);
<add> if (!this.metadataMimeType.equals(entry.mimeType())) {
<ide> throw new IllegalArgumentException(
<ide> "Connection configured for metadata mime type " +
<del> "'" + this.metadataMimeType + "', but actual is `" + this.metadata + "`");
<add> "'" + this.metadataMimeType + "', but actual is `" + entries + "`");
<ide> }
<del> return encodeEntry(entry.getKey(), entry.getValue());
<add> return encodeEntry(entry);
<ide> }
<ide> }
<ide>
<ide> private ByteBuf encodeRoute() {
<ide> this.allocator, Collections.singletonList(this.route)).getContent();
<ide> }
<ide>
<add> private <T> DataBuffer encodeEntry(MetadataEntry entry) {
<add> return encodeEntry(entry.value(), entry.mimeType());
<add> }
<add>
<ide> @SuppressWarnings("unchecked")
<del> private <T> DataBuffer encodeEntry(Object metadata, MimeType mimeType) {
<del> if (metadata instanceof ByteBuf) {
<del> return asDataBuffer((ByteBuf) metadata);
<add> private <T> DataBuffer encodeEntry(Object value, MimeType mimeType) {
<add> if (value instanceof ByteBuf) {
<add> return asDataBuffer((ByteBuf) value);
<ide> }
<del> ResolvableType type = ResolvableType.forInstance(metadata);
<add> ResolvableType type = ResolvableType.forInstance(value);
<ide> Encoder<T> encoder = this.strategies.encoder(type, mimeType);
<del> Assert.notNull(encoder, () -> "No encoder for metadata " + metadata + ", mimeType '" + mimeType + "'");
<del> return encoder.encodeValue((T) metadata, bufferFactory(), type, mimeType, Collections.emptyMap());
<add> Assert.notNull(encoder, () -> "No encoder for metadata " + value + ", mimeType '" + mimeType + "'");
<add> return encoder.encodeValue((T) value, bufferFactory(), type, mimeType, Collections.emptyMap());
<ide> }
<ide>
<ide> private DataBuffer asDataBuffer(ByteBuf byteBuf) {
<ide> private DataBuffer asDataBuffer(ByteBuf byteBuf) {
<ide> return buffer;
<ide> }
<ide> }
<add>
<add> private Mono<List<MetadataEntry>> resolveAsyncMetadata() {
<add> Assert.state(this.hasAsyncValues, "No asynchronous values to resolve");
<add> List<Mono<?>> valueMonos = new ArrayList<>();
<add> this.metadataEntries.forEach(entry -> {
<add> Object v = entry.value();
<add> valueMonos.add(v instanceof Mono ? (Mono<?>) v : Mono.just(v));
<add> });
<add> return Mono.zip(valueMonos, values -> {
<add> List<MetadataEntry> result = new ArrayList<>(values.length);
<add> for (int i = 0; i < values.length; i++) {
<add> if (values[i] != NO_VALUE) {
<add> result.add(new MetadataEntry(values[i], this.metadataEntries.get(i).mimeType()));
<add> }
<add> }
<add> return result;
<add> });
<add> }
<add>
<add>
<add> /**
<add> * Holder for the metadata value and mime type.
<add> * @since 5.2.2
<add> */
<add> private static class MetadataEntry {
<add>
<add> private final Object value;
<add>
<add> private final MimeType mimeType;
<add>
<add> MetadataEntry(Object value, MimeType mimeType) {
<add> this.value = value;
<add> this.mimeType = mimeType;
<add> }
<add>
<add> public Object value() {
<add> return this.value;
<add> }
<add>
<add> public MimeType mimeType() {
<add> return this.mimeType;
<add> }
<add> }
<add>
<ide> }
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/RSocketRequester.java
<ide> public interface RSocketRequester {
<ide> RequestSpec route(String route, Object... routeVars);
<ide>
<ide> /**
<del> * Begin to specify a new request with the given metadata value.
<add> * Begin to specify a new request with the given metadata value, which can
<add> * be a concrete value or any producer of a single value that can be adapted
<add> * to a {@link Publisher} via {@link ReactiveAdapterRegistry}.
<ide> * @param metadata the metadata value to encode
<ide> * @param mimeType the mime type that describes the metadata;
<ide> * This is required for connection using composite metadata. Otherwise the
<ide> interface Builder {
<ide> /**
<ide> * Set the data for the setup payload. The data will be encoded
<ide> * according to the configured {@link #dataMimeType(MimeType)}.
<add> * The data be a concrete value or any producer of a single value that
<add> * can be adapted to a {@link Publisher} via {@link ReactiveAdapterRegistry}.
<ide> * <p>By default this is not set.
<ide> */
<ide> RSocketRequester.Builder setupData(Object data);
<ide> interface Builder {
<ide> /**
<ide> * Add metadata entry to the setup payload. Composite metadata must be
<ide> * in use if this is called more than once or in addition to
<del> * {@link #setupRoute(String, Object...)}.
<add> * {@link #setupRoute(String, Object...)}. The metadata value be a
<add> * concrete value or any producer of a single value that can be adapted
<add> * to a {@link Publisher} via {@link ReactiveAdapterRegistry}.
<ide> */
<ide> RSocketRequester.Builder setupMetadata(Object value, @Nullable MimeType mimeType);
<ide>
<ide> interface RequestSpec extends MetadataSpec<RequestSpec> {
<ide> * Use this to append additional metadata entries when using composite
<ide> * metadata. An {@link IllegalArgumentException} is raised if this
<ide> * method is used when not using composite metadata.
<add> * The metadata value be a concrete value or any producer of a single
<add> * value that can be adapted to a {@link Publisher} via
<add> * {@link ReactiveAdapterRegistry}.
<ide> * @param metadata an Object to be encoded with a suitable
<ide> * {@link org.springframework.core.codec.Encoder Encoder}, or a
<ide> * {@link org.springframework.core.io.buffer.DataBuffer DataBuffer}
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/rsocket/DefaultMetadataExtractorTests.java
<ide> public void compositeMetadataWithDefaultSettings() {
<ide> .metadata("html data", TEXT_HTML)
<ide> .metadata("xml data", TEXT_XML);
<ide>
<del> DataBuffer metadata = metadataEncoder.encode();
<add> DataBuffer metadata = metadataEncoder.encode().block();
<ide> Payload payload = createPayload(metadata);
<ide> Map<String, Object> result = this.extractor.extract(payload, COMPOSITE_METADATA);
<ide> payload.release();
<ide> public void compositeMetadataWithMimeTypeRegistrations() {
<ide> .metadata("html data", TEXT_HTML)
<ide> .metadata("xml data", TEXT_XML);
<ide>
<del> DataBuffer metadata = metadataEncoder.encode();
<add> DataBuffer metadata = metadataEncoder.encode().block();
<ide> Payload payload = createPayload(metadata);
<ide> Map<String, Object> result = this.extractor.extract(payload, COMPOSITE_METADATA);
<ide> payload.release();
<ide> public void compositeMetadataWithMimeTypeRegistrations() {
<ide> public void route() {
<ide> MimeType metaMimeType = MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_ROUTING.getString());
<ide> MetadataEncoder metadataEncoder = new MetadataEncoder(metaMimeType, this.strategies).route("toA");
<del> DataBuffer metadata = metadataEncoder.encode();
<add> DataBuffer metadata = metadataEncoder.encode().block();
<ide> Payload payload = createPayload(metadata);
<ide> Map<String, Object> result = this.extractor.extract(payload, metaMimeType);
<ide> payload.release();
<ide> public void routeAsText() {
<ide> this.extractor.metadataToExtract(TEXT_PLAIN, String.class, ROUTE_KEY);
<ide>
<ide> MetadataEncoder metadataEncoder = new MetadataEncoder(TEXT_PLAIN, this.strategies).route("toA");
<del> DataBuffer metadata = metadataEncoder.encode();
<add> DataBuffer metadata = metadataEncoder.encode().block();
<ide> Payload payload = createPayload(metadata);
<ide> Map<String, Object> result = this.extractor.extract(payload, TEXT_PLAIN);
<ide> payload.release();
<ide> public void routeWithCustomFormatting() {
<ide> });
<ide>
<ide> MetadataEncoder encoder = new MetadataEncoder(TEXT_PLAIN, this.strategies).metadata("toA:text data", null);
<del> DataBuffer metadata = encoder.encode();
<add> DataBuffer metadata = encoder.encode().block();
<ide> Payload payload = createPayload(metadata);
<ide> Map<String, Object> result = this.extractor.extract(payload, TEXT_PLAIN);
<ide> payload.release();
<ide> public void nonCompositeMetadataCanBeReadTwice() {
<ide> extractor.metadataToExtract(TEXT_PLAIN, String.class, "name");
<ide>
<ide> MetadataEncoder encoder = new MetadataEncoder(TEXT_PLAIN, this.strategies).metadata("value", null);
<del> DataBuffer metadata = encoder.encode();
<add> DataBuffer metadata = encoder.encode().block();
<ide> Payload payload = createPayload(metadata);
<ide>
<ide> Map<String, Object> result = extractor.extract(payload, TEXT_PLAIN);
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/rsocket/DefaultRSocketRequesterBuilderTests.java
<ide> package org.springframework.messaging.rsocket;
<ide>
<ide> import java.lang.reflect.Field;
<add>import java.time.Duration;
<ide> import java.util.Collections;
<ide> import java.util.List;
<ide> import java.util.Map;
<ide> import org.springframework.core.ResolvableType;
<ide> import org.springframework.core.codec.Decoder;
<ide> import org.springframework.core.codec.DecodingException;
<add>import org.springframework.core.codec.StringDecoder;
<ide> import org.springframework.core.io.buffer.DataBuffer;
<ide> import org.springframework.core.io.buffer.DataBufferFactory;
<ide> import org.springframework.core.io.buffer.DefaultDataBufferFactory;
<ide> public void setupRoute() {
<ide> assertThat(setupPayload.getDataUtf8()).isEqualTo("My data");
<ide> }
<ide>
<add> @Test
<add> public void setupWithAsyncValues() {
<add>
<add> Mono<String> asyncMeta1 = Mono.delay(Duration.ofMillis(1)).map(aLong -> "Async Metadata 1");
<add> Mono<String> asyncMeta2 = Mono.delay(Duration.ofMillis(1)).map(aLong -> "Async Metadata 2");
<add> Mono<String> data = Mono.delay(Duration.ofMillis(1)).map(aLong -> "Async data");
<add>
<add> RSocketRequester.builder()
<add> .dataMimeType(MimeTypeUtils.TEXT_PLAIN)
<add> .setupRoute("toA")
<add> .setupMetadata(asyncMeta1, new MimeType("text", "x.test.metadata1"))
<add> .setupMetadata(asyncMeta2, new MimeType("text", "x.test.metadata2"))
<add> .setupData(data)
<add> .connect(this.transport)
<add> .block();
<add>
<add> ConnectionSetupPayload payload = Mono.from(this.connection.sentFrames())
<add> .map(ConnectionSetupPayload::create)
<add> .block();
<add>
<add> MimeType compositeMimeType =
<add> MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_COMPOSITE_METADATA.getString());
<add>
<add> DefaultMetadataExtractor extractor = new DefaultMetadataExtractor(StringDecoder.allMimeTypes());
<add> extractor.metadataToExtract(new MimeType("text", "x.test.metadata1"), String.class, "asyncMeta1");
<add> extractor.metadataToExtract(new MimeType("text", "x.test.metadata2"), String.class, "asyncMeta2");
<add> Map<String, Object> metadataValues = extractor.extract(payload, compositeMimeType);
<add>
<add> assertThat(metadataValues.get("asyncMeta1")).isEqualTo("Async Metadata 1");
<add> assertThat(metadataValues.get("asyncMeta2")).isEqualTo("Async Metadata 2");
<add> assertThat(payload.getDataUtf8()).isEqualTo("Async data");
<add> }
<add>
<ide> @Test
<ide> public void frameDecoderMatchesDataBufferFactory() throws Exception {
<ide> testFrameDecoder(new NettyDataBufferFactory(ByteBufAllocator.DEFAULT), PayloadDecoder.ZERO_COPY);
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/rsocket/DefaultRSocketRequesterTests.java
<ide> import java.time.Duration;
<ide> import java.util.Arrays;
<ide> import java.util.List;
<add>import java.util.Map;
<ide> import java.util.concurrent.atomic.AtomicBoolean;
<ide> import java.util.function.Function;
<ide>
<ide> import io.reactivex.Single;
<ide> import io.rsocket.AbstractRSocket;
<ide> import io.rsocket.Payload;
<add>import io.rsocket.metadata.WellKnownMimeType;
<ide> import org.junit.jupiter.api.BeforeEach;
<ide> import org.junit.jupiter.api.Test;
<ide> import org.reactivestreams.Publisher;
<ide> import org.springframework.core.io.buffer.DefaultDataBufferFactory;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.messaging.rsocket.RSocketRequester.RequestSpec;
<add>import org.springframework.util.MimeType;
<add>import org.springframework.util.MimeTypeUtils;
<ide>
<ide> import static java.util.concurrent.TimeUnit.MILLISECONDS;
<ide> import static org.assertj.core.api.Assertions.assertThat;
<del>import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
<add>import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
<ide> import static org.springframework.util.MimeTypeUtils.TEXT_PLAIN;
<ide>
<ide> /**
<ide> private void testSendFlux(Function<RequestSpec, RequestSpec> mapper, String... e
<ide> }
<ide> }
<ide>
<add> @Test
<add> public void sendWithoutData() {
<add> this.requester.route("toA").send().block(Duration.ofSeconds(5));
<add>
<add> assertThat(this.rsocket.getSavedMethodName()).isEqualTo("fireAndForget");
<add> assertThat(this.rsocket.getSavedPayload().getMetadataUtf8()).isEqualTo("toA");
<add> assertThat(this.rsocket.getSavedPayload().getDataUtf8()).isEqualTo("");
<add> }
<add>
<add> @Test
<add> public void sendMonoWithoutData() {
<add> this.requester.route("toA").retrieveMono(String.class).block(Duration.ofSeconds(5));
<add>
<add> assertThat(this.rsocket.getSavedMethodName()).isEqualTo("requestResponse");
<add> assertThat(this.rsocket.getSavedPayload().getMetadataUtf8()).isEqualTo("toA");
<add> assertThat(this.rsocket.getSavedPayload().getDataUtf8()).isEqualTo("");
<add> }
<add>
<add> @Test
<add> public void testSendWithAsyncMetadata() {
<add>
<add> MimeType compositeMimeType =
<add> MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_COMPOSITE_METADATA.getString());
<add>
<add> Mono<String> asyncMeta1 = Mono.delay(Duration.ofMillis(1)).map(aLong -> "Async Metadata 1");
<add> Mono<String> asyncMeta2 = Mono.delay(Duration.ofMillis(1)).map(aLong -> "Async Metadata 2");
<add>
<add> TestRSocket rsocket = new TestRSocket();
<add> RSocketRequester.wrap(rsocket, TEXT_PLAIN, compositeMimeType, this.strategies)
<add> .route("toA")
<add> .metadata(asyncMeta1, new MimeType("text", "x.test.metadata1"))
<add> .metadata(asyncMeta2, new MimeType("text", "x.test.metadata2"))
<add> .data("data")
<add> .send()
<add> .block(Duration.ofSeconds(5));
<add>
<add> Payload payload = rsocket.getSavedPayload();
<add>
<add> DefaultMetadataExtractor extractor = new DefaultMetadataExtractor(this.strategies.decoders());
<add> extractor.metadataToExtract(new MimeType("text", "x.test.metadata1"), String.class, "asyncMeta1");
<add> extractor.metadataToExtract(new MimeType("text", "x.test.metadata2"), String.class, "asyncMeta2");
<add> Map<String, Object> metadataValues = extractor.extract(payload, compositeMimeType);
<add>
<add> assertThat(metadataValues.get("asyncMeta1")).isEqualTo("Async Metadata 1");
<add> assertThat(metadataValues.get("asyncMeta2")).isEqualTo("Async Metadata 2");
<add> assertThat(payload.getDataUtf8()).isEqualTo("data");
<add> }
<add>
<ide> @Test
<ide> public void retrieveMono() {
<ide> String value = "bodyA";
<ide> public void retrieveFluxVoid() {
<ide>
<ide> @Test
<ide> public void fluxToMonoIsRejected() {
<del> assertThatIllegalArgumentException()
<add> assertThatIllegalStateException()
<ide> .isThrownBy(() -> this.requester.route("").data(Flux.just("a", "b")).retrieveMono(String.class))
<ide> .withMessage("No RSocket interaction model for Flux request to Mono response.");
<ide> }
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/rsocket/MetadataEncoderTests.java
<ide> */
<ide> package org.springframework.messaging.rsocket;
<ide>
<add>import java.time.Duration;
<ide> import java.util.Collections;
<ide> import java.util.Iterator;
<ide> import java.util.Map;
<ide> import io.rsocket.metadata.RoutingMetadata;
<ide> import io.rsocket.metadata.WellKnownMimeType;
<ide> import org.junit.jupiter.api.Test;
<add>import reactor.core.publisher.Mono;
<ide>
<ide> import org.springframework.core.io.buffer.DataBuffer;
<ide> import org.springframework.core.io.buffer.DefaultDataBufferFactory;
<ide> public class MetadataEncoderTests {
<ide> @Test
<ide> public void compositeMetadata() {
<ide>
<add> Mono<String> asyncMeta1 = Mono.delay(Duration.ofMillis(1)).map(aLong -> "Async Metadata 1");
<add> Mono<String> asyncMeta2 = Mono.delay(Duration.ofMillis(1)).map(aLong -> "Async Metadata 2");
<add>
<ide> DataBuffer buffer = new MetadataEncoder(COMPOSITE_METADATA, this.strategies)
<ide> .route("toA")
<ide> .metadata("My metadata", MimeTypeUtils.TEXT_PLAIN)
<add> .metadata(asyncMeta1, new MimeType("text", "x.test.metadata1"))
<ide> .metadata(Unpooled.wrappedBuffer("Raw data".getBytes(UTF_8)), MimeTypeUtils.APPLICATION_OCTET_STREAM)
<del> .encode();
<add> .metadata(asyncMeta2, new MimeType("text", "x.test.metadata2"))
<add> .encode()
<add> .block();
<ide>
<ide> CompositeMetadata entries = new CompositeMetadata(((NettyDataBuffer) buffer).getNativeBuffer(), false);
<ide> Iterator<CompositeMetadata.Entry> iterator = entries.iterator();
<ide> public void compositeMetadata() {
<ide> assertThat(entry.getMimeType()).isEqualTo(MimeTypeUtils.TEXT_PLAIN_VALUE);
<ide> assertThat(entry.getContent().toString(UTF_8)).isEqualTo("My metadata");
<ide>
<add> assertThat(iterator.hasNext()).isTrue();
<add> entry = iterator.next();
<add> assertThat(entry.getMimeType()).isEqualTo("text/x.test.metadata1");
<add> assertThat(entry.getContent().toString(UTF_8)).isEqualTo("Async Metadata 1");
<add>
<ide> assertThat(iterator.hasNext()).isTrue();
<ide> entry = iterator.next();
<ide> assertThat(entry.getMimeType()).isEqualTo(MimeTypeUtils.APPLICATION_OCTET_STREAM_VALUE);
<ide> assertThat(entry.getContent().toString(UTF_8)).isEqualTo("Raw data");
<ide>
<add> assertThat(iterator.hasNext()).isTrue();
<add> entry = iterator.next();
<add> assertThat(entry.getMimeType()).isEqualTo("text/x.test.metadata2");
<add> assertThat(entry.getContent().toString(UTF_8)).isEqualTo("Async Metadata 2");
<add>
<ide> assertThat(iterator.hasNext()).isFalse();
<ide> }
<ide>
<ide> public void routeWithRoutingMimeType() {
<ide> DataBuffer buffer =
<ide> new MetadataEncoder(mimeType, this.strategies)
<ide> .route("toA")
<del> .encode();
<add> .encode()
<add> .block();
<ide>
<ide> assertRoute("toA", ((NettyDataBuffer) buffer).getNativeBuffer());
<ide> }
<ide> public void routeWithTextPlainMimeType() {
<ide> DataBuffer buffer =
<ide> new MetadataEncoder(MimeTypeUtils.TEXT_PLAIN, this.strategies)
<ide> .route("toA")
<del> .encode();
<add> .encode()
<add> .block();
<ide>
<ide> assertThat(dumpString(buffer)).isEqualTo("toA");
<ide> }
<ide> public void routeWithVars() {
<ide> DataBuffer buffer =
<ide> new MetadataEncoder(MimeTypeUtils.TEXT_PLAIN, this.strategies)
<ide> .route("a.{b}.{c}", "BBB", "C.C.C")
<del> .encode();
<add> .encode()
<add> .block();
<ide>
<ide> assertThat(dumpString(buffer)).isEqualTo("a.BBB.C%2EC%2EC");
<ide> }
<ide> public void metadataWithTextPlainMimeType() {
<ide> DataBuffer buffer =
<ide> new MetadataEncoder(MimeTypeUtils.TEXT_PLAIN, this.strategies)
<ide> .metadata(Unpooled.wrappedBuffer("Raw data".getBytes(UTF_8)), null)
<del> .encode();
<add> .encode()
<add> .block();
<ide>
<ide> assertThat(dumpString(buffer)).isEqualTo("Raw data");
<ide> }
<ide> public void metadataWithByteBuf() {
<ide> DataBuffer buffer =
<ide> new MetadataEncoder(MimeTypeUtils.TEXT_PLAIN, this.strategies)
<ide> .metadata("toA", null)
<del> .encode();
<add> .encode()
<add> .block();
<ide>
<ide> assertThat(dumpString(buffer)).isEqualTo("toA");
<ide> }
<ide> public void mimeTypeDoesNotMatchConnectionMetadataMimeType() {
<ide> MetadataEncoder encoder = new MetadataEncoder(MimeTypeUtils.TEXT_PLAIN, this.strategies);
<ide>
<ide> assertThatThrownBy(() -> encoder.metadata("toA", MimeTypeUtils.APPLICATION_JSON))
<del> .hasMessage("Mime type is optional (may be null) " +
<del> "but was provided and does not match the connection metadata mime type.");
<add> .hasMessage("Mime type is optional when not using composite metadata, " +
<add> "but it was provided and does not match the connection metadata mime type 'text/plain'.");
<ide> }
<ide>
<ide> @Test
<ide> public void defaultDataBufferFactory() {
<ide>
<ide> DataBuffer buffer = new MetadataEncoder(COMPOSITE_METADATA, strategies)
<ide> .route("toA")
<del> .encode();
<add> .encode()
<add> .block();
<ide>
<ide> ByteBuf byteBuf = new NettyDataBufferFactory(ByteBufAllocator.DEFAULT)
<ide> .wrap(buffer.asByteBuffer()) | 8 |
Javascript | Javascript | reset baseurl in protractor conf | b4db713cde8539d118c9bbae91c4ded1979b0ebf | <ide><path>protractor-jenkins-conf.js
<ide> exports.config = {
<ide> 'browserName': 'chrome'
<ide> },
<ide>
<del> baseUrl: 'http://localhost:8000/build/docs/',
<add> baseUrl: 'http://localhost:8000/',
<ide>
<ide> framework: 'jasmine',
<ide> | 1 |
Javascript | Javascript | remove empty define({}) from build output | 2c1b556d98da597b0490f204e3561f656987f17c | <ide><path>build/tasks/build.js
<ide> module.exports = function( grunt ) {
<ide> optimize: "none",
<ide> // Include dependencies loaded with require
<ide> findNestedDependencies: true,
<add> // Avoid inserting define() placeholder
<add> skipModuleInsertion: true,
<ide> // Avoid breaking semicolons inserted by r.js
<ide> skipSemiColonInsertion: true,
<ide> wrap: {
<ide> module.exports = function( grunt ) {
<ide>
<ide> // Remove empty definitions
<ide> contents = contents
<del> .replace( /define\(\[[^\]]+\]\)[\W\n]+$/, "" );
<add> .replace( /define\(\[[^\]]*\]\)[\W\n]+$/, "" );
<ide> }
<ide> // AMD Name
<ide> if ( (amdName = grunt.option( "amd" )) != null && /^exports\/amd$/.test( name ) ) { | 1 |
Ruby | Ruby | remove unnecessary `remove_file` | 4e5a96dd292439e9bd525a645427b0a559a13608 | <ide><path>railties/lib/rails/generators/rails/app/app_generator.rb
<ide> def delete_application_record_skipping_active_record
<ide>
<ide> def delete_action_mailer_files_skipping_action_mailer
<ide> if options[:skip_action_mailer]
<del> remove_file "app/mailers/application_mailer.rb"
<ide> remove_file "app/views/layouts/mailer.html.erb"
<ide> remove_file "app/views/layouts/mailer.text.erb"
<ide> remove_dir "app/mailers" | 1 |
Text | Text | clarify behavior of fs.mkdir | 13d2df530b613f5f41db3e9680fa85d55bea0f1e | <ide><path>doc/api/fs.md
<ide> are given to the completion callback.
<ide>
<ide> The optional `options` argument can be an integer specifying mode (permission
<ide> and sticky bits), or an object with a `mode` property and a `recursive`
<del>property indicating whether parent folders should be created.
<add>property indicating whether parent folders should be created. Calling
<add>`fs.mkdir()` when `path` is a directory that exists results in an error only
<add>when `recursive` is false.
<ide>
<ide> ```js
<ide> // Creates /tmp/a/apple, regardless of whether `/tmp` and /tmp/a exist.
<ide> arguments upon success.
<ide>
<ide> The optional `options` argument can be an integer specifying mode (permission
<ide> and sticky bits), or an object with a `mode` property and a `recursive`
<del>property indicating whether parent folders should be created.
<add>property indicating whether parent folders should be created. Calling
<add>`fsPromises.mkdir()` when `path` is a directory that exists results in a
<add>rejection only when `recursive` is false.
<ide>
<ide> ### fsPromises.mkdtemp(prefix[, options])
<ide> <!-- YAML | 1 |
Javascript | Javascript | remove view keyword | 7c6574ffdfa61d879cbdbac28c025601e10249d4 | <ide><path>packages/ember-htmlbars/lib/env.js
<del>import { environment, ENV } from 'ember-environment';
<add>import { environment } from 'ember-environment';
<ide>
<ide> import { hooks } from 'htmlbars-runtime';
<ide> import assign from 'ember-metal/assign';
<ide> import debuggerKeyword from 'ember-htmlbars/keywords/debugger';
<ide> import withKeyword from 'ember-htmlbars/keywords/with';
<ide> import outlet from 'ember-htmlbars/keywords/outlet';
<ide> import unbound from 'ember-htmlbars/keywords/unbound';
<del>import view from 'ember-htmlbars/keywords/view';
<ide> import componentKeyword from 'ember-htmlbars/keywords/component';
<ide> import elementComponent from 'ember-htmlbars/keywords/element-component';
<ide> import partial from 'ember-htmlbars/keywords/partial';
<ide> registerKeyword('action', actionKeyword);
<ide> registerKeyword('render', renderKeyword);
<ide> registerKeyword('@element_action', elementActionKeyword);
<ide>
<del>if (ENV._ENABLE_LEGACY_VIEW_SUPPORT) {
<del> registerKeyword('view', view);
<del>}
<del>
<del>
<ide> export default {
<ide> hooks: emberHooks,
<ide> helpers: helpers,
<ide><path>packages/ember-htmlbars/lib/keywords/view.js
<del>/**
<del>@module ember
<del>@submodule ember-templates
<del>*/
<del>
<del>import { readViewFactory } from '../streams/utils';
<del>import EmberView from 'ember-views/views/view';
<del>import ViewNodeManager from 'ember-htmlbars/node-managers/view-node-manager';
<del>
<del>/**
<del> `{{view}}` inserts a new instance of an `Ember.View` into a template passing its
<del> options to the `Ember.View`'s `create` method and using the supplied block as
<del> the view's own template.
<del>
<del> An empty `<body>` and the following template:
<del>
<del> ```handlebars
<del> A span:
<del> {{#view tagName="span"}}
<del> hello.
<del> {{/view}}
<del> ```
<del>
<del> Will result in HTML structure:
<del>
<del> ```html
<del> <body>
<del> <!-- Note: the handlebars template script
<del> also results in a rendered Ember.View
<del> which is the outer <div> here -->
<del>
<del> <div class="ember-view">
<del> A span:
<del> <span id="ember1" class="ember-view">
<del> Hello.
<del> </span>
<del> </div>
<del> </body>
<del> ```
<del>
<del> ### `parentView` setting
<del>
<del> The `parentView` property of the new `Ember.View` instance created through
<del> `{{view}}` will be set to the `Ember.View` instance of the template where
<del> `{{view}}` was called.
<del>
<del> ```javascript
<del> aView = Ember.View.create({
<del> template: Ember.Handlebars.compile("{{#view}} my parent: {{parentView.elementId}} {{/view}}")
<del> });
<del>
<del> aView.appendTo('body');
<del> ```
<del>
<del> Will result in HTML structure:
<del>
<del> ```html
<del> <div id="ember1" class="ember-view">
<del> <div id="ember2" class="ember-view">
<del> my parent: ember1
<del> </div>
<del> </div>
<del> ```
<del>
<del> ### Setting CSS id and class attributes
<del>
<del> The HTML `id` attribute can be set on the `{{view}}`'s resulting element with
<del> the `id` option. This option will _not_ be passed to `Ember.View.create`.
<del>
<del> ```handlebars
<del> {{#view tagName="span" id="a-custom-id"}}
<del> hello.
<del> {{/view}}
<del> ```
<del>
<del> Results in the following HTML structure:
<del>
<del> ```html
<del> <div class="ember-view">
<del> <span id="a-custom-id" class="ember-view">
<del> hello.
<del> </span>
<del> </div>
<del> ```
<del>
<del> The HTML `class` attribute can be set on the `{{view}}`'s resulting element
<del> with the `class` or `classNameBindings` options. The `class` option will
<del> directly set the CSS `class` attribute and will not be passed to
<del> `Ember.View.create`. `classNameBindings` will be passed to `create` and use
<del> `Ember.View`'s class name binding functionality:
<del>
<del> ```handlebars
<del> {{#view tagName="span" class="a-custom-class"}}
<del> hello.
<del> {{/view}}
<del> ```
<del>
<del> Results in the following HTML structure:
<del>
<del> ```html
<del> <div class="ember-view">
<del> <span id="ember2" class="ember-view a-custom-class">
<del> hello.
<del> </span>
<del> </div>
<del> ```
<del>
<del> ### Supplying a different view class
<del>
<del> `{{view}}` can take an optional first argument before its supplied options to
<del> specify a path to a custom view class.
<del>
<del> ```handlebars
<del> {{#view "custom"}}{{! will look up App.CustomView }}
<del> hello.
<del> {{/view}}
<del> ```
<del>
<del> The first argument can also be a relative path accessible from the current
<del> context.
<del>
<del> ```javascript
<del> MyApp = Ember.Application.create({});
<del> MyApp.OuterView = Ember.View.extend({
<del> innerViewClass: Ember.View.extend({
<del> classNames: ['a-custom-view-class-as-property']
<del> }),
<del> template: Ember.Handlebars.compile('{{#view view.innerViewClass}} hi {{/view}}')
<del> });
<del>
<del> MyApp.OuterView.create().appendTo('body');
<del> ```
<del>
<del> Will result in the following HTML:
<del>
<del> ```html
<del> <div id="ember1" class="ember-view">
<del> <div id="ember2" class="ember-view a-custom-view-class-as-property">
<del> hi
<del> </div>
<del> </div>
<del> ```
<del>
<del> ### Blockless use
<del>
<del> If you supply a custom `Ember.View` subclass that specifies its own template
<del> or provide a `templateName` option to `{{view}}` it can be used without
<del> supplying a block. Attempts to use both a `templateName` option and supply a
<del> block will throw an error.
<del>
<del> ```javascript
<del> var App = Ember.Application.create();
<del> App.WithTemplateDefinedView = Ember.View.extend({
<del> templateName: 'defined-template'
<del> });
<del> ```
<del>
<del> ```handlebars
<del> {{! application.hbs }}
<del> {{view 'with-template-defined'}}
<del> ```
<del>
<del> ```handlebars
<del> {{! defined-template.hbs }}
<del> Some content for the defined template view.
<del> ```
<del>
<del> ### `viewName` property
<del>
<del> You can supply a `viewName` option to `{{view}}`. The `Ember.View` instance
<del> will be referenced as a property of its parent view by this name.
<del>
<del> ```javascript
<del> aView = Ember.View.create({
<del> template: Ember.Handlebars.compile('{{#view viewName="aChildByName"}} hi {{/view}}')
<del> });
<del>
<del> aView.appendTo('body');
<del> aView.get('aChildByName') // the instance of Ember.View created by {{view}} helper
<del> ```
<del>
<del> @method view
<del> @for Ember.Templates.helpers
<del> @public
<del> @deprecated
<del>*/
<del>
<del>export default {
<del> setupState(state, env, scope, params, hash) {
<del> var read = env.hooks.getValue;
<del> var targetObject = read(scope.getSelf());
<del> var viewClassOrInstance = state.viewClassOrInstance;
<del> if (!viewClassOrInstance) {
<del> viewClassOrInstance = getView(read(params[0]), env.owner);
<del> }
<del>
<del> // if parentView exists, use its controller (the default
<del> // behavior), otherwise use `scope.self` as the controller
<del> var controller = scope.hasLocal('view') ? null : read(scope.getSelf());
<del>
<del> return {
<del> manager: state.manager,
<del> parentView: env.view,
<del> controller,
<del> targetObject,
<del> viewClassOrInstance
<del> };
<del> },
<del>
<del> rerender(morph, env, scope, params, hash, template, inverse, visitor) {
<del> // If the hash is empty, the component cannot have extracted a part
<del> // of a mutable param and used it in its layout, because there are
<del> // no params at all.
<del> if (Object.keys(hash).length) {
<del> return morph.getState().manager.rerender(env, hash, visitor, true);
<del> }
<del> },
<del>
<del> render(node, env, scope, params, hash, template, inverse, visitor) {
<del> if (hash.tag) {
<del> hash = swapKey(hash, 'tag', 'tagName');
<del> }
<del>
<del> if (hash.classNameBindings) {
<del> hash.classNameBindings = hash.classNameBindings.split(' ');
<del> }
<del>
<del> var state = node.getState();
<del> var parentView = state.parentView;
<del>
<del> var options = {
<del> component: state.viewClassOrInstance,
<del> layout: null
<del> };
<del>
<del> options.createOptions = {};
<del> if (state.controller) {
<del> // Use `_controller` to avoid stomping on a CP
<del> // that exists in the target view/component
<del> options.createOptions._controller = state.controller;
<del> }
<del>
<del> if (state.targetObject) {
<del> // Use `_targetObject` to avoid stomping on a CP
<del> // that exists in the target view/component
<del> options.createOptions._targetObject = state.targetObject;
<del> }
<del>
<del> if (state.manager) {
<del> state.manager.destroy();
<del> state.manager = null;
<del> }
<del>
<del> var nodeManager = ViewNodeManager.create(node, env, hash, options, parentView, null, scope, template);
<del> state.manager = nodeManager;
<del>
<del> nodeManager.render(env, hash, visitor);
<del> }
<del>};
<del>
<del>function getView(viewPath, owner) {
<del> var viewClassOrInstance;
<del>
<del> if (!viewPath) {
<del> if (owner) {
<del> viewClassOrInstance = owner._lookupFactory('view:toplevel');
<del> } else {
<del> viewClassOrInstance = EmberView;
<del> }
<del> } else {
<del> viewClassOrInstance = readViewFactory(viewPath, owner);
<del> }
<del>
<del> return viewClassOrInstance;
<del>}
<del>
<del>function swapKey(hash, original, update) {
<del> var newHash = {};
<del>
<del> for (var prop in hash) {
<del> if (prop === original) {
<del> newHash[update] = hash[prop];
<del> } else {
<del> newHash[prop] = hash[prop];
<del> }
<del> }
<del>
<del> return newHash;
<del>}
<ide><path>packages/ember-testing/tests/helpers_test.js
<ide> import run from 'ember-metal/run_loop';
<ide> import EmberObject from 'ember-runtime/system/object';
<ide> import RSVP from 'ember-runtime/ext/rsvp';
<ide> import EmberView from 'ember-views/views/view';
<del>import Checkbox from 'ember-htmlbars/components/checkbox';
<ide> import jQuery from 'ember-views/system/jquery';
<add>import Component from 'ember-templates/component';
<ide>
<ide> import Test from 'ember-testing/test';
<ide> import 'ember-testing/helpers'; // ensure that the helpers are loaded
<ide> import EmberRoute from 'ember-routing/system/route';
<ide> import EmberApplication from 'ember-application/system/application';
<ide> import { compile } from 'ember-template-compiler/tests/utils/helpers';
<ide>
<del>import { registerKeyword, resetKeyword } from 'ember-htmlbars/tests/utils';
<del>import viewKeyword from 'ember-htmlbars/keywords/view';
<ide> import { setTemplates, set as setTemplate } from 'ember-templates/template_registry';
<ide> import {
<ide> pendingRequests,
<ide> import {
<ide>
<ide> var App;
<ide> var originalAdapter = getAdapter();
<del>var originalViewKeyword;
<ide>
<ide> function cleanup() {
<ide> // Teardown setupForTesting
<ide> QUnit.test('Ember.Application#removeTestHelpers resets the helperContainer\'s or
<ide>
<ide> QUnit.module('ember-testing: Helper methods', {
<ide> setup() {
<del> originalViewKeyword = registerKeyword('view', viewKeyword);
<ide> setupApp();
<ide> },
<ide> teardown() {
<ide> cleanup();
<del> resetKeyword('view', originalViewKeyword);
<ide> }
<ide> });
<ide>
<ide> test('`click` triggers appropriate events in order', function() {
<ide> this.$().on('mousedown focusin mouseup click', function(e) {
<ide> events.push(e.type);
<ide> });
<del> },
<del>
<del> Checkbox: Checkbox.extend({
<del> click() {
<del> events.push('click:' + this.get('checked'));
<del> },
<add> }
<add> });
<ide>
<del> change() {
<del> events.push('change:' + this.get('checked'));
<del> }
<del> })
<add> App.XCheckboxComponent = Component.extend({
<add> tagName: 'input',
<add> attributeBindings: ['type'],
<add> type: 'checkbox',
<add> click() {
<add> events.push('click:' + this.get('checked'));
<add> },
<add> change() {
<add> events.push('change:' + this.get('checked'));
<add> }
<ide> });
<ide>
<del> setTemplate('index', compile('{{input type="text"}} {{view view.Checkbox}} {{textarea}} <div contenteditable="true"> </div>'));
<add> setTemplate('index', compile('{{input type="text"}} {{x-checkbox type="checkbox"}} {{textarea}} <div contenteditable="true"> </div>'));
<ide>
<ide> run(App, App.advanceReadiness);
<ide>
<ide><path>packages/ember-testing/tests/integration_test.js
<ide> QUnit.module('ember-testing Integration', {
<ide> }
<ide> });
<ide>
<del>import { test } from 'ember-glimmer/tests/utils/skip-if-glimmer';
<add>import { test } from 'internal-test-helpers/tests/skip-if-glimmer';
<ide>
<ide> test('template is bound to empty array of people', function() {
<ide> App.Person.find = function() {
<ide><path>packages/ember-views/tests/compat/view_render_hook_test.js
<ide> import { runDestroy } from 'ember-runtime/tests/utils';
<ide> import View from 'ember-views/views/view';
<ide>
<del>import { registerKeyword, resetKeyword } from 'ember-htmlbars/tests/utils';
<del>import viewKeyword from 'ember-htmlbars/keywords/view';
<ide>
<del>var view, parentView, originalViewKeyword;
<add>var view, parentView;
<ide>
<ide> QUnit.module('ember-views: View#render hook', {
<del> setup() {
<del> originalViewKeyword = registerKeyword('view', viewKeyword);
<del> },
<ide> teardown() {
<ide> runDestroy(view);
<ide> runDestroy(parentView);
<del> resetKeyword('view', originalViewKeyword);
<ide> }
<ide> });
<ide>
<ide><path>packages/ember-views/tests/system/event_dispatcher_test.js
<ide> import Component from 'ember-htmlbars/component';
<ide> import buildOwner from 'container/tests/test-helpers/build-owner';
<ide> import { OWNER } from 'container/owner';
<ide> import { runAppend, runDestroy } from 'ember-runtime/tests/utils';
<del>
<del>import { registerKeyword, resetKeyword } from 'ember-htmlbars/tests/utils';
<del>import viewKeyword from 'ember-htmlbars/keywords/view';
<del>
<ide> import { subscribe, reset } from 'ember-metal/instrumentation';
<ide>
<del>var owner, view, originalViewKeyword;
<add>var owner, view;
<ide> var dispatcher;
<ide>
<ide> import isEnabled from 'ember-metal/features';
<ide>
<ide> QUnit.module('EventDispatcher', {
<ide> setup() {
<del> originalViewKeyword = registerKeyword('view', viewKeyword);
<del>
<ide> owner = buildOwner();
<ide> owner.registerOptionsForType('component', { singleton: false });
<ide> owner.registerOptionsForType('view', { singleton: false });
<ide> QUnit.module('EventDispatcher', {
<ide> runDestroy(view);
<ide> runDestroy(owner);
<ide> reset();
<del> resetKeyword('view', originalViewKeyword);
<ide> }
<ide> });
<ide>
<ide><path>packages/ember-views/tests/views/view/append_to_test.js
<ide> import { runAppend, runDestroy } from 'ember-runtime/tests/utils';
<ide> import buildOwner from 'container/tests/test-helpers/build-owner';
<ide> import { OWNER } from 'container/owner';
<ide>
<del>import { registerKeyword, resetKeyword } from 'ember-htmlbars/tests/utils';
<del>import viewKeyword from 'ember-htmlbars/keywords/view';
<del>
<del>var owner, View, view, otherView, willDestroyCalled, originalViewKeyword;
<add>var owner, View, view, otherView, willDestroyCalled;
<ide>
<ide> function commonSetup() {
<ide> owner = buildOwner();
<ide> function commonSetup() {
<ide>
<ide> QUnit.module('EmberView - append() and appendTo()', {
<ide> setup() {
<del> originalViewKeyword = registerKeyword('view', viewKeyword);
<ide> View = EmberView.extend({});
<ide> },
<ide>
<ide> teardown() {
<ide> runDestroy(view);
<ide> runDestroy(otherView);
<del> resetKeyword('view', originalViewKeyword);
<ide> }
<ide> });
<ide>
<ide> QUnit.test('raises an assert when a target does not exist in the DOM', function(
<ide> });
<ide> });
<ide>
<del>QUnit.test('trigger rerender of parent and SimpleBoundView', function () {
<del> var view = EmberView.create({
<del> show: true,
<del> foo: 'bar',
<del> template: compile('{{#if view.show}}{{#if view.foo}}{{view.foo}}{{/if}}{{/if}}')
<del> });
<del>
<del> run(function() { view.append(); });
<del>
<del> equal(view.$().text(), 'bar');
<del>
<del> run(function() {
<del> view.set('foo', 'baz'); // schedule render of simple bound
<del> view.set('show', false); // destroy tree
<del> });
<del>
<del> equal(view.$().text(), '');
<del>
<del> run(function() {
<del> view.destroy();
<del> });
<del>});
<del>
<ide>
<ide> QUnit.test('remove removes an element from the DOM', function() {
<ide> willDestroyCalled = 0;
<ide><path>packages/ember-views/tests/views/view/child_views_test.js
<del>import run from 'ember-metal/run_loop';
<del>import EmberView from 'ember-views/views/view';
<del>import Component from 'ember-htmlbars/component';
<del>import { compile } from 'ember-template-compiler';
<del>import { A as emberA } from 'ember-runtime/system/native_array';
<del>
<del>import { registerKeyword, resetKeyword } from 'ember-htmlbars/tests/utils';
<del>import viewKeyword from 'ember-htmlbars/keywords/view';
<del>import { setOwner } from 'container/owner';
<del>
<del>var originalViewKeyword;
<del>var parentView, childView;
<del>
<del>import { test, testModule } from 'internal-test-helpers/tests/skip-if-glimmer';
<del>
<del>testModule('tests/views/view/child_views_tests.js', {
<del> setup() {
<del> originalViewKeyword = registerKeyword('view', viewKeyword);
<del> childView = EmberView.create({
<del> template: compile('ber')
<del> });
<del>
<del> parentView = EmberView.create({
<del> template: compile('Em{{view view.childView}}'),
<del> childView: childView
<del> });
<del> },
<del>
<del> teardown() {
<del> run(function() {
<del> parentView.destroy();
<del> childView.destroy();
<del> });
<del> resetKeyword('view', originalViewKeyword);
<del> }
<del>});
<del>
<del>// no parent element, buffer, no element
<del>// parent element
<del>
<del>// no parent element, no buffer, no element
<del>test('should render an inserted child view when the child is inserted before a DOM element is created', function() {
<del> run(function() {
<del> parentView.append();
<del> });
<del>
<del> equal(parentView.$().text(), 'Ember', 'renders the child view after the parent view');
<del>});
<del>
<del>test('should not duplicate childViews when rerendering', function() {
<del> var InnerView = EmberView.extend();
<del> var InnerView2 = EmberView.extend();
<del>
<del> var MiddleView = EmberView.extend({
<del> innerViewClass: InnerView,
<del> innerView2Class: InnerView2,
<del> template: compile('{{view view.innerViewClass}}{{view view.innerView2Class}}')
<del> });
<del>
<del> var outerView = EmberView.create({
<del> middleViewClass: MiddleView,
<del> template: compile('{{view view.middleViewClass viewName="middle"}}')
<del> });
<del>
<del> run(function() {
<del> outerView.append();
<del> });
<del>
<del> equal(outerView.get('middle.childViews.length'), 2, 'precond middle has 2 child views rendered to buffer');
<del>
<del> run(function() {
<del> outerView.middle.rerender();
<del> });
<del>
<del> equal(outerView.get('middle.childViews.length'), 2, 'middle has 2 child views rendered to buffer');
<del>
<del> run(function() {
<del> outerView.destroy();
<del> });
<del>});
<del>
<del>test('should remove childViews inside {{if}} on destroy', function() {
<del> var outerView = EmberView.extend({
<del> component: 'my-thing',
<del> value: false,
<del> template: compile(`
<del> {{#if view.value}}
<del> {{component view.component value=view.value}}
<del> {{/if}}
<del> `)
<del> }).create();
<del>
<del> setOwner(outerView, {
<del> lookup() {
<del> return {
<del> componentFor() {
<del> return Component.extend();
<del> },
<del>
<del> layoutFor() {
<del> return null;
<del> }
<del> };
<del> }
<del> });
<del>
<del> run(outerView, 'append');
<del> run(outerView, 'set', 'value', true);
<del>
<del> equal(outerView.get('childViews.length'), 1);
<del>
<del> run(outerView, 'set', 'value', false);
<del>
<del> equal(outerView.get('childViews.length'), 0, 'expected no views to be leaked');
<del>
<del> run(function() {
<del> outerView.destroy();
<del> });
<del>});
<del>
<del>test('should remove childViews inside {{each}} on destroy', function() {
<del> var outerView = EmberView.extend({
<del> component: 'my-thing',
<del> init() {
<del> this._super(...arguments);
<del> this.value = false;
<del> },
<del> template: compile(`
<del> {{#if view.value}}
<del> {{#each view.data as |item|}}
<del> {{component view.component value=item.value}}
<del> {{/each}}
<del> {{/if}}
<del> `)
<del> }).create();
<del>
<del> setOwner(outerView, {
<del> lookup() {
<del> return {
<del> componentFor() {
<del> return Component.extend();
<del> },
<del>
<del> layoutFor() {
<del> return null;
<del> }
<del> };
<del> }
<del> });
<del>
<del> run(outerView, 'append');
<del>
<del> equal(outerView.get('childViews.length'), 0);
<del>
<del> run(outerView, 'set', 'data', emberA([
<del> { id: 1, value: new Date() },
<del> { id: 2, value: new Date() }
<del> ]));
<del>
<del> equal(outerView.get('childViews.length'), 0);
<del>
<del> run(outerView, 'set', 'value', true);
<del> equal(outerView.get('childViews.length'), 2);
<del>
<del> run(outerView, 'set', 'value', false);
<del>
<del> equal(outerView.get('childViews.length'), 0, 'expected no views to be leaked');
<del>
<del> run(function() {
<del> outerView.destroy();
<del> });
<del>});
<ide><path>packages/ember-views/tests/views/view/create_child_view_test.js
<ide> import EmberView from 'ember-views/views/view';
<ide> import { on } from 'ember-metal/events';
<ide> import { observer } from 'ember-metal/mixin';
<ide>
<del>import { registerKeyword, resetKeyword } from 'ember-htmlbars/tests/utils';
<del>import viewKeyword from 'ember-htmlbars/keywords/view';
<ide> import { getOwner, OWNER } from 'container/owner';
<ide>
<del>var view, myViewClass, newView, owner, originalViewKeyword;
<add>var view, myViewClass, newView, owner;
<ide>
<ide> QUnit.module('EmberView#createChildView', {
<ide> setup() {
<del> originalViewKeyword = registerKeyword('view', viewKeyword);
<ide> owner = {};
<ide> view = EmberView.create({
<ide> [OWNER]: owner
<ide> QUnit.module('EmberView#createChildView', {
<ide> view.destroy();
<ide> if (newView) { newView.destroy(); }
<ide> });
<del> resetKeyword('view', originalViewKeyword);
<ide> }
<ide> });
<ide>
<ide><path>packages/ember-views/tests/views/view/create_element_test.js
<ide> import run from 'ember-metal/run_loop';
<ide> import EmberView from 'ember-views/views/view';
<ide> import { compile } from 'ember-htmlbars-template-compiler';
<ide>
<del>import { registerKeyword, resetKeyword } from 'ember-htmlbars/tests/utils';
<del>import viewKeyword from 'ember-htmlbars/keywords/view';
<del>
<del>var view, originalViewKeyword;
<add>var view;
<ide>
<ide> QUnit.module('Ember.View#createElement', {
<del> setup() {
<del> originalViewKeyword = registerKeyword('view', viewKeyword);
<del> },
<ide> teardown() {
<ide> run(function() {
<ide> view.destroy();
<ide> });
<del> resetKeyword('view', originalViewKeyword);
<ide> }
<ide> });
<ide>
<ide><path>packages/ember-views/tests/views/view/destroy_element_test.js
<ide> import { get } from 'ember-metal/property_get';
<ide> import run from 'ember-metal/run_loop';
<ide> import EmberView from 'ember-views/views/view';
<ide>
<del>import { registerKeyword, resetKeyword } from 'ember-htmlbars/tests/utils';
<del>import viewKeyword from 'ember-htmlbars/keywords/view';
<del>
<del>var originalViewKeyword;
<ide> var view;
<ide>
<ide> QUnit.module('EmberView#destroyElement', {
<del> setup() {
<del> originalViewKeyword = registerKeyword('view', viewKeyword);
<del> },
<ide> teardown() {
<ide> run(function() {
<ide> view.destroy();
<ide> });
<del> resetKeyword('view', originalViewKeyword);
<ide> }
<ide> });
<ide>
<ide><path>packages/ember-views/tests/views/view/is_visible_test.js
<ide> import run from 'ember-metal/run_loop';
<ide> import { computed } from 'ember-metal/computed';
<ide> import EmberView from 'ember-views/views/view';
<ide>
<del>import { registerKeyword, resetKeyword } from 'ember-htmlbars/tests/utils';
<del>import viewKeyword from 'ember-htmlbars/keywords/view';
<del>
<ide> var view;
<ide> var warnings, originalWarn;
<del>var originalViewKeyword;
<ide>
<ide> QUnit.module('EmberView#isVisible', {
<ide> setup() {
<del> originalViewKeyword = registerKeyword('view', viewKeyword);
<ide> warnings = [];
<ide> originalWarn = getDebugFunction('warn');
<ide> setDebugFunction('warn', function(message, test) {
<ide> QUnit.module('EmberView#isVisible', {
<ide> if (view) {
<ide> run(function() { view.destroy(); });
<ide> }
<del> resetKeyword('view', originalViewKeyword);
<ide> setDebugFunction('warn', originalWarn);
<ide> }
<ide> });
<ide><path>packages/ember-views/tests/views/view/nearest_of_type_test.js
<del>import run from 'ember-metal/run_loop';
<del>import { Mixin as EmberMixin } from 'ember-metal/mixin';
<del>import View from 'ember-views/views/view';
<del>import { compile } from 'ember-htmlbars-template-compiler';
<del>
<del>import { registerKeyword, resetKeyword } from 'ember-htmlbars/tests/utils';
<del>import viewKeyword from 'ember-htmlbars/keywords/view';
<del>
<del>var parentView, view;
<del>var originalViewKeyword;
<del>
<del>var Mixin, Parent;
<del>
<del>QUnit.module('View#nearest*', {
<del> setup() {
<del> originalViewKeyword = registerKeyword('view', viewKeyword);
<del> Mixin = EmberMixin.create({});
<del> Parent = View.extend(Mixin, {
<del> template: compile(`{{view}}`)
<del> });
<del> },
<del> teardown() {
<del> run(function() {
<del> if (parentView) { parentView.destroy(); }
<del> if (view) { view.destroy(); }
<del> });
<del> resetKeyword('view', originalViewKeyword);
<del> }
<del>});
<del>
<del>QUnit.test('nearestOfType should find the closest view by view class', function() {
<del> var child;
<del>
<del> run(function() {
<del> parentView = Parent.create();
<del> parentView.appendTo('#qunit-fixture');
<del> });
<del>
<del> child = parentView.get('childViews')[0];
<del> equal(child.nearestOfType(Parent), parentView, 'finds closest view in the hierarchy by class');
<del>});
<del>
<del>QUnit.test('nearestOfType should find the closest view by mixin', function() {
<del> var child;
<del>
<del> run(function() {
<del> parentView = Parent.create();
<del> parentView.appendTo('#qunit-fixture');
<del> });
<del>
<del> child = parentView.get('childViews')[0];
<del> equal(child.nearestOfType(Mixin), parentView, 'finds closest view in the hierarchy by class');
<del>});
<del>
<del>QUnit.test('nearestWithProperty should search immediate parent', function() {
<del> var childView;
<del>
<del> view = View.create({
<del> myProp: true,
<del> template: compile('{{view}}')
<del> });
<del>
<del> run(function() {
<del> view.appendTo('#qunit-fixture');
<del> });
<del>
<del> childView = view.get('childViews')[0];
<del> equal(childView.nearestWithProperty('myProp'), view);
<del>});
<del>
<del>QUnit.test('nearestChildOf should be deprecated', function() {
<del> var child;
<del>
<del> run(function() {
<del> parentView = Parent.create();
<del> parentView.appendTo('#qunit-fixture');
<del> });
<del>
<del> child = parentView.get('childViews')[0];
<del> expectDeprecation(function() {
<del> child.nearestChildOf(Parent);
<del> }, 'nearestChildOf has been deprecated.');
<del>});
<del>
<ide><path>packages/ember-views/tests/views/view/remove_test.js
<ide> import run from 'ember-metal/run_loop';
<ide> import jQuery from 'ember-views/system/jquery';
<ide> import View from 'ember-views/views/view';
<ide>
<del>import { registerKeyword, resetKeyword } from 'ember-htmlbars/tests/utils';
<del>import viewKeyword from 'ember-htmlbars/keywords/view';
<del>
<ide> var parentView, child;
<del>var originalViewKeyword;
<ide>
<ide> var view;
<ide> // .......................................................
<ide> // removeFromParent()
<ide> //
<ide> QUnit.module('View#removeFromParent', {
<del> setup() {
<del> originalViewKeyword = registerKeyword('view', viewKeyword);
<del> },
<ide> teardown() {
<ide> run(function() {
<ide> if (parentView) { parentView.destroy(); }
<ide> if (child) { child.destroy(); }
<ide> if (view) { view.destroy(); }
<ide> });
<del> resetKeyword('view', originalViewKeyword);
<ide> }
<ide> });
<ide>
<ide><path>packages/ember-views/tests/views/view/view_lifecycle_test.js
<ide> import { context } from 'ember-environment';
<ide> import run from 'ember-metal/run_loop';
<del>import EmberObject from 'ember-runtime/system/object';
<ide> import jQuery from 'ember-views/system/jquery';
<ide> import EmberView from 'ember-views/views/view';
<ide> import { compile } from 'ember-template-compiler';
<ide> import { registerHelper } from 'ember-htmlbars/helpers';
<ide>
<del>import { registerKeyword, resetKeyword } from 'ember-htmlbars/tests/utils';
<del>import viewKeyword from 'ember-htmlbars/keywords/view';
<del>
<ide> var originalLookup = context.lookup;
<del>var originalViewKeyword;
<ide> var lookup, view;
<ide>
<ide> import { test, testModule } from 'internal-test-helpers/tests/skip-if-glimmer';
<ide>
<ide> QUnit.module('views/view/view_lifecycle_test - pre-render', {
<ide> setup() {
<del> originalViewKeyword = registerKeyword('view', viewKeyword);
<ide> context.lookup = lookup = {};
<ide> },
<ide>
<ide> QUnit.module('views/view/view_lifecycle_test - pre-render', {
<ide> });
<ide> }
<ide> context.lookup = originalLookup;
<del> resetKeyword('view', originalViewKeyword);
<ide> }
<ide> });
<ide>
<del>test('should create and append a DOM element after bindings have synced', function() {
<del> var ViewTest;
<del>
<del> lookup.ViewTest = ViewTest = {};
<del>
<del> run(function() {
<del> ViewTest.fakeController = EmberObject.create({
<del> fakeThing: 'controllerPropertyValue'
<del> });
<del>
<del> let deprecationMessage = '`Ember.Binding` is deprecated. Since you' +
<del> ' are binding to a global consider using a service instead.';
<del>
<del> expectDeprecation(() => {
<del> view = EmberView.create({
<del> fooBinding: 'ViewTest.fakeController.fakeThing',
<del> template: compile('{{view.foo}}')
<del> });
<del> }, deprecationMessage);
<del>
<del> ok(!view.get('element'), 'precond - does not have an element before appending');
<del>
<del> // the actual render happens in the `render` queue, which is after the `sync`
<del> // queue where the binding is synced.
<del> view.append();
<del> });
<del>
<del> equal(view.$().text(), 'controllerPropertyValue', 'renders and appends after bindings have synced');
<del>});
<del>
<ide> QUnit.test('should throw an exception if trying to append a child before rendering has begun', function() {
<ide> run(function() {
<ide> view = EmberView.create();
<ide> test('should not affect rendering if destroyElement is called before initial ren
<ide> });
<ide>
<ide> testModule('views/view/view_lifecycle_test - in render', {
<del> setup() {
<del> originalViewKeyword = registerKeyword('view', viewKeyword);
<del> },
<ide> teardown() {
<ide> if (view) {
<ide> run(function() {
<ide> view.destroy();
<ide> });
<ide> }
<del> resetKeyword('view', originalViewKeyword);
<ide> }
<ide> });
<ide>
<ide> test('rerender of top level view during rendering should throw', function() {
<ide> );
<ide> });
<ide>
<del>test('rerender of non-top level view during rendering should throw', function() {
<del> let innerView = EmberView.create({
<del> template: compile('{{throw}}')
<del> });
<del> registerHelper('throw', function() {
<del> innerView.rerender();
<del> });
<del> view = EmberView.create({
<del> template: compile('{{view view.innerView}}'),
<del> innerView
<del> });
<del> throws(
<del> function() {
<del> run(view, view.appendTo, '#qunit-fixture');
<del> },
<del> /Something you did caused a view to re-render after it rendered but before it was inserted into the DOM./,
<del> 'expected error was not raised'
<del> );
<del>});
<ide>
<ide> QUnit.module('views/view/view_lifecycle_test - hasElement', {
<ide> teardown() {
<ide><path>packages/ember-views/tests/views/view_test.js
<ide> import jQuery from 'ember-views/system/jquery';
<ide> import EmberView from 'ember-views/views/view';
<ide> import { compile } from 'ember-template-compiler';
<ide>
<del>import { registerKeyword, resetKeyword } from 'ember-htmlbars/tests/utils';
<del>import viewKeyword from 'ember-htmlbars/keywords/view';
<del>
<del>var view, originalViewKeyword;
<add>var view;
<ide>
<ide> QUnit.module('Ember.View', {
<del> setup() {
<del> originalViewKeyword = registerKeyword('view', viewKeyword);
<del> },
<ide> teardown() {
<ide> run(function() {
<ide> view.destroy();
<ide> });
<del> resetKeyword('view', originalViewKeyword);
<ide> }
<ide> });
<ide>
<ide> test('should re-render if the context is changed', function() {
<ide>
<ide> equal(jQuery('#qunit-fixture #template-context-test').text(), 'bang baz', 're-renders the view with the updated context');
<ide> });
<del>
<del>test('propagates dependent-key invalidated sets upstream', function() {
<del> view = EmberView.create({
<del> parentProp: 'parent-value',
<del> template: compile('{{view view.childView childProp=view.parentProp}}'),
<del> childView: EmberView.create({
<del> template: compile('child template'),
<del> childProp: 'old-value'
<del> })
<del> });
<del>
<del> run(view, view.append);
<del>
<del> equal(view.get('parentProp'), 'parent-value', 'precond - parent value is there');
<del> var childView = view.get('childView');
<del>
<del> run(function() {
<del> childView.set('childProp', 'new-value');
<del> });
<del>
<del> equal(view.get('parentProp'), 'new-value', 'new value is propagated across template');
<del>});
<del>
<del>test('propagates dependent-key invalidated bindings upstream', function() {
<del> view = EmberView.create({
<del> parentProp: 'parent-value',
<del> template: compile('{{view view.childView childProp=view.parentProp}}'),
<del> childView: EmberView.extend({
<del> template: compile('child template'),
<del> childProp: computed('dependencyProp', {
<del> get(key) {
<del> return this.get('dependencyProp');
<del> },
<del> set(key, value) {
<del> // Avoid getting stomped by the template attrs
<del> return this.get('dependencyProp');
<del> }
<del> }),
<del> dependencyProp: 'old-value'
<del> }).create()
<del> });
<del>
<del> run(view, view.append);
<del>
<del> equal(view.get('parentProp'), 'parent-value', 'precond - parent value is there');
<del> var childView = view.get('childView');
<del> run(() => childView.set('dependencyProp', 'new-value'));
<del> equal(childView.get('childProp'), 'new-value', 'pre-cond - new value is propagated to CP');
<del> equal(view.get('parentProp'), 'new-value', 'new value is propagated across template');
<del>});
<ide><path>packages/ember/tests/routing/basic_test.js
<ide> import { addObserver } from 'ember-metal/observer';
<ide> import { setTemplates, set as setTemplate } from 'ember-templates/template_registry';
<ide> import { test, asyncTest } from 'internal-test-helpers/tests/skip-if-glimmer';
<ide>
<del>
<ide> var trim = jQuery.trim;
<ide>
<ide> var Router, App, router, registry, container, originalLoggerError;
<ide> test('The template is not re-rendered when the route\'s context changes', functi
<ide> equal(insertionCount, 1, 'view should still have inserted only once');
<ide> });
<ide>
<add>test('The template is not re-rendered when two routes present the exact same template & controller', function() {
<add> Router.map(function() {
<add> this.route('first');
<add> this.route('second');
<add> this.route('third');
<add> this.route('fourth');
<add> });
<add>
<add> // Note add a component to test insertion
<add>
<add> let insertionCount = 0;
<add> App.XInputComponent = Component.extend({
<add> didInsertElement() {
<add> insertionCount += 1;
<add> }
<add> });
<add>
<add> App.SharedRoute = Route.extend({
<add> setupController(controller) {
<add> this.controllerFor('shared').set('message', 'This is the ' + this.routeName + ' message');
<add> },
<add>
<add> renderTemplate(controller, context) {
<add> this.render('shared', { controller: 'shared' });
<add> }
<add> });
<add>
<add> App.FirstRoute = App.SharedRoute.extend();
<add> App.SecondRoute = App.SharedRoute.extend();
<add> App.ThirdRoute = App.SharedRoute.extend();
<add> App.FourthRoute = App.SharedRoute.extend();
<add>
<add> App.SharedController = Controller.extend();
<add>
<add> setTemplate('shared', compile(
<add> '<p>{{message}}{{x-input}}</p>'
<add> ));
<add>
<add> bootApplication();
<add>
<add> handleURL('/first');
<add>
<add> equal(jQuery('p', '#qunit-fixture').text(), 'This is the first message');
<add> equal(insertionCount, 1, 'expected one assertion');
<add>
<add> // Transition by URL
<add> handleURL('/second');
<add>
<add> equal(jQuery('p', '#qunit-fixture').text(), 'This is the second message');
<add> equal(insertionCount, 1, 'expected one assertion');
<add>
<add> // Then transition directly by route name
<add> run(function() {
<add> router.transitionTo('third').then(function(value) {
<add> ok(true, 'expected transition');
<add> }, function(reason) {
<add> ok(false, 'unexpected transition failure: ', QUnit.jsDump.parse(reason));
<add> });
<add> });
<add>
<add> equal(jQuery('p', '#qunit-fixture').text(), 'This is the third message');
<add> equal(insertionCount, 1, 'expected one assertion');
<add>
<add> // Lastly transition to a different view, with the same controller and template
<add> handleURL('/fourth');
<add> equal(insertionCount, 1, 'expected one assertion');
<add>
<add> equal(jQuery('p', '#qunit-fixture').text(), 'This is the fourth message');
<add>});
<add>
<ide> QUnit.test('ApplicationRoute with model does not proxy the currentPath', function() {
<ide> var model = {};
<ide> var currentPath; | 17 |
PHP | PHP | use weak etag header in tests | d2aa969206aa1b7738b911cdaf29038f249b5066 | <ide><path>test/data/etag.php
<ide> $ts = $_REQUEST['ts'];
<ide> $etag = md5($ts);
<ide>
<del>$ifNoneMatch = isset($_SERVER['HTTP_IF_NONE_MATCH']) ? stripslashes($_SERVER['HTTP_IF_NONE_MATCH']) : false;
<add>$ifNoneMatch = isset($_SERVER['HTTP_IF_NONE_MATCH']) ? stripslashes($_SERVER['HTTP_IF_NONE_MATCH']) : "";
<add>preg_match('/"([^"]+)"/', $ifNoneMatch, $matches);
<add>$ifNoneMatch = isset($matches[1]) ? $matches[1] : false;
<add>
<ide> if ($ifNoneMatch == $etag) {
<ide> header('HTTP/1.0 304 Not Modified');
<ide> die; // stop processing
<ide> }
<ide>
<del>header("Etag: " . $etag);
<add>header("Etag: W/\"" . $etag . "\"");
<ide>
<ide> if ( $ifNoneMatch ) {
<ide> echo "OK: " . $etag; | 1 |
Text | Text | add single executable application initiative | 2de8dd15c185cdc5fa30dad9d303685ec1433e94 | <ide><path>doc/contributing/strategic-initiatives.md
<ide> agenda to ensure they are active and have the support they need.
<ide>
<ide> ## Current initiatives
<ide>
<del>| Initiative | Champion | Links |
<del>| ------------------- | --------------------------- | --------------------------------------------- |
<del>| Core Promise APIs | [Antoine du Hamel][aduh95] | <https://github.com/nodejs/TSC/issues/1094> |
<del>| QUIC / HTTP3 | [James M Snell][jasnell] | <https://github.com/nodejs/quic> |
<del>| Shadow Realm | [Chengzhong Wu][legendecas] | <https://github.com/nodejs/node/issues/42528> |
<del>| Startup performance | [Joyee Cheung][joyeecheung] | <https://github.com/nodejs/node/issues/35711> |
<del>| V8 Currency | [Michaël Zasso][targos] | |
<del>| Next-10 | [Michael Dawson][mhdawson] | <https://github.com/nodejs/next-10> |
<add>| Initiative | Champion | Links |
<add>| ---------------------- | --------------------------- | --------------------------------------------- |
<add>| Core Promise APIs | [Antoine du Hamel][aduh95] | <https://github.com/nodejs/TSC/issues/1094> |
<add>| QUIC / HTTP3 | [James M Snell][jasnell] | <https://github.com/nodejs/quic> |
<add>| Shadow Realm | [Chengzhong Wu][legendecas] | <https://github.com/nodejs/node/issues/42528> |
<add>| Startup performance | [Joyee Cheung][joyeecheung] | <https://github.com/nodejs/node/issues/35711> |
<add>| V8 Currency | [Michaël Zasso][targos] | |
<add>| Next-10 | [Michael Dawson][mhdawson] | <https://github.com/nodejs/next-10> |
<add>| Single executable apps | [Jesse Chan][jesec] | <https://github.com/nodejs/node/issues/43432> |
<ide>
<ide> <details>
<ide> <summary>List of completed initiatives</summary>
<ide> agenda to ensure they are active and have the support they need.
<ide>
<ide> [aduh95]: https://github.com/aduh95
<ide> [jasnell]: https://github.com/jasnell
<add>[jesec]: https://github.com/jesec
<ide> [joyeecheung]: https://github.com/joyeecheung
<ide> [legendecas]: https://github.com/legendecas
<ide> [mhdawson]: https://github.com/mhdawson | 1 |
Text | Text | add url.format() example | 1572a5b6cd16aeb6cafd338814ead76c0f198f1d | <ide><path>doc/api/url.md
<ide> changes:
<ide> The `url.format()` method returns a formatted URL string derived from
<ide> `urlObject`.
<ide>
<add>```js
<add>url.format({
<add> protocol: 'https',
<add> hostname: 'example.com',
<add> pathname: '/some/path',
<add> query: {
<add> page: 1,
<add> format: 'json'
<add> }
<add>});
<add>
<add>// => 'https://example.com/some/path?page=1&format=json'
<add>```
<add>
<ide> If `urlObject` is not an object or a string, `url.format()` will throw a
<ide> [`TypeError`][].
<ide> | 1 |
Javascript | Javascript | improve matrix3 closure performance | 2b46f6288c2c570c0eea2471d9c79deff2a06ffd | <ide><path>src/math/Matrix3.js
<ide> Object.assign( Matrix3.prototype, {
<ide>
<ide> applyToBufferAttribute: function () {
<ide>
<del> var v1;
<add> var v1 = new Vector3();
<ide>
<ide> return function applyToBufferAttribute( attribute ) {
<ide>
<del> if ( v1 === undefined ) v1 = new Vector3();
<del>
<ide> for ( var i = 0, l = attribute.count; i < l; i ++ ) {
<ide>
<ide> v1.x = attribute.getX( i ); | 1 |
Text | Text | remove beta from observablehq | 455f1f12c9013d727e1f7aa2b367b39fca9c2c4f | <ide><path>CHANGES.md
<ide>
<ide> D3 5.0 introduces only a few non-backwards-compatible changes.
<ide>
<del>D3 now uses [Promises](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises) instead of asynchronous callbacks to load data. Promises simplify the structure of asynchronous code, especially in modern browsers that support [async and await](https://javascript.info/async-await). (See this [introduction to promises](https://beta.observablehq.com/@mbostock/introduction-to-promises) on [Observable](https://beta.observablehq.com).) For example, to load a CSV file in v4, you might say:
<add>D3 now uses [Promises](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises) instead of asynchronous callbacks to load data. Promises simplify the structure of asynchronous code, especially in modern browsers that support [async and await](https://javascript.info/async-await). (See this [introduction to promises](https://observablehq.com/@mbostock/introduction-to-promises) on [Observable](https://observablehq.com).) For example, to load a CSV file in v4, you might say:
<ide>
<ide> ```js
<ide> d3.csv("file.csv", function(error, data) {
<ide> const data = await d3.csv("file.csv");
<ide> console.log(data);
<ide> ```
<ide>
<del>With the adoption of promises, D3 now uses the [Fetch API](https://fetch.spec.whatwg.org/) instead of [XMLHttpRequest](https://developer.mozilla.org/docs/Web/API/XMLHttpRequest): the [d3-request](https://github.com/d3/d3-request) module has been replaced by [d3-fetch](https://github.com/d3/d3-fetch). Fetch supports many powerful new features, such as [streaming responses](https://beta.observablehq.com/@mbostock/streaming-shapefiles). D3 5.0 also deprecates and removes the [d3-queue](https://github.com/d3/d3-queue) module. Use [Promise.all](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise/all) to run a batch of asynchronous tasks in parallel, or a helper library such as [p-queue](https://github.com/sindresorhus/p-queue) to [control concurrency](https://beta.observablehq.com/@mbostock/hello-p-queue).
<add>With the adoption of promises, D3 now uses the [Fetch API](https://fetch.spec.whatwg.org/) instead of [XMLHttpRequest](https://developer.mozilla.org/docs/Web/API/XMLHttpRequest): the [d3-request](https://github.com/d3/d3-request) module has been replaced by [d3-fetch](https://github.com/d3/d3-fetch). Fetch supports many powerful new features, such as [streaming responses](https://observablehq.com/@mbostock/streaming-shapefiles). D3 5.0 also deprecates and removes the [d3-queue](https://github.com/d3/d3-queue) module. Use [Promise.all](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise/all) to run a batch of asynchronous tasks in parallel, or a helper library such as [p-queue](https://github.com/sindresorhus/p-queue) to [control concurrency](https://observablehq.com/@mbostock/hello-p-queue).
<ide>
<ide> D3 no longer provides the d3.schemeCategory20* categorical color schemes. These twenty-color schemes were flawed because their grouped design could falsely imply relationships in the data: a shared hue can imply that the encoded data are part of a group (a super-category), while relative lightness can imply order. Instead, D3 now includes [d3-scale-chromatic](https://github.com/d3/d3-scale-chromatic), which implements excellent schemes from ColorBrewer, including [categorical](https://github.com/d3/d3-scale-chromatic/blob/master/README.md#categorical), [diverging](https://github.com/d3/d3-scale-chromatic/blob/master/README.md#diverging), [sequential single-hue](https://github.com/d3/d3-scale-chromatic/blob/master/README.md#sequential-single-hue) and [sequential multi-hue](https://github.com/d3/d3-scale-chromatic/blob/master/README.md#sequential-multi-hue) schemes. These schemes are available in both discrete and continuous variants.
<ide>
<del>D3 now provides implementations of [marching squares](https://beta.observablehq.com/@mbostock/d3-contour-plot) and [density estimation](https://beta.observablehq.com/@mbostock/d3-density-contours) via [d3-contour](https://github.com/d3/d3-contour)! There are two new [d3-selection](https://github.com/d3/d3-selection) methods: [*selection*.clone](https://github.com/d3/d3-selection/blob/master/README.md#selection_clone) for inserting clones of the selected nodes, and [d3.create](https://github.com/d3/d3-selection/blob/master/README.md#create) for creating detached elements. [Geographic projections](https://github.com/d3/d3-geo) now support [*projection*.angle](https://github.com/d3/d3-geo/blob/master/README.md#projection_angle), which has enabled several fantastic new [polyhedral projections](https://github.com/d3/d3-geo-polygon) by Philippe Rivière.
<add>D3 now provides implementations of [marching squares](https://observablehq.com/@mbostock/d3-contour-plot) and [density estimation](https://observablehq.com/@mbostock/d3-density-contours) via [d3-contour](https://github.com/d3/d3-contour)! There are two new [d3-selection](https://github.com/d3/d3-selection) methods: [*selection*.clone](https://github.com/d3/d3-selection/blob/master/README.md#selection_clone) for inserting clones of the selected nodes, and [d3.create](https://github.com/d3/d3-selection/blob/master/README.md#create) for creating detached elements. [Geographic projections](https://github.com/d3/d3-geo) now support [*projection*.angle](https://github.com/d3/d3-geo/blob/master/README.md#projection_angle), which has enabled several fantastic new [polyhedral projections](https://github.com/d3/d3-geo-polygon) by Philippe Rivière.
<ide>
<ide> Lastly, D3’s [package.json](https://github.com/d3/d3/blob/master/package.json) no longer pins exact versions of the dependent D3 modules. This fixes an issue with [duplicate installs](https://github.com/d3/d3/issues/3256) of D3 modules.
<ide> | 1 |
Ruby | Ruby | remove unused values variable | e5772a1f56568547ca72ad053cb812cd22dbd466 | <ide><path>lib/arel/visitors/to_sql.rb
<ide> def visit_Arel_Nodes_UpdateStatement o, collector
<ide>
<ide> collector << "UPDATE "
<ide> collector = visit o.relation, collector
<del> values = false
<ide> unless o.values.empty?
<del> values = true
<ide> collector << " SET "
<ide> collector = inject_join o.values, collector, ", "
<ide> end | 1 |
Go | Go | add testcontainerapipause case | 8636a219911536123decb547dab9bf50ebb2c8f8 | <ide><path>integration-cli/docker_api_containers_test.go
<ide> package main
<ide> import (
<ide> "bytes"
<ide> "encoding/json"
<add> "github.com/docker/docker/api/types"
<add> "github.com/docker/docker/pkg/stringid"
<add> "github.com/docker/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar"
<ide> "io"
<ide> "os/exec"
<ide> "strings"
<ide> "testing"
<ide> "time"
<del>
<del> "github.com/docker/docker/api/types"
<del> "github.com/docker/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar"
<ide> )
<ide>
<ide> func TestContainerApiGetAll(t *testing.T) {
<ide> func TestPostContainerBindNormalVolume(t *testing.T) {
<ide>
<ide> logDone("container REST API - can use path from normal volume as bind-mount to overwrite another volume")
<ide> }
<add>
<add>func TestContainerApiPause(t *testing.T) {
<add> defer deleteAllContainers()
<add> defer unpauseAllContainers()
<add> runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "sleep", "30")
<add> out, _, err := runCommandWithOutput(runCmd)
<add>
<add> if err != nil {
<add> t.Fatalf("failed to create a container: %s, %v", out, err)
<add> }
<add> ContainerID := strings.TrimSpace(out)
<add>
<add> if _, err = sockRequest("POST", "/containers/"+ContainerID+"/pause", nil); err != nil && !strings.Contains(err.Error(), "204 No Content") {
<add> t.Fatalf("POST a container pause: sockRequest failed: %v", err)
<add> }
<add>
<add> pausedContainers, err := getSliceOfPausedContainers()
<add>
<add> if err != nil {
<add> t.Fatalf("error thrown while checking if containers were paused: %v", err)
<add> }
<add>
<add> if len(pausedContainers) != 1 || stringid.TruncateID(ContainerID) != pausedContainers[0] {
<add> t.Fatalf("there should be one paused container and not %d", len(pausedContainers))
<add> }
<add>
<add> if _, err = sockRequest("POST", "/containers/"+ContainerID+"/unpause", nil); err != nil && !strings.Contains(err.Error(), "204 No Content") {
<add> t.Fatalf("POST a container pause: sockRequest failed: %v", err)
<add> }
<add>
<add> pausedContainers, err = getSliceOfPausedContainers()
<add>
<add> if err != nil {
<add> t.Fatalf("error thrown while checking if containers were paused: %v", err)
<add> }
<add>
<add> if pausedContainers != nil {
<add> t.Fatalf("There should be no paused container.")
<add> }
<add>
<add> logDone("container REST API - check POST containers/pause nad unpause")
<add>}
<ide><path>integration-cli/docker_utils.go
<ide> func getPausedContainers() (string, error) {
<ide> func getSliceOfPausedContainers() ([]string, error) {
<ide> out, err := getPausedContainers()
<ide> if err == nil {
<add> if len(out) == 0 {
<add> return nil, err
<add> }
<ide> slice := strings.Split(strings.TrimSpace(out), "\n")
<ide> return slice, err
<ide> } | 2 |
Javascript | Javascript | fix documentation for run.later | 5395ccb5021c7509725cbe4b294a2b964fea7b54 | <ide><path>packages/ember-metal/lib/run_loop.js
<ide> run.sync = function() {
<ide> target at the time the method is invoked.
<ide> @param {Object} [args*] Optional arguments to pass to the timeout.
<ide> @param {Number} wait Number of milliseconds to wait.
<del> @return {Object} Timer information for use in cancelling, see `run.cancel`.
<add> @return {*} Timer information for use in cancelling, see `run.cancel`.
<ide> */
<ide> run.later = function(/*target, method*/) {
<ide> return backburner.later.apply(backburner, arguments); | 1 |
Javascript | Javascript | add links to docs for addons and top level api | db175052c00a65e6a852011f889c12fea50bb34b | <ide><path>src/addons/ReactComponentWithPureRenderMixin.js
<ide> var shallowCompare = require('shallowCompare');
<ide> * complex data structures this mixin may have false-negatives for deeper
<ide> * differences. Only mixin to components which have simple props and state, or
<ide> * use `forceUpdate()` when you know deep data structures have changed.
<add> *
<add> * See https://facebook.github.io/react/docs/pure-render-mixin.html
<ide> */
<ide> var ReactComponentWithPureRenderMixin = {
<ide> shouldComponentUpdate: function(nextProps, nextState) {
<ide><path>src/addons/ReactFragment.js
<ide> var numericPropertyRegex = /^\d+$/;
<ide> var warnedAboutNumeric = false;
<ide>
<ide> var ReactFragment = {
<del> // Wrap a keyed object in an opaque proxy that warns you if you access any
<del> // of its properties.
<add> /**
<add> * Wrap a keyed object in an opaque proxy that warns you if you access any
<add> * of its properties.
<add> * See https://facebook.github.io/react/docs/create-fragment.html
<add> */
<ide> create: function(object) {
<ide> if (typeof object !== 'object' || !object || Array.isArray(object)) {
<ide> warning(
<ide><path>src/addons/link/LinkedStateMixin.js
<ide> var ReactStateSetters = require('ReactStateSetters');
<ide>
<ide> /**
<ide> * A simple mixin around ReactLink.forState().
<add> * See https://facebook.github.io/react/docs/two-way-binding-helpers.html
<ide> */
<ide> var LinkedStateMixin = {
<ide> /**
<ide><path>src/addons/link/ReactLink.js
<ide> var React = require('React');
<ide>
<ide> /**
<add> * Deprecated: An an easy way to express two-way binding with React.
<add> * See https://facebook.github.io/react/docs/two-way-binding-helpers.html
<add> *
<ide> * @param {*} value current value of the link
<ide> * @param {function} requestChange callback to request a change
<ide> */
<ide><path>src/addons/shallowCompare.js
<ide> var shallowEqual = require('shallowEqual');
<ide> /**
<ide> * Does a shallow comparison for props and state.
<ide> * See ReactComponentWithPureRenderMixin
<add> * See also https://facebook.github.io/react/docs/shallow-compare.html
<ide> */
<ide> function shallowCompare(instance, nextProps, nextState) {
<ide> return (
<ide><path>src/addons/transitions/ReactCSSTransitionGroup.js
<ide> function createTransitionTimeoutPropValidator(transitionType) {
<ide> };
<ide> }
<ide>
<add>/**
<add> * An easy way to perform CSS transitions and animations when a React component
<add> * enters or leaves the DOM.
<add> * See https://facebook.github.io/react/docs/animation.html#high-level-api-reactcsstransitiongroup
<add> */
<ide> var ReactCSSTransitionGroup = React.createClass({
<ide> displayName: 'ReactCSSTransitionGroup',
<ide>
<ide><path>src/addons/transitions/ReactTransitionGroup.js
<ide> var ReactTransitionChildMapping = require('ReactTransitionChildMapping');
<ide>
<ide> var emptyFunction = require('emptyFunction');
<ide>
<add>/**
<add> * A basis for animatins. When children are declaratively added or removed,
<add> * special lifecycle hooks are called.
<add> * See https://facebook.github.io/react/docs/animation.html#low-level-api-reacttransitiongroup
<add> */
<ide> var ReactTransitionGroup = React.createClass({
<ide> displayName: 'ReactTransitionGroup',
<ide>
<ide><path>src/addons/update.js
<ide> function invariantArrayCase(value, spec, command) {
<ide> );
<ide> }
<ide>
<add>/**
<add> * Returns a updated shallow copy of an object without mutating the original.
<add> * See https://facebook.github.io/react/docs/update.html for details.
<add> */
<ide> function update(value, spec) {
<ide> invariant(
<ide> typeof spec === 'object',
<ide><path>src/isomorphic/children/ReactChildren.js
<ide> function forEachSingleChild(bookKeeping, child, name) {
<ide> /**
<ide> * Iterates through children that are typically specified as `props.children`.
<ide> *
<add> * See https://facebook.github.io/react/docs/top-level-api.html#react.children.foreach
<add> *
<ide> * The provided forEachFunc(child, index) will be called for each
<ide> * leaf child.
<ide> *
<ide> function mapIntoWithKeyPrefixInternal(children, array, prefix, func, context) {
<ide> /**
<ide> * Maps children that are typically specified as `props.children`.
<ide> *
<del> * The provided mapFunction(child, index) will be called for each
<add> * See https://facebook.github.io/react/docs/top-level-api.html#react.children.map
<add> *
<add> * The provided mapFunction(child, key, index) will be called for each
<ide> * leaf child.
<ide> *
<ide> * @param {?*} children Children tree container.
<ide> function forEachSingleChildDummy(traverseContext, child, name) {
<ide> * Count the number of children that are typically specified as
<ide> * `props.children`.
<ide> *
<add> * See https://facebook.github.io/react/docs/top-level-api.html#react.children.count
<add> *
<ide> * @param {?*} children Children tree container.
<ide> * @return {number} The number of children.
<ide> */
<ide> function countChildren(children, context) {
<ide> /**
<ide> * Flatten a children object (typically specified as `props.children`) and
<ide> * return an array with appropriately re-keyed children.
<add> *
<add> * See https://facebook.github.io/react/docs/top-level-api.html#react.children.toarray
<ide> */
<ide> function toArray(children) {
<ide> var result = [];
<ide><path>src/isomorphic/children/onlyChild.js
<ide> var invariant = require('invariant');
<ide>
<ide> /**
<ide> * Returns the first child in a collection of children and verifies that there
<del> * is only one child in the collection. The current implementation of this
<del> * function assumes that a single child gets passed without a wrapper, but the
<del> * purpose of this helper function is to abstract away the particular structure
<del> * of children.
<add> * is only one child in the collection.
<add> *
<add> * See https://facebook.github.io/react/docs/top-level-api.html#react.children.only
<add> *
<add> * The current implementation of this function assumes that a single child gets
<add> * passed without a wrapper, but the purpose of this helper function is to
<add> * abstract away the particular structure of children.
<ide> *
<ide> * @param {?object} children Child collection structure.
<ide> * @return {ReactElement} The first and only `ReactElement` contained in the
<ide><path>src/isomorphic/classic/class/ReactClass.js
<ide> var ReactClass = {
<ide>
<ide> /**
<ide> * Creates a composite component class given a class specification.
<add> * See https://facebook.github.io/react/docs/top-level-api.html#react.createclass
<ide> *
<ide> * @param {object} spec Class specification (which must define `render`).
<ide> * @return {function} Component constructor function.
<ide><path>src/isomorphic/classic/element/ReactElement.js
<ide> var ReactElement = function(type, key, ref, self, source, owner, props) {
<ide> return element;
<ide> };
<ide>
<add>/**
<add> * Create and return a new ReactElement of the given type.
<add> * See https://facebook.github.io/react/docs/top-level-api.html#react.createelement
<add> */
<ide> ReactElement.createElement = function(type, config, children) {
<ide> var propName;
<ide>
<ide> ReactElement.createElement = function(type, config, children) {
<ide> );
<ide> };
<ide>
<add>/**
<add> * Return a function that produces ReactElements of a given type.
<add> * See https://facebook.github.io/react/docs/top-level-api.html#react.createfactory
<add> */
<ide> ReactElement.createFactory = function(type) {
<ide> var factory = ReactElement.createElement.bind(null, type);
<ide> // Expose the type on the factory and the prototype so that it can be
<ide> ReactElement.cloneAndReplaceKey = function(oldElement, newKey) {
<ide> return newElement;
<ide> };
<ide>
<add>/**
<add> * Clone and return a new ReactElement using element as the starting point.
<add> * See https://facebook.github.io/react/docs/top-level-api.html#react.cloneelement
<add> */
<ide> ReactElement.cloneElement = function(element, config, children) {
<ide> var propName;
<ide>
<ide> ReactElement.cloneElement = function(element, config, children) {
<ide> };
<ide>
<ide> /**
<add> * Verifies the object is a ReactElement.
<add> * See https://facebook.github.io/react/docs/top-level-api.html#react.isvalidelement
<ide> * @param {?object} object
<ide> * @return {boolean} True if `object` is a valid component.
<ide> * @final
<ide><path>src/renderers/dom/client/ReactMount.js
<ide> var ReactMount = {
<ide>
<ide> /**
<ide> * Renders a React component into the DOM in the supplied `container`.
<add> * See https://facebook.github.io/react/docs/top-level-api.html#reactdom.render
<ide> *
<ide> * If the React component was previously rendered into `container`, this will
<ide> * perform an update on it and only mutate the DOM as necessary to reflect the
<ide> var ReactMount = {
<ide>
<ide> /**
<ide> * Unmounts and destroys the React component rendered in the `container`.
<add> * See https://facebook.github.io/react/docs/top-level-api.html#reactdom.unmountcomponentatnode
<ide> *
<ide> * @param {DOMElement} container DOM element containing a React component.
<ide> * @return {boolean} True if a component was found in and unmounted from
<ide><path>src/renderers/dom/client/findDOMNode.js
<ide> var warning = require('warning');
<ide> /**
<ide> * Returns the DOM node rendered by this element.
<ide> *
<add> * See https://facebook.github.io/react/docs/top-level-api.html#reactdom.finddomnode
<add> *
<ide> * @param {ReactComponent|DOMElement} componentOrElement
<ide> * @return {?DOMElement} The root node of this element.
<ide> */
<ide><path>src/renderers/dom/server/ReactServerRendering.js
<ide> function renderToStringImpl(element, makeStaticMarkup) {
<ide> }
<ide> }
<ide>
<add>/**
<add> * Render a ReactElement to its initial HTML. This should only be used on the
<add> * server.
<add> * See https://facebook.github.io/react/docs/top-level-api.html#reactdomserver.rendertostring
<add> */
<ide> function renderToString(element) {
<ide> invariant(
<ide> ReactElement.isValidElement(element),
<ide> function renderToString(element) {
<ide> return renderToStringImpl(element, false);
<ide> }
<ide>
<add>/**
<add> * Similar to renderToString, except this doesn't create extra DOM attributes
<add> * such as data-react-id that React uses internally.
<add> * See https://facebook.github.io/react/docs/top-level-api.html#reactdomserver.rendertostaticmarkup
<add> */
<ide> function renderToStaticMarkup(element) {
<ide> invariant(
<ide> ReactElement.isValidElement(element),
<ide><path>src/test/ReactPerf.js
<ide> /**
<ide> * ReactPerf is a general AOP system designed to measure performance. This
<ide> * module only has the hooks: see ReactDefaultPerf for the analysis tool.
<add> * See also https://facebook.github.io/react/docs/perf.html
<ide> */
<ide> var ReactPerf = {
<ide> /**
<ide><path>src/test/ReactTestUtils.js
<ide> function findAllInRenderedTreeInternal(inst, test) {
<ide> }
<ide>
<ide> /**
<add> * Utilities for making it easy to test React components.
<add> *
<add> * See https://facebook.github.io/react/docs/test-utils.html
<add> *
<ide> * Todo: Support the entire DOM.scry query syntax. For now, these simple
<ide> * utilities will suffice for testing purposes.
<ide> * @lends ReactTestUtils | 17 |
Python | Python | add placeholders for extension methods | baac7377f7ad616d1e45b3456900be64c7d2ae8e | <ide><path>libcloud/dns/drivers/cloudflare.py
<ide> def _ex_get_user_account_memberships(params):
<ide> return self._paginate(_ex_get_user_account_memberships,
<ide> self.MEMBERSHIPS_PAGE_SIZE)
<ide>
<add> def ex_get_zone_stats(self, zone, interval=30):
<add> raise NotImplementedError('not yet implemented in v4 driver')
<add>
<add> def ex_zone_check(self, zones):
<add> raise NotImplementedError('not yet implemented in v4 driver')
<add>
<add> def ex_get_ip_threat_score(self, ip):
<add> raise NotImplementedError('not yet implemented in v4 driver')
<add>
<add> def ex_get_zone_settings(self, zone):
<add> raise NotImplementedError('not yet implemented in v4 driver')
<add>
<add> def ex_set_zone_security_level(self, zone, level):
<add> raise NotImplementedError('not yet implemented in v4 driver')
<add>
<add> def ex_set_zone_cache_level(self, zone, level):
<add> raise NotImplementedError('not yet implemented in v4 driver')
<add>
<add> def ex_enable_development_mode(self, zone):
<add> raise NotImplementedError('not yet implemented in v4 driver')
<add>
<add> def ex_disable_development_mode(self, zone):
<add> raise NotImplementedError('not yet implemented in v4 driver')
<add>
<add> def ex_purge_cached_files(self, zone):
<add> raise NotImplementedError('not yet implemented in v4 driver')
<add>
<add> def ex_purge_cached_file(self, zone, url):
<add> raise NotImplementedError('not yet implemented in v4 driver')
<add>
<add> def ex_whitelist_ip(self, zone, ip):
<add> raise NotImplementedError('not yet implemented in v4 driver')
<add>
<add> def ex_blacklist_ip(self, zone, ip):
<add> raise NotImplementedError('not yet implemented in v4 driver')
<add>
<add> def ex_unlist_ip(self, zone, ip):
<add> raise NotImplementedError('not yet implemented in v4 driver')
<add>
<add> def ex_enable_ipv6_support(self, zone):
<add> raise NotImplementedError('not yet implemented in v4 driver')
<add>
<add> def ex_disable_ipv6_support(self, zone):
<add> raise NotImplementedError('not yet implemented in v4 driver')
<add>
<ide> def _to_zone(self, item):
<ide> return Zone(
<ide> id=item['id'], | 1 |
Javascript | Javascript | add sourcetype as a new mandatory option | 3aa453d975794faa38f21a78c232628c6f4233db | <ide><path>jest/preprocessor.js
<ide> module.exports = {
<ide> platform: '',
<ide> projectRoot: '',
<ide> retainLines: true,
<add> sourceType: 'unambiguous', // b7 required. detects module vs script mode
<ide> },
<ide> src,
<ide> plugins: [ | 1 |
PHP | PHP | add integration test for the caseexpression | 820f52289bef9e3c477df411e8fc1f6a58e24bc1 | <ide><path>tests/TestCase/Database/QueryTest.php
<ide> public function testDirectIsNull() {
<ide> $this->assertEquals(['name' => 'larry'], $results->fetch('assoc'));
<ide> }
<ide>
<add>/**
<add> * Tests that case statements work correctly for various use-cases.
<add> *
<add> * @return void
<add> */
<add> public function testSqlCaseStatement() {
<add> $query = new Query($this->connection);
<add> $publishedCase = $query
<add> ->newExpr()
<add> ->addCase($query
<add> ->newExpr()
<add> ->add(['published' => 'Y'])
<add> );
<add> $notPublishedCase = $query
<add> ->newExpr()
<add> ->addCase($query
<add> ->newExpr()
<add> ->add(['published' => 'N'])
<add> );
<add> $results = $query
<add> ->select([
<add> 'published' => $query->func()->sum($publishedCase),
<add> 'not_published' => $query->func()->sum($notPublishedCase)
<add> ])
<add> ->from(['comments'])
<add> ->execute()
<add> ->fetchAll('assoc');
<add>
<add> $this->assertEquals(5, $results[0]['published']);
<add> $this->assertEquals(1, $results[0]['not_published']);
<add>
<add> $query = new Query($this->connection);
<add> $query
<add> ->insert(['article_id', 'user_id', 'comment', 'published'])
<add> ->into('comments')
<add> ->values([
<add> 'article_id' => 2,
<add> 'user_id' => 1,
<add> 'comment' => 'In limbo',
<add> 'published' => 'L'
<add> ])
<add> ->execute();
<add>
<add> $query = new Query($this->connection);
<add> $conditions = [
<add> $query
<add> ->newExpr()
<add> ->add(['published' => 'Y']),
<add> $query
<add> ->newExpr()
<add> ->add(['published' => 'N'])
<add> ];
<add> $trueValues = [
<add> 'Published',
<add> 'Not published'
<add> ];
<add> $results = $query
<add> ->select([
<add> 'id',
<add> 'comment',
<add> 'status' => $query->newExpr()->addCase($conditions, $trueValues, 'None')
<add> ])
<add> ->from(['comments'])
<add> ->execute()
<add> ->fetchAll('assoc');
<add>
<add> $this->assertEquals('Published', $results[2]['status']);
<add> $this->assertEquals('Not published', $results[3]['status']);
<add> $this->assertEquals('None', $results[6]['status']);
<add> }
<add>
<ide> /**
<ide> * Assertion for comparing a table's contents with what is in it.
<ide> * | 1 |
Go | Go | limit the amount of prints during normal runs | bc7fa7b95773d638754eb72e7921ac328acb2ad6 | <ide><path>devmapper/deviceset_devmapper.go
<ide> package devmapper
<ide>
<ide> import (
<add> "github.com/dotcloud/docker/utils"
<ide> "encoding/json"
<ide> "fmt"
<ide> "io"
<ide> func (devices *DeviceSetDM) ensureImage(name string, size int64) (string, error)
<ide> }
<ide>
<ide> func (devices *DeviceSetDM) createPool(dataFile *os.File, metadataFile *os.File) error {
<del> log.Printf("Activating device-mapper pool %s", devices.getPoolName())
<add> utils.Debugf("Activating device-mapper pool %s", devices.getPoolName())
<ide> task, err := devices.createTask(DeviceCreate, devices.getPoolName())
<ide> if task == nil {
<ide> return err
<ide><path>image.go
<ide> func (image *Image) ensureImageDevice(devices DeviceSet) error {
<ide>
<ide> mounted, err := Mounted(mountDir)
<ide> if err == nil && mounted {
<del> log.Printf("Image %s is unexpectedly mounted, unmounting...", image.ID)
<add> utils.Debugf("Image %s is unexpectedly mounted, unmounting...", image.ID)
<ide> err = syscall.Unmount(mountDir, 0)
<ide> if err != nil {
<ide> return err
<ide> }
<ide> }
<ide>
<ide> if devices.HasDevice(image.ID) {
<del> log.Printf("Found non-initialized demove-mapper device for image %s, removing", image.ID)
<add> utils.Debugf("Found non-initialized demove-mapper device for image %s, removing", image.ID)
<ide> err = devices.RemoveDevice(image.ID)
<ide> if err != nil {
<ide> return err
<ide> }
<ide> }
<ide>
<del> log.Printf("Creating device-mapper device for image id %s", image.ID)
<del>
<add> utils.Debugf("Creating device-mapper device for image id %s", image.ID)
<ide> err = devices.AddDevice(image.ID, image.Parent)
<ide> if err != nil {
<ide> return err
<ide> }
<ide>
<del> utils.Debugf("Mounting device %s at %s for image setup", image.ID, mountDir)
<ide> err = devices.MountDevice(image.ID, mountDir)
<ide> if err != nil {
<ide> _ = devices.RemoveDevice(image.ID)
<ide> func (image *Image) ensureImageDevice(devices DeviceSet) error {
<ide> return err
<ide> }
<ide>
<del> utils.Debugf("Applying layer %s at %s", image.ID, mountDir)
<ide> err = image.applyLayer(layerPath(root), mountDir)
<ide> if err != nil {
<ide> _ = devices.RemoveDevice(image.ID)
<ide> return err
<ide> }
<ide>
<del> utils.Debugf("Unmounting %s", mountDir)
<ide> err = syscall.Unmount(mountDir, 0)
<ide> if err != nil {
<ide> _ = devices.RemoveDevice(image.ID)
<ide><path>runtime.go
<ide> func (runtime *Runtime) GetMountMethod() MountMethod {
<ide> if runtime.mountMethod == MountMethodNone {
<ide> // Try to automatically pick a method
<ide> if hasFilesystemSupport("aufs") {
<del> log.Printf("Using AUFS backend.")
<add> utils.Debugf("Using AUFS backend.")
<ide> runtime.mountMethod = MountMethodAUFS
<ide> } else {
<ide> _ = exec.Command("modprobe", "aufs").Run()
<ide> if hasFilesystemSupport("aufs") {
<del> log.Printf("Using AUFS backend.")
<add> utils.Debugf("Using AUFS backend.")
<ide> runtime.mountMethod = MountMethodAUFS
<ide> } else {
<del> log.Printf("Using device-mapper backend.")
<add> utils.Debugf("Using device-mapper backend.")
<ide> runtime.mountMethod = MountMethodDeviceMapper
<ide> }
<ide> } | 3 |
Javascript | Javascript | fix exceptions when running `grunt test --debug` | d76e3e1632d0748cdede1f4b0af89a37d00e0ae4 | <ide><path>src/renderers/dom/client/__tests__/ReactMount-test.js
<ide> describe('ReactMount', function() {
<ide> var WebComponents = WebComponents;
<ide>
<ide> try {
<del> if (WebComponents === undefined && jest !== undefined) {
<add> if (WebComponents === undefined && typeof jest !== 'undefined') {
<ide> WebComponents = require('WebComponents');
<ide> }
<ide> } catch(e) {
<ide><path>src/shared/vendor/third_party/webcomponents.js
<ide> CustomElements.addModule(function(scope) {
<ide> window.Platform = scope;
<ide> })(window.WebComponents);
<ide>
<del>module.exports = window.WebComponents;
<add>if (typeof exports !== 'undefined') {
<add> module.exports = window.WebComponents;
<add>} | 2 |
Text | Text | add changelog episode badge to readme | 68b8c09095ea129d20206d98b042b07209f1b641 | <ide><path>README.md
<ide> It is tiny (2kB) and has no dependencies.
<ide> [](https://www.npmjs.com/package/redux)
<ide> [](https://discord.gg/0ZcbPKXt5bZ6au5t)
<ide> [](https://webchat.freenode.net/)
<add>[](https://changelog.com/187)
<ide>
<ide> >**New! Learn Redux from its creator:
<ide> >[Getting Started with Redux](https://egghead.io/series/getting-started-with-redux) (30 free videos)** | 1 |
PHP | PHP | add container tests | 6bffe4eb623ec9235f4e290bb4a7c95dd25e4a76 | <ide><path>tests/Container/ContainerTest.php
<ide> public function testSharedConcreteResolution()
<ide> {
<ide> $container = new Container;
<ide> $container->singleton('ContainerConcreteStub');
<del> $bindings = $container->getBindings();
<ide>
<ide> $var1 = $container->make('ContainerConcreteStub');
<ide> $var2 = $container->make('ContainerConcreteStub');
<ide> public function testContainerTags()
<ide>
<ide> $this->assertEmpty($container->tagged('this_tag_does_not_exist'));
<ide> }
<add>
<add> public function testForgetInstanceForgetsInstance()
<add> {
<add> $container = new Container;
<add> $containerConcreteStub = new ContainerConcreteStub;
<add> $container->instance('ContainerConcreteStub', $containerConcreteStub);
<add> $this->assertTrue($container->isShared('ContainerConcreteStub'));
<add> $container->forgetInstance('ContainerConcreteStub');
<add> $this->assertFalse($container->isShared('ContainerConcreteStub'));
<add> }
<add>
<add> public function testForgetInstancesForgetsAllInstances()
<add> {
<add> $container = new Container;
<add> $containerConcreteStub1 = new ContainerConcreteStub;
<add> $containerConcreteStub2 = new ContainerConcreteStub;
<add> $containerConcreteStub3 = new ContainerConcreteStub;
<add> $container->instance('Instance1', $containerConcreteStub1);
<add> $container->instance('Instance2', $containerConcreteStub2);
<add> $container->instance('Instance3', $containerConcreteStub3);
<add> $this->assertTrue($container->isShared('Instance1'));
<add> $this->assertTrue($container->isShared('Instance2'));
<add> $this->assertTrue($container->isShared('Instance3'));
<add> $container->forgetInstances();
<add> $this->assertFalse($container->isShared('Instance1'));
<add> $this->assertFalse($container->isShared('Instance2'));
<add> $this->assertFalse($container->isShared('Instance3'));
<add> }
<ide> }
<ide>
<ide> class ContainerConcreteStub | 1 |
Javascript | Javascript | add flow typing to quickperformancelogger | bcfbdf4fbec1a05da151a2255f44a87b651965d6 | <ide><path>Libraries/Performance/QuickPerformanceLogger.js
<ide> * of patent rights can be found in the PATENTS file in the same directory.
<ide> *
<ide> * @providesModule QuickPerformanceLogger
<add> * @flow
<ide> */
<ide>
<ide> 'use strict';
<ide>
<del>var fixOpts = function(opts) {
<del> var AUTO_SET_TIMESTAMP = -1;
<del> var DUMMY_INSTANCE_KEY = 0;
<del> opts = opts || {};
<del> opts.instanceKey = opts.instanceKey || DUMMY_INSTANCE_KEY;
<del> opts.timestamp = opts.timestamp || AUTO_SET_TIMESTAMP;
<del> return opts;
<del>};
<add>const AUTO_SET_TIMESTAMP = -1;
<add>const DUMMY_INSTANCE_KEY = 0;
<ide>
<del>var QuickPerformanceLogger = {
<del> markerStart(markerId, opts) {
<del> if (typeof markerId !== 'number') {
<del> return;
<del> }
<add>const QuickPerformanceLogger = {
<add> markerStart(
<add> markerId: number,
<add> instanceKey: number = DUMMY_INSTANCE_KEY,
<add> timestamp: number = AUTO_SET_TIMESTAMP,
<add> ): void {
<ide> if (global.nativeQPLMarkerStart) {
<del> opts = fixOpts(opts);
<del> global.nativeQPLMarkerStart(markerId, opts.instanceKey, opts.timestamp);
<add> global.nativeQPLMarkerStart(markerId, instanceKey, timestamp);
<ide> }
<ide> },
<ide>
<del> markerEnd(markerId, actionId, opts) {
<del> if (typeof markerId !== 'number' || typeof actionId !== 'number') {
<del> return;
<del> }
<add> markerEnd(
<add> markerId: number,
<add> actionId: number,
<add> instanceKey: number = DUMMY_INSTANCE_KEY,
<add> timestamp: number = AUTO_SET_TIMESTAMP,
<add> ): void {
<ide> if (global.nativeQPLMarkerEnd) {
<del> opts = fixOpts(opts);
<del> global.nativeQPLMarkerEnd(markerId, opts.instanceKey, actionId, opts.timestamp);
<add> global.nativeQPLMarkerEnd(markerId, instanceKey, actionId, timestamp);
<ide> }
<ide> },
<ide>
<del> markerNote(markerId, actionId, opts) {
<del> if (typeof markerId !== 'number' || typeof actionId !== 'number') {
<del> return;
<del> }
<add> markerNote(
<add> markerId: number,
<add> actionId: number,
<add> instanceKey: number = DUMMY_INSTANCE_KEY,
<add> timestamp: number = AUTO_SET_TIMESTAMP,
<add> ): void {
<ide> if (global.nativeQPLMarkerNote) {
<del> opts = fixOpts(opts);
<del> global.nativeQPLMarkerNote(markerId, opts.instanceKey, actionId, opts.timestamp);
<add> global.nativeQPLMarkerNote(markerId, instanceKey, actionId, timestamp);
<ide> }
<ide> },
<ide>
<del> markerTag(markerId, tag, opts) {
<del> if (typeof markerId !== 'number' || typeof tag !== 'string') {
<del> return;
<del> }
<add> markerTag(
<add> markerId: number,
<add> tag: string,
<add> instanceKey: number = DUMMY_INSTANCE_KEY,
<add> ): void {
<ide> if (global.nativeQPLMarkerTag) {
<del> opts = fixOpts(opts);
<del> global.nativeQPLMarkerTag(markerId, opts.instanceKey, tag);
<add> global.nativeQPLMarkerTag(markerId, instanceKey, tag);
<ide> }
<ide> },
<ide>
<del> markerAnnotate(markerId, annotationKey, annotationValue, opts) {
<del> if (typeof markerId !== 'number' ||
<del> typeof annotationKey !== 'string' ||
<del> typeof annotationValue !== 'string') {
<del> return;
<del> }
<add> markerAnnotate(
<add> markerId: number,
<add> annotationKey: string,
<add> annotationValue: string,
<add> instanceKey: number = DUMMY_INSTANCE_KEY,
<add> ): void {
<ide> if (global.nativeQPLMarkerAnnotate) {
<del> opts = fixOpts(opts);
<del> global.nativeQPLMarkerAnnotate(markerId, opts.instanceKey, annotationKey, annotationValue);
<add> global.nativeQPLMarkerAnnotate(
<add> markerId,
<add> instanceKey,
<add> annotationKey,
<add> annotationValue,
<add> );
<ide> }
<ide> },
<ide>
<del> markerCancel(markerId, opts) {
<del> if (typeof markerId !== 'number') {
<del> return;
<del> }
<add> markerCancel(
<add> markerId: number,
<add> instanceKey?: number = DUMMY_INSTANCE_KEY,
<add> ): void {
<ide> if (global.nativeQPLMarkerCancel) {
<del> opts = fixOpts(opts);
<del> global.nativeQPLMarkerCancel(markerId, opts.instanceKey);
<add> global.nativeQPLMarkerCancel(markerId, instanceKey);
<ide> }
<ide> },
<ide>
<del> currentTimestamp() {
<add> currentTimestamp(): number {
<ide> if (global.nativeQPLTimestamp) {
<ide> return global.nativeQPLTimestamp();
<ide> } | 1 |
Go | Go | match manifest list resolution with containerd | 9adad264d2bf17bee8ec7b8a29d7112b3f503771 | <ide><path>distribution/pull_v2.go
<ide> func (p *puller) pullManifestList(ctx context.Context, ref reference.Named, mfst
<ide>
<ide> manifestMatches := filterManifests(mfstList.Manifests, platform)
<ide>
<del> if len(manifestMatches) == 0 {
<del> errMsg := fmt.Sprintf("no matching manifest for %s in the manifest list entries", formatPlatform(platform))
<del> logrus.Debugf(errMsg)
<del> return "", "", errors.New(errMsg)
<del> }
<del>
<del> if len(manifestMatches) > 1 {
<del> logrus.Debugf("found multiple matches in manifest list, choosing best match %s", manifestMatches[0].Digest.String())
<del> }
<del> match := manifestMatches[0]
<del>
<del> if err := checkImageCompatibility(match.Platform.OS, match.Platform.OSVersion); err != nil {
<del> return "", "", err
<del> }
<del>
<del> desc := specs.Descriptor{
<del> Digest: match.Digest,
<del> Size: match.Size,
<del> MediaType: match.MediaType,
<del> }
<del> manifest, err := p.manifestStore.Get(ctx, desc)
<del> if err != nil {
<del> return "", "", err
<del> }
<del>
<del> manifestRef, err := reference.WithDigest(reference.TrimNamed(ref), match.Digest)
<del> if err != nil {
<del> return "", "", err
<del> }
<del>
<del> switch v := manifest.(type) {
<del> case *schema1.SignedManifest:
<del> msg := fmt.Sprintf("[DEPRECATION NOTICE] v2 schema1 manifests in manifest lists are not supported and will break in a future release. Suggest author of %s to upgrade to v2 schema2. More information at https://docs.docker.com/registry/spec/deprecated-schema-v1/", ref)
<del> logrus.Warn(msg)
<del> progress.Message(p.config.ProgressOutput, "", msg)
<del>
<del> platform := toOCIPlatform(manifestMatches[0].Platform)
<del> id, _, err = p.pullSchema1(ctx, manifestRef, v, &platform)
<del> if err != nil {
<add> for _, match := range manifestMatches {
<add> if err := checkImageCompatibility(match.Platform.OS, match.Platform.OSVersion); err != nil {
<ide> return "", "", err
<ide> }
<del> case *schema2.DeserializedManifest:
<del> platform := toOCIPlatform(manifestMatches[0].Platform)
<del> id, _, err = p.pullSchema2(ctx, manifestRef, v, &platform)
<add>
<add> desc := specs.Descriptor{
<add> Digest: match.Digest,
<add> Size: match.Size,
<add> MediaType: match.MediaType,
<add> }
<add> manifest, err := p.manifestStore.Get(ctx, desc)
<ide> if err != nil {
<ide> return "", "", err
<ide> }
<del> case *ocischema.DeserializedManifest:
<del> platform := toOCIPlatform(manifestMatches[0].Platform)
<del> id, _, err = p.pullOCI(ctx, manifestRef, v, &platform)
<add>
<add> manifestRef, err := reference.WithDigest(reference.TrimNamed(ref), match.Digest)
<ide> if err != nil {
<ide> return "", "", err
<ide> }
<del> default:
<del> return "", "", errors.New("unsupported manifest format")
<del> }
<ide>
<del> return id, manifestListDigest, err
<add> switch v := manifest.(type) {
<add> case *schema1.SignedManifest:
<add> msg := fmt.Sprintf("[DEPRECATION NOTICE] v2 schema1 manifests in manifest lists are not supported and will break in a future release. Suggest author of %s to upgrade to v2 schema2. More information at https://docs.docker.com/registry/spec/deprecated-schema-v1/", ref)
<add> logrus.Warn(msg)
<add> progress.Message(p.config.ProgressOutput, "", msg)
<add>
<add> platform := toOCIPlatform(match.Platform)
<add> id, _, err = p.pullSchema1(ctx, manifestRef, v, platform)
<add> if err != nil {
<add> return "", "", err
<add> }
<add> case *schema2.DeserializedManifest:
<add> platform := toOCIPlatform(match.Platform)
<add> id, _, err = p.pullSchema2(ctx, manifestRef, v, platform)
<add> if err != nil {
<add> return "", "", err
<add> }
<add> case *ocischema.DeserializedManifest:
<add> platform := toOCIPlatform(match.Platform)
<add> id, _, err = p.pullOCI(ctx, manifestRef, v, platform)
<add> if err != nil {
<add> return "", "", err
<add> }
<add> case *manifestlist.DeserializedManifestList:
<add> id, _, err = p.pullManifestList(ctx, manifestRef, v, pp)
<add> if err != nil {
<add> var noMatches noMatchesErr
<add> if !errors.As(err, &noMatches) {
<add> // test the next match
<add> continue
<add> }
<add> }
<add> default:
<add> // OCI spec requires to skip unknown manifest types
<add> continue
<add> }
<add> return id, manifestListDigest, err
<add> }
<add> return "", "", noMatchesErr{platform: platform}
<ide> }
<ide>
<ide> const (
<ide> func (p *puller) pullSchema2Config(ctx context.Context, dgst digest.Digest) (con
<ide> return configJSON, nil
<ide> }
<ide>
<add>type noMatchesErr struct {
<add> platform specs.Platform
<add>}
<add>
<add>func (e noMatchesErr) Error() string {
<add> return fmt.Sprintf("no matching manifest for %s in the manifest list entries", formatPlatform(e.platform))
<add>}
<add>
<ide> func retry(ctx context.Context, maxAttempts int, sleep time.Duration, f func(ctx context.Context) error) (err error) {
<ide> attempt := 0
<ide> for ; attempt < maxAttempts; attempt++ {
<ide> func createDownloadFile() (*os.File, error) {
<ide> return os.CreateTemp("", "GetImageBlob")
<ide> }
<ide>
<del>func toOCIPlatform(p manifestlist.PlatformSpec) specs.Platform {
<del> return specs.Platform{
<add>func toOCIPlatform(p manifestlist.PlatformSpec) *specs.Platform {
<add> // distribution pkg does define platform as pointer so this hack for empty struct
<add> // is necessary. This is temporary until correct OCI image-spec package is used.
<add> if p.OS == "" && p.Architecture == "" && p.Variant == "" && p.OSVersion == "" && p.OSFeatures == nil && p.Features == nil {
<add> return nil
<add> }
<add> return &specs.Platform{
<ide> OS: p.OS,
<ide> Architecture: p.Architecture,
<ide> Variant: p.Variant,
<ide><path>distribution/pull_v2_unix.go
<ide> func filterManifests(manifests []manifestlist.ManifestDescriptor, p specs.Platfo
<ide> m := platforms.Only(p)
<ide> var matches []manifestlist.ManifestDescriptor
<ide> for _, desc := range manifests {
<del> if m.Match(toOCIPlatform(desc.Platform)) {
<add> descP := toOCIPlatform(desc.Platform)
<add> if descP == nil || m.Match(*descP) {
<ide> matches = append(matches, desc)
<del> logrus.Debugf("found match for %s with media type %s, digest %s", platforms.Format(p), desc.MediaType, desc.Digest.String())
<add> if descP != nil {
<add> logrus.Debugf("found match for %s with media type %s, digest %s", platforms.Format(p), desc.MediaType, desc.Digest.String())
<add> }
<ide> }
<ide> }
<ide>
<ide> sort.SliceStable(matches, func(i, j int) bool {
<del> return m.Less(toOCIPlatform(matches[i].Platform), toOCIPlatform(matches[j].Platform))
<add> p1 := toOCIPlatform(matches[i].Platform)
<add> if p1 == nil {
<add> return false
<add> }
<add> p2 := toOCIPlatform(matches[j].Platform)
<add> if p2 == nil {
<add> return true
<add> }
<add> return m.Less(*p1, *p2)
<ide> })
<ide>
<ide> // deprecated: backwards compatibility with older versions that didn't compare variant | 2 |
Javascript | Javascript | sanitize values bound to a[href] | 9532234bf1c408af9a6fd2c4743fdb585b920531 | <ide><path>src/ng/compile.js
<ide> function $CompileProvider($provide) {
<ide> Suffix = 'Directive',
<ide> COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\d\w\-_]+)\s+(.*)$/,
<ide> CLASS_DIRECTIVE_REGEXP = /(([\d\w\-_]+)(?:\:([^;]+))?;?)/,
<del> MULTI_ROOT_TEMPLATE_ERROR = 'Template must have exactly one root element. was: ';
<add> MULTI_ROOT_TEMPLATE_ERROR = 'Template must have exactly one root element. was: ',
<add> urlSanitizationWhitelist = /^\s*(https?|ftp|mailto):/;
<ide>
<ide>
<ide> /**
<ide> function $CompileProvider($provide) {
<ide> };
<ide>
<ide>
<add> /**
<add> * @ngdoc function
<add> * @name ng.$compileProvider#urlSanitizationWhitelist
<add> * @methodOf ng.$compileProvider
<add> * @function
<add> *
<add> * @description
<add> * Retrieves or overrides the default regular expression that is used for whitelisting of safe
<add> * urls during a[href] sanitization.
<add> *
<add> * The sanitization is a security measure aimed at prevent XSS attacks via html links.
<add> *
<add> * Any url about to be assigned to a[href] via data-binding is first normalized and turned into an
<add> * absolute url. Afterwards the url is matched against the `urlSanitizationWhitelist` regular
<add> * expression. If a match is found the original url is written into the dom. Otherwise the
<add> * absolute url is prefixed with `'unsafe:'` string and only then it is written into the DOM.
<add> *
<add> * @param {RegExp=} regexp New regexp to whitelist urls with.
<add> * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
<add> * chaining otherwise.
<add> */
<add> this.urlSanitizationWhitelist = function(regexp) {
<add> if (isDefined(regexp)) {
<add> urlSanitizationWhitelist = regexp;
<add> return this;
<add> }
<add> return urlSanitizationWhitelist;
<add> };
<add>
<add>
<ide> this.$get = [
<ide> '$injector', '$interpolate', '$exceptionHandler', '$http', '$templateCache', '$parse',
<del> '$controller', '$rootScope',
<add> '$controller', '$rootScope', '$document',
<ide> function($injector, $interpolate, $exceptionHandler, $http, $templateCache, $parse,
<del> $controller, $rootScope) {
<add> $controller, $rootScope, $document) {
<ide>
<ide> var Attributes = function(element, attr) {
<ide> this.$$element = element;
<ide> function $CompileProvider($provide) {
<ide> */
<ide> $set: function(key, value, writeAttr, attrName) {
<ide> var booleanKey = getBooleanAttrName(this.$$element[0], key),
<del> $$observers = this.$$observers;
<add> $$observers = this.$$observers,
<add> normalizedVal;
<ide>
<ide> if (booleanKey) {
<ide> this.$$element.prop(key, value);
<ide> function $CompileProvider($provide) {
<ide> }
<ide> }
<ide>
<add>
<add> // sanitize a[href] values
<add> if (nodeName_(this.$$element[0]) === 'A' && key === 'href') {
<add> urlSanitizationNode.setAttribute('href', value);
<add>
<add> // href property always returns normalized absolute url, so we can match against that
<add> normalizedVal = urlSanitizationNode.href;
<add> if (!normalizedVal.match(urlSanitizationWhitelist)) {
<add> this[key] = value = 'unsafe:' + normalizedVal;
<add> }
<add> }
<add>
<add>
<ide> if (writeAttr !== false) {
<ide> if (value === null || value === undefined) {
<ide> this.$$element.removeAttr(attrName);
<ide> function $CompileProvider($provide) {
<ide> }
<ide> };
<ide>
<del> var startSymbol = $interpolate.startSymbol(),
<add> var urlSanitizationNode = $document[0].createElement('a'),
<add> startSymbol = $interpolate.startSymbol(),
<ide> endSymbol = $interpolate.endSymbol(),
<ide> denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}')
<ide> ? identity
<ide> function $CompileProvider($provide) {
<ide> }
<ide> break;
<ide> }
<del>
<add>
<ide> case '=': {
<ide> parentGet = $parse(attrs[attrName]);
<ide> parentSet = parentGet.assign || function() {
<ide> function $CompileProvider($provide) {
<ide> function addAttrInterpolateDirective(node, directives, value, name) {
<ide> var interpolateFn = $interpolate(value, true);
<ide>
<del>
<ide> // no interpolation found -> ignore
<ide> if (!interpolateFn) return;
<ide>
<add>
<ide> directives.push({
<ide> priority: 100,
<ide> compile: valueFn(function attrInterpolateLinkFn(scope, element, attr) {
<ide><path>src/ng/directive/booleanAttrs.js
<ide> forEach(['src', 'href'], function(attrName) {
<ide>
<ide> // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
<ide> // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
<del> // to set the property as well to achieve the desired effect
<del> if (msie) element.prop(attrName, value);
<add> // to set the property as well to achieve the desired effect.
<add> // we use attr[attrName] value since $set can sanitize the url.
<add> if (msie) element.prop(attrName, attr[attrName]);
<ide> });
<ide> }
<ide> };
<ide><path>test/ng/compileSpec.js
<ide> describe('$compile', function() {
<ide> expect(jqLite(element.find('span')[1]).text()).toEqual('T:true');
<ide> });
<ide> });
<add> });
<add>
<add>
<add> describe('href sanitization', function() {
<add>
<add> it('should sanitize javascript: urls', inject(function($compile, $rootScope) {
<add> element = $compile('<a href="{{testUrl}}"></a>')($rootScope);
<add> $rootScope.testUrl = "javascript:doEvilStuff()";
<add> $rootScope.$apply();
<add>
<add> expect(element.attr('href')).toBe('unsafe:javascript:doEvilStuff()');
<add> }));
<add>
<add>
<add> it('should sanitize data: urls', inject(function($compile, $rootScope) {
<add> element = $compile('<a href="{{testUrl}}"></a>')($rootScope);
<add> $rootScope.testUrl = "data:evilPayload";
<add> $rootScope.$apply();
<add>
<add> expect(element.attr('href')).toBe('unsafe:data:evilPayload');
<add> }));
<add>
<add>
<add> it('should sanitize obfuscated javascript: urls', inject(function($compile, $rootScope) {
<add> element = $compile('<a href="{{testUrl}}"></a>')($rootScope);
<add>
<add> // case-sensitive
<add> $rootScope.testUrl = "JaVaScRiPt:doEvilStuff()";
<add> $rootScope.$apply();
<add> expect(element[0].href).toBe('unsafe:javascript:doEvilStuff()');
<add>
<add> // tab in protocol
<add> $rootScope.testUrl = "java\u0009script:doEvilStuff()";
<add> $rootScope.$apply();
<add> expect(element[0].href).toMatch(/(http:\/\/|unsafe:javascript:doEvilStuff\(\))/);
<add>
<add> // space before
<add> $rootScope.testUrl = " javascript:doEvilStuff()";
<add> $rootScope.$apply();
<add> expect(element[0].href).toBe('unsafe:javascript:doEvilStuff()');
<add>
<add> // ws chars before
<add> $rootScope.testUrl = " \u000e javascript:doEvilStuff()";
<add> $rootScope.$apply();
<add> expect(element[0].href).toMatch(/(http:\/\/|unsafe:javascript:doEvilStuff\(\))/);
<add>
<add> // post-fixed with proper url
<add> $rootScope.testUrl = "javascript:doEvilStuff(); http://make.me/look/good";
<add> $rootScope.$apply();
<add> expect(element[0].href).toBeOneOf(
<add> 'unsafe:javascript:doEvilStuff(); http://make.me/look/good',
<add> 'unsafe:javascript:doEvilStuff();%20http://make.me/look/good'
<add> );
<add> }));
<add>
<add>
<add> it('should sanitize ngHref bindings as well', inject(function($compile, $rootScope) {
<add> element = $compile('<a ng-href="{{testUrl}}"></a>')($rootScope);
<add> $rootScope.testUrl = "javascript:doEvilStuff()";
<add> $rootScope.$apply();
<add>
<add> expect(element[0].href).toBe('unsafe:javascript:doEvilStuff()');
<add> }));
<add>
<add>
<add> it('should not sanitize valid urls', inject(function($compile, $rootScope) {
<add> element = $compile('<a href="{{testUrl}}"></a>')($rootScope);
<add>
<add> $rootScope.testUrl = "foo/bar";
<add> $rootScope.$apply();
<add> expect(element.attr('href')).toBe('foo/bar');
<add>
<add> $rootScope.testUrl = "/foo/bar";
<add> $rootScope.$apply();
<add> expect(element.attr('href')).toBe('/foo/bar');
<add>
<add> $rootScope.testUrl = "../foo/bar";
<add> $rootScope.$apply();
<add> expect(element.attr('href')).toBe('../foo/bar');
<add>
<add> $rootScope.testUrl = "#foo";
<add> $rootScope.$apply();
<add> expect(element.attr('href')).toBe('#foo');
<ide>
<add> $rootScope.testUrl = "http://foo/bar";
<add> $rootScope.$apply();
<add> expect(element.attr('href')).toBe('http://foo/bar');
<ide>
<add> $rootScope.testUrl = " http://foo/bar";
<add> $rootScope.$apply();
<add> expect(element.attr('href')).toBe(' http://foo/bar');
<add>
<add> $rootScope.testUrl = "https://foo/bar";
<add> $rootScope.$apply();
<add> expect(element.attr('href')).toBe('https://foo/bar');
<add>
<add> $rootScope.testUrl = "ftp://foo/bar";
<add> $rootScope.$apply();
<add> expect(element.attr('href')).toBe('ftp://foo/bar');
<add>
<add> $rootScope.testUrl = "mailto:foo@bar.com";
<add> $rootScope.$apply();
<add> expect(element.attr('href')).toBe('mailto:foo@bar.com');
<add> }));
<add>
<add>
<add> it('should not sanitize href on elements other than anchor', inject(function($compile, $rootScope) {
<add> element = $compile('<div href="{{testUrl}}"></div>')($rootScope);
<add> $rootScope.testUrl = "javascript:doEvilStuff()";
<add> $rootScope.$apply();
<add>
<add> expect(element.attr('href')).toBe('javascript:doEvilStuff()');
<add> }));
<add>
<add>
<add> it('should not sanitize attributes other than href', inject(function($compile, $rootScope) {
<add> element = $compile('<a title="{{testUrl}}"></a>')($rootScope);
<add> $rootScope.testUrl = "javascript:doEvilStuff()";
<add> $rootScope.$apply();
<add>
<add> expect(element.attr('title')).toBe('javascript:doEvilStuff()');
<add> }));
<add>
<add>
<add> it('should allow reconfiguration of the href whitelist', function() {
<add> module(function($compileProvider) {
<add> expect($compileProvider.urlSanitizationWhitelist() instanceof RegExp).toBe(true);
<add> var returnVal = $compileProvider.urlSanitizationWhitelist(/javascript:/);
<add> expect(returnVal).toBe($compileProvider);
<add> });
<add>
<add> inject(function($compile, $rootScope) {
<add> element = $compile('<a href="{{testUrl}}"></a>')($rootScope);
<add>
<add> $rootScope.testUrl = "javascript:doEvilStuff()";
<add> $rootScope.$apply();
<add> expect(element.attr('href')).toBe('javascript:doEvilStuff()');
<add>
<add> $rootScope.testUrl = "http://recon/figured";
<add> $rootScope.$apply();
<add> expect(element.attr('href')).toBe('unsafe:http://recon/figured');
<add> });
<add> });
<ide> });
<ide> }); | 3 |
Python | Python | remove __all__ export | c2469b813556780bb6d1545d5ca5e48a0e2c4280 | <ide><path>spacy/language_data/punctuation.py
<ide> r'(?<=[{a}"])[:<>=/](?=[{a}])'.format(a=ALPHA)
<ide> ]
<ide> )
<del>
<del>
<del>__all__ = ["TOKENIZER_PREFIXES", "TOKENIZER_SUFFIXES", "TOKENIZER_INFIXES"] | 1 |
Go | Go | accept uppercase endpoint mode | 8a0c5f157892efdfd5119410adedf0f04c9c16cf | <ide><path>api/client/service/opts.go
<ide> func (e *endpointOptions) ToEndpointSpec() *swarm.EndpointSpec {
<ide> }
<ide>
<ide> return &swarm.EndpointSpec{
<del> Mode: swarm.ResolutionMode(e.mode),
<add> Mode: swarm.ResolutionMode(strings.ToLower(e.mode)),
<ide> Ports: portConfigs,
<ide> }
<ide> }
<ide> func addServiceFlags(cmd *cobra.Command, opts *serviceOptions) {
<ide> flags.DurationVar(&opts.update.delay, flagUpdateDelay, time.Duration(0), "Delay between updates")
<ide>
<ide> flags.StringSliceVar(&opts.networks, flagNetwork, []string{}, "Network attachments")
<del> flags.StringVar(&opts.endpoint.mode, flagEndpointMode, "", "Endpoint mode(Valid values: VIP, DNSRR)")
<add> flags.StringVar(&opts.endpoint.mode, flagEndpointMode, "", "Endpoint mode(Valid values: vip, dnsrr)")
<ide> flags.VarP(&opts.endpoint.ports, flagPublish, "p", "Publish a port as a node port")
<ide> }
<ide> | 1 |
PHP | PHP | apply fixes from styleci | fe1d67b0fbda54c78f3e1ee217a2fc36edd3c79c | <ide><path>tests/Auth/AuthTokenGuardTest.php
<ide> public function testUserCanBeRetrievedByQueryStringVariable()
<ide> $this->assertEquals(1, $guard->id());
<ide> }
<ide>
<del>
<ide> public function testTokenCanBeHashed()
<ide> {
<ide> $provider = m::mock(UserProvider::class); | 1 |
Javascript | Javascript | fix minor style issue | 6df176d3f014effff3436f514ab9f5a03e0e80b4 | <ide><path>examples/js/objects/Sky.js
<ide> THREE.Sky.SkyShader = {
<ide> "mieCoefficient": { value: 0.005 },
<ide> "mieDirectionalG": { value: 0.8 },
<ide> "sunPosition": { value: new THREE.Vector3() },
<del> "up": { value: new THREE.Vector3(0, 1, 0) }
<add> "up": { value: new THREE.Vector3( 0, 1, 0 ) }
<ide> },
<ide>
<ide> vertexShader: [
<ide><path>examples/jsm/objects/Sky.js
<ide> Sky.SkyShader = {
<ide> "mieCoefficient": { value: 0.005 },
<ide> "mieDirectionalG": { value: 0.8 },
<ide> "sunPosition": { value: new Vector3() },
<del> "up": { value: new Vector3(0, 1, 0) }
<add> "up": { value: new Vector3( 0, 1, 0 ) }
<ide> },
<ide>
<ide> vertexShader: [ | 2 |
Javascript | Javascript | change splice to pop in annotation tests | b157d8b4786e9435483368ae45cef2626d3ae9d0 | <ide><path>test/unit/annotation_spec.js
<ide> describe('annotation', function() {
<ide>
<ide> // Remove the last invalid flag for the next iteration.
<ide> if (!valid) {
<del> flags -= invalidFieldFlags.splice(-1, 1);
<add> flags -= invalidFieldFlags.pop();
<ide> }
<ide> });
<ide> }); | 1 |
PHP | PHP | update doc blocks for email to return $this | a41d646b8ac412a58a5be97b2f06e753f5db765c | <ide><path>src/Network/Email/Email.php
<ide> public function __construct($config = null) {
<ide> * @param string|array $email Null to get, String with email,
<ide> * Array with email as key, name as value or email as value (without name)
<ide> * @param string $name Name
<del> * @return array|\Cake\Network\Email\Email
<add> * @return array|$this
<ide> * @throws \Cake\Network\Error\SocketException
<ide> */
<ide> public function from($email = null, $name = null) {
<ide> public function from($email = null, $name = null) {
<ide> * @param string|array $email Null to get, String with email,
<ide> * Array with email as key, name as value or email as value (without name)
<ide> * @param string $name Name
<del> * @return array|\Cake\Network\Email\Email
<add> * @return array|$this
<ide> * @throws \Cake\Network\Error\SocketException
<ide> */
<ide> public function sender($email = null, $name = null) {
<ide> public function sender($email = null, $name = null) {
<ide> * @param string|array $email Null to get, String with email,
<ide> * Array with email as key, name as value or email as value (without name)
<ide> * @param string $name Name
<del> * @return array|\Cake\Network\Email\Email
<add> * @return array|$this
<ide> * @throws \Cake\Network\Error\SocketException
<ide> */
<ide> public function replyTo($email = null, $name = null) {
<ide> public function replyTo($email = null, $name = null) {
<ide> * @param string|array $email Null to get, String with email,
<ide> * Array with email as key, name as value or email as value (without name)
<ide> * @param string $name Name
<del> * @return array|\Cake\Network\Email\Email
<add> * @return array|$this
<ide> * @throws \Cake\Network\Error\SocketException
<ide> */
<ide> public function readReceipt($email = null, $name = null) {
<ide> public function readReceipt($email = null, $name = null) {
<ide> * @param string|array $email Null to get, String with email,
<ide> * Array with email as key, name as value or email as value (without name)
<ide> * @param string $name Name
<del> * @return array|\Cake\Network\Email\Email
<add> * @return array|$this
<ide> * @throws \Cake\Network\Error\SocketException
<ide> */
<ide> public function returnPath($email = null, $name = null) {
<ide> public function returnPath($email = null, $name = null) {
<ide> * @param string|array $email Null to get, String with email,
<ide> * Array with email as key, name as value or email as value (without name)
<ide> * @param string $name Name
<del> * @return array|\Cake\Network\Email\Email
<add> * @return array|$this
<ide> */
<ide> public function to($email = null, $name = null) {
<ide> if ($email === null) {
<ide> public function to($email = null, $name = null) {
<ide> * @param string|array $email Null to get, String with email,
<ide> * Array with email as key, name as value or email as value (without name)
<ide> * @param string $name Name
<del> * @return \Cake\Network\Email\Email $this
<add> * @return $this
<ide> */
<ide> public function addTo($email, $name = null) {
<ide> return $this->_addEmail('_to', $email, $name);
<ide> public function addTo($email, $name = null) {
<ide> * @param string|array $email Null to get, String with email,
<ide> * Array with email as key, name as value or email as value (without name)
<ide> * @param string $name Name
<del> * @return array|\Cake\Network\Email\Email
<add> * @return array|$this
<ide> */
<ide> public function cc($email = null, $name = null) {
<ide> if ($email === null) {
<ide> public function cc($email = null, $name = null) {
<ide> * @param string|array $email Null to get, String with email,
<ide> * Array with email as key, name as value or email as value (without name)
<ide> * @param string $name Name
<del> * @return \Cake\Network\Email\Email $this
<add> * @return $this
<ide> */
<ide> public function addCc($email, $name = null) {
<ide> return $this->_addEmail('_cc', $email, $name);
<ide> public function addCc($email, $name = null) {
<ide> * @param string|array $email Null to get, String with email,
<ide> * Array with email as key, name as value or email as value (without name)
<ide> * @param string $name Name
<del> * @return array|\Cake\Network\Email\Email
<add> * @return array|$this
<ide> */
<ide> public function bcc($email = null, $name = null) {
<ide> if ($email === null) {
<ide> public function bcc($email = null, $name = null) {
<ide> * @param string|array $email Null to get, String with email,
<ide> * Array with email as key, name as value or email as value (without name)
<ide> * @param string $name Name
<del> * @return \Cake\Network\Email\Email $this
<add> * @return $this
<ide> */
<ide> public function addBcc($email, $name = null) {
<ide> return $this->_addEmail('_bcc', $email, $name);
<ide> public function headerCharset($charset = null) {
<ide> * EmailPattern setter/getter
<ide> *
<ide> * @param string $regex for email address validation
<del> * @return string|\Cake\Network\Email\Email
<add> * @return string|$this
<ide> */
<ide> public function emailPattern($regex = null) {
<ide> if ($regex === null) {
<ide> public function emailPattern($regex = null) {
<ide> * @param string|array $email String with email,
<ide> * Array with email as key, name as value or email as value (without name)
<ide> * @param string $name Name
<del> * @return \Cake\Network\Email\Email $this
<add> * @return $this
<ide> * @throws \Cake\Network\Error\SocketException
<ide> */
<ide> protected function _setEmail($varName, $email, $name) {
<ide> protected function _validateEmail($email) {
<ide> * Array with email as key, name as value or email as value (without name)
<ide> * @param string $name Name
<ide> * @param string $throwMessage Exception message
<del> * @return \Cake\Network\Email\Email $this
<add> * @return $this
<ide> * @throws \Cake\Network\Error\SocketException
<ide> */
<ide> protected function _setEmailSingle($varName, $email, $name, $throwMessage) {
<ide> protected function _setEmailSingle($varName, $email, $name, $throwMessage) {
<ide> * @param string|array $email String with email,
<ide> * Array with email as key, name as value or email as value (without name)
<ide> * @param string $name Name
<del> * @return \Cake\Network\Email\Email $this
<add> * @return $this
<ide> * @throws \Cake\Network\Error\SocketException
<ide> */
<ide> protected function _addEmail($varName, $email, $name) {
<ide> protected function _addEmail($varName, $email, $name) {
<ide> * Get/Set Subject.
<ide> *
<ide> * @param string $subject Subject string.
<del> * @return string|\Cake\Network\Email\Email
<add> * @return string|$this
<ide> */
<ide> public function subject($subject = null) {
<ide> if ($subject === null) {
<ide> public function subject($subject = null) {
<ide> * Sets headers for the message
<ide> *
<ide> * @param array $headers Associative array containing headers to be set.
<del> * @return \Cake\Network\Email\Email $this
<add> * @return $this
<ide> * @throws \Cake\Network\Error\SocketException
<ide> */
<ide> public function setHeaders($headers) {
<ide> public function setHeaders($headers) {
<ide> * Add header for the message
<ide> *
<ide> * @param array $headers Headers to set.
<del> * @return object $this
<add> * @return $this
<ide> * @throws \Cake\Network\Error\SocketException
<ide> */
<ide> public function addHeaders($headers) {
<ide> protected function _formatAddress($address) {
<ide> *
<ide> * @param bool|string $template Template name or null to not use
<ide> * @param bool|string $layout Layout name or null to not use
<del> * @return array|\Cake\Network\Email\Email
<add> * @return array|$this
<ide> */
<ide> public function template($template = false, $layout = false) {
<ide> if ($template === false) {
<ide> public function template($template = false, $layout = false) {
<ide> * View class for render
<ide> *
<ide> * @param string $viewClass View class name.
<del> * @return string|\Cake\Network\Email\Email
<add> * @return string|$this
<ide> */
<ide> public function viewRender($viewClass = null) {
<ide> if ($viewClass === null) {
<ide> public function viewRender($viewClass = null) {
<ide> * Variables to be set on render
<ide> *
<ide> * @param array $viewVars Variables to set for view.
<del> * @return array|\Cake\Network\Email\Email
<add> * @return array|$this
<ide> */
<ide> public function viewVars($viewVars = null) {
<ide> if ($viewVars === null) {
<ide> public function viewVars($viewVars = null) {
<ide> * Theme to use when rendering
<ide> *
<ide> * @param string $theme Theme name.
<del> * @return string|\Cake\Network\Email\Email
<add> * @return string|$this
<ide> */
<ide> public function theme($theme = null) {
<ide> if ($theme === null) {
<ide> public function theme($theme = null) {
<ide> * Helpers to be used in render
<ide> *
<ide> * @param array $helpers Helpers list.
<del> * @return array|\Cake\Network\Email\Email
<add> * @return array|$this
<ide> */
<ide> public function helpers($helpers = null) {
<ide> if ($helpers === null) {
<ide> public function helpers($helpers = null) {
<ide> * Email format
<ide> *
<ide> * @param string $format Formatting string.
<del> * @return string|\Cake\Network\Email\Email
<add> * @return string|$this
<ide> * @throws \Cake\Network\Error\SocketException
<ide> */
<ide> public function emailFormat($format = null) {
<ide> public function emailFormat($format = null) {
<ide> *
<ide> * @param string|AbstractTransport $name Either the name of a configured
<ide> * transport, or a transport instance.
<del> * @return AbstractTransport|\Cake\Network\Email\Email
<add> * @return \Cake\Network\Email\AbstractTransport|$this
<ide> * @throws \Cake\Network\Error\SocketException When the chosen transport lacks a send method.
<ide> */
<ide> public function transport($name = null) {
<ide> public function transport($name = null) {
<ide> * Build a transport instance from configuration data.
<ide> *
<ide> * @param string $name The transport configuration name to build.
<del> * @return AbstractTransport
<add> * @return \Cake\Network\Email\AbstractTransport
<ide> * @throws \Cake\Error\Exception When transport configuration is missing or invalid.
<ide> */
<ide> protected function _constructTransport($name) {
<ide> protected function _constructTransport($name) {
<ide> * Message-ID
<ide> *
<ide> * @param bool|string $message True to generate a new Message-ID, False to ignore (not send in email), String to set as Message-ID
<del> * @return bool|string|\Cake\Network\Email\Email
<add> * @return bool|string|$this
<ide> * @throws \Cake\Network\Error\SocketException
<ide> */
<ide> public function messageId($message = null) {
<ide> public function messageId($message = null) {
<ide> * Domain as top level (the part after @)
<ide> *
<ide> * @param string $domain Manually set the domain for CLI mailing
<del> * @return string|\Cake\Network\Email\Email
<add> * @return string|$this
<ide> */
<ide> public function domain($domain = null) {
<ide> if ($domain === null) {
<ide> public function domain($domain = null) {
<ide> * attachment compatibility with outlook email clients.
<ide> *
<ide> * @param string|array $attachments String with the filename or array with filenames
<del> * @return array|\Cake\Network\Email\Email Either the array of attachments when getting or $this when setting.
<add> * @return array|$this Either the array of attachments when getting or $this when setting.
<ide> * @throws \Cake\Network\Error\SocketException
<ide> */
<ide> public function attachments($attachments = null) {
<ide> public function attachments($attachments = null) {
<ide> * Add attachments
<ide> *
<ide> * @param string|array $attachments String with the filename or array with filenames
<del> * @return \Cake\Network\Email\Email $this
<add> * @return $this
<ide> * @throws \Cake\Network\Error\SocketException
<ide> * @see \Cake\Network\Email\Email::attachments()
<ide> */
<ide> public static function dropTransport($key) {
<ide> *
<ide> * @param null|string|array $config String with configuration name, or
<ide> * an array with config or null to return current config.
<del> * @return string|array|\Cake\Network\Email\Email
<add> * @return string|array|$this
<ide> */
<ide> public function profile($config = null) {
<ide> if ($config === null) {
<ide> protected function _applyConfig($config) {
<ide> /**
<ide> * Reset all the internal variables to be able to send out a new email.
<ide> *
<del> * @return \Cake\Network\Email\Email $this
<add> * @return $this
<ide> */
<ide> public function reset() {
<ide> $this->_to = array(); | 1 |
Text | Text | add troubleshooting and modification for linux | e7378912427c9ebad42242f0fec04c83d3e72f5e | <ide><path>docs/GettingStarted.md
<ide> cd AwesomeProject
<ide> react-native run-android
<ide> ```
<ide>
<del><block class="windows android" />
<add><block class="windows linux android" />
<ide>
<ide> ### Troubleshooting Run
<ide>
<del>A common issue on Windows is that the packager is not started automatically when you run
<add>A common issue is that the packager is not started automatically when you run
<ide> `react-native run-android`. You can start it manually using:
<ide>
<ide> ```
<ide> cd AwesomeProject
<ide> react-native start
<ide> ```
<ide>
<add><block class="windows android" />
<add>
<ide> Or if you hit a `ERROR Watcher took too long to load` on Windows, try increasing the timeout in [this file](https://github.com/facebook/react-native/blob/5fa33f3d07f8595a188f6fe04d6168a6ede1e721/packager/react-packager/src/DependencyResolver/FileWatcher/index.js#L16) (under your `node_modules/react-native/`).
<ide>
<add><block class="windows linux android" />
<add>
<ide> ### Modifying Project
<ide>
<ide> Now that you successfully started the project, let's modify it:
<ide>
<del>- Press the `R` key twice **OR** open the menu (F2 by default, or ⌘-M in Genymotion) and select Reload JS to see your change!
<add>- Open `index.android.js` in your text editor of choice (e.g. [Nuclide](http://nuclide.io/docs/platforms/react-native/)) and edit some lines.
<add>- Press the `R` key twice **OR** open the menu (F2 by default, or ⌘-M in the emulator) and select Reload JS to see your change!
<ide> - Run `adb logcat *:S ReactNative:V ReactNativeJS:V` in a terminal to see your app's logs
<ide>
<ide> ### That's It | 1 |
Javascript | Javascript | remove streams forced optimization | 541119c6ee5dc8dca1115569dd640e4753dcce40 | <ide><path>benchmark/streams/readable-bigread.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<del>const v8 = require('v8');
<ide> const Readable = require('stream').Readable;
<ide>
<ide> const bench = common.createBenchmark(main, {
<ide> function main(conf) {
<ide> function noop() {}
<ide> s._read = noop;
<ide>
<del> // Force optimization before starting the benchmark
<del> s.push(b);
<del> v8.setFlagsFromString('--allow_natives_syntax');
<del> eval('%OptimizeFunctionOnNextCall(s.read)');
<del> s.push(b);
<del> while (s.read(128));
<del>
<ide> bench.start();
<ide> for (var k = 0; k < n; ++k) {
<ide> for (var i = 0; i < 1e4; ++i)
<ide><path>benchmark/streams/readable-bigunevenread.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<del>const v8 = require('v8');
<ide> const Readable = require('stream').Readable;
<ide>
<ide> const bench = common.createBenchmark(main, {
<ide> function main(conf) {
<ide> function noop() {}
<ide> s._read = noop;
<ide>
<del> // Force optimization before starting the benchmark
<del> s.push(b);
<del> v8.setFlagsFromString('--allow_natives_syntax');
<del> eval('%OptimizeFunctionOnNextCall(s.read)');
<del> s.push(b);
<del> while (s.read(106));
<del>
<ide> bench.start();
<ide> for (var k = 0; k < n; ++k) {
<ide> for (var i = 0; i < 1e4; ++i)
<ide><path>benchmark/streams/readable-boundaryread.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<del>const v8 = require('v8');
<ide> const Readable = require('stream').Readable;
<ide>
<ide> const bench = common.createBenchmark(main, {
<ide> function main(conf) {
<ide> function noop() {}
<ide> s._read = noop;
<ide>
<del> // Force optimization before starting the benchmark
<del> s.push(b);
<del> v8.setFlagsFromString('--allow_natives_syntax');
<del> eval('%OptimizeFunctionOnNextCall(s.push)');
<del> eval('%OptimizeFunctionOnNextCall(s.read)');
<del> s.push(b);
<del> while (s.read(32));
<del>
<ide> bench.start();
<ide> for (var k = 0; k < n; ++k) {
<ide> for (var i = 0; i < 1e4; ++i)
<ide><path>benchmark/streams/readable-readall.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<del>const v8 = require('v8');
<ide> const Readable = require('stream').Readable;
<ide>
<ide> const bench = common.createBenchmark(main, {
<ide> function main(conf) {
<ide> function noop() {}
<ide> s._read = noop;
<ide>
<del> // Force optimization before starting the benchmark
<del> s.push(b);
<del> v8.setFlagsFromString('--allow_natives_syntax');
<del> eval('%OptimizeFunctionOnNextCall(s.read)');
<del> s.push(b);
<del> while (s.read());
<del>
<ide> bench.start();
<ide> for (var k = 0; k < n; ++k) {
<ide> for (var i = 0; i < 1e4; ++i)
<ide><path>benchmark/streams/readable-unevenread.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<del>const v8 = require('v8');
<ide> const Readable = require('stream').Readable;
<ide>
<ide> const bench = common.createBenchmark(main, {
<ide> function main(conf) {
<ide> function noop() {}
<ide> s._read = noop;
<ide>
<del> // Force optimization before starting the benchmark
<del> s.push(b);
<del> v8.setFlagsFromString('--allow_natives_syntax');
<del> eval('%OptimizeFunctionOnNextCall(s.read)');
<del> s.push(b);
<del> while (s.read(12));
<del>
<ide> bench.start();
<ide> for (var k = 0; k < n; ++k) {
<ide> for (var i = 0; i < 1e4; ++i) | 5 |
Text | Text | add curl examples | 5b03de8287b04177c30815f5c798fe5c69e0d122 | <ide><path>docs/tutorial/2-requests-and-responses.md
<ide> Here is the view for an individual snippet.
<ide> snippet = Snippet.objects.get(pk=pk)
<ide> except Snippet.DoesNotExist:
<ide> return Response(status=status.HTTP_404_NOT_FOUND)
<del>
<add>
<ide> if request.method == 'GET':
<ide> serializer = SnippetSerializer(snippet)
<ide> return Response(serializer.data)
<del>
<add>
<ide> elif request.method == 'PUT':
<ide> serializer = SnippetSerializer(snippet, data=request.DATA)
<ide> if serializer.is_valid():
<ide> We don't necessarily need to add these extra url patterns in, but it gives us a
<ide>
<ide> Go ahead and test the API from the command line, as we did in [tutorial part 1][tut-1]. Everything is working pretty similarly, although we've got some nicer error handling if we send invalid requests.
<ide>
<del>**TODO: Describe using accept headers, content-type headers, and format suffixed URLs**
<add>We can get a list of all of the snippets, as before.
<add>
<add> curl http://127.0.0.1:8000/snippets/
<add>
<add> [{"id": 1, "title": "", "code": "foo = \"bar\"\n", "linenos": false, "language": "python", "style": "friendly"}, {"id": 2, "title": "", "code": "print \"hello, world\"\n", "linenos": false, "language": "python", "style": "friendly"}]
<add>
<add>We can control the format of the response that we get back, either by using the `Accept` header:
<add>
<add> curl http://127.0.0.1:8000/snippets/ -H 'Accept: application/json' # Request JSON
<add> curl http://127.0.0.1:8000/snippets/ -H 'Accept: text/html' # Request HTML
<add>
<add>Or by appending a format suffix:
<add>
<add> curl http://127.0.0.1:8000/snippets/.json # JSON suffix
<add> curl http://127.0.0.1:8000/snippets/.api # Browseable API suffix
<add>
<add>Similarly, we can control the format of the request that we send, using the `Content-Type` header.
<add>
<add> # POST using form data
<add> curl -X POST http://127.0.0.1:8000/snippets/ -d "code=print 123"
<add>
<add> {"id": 3, "title": "", "code": "123", "linenos": false, "language": "python", "style": "friendly"}
<add>
<add> # POST using JSON
<add> curl -X POST http://127.0.0.1:8000/snippets/ -d '{"code": "print 456"}' -H "Content-Type: application/json"
<add>
<add> {"id": 4, "title": "", "code": "print 456", "linenos": true, "language": "python", "style": "friendly"}
<ide>
<ide> Now go and open the API in a web browser, by visiting [http://127.0.0.1:8000/snippets/][devserver].
<ide>
<ide> ### Browsability
<ide>
<del>Because the API chooses a return format based on what the client asks for, it will, by default, return an HTML-formatted representation of the resource when that resource is requested by a browser. This allows for the API to be easily browsable and usable by humans.
<add>Because the API chooses the content type of the response based on the client request, it will, by default, return an HTML-formatted representation of the resource when that resource is requested by a web browser. This allows for the API to return a fully web-browsable HTML representation.
<add>
<add>Having a web-browseable API is a huge usability win, and makes developing and using your API much easier. It also dramatically lowers the barrier-to-entry for other developers wanting to inspect and work with your API.
<ide>
<ide> See the [browsable api][browseable-api] topic for more information about the browsable API feature and how to customize it.
<ide> | 1 |
Python | Python | add gabor filter | 424c2008473b00a8d3f31a9ad043526d95c31e69 | <ide><path>digital_image_processing/filters/gabor_filter.py
<add># Implementation of the Gaborfilter
<add># https://en.wikipedia.org/wiki/Gabor_filter
<add>import numpy as np
<add>from cv2 import COLOR_BGR2GRAY, CV_8UC3, cvtColor, filter2D, imread, imshow, waitKey
<add>
<add>
<add>def gabor_filter_kernel(
<add> ksize: int, sigma: int, theta: int, lambd: int, gamma: int, psi: int
<add>) -> np.ndarray:
<add> """
<add> :param ksize: The kernelsize of the convolutional filter (ksize x ksize)
<add> :param sigma: standard deviation of the gaussian bell curve
<add> :param theta: The orientation of the normal to the parallel stripes
<add> of Gabor function.
<add> :param lambd: Wavelength of the sinusoidal component.
<add> :param gamma: The spatial aspect ratio and specifies the ellipticity
<add> of the support of Gabor function.
<add> :param psi: The phase offset of the sinusoidal function.
<add>
<add> >>> gabor_filter_kernel(3, 8, 0, 10, 0, 0).tolist()
<add> [[0.8027212023735046, 1.0, 0.8027212023735046], [0.8027212023735046, 1.0, \
<add>0.8027212023735046], [0.8027212023735046, 1.0, 0.8027212023735046]]
<add>
<add> """
<add>
<add> # prepare kernel
<add> # the kernel size have to be odd
<add> if (ksize % 2) == 0:
<add> ksize = ksize + 1
<add> gabor = np.zeros((ksize, ksize), dtype=np.float32)
<add>
<add> # each value
<add> for y in range(ksize):
<add> for x in range(ksize):
<add> # distance from center
<add> px = x - ksize // 2
<add> py = y - ksize // 2
<add>
<add> # degree to radiant
<add> _theta = theta / 180 * np.pi
<add> cos_theta = np.cos(_theta)
<add> sin_theta = np.sin(_theta)
<add>
<add> # get kernel x
<add> _x = cos_theta * px + sin_theta * py
<add>
<add> # get kernel y
<add> _y = -sin_theta * px + cos_theta * py
<add>
<add> # fill kernel
<add> gabor[y, x] = np.exp(
<add> -(_x ** 2 + gamma ** 2 * _y ** 2) / (2 * sigma ** 2)
<add> ) * np.cos(2 * np.pi * _x / lambd + psi)
<add>
<add> return gabor
<add>
<add>
<add>if __name__ == "__main__":
<add> import doctest
<add>
<add> doctest.testmod()
<add> # read original image
<add> img = imread("../image_data/lena.jpg")
<add> # turn image in gray scale value
<add> gray = cvtColor(img, COLOR_BGR2GRAY)
<add>
<add> # Apply multiple Kernel to detect edges
<add> out = np.zeros(gray.shape[:2])
<add> for theta in [0, 30, 60, 90, 120, 150]:
<add> """
<add> ksize = 10
<add> sigma = 8
<add> lambd = 10
<add> gamma = 0
<add> psi = 0
<add> """
<add> kernel_10 = gabor_filter_kernel(10, 8, theta, 10, 0, 0)
<add> out += filter2D(gray, CV_8UC3, kernel_10)
<add> out = out / out.max() * 255
<add> out = out.astype(np.uint8)
<add>
<add> imshow("Original", gray)
<add> imshow("Gabor filter with 20x20 mask and 6 directions", out)
<add>
<add> waitKey(0) | 1 |
PHP | PHP | add deprecation warnings to routing features | 2a434091878143ef30b26c8ead1b91f0dfc44817 | <ide><path>src/Routing/RequestActionTrait.php
<ide> trait RequestActionTrait
<ide> */
<ide> public function requestAction($url, array $extra = [])
<ide> {
<add> deprecationWarning(
<add> 'RequestActionTrait::requestAction() is deprecated. ' .
<add> 'You should refactor to use View Cells or Components instead.'
<add> );
<ide> if (empty($url)) {
<ide> return false;
<ide> }
<ide><path>src/Routing/Route/Route.php
<ide> class Route
<ide> public function __construct($template, $defaults = [], array $options = [])
<ide> {
<ide> $this->template = $template;
<del> // @deprecated The `[method]` format should be removed in 4.0.0
<ide> if (isset($defaults['[method]'])) {
<add> deprecationWarning('The `[method]` option is deprecated. Use `_method` instead.');
<ide> $defaults['_method'] = $defaults['[method]'];
<ide> unset($defaults['[method]']);
<ide> }
<ide> public function __construct($template, $defaults = [], array $options = [])
<ide> */
<ide> public function extensions($extensions = null)
<ide> {
<add> deprecationWarning(
<add> 'Route::extensions() is deprecated. ' .
<add> 'Use Route::setExtensions()/getExtensions() instead.'
<add> );
<ide> if ($extensions === null) {
<ide> return $this->_extensions;
<ide> }
<ide> protected function _matchMethod($url)
<ide> }
<ide> // @deprecated The `[method]` support should be removed in 4.0.0
<ide> if (isset($url['[method]'])) {
<add> deprecationWarning('The `[method]` key is deprecated. Use `_method` instead.');
<ide> $url['_method'] = $url['[method]'];
<ide> }
<ide> if (empty($url['_method'])) {
<ide><path>src/Routing/RouteBuilder.php
<ide> public function __construct(RouteCollection $collection, $path, array $params =
<ide> */
<ide> public function routeClass($routeClass = null)
<ide> {
<add> deprecationWarning(
<add> 'RouteBuilder::routeClass() is deprecated. ' .
<add> 'Use RouteBuilder::setRouteClass()/getRouteClass() instead.'
<add> );
<ide> if ($routeClass === null) {
<ide> return $this->getRouteClass();
<ide> }
<ide> public function getRouteClass()
<ide> */
<ide> public function extensions($extensions = null)
<ide> {
<add> deprecationWarning(
<add> 'RouteBuilder::extensions() is deprecated. ' .
<add> 'Use RouteBuilder::setExtensions()/getExtensions() instead.'
<add> );
<ide> if ($extensions === null) {
<ide> return $this->getExtensions();
<ide> }
<ide><path>src/Routing/RouteCollection.php
<ide> public function named()
<ide> */
<ide> public function extensions($extensions = null, $merge = true)
<ide> {
<add> deprecationWarning(
<add> 'RouteCollection::extensions() is deprecated. ' .
<add> 'Use RouteCollection::setExtensions()/getExtensions() instead.'
<add> );
<ide> if ($extensions !== null) {
<ide> $this->setExtensions((array)$extensions, $merge);
<ide> }
<ide><path>src/Routing/Router.php
<ide> public static function connect($route, $defaults = [], $options = [])
<ide> */
<ide> public static function redirect($route, $url, $options = [])
<ide> {
<add> deprecationWarning(
<add> 'Router::redirect() is deprecated. ' .
<add> 'Use Router::scope() and RouteBuilder::redirect() instead.'
<add> );
<ide> if (is_string($url)) {
<ide> $url = ['redirect' => $url];
<ide> }
<ide> public static function redirect($route, $url, $options = [])
<ide> */
<ide> public static function mapResources($controller, $options = [])
<ide> {
<add> deprecationWarning(
<add> 'Router::mapResources() is deprecated. ' .
<add> 'Use Router::scope() and RouteBuilder::resources() instead.'
<add> );
<ide> foreach ((array)$controller as $name) {
<ide> list($plugin, $name) = pluginSplit($name);
<ide>
<ide> public static function mapResources($controller, $options = [])
<ide> */
<ide> public static function parse($url, $method = '')
<ide> {
<add> deprecationWarning(
<add> 'Router::parse() is deprecated. ' .
<add> 'Use Router::parseRequest() instead. This will require adopting the Http\Server library.'
<add> );
<ide> if (!static::$initialized) {
<ide> static::_loadRoutes();
<ide> }
<ide> public static function extensions($extensions = null, $merge = true)
<ide> */
<ide> public static function parseNamedParams(ServerRequest $request, array $options = [])
<ide> {
<add> deprecationWarning(
<add> 'Router::parseNamedParams() is deprecated. ' .
<add> '2.x backwards compatible named parameter support will be removed in 4.0'
<add> );
<ide> $options += ['separator' => ':'];
<ide> if (empty($request->params['pass'])) {
<ide> $request->params['named'] = []; | 5 |
PHP | PHP | make return type a bit more precise | 7affebd69bd212da4f7e0674b61c5df51d101b30 | <ide><path>src/Illuminate/Contracts/Broadcasting/ShouldBroadcast.php
<ide>
<ide> namespace Illuminate\Contracts\Broadcasting;
<ide>
<add>use Illuminate\Broadcasting\Channel;
<add>
<ide> interface ShouldBroadcast
<ide> {
<ide> /**
<ide> * Get the channels the event should broadcast on.
<ide> *
<del> * @return array
<add> * @return Channel|Channel[]
<ide> */
<ide> public function broadcastOn();
<ide> } | 1 |
Text | Text | add changes for 1.7.0 | fe600c03da9f62b071e1b4d426c288ced4869c30 | <ide><path>CHANGELOG.md
<add><a name="1.7.0"></a>
<add># 1.7.0 nonexistent-physiology (2018-05-09)
<add>
<add>**Here are the full changes for the release of 1.7.0 that are not already released in the 1.6.x branch,
<add>which includes commits from 1.7.0-rc.0 and commits from 1.7.0 directly.**
<add>
<add>1.7.0 is the last scheduled release of AngularJS that includes breaking changes. 1.7.x patch
<add>releases will continue to receive bug fixes and non-breaking features until AngularJS enters Long
<add>Term Support mode (LTS) on July 1st 2018.
<add>
<add>## Bug Fixes
<add>- **input:**
<add> - listen on "change" instead of "click" for radio/checkbox ngModels
<add> ([656c8f](https://github.com/angular/angular.js/commit/656c8fa8f23b1277cc5c214c4d0237f3393afa1e),
<add> [#4516](https://github.com/angular/angular.js/issues/4516),
<add> [#14667](https://github.com/angular/angular.js/issues/14667),
<add> [#14685](https://github.com/angular/angular.js/issues/14685))
<add>- **input\[number\]:** validate min/max against viewValue
<add> ([aa3f95](https://github.com/angular/angular.js/commit/aa3f951330ec7b10b43ea884d9b5754e296770ec),
<add> [#12761](https://github.com/angular/angular.js/issues/12761),
<add> [#16325](https://github.com/angular/angular.js/issues/16325))
<add>- **input\[date\]:** correctly parse 2-digit years
<add> ([627180](https://github.com/angular/angular.js/commit/627180fb71b92048d5b9ca2606b9eff1fd99387e),
<add> [#16537](https://github.com/angular/angular.js/issues/16537),
<add> [#16539](https://github.com/angular/angular.js/issues/16539))
<add>- **jqLite:** make removeData() not remove event handlers
<add> ([b7d396](https://github.com/angular/angular.js/commit/b7d396b8b6e8f27a1f4556d58fc903321e8d532a),
<add> [#15869](https://github.com/angular/angular.js/issues/15869),
<add> [#16512](https://github.com/angular/angular.js/issues/16512))
<add>- **$compile:**
<add> - remove the preAssignBindingsEnabled flag
<add> ([38f8c9](https://github.com/angular/angular.js/commit/38f8c97af74649ce224b6dd45f433cc665acfbfb),
<add> [#15782](https://github.com/angular/angular.js/issues/15782))
<add> - add `base[href]` to the list of RESOURCE_URL context attributes
<add> ([1cf728](https://github.com/angular/angular.js/commit/1cf728e209a9e0016068fac2769827e8f747760e),
<add> [#15597](https://github.com/angular/angular.js/issues/15597))
<add>- **$interval:** throw when trying to cancel non-$interval promise
<add> ([a8bef9](https://github.com/angular/angular.js/commit/a8bef95127775d83d80daa4617c33227c4b443d4),
<add> [#16424](https://github.com/angular/angular.js/issues/16424),
<add> [#16476](https://github.com/angular/angular.js/issues/16476))
<add>- **$timeout:** throw when trying to cancel non-$timeout promise
<add> ([336525](https://github.com/angular/angular.js/commit/3365256502344970f86355d3ace1cb4251ae9828),
<add> [#16424](https://github.com/angular/angular.js/issues/16424),
<add> [#16476](https://github.com/angular/angular.js/issues/16476))
<add>- **$cookies:** remove the deprecated $cookieStore factory
<add> ([73c646](https://github.com/angular/angular.js/commit/73c6467f1468353215dc689c019ed83aa4993c77),
<add> [#16465](https://github.com/angular/angular.js/issues/16465))
<add>- **$resource:** fix interceptors and success/error callbacks
<add> ([ea0585](https://github.com/angular/angular.js/commit/ea0585773bb93fd891576e2271254a17e15f1ddd),
<add> [#6731](https://github.com/angular/angular.js/issues/6731),
<add> [#9334](https://github.com/angular/angular.js/issues/9334),
<add> [#6865](https://github.com/angular/angular.js/issues/6865),
<add> [#16446](https://github.com/angular/angular.js/issues/16446))
<add>- **$templateRequest:**
<add> - give tpload error the correct namespace
<add> ([c617d6](https://github.com/angular/angular.js/commit/c617d6dceee5b000bfceda44ced22fc16b48b18b))
<add> - always return the template that is stored in the cache
<add> ([fb0099](https://github.com/angular/angular.js/commit/fb00991460cf69ae8bc7f1f826363d09c73c0d5e),
<add> [#16225](https://github.com/angular/angular.js/issues/16225))
<add>- **$animate:** let cancel() reject the runner promise
<add> ([16b82c](https://github.com/angular/angular.js/commit/16b82c6afe0ab916fef1d6ca78053b00bf5ada83),
<add> [#14204](https://github.com/angular/angular.js/issues/14204),
<add> [#16373](https://github.com/angular/angular.js/issues/16373))
<add>- **ngTouch:**
<add> - deprecate the module and its contents
<add> ([67f54b](https://github.com/angular/angular.js/commit/67f54b660038de2b4346b3e76d66a8dc8ccb1f9b),
<add> [#16427](https://github.com/angular/angular.js/issues/16427),
<add> [#16431](https://github.com/angular/angular.js/issues/16431))
<add> - remove ngClick override, `$touchProvider`, and `$touch`
<add> ([11d9ad](https://github.com/angular/angular.js/commit/11d9ad1eb25eaf5967195e424108207427835d50),
<add> [#15761](https://github.com/angular/angular.js/issues/15761),
<add> [#15755](https://github.com/angular/angular.js/issues/15755))
<add>- **ngScenario:** completely remove the angular scenario runner
<add> ([0cd392](https://github.com/angular/angular.js/commit/0cd39217828b0ad53eaf731576af17d66c18ff60),
<add> [#9405](https://github.com/angular/angular.js/issues/9405))
<add>- **form:** set $submitted to true on child forms when parent is submitted
<add> ([223de5](https://github.com/angular/angular.js/commit/223de59e988dc0cc8b4ec3a045b7c0735eba1c77),
<add> [#10071](https://github.com/angular/angular.js/issues/10071))
<add>- **$rootScope:**
<add> - provide correct value of one-time bindings in watchGroup
<add> ([c2b8fa](https://github.com/angular/angular.js/commit/c2b8fab0a480204374d561d6b9b3d47347ac5570))
<add> - don't allow explicit digest calls to affect $evalAsync
<add> ([02c046](https://github.com/angular/angular.js/commit/02c04690da16a9bef55694f5db0b8368dc0125c9),
<add> [#15127](https://github.com/angular/angular.js/issues/15127),
<add> [#15494](https://github.com/angular/angular.js/issues/15494))
<add>- **ngAria:** do not set aria attributes on input[type="hidden"]
<add> ([6d5ef3](https://github.com/angular/angular.js/commit/6d5ef34fc6a974cde73157ba94f9706723dd8f5b),
<add> [#15113](https://github.com/angular/angular.js/issues/15113),
<add> [#16367](https://github.com/angular/angular.js/issues/16367))
<add>- **ngModel, input:** improve handling of built-in named parsers
<add> ([74b04c](https://github.com/angular/angular.js/commit/74b04c9403af4fc7df5b6420f22c9f45a3e84140),
<add> [#14292](https://github.com/angular/angular.js/issues/14292),
<add> [#10076](https://github.com/angular/angular.js/issues/10076),
<add> [#16347](https://github.com/angular/angular.js/issues/16347))
<add>- **$httpParamSerializerJQLike:**
<add> - call functions as jQuery does
<add> ([a784fa](https://github.com/angular/angular.js/commit/a784fab605d825f1158c6292b3c42f8c4a502fdf),
<add> [#16138](https://github.com/angular/angular.js/issues/16138),
<add> [#16139](https://github.com/angular/angular.js/issues/16139))
<add> - follow jQuery for `null` and `undefined`
<add> ([301fdd](https://github.com/angular/angular.js/commit/301fdda648680d89ccab607c413a7ddede7b0165))
<add>- **$parse:**
<add> - do not pass scope/locals to interceptors of one-time bindings
<add> ([87a586](https://github.com/angular/angular.js/commit/87a586eb9a23cfd0d0bb681cc778b4b8e5c8451d))
<add> - always pass the intercepted value to watchers
<add> ([2ee503](https://github.com/angular/angular.js/commit/2ee5033967d5f87a516bad137686b0592e25d26b),
<add> [#16021](https://github.com/angular/angular.js/issues/16021))
<add> - respect the interceptor.$stateful flag
<add> ([de7403](https://github.com/angular/angular.js/commit/de74034ddf6f92505ccdb61be413a6df2c723f87))
<add>- **Angular:** remove `angular.lowercase` and `angular.uppercase`
<add> ([1daa4f](https://github.com/angular/angular.js/commit/1daa4f2231a89ee88345689f001805ffffa9e7de),
<add> [#15445](https://github.com/angular/angular.js/issues/15445))
<add>- **$controller:** remove instantiating controllers defined on window
<add> ([e269c1](https://github.com/angular/angular.js/commit/e269c14425a3209040f65c022658770e00a36f16),
<add> [#15349](https://github.com/angular/angular.js/issues/15349),
<add> [#15762](https://github.com/angular/angular.js/issues/15762))
<add>
<add>
<add>## New Features
<add>- **angular.isArray:** support Array subclasses in `angular.isArray()`
<add> ([e3ece2](https://github.com/angular/angular.js/commit/e3ece2fad9e1e6d47b5f06815ff186d7e6f44948),
<add> [#15533](https://github.com/angular/angular.js/issues/15533),
<add> [#15541](https://github.com/angular/angular.js/issues/15541))
<add>- **$sce:** handle URL sanitization through the `$sce` service
<add> ([1e9ead](https://github.com/angular/angular.js/commit/1e9eadcd72dbbd5c67dae8328a63e535cfa91ff9))
<add>- **orderBy:** consider `null` and `undefined` greater than other values
<add> ([1d8046](https://github.com/angular/angular.js/commit/1d804645f7656d592c90216a0355b4948807f6b8),
<add> [#15294](https://github.com/angular/angular.js/issues/15294),
<add> [#16376](https://github.com/angular/angular.js/issues/16376))
<add>- **$resource:** add support for `request` and `requestError` interceptors (#15674)
<add> ([240a3d](https://github.com/angular/angular.js/commit/240a3ddbf12a9bb79754031be95dae4b6bd2dded),
<add> [#5146](https://github.com/angular/angular.js/issues/5146))
<add>- **ngModelOptions:** add debounce catch-all + allow debouncing 'default' only
<add> ([55ba44](https://github.com/angular/angular.js/commit/55ba44913e02650b56410aa9ab5eeea5d3492b68),
<add> [#15411](https://github.com/angular/angular.js/issues/15411),
<add> [#16335](https://github.com/angular/angular.js/issues/16335))
<add>- **$compile:** lower the `xlink:href` security context for SVG's `a` and `image` elements
<add> ([6ccbfa](https://github.com/angular/angular.js/commit/6ccbfa65d60a3dc396d0cf6da21b993ad74653fd),
<add> [#15736](https://github.com/angular/angular.js/issues/15736))
<add>
<add>
<add>## Performance Improvements
<add>- **$rootScope:** allow $watchCollection use of expression input watching
<add> ([97b00c](https://github.com/angular/angular.js/commit/97b00ca497676aaff8a803762a9f8c7ff4aa24dd))
<add>- **ngStyle:** use $watchCollection
<add> ([15bbd3](https://github.com/angular/angular.js/commit/15bbd3e18cd89b91f7206a06c73d40e54a8a48a0),
<add> [#15947](https://github.com/angular/angular.js/issues/15947))
<add>- **$compile:** do not use deepWatch in literal one-way bindings
<add> ([fd4f01](https://github.com/angular/angular.js/commit/fd4f0111188b62773b99ab6eab38b4d2b5d8d727),
<add> [#15301](https://github.com/angular/angular.js/issues/15301))
<add>
<add>
<add>
<add>
<add>## Breaking Changes
<add>
<add>### **jqLite** due to:
<add> - **[b7d396](https://github.com/angular/angular.js/commit/b7d396b8b6e8f27a1f4556d58fc903321e8d532a)**: make removeData() not remove event handlers
<add>
<add>Before this commit `removeData()` invoked on an element removed its event
<add>handlers as well. If you want to trigger a full cleanup of an element, change:
<add>
<add>```js
<add>elem.removeData();
<add>```
<add>
<add>to:
<add>
<add>```js
<add>angular.element.cleanData(elem);
<add>```
<add>
<add>In most cases, though, cleaning up after an element is supposed to be done
<add>only when it's removed from the DOM as well; in such cases the following:
<add>
<add>```js
<add>elem.remove();
<add>```
<add>
<add>will remove event handlers as well.
<add>
<add>### **$cookies** due to:
<add> - **[73c646](https://github.com/angular/angular.js/commit/73c6467f1468353215dc689c019ed83aa4993c77)**: remove the deprecated $cookieStore factory
<add>
<add>The $cookieStore has been removed. Migrate to the $cookies service. Note that
<add>for object values you need to use the `putObject` & `getObject` methods as
<add>`get`/`put` will not correctly save/retrieve them.
<add>
<add>Before:
<add>```js
<add>$cookieStore.put('name', {key: 'value'});
<add>$cookieStore.get('name'); // {key: 'value'}
<add>$cookieStore.remove('name');
<add>```
<add>
<add>After:
<add>```js
<add>$cookies.putObject('name', {key: 'value'});
<add>$cookies.getObject('name'); // {key: 'value'}
<add>$cookies.remove('name');
<add>```
<add>
<add>### **$resource** due to:
<add> - **[ea0585](https://github.com/angular/angular.js/commit/ea0585773bb93fd891576e2271254a17e15f1ddd)**: fix interceptors and success/error callbacks
<add>
<add>If you are not using `success` or `error` callbacks with `$resource`,
<add>your app should not be affected by this change.
<add>
<add>If you are using `success` or `error` callbacks (with or without
<add>response interceptors), one (subtle) difference is that throwing an
<add>error inside the callbacks will not propagate to the returned
<add>`$promise`. Therefore, you should try to use the promises whenever
<add>possible. E.g.:
<add>
<add>```js
<add>// Avoid
<add>User.query(function onSuccess(users) { throw new Error(); }).
<add> $promise.
<add> catch(function onError() { /* Will not be called. */ });
<add>
<add>// Prefer
<add>User.query().
<add> $promise.
<add> then(function onSuccess(users) { throw new Error(); }).
<add> catch(function onError() { /* Will be called. */ });
<add>```
<add>
<add>Finally, if you are using `success` or `error` callbacks with response
<add>interceptors, the callbacks will now always run _after_ the interceptors
<add>(and wait for them to resolve in case they return a promise).
<add>Previously, the `error` callback was called before the `responseError`
<add>interceptor and the `success` callback was synchronously called after
<add>the `response` interceptor. E.g.:
<add>
<add>```js
<add>var User = $resource('/api/users/:id', {id: '@id'}, {
<add> get: {
<add> method: 'get',
<add> interceptor: {
<add> response: function(response) {
<add> console.log('responseInterceptor-1');
<add> return $timeout(1000).then(function() {
<add> console.log('responseInterceptor-2');
<add> return response.resource;
<add> });
<add> },
<add> responseError: function(response) {
<add> console.log('responseErrorInterceptor-1');
<add> return $timeout(1000).then(function() {
<add> console.log('responseErrorInterceptor-2');
<add> return $q.reject('Ooops!');
<add> });
<add> }
<add> }
<add> }
<add>});
<add>var onSuccess = function(value) { console.log('successCallback', value); };
<add>var onError = function(error) { console.log('errorCallback', error); };
<add>
<add>// Assuming the following call is successful...
<add>User.get({id: 1}, onSuccess, onError);
<add> // Old behavior:
<add> // responseInterceptor-1
<add> // successCallback, {/* Promise object */}
<add> // responseInterceptor-2
<add> // New behavior:
<add> // responseInterceptor-1
<add> // responseInterceptor-2
<add> // successCallback, {/* User object */}
<add>
<add>// Assuming the following call returns an error...
<add>User.get({id: 2}, onSuccess, onError);
<add> // Old behavior:
<add> // errorCallback, {/* Response object */}
<add> // responseErrorInterceptor-1
<add> // responseErrorInterceptor-2
<add> // New behavior:
<add> // responseErrorInterceptor-1
<add> // responseErrorInterceptor-2
<add> // errorCallback, Ooops!
<add>```
<add>
<add> - **[240a3d](https://github.com/angular/angular.js/commit/240a3ddbf12a9bb79754031be95dae4b6bd2dded)**: add support for `request` and `requestError` interceptors (#15674)
<add>
<add>Previously, calling a `$resource` method would synchronously call
<add>`$http`. Now, it will be called asynchronously (regardless if a
<add>`request`/`requestError` interceptor has been defined.
<add>
<add>This is not expected to affect applications at runtime, since the
<add>overall operation is asynchronous already, but may affect assertions in
<add>tests. For example, if you want to assert that `$http` has been called
<add>with specific arguments as a result of a `$resource` call, you now need
<add>to run a `$digest` first, to ensure the (possibly empty) request
<add>interceptor promise has been resolved.
<add>
<add>Before:
<add>```js
<add>it('...', function() {
<add> $httpBackend.expectGET('/api/things').respond(...);
<add> var Things = $resource('/api/things');
<add> Things.query();
<add>
<add> expect($http).toHaveBeenCalledWith(...);
<add>});
<add>```
<add>
<add>After:
<add>```js
<add>it('...', function() {
<add> $httpBackend.expectGET('/api/things').respond(...);
<add> var Things = $resource('/api/things');
<add> Things.query();
<add> $rootScope.$digest();
<add>
<add> expect($http).toHaveBeenCalledWith(...);
<add>});
<add>```
<add>
<add>### **$templateRequest**:
<add> - due to **[c617d6](https://github.com/angular/angular.js/commit/c617d6dceee5b000bfceda44ced22fc16b48b18b)**: give tpload error the correct namespace
<add>
<add>Previously the `tpload` error was namespaced to `$compile`. If you have
<add>code that matches errors of the form `[$compile:tpload]` it will no
<add>longer run. You should change the code to match
<add>`[$templateRequest:tpload]`.
<add>
<add> - due to **([fb0099](https://github.com/angular/angular.js/commit/fb00991460cf69ae8bc7f1f826363d09c73c0d5e)**: always return the template that is stored in the cache
<add>
<add>The service now returns the result of `$templateCache.put()` when making a server request to the
<add>template. Previously it would return the content of the response directly.
<add>This now means if you are decorating `$templateCache.put()` to manipulate the template, you will
<add>now get this manipulated result also on the first `$templateRequest` rather than only on subsequent
<add>calls (when the template is retrived from the cache).
<add>In practice this should not affect any apps, as it is unlikely that they rely on the template being
<add>different in the first and subsequent calls.
<add>
<add>### **$animate** due to:
<add> - **[16b82c](https://github.com/angular/angular.js/commit/16b82c6afe0ab916fef1d6ca78053b00bf5ada83)**: let cancel() reject the runner promise
<add>
<add>$animate.cancel(runner) now rejects the underlying
<add>promise and calls the catch() handler on the runner
<add>returned by $animate functions (enter, leave, move,
<add>addClass, removeClass, setClass, animate).
<add>Previously it would resolve the promise as if the animation
<add>had ended successfully.
<add>
<add>Example:
<add>
<add>```js
<add>var runner = $animate.addClass('red');
<add>runner.then(function() { console.log('success')});
<add>runner.catch(function() { console.log('cancelled')});
<add>
<add>runner.cancel();
<add>```
<add>
<add>Pre-1.7.0, this logs 'success', 1.7.0 and later it logs 'cancelled'.
<add>To migrate, add a catch() handler to your animation runners.
<add>
<add>### **angular.isArray** due to:
<add> - **[e3ece2](https://github.com/angular/angular.js/commit/e3ece2fad9e1e6d47b5f06815ff186d7e6f44948)**: support Array subclasses in `angular.isArray()`
<add>
<add>Previously, `angular.isArray()` was an alias for `Array.isArray()`.
<add>Therefore, objects that prototypally inherit from `Array` where not
<add>considered arrays. Now such objects are considered arrays too.
<add>
<add>This change affects several other methods that use `angular.isArray()`
<add>under the hood, such as `angular.copy()`, `angular.equals()`,
<add>`angular.forEach()`, and `angular.merge()`.
<add>
<add>This in turn affects how dirty checking treats objects that prototypally
<add>inherit from `Array` (e.g. MobX observable arrays). AngularJS will now
<add>be able to handle these objects better when copying or watching.
<add>
<add>### **$sce** due to:
<add> - **[1e9ead](https://github.com/angular/angular.js/commit/1e9eadcd72dbbd5c67dae8328a63e535cfa91ff9)**: handle URL sanitization through the `$sce` service
<add>
<add>If you use `attrs.$set` for URL attributes (a[href] and img[src]) there will no
<add>longer be any automated sanitization of the value. This is in line with other
<add>programmatic operations, such as writing to the innerHTML of an element.
<add>
<add>If you are programmatically writing URL values to attributes from untrusted
<add>input then you must sanitize it yourself. You could write your own sanitizer or copy
<add>the private `$$sanitizeUri` service.
<add>
<add>Note that values that have been passed through the `$interpolate` service within the
<add>`URL` or `MEDIA_URL` will have already been sanitized, so you would not need to sanitize
<add>these values again.
<add>
<add>### **orderBy** due to:
<add> - **[1d8046](https://github.com/angular/angular.js/commit/1d804645f7656d592c90216a0355b4948807f6b8)**: consider `null` and `undefined` greater than other values
<add>
<add>When using `orderBy` to sort arrays containing `null` values, the `null` values
<add>will be considered "greater than" all other values, except for `undefined`.
<add>Previously, they were sorted as strings. This will result in different (but more
<add>intuitive) sorting order.
<add>
<add>Before:
<add>```js
<add>orderByFilter(['a', undefined, 'o', null, 'z']);
<add>//--> 'a', null, 'o', 'z', undefined
<add>```
<add>
<add>After:
<add>```js
<add>orderByFilter(['a', undefined, 'o', null, 'z']);
<add>//--> 'a', 'o', 'z', null, undefined
<add>```
<add>
<add>### **ngScenario** due to:
<add> - **[0cd392](https://github.com/angular/angular.js/commit/0cd39217828b0ad53eaf731576af17d66c18ff60)**: completely remove the angular scenario runner
<add>
<add>The angular scenario runner end-to-end test framework has been
<add>removed from the project and will no longer be available on npm
<add>or bower starting with 1.7.0.
<add>It was deprecated and removed from the documentation in 2014.
<add>Applications that still use it should migrate to
<add>[Protractor](http://www.protractortest.org).
<add>Technically, it should also be possible to continue using an
<add>older version of the scenario runner, as the underlying APIs have
<add>not changed. However, we do not guarantee future compatibility.
<add>
<add>### **form** due to:
<add> - **[223de5](https://github.com/angular/angular.js/commit/223de59e988dc0cc8b4ec3a045b7c0735eba1c77)**: set $submitted to true on child forms when parent is submitted
<add>
<add>Forms will now set $submitted on child forms when they are submitted.
<add>For example:
<add>```
<add><form name="parentform" ng-submit="$ctrl.submit()">
<add> <ng-form name="childform">
<add> <input type="text" name="input" ng-model="my.model" />
<add> </ng-form>
<add> <input type="submit" />
<add></form>
<add>```
<add>
<add>Submitting this form will set $submitted on "parentform" and "childform".
<add>Previously, it was only set on "parentform".
<add>
<add>This change was introduced because mixing form and ngForm does not create
<add>logically separate forms, but rather something like input groups.
<add>Therefore, child forms should inherit the submission state from their parent form.
<add>
<add>### **ngAria** due to:
<add> - **[6d5ef3](https://github.com/angular/angular.js/commit/6d5ef34fc6a974cde73157ba94f9706723dd8f5b)**: do not set aria attributes on input[type="hidden"]
<add>
<add>ngAria no longer sets aria-* attributes on input[type="hidden"] with ngModel.
<add>This can affect apps that test for the presence of aria attributes on hidden inputs.
<add>To migrate, remove these assertions.
<add>In actual apps, this should not have a user-facing effect, as the previous behavior
<add>was incorrect, and the new behavior is correct for accessibility.
<add>
<add>### **ngModel, input** due to:
<add> - **[74b04c](https://github.com/angular/angular.js/commit/74b04c9403af4fc7df5b6420f22c9f45a3e84140)**: improve handling of built-in named parsers
<add>
<add>*Custom* parsers that fail to parse on input types "email", "url", "number", "date", "month",
<add>"time", "datetime-local", "week", do no longer set `ngModelController.$error[inputType]`, and
<add>the `ng-invalid-[inputType]` class. Also, custom parsers on input type "range" do no
<add>longer set `ngModelController.$error.number` and the `ng-invalid-number` class.
<add>
<add>Instead, any custom parsers on these inputs set `ngModelController.$error.parse` and
<add>`ng-invalid-parse`. This change was made to make distinguishing errors from built-in parsers
<add>and custom parsers easier.
<add>
<add>### **ngModelOptions** due to:
<add> - **[55ba44](https://github.com/angular/angular.js/commit/55ba44913e02650b56410aa9ab5eeea5d3492b68)**: add debounce catch-all + allow debouncing 'default' only
<add>
<add>the 'default' key in 'debounce' now only debounces the default event, i.e. the event
<add>that is added as an update trigger by the different input directives automatically.
<add>
<add>Previously, it also applied to other update triggers defined in 'updateOn' that
<add>did not have a corresponding key in the 'debounce'.
<add>
<add>This behavior is now supported via a special wildcard / catch-all key: '*'.
<add>
<add>See the following example:
<add>
<add>Pre-1.7:
<add>'mouseup' is also debounced by 500 milliseconds because 'default' is applied:
<add>```
<add>ng-model-options="{
<add> updateOn: 'default blur mouseup',
<add> debounce: { 'default': 500, 'blur': 0 }
<add>}
<add>```
<add>
<add>1.7:
<add>The pre-1.7 behavior can be re-created by setting '*' as a catch-all debounce value:
<add>```
<add>ng-model-options="{
<add> updateOn: 'default blur mouseup',
<add> debounce: { '*': 500, 'blur': 0 }
<add>}
<add>```
<add>
<add>In contrast, when only 'default' is used, 'blur' and 'mouseup' are not debounced:
<add>```
<add>ng-model-options="{
<add> updateOn: 'default blur mouseup',
<add> debounce: { 'default': 500 }
<add>}
<add>```
<add>
<add>### **input\[number\]** due to:
<add> - **[aa3f95](https://github.com/angular/angular.js/commit/aa3f951330ec7b10b43ea884d9b5754e296770ec)**: validate min/max against viewValue
<add>
<add>`input[type=number]` with `ngModel` now validates the input for the `max`/`min` restriction against
<add>the `ngModelController.$viewValue` instead of against the `ngModelController.$modelValue`.
<add>
<add>This affects apps that use `$parsers` or `$formatters` to transform the input / model value.
<add>
<add>If you rely on the $modelValue validation, you can overwrite the `min`/`max` validator from a custom directive, as seen in the following example directive definition object:
<add>
<add>```
<add>{
<add> restrict: 'A',
<add> require: 'ngModel',
<add> link: function(scope, element, attrs, ctrl) {
<add> var maxValidator = ctrl.$validators.max;
<add>
<add> ctrk.$validators.max = function(modelValue, viewValue) {
<add> return maxValidator(modelValue, modelValue);
<add> };
<add> }
<add>}
<add>```
<add>
<add>### **input** due to:
<add> - **[656c8f](https://github.com/angular/angular.js/commit/656c8fa8f23b1277cc5c214c4d0237f3393afa1e)**: listen on "change" instead of "click" for radio/checkbox ngModels
<add>
<add>`input[radio]` and `input[checkbox]` now listen to the "change" event instead of the "click" event.
<add>Most apps should not be affected, as "change" is automatically fired by browsers after "click"
<add>happens.
<add>
<add>Two scenarios might need migration:
<add>
<add>- Custom click events:
<add>
<add>Before this change, custom click event listeners on radio / checkbox would be called after the
<add>input element and `ngModel` had been updated, unless they were specifically registered before
<add>the built-in click handlers.
<add>After this change, they are called before the input is updated, and can call event.preventDefault()
<add>to prevent the input from updating.
<add>
<add>If an app uses a click event listener that expects ngModel to be updated when it is called, it now
<add>needs to register a change event listener instead.
<add>
<add>- Triggering click events:
<add>
<add>Conventional trigger functions:
<add>
<add>The change event might not be fired when the input element is not attached to the document. This
<add>can happen in **tests** that compile input elements and
<add>trigger click events on them. Depending on the browser (Chrome and Safari) and the trigger method,
<add>the change event will not be fired when the input isn't attached to the document.
<add>
<add>Before:
<add>
<add>```js
<add> it('should update the model', inject(function($compile, $rootScope) {
<add> var inputElm = $compile('<input type="checkbox" ng-model="checkbox" />')($rootScope);
<add>
<add> inputElm[0].click(); // Or different trigger mechanisms, such as jQuery.trigger()
<add> expect($rootScope.checkbox).toBe(true);
<add> });
<add>```
<add>
<add>With this patch, `$rootScope.checkbox` might not be true, because the click event
<add>hasn't triggered the change event. To make the test, work append the inputElm to the app's
<add>`$rootElement`, and the `$rootElement` to the `$document`.
<add>
<add>After:
<add>
<add>```js
<add> it('should update the model', inject(function($compile, $rootScope, $rootElement, $document) {
<add> var inputElm = $compile('<input type="checkbox" ng-model="checkbox" />')($rootScope);
<add>
<add> $rootElement.append(inputElm);
<add> $document.append($rootElement);
<add>
<add> inputElm[0].click(); // Or different trigger mechanisms, such as jQuery.trigger()
<add> expect($rootScope.checkbox).toBe(true);
<add> });
<add>```
<add>
<add>`triggerHandler()`:
<add>
<add>If you are using this jQuery / jqLite function on the input elements, you don't have to attach
<add>the elements to the document, but instead change the triggered event to "change". This is because
<add>`triggerHandler(event)` only triggers the exact event when it has been added by jQuery / jqLite.
<add>
<add>### **ngStyle** due to:
<add> - **[15bbd3](https://github.com/angular/angular.js/commit/15bbd3e18cd89b91f7206a06c73d40e54a8a48a0)**: use $watchCollection
<add>
<add>Previously the use of deep watch by ng-style would trigger styles to be
<add>re-applied when nested state changed. Now only changes to direct
<add>properties of the watched object will trigger changes.
<add>
<add>### **$compile** due to:
<add> - **[38f8c9](https://github.com/angular/angular.js/commit/38f8c97af74649ce224b6dd45f433cc665acfbfb)**: remove the preAssignBindingsEnabled flag
<add>
<add>Previously, the `$compileProvider.preAssignBindingsEnabled` flag was supported.
<add>The flag controlled whether bindings were available inside the controller
<add>constructor or only in the `$onInit` hook. The bindings are now no longer
<add>available in the constructor.
<add>
<add>To migrate your code:
<add>
<add>1. If you haven't invoked `$compileProvider.preAssignBindingsEnabled()` you
<add>don't have to do anything to migrate.
<add>
<add>2. If you specified `$compileProvider.preAssignBindingsEnabled(false)`, you
<add>can remove that statement - since AngularJS 1.6.0 this is the default so your
<add>app should still work even in AngularJS 1.6 after such removal. Afterwards,
<add>migrating to AngularJS 1.7.0 shouldn't require any further action.
<add>
<add>3. If you specified `$compileProvider.preAssignBindingsEnabled(true)` you need
<add>to first migrate your code so that the flag can be flipped to `false`. The
<add>instructions on how to do that are available in the "Migrating from 1.5 to 1.6"
<add>guide:
<add>https://docs.angularjs.org/guide/migration#migrating-from-1-5-to-1-6
<add>Afterwards, remove the `$compileProvider.preAssignBindingsEnabled(true)`
<add>statement.
<add>
<add> - **[6ccbfa](https://github.com/angular/angular.js/commit/6ccbfa65d60a3dc396d0cf6da21b993ad74653fd)**: lower the `xlink:href` security context for SVG's `a` and `image` elements
<add>
<add>In the unlikely case that an app relied on RESOURCE_URL whitelisting for the
<add>purpose of binding to the `xlink:href` property of SVG's `<a>` or `<image>`
<add>elements and if the values do not pass the regular URL sanitization, they will
<add>break.
<add>
<add>To fix this you need to ensure that the values used for binding to the affected
<add>`xlink:href` contexts are considered safe URLs, e.g. by whitelisting them in
<add>`$compileProvider`'s `aHrefSanitizationWhitelist` (for `<a>` elements) or
<add>`imgSrcSanitizationWhitelist` (for `<image>` elements).
<add>
<add> - **[fd4f01](https://github.com/angular/angular.js/commit/fd4f0111188b62773b99ab6eab38b4d2b5d8d727)**: do not use deepWatch in literal one-way bindings
<add>
<add>Previously when a literal value was passed into a directive/component via
<add>one-way binding it would be watched with a deep watcher.
<add>
<add>For example, for `<my-component input="[a]">`, a new instance of the array
<add>would be passed into the directive/component (and trigger $onChanges) not
<add>only if `a` changed but also if any sub property of `a` changed such as
<add>`a.b` or `a.b.c.d.e` etc.
<add>
<add>This also means a new but equal value for `a` would NOT trigger such a
<add>change.
<add>
<add>Now literal values use an input-based watch similar to other directive/component
<add>one-way bindings. In this context inputs are the non-constant parts of the
<add>literal. In the example above the input would be `a`. Changes are only
<add>triggered when the inputs to the literal change.
<add>
<add> - **[1cf728](https://github.com/angular/angular.js/commit/1cf728e209a9e0016068fac2769827e8f747760e)**: add `base[href]` to the list of RESOURCE_URL context attributes
<add>
<add>Previously, `<base href="{{ $ctrl.baseUrl }}" />` would not require `baseUrl` to
<add>be trusted as a RESOURCE_URL. Now, `baseUrl` will be sent to `$sce`'s
<add>RESOURCE_URL checks. By default, it will break unless `baseUrl` is of the same
<add>origin as the application document.
<add>
<add>Refer to the
<add>[`$sce` API docs](https://code.angularjs.org/snapshot/docs/api/ng/service/$sce)
<add>for more info on how to trust a value in a RESOURCE_URL context.
<add>
<add>Also, concatenation in trusted contexts is not allowed, which means that the
<add>following won't work: `<base href="/something/{{ $ctrl.partialPath }}" />`.
<add>
<add>Either construct complex values in a controller (recommended):
<add>
<add>```js
<add>this.baseUrl = '/something/' + this.partialPath;
<add>```
<add>```html
<add><base href="{{ $ctrl.baseUrl }}" />
<add>```
<add>
<add>Or use string concatenation in the interpolation expression (not recommended
<add>except for the simplest of cases):
<add>
<add>```html
<add><base href="{{ '/something/' + $ctrl.partialPath }}" />
<add>```
<add>
<add>### **ngTouch** due to:
<add> - **[11d9ad](https://github.com/angular/angular.js/commit/11d9ad1eb25eaf5967195e424108207427835d50)**: remove ngClick override, `$touchProvider`, and `$touch`
<add>
<add>The `ngClick` directive from the ngTouch module has been removed, and with it the
<add>corresponding `$touchProvider` and `$touch` service.
<add>
<add>If you have included ngTouch v1.5.0 or higher in your application, and have not
<add>changed the value of `$touchProvider.ngClickOverrideEnabled()`, or injected and used the `$touch`
<add>service, then there are no migration steps for your code. Otherwise you must remove references to
<add>the provider and service.
<add>
<add>The `ngClick` override directive had been deprecated and by default disabled since v1.5.0,
<add>because of buggy behavior in edge cases, and a general trend to avoid special touch based
<add>overrides of click events. In modern browsers, it should not be necessary to use a touch override
<add>library:
<add>
<add>- Chrome, Firefox, Edge, and Safari remove the 300ms delay when
<add> `<meta name="viewport" content="width=device-width">` is set.
<add>- Internet Explorer 10+, Edge, Safari, and Chrome remove the delay on elements that have the
<add> `touch-action` css property is set to `manipulation`.
<add>
<add>You can find out more in these articles:
<add>https://developers.google.com/web/updates/2013/12/300ms-tap-delay-gone-away
<add>https://developer.apple.com/library/content/releasenotes/General/WhatsNewInSafari/Articles/Safari_9_1.html#//apple_ref/doc/uid/TP40014305-CH10-SW8
<add>https://blogs.msdn.microsoft.com/ie/2015/02/24/pointer-events-w3c-recommendation-interoperable-touch-and-removing-the-dreaded-300ms-tap-delay/
<add>
<add>### **Angular** due to:
<add> - **[1daa4f](https://github.com/angular/angular.js/commit/1daa4f2231a89ee88345689f001805ffffa9e7de)**: remove `angular.lowercase` and `angular.uppercase`
<add>
<add>The helper functions `angular.lowercase` `and angular.uppercase` have
<add>been removed.
<add>
<add>These functions have been deprecated since 1.5.0. They are internally
<add>used, but should not be exposed as they contain special locale handling
<add>(for Turkish) to maintain internal consistency regardless of user-set locale.
<add>
<add>Developers should generally use the built-ins `toLowerCase` and `toUpperCase`
<add>or `toLocaleLowerCase` and `toLocaleUpperCase` for special cases.
<add>
<add>Further, we generally discourage using the angular.x helpers in application code.
<add>
<add>### **$controller** due to:
<add> - **[e269c1](https://github.com/angular/angular.js/commit/e269c14425a3209040f65c022658770e00a36f16)**: remove instantiating controllers defined on window
<add>
<add>The option to instantiate controllers from constructors on the global `window` object
<add>has been removed. Likewise, the deprecated `$controllerProvider.allowGlobals()`
<add>method that could enable this behavior, has been removed.
<add>
<add>This behavior had been deprecated since AngularJS v1.3.0, because polluting the global scope
<add>is bad. To migrate, remove the call to $controllerProvider.allowGlobals() in the config, and
<add>register your controller via the Module API or the $controllerProvider, e.g.
<add>
<add>```
<add>angular.module('myModule', []).controller('myController', function() {...});
<add>
<add>angular.module('myModule', []).config(function($controllerProvider) {
<add> $controllerProvider.register('myController', function() {...});
<add>});
<add>
<add>```
<add>
<add>### **$rootScope** due to:
<add> - **[c2b8fa](https://github.com/angular/angular.js/commit/c2b8fab0a480204374d561d6b9b3d47347ac5570)**: provide correct value of one-time bindings in watchGroup
<add>
<add>Previously when using `$watchGroup` the entries in `newValues` and
<add>`oldValues` represented the *most recent change of each entry*.
<add>
<add>Now the entries in `oldValues` will always equal the `newValues` of the previous
<add>call of the listener. This means comparing the entries in `newValues` and
<add>`oldValues` can be used to determine which individual expressions changed.
<add>
<add>For example `$scope.$watchGroup(['a', 'b'], fn)` would previously:
<add>
<add>| Action | newValue | oldValue |
<add>|----------|------------|------------|
<add>| (init) | [undefined, undefined] | [undefined, undefined] |
<add>| `a=1` | [1, undefined] | [undefined, undefined] |
<add>| `a=2` | [2, undefined] | [1, undefined] |
<add>| `b=3` | [2, 3] | [1, undefined] |
<add>
<add>
<add>Now the `oldValue` will always equal the previous `newValue`:
<add>
<add>| Action | newValue | oldValue |
<add>|----------|------------|------------|
<add>| (init) | [undefined, undefined] | [undefined, undefined] |
<add>| `a=1` | [1, undefined] | [undefined, undefined] |
<add>| `a=2` | [2, undefined] | [1, undefined] |
<add>| `b=3` | [2, 3] | [2, undefined] |
<add>
<add>Note the last call now shows `a === 2` in the `oldValues` array.
<add>
<add>This also makes the `oldValue` of one-time watchers more clear. Previously
<add>the `oldValue` of a one-time watcher would remain `undefined` forever. For
<add>example `$scope.$watchGroup(['a', '::b'], fn)` would previously:
<add>
<add>| Action | newValue | oldValue |
<add>|----------|------------|------------|
<add>| (init) | [undefined, undefined] | [undefined, undefined] |
<add>| `a=1` | [1, undefined] | [undefined, undefined] |
<add>| `b=2` | [1, 2] | [undefined, undefined] |
<add>| `a=b=3` | [3, 2] | [1, undefined] |
<add>
<add>Where now the `oldValue` will always equal the previous `newValue`:
<add>
<add>| Action | newValue | oldValue |
<add>|----------|------------|------------|
<add>| (init) | [undefined, undefined] | [undefined, undefined] |
<add>| `a=1` | [1, undefined] | [undefined, undefined] |
<add>| `b=2` | [1, 2] | [1, undefined] |
<add>| `a=b=3` | [3, 2] | [1, 2] |
<add>
<add>### **$interval** due to:
<add> - **[a8bef9](https://github.com/angular/angular.js/commit/a8bef95127775d83d80daa4617c33227c4b443d4)**: throw when trying to cancel non-$interval promise
<add>
<add>`$interval.cancel()` will throw an error if called with a promise that
<add>was not generated by `$interval()`. Previously, it would silently do
<add>nothing.
<add>
<add>Before:
<add>```js
<add>var promise = $interval(doSomething, 1000, 5).then(doSomethingElse);
<add>$interval.cancel(promise); // No error; interval NOT canceled.
<add>```
<add>
<add>After:
<add>```js
<add>var promise = $interval(doSomething, 1000, 5).then(doSomethingElse);
<add>$interval.cancel(promise); // Throws error.
<add>```
<add>
<add>Correct usage:
<add>```js
<add>var promise = $interval(doSomething, 1000, 5);
<add>var newPromise = promise.then(doSomethingElse);
<add>$interval.cancel(promise); // Interval canceled.
<add>```
<add>
<add>### **$timeout** due to:
<add> - **[336525](https://github.com/angular/angular.js/commit/3365256502344970f86355d3ace1cb4251ae9828)**: throw when trying to cancel non-$timeout promise
<add>
<add>`$timeout.cancel()` will throw an error if called with a promise that
<add>was not generated by `$timeout()`. Previously, it would silently do
<add>nothing.
<add>
<add>Before:
<add>```js
<add>var promise = $timeout(doSomething, 1000).then(doSomethingElse);
<add>$timeout.cancel(promise); // No error; timeout NOT canceled.
<add>```
<add>
<add>After:
<add>```js
<add>var promise = $timeout(doSomething, 1000).then(doSomethingElse);
<add>$timeout.cancel(promise); // Throws error.
<add>```
<add>
<add>Correct usage:
<add>```js
<add>var promise = $timeout(doSomething, 1000);
<add>var newPromise = promise.then(doSomethingElse);
<add>$timeout.cancel(promise); // Timeout canceled.
<add>```
<add>
<ide> <a name="1.7.0-rc.0"></a>
<ide> # 1.7.0-rc.0 maximum-overdrive (2018-04-19)
<ide> | 1 |
Text | Text | provide example for dict in validationerror detail | ef112f5017bb6d3d6a331ff485dbf6a9209fb8b4 | <ide><path>docs/api-guide/exceptions.md
<ide> By default this exception results in a response with the HTTP status code "429 T
<ide> The `ValidationError` exception is slightly different from the other `APIException` classes:
<ide>
<ide> * The `detail` argument is mandatory, not optional.
<del>* The `detail` argument may be a list or dictionary of error details, and may also be a nested data structure.
<add>* The `detail` argument may be a list or dictionary of error details, and may also be a nested data structure. By using a dictionary, you can specify field-level errors while performing object-level validation in the `validate()` method of a serializer. For example. `raise serializers.ValidationError({'name': 'Please enter a valid name.'})`
<ide> * By convention you should import the serializers module and use a fully qualified `ValidationError` style, in order to differentiate it from Django's built-in validation error. For example. `raise serializers.ValidationError('This field must be an integer value.')`
<ide>
<ide> The `ValidationError` class should be used for serializer and field validation, and by validator classes. It is also raised when calling `serializer.is_valid` with the `raise_exception` keyword argument: | 1 |
Go | Go | fix ip case for bridgeip | cb3bd91689b9beaaa4e287e126bc8150b5161c57 | <ide><path>config.go
<ide> func DaemonConfigFromJob(job *engine.Job) *DaemonConfig {
<ide> AutoRestart: job.GetenvBool("AutoRestart"),
<ide> EnableIptables: job.GetenvBool("EnableIptables"),
<ide> EnableIpForward: job.GetenvBool("EnableIpForward"),
<del> BridgeIP: job.Getenv("BridgeIp"),
<add> BridgeIP: job.Getenv("BridgeIP"),
<ide> DefaultIp: net.ParseIP(job.Getenv("DefaultIp")),
<ide> InterContainerCommunication: job.GetenvBool("InterContainerCommunication"),
<ide> GraphDriver: job.Getenv("GraphDriver"),
<ide><path>docker/docker.go
<ide> func main() {
<ide> job.SetenvBool("EnableIptables", *flEnableIptables)
<ide> job.SetenvBool("EnableIpForward", *flEnableIpForward)
<ide> job.Setenv("BridgeIface", *bridgeName)
<del> job.Setenv("BridgeIp", *bridgeIp)
<add> job.Setenv("BridgeIP", *bridgeIp)
<ide> job.Setenv("DefaultIp", *flDefaultIp)
<ide> job.SetenvBool("InterContainerCommunication", *flInterContainerComm)
<ide> job.Setenv("GraphDriver", *flGraphDriver) | 2 |
Mixed | Python | add xcom.get_one() method back | d0e010f1f7691d9ed2fd547ca0218f932e6e36b9 | <ide><path>UPDATING.md
<ide> with redirect_stdout(StreamLogWriter(logger, logging.INFO)), \
<ide> print("I Love Airflow")
<ide> ```
<ide>
<del>### Removal of XCom.get_one()
<del>
<del>This one is superseded by `XCom.get_many().first()` which will return the same result.
<del>
<ide> ### Changes to SQLSensor
<ide>
<ide> SQLSensor now consistent with python `bool()` function and the `allow_null` parameter has been removed.
<ide><path>airflow/models/xcom.py
<ide> def set(
<ide>
<ide> session.commit()
<ide>
<add> @classmethod
<add> @provide_session
<add> def get_one(cls,
<add> execution_date: pendulum.DateTime,
<add> key: Optional[str] = None,
<add> task_id: Optional[Union[str, Iterable[str]]] = None,
<add> dag_id: Optional[Union[str, Iterable[str]]] = None,
<add> include_prior_dates: bool = False,
<add> session: Session = None) -> Optional[Any]:
<add> """
<add> Retrieve an XCom value, optionally meeting certain criteria. Returns None
<add> of there are no results.
<add>
<add> :param execution_date: Execution date for the task
<add> :type execution_date: pendulum.datetime
<add> :param key: A key for the XCom. If provided, only XComs with matching
<add> keys will be returned. To remove the filter, pass key=None.
<add> :type key: str
<add> :param task_id: Only XComs from task with matching id will be
<add> pulled. Can pass None to remove the filter.
<add> :type task_id: str
<add> :param dag_id: If provided, only pulls XCom from this DAG.
<add> If None (default), the DAG of the calling task is used.
<add> :type dag_id: str
<add> :param include_prior_dates: If False, only XCom from the current
<add> execution_date are returned. If True, XCom from previous dates
<add> are returned as well.
<add> :type include_prior_dates: bool
<add> :param session: database session
<add> :type session: sqlalchemy.orm.session.Session
<add> """
<add> result = cls.get_many(execution_date=execution_date,
<add> key=key,
<add> task_ids=task_id,
<add> dag_ids=dag_id,
<add> include_prior_dates=include_prior_dates,
<add> session=session).first()
<add> if result:
<add> return result.value
<add> return None
<add>
<ide> @classmethod
<ide> @provide_session
<ide> def get_many(cls,
<ide><path>tests/models/test_cleartasks.py
<ide> def test_xcom_disable_pickle_type(self):
<ide>
<ide> self.assertEqual(ret_value, json_obj)
<ide>
<add> @conf_vars({("core", "enable_xcom_pickling"): "False"})
<add> def test_xcom_get_one_disable_pickle_type(self):
<add> json_obj = {"key": "value"}
<add> execution_date = timezone.utcnow()
<add> key = "xcom_test1"
<add> dag_id = "test_dag1"
<add> task_id = "test_task1"
<add> XCom.set(key=key,
<add> value=json_obj,
<add> dag_id=dag_id,
<add> task_id=task_id,
<add> execution_date=execution_date)
<add>
<add> ret_value = XCom.get_one(key=key,
<add> dag_id=dag_id,
<add> task_id=task_id,
<add> execution_date=execution_date)
<add>
<add> self.assertEqual(ret_value, json_obj)
<add>
<add> session = settings.Session()
<add> ret_value = session.query(XCom).filter(XCom.key == key, XCom.dag_id == dag_id,
<add> XCom.task_id == task_id,
<add> XCom.execution_date == execution_date
<add> ).first().value
<add>
<add> self.assertEqual(ret_value, json_obj)
<add>
<ide> @conf_vars({("core", "enable_xcom_pickling"): "True"})
<ide> def test_xcom_enable_pickle_type(self):
<ide> json_obj = {"key": "value"}
<ide> def test_xcom_enable_pickle_type(self):
<ide>
<ide> self.assertEqual(ret_value, json_obj)
<ide>
<add> @conf_vars({("core", "enable_xcom_pickling"): "True"})
<add> def test_xcom_get_one_enable_pickle_type(self):
<add> json_obj = {"key": "value"}
<add> execution_date = timezone.utcnow()
<add> key = "xcom_test3"
<add> dag_id = "test_dag"
<add> task_id = "test_task3"
<add> XCom.set(key=key,
<add> value=json_obj,
<add> dag_id=dag_id,
<add> task_id=task_id,
<add> execution_date=execution_date)
<add>
<add> ret_value = XCom.get_one(key=key,
<add> dag_id=dag_id,
<add> task_id=task_id,
<add> execution_date=execution_date)
<add>
<add> self.assertEqual(ret_value, json_obj)
<add>
<add> session = settings.Session()
<add> ret_value = session.query(XCom).filter(XCom.key == key, XCom.dag_id == dag_id,
<add> XCom.task_id == task_id,
<add> XCom.execution_date == execution_date
<add> ).first().value
<add>
<add> self.assertEqual(ret_value, json_obj)
<add>
<ide> @conf_vars({("core", "xcom_enable_pickling"): "False"})
<ide> def test_xcom_disable_pickle_type_fail_on_non_json(self):
<ide> class PickleRce: | 3 |
Javascript | Javascript | evaluate only scripts with type text/javascript | d1558d7924dec1156784f3b4576880f72213f671 | <ide><path>docs/src/templates/doc_widgets.js
<ide> angular.module('ngdocs.directives', [], function($compileProvider) {
<ide> //jqlite instead. jqlite's find() method currently supports onlt getElementsByTagName!
<ide> var example = element.find('pre').eq(0), //doc-source
<ide> scriptSrc = '',
<del> htmlSrc = example.text().replace(/<script[^\>]*>([\s\S]+)<\/script>/im, function(_, script) {
<add> htmlSrc = example.text().replace(/<script(\s+type="text\/javascript")?>([\s\S]+)<\/script>/im, function(_, type, script) {
<ide> scriptSrc = script;
<ide> return '';
<ide> }), | 1 |
Javascript | Javascript | add react native modules to module map + fix fbjs | 240dfae28c81a05dab137a84e81e48c5ccecdcec | <ide><path>gulpfile.js
<ide> var paths = {
<ide> react: {
<ide> src: [
<ide> 'src/**/*.js',
<add> '!src/**/__benchmarks__/**/*.js',
<ide> '!src/**/__tests__/**/*.js',
<ide> '!src/**/__mocks__/**/*.js',
<ide> '!src/shared/vendor/**/*.js',
<ide> var paths = {
<ide> },
<ide> };
<ide>
<add>var fbjsModuleMap = require('fbjs/module-map');
<add>var moduleMap = {};
<add>for (var key in fbjsModuleMap) {
<add> moduleMap[key] = fbjsModuleMap[key];
<add>}
<add>var whiteListNames = [
<add> 'deepDiffer',
<add> 'deepFreezeAndThrowOnMutationInDev',
<add> 'flattenStyle',
<add> 'InitializeJavaScriptAppEngine',
<add> 'InteractionManager',
<add> 'JSTimersExecution',
<add> 'merge',
<add> 'Platform',
<add> 'RCTEventEmitter',
<add> 'RCTLog',
<add> 'TextInputState',
<add> 'UIManager',
<add> 'View',
<add>];
<add>
<add>whiteListNames.forEach(function(name) {
<add> moduleMap[name] = name;
<add>});
<add>
<add>moduleMap['object-assign'] = 'object-assign';
<add>
<ide> var babelOpts = {
<ide> plugins: [
<del> [babelPluginModules, {
<del> map: Object.assign(
<del> {},
<del> require('fbjs/module-map'),
<del> {
<del> 'object-assign': 'object-assign',
<del> }
<del> ),
<del> }],
<add> [babelPluginModules, { map: moduleMap }],
<ide> ],
<ide> };
<ide>
<ide><path>packages/react/lib/ReactDOM.native.js
<add>/**
<add> * @providesModule ReactDOM
<add> */
<add>
<ide> 'use strict';
<ide>
<ide> var ReactUpdates = require('./ReactUpdates');
<ide><path>src/renderers/native/NodeHandle/UniversalWorkerNodeHandle.js
<ide>
<ide> var ReactNativeTagHandles = require('ReactNativeTagHandles');
<ide>
<del>var invariant = require('fbjs/lib/invariant');
<add>var invariant = require('invariant');
<ide>
<ide> var UniversalWorkerNodeHandle = {
<ide> getRootNodeID: function(nodeHandle) {
<ide><path>src/renderers/native/ReactIOS/IOSNativeBridgeEventPlugin.js
<ide> var SyntheticEvent = require('SyntheticEvent');
<ide> var UIManager = require('UIManager');
<ide>
<ide> var merge = require('merge');
<del>var warning = require('fbjs/lib/warning');
<add>var warning = require('warning');
<ide>
<ide> var customBubblingEventTypes = UIManager.customBubblingEventTypes;
<ide> var customDirectEventTypes = UIManager.customDirectEventTypes;
<ide><path>src/renderers/native/ReactIOS/NativeMethodsMixin.js
<ide> var TextInputState = require('TextInputState');
<ide> var UIManager = require('UIManager');
<ide>
<ide> var findNodeHandle = require('findNodeHandle');
<del>var invariant = require('fbjs/lib/invariant');
<add>var invariant = require('invariant');
<ide>
<ide> type MeasureOnSuccessCallback = (
<ide> x: number,
<ide><path>src/renderers/native/ReactNative/ReactNativeBaseComponent.js
<ide> var ReactMultiChild = require('ReactMultiChild');
<ide> var UIManager = require('UIManager');
<ide>
<ide> var deepFreezeAndThrowOnMutationInDev = require('deepFreezeAndThrowOnMutationInDev');
<del>var invariant = require('fbjs/lib/invariant');
<del>var warning = require('fbjs/lib/warning');
<add>var invariant = require('invariant');
<add>var warning = require('warning');
<ide>
<ide> var registrationNames = ReactNativeEventEmitter.registrationNames;
<ide> var putListener = ReactNativeEventEmitter.putListener;
<ide><path>src/renderers/native/ReactNative/ReactNativeDefaultInjection.js
<ide> var ReactUpdates = require('ReactUpdates');
<ide> var ResponderEventPlugin = require('ResponderEventPlugin');
<ide> var UniversalWorkerNodeHandle = require('UniversalWorkerNodeHandle');
<ide>
<del>var invariant = require('fbjs/lib/invariant');
<add>var invariant = require('invariant');
<ide>
<ide> // Just to ensure this gets packaged, since its only caller is from Native.
<ide> require('RCTEventEmitter');
<ide><path>src/renderers/native/ReactNative/ReactNativeEventEmitter.js
<ide> var NodeHandle = require('NodeHandle');
<ide> var EventConstants = require('EventConstants');
<ide>
<ide> var merge = require('merge');
<del>var warning = require('fbjs/lib/warning');
<add>var warning = require('warning');
<ide>
<ide> var topLevelTypes = EventConstants.topLevelTypes;
<ide>
<ide><path>src/renderers/native/ReactNative/ReactNativeMount.js
<ide> var ReactUpdateQueue = require('ReactUpdateQueue');
<ide> var ReactUpdates = require('ReactUpdates');
<ide> var UIManager = require('UIManager');
<ide>
<del>var emptyObject = require('fbjs/lib/emptyObject');
<add>var emptyObject = require('emptyObject');
<ide> var instantiateReactComponent = require('instantiateReactComponent');
<ide> var shouldUpdateReactComponent = require('shouldUpdateReactComponent');
<ide>
<ide><path>src/renderers/native/ReactNative/ReactNativeTagHandles.js
<ide> */
<ide> 'use strict';
<ide>
<del>var invariant = require('fbjs/lib/invariant');
<del>var warning = require('fbjs/lib/warning');
<add>var invariant = require('invariant');
<add>var warning = require('warning');
<ide>
<ide> /**
<ide> * Keeps track of allocating and associating native "tags" which are numeric,
<ide><path>src/renderers/native/ReactNative/ReactNativeTextComponent.js
<ide> var ReactNativeTagHandles = require('ReactNativeTagHandles');
<ide> var UIManager = require('UIManager');
<ide>
<del>var invariant = require('fbjs/lib/invariant');
<add>var invariant = require('invariant');
<ide>
<ide> var ReactNativeTextComponent = function(props) {
<ide> // This constructor and its argument is currently used by mocks.
<ide><path>src/renderers/native/ReactNative/findNodeHandle.js
<ide> var ReactCurrentOwner = require('ReactCurrentOwner');
<ide> var ReactInstanceMap = require('ReactInstanceMap');
<ide> var ReactNativeTagHandles = require('ReactNativeTagHandles');
<ide>
<del>var invariant = require('fbjs/lib/invariant');
<del>var warning = require('fbjs/lib/warning');
<add>var invariant = require('invariant');
<add>var warning = require('warning');
<ide>
<ide> /**
<ide> * ReactNative vs ReactWeb | 12 |
Python | Python | fix small typo on extractor.py | c99f4e3a7509a37125e9fa5f225cd31f2a42e503 | <ide><path>research/delf/delf/python/examples/extractor.py
<ide> def ExtractorFn(image, resize_factor=1.0):
<ide> if hasattr(config, 'is_tf2_exported') and config.is_tf2_exported:
<ide> predict = model.signatures['serving_default']
<ide> if config.use_local_features and config.use_global_features:
<del> if config.use_global_features:
<del> output_dict = predict(
<del> input_image=image_tensor,
<del> input_scales=image_scales_tensor,
<del> input_max_feature_num=max_feature_num_tensor,
<del> input_abs_thres=score_threshold_tensor,
<del> input_global_scales_ind=global_scales_ind_tensor)
<del> output = [
<del> output_dict['boxes'], output_dict['features'],
<del> output_dict['scales'], output_dict['scores'],
<del> output_dict['global_descriptors']
<del> ]
<add> output_dict = predict(
<add> input_image=image_tensor,
<add> input_scales=image_scales_tensor,
<add> input_max_feature_num=max_feature_num_tensor,
<add> input_abs_thres=score_threshold_tensor,
<add> input_global_scales_ind=global_scales_ind_tensor)
<add> output = [
<add> output_dict['boxes'], output_dict['features'],
<add> output_dict['scales'], output_dict['scores'],
<add> output_dict['global_descriptors']
<add> ]
<ide> elif config.use_local_features:
<ide> output_dict = predict(
<ide> input_image=image_tensor, | 1 |
Mixed | Javascript | deprecate all previous private apis | fe069cca6a87bcbc7030e8a1e631a81ba8c49580 | <ide><path>doc/api/deprecations.md
<ide> Type: Documentation-only
<ide> The `process.binding()` API is intended for use by Node.js internal code
<ide> only. Use of `process.binding()` by userland code is unsupported.
<ide>
<add><a id="DEP0112"></a>
<add>### DEP0112: dgram private APIs
<add>
<add>Type: Runtime
<add>
<add>The `dgram` module previously contained several APIs that were never meant to
<add>accessed outside of Node.js core: `Socket.prototype._handle`,
<add>`Socket.prototype._receiving`, `Socket.prototype._bindState`,
<add>`Socket.prototype._queue`, `Socket.prototype._reuseAddr`,
<add>`Socket.prototype._healthCheck()`, `Socket.prototype._stopReceiving()`, and
<add>`dgram._createSocketHandle()`.
<add>
<ide> [`--pending-deprecation`]: cli.html#cli_pending_deprecation
<ide> [`Buffer.allocUnsafeSlow(size)`]: buffer.html#buffer_class_method_buffer_allocunsafeslow_size
<ide> [`Buffer.from(array)`]: buffer.html#buffer_class_method_buffer_from_array
<ide><path>lib/dgram.js
<ide> Socket.prototype.getSendBufferSize = function() {
<ide> };
<ide>
<ide>
<del>// Legacy private APIs to be deprecated in the future.
<add>// Deprecated private APIs.
<ide> Object.defineProperty(Socket.prototype, '_handle', {
<del> get() {
<add> get: util.deprecate(function() {
<ide> return this[kStateSymbol].handle;
<del> },
<del> set(val) {
<add> }, 'Socket.prototype._handle is deprecated', 'DEP0112'),
<add> set: util.deprecate(function(val) {
<ide> this[kStateSymbol].handle = val;
<del> }
<add> }, 'Socket.prototype._handle is deprecated', 'DEP0112')
<ide> });
<ide>
<ide>
<ide> Object.defineProperty(Socket.prototype, '_receiving', {
<del> get() {
<add> get: util.deprecate(function() {
<ide> return this[kStateSymbol].receiving;
<del> },
<del> set(val) {
<add> }, 'Socket.prototype._receiving is deprecated', 'DEP0112'),
<add> set: util.deprecate(function(val) {
<ide> this[kStateSymbol].receiving = val;
<del> }
<add> }, 'Socket.prototype._receiving is deprecated', 'DEP0112')
<ide> });
<ide>
<ide>
<ide> Object.defineProperty(Socket.prototype, '_bindState', {
<del> get() {
<add> get: util.deprecate(function() {
<ide> return this[kStateSymbol].bindState;
<del> },
<del> set(val) {
<add> }, 'Socket.prototype._bindState is deprecated', 'DEP0112'),
<add> set: util.deprecate(function(val) {
<ide> this[kStateSymbol].bindState = val;
<del> }
<add> }, 'Socket.prototype._bindState is deprecated', 'DEP0112')
<ide> });
<ide>
<ide>
<ide> Object.defineProperty(Socket.prototype, '_queue', {
<del> get() {
<add> get: util.deprecate(function() {
<ide> return this[kStateSymbol].queue;
<del> },
<del> set(val) {
<add> }, 'Socket.prototype._queue is deprecated', 'DEP0112'),
<add> set: util.deprecate(function(val) {
<ide> this[kStateSymbol].queue = val;
<del> }
<add> }, 'Socket.prototype._queue is deprecated', 'DEP0112')
<ide> });
<ide>
<ide>
<ide> Object.defineProperty(Socket.prototype, '_reuseAddr', {
<del> get() {
<add> get: util.deprecate(function() {
<ide> return this[kStateSymbol].reuseAddr;
<del> },
<del> set(val) {
<add> }, 'Socket.prototype._reuseAddr is deprecated', 'DEP0112'),
<add> set: util.deprecate(function(val) {
<ide> this[kStateSymbol].reuseAddr = val;
<del> }
<add> }, 'Socket.prototype._reuseAddr is deprecated', 'DEP0112')
<ide> });
<ide>
<ide>
<del>Socket.prototype._healthCheck = function() {
<add>Socket.prototype._healthCheck = util.deprecate(function() {
<ide> healthCheck(this);
<del>};
<add>}, 'Socket.prototype._healthCheck() is deprecated', 'DEP0112');
<ide>
<ide>
<del>Socket.prototype._stopReceiving = function() {
<add>Socket.prototype._stopReceiving = util.deprecate(function() {
<ide> stopReceiving(this);
<del>};
<add>}, 'Socket.prototype._stopReceiving() is deprecated', 'DEP0112');
<ide>
<ide>
<ide> // Legacy alias on the C++ wrapper object. This is not public API, so we may
<ide> Object.defineProperty(UDP.prototype, 'owner', {
<ide>
<ide>
<ide> module.exports = {
<del> _createSocketHandle,
<add> _createSocketHandle: util.deprecate(
<add> _createSocketHandle,
<add> 'dgram._createSocketHandle() is deprecated',
<add> 'DEP0112'
<add> ),
<ide> createSocket,
<ide> Socket
<ide> }; | 2 |
Javascript | Javascript | remove old code | 60b1d20667b6855b6b9ff27c5513fc738af02045 | <ide><path>src/linear-line-top-index.js
<ide> class LineTopIndex {
<ide> }
<ide>
<ide> splice (startRow, oldExtent, newExtent) {
<del> let blocksHeight = 0
<ide> this.blocks.forEach(function (block) {
<ide> if (block.row >= startRow) {
<ide> if (block.row >= startRow + oldExtent) {
<ide> class LineTopIndex {
<ide> block.row = startRow + newExtent
<ide> // invalidate marker?
<ide> }
<del>
<del> block.top = block.row * this.defaultLineHeight + blocksHeight
<del> blocksHeight += block.height
<ide> }
<ide> })
<ide> | 1 |
Python | Python | add saving tests | d1b40b169f3d70afe4db539d140d6ed374dab21e | <ide><path>tests/test_model_saving.py
<ide> def test_loading_weights_by_name_and_reshape():
<ide> model.load_weights(fname, by_name=False, reshape=False)
<ide> model.load_weights(fname, by_name=False, reshape=True)
<ide> model.load_weights(fname, by_name=True, reshape=True)
<del> os.remove(fname)
<ide>
<ide> out2 = model.predict(x)
<ide> assert_allclose(np.squeeze(out), np.squeeze(out2), atol=1e-05)
<ide> def test_loading_weights_by_name_and_reshape():
<ide> if old_weights[i]:
<ide> assert_allclose(old_weights[i][j], new_weights[j], atol=1e-05)
<ide>
<add> # delete and recreate model with `use_bias=False`
<add> del(model)
<add> model = Sequential()
<add> model.add(Conv2D(2, (1, 1), input_shape=(1, 1, 1), use_bias=False, name='rick'))
<add> model.add(Flatten())
<add> model.add(Dense(3, name='morty'))
<add> with pytest.raises(ValueError,
<add> match=r'.* expects [0-9]+ .* but the saved .* [0-9]+ .*'):
<add> model.load_weights(fname)
<add> with pytest.raises(ValueError,
<add> match=r'.* expects [0-9]+ .* but the saved .* [0-9]+ .*'):
<add> model.load_weights(fname, by_name=True)
<add> with pytest.warns(UserWarning,
<add> match=r'Skipping loading .* due to mismatch .*'):
<add> model.load_weights(fname, by_name=True, skip_mismatch=True)
<add>
<add> # delete and recreate model with `filters=10`
<add> del(model)
<add> model = Sequential()
<add> model.add(Conv2D(10, (1, 1), input_shape=(1, 1, 1), name='rick'))
<add> with pytest.raises(ValueError,
<add> match=r'.* has shape .* but the saved .* shape .*'):
<add> model.load_weights(fname, by_name=True)
<add> with pytest.raises(ValueError,
<add> match=r'.* load .* [0-9]+ layers into .* [0-9]+ layers.'):
<add> model.load_weights(fname)
<add>
<add> os.remove(fname)
<add>
<ide>
<ide> @keras_test
<ide> def test_loading_weights_by_name_2(): | 1 |
Ruby | Ruby | convert download strategies test to spec | 92710c50c65beccfc2fca744cc8ee1be19a87aad | <ide><path>Library/Homebrew/test/download_strategies_spec.rb
<add>require "download_strategy"
<add>
<add>describe AbstractDownloadStrategy do
<add> subject { described_class.new(name, resource) }
<add> let(:name) { "foo" }
<add> let(:url) { "http://example.com/foo.tar.gz" }
<add> let(:resource) { double(Resource, url: url, mirrors: [], specs: {}, version: nil) }
<add> let(:args) { %w[foo bar baz] }
<add>
<add> describe "#expand_safe_system_args" do
<add> it "works with an explicit quiet flag" do
<add> args << { quiet_flag: "--flag" }
<add> expanded_args = subject.expand_safe_system_args(args)
<add> expect(expanded_args).to eq(%w[foo bar baz --flag])
<add> end
<add>
<add> it "adds an implicit quiet flag" do
<add> expanded_args = subject.expand_safe_system_args(args)
<add> expect(expanded_args).to eq(%w[foo bar -q baz])
<add> end
<add>
<add> it "does not mutate the arguments" do
<add> result = subject.expand_safe_system_args(args)
<add> expect(args).to eq(%w[foo bar baz])
<add> expect(result).not_to be args
<add> end
<add> end
<add>
<add> specify "#source_modified_time" do
<add> FileUtils.mktemp "mtime" do
<add> FileUtils.touch "foo", mtime: Time.now - 10
<add> FileUtils.touch "bar", mtime: Time.now - 100
<add> FileUtils.ln_s "not-exist", "baz"
<add> expect(subject.source_modified_time).to eq(File.mtime("foo"))
<add> end
<add> end
<add>end
<add>
<add>describe VCSDownloadStrategy do
<add> let(:url) { "http://example.com/bar" }
<add> let(:resource) { double(Resource, url: url, mirrors: [], specs: {}, version: nil) }
<add>
<add> describe "#cached_location" do
<add> it "returns the path of the cached resource" do
<add> allow_any_instance_of(described_class).to receive(:cache_tag).and_return("foo")
<add> downloader = described_class.new("baz", resource)
<add> expect(downloader.cached_location).to eq(HOMEBREW_CACHE/"baz--foo")
<add> end
<add> end
<add>end
<add>
<add>describe GitHubPrivateRepositoryDownloadStrategy do
<add> subject { described_class.new("foo", resource) }
<add> let(:url) { "https://github.com/owner/repo/archive/1.1.5.tar.gz" }
<add> let(:resource) { double(Resource, url: url, mirrors: [], specs: {}, version: nil) }
<add>
<add> before(:each) do
<add> ENV["HOMEBREW_GITHUB_API_TOKEN"] = "token"
<add> allow(GitHub).to receive(:repository).and_return({})
<add> end
<add>
<add> it "sets the @github_token instance variable" do
<add> expect(subject.instance_variable_get(:@github_token)).to eq("token")
<add> end
<add>
<add> it "parses the URL and sets the corresponding instance variables" do
<add> expect(subject.instance_variable_get(:@owner)).to eq("owner")
<add> expect(subject.instance_variable_get(:@repo)).to eq("repo")
<add> expect(subject.instance_variable_get(:@filepath)).to eq("archive/1.1.5.tar.gz")
<add> end
<add>
<add> its(:download_url) { is_expected.to eq("https://token@github.com/owner/repo/archive/1.1.5.tar.gz") }
<add>end
<add>
<add>describe GitHubPrivateRepositoryReleaseDownloadStrategy do
<add> subject { described_class.new("foo", resource) }
<add> let(:url) { "https://github.com/owner/repo/releases/download/tag/foo_v0.1.0_darwin_amd64.tar.gz" }
<add> let(:resource) { double(Resource, url: url, mirrors: [], specs: {}, version: nil) }
<add>
<add> before(:each) do
<add> ENV["HOMEBREW_GITHUB_API_TOKEN"] = "token"
<add> allow(GitHub).to receive(:repository).and_return({})
<add> end
<add>
<add> it "parses the URL and sets the corresponding instance variables" do
<add> expect(subject.instance_variable_get(:@owner)).to eq("owner")
<add> expect(subject.instance_variable_get(:@repo)).to eq("repo")
<add> expect(subject.instance_variable_get(:@tag)).to eq("tag")
<add> expect(subject.instance_variable_get(:@filename)).to eq("foo_v0.1.0_darwin_amd64.tar.gz")
<add> end
<add>
<add> describe "#download_url" do
<add> it "returns the download URL for a given resource" do
<add> allow(subject).to receive(:resolve_asset_id).and_return(456)
<add> expect(subject.download_url).to eq("https://token@api.github.com/repos/owner/repo/releases/assets/456")
<add> end
<add> end
<add>
<add> specify "#resolve_asset_id" do
<add> release_metadata = {
<add> "assets" => [
<add> {
<add> "id" => 123,
<add> "name" => "foo_v0.1.0_linux_amd64.tar.gz",
<add> },
<add> {
<add> "id" => 456,
<add> "name" => "foo_v0.1.0_darwin_amd64.tar.gz",
<add> },
<add> ],
<add> }
<add> allow(subject).to receive(:fetch_release_metadata).and_return(release_metadata)
<add> expect(subject.send(:resolve_asset_id)).to eq(456)
<add> end
<add>
<add> describe "#fetch_release_metadata" do
<add> it "fetches release metadata from GitHub" do
<add> expected_release_url = "https://api.github.com/repos/owner/repo/releases/tags/tag"
<add> expect(GitHub).to receive(:open).with(expected_release_url).and_return({})
<add> subject.send(:fetch_release_metadata)
<add> end
<add> end
<add>end
<add>
<add>describe GitHubGitDownloadStrategy do
<add> subject { described_class.new(name, resource) }
<add> let(:name) { "brew" }
<add> let(:url) { "https://github.com/homebrew/brew.git" }
<add> let(:resource) { double(Resource, url: url, mirrors: [], specs: {}, version: nil) }
<add>
<add> it "parses the URL and sets the corresponding instance variables" do
<add> expect(subject.instance_variable_get(:@user)).to eq("homebrew")
<add> expect(subject.instance_variable_get(:@repo)).to eq("brew")
<add> end
<add>end
<add>
<add>describe GitDownloadStrategy do
<add> subject { described_class.new(name, resource) }
<add> let(:name) { "baz" }
<add> let(:url) { "https://github.com/homebrew/foo" }
<add> let(:resource) { double(Resource, url: url, mirrors: [], specs: {}, version: nil) }
<add> let(:cached_location) { subject.cached_location }
<add>
<add> before(:each) do
<add> @commit_id = 1
<add> FileUtils.mkpath cached_location
<add> end
<add>
<add> def git_commit_all
<add> shutup do
<add> system "git", "add", "--all"
<add> system "git", "commit", "-m", "commit number #{@commit_id}"
<add> @commit_id += 1
<add> end
<add> end
<add>
<add> def setup_git_repo
<add> shutup do
<add> system "git", "init"
<add> system "git", "remote", "add", "origin", "https://github.com/Homebrew/homebrew-foo"
<add> end
<add> FileUtils.touch "README"
<add> git_commit_all
<add> end
<add>
<add> describe "#source_modified_time" do
<add> it "returns the right modification time" do
<add> cached_location.cd do
<add> setup_git_repo
<add> end
<add> expect(subject.source_modified_time.to_i).to eq(1_485_115_153)
<add> end
<add> end
<add>
<add> specify "#last_commit" do
<add> cached_location.cd do
<add> setup_git_repo
<add> FileUtils.touch "LICENSE"
<add> git_commit_all
<add> end
<add> expect(subject.last_commit).to eq("f68266e")
<add> end
<add>
<add> describe "#fetch_last_commit" do
<add> let(:url) { "file://#{remote_repo}" }
<add> let(:version) { Version.create("HEAD") }
<add> let(:resource) { double(Resource, url: url, mirrors: [], specs: {}, version: version) }
<add> let(:remote_repo) { HOMEBREW_PREFIX/"remote_repo" }
<add>
<add> before(:each) { remote_repo.mkpath }
<add>
<add> after(:each) { FileUtils.rm_rf remote_repo }
<add>
<add> it "fetches the hash of the last commit" do
<add> remote_repo.cd do
<add> setup_git_repo
<add> FileUtils.touch "LICENSE"
<add> git_commit_all
<add> end
<add>
<add> subject.shutup!
<add> expect(subject.fetch_last_commit).to eq("f68266e")
<add> end
<add> end
<add>end
<add>
<add>describe DownloadStrategyDetector do
<add> describe "::detect" do
<add> subject { described_class.detect(url) }
<add> let(:url) { Object.new }
<add>
<add> context "when given Git URL" do
<add> let(:url) { "git://example.com/foo.git" }
<add> it { is_expected.to eq(GitDownloadStrategy) }
<add> end
<add>
<add> context "when given a GitHub Git URL" do
<add> let(:url) { "https://github.com/homebrew/brew.git" }
<add> it { is_expected.to eq(GitHubGitDownloadStrategy) }
<add> end
<add>
<add> it "defaults to cURL" do
<add> expect(subject).to eq(CurlDownloadStrategy)
<add> end
<add>
<add> it "raises an error when passed an unrecognized strategy" do
<add> expect {
<add> described_class.detect("foo", Class.new)
<add> }.to raise_error(TypeError)
<add> end
<add> end
<add>end
<ide><path>Library/Homebrew/test/download_strategies_test.rb
<del>require "testing_env"
<del>require "download_strategy"
<del>
<del>class ResourceDouble
<del> attr_reader :url, :specs, :version, :mirrors
<del>
<del> def initialize(url = "http://example.com/foo.tar.gz", specs = {})
<del> @url = url
<del> @specs = specs
<del> @mirrors = []
<del> end
<del>end
<del>
<del>class AbstractDownloadStrategyTests < Homebrew::TestCase
<del> include FileUtils
<del>
<del> def setup
<del> super
<del> @name = "foo"
<del> @resource = ResourceDouble.new
<del> @strategy = AbstractDownloadStrategy.new(@name, @resource)
<del> @args = %w[foo bar baz]
<del> end
<del>
<del> def test_expand_safe_system_args_with_explicit_quiet_flag
<del> @args << { quiet_flag: "--flag" }
<del> expanded_args = @strategy.expand_safe_system_args(@args)
<del> assert_equal %w[foo bar baz --flag], expanded_args
<del> end
<del>
<del> def test_expand_safe_system_args_with_implicit_quiet_flag
<del> expanded_args = @strategy.expand_safe_system_args(@args)
<del> assert_equal %w[foo bar -q baz], expanded_args
<del> end
<del>
<del> def test_expand_safe_system_args_does_not_mutate_argument
<del> result = @strategy.expand_safe_system_args(@args)
<del> assert_equal %w[foo bar baz], @args
<del> refute_same @args, result
<del> end
<del>
<del> def test_source_modified_time
<del> mktemp "mtime" do
<del> touch "foo", mtime: Time.now - 10
<del> touch "bar", mtime: Time.now - 100
<del> ln_s "not-exist", "baz"
<del> assert_equal File.mtime("foo"), @strategy.source_modified_time
<del> end
<del> end
<del>end
<del>
<del>class VCSDownloadStrategyTests < Homebrew::TestCase
<del> def test_cache_filename
<del> resource = ResourceDouble.new("http://example.com/bar")
<del> strategy = Class.new(VCSDownloadStrategy) do
<del> def cache_tag
<del> "foo"
<del> end
<del> end
<del> downloader = strategy.new("baz", resource)
<del> assert_equal HOMEBREW_CACHE.join("baz--foo"), downloader.cached_location
<del> end
<del>end
<del>
<del>class GitHubPrivateRepositoryDownloadStrategyTests < Homebrew::TestCase
<del> def setup
<del> super
<del> resource = ResourceDouble.new("https://github.com/owner/repo/archive/1.1.5.tar.gz")
<del> ENV["HOMEBREW_GITHUB_API_TOKEN"] = "token"
<del> GitHub.stubs(:repository).returns {}
<del> @strategy = GitHubPrivateRepositoryDownloadStrategy.new("foo", resource)
<del> end
<del>
<del> def test_set_github_token
<del> assert_equal "token", @strategy.instance_variable_get(:@github_token)
<del> end
<del>
<del> def test_parse_url_pattern
<del> assert_equal "owner", @strategy.instance_variable_get(:@owner)
<del> assert_equal "repo", @strategy.instance_variable_get(:@repo)
<del> assert_equal "archive/1.1.5.tar.gz", @strategy.instance_variable_get(:@filepath)
<del> end
<del>
<del> def test_download_url
<del> expected = "https://token@github.com/owner/repo/archive/1.1.5.tar.gz"
<del> assert_equal expected, @strategy.download_url
<del> end
<del>end
<del>
<del>class GitHubPrivateRepositoryReleaseDownloadStrategyTests < Homebrew::TestCase
<del> def setup
<del> super
<del> resource = ResourceDouble.new("https://github.com/owner/repo/releases/download/tag/foo_v0.1.0_darwin_amd64.tar.gz")
<del> ENV["HOMEBREW_GITHUB_API_TOKEN"] = "token"
<del> GitHub.stubs(:repository).returns {}
<del> @strategy = GitHubPrivateRepositoryReleaseDownloadStrategy.new("foo", resource)
<del> end
<del>
<del> def test_parse_url_pattern
<del> assert_equal "owner", @strategy.instance_variable_get(:@owner)
<del> assert_equal "repo", @strategy.instance_variable_get(:@repo)
<del> assert_equal "tag", @strategy.instance_variable_get(:@tag)
<del> assert_equal "foo_v0.1.0_darwin_amd64.tar.gz", @strategy.instance_variable_get(:@filename)
<del> end
<del>
<del> def test_download_url
<del> @strategy.stubs(:resolve_asset_id).returns(456)
<del> expected = "https://token@api.github.com/repos/owner/repo/releases/assets/456"
<del> assert_equal expected, @strategy.download_url
<del> end
<del>
<del> def test_resolve_asset_id
<del> release_metadata = {
<del> "assets" => [
<del> {
<del> "id" => 123,
<del> "name" => "foo_v0.1.0_linux_amd64.tar.gz",
<del> },
<del> {
<del> "id" => 456,
<del> "name" => "foo_v0.1.0_darwin_amd64.tar.gz",
<del> },
<del> ],
<del> }
<del> @strategy.stubs(:fetch_release_metadata).returns(release_metadata)
<del> assert_equal 456, @strategy.send(:resolve_asset_id)
<del> end
<del>
<del> def test_fetch_release_metadata
<del> expected_release_url = "https://api.github.com/repos/owner/repo/releases/tags/tag"
<del> github_mock = MiniTest::Mock.new
<del> github_mock.expect :call, {}, [expected_release_url]
<del> GitHub.stub :open, github_mock do
<del> @strategy.send(:fetch_release_metadata)
<del> end
<del> github_mock.verify
<del> end
<del>end
<del>
<del>class GitDownloadStrategyTests < Homebrew::TestCase
<del> include FileUtils
<del>
<del> def setup
<del> super
<del> resource = ResourceDouble.new("https://github.com/homebrew/foo")
<del> @commit_id = 1
<del> @strategy = GitDownloadStrategy.new("baz", resource)
<del> @cached_location = @strategy.cached_location
<del> mkpath @cached_location
<del> end
<del>
<del> def git_commit_all
<del> shutup do
<del> system "git", "add", "--all"
<del> system "git", "commit", "-m", "commit number #{@commit_id}"
<del> @commit_id += 1
<del> end
<del> end
<del>
<del> def setup_git_repo
<del> @cached_location.cd do
<del> shutup do
<del> system "git", "init"
<del> system "git", "remote", "add", "origin", "https://github.com/Homebrew/homebrew-foo"
<del> end
<del> touch "README"
<del> git_commit_all
<del> end
<del> end
<del>
<del> def test_github_git_download_strategy_user_repo
<del> resource = ResourceDouble.new("https://github.com/homebrew/brew.git")
<del> strategy = GitHubGitDownloadStrategy.new("brew", resource)
<del>
<del> assert_equal strategy.instance_variable_get(:@user), "homebrew"
<del> assert_equal strategy.instance_variable_get(:@repo), "brew"
<del> end
<del>
<del> def test_source_modified_time
<del> setup_git_repo
<del> assert_equal 1_485_115_153, @strategy.source_modified_time.to_i
<del> end
<del>
<del> def test_last_commit
<del> setup_git_repo
<del> @cached_location.cd do
<del> touch "LICENSE"
<del> git_commit_all
<del> end
<del> assert_equal "f68266e", @strategy.last_commit
<del> end
<del>
<del> def test_fetch_last_commit
<del> remote_repo = HOMEBREW_PREFIX.join("remote_repo")
<del> remote_repo.mkdir
<del>
<del> resource = ResourceDouble.new("file://#{remote_repo}")
<del> resource.instance_variable_set(:@version, Version.create("HEAD"))
<del> @strategy = GitDownloadStrategy.new("baz", resource)
<del>
<del> remote_repo.cd do
<del> shutup do
<del> system "git", "init"
<del> system "git", "remote", "add", "origin", "https://github.com/Homebrew/homebrew-foo"
<del> end
<del> touch "README"
<del> git_commit_all
<del> touch "LICENSE"
<del> git_commit_all
<del> end
<del>
<del> @strategy.shutup!
<del> assert_equal "f68266e", @strategy.fetch_last_commit
<del> ensure
<del> remote_repo.rmtree if remote_repo.directory?
<del> end
<del>end
<del>
<del>class DownloadStrategyDetectorTests < Homebrew::TestCase
<del> def setup
<del> super
<del> @d = DownloadStrategyDetector.new
<del> end
<del>
<del> def test_detect_git_download_startegy
<del> @d = DownloadStrategyDetector.detect("git://example.com/foo.git")
<del> assert_equal GitDownloadStrategy, @d
<del> end
<del>
<del> def test_detect_github_git_download_strategy
<del> @d = DownloadStrategyDetector.detect("https://github.com/homebrew/brew.git")
<del> assert_equal GitHubGitDownloadStrategy, @d
<del> end
<del>
<del> def test_default_to_curl_strategy
<del> @d = DownloadStrategyDetector.detect(Object.new)
<del> assert_equal CurlDownloadStrategy, @d
<del> end
<del>
<del> def test_raises_when_passed_unrecognized_strategy
<del> assert_raises(TypeError) do
<del> DownloadStrategyDetector.detect("foo", Class.new)
<del> end
<del> end
<del>end | 2 |
Python | Python | fix linter error | 831849ea5d1a9ec0ce56f28f682cd06f8da736c5 | <ide><path>doc/conftest.py
<ide> def check_output(self, want, got, optionflags):
<ide> break
<ide> return OutputChecker.check_output(self, want, got, optionflags)
<ide>
<add>
<ide> doctest.OutputChecker = SkipMatplotlibOutputChecker
<ide>
<ide> @pytest.fixture(autouse=True) | 1 |
Javascript | Javascript | fix context access and double function call | 7812ae75d578314c1a285e9644fc75812940eb1d | <ide><path>src/ng/parse.js
<ide> function parser(text, json, $filter, csp){
<ide> text.substring(0, token.index) + "] can not be assigned to", token);
<ide> }
<ide> right = logicalOR();
<del> return function(self, locals){
<del> return left.assign(self, right(self, locals), locals);
<add> return function(scope, locals){
<add> return left.assign(scope, right(scope, locals), locals);
<ide> };
<ide> } else {
<ide> return left;
<ide> function parser(text, json, $filter, csp){
<ide> var field = expect().text;
<ide> var getter = getterFn(field, csp);
<ide> return extend(
<del> function(self, locals) {
<del> return getter(object(self, locals), locals);
<add> function(scope, locals, self) {
<add> return getter(self || object(scope, locals), locals);
<ide> },
<ide> {
<del> assign:function(self, value, locals) {
<del> return setter(object(self, locals), field, value);
<add> assign:function(scope, value, locals) {
<add> return setter(object(scope, locals), field, value);
<ide> }
<ide> }
<ide> );
<ide> function parser(text, json, $filter, csp){
<ide> } while (expect(','));
<ide> }
<ide> consume(')');
<del> return function(self, locals){
<add> return function(scope, locals){
<ide> var args = [],
<del> context = contextGetter ? contextGetter(self, locals) : self;
<add> context = contextGetter ? contextGetter(scope, locals) : scope;
<ide>
<ide> for ( var i = 0; i < argsFn.length; i++) {
<del> args.push(argsFn[i](self, locals));
<add> args.push(argsFn[i](scope, locals));
<ide> }
<del> var fnPtr = fn(self, locals) || noop;
<add> var fnPtr = fn(scope, locals, context) || noop;
<ide> // IE stupidity!
<ide> return fnPtr.apply
<ide> ? fnPtr.apply(context, args) | 1 |
Javascript | Javascript | remove smallestlabelseparation from timescale | c283867f73a5caea271304dd42480383ccd515ba | <ide><path>src/scales/scale.time.js
<ide> module.exports = function(Chart) {
<ide> me.scaleSizeInUnits = me.lastTick.diff(me.firstTick, me.tickUnit, true);
<ide> }
<ide>
<del> me.smallestLabelSeparation = me.width;
<del>
<del> helpers.each(me.chart.data.datasets, function(dataset, datasetIndex) {
<del> for (var i = 1; i < me.labelMoments[datasetIndex].length; i++) {
<del> me.smallestLabelSeparation = Math.min(me.smallestLabelSeparation, me.labelMoments[datasetIndex][i].diff(me.labelMoments[datasetIndex][i - 1], me.tickUnit, true));
<del> }
<del> }, me);
<del>
<ide> // Tick displayFormat override
<ide> if (me.options.time.displayFormat) {
<ide> me.displayFormat = me.options.time.displayFormat; | 1 |
Ruby | Ruby | use inline gemfile dependency when reporting bugs | ebd806cf4bcfabae7cabfa23bb64916e607dd41c | <ide><path>guides/bug_report_templates/action_controller_master.rb
<del>unless File.exist?('Gemfile')
<del> File.write('Gemfile', <<-GEMFILE)
<del> source 'https://rubygems.org'
<del> gem 'rails', github: 'rails/rails'
<del> gem 'arel', github: 'rails/arel'
<del> GEMFILE
<del>
<del> system 'bundle'
<del>end
<add>require 'bundler/inline'
<ide>
<del>require 'bundler'
<del>Bundler.setup(:default)
<add>gemfile(true) do
<add> source 'https://rubygems.org'
<add> gem 'rails', github: 'rails/rails'
<add> gem 'arel', github: 'rails/arel'
<add>end
<ide>
<ide> require 'rails'
<ide> require 'action_controller/railtie'
<ide><path>guides/bug_report_templates/active_record_master.rb
<del>unless File.exist?('Gemfile')
<del> File.write('Gemfile', <<-GEMFILE)
<del> source 'https://rubygems.org'
<del> gem 'rails', github: 'rails/rails'
<del> gem 'arel', github: 'rails/arel'
<del> gem 'sqlite3'
<del> GEMFILE
<del>
<del> system 'bundle'
<del>end
<add>require 'bundler/inline'
<ide>
<del>require 'bundler'
<del>Bundler.setup(:default)
<add>gemfile(true) do
<add> source 'https://rubygems.org'
<add> gem 'rails', github: 'rails/rails'
<add> gem 'arel', github: 'rails/arel'
<add> gem 'sqlite3'
<add>end
<ide>
<ide> require 'active_record'
<ide> require 'minitest/autorun'
<ide><path>guides/bug_report_templates/generic_master.rb
<del>unless File.exist?('Gemfile')
<del> File.write('Gemfile', <<-GEMFILE)
<del> source 'https://rubygems.org'
<del> gem 'rails', github: 'rails/rails'
<del> gem 'arel', github: 'rails/arel'
<del> GEMFILE
<add>require 'bundler/inline'
<ide>
<del> system 'bundle'
<add>gemfile(true) do
<add> source 'https://rubygems.org'
<add> gem 'rails', github: 'rails/rails'
<add> gem 'arel', github: 'rails/arel'
<ide> end
<ide>
<del>require 'bundler'
<del>Bundler.setup(:default)
<del>
<ide> require 'active_support'
<ide> require 'active_support/core_ext/object/blank'
<ide> require 'minitest/autorun' | 3 |
Ruby | Ruby | add missing require | d2cdbcbb18aaf667077eb46c2abc2cfd8690f919 | <ide><path>Library/Homebrew/test/test_integration_cmds.rb
<ide> require "testing_env"
<ide> require "fileutils"
<ide> require "pathname"
<add>require "formula"
<ide>
<ide> class IntegrationCommandTests < Homebrew::TestCase
<ide> def setup | 1 |
Ruby | Ruby | prevent symbol gc | 8dcfc5d0814942edfb8bb07366fd2a57bdea3512 | <ide><path>activerecord/test/cases/finder_test.rb
<ide> def test_find_passing_active_record_object_is_deprecated
<ide> end
<ide>
<ide> def test_symbols_table_ref
<add> gc_disabled = GC.disable if RUBY_VERSION >= '2.2.0'
<ide> Post.where("author_id" => nil) # warm up
<ide> x = Symbol.all_symbols.count
<ide> Post.where("title" => {"xxxqqqq" => "bar"})
<ide> assert_equal x, Symbol.all_symbols.count
<add> ensure
<add> GC.enable if gc_disabled == false
<ide> end
<ide>
<ide> # find should handle strings that come from URLs | 1 |
Javascript | Javascript | improve code coverage for sourcemap class | 6c1aa01874f437cae920ea633c949a1325492353 | <ide><path>test/parallel/test-source-map-api.js
<ide> const { readFileSync } = require('fs');
<ide> assert.notStrictEqual(payload.sources, sourceMap.payload.sources);
<ide> }
<ide>
<add>// findEntry() must return empty object instead error when
<add>// receive a malformed mappings.
<add>{
<add> const payload = JSON.parse(readFileSync(
<add> require.resolve('../fixtures/source-map/disk.map'), 'utf8'
<add> ));
<add> payload.mappings = ';;;;;;;;;';
<add>
<add> const sourceMap = new SourceMap(payload);
<add> const result = sourceMap.findEntry(0, 5);
<add> assert.strictEqual(typeof result, 'object');
<add> assert.strictEqual(Object.keys(result).length, 0);
<add>}
<add>
<ide> // Test various known decodings to ensure decodeVLQ works correctly.
<ide> {
<ide> function makeMinimalMap(column) { | 1 |
Python | Python | fix silly error. this makes more sense | bbfa404e4679f4229e44fd7e641e62fdd2e7bdd5 | <ide><path>djangorestframework/__init__.py
<del>__version__ = '0.3.2-dev'
<add>__version__ = '0.3.3-dev'
<ide>
<ide> VERSION = __version__ # synonym | 1 |
PHP | PHP | fix issue with nested named parameters | 8b3c72f7c1c7c53ed22e6ec8565cbce7bc275894 | <ide><path>lib/Cake/Routing/Route/CakeRoute.php
<ide> <?php
<ide> /**
<del> * A single Route used by the Router to connect requests to
<del> * parameter maps.
<del> *
<del> * Not normally created as a standalone. Use Router::connect() to create
<del> * Routes for your application.
<del> *
<del> * PHP5
<del> *
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide> *
<ide> *
<ide> * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide> * @link http://cakephp.org CakePHP(tm) Project
<del> * @package Cake.Routing.Route
<ide> * @since CakePHP(tm) v 1.3
<ide> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<ide> */
<add>App::uses('Set', 'Utility');
<add>
<add>/**
<add> * A single Route used by the Router to connect requests to
<add> * parameter maps.
<add> *
<add> * Not normally created as a standalone. Use Router::connect() to create
<add> * Routes for your application.
<add> *
<add> * @package Cake.Routing.Route
<add> */
<ide> class CakeRoute {
<ide>
<ide> /**
<ide> protected function _writeUrl($params) {
<ide> $named = array();
<ide> foreach ($params['named'] as $key => $value) {
<ide> if (is_array($value)) {
<del> foreach ($value as $namedKey => $namedValue) {
<add> $flat = Set::flatten($value, '][');
<add> foreach ($flat as $namedKey => $namedValue) {
<ide> $named[] = $key . "[$namedKey]" . $separator . rawurlencode($namedValue);
<ide> }
<ide> } else {
<ide><path>lib/Cake/Test/Case/Routing/Route/CakeRouteTest.php
<ide> public function testParseArrayNamedParameters() {
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide>
<add>/**
<add> * Test that match can handle array named parameters
<add> *
<add> * @return void
<add> */
<add> public function testMatchNamedParametersArray() {
<add> $route = new CakeRoute('/:controller/:action/*');
<add>
<add> $url = array(
<add> 'controller' => 'posts',
<add> 'action' => 'index',
<add> 'filter' => array(
<add> 'one',
<add> 'model' => 'value'
<add> )
<add> );
<add> $result = $route->match($url);
<add> $expected = '/posts/index/filter[0]:one/filter[model]:value';
<add> $this->assertEquals($expected, $result);
<add>
<add> $url = array(
<add> 'controller' => 'posts',
<add> 'action' => 'index',
<add> 'filter' => array(
<add> 'one',
<add> 'model' => array(
<add> 'two',
<add> 'order' => 'field'
<add> )
<add> )
<add> );
<add> $result = $route->match($url);
<add> $expected = '/posts/index/filter[0]:one/filter[model][0]:two/filter[model][order]:field';
<add> $this->assertEquals($expected, $result);
<add> }
<add>
<ide> /**
<ide> * test restructuring args with pass key
<ide> * | 2 |
PHP | PHP | add missing @throws | cc3c2366579710c01bbe3ed1caae27a7587c550d | <ide><path>src/Illuminate/Foundation/Exceptions/Handler.php
<ide> public function __construct(Container $container)
<ide> * Report or log an exception.
<ide> *
<ide> * @param \Exception $e
<add> * @throws \Exception $e
<ide> * @return void
<ide> */
<ide> public function report(Exception $e) | 1 |
Javascript | Javascript | remove reference to scope | 3fc95e06e78b3c0e3e124bc48963c9876f33a91f | <ide><path>src/ngRoute/directive/ngView.js
<ide> ngRouteModule.directive('ngView', ngViewFillContentFactory);
<ide> <pre>$location.path() = {{main.$location.path()}}</pre>
<ide> <pre>$route.current.templateUrl = {{main.$route.current.templateUrl}}</pre>
<ide> <pre>$route.current.params = {{main.$route.current.params}}</pre>
<del> <pre>$route.current.scope.name = {{main.$route.current.scope.name}}</pre>
<ide> <pre>$routeParams = {{main.$routeParams}}</pre>
<ide> </div>
<ide> </file> | 1 |
Javascript | Javascript | update code style | a5f3962ef6dae53b1bb0f19284773af2400fc56a | <ide><path>src/test/__tests__/ReactTestUtils-test.js
<ide> describe('ReactTestUtils', function() {
<ide>
<ide> it('Test scryRenderedDOMComponentsWithClass with className contains \\n', function() {
<ide> var renderedComponent = ReactTestUtils.renderIntoDocument(
<del> <div>Hello <span className={`x
<del> y`}>Jim</span></div>
<add> <div>Hello <span className={'x\ny'}>Jim</span></div>
<ide> );
<ide> var scryResults = ReactTestUtils.scryRenderedDOMComponentsWithClass(
<ide> renderedComponent, | 1 |
Javascript | Javascript | save some bytes. close gh-1071 | a270d638f84f4ac4ea419665249bdf7952671f09 | <ide><path>src/css.js
<ide> jQuery.extend({
<ide> // We should always get a number back from opacity
<ide> var ret = curCSS( elem, "opacity" );
<ide> return ret === "" ? "1" : ret;
<del>
<ide> }
<ide> }
<ide> }
<ide> if ( window.getComputedStyle ) {
<ide> function setPositiveNumber( elem, value, subtract ) {
<ide> var matches = rnumsplit.exec( value );
<ide> return matches ?
<del> Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
<del> value;
<add> // Guard against undefined "subtract", e.g., when used as in cssHooks
<add> Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
<add> value;
<ide> }
<ide>
<ide> function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
<ide> function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
<ide> function getWidthOrHeight( elem, name, extra ) {
<ide>
<ide> // Start with offset property, which is equivalent to the border-box value
<del> var val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
<del> valueIsBorderBox = true,
<add> var valueIsBorderBox = true,
<add> val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
<ide> styles = getStyles( elem ),
<ide> isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box";
<ide>
<ide> function css_defaultDisplay( nodeName ) {
<ide>
<ide> // Called ONLY from within css_defaultDisplay
<ide> function actualDisplay( name, doc ) {
<del> var elem, display;
<del> elem = jQuery( doc.createElement( name ) );
<del> display = jQuery.css( elem.appendTo( doc.body )[0], "display" );
<add> var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),
<add> display = jQuery.css( elem[0], "display" );
<ide> elem.remove();
<ide> return display;
<ide> }
<ide> if ( !jQuery.support.opacity ) {
<ide> // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
<ide> // if value === "", then remove inline opacity #12685
<ide> if ( ( value >= 1 || value === "" ) &&
<del> jQuery.trim( filter.replace( ralpha, "" ) ) === "" &&
<del> style.removeAttribute ) {
<add> jQuery.trim( filter.replace( ralpha, "" ) ) === "" &&
<add> style.removeAttribute ) {
<ide>
<ide> // Setting style.filter to null, "" & " " still leave "filter:" in the cssText
<ide> // if "filter:" is present at all, clearType is disabled, we want to avoid this
<ide> jQuery(function() {
<ide> jQuery.each( [ "top", "left" ], function( i, prop ) {
<ide> jQuery.cssHooks[ prop ] = {
<ide> get: function( elem, computed ) {
<add> var ret;
<ide> if ( computed ) {
<del> var ret = curCSS( elem, prop );
<add> ret = curCSS( elem, prop );
<ide> // if curCSS returns percentage, fallback to offset
<ide> return rnumnonpx.test( ret ) ? jQuery( elem ).position()[ prop ] + "px" : ret;
<ide> }
<ide> jQuery.each({
<ide> }, function( prefix, suffix ) {
<ide> jQuery.cssHooks[ prefix + suffix ] = {
<ide> expand: function( value ) {
<del> var i,
<add> var i = 0,
<ide>
<ide> // assumes a single number if not a string
<ide> parts = typeof value === "string" ? value.split(" ") : [ value ],
<ide> expanded = {};
<ide>
<del> for ( i = 0; i < 4; i++ ) {
<add> for ( ; i < 4; i++ ) {
<ide> expanded[ prefix + cssExpand[ i ] + suffix ] =
<ide> parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
<ide> } | 1 |
Python | Python | add model_builder and feature_map_extractor back | a703fc0c979aad61ff8994b2098289259ba99d04 | <ide><path>research/object_detection/builders/model_builder.py
<add># Copyright 2017 The TensorFlow Authors. All Rights Reserved.
<add>#
<add># Licensed under the Apache License, Version 2.0 (the "License");
<add># you may not use this file except in compliance with the License.
<add># You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing, software
<add># distributed under the License is distributed on an "AS IS" BASIS,
<add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add># See the License for the specific language governing permissions and
<add># limitations under the License.
<add># ==============================================================================
<add>
<add>"""A function to build a DetectionModel from configuration."""
<add>from object_detection.builders import anchor_generator_builder
<add>from object_detection.builders import box_coder_builder
<add>from object_detection.builders import box_predictor_builder
<add>from object_detection.builders import hyperparams_builder
<add>from object_detection.builders import image_resizer_builder
<add>from object_detection.builders import losses_builder
<add>from object_detection.builders import matcher_builder
<add>from object_detection.builders import post_processing_builder
<add>from object_detection.builders import region_similarity_calculator_builder as sim_calc
<add>from object_detection.core import box_predictor
<add>from object_detection.meta_architectures import faster_rcnn_meta_arch
<add>from object_detection.meta_architectures import rfcn_meta_arch
<add>from object_detection.meta_architectures import ssd_meta_arch
<add>from object_detection.models import faster_rcnn_inception_resnet_v2_feature_extractor as frcnn_inc_res
<add>from object_detection.models import faster_rcnn_inception_v2_feature_extractor as frcnn_inc_v2
<add>from object_detection.models import faster_rcnn_nas_feature_extractor as frcnn_nas
<add>from object_detection.models import faster_rcnn_pnas_feature_extractor as frcnn_pnas
<add>from object_detection.models import faster_rcnn_resnet_v1_feature_extractor as frcnn_resnet_v1
<add>from object_detection.models import ssd_resnet_v1_fpn_feature_extractor as ssd_resnet_v1_fpn
<add>from object_detection.models.embedded_ssd_mobilenet_v1_feature_extractor import EmbeddedSSDMobileNetV1FeatureExtractor
<add>from object_detection.models.ssd_inception_v2_feature_extractor import SSDInceptionV2FeatureExtractor
<add>from object_detection.models.ssd_inception_v3_feature_extractor import SSDInceptionV3FeatureExtractor
<add>from object_detection.models.ssd_mobilenet_v1_feature_extractor import SSDMobileNetV1FeatureExtractor
<add>from object_detection.models.ssd_mobilenet_v2_feature_extractor import SSDMobileNetV2FeatureExtractor
<add>from object_detection.protos import model_pb2
<add>
<add># A map of names to SSD feature extractors.
<add>SSD_FEATURE_EXTRACTOR_CLASS_MAP = {
<add> 'ssd_inception_v2': SSDInceptionV2FeatureExtractor,
<add> 'ssd_inception_v3': SSDInceptionV3FeatureExtractor,
<add> 'ssd_mobilenet_v1': SSDMobileNetV1FeatureExtractor,
<add> 'ssd_mobilenet_v2': SSDMobileNetV2FeatureExtractor,
<add> 'ssd_resnet50_v1_fpn': ssd_resnet_v1_fpn.SSDResnet50V1FpnFeatureExtractor,
<add> 'ssd_resnet101_v1_fpn': ssd_resnet_v1_fpn.SSDResnet101V1FpnFeatureExtractor,
<add> 'ssd_resnet152_v1_fpn': ssd_resnet_v1_fpn.SSDResnet152V1FpnFeatureExtractor,
<add> 'embedded_ssd_mobilenet_v1': EmbeddedSSDMobileNetV1FeatureExtractor,
<add>}
<add>
<add># A map of names to Faster R-CNN feature extractors.
<add>FASTER_RCNN_FEATURE_EXTRACTOR_CLASS_MAP = {
<add> 'faster_rcnn_nas':
<add> frcnn_nas.FasterRCNNNASFeatureExtractor,
<add> 'faster_rcnn_pnas':
<add> frcnn_pnas.FasterRCNNPNASFeatureExtractor,
<add> 'faster_rcnn_inception_resnet_v2':
<add> frcnn_inc_res.FasterRCNNInceptionResnetV2FeatureExtractor,
<add> 'faster_rcnn_inception_v2':
<add> frcnn_inc_v2.FasterRCNNInceptionV2FeatureExtractor,
<add> 'faster_rcnn_resnet50':
<add> frcnn_resnet_v1.FasterRCNNResnet50FeatureExtractor,
<add> 'faster_rcnn_resnet101':
<add> frcnn_resnet_v1.FasterRCNNResnet101FeatureExtractor,
<add> 'faster_rcnn_resnet152':
<add> frcnn_resnet_v1.FasterRCNNResnet152FeatureExtractor,
<add>}
<add>
<add>
<add>def build(model_config, is_training, add_summaries=True,
<add> add_background_class=True):
<add> """Builds a DetectionModel based on the model config.
<add>
<add> Args:
<add> model_config: A model.proto object containing the config for the desired
<add> DetectionModel.
<add> is_training: True if this model is being built for training purposes.
<add> add_summaries: Whether to add tensorflow summaries in the model graph.
<add> add_background_class: Whether to add an implicit background class to one-hot
<add> encodings of groundtruth labels. Set to false if using groundtruth labels
<add> with an explicit background class or using multiclass scores instead of
<add> truth in the case of distillation. Ignored in the case of faster_rcnn.
<add> Returns:
<add> DetectionModel based on the config.
<add>
<add> Raises:
<add> ValueError: On invalid meta architecture or model.
<add> """
<add> if not isinstance(model_config, model_pb2.DetectionModel):
<add> raise ValueError('model_config not of type model_pb2.DetectionModel.')
<add> meta_architecture = model_config.WhichOneof('model')
<add> if meta_architecture == 'ssd':
<add> return _build_ssd_model(model_config.ssd, is_training, add_summaries,
<add> add_background_class)
<add> if meta_architecture == 'faster_rcnn':
<add> return _build_faster_rcnn_model(model_config.faster_rcnn, is_training,
<add> add_summaries)
<add> raise ValueError('Unknown meta architecture: {}'.format(meta_architecture))
<add>
<add>
<add>def _build_ssd_feature_extractor(feature_extractor_config, is_training,
<add> reuse_weights=None):
<add> """Builds a ssd_meta_arch.SSDFeatureExtractor based on config.
<add>
<add> Args:
<add> feature_extractor_config: A SSDFeatureExtractor proto config from ssd.proto.
<add> is_training: True if this feature extractor is being built for training.
<add> reuse_weights: if the feature extractor should reuse weights.
<add>
<add> Returns:
<add> ssd_meta_arch.SSDFeatureExtractor based on config.
<add>
<add> Raises:
<add> ValueError: On invalid feature extractor type.
<add> """
<add> feature_type = feature_extractor_config.type
<add> depth_multiplier = feature_extractor_config.depth_multiplier
<add> min_depth = feature_extractor_config.min_depth
<add> pad_to_multiple = feature_extractor_config.pad_to_multiple
<add> use_explicit_padding = feature_extractor_config.use_explicit_padding
<add> use_depthwise = feature_extractor_config.use_depthwise
<add> conv_hyperparams = hyperparams_builder.build(
<add> feature_extractor_config.conv_hyperparams, is_training)
<add> override_base_feature_extractor_hyperparams = (
<add> feature_extractor_config.override_base_feature_extractor_hyperparams)
<add>
<add> if feature_type not in SSD_FEATURE_EXTRACTOR_CLASS_MAP:
<add> raise ValueError('Unknown ssd feature_extractor: {}'.format(feature_type))
<add>
<add> feature_extractor_class = SSD_FEATURE_EXTRACTOR_CLASS_MAP[feature_type]
<add> return feature_extractor_class(
<add> is_training, depth_multiplier, min_depth, pad_to_multiple,
<add> conv_hyperparams, reuse_weights, use_explicit_padding, use_depthwise,
<add> override_base_feature_extractor_hyperparams)
<add>
<add>
<add>def _build_ssd_model(ssd_config, is_training, add_summaries,
<add> add_background_class=True):
<add> """Builds an SSD detection model based on the model config.
<add>
<add> Args:
<add> ssd_config: A ssd.proto object containing the config for the desired
<add> SSDMetaArch.
<add> is_training: True if this model is being built for training purposes.
<add> add_summaries: Whether to add tf summaries in the model.
<add> add_background_class: Whether to add an implicit background class to one-hot
<add> encodings of groundtruth labels. Set to false if using groundtruth labels
<add> with an explicit background class or using multiclass scores instead of
<add> truth in the case of distillation.
<add> Returns:
<add> SSDMetaArch based on the config.
<add>
<add> Raises:
<add> ValueError: If ssd_config.type is not recognized (i.e. not registered in
<add> model_class_map).
<add> """
<add> num_classes = ssd_config.num_classes
<add>
<add> # Feature extractor
<add> feature_extractor = _build_ssd_feature_extractor(
<add> feature_extractor_config=ssd_config.feature_extractor,
<add> is_training=is_training)
<add>
<add> box_coder = box_coder_builder.build(ssd_config.box_coder)
<add> matcher = matcher_builder.build(ssd_config.matcher)
<add> region_similarity_calculator = sim_calc.build(
<add> ssd_config.similarity_calculator)
<add> encode_background_as_zeros = ssd_config.encode_background_as_zeros
<add> negative_class_weight = ssd_config.negative_class_weight
<add> ssd_box_predictor = box_predictor_builder.build(hyperparams_builder.build,
<add> ssd_config.box_predictor,
<add> is_training, num_classes)
<add> anchor_generator = anchor_generator_builder.build(
<add> ssd_config.anchor_generator)
<add> image_resizer_fn = image_resizer_builder.build(ssd_config.image_resizer)
<add> non_max_suppression_fn, score_conversion_fn = post_processing_builder.build(
<add> ssd_config.post_processing)
<add> (classification_loss, localization_loss, classification_weight,
<add> localization_weight, hard_example_miner,
<add> random_example_sampler) = losses_builder.build(ssd_config.loss)
<add> normalize_loss_by_num_matches = ssd_config.normalize_loss_by_num_matches
<add> normalize_loc_loss_by_codesize = ssd_config.normalize_loc_loss_by_codesize
<add>
<add> return ssd_meta_arch.SSDMetaArch(
<add> is_training,
<add> anchor_generator,
<add> ssd_box_predictor,
<add> box_coder,
<add> feature_extractor,
<add> matcher,
<add> region_similarity_calculator,
<add> encode_background_as_zeros,
<add> negative_class_weight,
<add> image_resizer_fn,
<add> non_max_suppression_fn,
<add> score_conversion_fn,
<add> classification_loss,
<add> localization_loss,
<add> classification_weight,
<add> localization_weight,
<add> normalize_loss_by_num_matches,
<add> hard_example_miner,
<add> add_summaries=add_summaries,
<add> normalize_loc_loss_by_codesize=normalize_loc_loss_by_codesize,
<add> freeze_batchnorm=ssd_config.freeze_batchnorm,
<add> inplace_batchnorm_update=ssd_config.inplace_batchnorm_update,
<add> add_background_class=add_background_class,
<add> random_example_sampler=random_example_sampler)
<add>
<add>
<add>def _build_faster_rcnn_feature_extractor(
<add> feature_extractor_config, is_training, reuse_weights=None,
<add> inplace_batchnorm_update=False):
<add> """Builds a faster_rcnn_meta_arch.FasterRCNNFeatureExtractor based on config.
<add>
<add> Args:
<add> feature_extractor_config: A FasterRcnnFeatureExtractor proto config from
<add> faster_rcnn.proto.
<add> is_training: True if this feature extractor is being built for training.
<add> reuse_weights: if the feature extractor should reuse weights.
<add> inplace_batchnorm_update: Whether to update batch_norm inplace during
<add> training. This is required for batch norm to work correctly on TPUs. When
<add> this is false, user must add a control dependency on
<add> tf.GraphKeys.UPDATE_OPS for train/loss op in order to update the batch
<add> norm moving average parameters.
<add>
<add> Returns:
<add> faster_rcnn_meta_arch.FasterRCNNFeatureExtractor based on config.
<add>
<add> Raises:
<add> ValueError: On invalid feature extractor type.
<add> """
<add> if inplace_batchnorm_update:
<add> raise ValueError('inplace batchnorm updates not supported.')
<add> feature_type = feature_extractor_config.type
<add> first_stage_features_stride = (
<add> feature_extractor_config.first_stage_features_stride)
<add> batch_norm_trainable = feature_extractor_config.batch_norm_trainable
<add>
<add> if feature_type not in FASTER_RCNN_FEATURE_EXTRACTOR_CLASS_MAP:
<add> raise ValueError('Unknown Faster R-CNN feature_extractor: {}'.format(
<add> feature_type))
<add> feature_extractor_class = FASTER_RCNN_FEATURE_EXTRACTOR_CLASS_MAP[
<add> feature_type]
<add> return feature_extractor_class(
<add> is_training, first_stage_features_stride,
<add> batch_norm_trainable, reuse_weights)
<add>
<add>
<add>def _build_faster_rcnn_model(frcnn_config, is_training, add_summaries):
<add> """Builds a Faster R-CNN or R-FCN detection model based on the model config.
<add>
<add> Builds R-FCN model if the second_stage_box_predictor in the config is of type
<add> `rfcn_box_predictor` else builds a Faster R-CNN model.
<add>
<add> Args:
<add> frcnn_config: A faster_rcnn.proto object containing the config for the
<add> desired FasterRCNNMetaArch or RFCNMetaArch.
<add> is_training: True if this model is being built for training purposes.
<add> add_summaries: Whether to add tf summaries in the model.
<add>
<add> Returns:
<add> FasterRCNNMetaArch based on the config.
<add>
<add> Raises:
<add> ValueError: If frcnn_config.type is not recognized (i.e. not registered in
<add> model_class_map).
<add> """
<add> num_classes = frcnn_config.num_classes
<add> image_resizer_fn = image_resizer_builder.build(frcnn_config.image_resizer)
<add>
<add> feature_extractor = _build_faster_rcnn_feature_extractor(
<add> frcnn_config.feature_extractor, is_training,
<add> frcnn_config.inplace_batchnorm_update)
<add>
<add> number_of_stages = frcnn_config.number_of_stages
<add> first_stage_anchor_generator = anchor_generator_builder.build(
<add> frcnn_config.first_stage_anchor_generator)
<add>
<add> first_stage_atrous_rate = frcnn_config.first_stage_atrous_rate
<add> first_stage_box_predictor_arg_scope_fn = hyperparams_builder.build(
<add> frcnn_config.first_stage_box_predictor_conv_hyperparams, is_training)
<add> first_stage_box_predictor_kernel_size = (
<add> frcnn_config.first_stage_box_predictor_kernel_size)
<add> first_stage_box_predictor_depth = frcnn_config.first_stage_box_predictor_depth
<add> first_stage_minibatch_size = frcnn_config.first_stage_minibatch_size
<add> first_stage_positive_balance_fraction = (
<add> frcnn_config.first_stage_positive_balance_fraction)
<add> first_stage_nms_score_threshold = frcnn_config.first_stage_nms_score_threshold
<add> first_stage_nms_iou_threshold = frcnn_config.first_stage_nms_iou_threshold
<add> first_stage_max_proposals = frcnn_config.first_stage_max_proposals
<add> first_stage_loc_loss_weight = (
<add> frcnn_config.first_stage_localization_loss_weight)
<add> first_stage_obj_loss_weight = frcnn_config.first_stage_objectness_loss_weight
<add>
<add> initial_crop_size = frcnn_config.initial_crop_size
<add> maxpool_kernel_size = frcnn_config.maxpool_kernel_size
<add> maxpool_stride = frcnn_config.maxpool_stride
<add>
<add> second_stage_box_predictor = box_predictor_builder.build(
<add> hyperparams_builder.build,
<add> frcnn_config.second_stage_box_predictor,
<add> is_training=is_training,
<add> num_classes=num_classes)
<add> second_stage_batch_size = frcnn_config.second_stage_batch_size
<add> second_stage_balance_fraction = frcnn_config.second_stage_balance_fraction
<add> (second_stage_non_max_suppression_fn, second_stage_score_conversion_fn
<add> ) = post_processing_builder.build(frcnn_config.second_stage_post_processing)
<add> second_stage_localization_loss_weight = (
<add> frcnn_config.second_stage_localization_loss_weight)
<add> second_stage_classification_loss = (
<add> losses_builder.build_faster_rcnn_classification_loss(
<add> frcnn_config.second_stage_classification_loss))
<add> second_stage_classification_loss_weight = (
<add> frcnn_config.second_stage_classification_loss_weight)
<add> second_stage_mask_prediction_loss_weight = (
<add> frcnn_config.second_stage_mask_prediction_loss_weight)
<add>
<add> hard_example_miner = None
<add> if frcnn_config.HasField('hard_example_miner'):
<add> hard_example_miner = losses_builder.build_hard_example_miner(
<add> frcnn_config.hard_example_miner,
<add> second_stage_classification_loss_weight,
<add> second_stage_localization_loss_weight)
<add>
<add> common_kwargs = {
<add> 'is_training': is_training,
<add> 'num_classes': num_classes,
<add> 'image_resizer_fn': image_resizer_fn,
<add> 'feature_extractor': feature_extractor,
<add> 'number_of_stages': number_of_stages,
<add> 'first_stage_anchor_generator': first_stage_anchor_generator,
<add> 'first_stage_atrous_rate': first_stage_atrous_rate,
<add> 'first_stage_box_predictor_arg_scope_fn':
<add> first_stage_box_predictor_arg_scope_fn,
<add> 'first_stage_box_predictor_kernel_size':
<add> first_stage_box_predictor_kernel_size,
<add> 'first_stage_box_predictor_depth': first_stage_box_predictor_depth,
<add> 'first_stage_minibatch_size': first_stage_minibatch_size,
<add> 'first_stage_positive_balance_fraction':
<add> first_stage_positive_balance_fraction,
<add> 'first_stage_nms_score_threshold': first_stage_nms_score_threshold,
<add> 'first_stage_nms_iou_threshold': first_stage_nms_iou_threshold,
<add> 'first_stage_max_proposals': first_stage_max_proposals,
<add> 'first_stage_localization_loss_weight': first_stage_loc_loss_weight,
<add> 'first_stage_objectness_loss_weight': first_stage_obj_loss_weight,
<add> 'second_stage_batch_size': second_stage_batch_size,
<add> 'second_stage_balance_fraction': second_stage_balance_fraction,
<add> 'second_stage_non_max_suppression_fn':
<add> second_stage_non_max_suppression_fn,
<add> 'second_stage_score_conversion_fn': second_stage_score_conversion_fn,
<add> 'second_stage_localization_loss_weight':
<add> second_stage_localization_loss_weight,
<add> 'second_stage_classification_loss':
<add> second_stage_classification_loss,
<add> 'second_stage_classification_loss_weight':
<add> second_stage_classification_loss_weight,
<add> 'hard_example_miner': hard_example_miner,
<add> 'add_summaries': add_summaries}
<add>
<add> if isinstance(second_stage_box_predictor, box_predictor.RfcnBoxPredictor):
<add> return rfcn_meta_arch.RFCNMetaArch(
<add> second_stage_rfcn_box_predictor=second_stage_box_predictor,
<add> **common_kwargs)
<add> else:
<add> return faster_rcnn_meta_arch.FasterRCNNMetaArch(
<add> initial_crop_size=initial_crop_size,
<add> maxpool_kernel_size=maxpool_kernel_size,
<add> maxpool_stride=maxpool_stride,
<add> second_stage_mask_rcnn_box_predictor=second_stage_box_predictor,
<add> second_stage_mask_prediction_loss_weight=(
<add> second_stage_mask_prediction_loss_weight),
<add> **common_kwargs)
<ide><path>research/object_detection/builders/model_builder_test.py
<add># Copyright 2017 The TensorFlow Authors. All Rights Reserved.
<add>#
<add># Licensed under the Apache License, Version 2.0 (the "License");
<add># you may not use this file except in compliance with the License.
<add># You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing, software
<add># distributed under the License is distributed on an "AS IS" BASIS,
<add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add># See the License for the specific language governing permissions and
<add># limitations under the License.
<add># ==============================================================================
<add>
<add>"""Tests for object_detection.models.model_builder."""
<add>
<add>import tensorflow as tf
<add>
<add>from google.protobuf import text_format
<add>from object_detection.builders import model_builder
<add>from object_detection.meta_architectures import faster_rcnn_meta_arch
<add>from object_detection.meta_architectures import rfcn_meta_arch
<add>from object_detection.meta_architectures import ssd_meta_arch
<add>from object_detection.models import faster_rcnn_inception_resnet_v2_feature_extractor as frcnn_inc_res
<add>from object_detection.models import faster_rcnn_inception_v2_feature_extractor as frcnn_inc_v2
<add>from object_detection.models import faster_rcnn_nas_feature_extractor as frcnn_nas
<add>from object_detection.models import faster_rcnn_pnas_feature_extractor as frcnn_pnas
<add>from object_detection.models import faster_rcnn_resnet_v1_feature_extractor as frcnn_resnet_v1
<add>from object_detection.models import ssd_resnet_v1_fpn_feature_extractor as ssd_resnet_v1_fpn
<add>from object_detection.models.embedded_ssd_mobilenet_v1_feature_extractor import EmbeddedSSDMobileNetV1FeatureExtractor
<add>from object_detection.models.ssd_inception_v2_feature_extractor import SSDInceptionV2FeatureExtractor
<add>from object_detection.models.ssd_inception_v3_feature_extractor import SSDInceptionV3FeatureExtractor
<add>from object_detection.models.ssd_mobilenet_v1_feature_extractor import SSDMobileNetV1FeatureExtractor
<add>from object_detection.models.ssd_mobilenet_v2_feature_extractor import SSDMobileNetV2FeatureExtractor
<add>from object_detection.protos import model_pb2
<add>
<add>FRCNN_RESNET_FEAT_MAPS = {
<add> 'faster_rcnn_resnet50':
<add> frcnn_resnet_v1.FasterRCNNResnet50FeatureExtractor,
<add> 'faster_rcnn_resnet101':
<add> frcnn_resnet_v1.FasterRCNNResnet101FeatureExtractor,
<add> 'faster_rcnn_resnet152':
<add> frcnn_resnet_v1.FasterRCNNResnet152FeatureExtractor
<add>}
<add>
<add>SSD_RESNET_V1_FPN_FEAT_MAPS = {
<add> 'ssd_resnet50_v1_fpn':
<add> ssd_resnet_v1_fpn.SSDResnet50V1FpnFeatureExtractor,
<add> 'ssd_resnet101_v1_fpn':
<add> ssd_resnet_v1_fpn.SSDResnet101V1FpnFeatureExtractor,
<add> 'ssd_resnet152_v1_fpn':
<add> ssd_resnet_v1_fpn.SSDResnet152V1FpnFeatureExtractor
<add>}
<add>
<add>
<add>class ModelBuilderTest(tf.test.TestCase):
<add>
<add> def create_model(self, model_config):
<add> """Builds a DetectionModel based on the model config.
<add>
<add> Args:
<add> model_config: A model.proto object containing the config for the desired
<add> DetectionModel.
<add>
<add> Returns:
<add> DetectionModel based on the config.
<add> """
<add> return model_builder.build(model_config, is_training=True)
<add>
<add> def test_create_ssd_inception_v2_model_from_config(self):
<add> model_text_proto = """
<add> ssd {
<add> feature_extractor {
<add> type: 'ssd_inception_v2'
<add> conv_hyperparams {
<add> regularizer {
<add> l2_regularizer {
<add> }
<add> }
<add> initializer {
<add> truncated_normal_initializer {
<add> }
<add> }
<add> }
<add> override_base_feature_extractor_hyperparams: true
<add> }
<add> box_coder {
<add> faster_rcnn_box_coder {
<add> }
<add> }
<add> matcher {
<add> argmax_matcher {
<add> }
<add> }
<add> similarity_calculator {
<add> iou_similarity {
<add> }
<add> }
<add> anchor_generator {
<add> ssd_anchor_generator {
<add> aspect_ratios: 1.0
<add> }
<add> }
<add> image_resizer {
<add> fixed_shape_resizer {
<add> height: 320
<add> width: 320
<add> }
<add> }
<add> box_predictor {
<add> convolutional_box_predictor {
<add> conv_hyperparams {
<add> regularizer {
<add> l2_regularizer {
<add> }
<add> }
<add> initializer {
<add> truncated_normal_initializer {
<add> }
<add> }
<add> }
<add> }
<add> }
<add> loss {
<add> classification_loss {
<add> weighted_softmax {
<add> }
<add> }
<add> localization_loss {
<add> weighted_smooth_l1 {
<add> }
<add> }
<add> }
<add> }"""
<add> model_proto = model_pb2.DetectionModel()
<add> text_format.Merge(model_text_proto, model_proto)
<add> model = self.create_model(model_proto)
<add> self.assertIsInstance(model, ssd_meta_arch.SSDMetaArch)
<add> self.assertIsInstance(model._feature_extractor,
<add> SSDInceptionV2FeatureExtractor)
<add>
<add> def test_create_ssd_inception_v3_model_from_config(self):
<add> model_text_proto = """
<add> ssd {
<add> feature_extractor {
<add> type: 'ssd_inception_v3'
<add> conv_hyperparams {
<add> regularizer {
<add> l2_regularizer {
<add> }
<add> }
<add> initializer {
<add> truncated_normal_initializer {
<add> }
<add> }
<add> }
<add> override_base_feature_extractor_hyperparams: true
<add> }
<add> box_coder {
<add> faster_rcnn_box_coder {
<add> }
<add> }
<add> matcher {
<add> argmax_matcher {
<add> }
<add> }
<add> similarity_calculator {
<add> iou_similarity {
<add> }
<add> }
<add> anchor_generator {
<add> ssd_anchor_generator {
<add> aspect_ratios: 1.0
<add> }
<add> }
<add> image_resizer {
<add> fixed_shape_resizer {
<add> height: 320
<add> width: 320
<add> }
<add> }
<add> box_predictor {
<add> convolutional_box_predictor {
<add> conv_hyperparams {
<add> regularizer {
<add> l2_regularizer {
<add> }
<add> }
<add> initializer {
<add> truncated_normal_initializer {
<add> }
<add> }
<add> }
<add> }
<add> }
<add> loss {
<add> classification_loss {
<add> weighted_softmax {
<add> }
<add> }
<add> localization_loss {
<add> weighted_smooth_l1 {
<add> }
<add> }
<add> }
<add> }"""
<add> model_proto = model_pb2.DetectionModel()
<add> text_format.Merge(model_text_proto, model_proto)
<add> model = self.create_model(model_proto)
<add> self.assertIsInstance(model, ssd_meta_arch.SSDMetaArch)
<add> self.assertIsInstance(model._feature_extractor,
<add> SSDInceptionV3FeatureExtractor)
<add>
<add> def test_create_ssd_resnet_v1_fpn_model_from_config(self):
<add> model_text_proto = """
<add> ssd {
<add> feature_extractor {
<add> type: 'ssd_resnet50_v1_fpn'
<add> conv_hyperparams {
<add> regularizer {
<add> l2_regularizer {
<add> }
<add> }
<add> initializer {
<add> truncated_normal_initializer {
<add> }
<add> }
<add> }
<add> }
<add> box_coder {
<add> faster_rcnn_box_coder {
<add> }
<add> }
<add> matcher {
<add> argmax_matcher {
<add> }
<add> }
<add> similarity_calculator {
<add> iou_similarity {
<add> }
<add> }
<add> encode_background_as_zeros: true
<add> anchor_generator {
<add> multiscale_anchor_generator {
<add> aspect_ratios: [1.0, 2.0, 0.5]
<add> scales_per_octave: 2
<add> }
<add> }
<add> image_resizer {
<add> fixed_shape_resizer {
<add> height: 320
<add> width: 320
<add> }
<add> }
<add> box_predictor {
<add> weight_shared_convolutional_box_predictor {
<add> depth: 32
<add> conv_hyperparams {
<add> regularizer {
<add> l2_regularizer {
<add> }
<add> }
<add> initializer {
<add> random_normal_initializer {
<add> }
<add> }
<add> }
<add> num_layers_before_predictor: 1
<add> }
<add> }
<add> normalize_loss_by_num_matches: true
<add> normalize_loc_loss_by_codesize: true
<add> loss {
<add> classification_loss {
<add> weighted_sigmoid_focal {
<add> alpha: 0.25
<add> gamma: 2.0
<add> }
<add> }
<add> localization_loss {
<add> weighted_smooth_l1 {
<add> delta: 0.1
<add> }
<add> }
<add> classification_weight: 1.0
<add> localization_weight: 1.0
<add> }
<add> }"""
<add> model_proto = model_pb2.DetectionModel()
<add> text_format.Merge(model_text_proto, model_proto)
<add>
<add> for extractor_type, extractor_class in SSD_RESNET_V1_FPN_FEAT_MAPS.items():
<add> model_proto.ssd.feature_extractor.type = extractor_type
<add> model = model_builder.build(model_proto, is_training=True)
<add> self.assertIsInstance(model, ssd_meta_arch.SSDMetaArch)
<add> self.assertIsInstance(model._feature_extractor, extractor_class)
<add>
<add> def test_create_ssd_mobilenet_v1_model_from_config(self):
<add> model_text_proto = """
<add> ssd {
<add> freeze_batchnorm: true
<add> inplace_batchnorm_update: true
<add> feature_extractor {
<add> type: 'ssd_mobilenet_v1'
<add> conv_hyperparams {
<add> regularizer {
<add> l2_regularizer {
<add> }
<add> }
<add> initializer {
<add> truncated_normal_initializer {
<add> }
<add> }
<add> }
<add> }
<add> box_coder {
<add> faster_rcnn_box_coder {
<add> }
<add> }
<add> matcher {
<add> argmax_matcher {
<add> }
<add> }
<add> similarity_calculator {
<add> iou_similarity {
<add> }
<add> }
<add> anchor_generator {
<add> ssd_anchor_generator {
<add> aspect_ratios: 1.0
<add> }
<add> }
<add> image_resizer {
<add> fixed_shape_resizer {
<add> height: 320
<add> width: 320
<add> }
<add> }
<add> box_predictor {
<add> convolutional_box_predictor {
<add> conv_hyperparams {
<add> regularizer {
<add> l2_regularizer {
<add> }
<add> }
<add> initializer {
<add> truncated_normal_initializer {
<add> }
<add> }
<add> }
<add> }
<add> }
<add> normalize_loc_loss_by_codesize: true
<add> loss {
<add> classification_loss {
<add> weighted_softmax {
<add> }
<add> }
<add> localization_loss {
<add> weighted_smooth_l1 {
<add> }
<add> }
<add> }
<add> }"""
<add> model_proto = model_pb2.DetectionModel()
<add> text_format.Merge(model_text_proto, model_proto)
<add> model = self.create_model(model_proto)
<add> self.assertIsInstance(model, ssd_meta_arch.SSDMetaArch)
<add> self.assertIsInstance(model._feature_extractor,
<add> SSDMobileNetV1FeatureExtractor)
<add> self.assertTrue(model._normalize_loc_loss_by_codesize)
<add> self.assertTrue(model._freeze_batchnorm)
<add> self.assertTrue(model._inplace_batchnorm_update)
<add>
<add> def test_create_ssd_mobilenet_v2_model_from_config(self):
<add> model_text_proto = """
<add> ssd {
<add> feature_extractor {
<add> type: 'ssd_mobilenet_v2'
<add> conv_hyperparams {
<add> regularizer {
<add> l2_regularizer {
<add> }
<add> }
<add> initializer {
<add> truncated_normal_initializer {
<add> }
<add> }
<add> }
<add> }
<add> box_coder {
<add> faster_rcnn_box_coder {
<add> }
<add> }
<add> matcher {
<add> argmax_matcher {
<add> }
<add> }
<add> similarity_calculator {
<add> iou_similarity {
<add> }
<add> }
<add> anchor_generator {
<add> ssd_anchor_generator {
<add> aspect_ratios: 1.0
<add> }
<add> }
<add> image_resizer {
<add> fixed_shape_resizer {
<add> height: 320
<add> width: 320
<add> }
<add> }
<add> box_predictor {
<add> convolutional_box_predictor {
<add> conv_hyperparams {
<add> regularizer {
<add> l2_regularizer {
<add> }
<add> }
<add> initializer {
<add> truncated_normal_initializer {
<add> }
<add> }
<add> }
<add> }
<add> }
<add> normalize_loc_loss_by_codesize: true
<add> loss {
<add> classification_loss {
<add> weighted_softmax {
<add> }
<add> }
<add> localization_loss {
<add> weighted_smooth_l1 {
<add> }
<add> }
<add> }
<add> }"""
<add> model_proto = model_pb2.DetectionModel()
<add> text_format.Merge(model_text_proto, model_proto)
<add> model = self.create_model(model_proto)
<add> self.assertIsInstance(model, ssd_meta_arch.SSDMetaArch)
<add> self.assertIsInstance(model._feature_extractor,
<add> SSDMobileNetV2FeatureExtractor)
<add> self.assertTrue(model._normalize_loc_loss_by_codesize)
<add>
<add> def test_create_embedded_ssd_mobilenet_v1_model_from_config(self):
<add> model_text_proto = """
<add> ssd {
<add> feature_extractor {
<add> type: 'embedded_ssd_mobilenet_v1'
<add> conv_hyperparams {
<add> regularizer {
<add> l2_regularizer {
<add> }
<add> }
<add> initializer {
<add> truncated_normal_initializer {
<add> }
<add> }
<add> }
<add> }
<add> box_coder {
<add> faster_rcnn_box_coder {
<add> }
<add> }
<add> matcher {
<add> argmax_matcher {
<add> }
<add> }
<add> similarity_calculator {
<add> iou_similarity {
<add> }
<add> }
<add> anchor_generator {
<add> ssd_anchor_generator {
<add> aspect_ratios: 1.0
<add> }
<add> }
<add> image_resizer {
<add> fixed_shape_resizer {
<add> height: 256
<add> width: 256
<add> }
<add> }
<add> box_predictor {
<add> convolutional_box_predictor {
<add> conv_hyperparams {
<add> regularizer {
<add> l2_regularizer {
<add> }
<add> }
<add> initializer {
<add> truncated_normal_initializer {
<add> }
<add> }
<add> }
<add> }
<add> }
<add> loss {
<add> classification_loss {
<add> weighted_softmax {
<add> }
<add> }
<add> localization_loss {
<add> weighted_smooth_l1 {
<add> }
<add> }
<add> }
<add> }"""
<add> model_proto = model_pb2.DetectionModel()
<add> text_format.Merge(model_text_proto, model_proto)
<add> model = self.create_model(model_proto)
<add> self.assertIsInstance(model, ssd_meta_arch.SSDMetaArch)
<add> self.assertIsInstance(model._feature_extractor,
<add> EmbeddedSSDMobileNetV1FeatureExtractor)
<add>
<add> def test_create_faster_rcnn_resnet_v1_models_from_config(self):
<add> model_text_proto = """
<add> faster_rcnn {
<add> inplace_batchnorm_update: true
<add> num_classes: 3
<add> image_resizer {
<add> keep_aspect_ratio_resizer {
<add> min_dimension: 600
<add> max_dimension: 1024
<add> }
<add> }
<add> feature_extractor {
<add> type: 'faster_rcnn_resnet101'
<add> }
<add> first_stage_anchor_generator {
<add> grid_anchor_generator {
<add> scales: [0.25, 0.5, 1.0, 2.0]
<add> aspect_ratios: [0.5, 1.0, 2.0]
<add> height_stride: 16
<add> width_stride: 16
<add> }
<add> }
<add> first_stage_box_predictor_conv_hyperparams {
<add> regularizer {
<add> l2_regularizer {
<add> }
<add> }
<add> initializer {
<add> truncated_normal_initializer {
<add> }
<add> }
<add> }
<add> initial_crop_size: 14
<add> maxpool_kernel_size: 2
<add> maxpool_stride: 2
<add> second_stage_box_predictor {
<add> mask_rcnn_box_predictor {
<add> fc_hyperparams {
<add> op: FC
<add> regularizer {
<add> l2_regularizer {
<add> }
<add> }
<add> initializer {
<add> truncated_normal_initializer {
<add> }
<add> }
<add> }
<add> }
<add> }
<add> second_stage_post_processing {
<add> batch_non_max_suppression {
<add> score_threshold: 0.01
<add> iou_threshold: 0.6
<add> max_detections_per_class: 100
<add> max_total_detections: 300
<add> }
<add> score_converter: SOFTMAX
<add> }
<add> }"""
<add> model_proto = model_pb2.DetectionModel()
<add> text_format.Merge(model_text_proto, model_proto)
<add> for extractor_type, extractor_class in FRCNN_RESNET_FEAT_MAPS.items():
<add> model_proto.faster_rcnn.feature_extractor.type = extractor_type
<add> model = model_builder.build(model_proto, is_training=True)
<add> self.assertIsInstance(model, faster_rcnn_meta_arch.FasterRCNNMetaArch)
<add> self.assertIsInstance(model._feature_extractor, extractor_class)
<add>
<add> def test_create_faster_rcnn_resnet101_with_mask_prediction_enabled(self):
<add> model_text_proto = """
<add> faster_rcnn {
<add> num_classes: 3
<add> image_resizer {
<add> keep_aspect_ratio_resizer {
<add> min_dimension: 600
<add> max_dimension: 1024
<add> }
<add> }
<add> feature_extractor {
<add> type: 'faster_rcnn_resnet101'
<add> }
<add> first_stage_anchor_generator {
<add> grid_anchor_generator {
<add> scales: [0.25, 0.5, 1.0, 2.0]
<add> aspect_ratios: [0.5, 1.0, 2.0]
<add> height_stride: 16
<add> width_stride: 16
<add> }
<add> }
<add> first_stage_box_predictor_conv_hyperparams {
<add> regularizer {
<add> l2_regularizer {
<add> }
<add> }
<add> initializer {
<add> truncated_normal_initializer {
<add> }
<add> }
<add> }
<add> initial_crop_size: 14
<add> maxpool_kernel_size: 2
<add> maxpool_stride: 2
<add> second_stage_box_predictor {
<add> mask_rcnn_box_predictor {
<add> fc_hyperparams {
<add> op: FC
<add> regularizer {
<add> l2_regularizer {
<add> }
<add> }
<add> initializer {
<add> truncated_normal_initializer {
<add> }
<add> }
<add> }
<add> conv_hyperparams {
<add> regularizer {
<add> l2_regularizer {
<add> }
<add> }
<add> initializer {
<add> truncated_normal_initializer {
<add> }
<add> }
<add> }
<add> predict_instance_masks: true
<add> }
<add> }
<add> second_stage_mask_prediction_loss_weight: 3.0
<add> second_stage_post_processing {
<add> batch_non_max_suppression {
<add> score_threshold: 0.01
<add> iou_threshold: 0.6
<add> max_detections_per_class: 100
<add> max_total_detections: 300
<add> }
<add> score_converter: SOFTMAX
<add> }
<add> }"""
<add> model_proto = model_pb2.DetectionModel()
<add> text_format.Merge(model_text_proto, model_proto)
<add> model = model_builder.build(model_proto, is_training=True)
<add> self.assertAlmostEqual(model._second_stage_mask_loss_weight, 3.0)
<add>
<add> def test_create_faster_rcnn_nas_model_from_config(self):
<add> model_text_proto = """
<add> faster_rcnn {
<add> num_classes: 3
<add> image_resizer {
<add> keep_aspect_ratio_resizer {
<add> min_dimension: 600
<add> max_dimension: 1024
<add> }
<add> }
<add> feature_extractor {
<add> type: 'faster_rcnn_nas'
<add> }
<add> first_stage_anchor_generator {
<add> grid_anchor_generator {
<add> scales: [0.25, 0.5, 1.0, 2.0]
<add> aspect_ratios: [0.5, 1.0, 2.0]
<add> height_stride: 16
<add> width_stride: 16
<add> }
<add> }
<add> first_stage_box_predictor_conv_hyperparams {
<add> regularizer {
<add> l2_regularizer {
<add> }
<add> }
<add> initializer {
<add> truncated_normal_initializer {
<add> }
<add> }
<add> }
<add> initial_crop_size: 17
<add> maxpool_kernel_size: 1
<add> maxpool_stride: 1
<add> second_stage_box_predictor {
<add> mask_rcnn_box_predictor {
<add> fc_hyperparams {
<add> op: FC
<add> regularizer {
<add> l2_regularizer {
<add> }
<add> }
<add> initializer {
<add> truncated_normal_initializer {
<add> }
<add> }
<add> }
<add> }
<add> }
<add> second_stage_post_processing {
<add> batch_non_max_suppression {
<add> score_threshold: 0.01
<add> iou_threshold: 0.6
<add> max_detections_per_class: 100
<add> max_total_detections: 300
<add> }
<add> score_converter: SOFTMAX
<add> }
<add> }"""
<add> model_proto = model_pb2.DetectionModel()
<add> text_format.Merge(model_text_proto, model_proto)
<add> model = model_builder.build(model_proto, is_training=True)
<add> self.assertIsInstance(model, faster_rcnn_meta_arch.FasterRCNNMetaArch)
<add> self.assertIsInstance(
<add> model._feature_extractor,
<add> frcnn_nas.FasterRCNNNASFeatureExtractor)
<add>
<add> def test_create_faster_rcnn_pnas_model_from_config(self):
<add> model_text_proto = """
<add> faster_rcnn {
<add> num_classes: 3
<add> image_resizer {
<add> keep_aspect_ratio_resizer {
<add> min_dimension: 600
<add> max_dimension: 1024
<add> }
<add> }
<add> feature_extractor {
<add> type: 'faster_rcnn_pnas'
<add> }
<add> first_stage_anchor_generator {
<add> grid_anchor_generator {
<add> scales: [0.25, 0.5, 1.0, 2.0]
<add> aspect_ratios: [0.5, 1.0, 2.0]
<add> height_stride: 16
<add> width_stride: 16
<add> }
<add> }
<add> first_stage_box_predictor_conv_hyperparams {
<add> regularizer {
<add> l2_regularizer {
<add> }
<add> }
<add> initializer {
<add> truncated_normal_initializer {
<add> }
<add> }
<add> }
<add> initial_crop_size: 17
<add> maxpool_kernel_size: 1
<add> maxpool_stride: 1
<add> second_stage_box_predictor {
<add> mask_rcnn_box_predictor {
<add> fc_hyperparams {
<add> op: FC
<add> regularizer {
<add> l2_regularizer {
<add> }
<add> }
<add> initializer {
<add> truncated_normal_initializer {
<add> }
<add> }
<add> }
<add> }
<add> }
<add> second_stage_post_processing {
<add> batch_non_max_suppression {
<add> score_threshold: 0.01
<add> iou_threshold: 0.6
<add> max_detections_per_class: 100
<add> max_total_detections: 300
<add> }
<add> score_converter: SOFTMAX
<add> }
<add> }"""
<add> model_proto = model_pb2.DetectionModel()
<add> text_format.Merge(model_text_proto, model_proto)
<add> model = model_builder.build(model_proto, is_training=True)
<add> self.assertIsInstance(model, faster_rcnn_meta_arch.FasterRCNNMetaArch)
<add> self.assertIsInstance(
<add> model._feature_extractor,
<add> frcnn_pnas.FasterRCNNPNASFeatureExtractor)
<add>
<add> def test_create_faster_rcnn_inception_resnet_v2_model_from_config(self):
<add> model_text_proto = """
<add> faster_rcnn {
<add> num_classes: 3
<add> image_resizer {
<add> keep_aspect_ratio_resizer {
<add> min_dimension: 600
<add> max_dimension: 1024
<add> }
<add> }
<add> feature_extractor {
<add> type: 'faster_rcnn_inception_resnet_v2'
<add> }
<add> first_stage_anchor_generator {
<add> grid_anchor_generator {
<add> scales: [0.25, 0.5, 1.0, 2.0]
<add> aspect_ratios: [0.5, 1.0, 2.0]
<add> height_stride: 16
<add> width_stride: 16
<add> }
<add> }
<add> first_stage_box_predictor_conv_hyperparams {
<add> regularizer {
<add> l2_regularizer {
<add> }
<add> }
<add> initializer {
<add> truncated_normal_initializer {
<add> }
<add> }
<add> }
<add> initial_crop_size: 17
<add> maxpool_kernel_size: 1
<add> maxpool_stride: 1
<add> second_stage_box_predictor {
<add> mask_rcnn_box_predictor {
<add> fc_hyperparams {
<add> op: FC
<add> regularizer {
<add> l2_regularizer {
<add> }
<add> }
<add> initializer {
<add> truncated_normal_initializer {
<add> }
<add> }
<add> }
<add> }
<add> }
<add> second_stage_post_processing {
<add> batch_non_max_suppression {
<add> score_threshold: 0.01
<add> iou_threshold: 0.6
<add> max_detections_per_class: 100
<add> max_total_detections: 300
<add> }
<add> score_converter: SOFTMAX
<add> }
<add> }"""
<add> model_proto = model_pb2.DetectionModel()
<add> text_format.Merge(model_text_proto, model_proto)
<add> model = model_builder.build(model_proto, is_training=True)
<add> self.assertIsInstance(model, faster_rcnn_meta_arch.FasterRCNNMetaArch)
<add> self.assertIsInstance(
<add> model._feature_extractor,
<add> frcnn_inc_res.FasterRCNNInceptionResnetV2FeatureExtractor)
<add>
<add> def test_create_faster_rcnn_inception_v2_model_from_config(self):
<add> model_text_proto = """
<add> faster_rcnn {
<add> num_classes: 3
<add> image_resizer {
<add> keep_aspect_ratio_resizer {
<add> min_dimension: 600
<add> max_dimension: 1024
<add> }
<add> }
<add> feature_extractor {
<add> type: 'faster_rcnn_inception_v2'
<add> }
<add> first_stage_anchor_generator {
<add> grid_anchor_generator {
<add> scales: [0.25, 0.5, 1.0, 2.0]
<add> aspect_ratios: [0.5, 1.0, 2.0]
<add> height_stride: 16
<add> width_stride: 16
<add> }
<add> }
<add> first_stage_box_predictor_conv_hyperparams {
<add> regularizer {
<add> l2_regularizer {
<add> }
<add> }
<add> initializer {
<add> truncated_normal_initializer {
<add> }
<add> }
<add> }
<add> initial_crop_size: 14
<add> maxpool_kernel_size: 2
<add> maxpool_stride: 2
<add> second_stage_box_predictor {
<add> mask_rcnn_box_predictor {
<add> fc_hyperparams {
<add> op: FC
<add> regularizer {
<add> l2_regularizer {
<add> }
<add> }
<add> initializer {
<add> truncated_normal_initializer {
<add> }
<add> }
<add> }
<add> }
<add> }
<add> second_stage_post_processing {
<add> batch_non_max_suppression {
<add> score_threshold: 0.01
<add> iou_threshold: 0.6
<add> max_detections_per_class: 100
<add> max_total_detections: 300
<add> }
<add> score_converter: SOFTMAX
<add> }
<add> }"""
<add> model_proto = model_pb2.DetectionModel()
<add> text_format.Merge(model_text_proto, model_proto)
<add> model = model_builder.build(model_proto, is_training=True)
<add> self.assertIsInstance(model, faster_rcnn_meta_arch.FasterRCNNMetaArch)
<add> self.assertIsInstance(model._feature_extractor,
<add> frcnn_inc_v2.FasterRCNNInceptionV2FeatureExtractor)
<add>
<add> def test_create_faster_rcnn_model_from_config_with_example_miner(self):
<add> model_text_proto = """
<add> faster_rcnn {
<add> num_classes: 3
<add> feature_extractor {
<add> type: 'faster_rcnn_inception_resnet_v2'
<add> }
<add> image_resizer {
<add> keep_aspect_ratio_resizer {
<add> min_dimension: 600
<add> max_dimension: 1024
<add> }
<add> }
<add> first_stage_anchor_generator {
<add> grid_anchor_generator {
<add> scales: [0.25, 0.5, 1.0, 2.0]
<add> aspect_ratios: [0.5, 1.0, 2.0]
<add> height_stride: 16
<add> width_stride: 16
<add> }
<add> }
<add> first_stage_box_predictor_conv_hyperparams {
<add> regularizer {
<add> l2_regularizer {
<add> }
<add> }
<add> initializer {
<add> truncated_normal_initializer {
<add> }
<add> }
<add> }
<add> second_stage_box_predictor {
<add> mask_rcnn_box_predictor {
<add> fc_hyperparams {
<add> op: FC
<add> regularizer {
<add> l2_regularizer {
<add> }
<add> }
<add> initializer {
<add> truncated_normal_initializer {
<add> }
<add> }
<add> }
<add> }
<add> }
<add> hard_example_miner {
<add> num_hard_examples: 10
<add> iou_threshold: 0.99
<add> }
<add> }"""
<add> model_proto = model_pb2.DetectionModel()
<add> text_format.Merge(model_text_proto, model_proto)
<add> model = model_builder.build(model_proto, is_training=True)
<add> self.assertIsNotNone(model._hard_example_miner)
<add>
<add> def test_create_rfcn_resnet_v1_model_from_config(self):
<add> model_text_proto = """
<add> faster_rcnn {
<add> num_classes: 3
<add> image_resizer {
<add> keep_aspect_ratio_resizer {
<add> min_dimension: 600
<add> max_dimension: 1024
<add> }
<add> }
<add> feature_extractor {
<add> type: 'faster_rcnn_resnet101'
<add> }
<add> first_stage_anchor_generator {
<add> grid_anchor_generator {
<add> scales: [0.25, 0.5, 1.0, 2.0]
<add> aspect_ratios: [0.5, 1.0, 2.0]
<add> height_stride: 16
<add> width_stride: 16
<add> }
<add> }
<add> first_stage_box_predictor_conv_hyperparams {
<add> regularizer {
<add> l2_regularizer {
<add> }
<add> }
<add> initializer {
<add> truncated_normal_initializer {
<add> }
<add> }
<add> }
<add> initial_crop_size: 14
<add> maxpool_kernel_size: 2
<add> maxpool_stride: 2
<add> second_stage_box_predictor {
<add> rfcn_box_predictor {
<add> conv_hyperparams {
<add> op: CONV
<add> regularizer {
<add> l2_regularizer {
<add> }
<add> }
<add> initializer {
<add> truncated_normal_initializer {
<add> }
<add> }
<add> }
<add> }
<add> }
<add> second_stage_post_processing {
<add> batch_non_max_suppression {
<add> score_threshold: 0.01
<add> iou_threshold: 0.6
<add> max_detections_per_class: 100
<add> max_total_detections: 300
<add> }
<add> score_converter: SOFTMAX
<add> }
<add> }"""
<add> model_proto = model_pb2.DetectionModel()
<add> text_format.Merge(model_text_proto, model_proto)
<add> for extractor_type, extractor_class in FRCNN_RESNET_FEAT_MAPS.items():
<add> model_proto.faster_rcnn.feature_extractor.type = extractor_type
<add> model = model_builder.build(model_proto, is_training=True)
<add> self.assertIsInstance(model, rfcn_meta_arch.RFCNMetaArch)
<add> self.assertIsInstance(model._feature_extractor, extractor_class)
<add>
<add>
<add>if __name__ == '__main__':
<add> tf.test.main()
<ide><path>research/object_detection/models/feature_map_generators.py
<add># Copyright 2017 The TensorFlow Authors. All Rights Reserved.
<add>#
<add># Licensed under the Apache License, Version 2.0 (the "License");
<add># you may not use this file except in compliance with the License.
<add># You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing, software
<add># distributed under the License is distributed on an "AS IS" BASIS,
<add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add># See the License for the specific language governing permissions and
<add># limitations under the License.
<add># ==============================================================================
<add>
<add>"""Functions to generate a list of feature maps based on image features.
<add>
<add>Provides several feature map generators that can be used to build object
<add>detection feature extractors.
<add>
<add>Object detection feature extractors usually are built by stacking two components
<add>- A base feature extractor such as Inception V3 and a feature map generator.
<add>Feature map generators build on the base feature extractors and produce a list
<add>of final feature maps.
<add>"""
<add>import collections
<add>import tensorflow as tf
<add>from object_detection.utils import ops
<add>slim = tf.contrib.slim
<add>
<add>
<add>def get_depth_fn(depth_multiplier, min_depth):
<add> """Builds a callable to compute depth (output channels) of conv filters.
<add>
<add> Args:
<add> depth_multiplier: a multiplier for the nominal depth.
<add> min_depth: a lower bound on the depth of filters.
<add>
<add> Returns:
<add> A callable that takes in a nominal depth and returns the depth to use.
<add> """
<add> def multiply_depth(depth):
<add> new_depth = int(depth * depth_multiplier)
<add> return max(new_depth, min_depth)
<add> return multiply_depth
<add>
<add>
<add>def multi_resolution_feature_maps(feature_map_layout, depth_multiplier,
<add> min_depth, insert_1x1_conv, image_features):
<add> """Generates multi resolution feature maps from input image features.
<add>
<add> Generates multi-scale feature maps for detection as in the SSD papers by
<add> Liu et al: https://arxiv.org/pdf/1512.02325v2.pdf, See Sec 2.1.
<add>
<add> More specifically, it performs the following two tasks:
<add> 1) If a layer name is provided in the configuration, returns that layer as a
<add> feature map.
<add> 2) If a layer name is left as an empty string, constructs a new feature map
<add> based on the spatial shape and depth configuration. Note that the current
<add> implementation only supports generating new layers using convolution of
<add> stride 2 resulting in a spatial resolution reduction by a factor of 2.
<add> By default convolution kernel size is set to 3, and it can be customized
<add> by caller.
<add>
<add> An example of the configuration for Inception V3:
<add> {
<add> 'from_layer': ['Mixed_5d', 'Mixed_6e', 'Mixed_7c', '', '', ''],
<add> 'layer_depth': [-1, -1, -1, 512, 256, 128]
<add> }
<add>
<add> Args:
<add> feature_map_layout: Dictionary of specifications for the feature map
<add> layouts in the following format (Inception V2/V3 respectively):
<add> {
<add> 'from_layer': ['Mixed_3c', 'Mixed_4c', 'Mixed_5c', '', '', ''],
<add> 'layer_depth': [-1, -1, -1, 512, 256, 128]
<add> }
<add> or
<add> {
<add> 'from_layer': ['Mixed_5d', 'Mixed_6e', 'Mixed_7c', '', '', '', ''],
<add> 'layer_depth': [-1, -1, -1, 512, 256, 128]
<add> }
<add> If 'from_layer' is specified, the specified feature map is directly used
<add> as a box predictor layer, and the layer_depth is directly infered from the
<add> feature map (instead of using the provided 'layer_depth' parameter). In
<add> this case, our convention is to set 'layer_depth' to -1 for clarity.
<add> Otherwise, if 'from_layer' is an empty string, then the box predictor
<add> layer will be built from the previous layer using convolution operations.
<add> Note that the current implementation only supports generating new layers
<add> using convolutions of stride 2 (resulting in a spatial resolution
<add> reduction by a factor of 2), and will be extended to a more flexible
<add> design. Convolution kernel size is set to 3 by default, and can be
<add> customized by 'conv_kernel_size' parameter (similarily, 'conv_kernel_size'
<add> should be set to -1 if 'from_layer' is specified). The created convolution
<add> operation will be a normal 2D convolution by default, and a depthwise
<add> convolution followed by 1x1 convolution if 'use_depthwise' is set to True.
<add> depth_multiplier: Depth multiplier for convolutional layers.
<add> min_depth: Minimum depth for convolutional layers.
<add> insert_1x1_conv: A boolean indicating whether an additional 1x1 convolution
<add> should be inserted before shrinking the feature map.
<add> image_features: A dictionary of handles to activation tensors from the
<add> base feature extractor.
<add>
<add> Returns:
<add> feature_maps: an OrderedDict mapping keys (feature map names) to
<add> tensors where each tensor has shape [batch, height_i, width_i, depth_i].
<add>
<add> Raises:
<add> ValueError: if the number entries in 'from_layer' and
<add> 'layer_depth' do not match.
<add> ValueError: if the generated layer does not have the same resolution
<add> as specified.
<add> """
<add> depth_fn = get_depth_fn(depth_multiplier, min_depth)
<add>
<add> feature_map_keys = []
<add> feature_maps = []
<add> base_from_layer = ''
<add> use_explicit_padding = False
<add> if 'use_explicit_padding' in feature_map_layout:
<add> use_explicit_padding = feature_map_layout['use_explicit_padding']
<add> use_depthwise = False
<add> if 'use_depthwise' in feature_map_layout:
<add> use_depthwise = feature_map_layout['use_depthwise']
<add> for index, from_layer in enumerate(feature_map_layout['from_layer']):
<add> layer_depth = feature_map_layout['layer_depth'][index]
<add> conv_kernel_size = 3
<add> if 'conv_kernel_size' in feature_map_layout:
<add> conv_kernel_size = feature_map_layout['conv_kernel_size'][index]
<add> if from_layer:
<add> feature_map = image_features[from_layer]
<add> base_from_layer = from_layer
<add> feature_map_keys.append(from_layer)
<add> else:
<add> pre_layer = feature_maps[-1]
<add> intermediate_layer = pre_layer
<add> if insert_1x1_conv:
<add> layer_name = '{}_1_Conv2d_{}_1x1_{}'.format(
<add> base_from_layer, index, depth_fn(layer_depth / 2))
<add> intermediate_layer = slim.conv2d(
<add> pre_layer,
<add> depth_fn(layer_depth / 2), [1, 1],
<add> padding='SAME',
<add> stride=1,
<add> scope=layer_name)
<add> layer_name = '{}_2_Conv2d_{}_{}x{}_s2_{}'.format(
<add> base_from_layer, index, conv_kernel_size, conv_kernel_size,
<add> depth_fn(layer_depth))
<add> stride = 2
<add> padding = 'SAME'
<add> if use_explicit_padding:
<add> padding = 'VALID'
<add> intermediate_layer = ops.fixed_padding(
<add> intermediate_layer, conv_kernel_size)
<add> if use_depthwise:
<add> feature_map = slim.separable_conv2d(
<add> intermediate_layer,
<add> None, [conv_kernel_size, conv_kernel_size],
<add> depth_multiplier=1,
<add> padding=padding,
<add> stride=stride,
<add> scope=layer_name + '_depthwise')
<add> feature_map = slim.conv2d(
<add> feature_map,
<add> depth_fn(layer_depth), [1, 1],
<add> padding='SAME',
<add> stride=1,
<add> scope=layer_name)
<add> else:
<add> feature_map = slim.conv2d(
<add> intermediate_layer,
<add> depth_fn(layer_depth), [conv_kernel_size, conv_kernel_size],
<add> padding=padding,
<add> stride=stride,
<add> scope=layer_name)
<add> feature_map_keys.append(layer_name)
<add> feature_maps.append(feature_map)
<add> return collections.OrderedDict(
<add> [(x, y) for (x, y) in zip(feature_map_keys, feature_maps)])
<add>
<add>
<add>def fpn_top_down_feature_maps(image_features, depth, scope=None):
<add> """Generates `top-down` feature maps for Feature Pyramid Networks.
<add>
<add> See https://arxiv.org/abs/1612.03144 for details.
<add>
<add> Args:
<add> image_features: list of tuples of (tensor_name, image_feature_tensor).
<add> Spatial resolutions of succesive tensors must reduce exactly by a factor
<add> of 2.
<add> depth: depth of output feature maps.
<add> scope: A scope name to wrap this op under.
<add>
<add> Returns:
<add> feature_maps: an OrderedDict mapping keys (feature map names) to
<add> tensors where each tensor has shape [batch, height_i, width_i, depth_i].
<add> """
<add> with tf.name_scope(scope, 'top_down'):
<add> num_levels = len(image_features)
<add> output_feature_maps_list = []
<add> output_feature_map_keys = []
<add> with slim.arg_scope(
<add> [slim.conv2d], padding='SAME', stride=1):
<add> top_down = slim.conv2d(
<add> image_features[-1][1],
<add> depth, [1, 1], activation_fn=None, normalizer_fn=None,
<add> scope='projection_%d' % num_levels)
<add> output_feature_maps_list.append(top_down)
<add> output_feature_map_keys.append(
<add> 'top_down_%s' % image_features[-1][0])
<add>
<add> for level in reversed(range(num_levels - 1)):
<add> top_down = ops.nearest_neighbor_upsampling(top_down, 2)
<add> residual = slim.conv2d(
<add> image_features[level][1], depth, [1, 1],
<add> activation_fn=None, normalizer_fn=None,
<add> scope='projection_%d' % (level + 1))
<add> top_down += residual
<add> output_feature_maps_list.append(slim.conv2d(
<add> top_down,
<add> depth, [3, 3],
<add> scope='smoothing_%d' % (level + 1)))
<add> output_feature_map_keys.append('top_down_%s' % image_features[level][0])
<add> return collections.OrderedDict(
<add> reversed(zip(output_feature_map_keys, output_feature_maps_list))) | 3 |
PHP | PHP | add tests for interacts with database trait | 402eface32dd131468948ac34022a2bb20702655 | <ide><path>tests/Foundation/FoundationInteractsWithDatabaseTest.php
<add><?php
<add>
<add>use Mockery as m;
<add>use Illuminate\Database\Connection;
<add>use Illuminate\Database\Query\Builder;
<add>use Illuminate\Foundation\Testing\Concerns\InteractsWithDatabase;
<add>
<add>class FoundationInteractsWithDatabaseTest extends PHPUnit_Framework_TestCase
<add>{
<add> use InteractsWithDatabase;
<add>
<add> protected $table = 'products';
<add>
<add> protected $data = ['title' => 'Spark'];
<add>
<add> protected $connection;
<add>
<add> public function setUp()
<add> {
<add> $this->connection = m::mock(Connection::class);
<add> }
<add>
<add> public function tearDown()
<add> {
<add> m::close();
<add> }
<add>
<add> public function testSeeInDatabaseFindsResults()
<add> {
<add> $this->mockCountBuilder(1);
<add>
<add> $this->seeInDatabase($this->table, $this->data);
<add> }
<add>
<add> /**
<add> * @expectedException \PHPUnit_Framework_ExpectationFailedException
<add> * @expectedExceptionMessage The table is empty.
<add> */
<add> public function testSeeInDatabaseDoesNotFindResults()
<add> {
<add> $builder = $this->mockCountBuilder(0);
<add>
<add> $builder->shouldReceive('get')->once()->andReturn(collect());
<add>
<add> $this->seeInDatabase($this->table, $this->data);
<add> }
<add>
<add> /**
<add> * @expectedException \PHPUnit_Framework_ExpectationFailedException
<add> * @expectedExceptionMessage Found: [{"title":"Forge"}].
<add> */
<add> public function testSeeInDatabaseFindsNotMatchingResults()
<add> {
<add> $builder = $this->mockCountBuilder(0);
<add>
<add> $builder->shouldReceive('get')->once()->andReturn(collect([['title' => 'Forge']]));
<add>
<add> $this->seeInDatabase($this->table, $this->data);
<add> }
<add>
<add> /**
<add> * @expectedException \PHPUnit_Framework_ExpectationFailedException
<add> * @expectedExceptionMessage Found: ["data","data","data"] and 2 others.
<add> */
<add> public function testSeeInDatabaseFindsManyNotMatchingResults()
<add> {
<add> $builder = $this->mockCountBuilder(0);
<add>
<add> $builder->shouldReceive('get')->once()->andReturn(
<add> collect(array_fill(0, 5, 'data'))
<add> );
<add>
<add> $this->seeInDatabase($this->table, $this->data);
<add> }
<add>
<add> public function testDontSeeInDatabaseDoesNotFindResults()
<add> {
<add> $this->mockCountBuilder(0);
<add>
<add> $this->dontSeeInDatabase($this->table, $this->data);
<add> }
<add>
<add> /**
<add> * @expectedException \PHPUnit_Framework_ExpectationFailedException
<add> * @expectedExceptionMessage a row in the table [products] does not match the attributes {"title":"Spark"}
<add> */
<add> public function testDontSeeInDatabaseFindsResults()
<add> {
<add> $builder = $this->mockCountBuilder(1);
<add>
<add> $builder->shouldReceive('get')->once()->andReturn(collect([$this->data]));
<add>
<add> $this->dontSeeInDatabase($this->table, $this->data);
<add> }
<add>
<add> protected function mockCountBuilder($countResult)
<add> {
<add> $builder = m::mock(Builder::class);
<add>
<add> $builder->shouldReceive('where')->with($this->data)->andReturnSelf();
<add>
<add> $builder->shouldReceive('count')->andReturn($countResult);
<add>
<add> $this->connection->shouldReceive('table')
<add> ->with($this->table)
<add> ->andReturn($builder);
<add>
<add> return $builder;
<add> }
<add>
<add> protected function getConnection()
<add> {
<add> return $this->connection;
<add> }
<add>} | 1 |
Javascript | Javascript | fix test-net-connect-timeout.js test | 56ec4e4f3cf8ebea1152ef8c295276168175e7c6 | <ide><path>lib/net_uv.js
<ide> exports.Stream = Socket; // Legacy naming.
<ide> Socket.prototype.setTimeout = function(msecs, callback) {
<ide> if (msecs > 0) {
<ide> timers.enroll(this, msecs);
<del> if (typeof this.fd === 'number') { timers.active(this); }
<add> timers.active(this);
<ide> if (callback) {
<ide> this.once('timeout', callback);
<ide> }
<ide> Socket.prototype.setTimeout = function(msecs, callback) {
<ide> };
<ide>
<ide>
<add>Socket.prototype._onTimeout = function() {
<add> this.emit('timeout');
<add>};
<add>
<add>
<ide> Socket.prototype.setNoDelay = function() {
<ide> /* TODO implement me */
<ide> };
<ide><path>lib/timers_uv.js
<ide> exports.active = function(item) {
<ide> var msecs = item._idleTimeout;
<ide> if (msecs >= 0) {
<ide> var list = lists[msecs];
<del> if (item._idleNext == item) {
<add> if (!list || L.isEmpty(list)) {
<ide> insert(item, msecs);
<ide> } else {
<ide> item._idleStart = new Date(); | 2 |
Python | Python | run the test_compare_ragged_with_masks on v2 only | ab5b8a771cfff14413fb8d01a8e5c24f653fb4ff | <ide><path>keras/layers/recurrent_v2_test.py
<ide> def test_ragged(self, layer):
<ide> lstm(embedded_inputs)
<ide>
<ide> @parameterized.parameters([rnn_v2.LSTM, rnn_v2.GRU])
<add> @testing_utils.run_v2_only
<ide> def test_compare_ragged_with_masks(self, layer):
<ide> vocab_size = 100
<ide> timestep = 20 | 1 |
Python | Python | add sample code create node uncustomised | 096b6065f8454ff70b07dc45b9fc24619397ab8b | <ide><path>docs/examples/compute/dimensiondata/Nodes_Create_mcp2_Uncustomised.py
<add>from pprint import pprint
<add>from libcloud.compute.types import Provider
<add>from libcloud.compute.providers import get_driver
<add>import libcloud.security
<add>
<add># Get dimension data driver
<add>libcloud.security.VERIFY_SSL_CERT = True
<add>cls = get_driver(Provider.DIMENSIONDATA)
<add>driver = cls('myusername','mypassword', region='dd-au')
<add>
<add># Get location
<add>location = driver.ex_get_location_by_id(id='AU9')
<add>
<add># Get network domain by location
<add>networkDomainName = "Test Apache Libcloud"
<add>network_domains = driver.ex_list_network_domains(location=location)
<add>my_network_domain = [d for d in network_domains if d.name == networkDomainName][0]
<add>
<add>vlan = driver.ex_list_vlans(name='Libcloud Test VLAN')[0]
<add>
<add># Get Image
<add>images = driver.ex_list_customer_images(location=location)
<add>image = images[1]
<add>
<add>tags = driver.ex_list_tags()
<add>pprint(tags)
<add>
<add>ex_tagname_value_pairs = {}
<add>ex_tagname_value_pairs['AA_Tag1'] = 'demo 1'
<add>ex_tagname_value_pairs['AA_Tag2'] = 'demo 2'
<add>
<add>ex_tagid_value_pairs = {}
<add>ex_tagid_value_pairs['4927c8fd-7f41-4206-a7d5-c5def927c6d2'] = 'demo 1'
<add>ex_tagid_value_pairs['2579fc7c-a89c-47cd-ac3b-67999dded93b'] = 'demo 2'
<add>
<add>
<add># Create node using vlan instead of private IPv4
<add>node = driver.ex_create_node_uncustomized(
<add> name='test_server_05',
<add> image=image,
<add> ex_network_domain=my_network_domain,
<add> ex_is_started=False,
<add> ex_description=None,
<add> ex_cluster_id=None,
<add> ex_cpu_specification=None,
<add> ex_memory_gb=None,
<add> ex_primary_nic_private_ipv4=None,
<add> ex_primary_nic_vlan=vlan,
<add> ex_primary_nic_network_adapter=None,
<add> ex_additional_nics=None,
<add> ex_disks=None,
<add> ex_tagid_value_pairs=ex_tagid_value_pairs,
<add> ex_tagname_value_pairs=None
<add>)
<add>
<add>pprint(node) | 1 |
Ruby | Ruby | register the interlock hook only if reloading | e3f54144d8b4575f179e36edb6855c3e442cfe4a | <ide><path>railties/lib/rails/application/finisher.rb
<ide> def self.complete(_state)
<ide> else
<ide> # Default concurrency setting: enabled, but safe
<ide>
<del> if config.reloading_enabled? || !config.eager_load
<add> if config.reloading_enabled?
<ide> app.executor.register_hook(InterlockHook, outer: true)
<ide> end
<ide> end | 1 |
Ruby | Ruby | fix occurrences fixnum|bignum | ce03e7d991a703c8d2e9c721902f312ccaeb5123 | <ide><path>actionview/test/template/date_helper_test.rb
<ide> def test_distance_in_words_with_mixed_argument_types
<ide> end
<ide>
<ide> def test_distance_in_words_doesnt_use_the_quotient_operator
<del> rubinius_skip "Date is written in Ruby and relies on Fixnum#/"
<del> jruby_skip "Date is written in Ruby and relies on Fixnum#/"
<add> rubinius_skip "Date is written in Ruby and relies on Integer#/"
<add> jruby_skip "Date is written in Ruby and relies on Integer#/"
<ide>
<del> # Make sure that we avoid {Integer,Fixnum}#/ (redefined by mathn)
<add> # Make sure that we avoid Integer#/ (redefined by mathn)
<ide> Integer.send :private, :/
<ide>
<ide> from = Time.utc(2004, 6, 6, 21, 45, 0)
<ide><path>activerecord/test/cases/migration_test.rb
<ide> def test_add_table_with_decimals
<ide> assert BigNumber.create(
<ide> bank_balance: 1586.43,
<ide> big_bank_balance: BigDecimal("1000234000567.95"),
<del> world_population: 6000000000,
<add> world_population: 2**62,
<ide> my_house_population: 3,
<ide> value_of_e: BigDecimal("2.7182818284590452353602875")
<ide> )
<ide> def test_add_table_with_decimals
<ide> assert_not_nil b.my_house_population
<ide> assert_not_nil b.value_of_e
<ide>
<del> # TODO: set world_population >= 2**62 to cover 64-bit platforms and test
<del> # is_a?(Bignum)
<ide> assert_kind_of Integer, b.world_population
<del> assert_equal 6000000000, b.world_population
<add> assert_equal 2**62, b.world_population
<ide> assert_kind_of Integer, b.my_house_population
<ide> assert_equal 3, b.my_house_population
<ide> assert_kind_of BigDecimal, b.bank_balance
<ide><path>activerecord/test/cases/numeric_data_test.rb
<ide> def test_numeric_fields
<ide> m = NumericData.new(
<ide> bank_balance: 1586.43,
<ide> big_bank_balance: BigDecimal("1000234000567.95"),
<del> world_population: 6000000000,
<add> world_population: 2**62,
<ide> my_house_population: 3
<ide> )
<ide> assert m.save
<ide>
<ide> m1 = NumericData.find(m.id)
<ide> assert_not_nil m1
<ide>
<del> # As with migration_test.rb, we should make world_population >= 2**62
<del> # to cover 64-bit platforms and test it is a Bignum, but the main thing
<del> # is that it's an Integer.
<ide> assert_kind_of Integer, m1.world_population
<del> assert_equal 6000000000, m1.world_population
<add> assert_equal 2**62, m1.world_population
<ide>
<ide> assert_kind_of Integer, m1.my_house_population
<ide> assert_equal 3, m1.my_house_population
<ide> def test_numeric_fields_with_scale
<ide> m = NumericData.new(
<ide> bank_balance: 1586.43122334,
<ide> big_bank_balance: BigDecimal("234000567.952344"),
<del> world_population: 6000000000,
<add> world_population: 2**62,
<ide> my_house_population: 3
<ide> )
<ide> assert m.save
<ide>
<ide> m1 = NumericData.find(m.id)
<ide> assert_not_nil m1
<ide>
<del> # As with migration_test.rb, we should make world_population >= 2**62
<del> # to cover 64-bit platforms and test it is a Bignum, but the main thing
<del> # is that it's an Integer.
<ide> assert_kind_of Integer, m1.world_population
<del> assert_equal 6000000000, m1.world_population
<add> assert_equal 2**62, m1.world_population
<ide>
<ide> assert_kind_of Integer, m1.my_house_population
<ide> assert_equal 3, m1.my_house_population
<ide><path>activerecord/test/migrations/decimal/1_give_me_big_numbers.rb
<ide> def self.up
<ide> create_table :big_numbers do |table|
<ide> table.column :bank_balance, :decimal, precision: 10, scale: 2
<ide> table.column :big_bank_balance, :decimal, precision: 15, scale: 2
<del> table.column :world_population, :decimal, precision: 10
<add> table.column :world_population, :decimal, precision: 20
<ide> table.column :my_house_population, :decimal, precision: 2
<ide> table.column :value_of_e, :decimal
<ide> end
<ide><path>activerecord/test/schema/schema.rb
<ide> create_table :numeric_data, force: true do |t|
<ide> t.decimal :bank_balance, precision: 10, scale: 2
<ide> t.decimal :big_bank_balance, precision: 15, scale: 2
<del> t.decimal :world_population, precision: 10, scale: 0
<add> t.decimal :world_population, precision: 20, scale: 0
<ide> t.decimal :my_house_population, precision: 2, scale: 0
<ide> t.decimal :decimal_number_with_default, precision: 3, scale: 2, default: 2.78
<ide> t.float :temperature | 5 |
PHP | PHP | fix pcntl extension error for queue | 40438b3b88d7164f3c18f463ee1587bde9ad8ef4 | <ide><path>src/Illuminate/Queue/Console/ListenCommand.php
<ide>
<ide> namespace Illuminate\Queue\Console;
<ide>
<add>use RuntimeException;
<ide> use Illuminate\Queue\Listener;
<ide> use Illuminate\Console\Command;
<ide> use Symfony\Component\Console\Input\InputOption;
<ide> public function __construct(Listener $listener)
<ide> * Execute the console command.
<ide> *
<ide> * @return void
<add> *
<add> * @throws \RuntimeException
<ide> */
<ide> public function fire()
<ide> {
<ide> public function fire()
<ide>
<ide> $timeout = $this->input->getOption('timeout');
<ide>
<add> if ($timeout && ! function_exists('pcntl_fork')) {
<add> throw new RuntimeException('Timeouts not supported without the pcntl_fork extension.');
<add> }
<add>
<ide> // We need to get the right queue for the connection which is set in the queue
<ide> // configuration file for the application. We will pull it based on the set
<ide> // connection being run for the queue operation currently being executed. | 1 |
Python | Python | add the glances history script | 3f16f409aa51f8e0929b250108c8e9069f6f48d5 | <ide><path>glances/outputs/glances_history.py
<add># -*- coding: utf-8 -*-
<add>#
<add># This file is part of Glances.
<add>#
<add># Copyright (C) 2014 Nicolargo <nicolas@nicolargo.com>
<add>#
<add># Glances is free software; you can redistribute it and/or modify
<add># it under the terms of the GNU Lesser General Public License as published by
<add># the Free Software Foundation, either version 3 of the License, or
<add># (at your option) any later version.
<add>#
<add># Glances is distributed in the hope that it will be useful,
<add># but WITHOUT ANY WARRANTY; without even the implied warranty of
<add># MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
<add># GNU Lesser General Public License for more details.
<add>#
<add># You should have received a copy of the GNU Lesser General Public License
<add># along with this program. If not, see <http://www.gnu.org/licenses/>.
<add>
<add>"""History class."""
<add>
<add># Import system lib
<add>import os
<add>import tempfile
<add>
<add># Import Glances lib
<add>from glances.core.glances_globals import logger
<add>
<add># Import specific lib
<add>try:
<add> from matplotlib import __version__ as matplotlib_version
<add> import matplotlib.pyplot as plt
<add> import matplotlib.dates as dates
<add>except:
<add> matplotlib_check = False
<add> logger.warning('Can not load Matplotlib library. Please install it using "pip install matplotlib"')
<add>else:
<add> matplotlib_check = True
<add> logger.info('Load Matplotlib version %s' % matplotlib_version)
<add>
<add>
<add>class GlancesHistory(object):
<add>
<add> """This class define the object to manage stats history"""
<add>
<add> def __init__(self, output_folder=tempfile.gettempdir()):
<add> # !!! MINUS: matplotlib footprint (mem/cpu) => Fork process ?
<add> # !!! MINUS: Mem used to store history
<add> # !!! TODO: sampling before graph => Usefull ?
<add> # !!! TODO: do not display first two point (glances is running)
<add> # !!! TODO: replace /tmp by a cross platform way to get /tmp folder
<add> self.output_folder = output_folder
<add>
<add> def get_output_folder(self):
<add> """Return the output folder where the graph are generated"""
<add> return self.output_folder
<add>
<add> def graph_enabled(self):
<add> """Return True if Glances can generaate history graphs"""
<add> return matplotlib_check
<add>
<add> def reset(self, stats):
<add> """
<add> Reset all the history
<add> """
<add> if not self.graph_enabled():
<add> return False
<add> for p in stats.getAllPlugins():
<add> h = stats.get_plugin(p).get_stats_history()
<add> if h is not None:
<add> stats.get_plugin(p).reset_stats_history()
<add> return True
<add>
<add> def generate_graph(self, stats):
<add> """
<add> Generate graphs from plugins history
<add> """
<add> if not self.graph_enabled():
<add> return False
<add>
<add> for p in stats.getAllPlugins():
<add> h = stats.get_plugin(p).get_stats_history()
<add> if h is not None:
<add> # Build the graph
<add> # fig = plt.figure(dpi=72)
<add> ax = plt.subplot(1, 1, 1)
<add>
<add> # Label
<add> plt.title("%s stats" % p)
<add>
<add> handles = []
<add> for i in stats.get_plugin(p).get_items_history_list():
<add> handles.append(plt.Rectangle((0, 0), 1, 1, fc=i['color'], ec=i['color'], linewidth=1))
<add> labels = [i['name'] for i in stats.get_plugin(p).get_items_history_list()]
<add> plt.legend(handles, labels, loc=1, prop={'size':9})
<add> formatter = dates.DateFormatter('%H:%M:%S')
<add> ax.xaxis.set_major_formatter(formatter)
<add> # ax.set_ylabel('%')
<add>
<add> # Draw the stats
<add> for i in stats.get_plugin(p).get_items_history_list():
<add> ax.plot_date(h['date'], h[i['name']],
<add> i['color'],
<add> label='%s' % i['name'],
<add> xdate=True, ydate=False)
<add>
<add> # Save and display
<add> plt.savefig(os.path.join(self.output_folder, 'glances_%s.png' % p), dpi=72)
<add> # plt.show()
<add>
<add> return True | 1 |
Javascript | Javascript | fix handling of malicious getters (scrypt) | 499533f72a2dce111d6fde9c21b90b51fff35ab6 | <ide><path>lib/internal/crypto/scrypt.js
<ide> function check(password, salt, keylen, options) {
<ide> if (options && options !== defaults) {
<ide> let has_N, has_r, has_p;
<ide> if (has_N = (options.N !== undefined)) {
<del> validateUint32(options.N, 'N');
<ide> N = options.N;
<add> validateUint32(N, 'N');
<ide> }
<ide> if (options.cost !== undefined) {
<ide> if (has_N) throw new ERR_CRYPTO_SCRYPT_INVALID_PARAMETER();
<del> validateUint32(options.cost, 'cost');
<ide> N = options.cost;
<add> validateUint32(N, 'cost');
<ide> }
<ide> if (has_r = (options.r !== undefined)) {
<del> validateUint32(options.r, 'r');
<ide> r = options.r;
<add> validateUint32(r, 'r');
<ide> }
<ide> if (options.blockSize !== undefined) {
<ide> if (has_r) throw new ERR_CRYPTO_SCRYPT_INVALID_PARAMETER();
<del> validateUint32(options.blockSize, 'blockSize');
<ide> r = options.blockSize;
<add> validateUint32(r, 'blockSize');
<ide> }
<ide> if (has_p = (options.p !== undefined)) {
<del> validateUint32(options.p, 'p');
<ide> p = options.p;
<add> validateUint32(p, 'p');
<ide> }
<ide> if (options.parallelization !== undefined) {
<ide> if (has_p) throw new ERR_CRYPTO_SCRYPT_INVALID_PARAMETER();
<del> validateUint32(options.parallelization, 'parallelization');
<ide> p = options.parallelization;
<add> validateUint32(p, 'parallelization');
<ide> }
<ide> if (options.maxmem !== undefined) {
<ide> maxmem = options.maxmem;
<ide><path>test/parallel/test-crypto-scrypt.js
<ide> for (const { args, expected } of badargs) {
<ide> code: 'ERR_OUT_OF_RANGE'
<ide> });
<ide> }
<add>
<add>{
<add> // Regression test for https://github.com/nodejs/node/issues/28836.
<add>
<add> function testParameter(name, value) {
<add> let accessCount = 0;
<add>
<add> // Find out how often the value is accessed.
<add> crypto.scryptSync('', '', 1, {
<add> get [name]() {
<add> accessCount++;
<add> return value;
<add> }
<add> });
<add>
<add> // Try to crash the process on the last access.
<add> common.expectsError(() => {
<add> crypto.scryptSync('', '', 1, {
<add> get [name]() {
<add> if (--accessCount === 0)
<add> return '';
<add> return value;
<add> }
<add> });
<add> }, {
<add> code: 'ERR_INVALID_ARG_TYPE'
<add> });
<add> }
<add>
<add> [
<add> ['N', 16384], ['cost', 16384],
<add> ['r', 8], ['blockSize', 8],
<add> ['p', 1], ['parallelization', 1]
<add> ].forEach((arg) => testParameter(...arg));
<add>} | 2 |
Javascript | Javascript | fix haste module reference | 2c7e89d17c78aef2548aa3c096d2325ba7551ece | <ide><path>Libraries/Utilities/__tests__/useRefEffect-test.js
<ide> import type {
<ide> MeasureInWindowOnSuccessCallback,
<ide> MeasureLayoutOnSuccessCallback,
<ide> MeasureOnSuccessCallback,
<del>} from 'ReactNativeTypes';
<add>} from '../../Renderer/shims/ReactNativeTypes.js';
<ide>
<ide> import View from '../../Components/View/View';
<ide> import useRefEffect from '../useRefEffect'; | 1 |
Ruby | Ruby | allow tilde expansion to '$home' | a0261c4b394d661737e780607248174fb81996e2 | <ide><path>Library/Homebrew/cask/artifact/abstract_artifact.rb
<ide> def self.dirmethod
<ide>
<ide> def staged_path_join_executable(path)
<ide> path = Pathname(path)
<add> path = path.expand_path if path.to_s.start_with?("~")
<ide>
<ide> absolute_path = if path.absolute?
<ide> path
<ide><path>Library/Homebrew/test/cask/cmd/uninstall_spec.rb
<ide> expect(cask).not_to be_installed
<ide> end
<ide>
<add> context "when Casks use script path with `~` as `HOME`" do
<add> let(:home_dir) { mktmpdir }
<add> let(:app) { Pathname.new("#{home_dir}/MyFancyApp.app") }
<add> let(:cask) { Cask::CaskLoader.load(cask_path("with-uninstall-script-user-relative")) }
<add>
<add> before do
<add> ENV["HOME"] = home_dir
<add> end
<add>
<add> it "can still uninstall them" do
<add> Cask::Installer.new(cask).install
<add>
<add> expect(cask).to be_installed
<add> expect(app).to exist
<add>
<add> expect {
<add> described_class.run("with-uninstall-script-user-relative")
<add> }.not_to raise_error
<add>
<add> expect(cask).not_to be_installed
<add> expect(app).not_to exist
<add> end
<add> end
<add>
<ide> describe "when multiple versions of a cask are installed" do
<ide> let(:token) { "versioned-cask" }
<ide> let(:first_installed_version) { "1.2.3" }
<ide><path>Library/Homebrew/test/support/fixtures/cask/Casks/with-uninstall-script-user-relative.rb
<add>cask "with-uninstall-script-user-relative" do
<add> version "1.2.3"
<add> sha256 "5633c3a0f2e572cbf021507dec78c50998b398c343232bdfc7e26221d0a5db4d"
<add>
<add> url "file://#{TEST_FIXTURE_DIR}/cask/MyFancyApp.zip"
<add> homepage "https://brew.sh/MyFancyApp"
<add>
<add> app "MyFancyApp/MyFancyApp.app", target: "~/MyFancyApp.app"
<add>
<add> postflight do
<add> IO.write "#{ENV["HOME"]}/MyFancyApp.app/uninstall.sh", <<~SH
<add> #!/bin/sh
<add> /bin/rm -r "#{ENV["HOME"]}/MyFancyApp.app"
<add> SH
<add> end
<add>
<add> uninstall script: {
<add> executable: "~/MyFancyApp.app/uninstall.sh",
<add> sudo: false,
<add> }
<add>end | 3 |
Python | Python | fix issue with lstm dynamic masking | fbd12f7d4436e26aa9fb78a9acdfcb5862e3486e | <ide><path>keras/backend/tensorflow_backend.py
<ide> def rnn(step_function, inputs, initial_states,
<ide> time step.
<ide> states: list of tensors.
<ide> Returns:
<del> output: tensor with shape (samples, output_dim) (no time dimension),
<add> output: tensor with shape (samples, output_dim)
<add> (no time dimension).
<ide> new_states: list of tensors, same length and shapes
<ide> as 'states'. The first state in the list must be the
<ide> output tensor at the previous timestep.
<del> initial_states: tensor with shape (samples, output_dim) (no time dimension),
<add> initial_states: tensor with shape (samples, output_dim)
<add> (no time dimension),
<ide> containing the initial values for the states used in
<ide> the step function.
<ide> go_backwards: boolean. If True, do the iteration over
<ide> def rnn(step_function, inputs, initial_states,
<ide> the step function, of shape (samples, ...).
<ide> '''
<ide> ndim = len(inputs.get_shape())
<del> assert ndim >= 3, 'Input should be at least 3D.'
<add> if ndim < 3:
<add> raise ValueError('Input should be at least 3D.')
<ide> axes = [1, 0] + list(range(2, ndim))
<ide> inputs = tf.transpose(inputs, (axes))
<ide>
<ide> def rnn(step_function, inputs, initial_states,
<ide>
<ide> if unroll:
<ide> if not inputs.get_shape()[0]:
<del> raise Exception('Unrolling requires a fixed number of timesteps.')
<del>
<add> raise ValueError('Unrolling requires a '
<add> 'fixed number of timesteps.')
<ide> states = initial_states
<ide> successive_states = []
<ide> successive_outputs = []
<ide> def rnn(step_function, inputs, initial_states,
<ide> for input, mask_t in zip(input_list, mask_list):
<ide> output, new_states = step_function(input, states + constants)
<ide>
<del> # tf.select needs its condition tensor to be the same shape as its two
<del> # result tensors, but in our case the condition (mask) tensor is
<del> # (nsamples, 1), and A and B are (nsamples, ndimensions). So we need to
<del> # broadcast the mask to match the shape of A and B. That's what the
<del> # tile call does, is just repeat the mask along its second dimension
<del> # ndimensions times.
<del> tiled_mask_t = tf.tile(mask_t, tf.pack([1, tf.shape(output)[1]]))
<add> # tf.select needs its condition tensor
<add> # to be the same shape as its two
<add> # result tensors, but in our case
<add> # the condition (mask) tensor is
<add> # (nsamples, 1), and A and B are (nsamples, ndimensions).
<add> # So we need to
<add> # broadcast the mask to match the shape of A and B.
<add> # That's what the tile call does,
<add> # it just repeats the mask along its second dimension
<add> # n times.
<add> tiled_mask_t = tf.tile(mask_t,
<add> tf.pack([1, tf.shape(output)[1]]))
<ide>
<ide> if len(successive_outputs) == 0:
<ide> prev_output = zeros_like(output)
<ide> def rnn(step_function, inputs, initial_states,
<ide> return_states = []
<ide> for state, new_state in zip(states, new_states):
<ide> # (see earlier comment for tile explanation)
<del> tiled_mask_t = tf.tile(mask_t, tf.pack([1, tf.shape(new_state)[1]]))
<del> return_states.append(tf.select(tiled_mask_t, new_state, state))
<del>
<add> tiled_mask_t = tf.tile(mask_t,
<add> tf.pack([1, tf.shape(new_state)[1]]))
<add> return_states.append(tf.select(tiled_mask_t,
<add> new_state,
<add> state))
<ide> states = return_states
<ide> successive_outputs.append(output)
<ide> successive_states.append(states)
<ide> def rnn(step_function, inputs, initial_states,
<ide> 'as its first state at time `t` '
<ide> 'the output at time `t-1`).')
<ide> if go_backwards:
<del> mask = tf.reverse(mask, [True] + [False] * (ndim - 2))
<add> mask = tf.reverse(mask, [True] + [False] * (ndim - 1))
<ide>
<ide> mask_ta = tensor_array_ops.TensorArray(
<ide> dtype=tf.bool,
<ide> def _step(time, output_ta_t, *states):
<ide> tuple(constants))
<ide> for state, new_state in zip(states, new_states):
<ide> new_state.set_shape(state.get_shape())
<del> tiled_mask_t = tf.tile(mask_t, tf.pack([1, tf.shape(output)[1]]))
<add> tiled_mask_t = tf.tile(mask_t,
<add> tf.pack([1, tf.shape(output)[1]]))
<ide> output = tf.select(tiled_mask_t, output, states[0])
<ide> new_states = [tf.select(tiled_mask_t, new_states[i], states[i]) for i in range(len(states))]
<ide> output_ta_t = output_ta_t.write(time, output) | 1 |
Javascript | Javascript | remove grammar argument from populateinjections | 1ba18314f94d691e55c34bfed68dcde1408d4912 | <ide><path>src/tree-sitter-language-mode.js
<ide> class LanguageLayer {
<ide> if (!grammar.injectionRegExp) return
<ide> if (!this.currentParsePromise) this.currentParsePromise = Promise.resolve()
<ide> this.currentParsePromise = this.currentParsePromise.then(async () => {
<del> await this._populateInjections(MAX_RANGE, grammar)
<add> await this._populateInjections(MAX_RANGE)
<ide> const markers = this.languageMode.injectionsMarkerLayer.getMarkers().filter(marker =>
<ide> marker.parentLanguageLayer === this
<ide> )
<ide> for (const marker of markers) {
<del> await marker.languageLayer._populateInjections(MAX_RANGE, grammar)
<add> await marker.languageLayer._populateInjections(MAX_RANGE)
<ide> }
<ide> this.currentParsePromise = null
<ide> })
<ide> class LanguageLayer {
<ide> await this._populateInjections(affectedRange)
<ide> }
<ide>
<del> async _populateInjections (range, newGrammar = null) {
<add> async _populateInjections (range) {
<ide> const {injectionsMarkerLayer, grammarForLanguageString} = this.languageMode
<ide>
<ide> const existingInjectionMarkers = injectionsMarkerLayer
<ide> class LanguageLayer {
<ide>
<ide> const grammar = grammarForLanguageString(languageName)
<ide> if (!grammar) continue
<del> if (newGrammar && grammar !== newGrammar) continue
<ide>
<ide> const contentNodes = injectionPoint.content(node)
<ide> if (!contentNodes) continue | 1 |
Python | Python | use _umath_linalg for svd() | bbdca51cac02a9f9352f671229037afa139ac7b5 | <ide><path>numpy/linalg/linalg.py
<ide> def svd(a, full_matrices=1, compute_uv=1):
<ide>
<ide> Parameters
<ide> ----------
<del> a : array_like
<add> a : (..., M, N) array_like
<ide> A real or complex matrix of shape (`M`, `N`) .
<ide> full_matrices : bool, optional
<ide> If True (default), `u` and `v` have the shapes (`M`, `M`) and
<ide> def svd(a, full_matrices=1, compute_uv=1):
<ide>
<ide> Returns
<ide> -------
<del> u : ndarray
<del> Unitary matrix. The shape of `u` is (`M`, `M`) or (`M`, `K`)
<del> depending on value of ``full_matrices``.
<del> s : ndarray
<del> The singular values, sorted so that ``s[i] >= s[i+1]``. `s` is
<del> a 1-d array of length min(`M`, `N`).
<del> v : ndarray
<del> Unitary matrix of shape (`N`, `N`) or (`K`, `N`), depending on
<del> ``full_matrices``.
<add> u : { (..., M, M), (..., M, K) } array
<add> Unitary matrices. The actual shape depends on the value of
<add> ``full_matrices``. Only returned when ``compute_uv`` is True.
<add> s : (..., K) array
<add> The singular values for every matrix, sorted in descending order.
<add> v : { (..., N, N), (..., K, N) } array
<add> Unitary matrices. The actual shape depends on the value of
<add> ``full_matrices``. Only returned when ``compute_uv`` is True.
<ide>
<ide> Raises
<ide> ------
<ide> def svd(a, full_matrices=1, compute_uv=1):
<ide>
<ide> Notes
<ide> -----
<add> Broadcasting rules apply, see the `numpy.linalg` documentation for
<add> details.
<add>
<add> The decomposition is performed using LAPACK routine _gesdd
<add>
<ide> The SVD is commonly written as ``a = U S V.H``. The `v` returned
<ide> by this function is ``V.H`` and ``u = U``.
<ide>
<ide> def svd(a, full_matrices=1, compute_uv=1):
<ide>
<ide> """
<ide> a, wrap = _makearray(a)
<del> _assertRank2(a)
<ide> _assertNonEmpty(a)
<del> m, n = a.shape
<add> _assertRankAtLeast2(a)
<ide> t, result_t = _commonType(a)
<del> real_t = _linalgRealType(t)
<del> a = _fastCopyAndTranspose(t, a)
<del> a = _to_native_byte_order(a)
<del> s = zeros((min(n, m),), real_t)
<add>
<add> extobj = get_linalg_error_extobj(_raise_linalgerror_svd_nonconvergence)
<add>
<add> m = a.shape[-2]
<add> n = a.shape[-1]
<ide> if compute_uv:
<ide> if full_matrices:
<del> nu = m
<del> nvt = n
<del> option = _A
<add> if m < n:
<add> gufunc = _umath_linalg.svd_m_f
<add> else:
<add> gufunc = _umath_linalg.svd_n_f
<ide> else:
<del> nu = min(n, m)
<del> nvt = min(n, m)
<del> option = _S
<del> u = zeros((nu, m), t)
<del> vt = zeros((n, nvt), t)
<del> else:
<del> option = _N
<del> nu = 1
<del> nvt = 1
<del> u = empty((1, 1), t)
<del> vt = empty((1, 1), t)
<add> if m < n:
<add> gufunc = _umath_linalg.svd_m_s
<add> else:
<add> gufunc = _umath_linalg.svd_n_s
<ide>
<del> iwork = zeros((8*min(m, n),), fortran_int)
<del> if isComplexType(t):
<del> lapack_routine = lapack_lite.zgesdd
<del> lrwork = min(m,n)*max(5*min(m,n)+7, 2*max(m,n)+2*min(m,n)+1)
<del> rwork = zeros((lrwork,), real_t)
<del> lwork = 1
<del> work = zeros((lwork,), t)
<del> results = lapack_routine(option, m, n, a, m, s, u, m, vt, nvt,
<del> work, -1, rwork, iwork, 0)
<del> lwork = int(abs(work[0]))
<del> work = zeros((lwork,), t)
<del> results = lapack_routine(option, m, n, a, m, s, u, m, vt, nvt,
<del> work, lwork, rwork, iwork, 0)
<del> else:
<del> lapack_routine = lapack_lite.dgesdd
<del> lwork = 1
<del> work = zeros((lwork,), t)
<del> results = lapack_routine(option, m, n, a, m, s, u, m, vt, nvt,
<del> work, -1, iwork, 0)
<del> lwork = int(work[0])
<del> work = zeros((lwork,), t)
<del> results = lapack_routine(option, m, n, a, m, s, u, m, vt, nvt,
<del> work, lwork, iwork, 0)
<del> if results['info'] > 0:
<del> raise LinAlgError('SVD did not converge')
<del> s = s.astype(_realType(result_t))
<del> if compute_uv:
<del> u = u.transpose().astype(result_t)
<del> vt = vt.transpose().astype(result_t)
<add> u, s, vt = gufunc(a.astype(t), extobj=extobj)
<add> u = u.astype(result_t)
<add> s = s.astype(_realType(result_t))
<add> vt = vt.astype(result_t)
<ide> return wrap(u), s, wrap(vt)
<ide> else:
<add> if m < n:
<add> gufunc = _umath_linalg.svd_m
<add> else:
<add> gufunc = _umath_linalg.svd_n
<add>
<add> s = gufunc(a.astype(t), extobj=extobj)
<add> s = s.astype(_realType(result_t))
<ide> return s
<ide>
<ide> def cond(x, p=None): | 1 |
Python | Python | add trademark notice to the docs footer | 4825a2d16734c1f2f8d4e0251f4836432aba938f | <ide><path>docs/conf.py
<ide> # General information about the project.
<ide> now = datetime.datetime.utcnow()
<ide> project = u'Apache Libcloud'
<del>copyright = u'2013 - %s, The Apache Software Foundation' % (now.year)
<add>copyright = u'2013 - %s, The Apache Software Foundation. Apache Libcloud, Libcloud, Apache, the Apache feather, and the Apache Libcloud project logo are trademarks of the Apache Software Foundation. All other marks mentioned may be trademarks or registered trademarks of their respective owners.' % (now.year)
<add>
<add>html_show_sphinx = False
<ide>
<ide> # The version info for the project you're documenting, acts as replacement for
<ide> # |version| and |release|, also used in various other places throughout the | 1 |
Text | Text | add missing code block | 9409f8690279342bed1aa7084b086e62280e67e2 | <ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-more-about-css-pseudo-selectors-by-building-a-balance-sheet/61fd67a656743144844941cb.md
<ide> Give your existing `span` the `class` attribute set to `flex`, and add two `span
<ide>
<ide> # --hints--
<ide>
<del>Your existing span element should have the `class` attribute set to `flex`.
<add>Your existing `span` element should have the `class` attribute set to `flex`.
<ide>
<ide> ```js
<ide> assert(document.querySelector('h1')?.children?.[0]?.classList?.contains('flex')); | 1 |
PHP | PHP | use the model key if set | 5b347060545faf3dfd89bcd2d6759d0cfa230293 | <ide><path>src/ORM/Behavior/TranslateBehavior.php
<ide> public function initialize(array $config)
<ide> $this->setupFieldAssociations(
<ide> $this->_config['fields'],
<ide> $this->_config['translationTable'],
<del> $this->_config['model'] ? $this->_config['model'] : $this->_table->alias(),
<add> $this->_config['model'] ?: $this->_table->alias(),
<ide> $this->_config['strategy']
<ide> );
<ide> }
<ide> protected function _bundleTranslatedFields($entity)
<ide> }
<ide>
<ide> $results = $this->_findExistingTranslations($find);
<del> $alias = $this->_table->alias();
<add> $model = $this->_config['model'] ?: $this->_table->alias();
<ide>
<ide> foreach ($find as $i => $translation) {
<ide> if (!empty($results[$i])) {
<ide> $contents[$i]->set('id', $results[$i], ['setter' => false]);
<ide> $contents[$i]->isNew(false);
<ide> } else {
<del> $translation['model'] = $alias;
<add> $translation['model'] = $model;
<ide> $contents[$i]->set($translation, ['setter' => false, 'guard' => false]);
<ide> $contents[$i]->isNew(true);
<ide> } | 1 |
Go | Go | extract treesize to daemon build | b64c9b521ab4e4082ed874a23a493f4a266304d5 | <ide><path>daemon/graphdriver/fsdiff.go
<add>// +build daemon
<add>
<ide> package graphdriver
<ide>
<ide> import (
<ide><path>utils/utils.go
<ide> import (
<ide> "strconv"
<ide> "strings"
<ide> "sync"
<del> "syscall"
<ide>
<ide> log "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/dockerversion"
<ide> func ReadSymlinkedDirectory(path string) (string, error) {
<ide> return realPath, nil
<ide> }
<ide>
<del>// TreeSize walks a directory tree and returns its total size in bytes.
<del>func TreeSize(dir string) (size int64, err error) {
<del> data := make(map[uint64]struct{})
<del> err = filepath.Walk(dir, func(d string, fileInfo os.FileInfo, e error) error {
<del> // Ignore directory sizes
<del> if fileInfo == nil {
<del> return nil
<del> }
<del>
<del> s := fileInfo.Size()
<del> if fileInfo.IsDir() || s == 0 {
<del> return nil
<del> }
<del>
<del> // Check inode to handle hard links correctly
<del> inode := fileInfo.Sys().(*syscall.Stat_t).Ino
<del> // inode is not a uint64 on all platforms. Cast it to avoid issues.
<del> if _, exists := data[uint64(inode)]; exists {
<del> return nil
<del> }
<del> // inode is not a uint64 on all platforms. Cast it to avoid issues.
<del> data[uint64(inode)] = struct{}{}
<del>
<del> size += s
<del>
<del> return nil
<del> })
<del> return
<del>}
<del>
<ide> // ValidateContextDirectory checks if all the contents of the directory
<ide> // can be read and returns an error if some files can't be read
<ide> // symlinks which point to non-existing files don't trigger an error
<ide><path>utils/utils_daemon.go
<add>// +build daemon
<add>
<add>package utils
<add>
<add>import (
<add> "os"
<add> "path/filepath"
<add> "syscall"
<add>)
<add>
<add>// TreeSize walks a directory tree and returns its total size in bytes.
<add>func TreeSize(dir string) (size int64, err error) {
<add> data := make(map[uint64]struct{})
<add> err = filepath.Walk(dir, func(d string, fileInfo os.FileInfo, e error) error {
<add> // Ignore directory sizes
<add> if fileInfo == nil {
<add> return nil
<add> }
<add>
<add> s := fileInfo.Size()
<add> if fileInfo.IsDir() || s == 0 {
<add> return nil
<add> }
<add>
<add> // Check inode to handle hard links correctly
<add> inode := fileInfo.Sys().(*syscall.Stat_t).Ino
<add> // inode is not a uint64 on all platforms. Cast it to avoid issues.
<add> if _, exists := data[uint64(inode)]; exists {
<add> return nil
<add> }
<add> // inode is not a uint64 on all platforms. Cast it to avoid issues.
<add> data[uint64(inode)] = struct{}{}
<add>
<add> size += s
<add>
<add> return nil
<add> })
<add> return
<add>} | 3 |
Javascript | Javascript | add missing license to unimplementedview.js | 49e6d3965f8089f422df04378cf68bf69cf7369c | <ide><path>Libraries/Components/UnimplementedViews/UnimplementedView.js
<ide> /**
<del> * Common implementation for a simple stubbed view. Simply applies the view's styles to the inner
<del> * View component and renders its children.
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<ide> *
<ide> * @providesModule UnimplementedView
<add> * @flow
<ide> */
<del>
<ide> 'use strict';
<ide>
<ide> var React = require('React');
<ide> var StyleSheet = require('StyleSheet');
<ide>
<add>/**
<add> * Common implementation for a simple stubbed view. Simply applies the view's styles to the inner
<add> * View component and renders its children.
<add> */
<ide> class UnimplementedView extends React.Component {
<ide> setNativeProps = () => {
<ide> // Do nothing. | 1 |
Javascript | Javascript | improve coverage for `module` getters | 9e7d1a1c24888ee9f1290579c7170b1eb094d609 | <ide><path>test/parallel/test-vm-module-errors.js
<ide> const common = require('../common');
<ide>
<ide> const assert = require('assert');
<ide>
<del>const { SourceTextModule, createContext } = require('vm');
<add>const { SourceTextModule, createContext, Module } = require('vm');
<ide>
<ide> async function createEmptyLinkedModule() {
<ide> const m = new SourceTextModule('');
<ide> async function checkInvalidOptionForEvaluate() {
<ide> "Received type string ('a-string')",
<ide> code: 'ERR_INVALID_ARG_TYPE'
<ide> });
<add>
<add> {
<add> ['link', 'evaluate'].forEach(async (method) => {
<add> await assert.rejects(async () => {
<add> await Module.prototype[method]();
<add> }, {
<add> code: 'ERR_VM_MODULE_NOT_MODULE',
<add> message: /Provided module is not an instance of Module/
<add> });
<add> });
<add> }
<ide> }
<ide>
<ide> function checkInvalidCachedData() {
<ide> function checkInvalidCachedData() {
<ide> });
<ide> }
<ide>
<add>function checkGettersErrors() {
<add> const getters = ['identifier', 'context', 'namespace', 'status', 'error'];
<add> getters.forEach((getter) => {
<add> assert.throws(() => {
<add> // eslint-disable-next-line no-unused-expressions
<add> Module.prototype[getter];
<add> }, {
<add> code: 'ERR_VM_MODULE_NOT_MODULE',
<add> message: /Provided module is not an instance of Module/
<add> });
<add> });
<add>}
<add>
<ide> const finished = common.mustCall();
<ide>
<ide> (async function main() {
<ide> const finished = common.mustCall();
<ide> await checkExecution();
<ide> await checkInvalidOptionForEvaluate();
<ide> checkInvalidCachedData();
<add> checkGettersErrors();
<ide> finished();
<ide> })().then(common.mustCall()); | 1 |
PHP | PHP | reduce the number of templates used | de15f6835b46957d9c980ca79514d3356e43c6e7 | <ide><path>Cake/View/Input/SelectBox.php
<ide> protected function _renderOptions($options, $disabled, $selected, $escape) {
<ide> 'content' => implode('', $groupOptions)
<ide> ]);
<ide> } else {
<del> $template = 'option';
<del> $isSelected = $this->_isSelected($key, $selected);
<del> $isDisabled = $this->_isDisabled($key, $disabled);
<del> if ($isSelected) {
<del> $template .= 'Selected';
<add> $optAttrs = [];
<add> if ($this->_isSelected($key, $selected)) {
<add> $optAttrs['selected'] = true;
<ide> }
<del> if ($isDisabled) {
<del> $template .= 'Disabled';
<add> if ($this->_isDisabled($key, $disabled)) {
<add> $optAttrs['disabled'] = true;
<ide> }
<add> $optAttrs['escape'] = $escape;
<ide>
<del> $out[] = $this->_templates->format($template, [
<add> $out[] = $this->_templates->format('option', [
<ide> 'name' => $escape ? h($key) : $key,
<ide> 'value' => $escape ? h($val) : $val,
<add> 'attrs' => $this->_templates->formatAttributes($optAttrs),
<ide> ]);
<ide> }
<ide> }
<ide><path>Test/TestCase/View/Input/SelectBoxTest.php
<ide> public function setUp() {
<ide> parent::setUp();
<ide> $templates = [
<ide> 'select' => '<select name="{{name}}"{{attrs}}>{{content}}</select>',
<del> 'option' => '<option value="{{name}}">{{value}}</option>',
<del> 'optionSelected' => '<option value="{{name}}" selected="selected">{{value}}</option>',
<del> 'optionDisabled' => '<option value="{{name}}" disabled="disabled">{{value}}</option>',
<del> 'optionSelectedDisabled' => '<option value="{{name}}" selected="selected" disabled="disabled">{{value}}</option>',
<add> 'option' => '<option value="{{name}}"{{attrs}}>{{value}}</option>',
<ide> 'optgroup' => '<optgroup label="{{label}}">{{content}}</optgroup>',
<ide> ];
<ide> $this->templates = new StringTemplate(); | 2 |
Text | Text | update accuracies for new a1 models | b132cb3036a44dc6ccf8093befb53591dc978e3c | <ide><path>website/docs/usage/_benchmarks-models.md
<ide> import { Help } from 'components/typography'; import Link from 'components/link'
<ide>
<ide> | Pipeline | Parser | Tagger | NER |
<ide> | ---------------------------------------------------------- | -----: | -----: | ---: |
<del>| [`en_core_web_trf`](/models/en#en_core_web_trf) (spaCy v3) | 95.5 | 98.3 | 89.4 |
<del>| [`en_core_web_lg`](/models/en#en_core_web_lg) (spaCy v3) | 92.2 | 97.4 | 85.4 |
<add>| [`en_core_web_trf`](/models/en#en_core_web_trf) (spaCy v3) | 95.2 | 97.8 | 89.9 |
<add>| [`en_core_web_lg`](/models/en#en_core_web_lg) (spaCy v3) | 91.9 | 97.4 | 85.5 |
<ide> | `en_core_web_lg` (spaCy v2) | 91.9 | 97.2 | 85.5 |
<ide>
<ide> <figcaption class="caption">
<ide>
<add><!-- TODO: speed (or update caption below) -->
<add>
<ide> **Full pipeline accuracy and speed** on the
<ide> [OntoNotes 5.0](https://catalog.ldc.upenn.edu/LDC2013T19) corpus (reported on
<ide> the development set). | 1 |
PHP | PHP | add test for empty middleware groups | ad18afca429e8e2c5ba9eb00eceb0de1572a0d96 | <ide><path>tests/Integration/Routing/FluentRoutingTest.php
<ide> public function testMiddlewareRunWhenRegisteredAsArrayOrParams()
<ide> $this->assertSame('1_2', $this->get('before_after')->content());
<ide> $this->assertSame('1_2', $this->get('both_before')->content());
<ide> $this->assertSame('1_2', $this->get('both_after')->content());
<add> $this->assertSame('1_2', $this->get('both_after')->content());
<add> }
<add>
<add> public function testEmptyMiddlewareGroupAreHandledGracefully()
<add> {
<add> $controller = function () {
<add> return 'Hello World';
<add> };
<add>
<add> Route::middlewareGroup('public', []);
<add>
<add> Route::middleware('public')
<add> ->get('public', $controller);
<add>
<add> $this->assertSame('Hello World', $this->get('public')->content());
<ide> }
<ide> }
<ide> | 1 |
Javascript | Javascript | fix usage of console.error to prevent transform | fe6e0741286345edb2aa23784c21f8ea611ebdea | <ide><path>packages/react-dom/src/client/ReactDOMRoot.js
<ide> const defaultOnRecoverableError =
<ide> reportError
<ide> : (error: mixed) => {
<ide> // In older browsers and test environments, fallback to console.error.
<del> // eslint-disable-next-line react-internal/no-production-logging, react-internal/warning-args
<del> console.error(error);
<add> // eslint-disable-next-line react-internal/no-production-logging
<add> console['error'](error);
<ide> };
<ide>
<ide> function ReactDOMRoot(internalRoot: FiberRoot) { | 1 |
Javascript | Javascript | add tests for `hashkey()` | 028fa1abb240d367b7e4f1f21fcd45417450b686 | <ide><path>test/ApiSpecs.js
<ide> 'use strict';
<ide>
<ide> describe('api', function() {
<add> describe('hashKey()', function() {
<add> it('should use an existing `$$hashKey`', function() {
<add> var obj = {$$hashKey: 'foo'};
<add> expect(hashKey(obj)).toBe('foo');
<add> });
<add>
<add> it('should support a function as `$$hashKey` (and call it)', function() {
<add> var obj = {$$hashKey: valueFn('foo')};
<add> expect(hashKey(obj)).toBe('foo');
<add> });
<add>
<add> it('should create a new `$$hashKey` if none exists (and return it)', function() {
<add> var obj = {};
<add> expect(hashKey(obj)).toBe(obj.$$hashKey);
<add> expect(obj.$$hashKey).toBeDefined();
<add> });
<add>
<add> it('should create appropriate `$$hashKey`s for primitive values', function() {
<add> expect(hashKey(undefined)).toBe(hashKey(undefined));
<add> expect(hashKey(null)).toBe(hashKey(null));
<add> expect(hashKey(null)).not.toBe(hashKey(undefined));
<add> expect(hashKey(true)).toBe(hashKey(true));
<add> expect(hashKey(false)).toBe(hashKey(false));
<add> expect(hashKey(false)).not.toBe(hashKey(true));
<add> expect(hashKey(42)).toBe(hashKey(42));
<add> expect(hashKey(1337)).toBe(hashKey(1337));
<add> expect(hashKey(1337)).not.toBe(hashKey(42));
<add> expect(hashKey('foo')).toBe(hashKey('foo'));
<add> expect(hashKey('foo')).not.toBe(hashKey('bar'));
<add> });
<add>
<add> it('should create appropriate `$$hashKey`s for non-primitive values', function() {
<add> var fn = function() {};
<add> var arr = [];
<add> var obj = {};
<add> var date = new Date();
<add>
<add> expect(hashKey(fn)).toBe(hashKey(fn));
<add> expect(hashKey(fn)).not.toBe(hashKey(function() {}));
<add> expect(hashKey(arr)).toBe(hashKey(arr));
<add> expect(hashKey(arr)).not.toBe(hashKey([]));
<add> expect(hashKey(obj)).toBe(hashKey(obj));
<add> expect(hashKey(obj)).not.toBe(hashKey({}));
<add> expect(hashKey(date)).toBe(hashKey(date));
<add> expect(hashKey(date)).not.toBe(hashKey(new Date()));
<add> });
<add>
<add> it('should support a custom `nextUidFn`', function() {
<add> var nextUidFn = jasmine.createSpy('nextUidFn').and.returnValues('foo', 'bar', 'baz', 'qux');
<add>
<add> var fn = function() {};
<add> var arr = [];
<add> var obj = {};
<add> var date = new Date();
<add>
<add> hashKey(fn, nextUidFn);
<add> hashKey(arr, nextUidFn);
<add> hashKey(obj, nextUidFn);
<add> hashKey(date, nextUidFn);
<add>
<add> expect(fn.$$hashKey).toBe('function:foo');
<add> expect(arr.$$hashKey).toBe('object:bar');
<add> expect(obj.$$hashKey).toBe('object:baz');
<add> expect(date.$$hashKey).toBe('object:qux');
<add> });
<add> });
<ide>
<ide> describe('HashMap', function() {
<ide> it('should do basic crud', function() { | 1 |
Ruby | Ruby | fix boolean test | 46106755b7c8a783a53791e4ed2f5e98a0c40170 | <ide><path>activerecord/test/base_test.rb
<ide> def test_boolean
<ide> end
<ide>
<ide> def test_boolean_cast_from_string
<del> b_false = Booleantest.create({ "value" => "false" })
<add> b_false = Booleantest.create({ "value" => "0" })
<ide> false_id = b_false.id
<del> b_true = Booleantest.create({ "value" => "true" })
<add> b_true = Booleantest.create({ "value" => "1" })
<ide> true_id = b_true.id
<ide>
<ide> b_false = Booleantest.find(false_id) | 1 |
Text | Text | fix typo in heading | 458f4b112be39f551d5106d6f867b673c2f240b5 | <ide><path>guide/english/react/installation/index.md
<ide> After you finish your project and are ready to deploy your App to production, yo
<ide> `npm run build`
<ide> to create an optimized build of your app in the `build`folder.
<ide>
<del>#### Usefull links
<add>#### Useful links
<ide> [Create React App repository](https://github.com/facebookincubator/create-react-app#create-react-app-)
<ide>
<ide> #### Sources | 1 |
Python | Python | prepare new pypi release | c627fa5bbdb37d9f196486b27b5cec7445ab7704 | <ide><path>keras/__init__.py
<ide> # Importable from root because it's technically not a layer
<ide> from .layers import Input
<ide>
<del>__version__ = '2.0.3'
<add>__version__ = '2.0.4'
<ide><path>setup.py
<ide>
<ide>
<ide> setup(name='Keras',
<del> version='2.0.3',
<add> version='2.0.4',
<ide> description='Deep Learning for Python',
<ide> author='Francois Chollet',
<ide> author_email='francois.chollet@gmail.com',
<ide> url='https://github.com/fchollet/keras',
<del> download_url='https://github.com/fchollet/keras/tarball/2.0.3',
<add> download_url='https://github.com/fchollet/keras/tarball/2.0.4',
<ide> license='MIT',
<ide> install_requires=['theano', 'pyyaml', 'six'],
<ide> extras_require={ | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.