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
Ruby
Ruby
change usec to 0 on tests that compare seconds
7058321725ba0054390a65d8f6343613df31eea9
<ide><path>activerecord/test/cases/persistence_test.rb <ide> def test_update_attribute_with_one_updated <ide> <ide> def test_update_attribute_for_updated_at_on <ide> developer = Developer.find(1) <del> prev_month = Time.now.prev_month <add> prev_month = Time.now.prev_month.change(usec: 0) <ide> <ide> developer.update_attribute(:updated_at, prev_month) <ide> assert_equal prev_month, developer.updated_at <ide> def test_update_column_for_readonly_attribute <ide> <ide> def test_update_column_should_not_modify_updated_at <ide> developer = Developer.find(1) <del> prev_month = Time.now.prev_month <add> prev_month = Time.now.prev_month.change(usec: 0) <ide> <ide> developer.update_column(:updated_at, prev_month) <ide> assert_equal prev_month, developer.updated_at <ide> def test_update_columns_with_one_readonly_attribute <ide> <ide> def test_update_columns_should_not_modify_updated_at <ide> developer = Developer.find(1) <del> prev_month = Time.now.prev_month <add> prev_month = Time.now.prev_month.change(usec: 0) <ide> <ide> developer.update_columns(updated_at: prev_month) <ide> assert_equal prev_month, developer.updated_at
1
Python
Python
fix dag endpoint tests not being collected nor ran
ece021d1fc78a8f9b7b55460fd58d17fab620280
<ide><path>tests/api_connexion/endpoints/test_dag_endpoint.py <ide> <ide> SERIALIZER = URLSafeSerializer(conf.get('webserver', 'secret_key')) <ide> FILE_TOKEN = SERIALIZER.dumps(__file__) <add>DAG_ID = "test_dag" <add>TASK_ID = "op1" <add>DAG2_ID = "test_dag2" <add>DAG3_ID = "test_dag3" <ide> <ide> <ide> @pytest.fixture(scope="module") <ide> def configured_app(minimal_app_for_api): <ide> app = minimal_app_for_api <add> <ide> create_user( <ide> app, # type: ignore <ide> username="test", <ide> def configured_app(minimal_app_for_api): <ide> "TEST_DAG_1", <ide> access_control={'TestGranularDag': [permissions.ACTION_CAN_EDIT, permissions.ACTION_CAN_READ]}, <ide> ) <add> app.appbuilder.sm.sync_perm_for_dag( # type: ignore # pylint: disable=no-member <add> "TEST_DAG_1", <add> access_control={'TestGranularDag': [permissions.ACTION_CAN_EDIT, permissions.ACTION_CAN_READ]}, <add> ) <add> <add> with DAG( <add> DAG_ID, <add> start_date=datetime(2020, 6, 15), <add> doc_md="details", <add> params={"foo": 1}, <add> tags=['example'], <add> ) as dag: <add> DummyOperator(task_id=TASK_ID) <add> <add> with DAG(DAG2_ID, start_date=datetime(2020, 6, 15)) as dag2: # no doc_md <add> DummyOperator(task_id=TASK_ID) <add> <add> with DAG(DAG3_ID) as dag3: # DAG start_date set to None <add> DummyOperator(task_id=TASK_ID, start_date=datetime(2019, 6, 12)) <add> <add> dag_bag = DagBag(os.devnull, include_examples=False) <add> dag_bag.dags = {dag.dag_id: dag, dag2.dag_id: dag2, dag3.dag_id: dag3} <add> <add> app.dag_bag = dag_bag <ide> <ide> yield app <ide> <ide> def configured_app(minimal_app_for_api): <ide> <ide> <ide> class TestDagEndpoint: <del> dag_id = "test_dag" <del> task_id = "op1" <del> dag2_id = "test_dag2" <del> dag3_id = "test_dag3" <del> <ide> @staticmethod <ide> def clean_db(): <ide> clear_db_runs() <ide> clear_db_dags() <ide> clear_db_serialized_dags() <ide> <del> def __init__(self, configured_app): <del> <del> app = configured_app <del> app.appbuilder.sm.sync_perm_for_dag( # type: ignore # pylint: disable=no-member <del> "TEST_DAG_1", <del> access_control={'TestGranularDag': [permissions.ACTION_CAN_EDIT, permissions.ACTION_CAN_READ]}, <del> ) <del> <del> with DAG( <del> self.dag_id, <del> start_date=datetime(2020, 6, 15), <del> doc_md="details", <del> params={"foo": 1}, <del> tags=['example'], <del> ) as dag: <del> DummyOperator(task_id=self.task_id) <del> <del> with DAG(self.dag2_id, start_date=datetime(2020, 6, 15)) as dag2: # no doc_md <del> DummyOperator(task_id=self.task_id) <del> <del> with DAG(self.dag3_id) as dag3: # DAG start_date set to None <del> DummyOperator(task_id=self.task_id, start_date=datetime(2019, 6, 12)) <del> <del> self.dag = dag # type:ignore <del> self.dag2 = dag2 # type: ignore <del> self.dag3 = dag3 # tupe: ignore <del> <del> dag_bag = DagBag(os.devnull, include_examples=False) <del> dag_bag.dags = {dag.dag_id: dag, dag2.dag_id: dag2, dag3.dag_id: dag3} <del> <del> configured_app.dag_bag = dag_bag # type:ignore <del> <ide> @pytest.fixture(autouse=True) <ide> def setup_attrs(self, configured_app) -> None: <ide> self.clean_db() <ide> self.app = configured_app <ide> self.client = self.app.test_client() # type:ignore <add> self.dag_id = DAG_ID <add> self.dag2_id = DAG2_ID <add> self.dag3_id = DAG3_ID <ide> <ide> def teardown_method(self) -> None: <ide> self.clean_db()
1
Text
Text
add esm examples in `module` api doc page
b0cc6572b0d6d3f302af5bb4aa3f098c9d8003c8
<ide><path>doc/api/module.md <ide> * {Object} <ide> <ide> Provides general utility methods when interacting with instances of <del>`Module`, the `module` variable often seen in file modules. Accessed <del>via `require('module')`. <add>`Module`, the [`module`][] variable often seen in [CommonJS][] modules. Accessed <add>via `import 'module'` or `require('module')`. <ide> <ide> ### `module.builtinModules` <ide> <!-- YAML <ide> if a module is maintained by a third party or not. <ide> by the [module wrapper][]. To access it, require the `Module` module: <ide> <ide> ```js <add>// module.mjs <add>// In an ECMAScript module <add>import { builtinModules as builtin } from 'module'; <add>``` <add> <add>```js <add>// module.cjs <add>// In a CommonJS module <ide> const builtin = require('module').builtinModules; <ide> ``` <ide> <ide> added: v12.12.0 <ide> --> <ide> <ide> The `module.syncBuiltinESMExports()` method updates all the live bindings for <del>builtin ES Modules to match the properties of the CommonJS exports. It does <del>not add or remove exported names from the ES Modules. <add>builtin [ES Modules][] to match the properties of the [CommonJS][] exports. It <add>does not add or remove exported names from the [ES Modules][]. <ide> <ide> ```js <ide> const fs = require('fs'); <ide> To enable source map parsing, Node.js must be run with the flag <ide> [`NODE_V8_COVERAGE=dir`][]. <ide> <ide> ```js <add>// module.mjs <add>// In an ECMAScript module <add>import { findSourceMap, SourceMap } from 'module'; <add>``` <add> <add>```js <add>// module.cjs <add>// In a CommonJS module <ide> const { findSourceMap, SourceMap } = require('module'); <ide> ``` <ide> <ide> consists of the following keys: <ide> [`createRequire()`]: #module_module_createrequire_filename <ide> [module wrapper]: modules_cjs.html#modules_cjs_the_module_wrapper <ide> [source map include directives]: https://sourcemaps.info/spec.html#h.lmz475t4mvbx <add>[`module`]: modules.html#modules_the_module_object <add>[CommonJS]: modules.html <add>[ES Modules]: esm.html
1
PHP
PHP
use proper assertions
bbc0a1980a51a8894c5bcc9a42e605f43b18f897
<ide><path>tests/Database/DatabaseEloquentModelTest.php <ide> public function testArrayAccessToAttributes() <ide> $this->assertTrue(isset($model['connection'])); <ide> $this->assertEquals($model['connection'], 2); <ide> $this->assertFalse(isset($model['table'])); <del> $this->assertEquals($model['table'], null); <add> $this->assertNull($model['table']); <ide> $this->assertFalse(isset($model['with'])); <ide> } <ide> <ide><path>tests/Http/HttpRequestTest.php <ide> class HttpRequestTest extends TestCase <ide> { <ide> protected function tearDown(): void <ide> { <add> parent::tearDown(); <add> <ide> m::close(); <ide> } <ide> <ide> public function testMagicMethods() <ide> <ide> // Parameter 'foo' is 'bar', then it ISSET and is NOT EMPTY. <ide> $this->assertEquals($request->foo, 'bar'); <del> $this->assertEquals(isset($request->foo), true); <del> $this->assertEquals(empty($request->foo), false); <add> $this->assertTrue(isset($request->foo)); <add> $this->assertFalse(empty($request->foo)); <ide> <ide> // Parameter 'empty' is '', then it ISSET and is EMPTY. <ide> $this->assertEquals($request->empty, ''); <ide> $this->assertTrue(isset($request->empty)); <ide> $this->assertEmpty($request->empty); <ide> <ide> // Parameter 'undefined' is undefined/null, then it NOT ISSET and is EMPTY. <del> $this->assertEquals($request->undefined, null); <del> $this->assertEquals(isset($request->undefined), false); <del> $this->assertEquals(empty($request->undefined), true); <add> $this->assertNull($request->undefined); <add> $this->assertFalse(isset($request->undefined)); <add> $this->assertEmpty($request->undefined); <ide> <ide> // Simulates Route parameters. <ide> $request = Request::create('/example/bar', 'GET', ['xyz' => 'overwritten']); <ide> public function testMagicMethods() <ide> // Router parameter 'foo' is 'bar', then it ISSET and is NOT EMPTY. <ide> $this->assertEquals('bar', $request->foo); <ide> $this->assertEquals('bar', $request['foo']); <del> $this->assertEquals(isset($request->foo), true); <del> $this->assertEquals(empty($request->foo), false); <add> $this->assertTrue(isset($request->foo)); <add> $this->assertFalse(empty($request->foo)); <ide> <ide> // Router parameter 'undefined' is undefined/null, then it NOT ISSET and is EMPTY. <del> $this->assertEquals($request->undefined, null); <del> $this->assertEquals(isset($request->undefined), false); <del> $this->assertEquals(empty($request->undefined), true); <add> $this->assertNull($request->undefined); <add> $this->assertFalse(isset($request->undefined)); <add> $this->assertTrue($request->undefined); <ide> <ide> // Special case: router parameter 'xyz' is 'overwritten' by QueryString, then it ISSET and is NOT EMPTY. <ide> // Basically, QueryStrings have priority over router parameters. <ide> $this->assertEquals($request->xyz, 'overwritten'); <del> $this->assertEquals(isset($request->foo), true); <del> $this->assertEquals(empty($request->foo), false); <add> $this->assertTrue(isset($request->foo)); <add> $this->assertFalse(empty($request->foo)); <ide> <ide> // Simulates empty QueryString and Routes. <ide> $request = Request::create('/', 'GET'); <ide> public function testMagicMethods() <ide> }); <ide> <ide> // Parameter 'undefined' is undefined/null, then it NOT ISSET and is EMPTY. <del> $this->assertEquals($request->undefined, null); <del> $this->assertEquals(isset($request->undefined), false); <del> $this->assertEquals(empty($request->undefined), true); <add> $this->assertNull($request->undefined); <add> $this->assertFalse(isset($request->undefined)); <add> $this->assertEmpty($request->undefined); <ide> <ide> // Special case: simulates empty QueryString and Routes, without the Route Resolver. <ide> // It'll happen when you try to get a parameter outside a route. <ide> $request = Request::create('/', 'GET'); <ide> <ide> // Parameter 'undefined' is undefined/null, then it NOT ISSET and is EMPTY. <del> $this->assertEquals($request->undefined, null); <del> $this->assertEquals(isset($request->undefined), false); <del> $this->assertEquals(empty($request->undefined), true); <add> $this->assertNull($request->undefined); <add> $this->assertFalse(isset($request->undefined)); <add> $this->assertTrue($request->undefined); <ide> } <ide> <ide> public function testHttpRequestFlashCallsSessionFlashInputWithInputData() <ide><path>tests/Mail/MailMarkdownTest.php <ide> class MailMarkdownTest extends TestCase <ide> { <ide> protected function tearDown(): void <ide> { <add> parent::tearDown(); <add> <ide> m::close(); <ide> } <ide> <ide> public function testRenderFunctionReturnsHtml() <ide> $viewFactory->shouldReceive('make')->with('mail::themes.default')->andReturnSelf(); <ide> $viewFactory->shouldReceive('render')->twice()->andReturn('<html></html>', 'body {}'); <ide> <del> $result = $markdown->render('view', []); <add> $result = $markdown->render('view', [])->toHtml(); <ide> <del> $this->assertTrue(strpos($result, '<html></html>') !== false); <add> $this->assertNotFalse(strpos($result, '<html></html>')); <ide> } <ide> <ide> public function testRenderFunctionReturnsHtmlWithCustomTheme() <ide> public function testRenderFunctionReturnsHtmlWithCustomTheme() <ide> $viewFactory->shouldReceive('make')->with('mail::themes.yaz')->andReturnSelf(); <ide> $viewFactory->shouldReceive('render')->twice()->andReturn('<html></html>', 'body {}'); <ide> <del> $result = $markdown->render('view', []); <add> $result = $markdown->render('view', [])->toHtml(); <ide> <del> $this->assertTrue(strpos($result, '<html></html>') !== false); <add> $this->assertNotFalse(strpos($result, '<html></html>')); <ide> } <ide> <ide> public function testRenderTextReturnsText()
3
Java
Java
add packages documentation
ae6912086aa4177b13615339cb9050558fd8ce47
<ide><path>spring-web-reactive/src/main/java/org/springframework/core/codec/package-info.java <add>/* <add> * Copyright 2002-2016 the original author or authors. <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>/** <add> * Root-package for codecs used to transform streams of bytes. <add> * Used for example for serialization/deserialization. <add> */ <add>package org.springframework.core.codec; <ide><path>spring-web-reactive/src/main/java/org/springframework/core/codec/support/package-info.java <add>/* <add> * Copyright 2002-2016 the original author or authors. <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>/** <add> * This package contains codec implementations. <add> */ <add>package org.springframework.core.codec.support; <ide><path>spring-web-reactive/src/main/java/org/springframework/core/convert/support/package-info.java <add>/* <add> * Copyright 2002-2016 the original author or authors. <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>/** <add> * Default implementation of the type conversion system. <add> */ <add>package org.springframework.core.convert.support; <ide><path>spring-web-reactive/src/main/java/org/springframework/http/client/package-info.java <add>/* <add> * Copyright 2002-2016 the original author or authors. <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>/** <add> * Core package of the client-side web support. <add> * Provides a RestTemplate class and various callback interfaces. <add> */ <add>package org.springframework.http.client; <ide><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/package-info.java <add>/* <add> * Copyright 2002-2016 the original author or authors. <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>/** <add> * Core package of the reactive server-side HTTP support. <add> */ <add>package org.springframework.http.server.reactive; <ide><path>spring-web-reactive/src/main/java/org/springframework/util/package-info.java <add>/* <add> * Copyright 2002-2016 the original author or authors. <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>/** <add> * Miscellaneous utility classes, such as InputStream/OutputStream manipulation utilities. <add> */ <add>package org.springframework.util; <ide><path>spring-web-reactive/src/main/java/org/springframework/web/package-info.java <add>/* <add> * Copyright 2002-2016 the original author or authors. <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>/** <add> * Common, generic interfaces that define minimal boundary points <add> * between Spring's web infrastructure and other framework modules. <add> */ <add>package org.springframework.web; <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/handler/package-info.java <add>/* <add> * Copyright 2002-2016 the original author or authors. <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>/** <add> * Provides reactive HandlerMapping implementations. <add> */ <add>package org.springframework.web.reactive.handler; <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/method/annotation/package-info.java <add>/* <add> * Copyright 2002-2016 the original author or authors. <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>/** <add> * Reactive infrastructure for annotation-based handler method processing. <add> */ <add>package org.springframework.web.reactive.method.annotation; <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/method/package-info.java <add>/* <add> * Copyright 2002-2016 the original author or authors. <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>/** <add> * Reactive infrastructure for handler method processing. <add> */ <add>package org.springframework.web.reactive.method; <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/package-info.java <add>/* <add> * Copyright 2002-2016 the original author or authors. <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>/** <add> * Provides the core interfaces and classes for the Spring web reactive framework. <add> */ <add>package org.springframework.web.reactive; <ide><path>spring-web-reactive/src/main/java/org/springframework/web/server/package-info.java <add>/* <add> * Copyright 2002-2016 the original author or authors. <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>/** <add> * Web server infrastructure like filter, exchange (request + response), etc. <add> */ <add>package org.springframework.web.server;
12
Text
Text
add debugging section to index
62c147761558dc0d338437667710d61a0068b401
<ide><path>docs/index.md <ide> Guides explain general topics and use cases (e.g. setup). API docs are automatic <ide> * [Tech](#tech) <ide> * [Languages](#languages) <ide> * [Hooks](#hooks) <add> * [Debugging](#debugging) <ide> * [API Docs](#api-docs) <ide> <ide> ## Resolving Issues <ide> Video.js has multi-language support! Follow this guide to see how you can contri <ide> <ide> A "hook" is functionality that wants to do when videojs creates a player. Right now only `beforesetup` and `setup` are supported. See the guide for more information on that. <ide> <add>#### [Debugging](/docs/guides/debugging.md) <add> <add>Follow this guide to see how you can use `videojs.log` for debugging purposes. <add> <ide> ## [API Docs][api] <ide> <ide> You can refer to the [full list of API docs][api], but the most relevant API doc is for the [Player][api-player].
1
Go
Go
add destination validation to "validators"
71b0e47bee6674f2571303a3663f645368479c75
<ide><path>volume/mounts/lcow_parser.go <ide> var ( <ide> lcowSplitRawSpec = regexp.MustCompile(`^` + rxSource + rxLCOWDestination + rxMode + `$`) <ide> ) <ide> <del>var lcowSpecificValidators mountValidator = func(m *mount.Mount) error { <add>var lcowValidators mountValidator = func(m *mount.Mount) error { <ide> if path.Clean(m.Target) == "/" { <ide> return ErrVolumeTargetIsRoot <ide> } <ide> if m.Type == mount.TypeNamedPipe { <ide> return errors.New("Linux containers on Windows do not support named pipe mounts") <ide> } <add> if err := windowsValidateRegex(m.Target, lcowMountDestinationRegex); err != nil { <add> return err <add> } <ide> return nil <ide> } <ide> <ide> type lcowParser struct { <ide> } <ide> <ide> func (p *lcowParser) ValidateMountConfig(mnt *mount.Mount) error { <del> return p.validateMountConfigReg(mnt, lcowMountDestinationRegex, lcowSpecificValidators) <add> return p.validateMountConfigReg(mnt, lcowValidators) <ide> } <ide> <ide> func (p *lcowParser) ParseMountRaw(raw, volumeDriver string) (*MountPoint, error) { <ide> arr, err := p.splitRawSpec(raw, lcowSplitRawSpec) <ide> if err != nil { <ide> return nil, err <ide> } <del> return p.parseMount(arr, raw, volumeDriver, lcowMountDestinationRegex, false, lcowSpecificValidators) <add> return p.parseMount(arr, raw, volumeDriver, false, lcowValidators) <ide> } <ide> <ide> func (p *lcowParser) ParseMountSpec(cfg mount.Mount) (*MountPoint, error) { <del> return p.parseMountSpec(cfg, lcowMountDestinationRegex, false, lcowSpecificValidators) <add> return p.parseMountSpec(cfg, false, lcowValidators) <ide> } <ide><path>volume/mounts/windows_parser.go <ide> func windowsValidateNotRoot(p string) error { <ide> return nil <ide> } <ide> <del>var windowsSpecificValidators mountValidator = func(mnt *mount.Mount) error { <del> return windowsValidateNotRoot(mnt.Target) <add>var windowsValidators mountValidator = func(m *mount.Mount) error { <add> if err := windowsValidateNotRoot(m.Target); err != nil { <add> return err <add> } <add> return windowsValidateRegex(m.Target, mountDestinationRegexp) <ide> } <ide> <ide> func windowsValidateRegex(p string, r *regexp.Regexp) error { <ide> func (p *windowsParser) ValidateVolumeName(name string) error { <ide> return nil <ide> } <ide> func (p *windowsParser) ValidateMountConfig(mnt *mount.Mount) error { <del> return p.validateMountConfigReg(mnt, mountDestinationRegexp, windowsSpecificValidators) <add> return p.validateMountConfigReg(mnt, windowsValidators) <ide> } <ide> <ide> type fileInfoProvider interface { <ide> func (defaultFileInfoProvider) fileInfo(path string) (exist, isDir bool, err err <ide> return true, fi.IsDir(), nil <ide> } <ide> <del>func (p *windowsParser) validateMountConfigReg(mnt *mount.Mount, destRegex *regexp.Regexp, additionalValidators ...mountValidator) error { <add>func (p *windowsParser) validateMountConfigReg(mnt *mount.Mount, additionalValidators ...mountValidator) error { <add> if len(mnt.Target) == 0 { <add> return &errMountConfig{mnt, errMissingField("Target")} <add> } <ide> for _, v := range additionalValidators { <ide> if err := v(mnt); err != nil { <ide> return &errMountConfig{mnt, err} <ide> } <ide> } <del> if len(mnt.Target) == 0 { <del> return &errMountConfig{mnt, errMissingField("Target")} <del> } <del> <del> if err := windowsValidateRegex(mnt.Target, destRegex); err != nil { <del> return &errMountConfig{mnt, err} <del> } <ide> <ide> switch mnt.Type { <ide> case mount.TypeBind: <ide> func (p *windowsParser) ParseMountRaw(raw, volumeDriver string) (*MountPoint, er <ide> if err != nil { <ide> return nil, err <ide> } <del> return p.parseMount(arr, raw, volumeDriver, mountDestinationRegexp, true, windowsSpecificValidators) <add> return p.parseMount(arr, raw, volumeDriver, true, windowsValidators) <ide> } <ide> <del>func (p *windowsParser) parseMount(arr []string, raw, volumeDriver string, destRegex *regexp.Regexp, convertTargetToBackslash bool, additionalValidators ...mountValidator) (*MountPoint, error) { <add>func (p *windowsParser) parseMount(arr []string, raw, volumeDriver string, convertTargetToBackslash bool, additionalValidators ...mountValidator) (*MountPoint, error) { <ide> var spec mount.Mount <ide> var mode string <ide> switch len(arr) { <ide> func (p *windowsParser) parseMount(arr []string, raw, volumeDriver string, destR <ide> spec.VolumeOptions.NoCopy = !copyData <ide> } <ide> <del> mp, err := p.parseMountSpec(spec, destRegex, convertTargetToBackslash, additionalValidators...) <add> mp, err := p.parseMountSpec(spec, convertTargetToBackslash, additionalValidators...) <ide> if mp != nil { <ide> mp.Mode = mode <ide> } <ide> func (p *windowsParser) parseMount(arr []string, raw, volumeDriver string, destR <ide> } <ide> <ide> func (p *windowsParser) ParseMountSpec(cfg mount.Mount) (*MountPoint, error) { <del> return p.parseMountSpec(cfg, mountDestinationRegexp, true, windowsSpecificValidators) <add> return p.parseMountSpec(cfg, true, windowsValidators) <ide> } <del>func (p *windowsParser) parseMountSpec(cfg mount.Mount, destRegex *regexp.Regexp, convertTargetToBackslash bool, additionalValidators ...mountValidator) (*MountPoint, error) { <del> if err := p.validateMountConfigReg(&cfg, destRegex, additionalValidators...); err != nil { <add> <add>func (p *windowsParser) parseMountSpec(cfg mount.Mount, convertTargetToBackslash bool, additionalValidators ...mountValidator) (*MountPoint, error) { <add> if err := p.validateMountConfigReg(&cfg, additionalValidators...); err != nil { <ide> return nil, err <ide> } <ide> mp := &MountPoint{
2
PHP
PHP
use fetch_obj instead of fetch_class
6670a242a822676fbf995e6d494c4720acc810ae
<ide><path>src/Illuminate/Database/Capsule/Manager.php <ide> public function __construct(Container $container = null) <ide> */ <ide> protected function setupDefaultConfiguration() <ide> { <del> $this->container['config']['database.fetch'] = PDO::FETCH_CLASS; <add> $this->container['config']['database.fetch'] = PDO::FETCH_OBJ; <ide> <ide> $this->container['config']['database.default'] = 'default'; <ide> } <ide><path>src/Illuminate/Database/Connection.php <ide> class Connection implements ConnectionInterface { <ide> * <ide> * @var int <ide> */ <del> protected $fetchMode = PDO::FETCH_CLASS; <add> protected $fetchMode = PDO::FETCH_OBJ; <ide> <ide> /** <ide> * The number of active transactions.
2
Ruby
Ruby
expand dependencies only once
05f92b5c98775b554a609d10c96f6c55377045be
<ide><path>Library/Homebrew/build.rb <ide> def post_superenv_hacks <ide> <ide> def pre_superenv_hacks <ide> # Allow a formula to opt-in to the std environment. <del> ARGV.unshift '--env=std' if (f.env.std? or <del> f.recursive_dependencies.detect{|d| d.name == 'scons' }) and <add> ARGV.unshift '--env=std' if (f.env.std? or deps.any? { |d| d.name == 'scons' }) and <ide> not ARGV.include? '--env=super' <ide> end <ide>
1
Javascript
Javascript
reduce usage of public util
7866508482c39d1289a901a41ec6978fb8345e03
<ide><path>lib/timers.js <ide> const { <ide> initAsyncResource, <ide> validateTimerDuration <ide> } = require('internal/timers'); <del>const internalUtil = require('internal/util'); <del>const util = require('util'); <add>const { <add> promisify: { custom: customPromisify }, <add> deprecate <add>} = require('internal/util'); <add>const { inspect } = require('internal/util/inspect'); <ide> const { ERR_INVALID_CALLBACK } = require('internal/errors').codes; <ide> <ide> let debuglog; <ide> function TimersList(expiry, msecs) { <ide> } <ide> <ide> // Make sure the linked list only shows the minimal necessary information. <del>TimersList.prototype[util.inspect.custom] = function(_, options) { <del> return util.inspect(this, { <add>TimersList.prototype[inspect.custom] = function(_, options) { <add> return inspect(this, { <ide> ...options, <ide> // Only inspect one level. <ide> depth: 0, <ide> function setTimeout(callback, after, arg1, arg2, arg3) { <ide> return timeout; <ide> } <ide> <del>setTimeout[internalUtil.promisify.custom] = function(after, value) { <add>setTimeout[customPromisify] = function(after, value) { <ide> const args = value !== undefined ? [value] : value; <ide> return new Promise((resolve) => { <ide> active(new Timeout(resolve, after, args, false)); <ide> function setImmediate(callback, arg1, arg2, arg3) { <ide> return new Immediate(callback, args); <ide> } <ide> <del>setImmediate[internalUtil.promisify.custom] = function(value) { <add>setImmediate[customPromisify] = function(value) { <ide> return new Promise((resolve) => new Immediate(resolve, [value])); <ide> }; <ide> <ide> module.exports = { <ide> clearImmediate, <ide> setInterval, <ide> clearInterval, <del> unenroll: util.deprecate( <add> unenroll: deprecate( <ide> unenroll, <ide> 'timers.unenroll() is deprecated. Please use clearTimeout instead.', <ide> 'DEP0096'), <del> enroll: util.deprecate( <add> enroll: deprecate( <ide> enroll, <ide> 'timers.enroll() is deprecated. Please use setTimeout instead.', <ide> 'DEP0095')
1
Javascript
Javascript
fix use of browsertrigger
821da26e18ab4dca7d5676525c35baf1ffc40776
<ide><path>test/ng/locationSpec.js <ide> describe('$location', function() { <ide> initBrowser(), <ide> initLocation(), <ide> function($browser) { <del> browserTrigger(link, 'click', ['ctrl']); <add> browserTrigger(link, 'click', { keys: ['ctrl'] }); <ide> expectNoRewrite($browser); <ide> } <ide> ); <ide> describe('$location', function() { <ide> initBrowser(), <ide> initLocation(), <ide> function($browser) { <del> browserTrigger(link, 'click', ['meta']); <add> browserTrigger(link, 'click', { keys: ['meta'] }); <ide> expectNoRewrite($browser); <ide> } <ide> );
1
Javascript
Javascript
remove unused reference in text.js
47addd8e34a8ee1233694f250e9badae8b86defa
<ide><path>Libraries/Text/Text.js <ide> const ColorPropType = require('ColorPropType'); <ide> const EdgeInsetsPropType = require('EdgeInsetsPropType'); <ide> const NativeMethodsMixin = require('NativeMethodsMixin'); <del>const Platform = require('Platform'); <ide> const React = require('React'); <ide> const PropTypes = require('prop-types'); <ide> const ReactNativeViewAttributes = require('ReactNativeViewAttributes');
1
Python
Python
fix deprecation warnings
9cf956b88116e3b550d731751016e61f394d621c
<ide><path>glances/core/glances_processes.py <ide> def __init__(self, cache_timeout=60): <ide> # See: https://code.google.com/p/psutil/issues/detail?id=462 <ide> self.username_cache = {} <ide> self.cmdline_cache = {} <del> <add> <ide> # The internals caches will be cleaned each 'cache_timeout' seconds <ide> self.cache_timeout = cache_timeout <ide> self.cache_timer = Timer(self.cache_timeout) <del> <add> <ide> # Init the io dict <ide> # key = pid <ide> # value = [ read_bytes_old, write_bytes_old ] <ide> self.io_old = {} <del> <add> <ide> # Init stats <ide> self.processsort = 'cpu_percent' <ide> self.processlist = [] <ide> def __get_process_stats(self, proc): <ide> procstat['status'] = str(proc.status())[:1].upper() <ide> <ide> # Process nice <del> procstat['nice'] = proc.get_nice() <add> procstat['nice'] = proc.nice() <ide> <ide> # Process memory <del> procstat['memory_info'] = proc.get_memory_info() <del> procstat['memory_percent'] = proc.get_memory_percent() <add> procstat['memory_info'] = proc.memory_info() <add> procstat['memory_percent'] = proc.memory_percent() <ide> <ide> # Process CPU <del> procstat['cpu_times'] = proc.get_cpu_times() <del> procstat['cpu_percent'] = proc.get_cpu_percent(interval=0) <add> procstat['cpu_times'] = proc.cpu_times() <add> procstat['cpu_percent'] = proc.cpu_percent(interval=0) <ide> <ide> # Process network connections (TCP and UDP) (Experimental) <ide> # !!! High CPU consumption <ide> # try: <del> # procstat['tcp'] = len(proc.get_connections(kind="tcp")) <del> # procstat['udp'] = len(proc.get_connections(kind="udp")) <add> # procstat['tcp'] = len(proc.connections(kind="tcp")) <add> # procstat['udp'] = len(proc.connections(kind="udp")) <ide> # except: <ide> # procstat['tcp'] = 0 <ide> # procstat['udp'] = 0 <ide> def __get_process_stats(self, proc): <ide> if not is_Mac: <ide> try: <ide> # Get the process IO counters <del> proc_io = proc.get_io_counters() <add> proc_io = proc.io_counters() <ide> io_new = [proc_io.read_bytes, proc_io.write_bytes] <ide> except AccessDenied: <ide> # Access denied to process IO (no root account) <ide> def update(self): <ide> <ide> # Do not process if disable tag is set <ide> if (self.disable_tag): <del> return <add> return <ide> <ide> # Get the time since last update <ide> time_since_update = getTimeSinceLastUpdate('process_disk') <ide> def update(self): <ide> self.processcount['total'] += 1 <ide> # Update thread number (global statistics) <ide> try: <del> self.processcount['thread'] += proc.get_num_threads() <add> self.processcount['thread'] += proc.num_threads() <ide> except: <ide> pass <ide> except (NoSuchProcess, AccessDenied): <ide><path>glances/plugins/glances_uptime.py <ide> # along with this program. If not, see <http://www.gnu.org/licenses/>. <ide> <ide> # Import system libs <del># Check for PSUtil already done in the glances_core script <del>try: <del> from psutil import get_boot_time <del>except: <del> from psutil import BOOT_TIME <del> <ide> from datetime import datetime <ide> <add># Check for psutil already done in the glances_core script <add>import psutil <add> <ide> # Import Glances libs <ide> from glances.plugins.glances_plugin import GlancesPlugin <ide> <ide> def update(self): <ide> """ <ide> Update uptime stat <ide> """ <del> try: <del> # For PsUtil >= 0.7.0 <del> uptime = datetime.now() - datetime.fromtimestamp(get_boot_time()) <del> except NameError: <del> uptime = datetime.now() - datetime.fromtimestamp(BOOT_TIME) <del> else: <del> uptime = '.UNKNOW' <add> uptime = datetime.now() - datetime.fromtimestamp(psutil.boot_time()) <ide> <ide> # Convert uptime to string (because datetime is not JSONifi) <ide> self.stats = str(uptime).split('.')[0]
2
Javascript
Javascript
remove ember.descriptor from exports
b339c671df7bcbdfdd9381ede4faf56f5f405b36
<ide><path>packages/ember-metal/lib/computed.js <ide> function UNDEFINED() { } <ide> <ide> @class ComputedProperty <ide> @namespace Ember <del> @extends Ember.Descriptor <ide> @constructor <ide> */ <ide> function ComputedProperty(config, opts) { <ide><path>packages/ember-metal/lib/injected_property.js <ide> import create from "ember-metal/platform/create"; <ide> <ide> @class InjectedProperty <ide> @namespace Ember <del> @extends Ember.Descriptor <ide> @constructor <ide> @param {String} type The container type the property will lookup <ide> @param {String} name (optional) The name the property will lookup, defaults <ide><path>packages/ember-metal/lib/main.js <ide> Ember.beginPropertyChanges = beginPropertyChanges; <ide> Ember.endPropertyChanges = endPropertyChanges; <ide> Ember.changeProperties = changeProperties; <ide> <del>Ember.Descriptor = Descriptor; <ide> Ember.defineProperty = defineProperty; <ide> <ide> Ember.set = set; <ide><path>packages/ember-metal/lib/mixin.js <ide> Alias.prototype = new Descriptor(); <ide> @method aliasMethod <ide> @for Ember <ide> @param {String} methodName name of the method to alias <del> @return {Ember.Descriptor} <ide> */ <ide> export function aliasMethod(methodName) { <ide> return new Alias(methodName); <ide><path>packages/ember-metal/lib/properties.js <ide> import { overrideChains } from "ember-metal/property_events"; <ide> /** <ide> Objects of this type can implement an interface to respond to requests to <ide> get and set. The default implementation handles simple properties. <del> <del> You generally won't need to create or subclass this directly. <del> <del> @class Descriptor <del> @namespace Ember <del> @private <del> @constructor <ide> */ <ide> export function Descriptor() { <ide> this.isDescriptor = true; <ide> export function DEFAULT_GETTER_FUNCTION(name) { <ide> properties and other special descriptors. <ide> <ide> Normally this method takes only three parameters. However if you pass an <del> instance of `Ember.Descriptor` as the third param then you can pass an <add> instance of `Descriptor` as the third param then you can pass an <ide> optional value as the fourth parameter. This is often more efficient than <ide> creating new descriptor hashes for each property. <ide> <ide> export function DEFAULT_GETTER_FUNCTION(name) { <ide> @for Ember <ide> @param {Object} obj the object to define this property on. This may be a prototype. <ide> @param {String} keyName the name of the property <del> @param {Ember.Descriptor} [desc] an instance of `Ember.Descriptor` (typically a <add> @param {Descriptor} [desc] an instance of `Descriptor` (typically a <ide> computed property) or an ES5 descriptor. <ide> You must provide this or `data` but not both. <ide> @param {*} [data] something other than a descriptor, that will
5
Python
Python
use current working dir as default throughout
a46b76f188290adc17e3bf5f883c089c18383ec7
<ide><path>spacy/cli/project.py <ide> def project_clone_cli( <ide> <ide> @project_cli.command("init") <ide> def project_init_cli( <del> path: Path = Arg(..., help="Path to cloned project", exists=True, file_okay=False), <add> path: Path = Arg(Path.cwd(), help="Path to cloned project. Defaults to current working directory.", exists=True, file_okay=False), <ide> git: bool = Opt(False, "--git", "-G", help="Initialize project as a Git repo"), <ide> force: bool = Opt(False, "--force", "-F", help="Force initiziation"), <ide> ): <ide> def project_init_cli( <ide> @project_cli.command("assets") <ide> def project_assets_cli( <ide> # fmt: off <del> project_dir: Path = Arg(..., help="Path to cloned project", exists=True, file_okay=False), <add> project_dir: Path = Arg(Path.cwd(), help="Path to cloned project. Defaults to current working directory.", exists=True, file_okay=False), <ide> # fmt: on <ide> ): <ide> """Use DVC (Data Version Control) to fetch project assets. Assets are <ide> def project_assets_cli( <ide> def project_run_all_cli( <ide> # fmt: off <ide> ctx: typer.Context, <del> project_dir: Path = Arg(..., help="Location of project directory", exists=True, file_okay=False), <add> project_dir: Path = Arg(Path.cwd(), help="Location of project directory. Defaults to current working directory.", exists=True, file_okay=False), <ide> show_help: bool = Opt(False, "--help", help="Show help message and available subcommands") <ide> # fmt: on <ide> ): <ide> def project_run_all_cli( <ide> def project_run_cli( <ide> # fmt: off <ide> ctx: typer.Context, <del> project_dir: Path = Arg(..., help="Location of project directory", exists=True, file_okay=False), <add> project_dir: Path = Arg(Path.cwd(), help="Location of project directory. Defaults to current working directory.", exists=True, file_okay=False), <ide> subcommand: str = Arg(None, help="Name of command defined in project config"), <ide> show_help: bool = Opt(False, "--help", help="Show help message and available subcommands") <ide> # fmt: on <ide> def project_run_cli( <ide> @project_cli.command("exec", hidden=True) <ide> def project_exec_cli( <ide> # fmt: off <del> project_dir: Path = Arg(..., help="Location of project directory", exists=True, file_okay=False), <add> project_dir: Path = Arg(Path.cwd(), help="Location of project directory. Defaults to current working directory.", exists=True, file_okay=False), <ide> subcommand: str = Arg(..., help="Name of command defined in project config"), <ide> # fmt: on <ide> ): <ide> def project_exec_cli( <ide> @project_cli.command("update-dvc") <ide> def project_update_dvc_cli( <ide> # fmt: off <del> project_dir: Path = Arg(..., help="Location of project directory", exists=True, file_okay=False), <add> project_dir: Path = Arg(Path.cwd(), help="Location of project directory. Defaults to current working directory.", exists=True, file_okay=False), <ide> verbose: bool = Opt(False, "--verbose", "-V", help="Print more info"), <ide> force: bool = Opt(False, "--force", "-F", help="Force update DVC config"), <ide> # fmt: on
1
Text
Text
add changelog entry for "fixtures" -> "fixtureset"
bf4d6a235367a4704fd341711806c170aa234f80
<ide><path>activerecord/CHANGELOG.md <ide> ## Rails 4.0.0 (unreleased) ## <ide> <add>* Rename `ActiveRecord::Fixtures` class to `ActiveRecord::FixtureSet`. <add> Instances of this class normally hold a collection of fixtures (records) <add> loaded either from a single YAML file, or from a file and a folder <add> with the same name. This change make the class name singular and makes <add> the class easier to distinguish from the modules like <add> `ActiveRecord::TestFixtures`, which operates on multiple fixture sets, <add> or `DelegatingFixtures`, `::Fixtures`, etc., <add> and from the class `ActiveRecord::Fixture`, which corresponds to a single <add> fixture. <add> <add> *Alexey Muranov* <add> <ide> * The postgres adapter now supports tables with capital letters. <ide> Fix #5920 <ide> <ide> *Michael Pearson* <ide> <ide> * Added default order to `first` to assure consistent results among <del> diferent database engines. Introduced `take` as a replacement to <add> different database engines. Introduced `take` as a replacement to <ide> the old behavior of `first`. <ide> <ide> *Marcelo Silveira*
1
Ruby
Ruby
change directory for git rev-parse --verify
f92fc98ec03fd6b5176f65dd0d0d855925dcf59b
<ide><path>Library/Homebrew/cmd/test-bot.rb <ide> def initialize(argument, options={}) <ide> @repository = @tap.path <ide> @skip_homebrew = options.fetch(:skip_homebrew, false) <ide> <del> if quiet_system "git", "rev-parse", "--verify", "-q", argument <add> if quiet_system "git", "-C", @repository.to_s, "rev-parse", "--verify", "-q", argument <ide> @hash = argument <ide> elsif url_match = argument.match(HOMEBREW_PULL_OR_COMMIT_URL_REGEX) <ide> @url = url_match[0]
1
PHP
PHP
use configure to load plugin paths
b60cd1f8f6e7dc02355d85191c53c62b7e039102
<ide><path>src/Core/Plugin.php <ide> namespace Cake\Core; <ide> <ide> use Cake\Core\ClassLoader; <add>use Cake\Core\Configure; <ide> use DirectoryIterator; <ide> <ide> /** <ide> class Plugin <ide> */ <ide> protected static $_loader; <ide> <del> /** <del> * The config map of plugins and their paths. <del> * <del> * @var array <del> */ <del> protected static $_config; <del> <ide> /** <ide> * Loads a plugin and optionally loads bootstrapping, <ide> * routing files or runs an initialization function. <ide> public static function load($plugin, array $config = []) <ide> } <ide> return; <ide> } <del> if (static::$_config === null) { <del> static::_loadConfigMap(); <add> if (!Configure::check('pluginPaths')) { <add> Configure::load('plugins'); <ide> } <ide> <ide> $config += [ <ide> public static function load($plugin, array $config = []) <ide> 'ignoreMissing' => false <ide> ]; <ide> <del> if (!isset($config['path']) && isset(static::$_config[$plugin])) { <del> $config['path'] = static::$_config[$plugin]; <add> if (!isset($config['path'])) { <add> $config['path'] = Configure::read('plugins.' . $plugin); <ide> } <ide> <ide> if (empty($config['path'])) { <ide> $paths = App::path('Plugin'); <ide> foreach ($paths as $path) { <ide> $pluginPath = str_replace('/', DS, $plugin); <ide> if (is_dir($path . $pluginPath)) { <del> $config += ['path' => $path . $pluginPath . DS]; <add> $config['path'] = $path . $pluginPath . DS; <ide> break; <ide> } <ide> } <ide> public static function load($plugin, array $config = []) <ide> } <ide> } <ide> <del> /** <del> * Loads the config mappings for plugins. <del> * <del> * The map data in CONFIG/plugins.php map data is used set default paths <del> * for where plugins are located. <del> * <del> * @return void <del> */ <del> protected static function _loadConfigMap() <del> { <del> if (!file_exists(CONFIG . 'plugins.php')) { <del> static::$_config = []; <del> return; <del> } <del> $config = include CONFIG . 'plugins.php'; <del> static::$_config = $config; <del> } <del> <ide> /** <ide> * Will load all the plugins located in the default plugin folder. <ide> * <ide><path>tests/test_app/config/plugins.php <add><?php <add>$config = [ <add> 'plugins' => [] <add>];
2
Javascript
Javascript
add ngmobile module with mobile-specific ngclick
707c65d5a228b44ab3aea2fad95516fe6c57169a
<ide><path>Gruntfile.js <ide> module.exports = function(grunt) { <ide> dest: 'build/angular-loader.js', <ide> src: util.wrap(['src/loader.js'], 'loader') <ide> }, <add> mobile: { <add> dest: 'build/angular-mobile.js', <add> src: util.wrap([ <add> 'src/ngMobile/mobile.js', <add> 'src/ngMobile/directive/ngClick.js' <add> ], 'module') <add> }, <ide> mocks: { <ide> dest: 'build/angular-mocks.js', <ide> src: ['src/ngMock/angular-mocks.js'], <ide> module.exports = function(grunt) { <ide> angular: 'build/angular.js', <ide> cookies: 'build/angular-cookies.js', <ide> loader: 'build/angular-loader.js', <add> mobile: 'build/angular-mobile.js', <ide> resource: 'build/angular-resource.js', <ide> sanitize: 'build/angular-sanitize.js', <ide> bootstrap: 'build/angular-bootstrap.js', <ide><path>angularFiles.js <ide> angularFiles = { <ide> 'src/ngSanitize/directive/ngBindHtml.js', <ide> 'src/ngSanitize/filter/linky.js', <ide> 'src/ngMock/angular-mocks.js', <add> 'src/ngMobile/mobile.js', <add> 'src/ngMobile/directive/ngClick.js', <ide> <ide> 'src/bootstrap/bootstrap.js' <ide> ], <ide> angularFiles = { <ide> 'test/ngSanitize/*.js', <ide> 'test/ngSanitize/directive/*.js', <ide> 'test/ngSanitize/filter/*.js', <del> 'test/ngMock/*.js' <add> 'test/ngMock/*.js', <add> 'test/ngMobile/directive/*.js' <ide> ], <ide> <ide> 'jstd': [ <ide> angularFiles = { <ide> 'lib/jasmine/jasmine.js', <ide> 'lib/jasmine-jstd-adapter/JasmineAdapter.js', <ide> 'build/angular.js', <add> 'build/angular-scenario.js', <ide> 'src/ngMock/angular-mocks.js', <ide> 'src/ngCookies/cookies.js', <ide> 'src/ngResource/resource.js', <add> 'src/ngMobile/mobile.js', <add> 'src/ngMobile/directive/ngClick.js', <ide> 'src/ngSanitize/sanitize.js', <ide> 'src/ngSanitize/directive/ngBindHtml.js', <ide> 'src/ngSanitize/filter/linky.js', <ide> angularFiles = { <ide> 'test/ngResource/*.js', <ide> 'test/ngSanitize/*.js', <ide> 'test/ngSanitize/directive/*.js', <del> 'test/ngSanitize/filter/*.js' <add> 'test/ngSanitize/filter/*.js', <add> 'test/ngMobile/directive/*.js' <ide> ], <ide> <ide> 'jstdPerf': [ <ide><path>src/ngMobile/directive/ngClick.js <add>'use strict'; <add> <add>/** <add> * @ngdoc directive <add> * @name ngMobile.directive:ngTap <add> * <add> * @description <add> * Specify custom behavior when element is tapped on a touchscreen device. <add> * A tap is a brief, down-and-up touch without much motion. <add> * <add> * @element ANY <add> * @param {expression} ngClick {@link guide/expression Expression} to evaluate <add> * upon tap. (Event object is available as `$event`) <add> * <add> * @example <add> <doc:example> <add> <doc:source> <add> <button ng-tap="count = count + 1" ng-init="count=0"> <add> Increment <add> </button> <add> count: {{ count }} <add> </doc:source> <add> </doc:example> <add> */ <add> <add>ngMobile.config(function($provide) { <add> $provide.decorator('ngClickDirective', function($delegate) { <add> // drop the default ngClick directive <add> $delegate.shift(); <add> return $delegate; <add> }); <add>}); <add> <add>ngMobile.directive('ngClick', ['$parse', '$timeout', '$rootElement', <add> function($parse, $timeout, $rootElement) { <add> var TAP_DURATION = 750; // Shorter than 750ms is a tap, longer is a taphold or drag. <add> var MOVE_TOLERANCE = 12; // 12px seems to work in most mobile browsers. <add> var PREVENT_DURATION = 2500; // 2.5 seconds maximum from preventGhostClick call to click <add> var CLICKBUSTER_THRESHOLD = 25; // 25 pixels in any dimension is the limit for busting clicks. <add> var lastPreventedTime; <add> var touchCoordinates; <add> <add> <add> // TAP EVENTS AND GHOST CLICKS <add> // <add> // Why tap events? <add> // Mobile browsers detect a tap, then wait a moment (usually ~300ms) to see if you're <add> // double-tapping, and then fire a click event. <add> // <add> // This delay sucks and makes mobile apps feel unresponsive. <add> // So we detect touchstart, touchmove, touchcancel and touchend ourselves and determine when <add> // the user has tapped on something. <add> // <add> // What happens when the browser then generates a click event? <add> // The browser, of course, also detects the tap and fires a click after a delay. This results in <add> // tapping/clicking twice. So we do "clickbusting" to prevent it. <add> // <add> // How does it work? <add> // We attach global touchstart and click handlers, that run during the capture (early) phase. <add> // So the sequence for a tap is: <add> // - global touchstart: Sets an "allowable region" at the point touched. <add> // - element's touchstart: Starts a touch <add> // (- touchmove or touchcancel ends the touch, no click follows) <add> // - element's touchend: Determines if the tap is valid (didn't move too far away, didn't hold <add> // too long) and fires the user's tap handler. The touchend also calls preventGhostClick(). <add> // - preventGhostClick() removes the allowable region the global touchstart created. <add> // - The browser generates a click event. <add> // - The global click handler catches the click, and checks whether it was in an allowable region. <add> // - If preventGhostClick was called, the region will have been removed, the click is busted. <add> // - If the region is still there, the click proceeds normally. Therefore clicks on links and <add> // other elements without ngTap on them work normally. <add> // <add> // This is an ugly, terrible hack! <add> // Yeah, tell me about it. The alternatives are using the slow click events, or making our users <add> // deal with the ghost clicks, so I consider this the least of evils. Fortunately Angular <add> // encapsulates this ugly logic away from the user. <add> // <add> // Why not just put click handlers on the element? <add> // We do that too, just to be sure. The problem is that the tap event might have caused the DOM <add> // to change, so that the click fires in the same position but something else is there now. So <add> // the handlers are global and care only about coordinates and not elements. <add> <add> // Checks if the coordinates are close enough to be within the region. <add> function hit(x1, y1, x2, y2) { <add> return Math.abs(x1 - x2) < CLICKBUSTER_THRESHOLD && Math.abs(y1 - y2) < CLICKBUSTER_THRESHOLD; <add> } <add> <add> // Checks a list of allowable regions against a click location. <add> // Returns true if the click should be allowed. <add> // Splices out the allowable region from the list after it has been used. <add> function checkAllowableRegions(touchCoordinates, x, y) { <add> for (var i = 0; i < touchCoordinates.length; i += 2) { <add> if (hit(touchCoordinates[i], touchCoordinates[i+1], x, y)) { <add> touchCoordinates.splice(i, i + 2); <add> return true; // allowable region <add> } <add> } <add> return false; // No allowable region; bust it. <add> } <add> <add> // Global click handler that prevents the click if it's in a bustable zone and preventGhostClick <add> // was called recently. <add> function onClick(event) { <add> if (Date.now() - lastPreventedTime > PREVENT_DURATION) { <add> return; // Too old. <add> } <add> <add> var touches = event.touches && event.touches.length ? event.touches : [event]; <add> var x = touches[0].clientX; <add> var y = touches[0].clientY; <add> // Work around desktop Webkit quirk where clicking a label will fire two clicks (on the label <add> // and on the input element). Depending on the exact browser, this second click we don't want <add> // to bust has either (0,0) or negative coordinates. <add> if (x < 1 && y < 1) { <add> return; // offscreen <add> } <add> <add> // Look for an allowable region containing this click. <add> // If we find one, that means it was created by touchstart and not removed by <add> // preventGhostClick, so we don't bust it. <add> if (checkAllowableRegions(touchCoordinates, x, y)) { <add> return; <add> } <add> <add> // If we didn't find an allowable region, bust the click. <add> event.stopPropagation(); <add> event.preventDefault(); <add> } <add> <add> <add> // Global touchstart handler that creates an allowable region for a click event. <add> // This allowable region can be removed by preventGhostClick if we want to bust it. <add> function onTouchStart(event) { <add> var touches = event.touches && event.touches.length ? event.touches : [event]; <add> var x = touches[0].clientX; <add> var y = touches[0].clientY; <add> touchCoordinates.push(x, y); <add> <add> $timeout(function() { <add> // Remove the allowable region. <add> for (var i = 0; i < touchCoordinates.length; i += 2) { <add> if (touchCoordinates[i] == x && touchCoordinates[i+1] == y) { <add> touchCoordinates.splice(i, i + 2); <add> return; <add> } <add> } <add> }, PREVENT_DURATION, false); <add> } <add> <add> // On the first call, attaches some event handlers. Then whenever it gets called, it creates a <add> // zone around the touchstart where clicks will get busted. <add> function preventGhostClick(x, y) { <add> if (!touchCoordinates) { <add> $rootElement[0].addEventListener('click', onClick, true); <add> $rootElement[0].addEventListener('touchstart', onTouchStart, true); <add> touchCoordinates = []; <add> } <add> <add> lastPreventedTime = Date.now(); <add> <add> checkAllowableRegions(touchCoordinates, x, y); <add> } <add> <add> // Actual linking function. <add> return function(scope, element, attr) { <add> var expressionFn = $parse(attr.ngClick), <add> tapping = false, <add> tapElement, // Used to blur the element after a tap. <add> startTime, // Used to check if the tap was held too long. <add> touchStartX, <add> touchStartY; <add> <add> function resetState() { <add> tapping = false; <add> } <add> <add> element.bind('touchstart', function(event) { <add> tapping = true; <add> tapElement = event.target ? event.target : event.srcElement; // IE uses srcElement. <add> // Hack for Safari, which can target text nodes instead of containers. <add> if(tapElement.nodeType == 3) { <add> tapElement = tapElement.parentNode; <add> } <add> <add> startTime = Date.now(); <add> <add> var touches = event.touches && event.touches.length ? event.touches : [event]; <add> var e = touches[0].originalEvent || touches[0]; <add> touchStartX = e.clientX; <add> touchStartY = e.clientY; <add> }); <add> <add> element.bind('touchmove', function(event) { <add> resetState(); <add> }); <add> <add> element.bind('touchcancel', function(event) { <add> resetState(); <add> }); <add> <add> element.bind('touchend', function(event) { <add> var diff = Date.now() - startTime; <add> <add> var touches = (event.changedTouches && event.changedTouches.length) ? event.changedTouches : <add> ((event.touches && event.touches.length) ? event.touches : [event]); <add> var e = touches[0].originalEvent || touches[0]; <add> var x = e.clientX; <add> var y = e.clientY; <add> var dist = Math.sqrt( Math.pow(x - touchStartX, 2) + Math.pow(y - touchStartY, 2) ); <add> <add> if (tapping && diff < TAP_DURATION && dist < MOVE_TOLERANCE) { <add> // Call preventGhostClick so the clickbuster will catch the corresponding click. <add> preventGhostClick(x, y); <add> <add> // Blur the focused element (the button, probably) before firing the callback. <add> // This doesn't work perfectly on Android Chrome, but seems to work elsewhere. <add> // I couldn't get anything to work reliably on Android Chrome. <add> if (tapElement) { <add> tapElement.blur(); <add> } <add> <add> scope.$apply(function() { <add> // TODO(braden): This is sending the touchend, not a tap or click. Is that kosher? <add> expressionFn(scope, {$event: event}); <add> }); <add> } <add> tapping = false; <add> }); <add> <add> // Hack for iOS Safari's benefit. It goes searching for onclick handlers and is liable to click <add> // something else nearby. <add> element.onclick = function(event) { }; <add> <add> // Fallback click handler. <add> // Busted clicks don't get this far, and adding this handler allows ng-tap to be used on <add> // desktop as well, to allow more portable sites. <add> element.bind('click', function(event) { <add> scope.$apply(function() { <add> expressionFn(scope, {$event: event}); <add> }); <add> }); <add> }; <add>}]); <add> <ide><path>src/ngMobile/mobile.js <add>'use strict'; <add> <add>/** <add> * @ngdoc overview <add> * @name ngMobile <add> * @description <add> */ <add> <add>/* <add> * Touch events and other mobile helpers by Braden Shepherdson (braden.shepherdson@gmail.com) <add> * Based on jQuery Mobile touch event handling (jquerymobile.com) <add> */ <add> <add>// define ngSanitize module and register $sanitize service <add>var ngMobile = angular.module('ngMobile', []); <add> <ide><path>src/ngScenario/Scenario.js <ide> function callerFile(offset) { <ide> * @param {string} type Optional event type. <ide> * @param {Array.<string>=} keys Optional list of pressed keys <ide> * (valid values: 'alt', 'meta', 'shift', 'ctrl') <add> * @param {number} x Optional x-coordinate for mouse/touch events. <add> * @param {number} y Optional y-coordinate for mouse/touch events. <ide> */ <del>function browserTrigger(element, type, keys) { <add>function browserTrigger(element, type, keys, x, y) { <ide> if (element && !element.nodeName) element = element[0]; <ide> if (!element) return; <ide> if (!type) { <ide> function browserTrigger(element, type, keys) { <ide> return originalPreventDefault.apply(evnt, arguments); <ide> }; <ide> <del> evnt.initMouseEvent(type, true, true, window, 0, 0, 0, 0, 0, pressed('ctrl'), pressed('alt'), <add> x = x || 0; <add> y = y || 0; <add> evnt.initMouseEvent(type, true, true, window, 0, x, y, x, y, pressed('ctrl'), pressed('alt'), <ide> pressed('shift'), pressed('meta'), 0, element); <ide> <ide> element.dispatchEvent(evnt); <ide><path>test/ngMobile/directive/ngClickSpec.js <add>'use strict'; <add> <add>describe('ngClick (mobile)', function() { <add> var element, time, orig_now; <add> <add> // TODO(braden): Once we have other touch-friendly browsers on CI, allow them here. <add> // Currently Firefox and IE refuse to fire touch events. <add> var chrome = /chrome/.test(navigator.userAgent.toLowerCase()); <add> if (!chrome) { <add> return; <add> } <add> <add> function mockTime() { <add> return time; <add> } <add> <add> <add> beforeEach(function() { <add> module('ngMobile'); <add> orig_now = Date.now; <add> time = 0; <add> Date.now = mockTime; <add> }); <add> <add> afterEach(function() { <add> dealoc(element); <add> Date.now = orig_now; <add> }); <add> <add> <add> it('should get called on a tap', inject(function($rootScope, $compile) { <add> element = $compile('<div ng-click="tapped = true"></div>')($rootScope); <add> $rootScope.$digest(); <add> expect($rootScope.tapped).toBeUndefined(); <add> <add> browserTrigger(element, 'touchstart'); <add> browserTrigger(element, 'touchend'); <add> expect($rootScope.tapped).toEqual(true); <add> })); <add> <add> <add> it('should pass event object', inject(function($rootScope, $compile) { <add> element = $compile('<div ng-click="event = $event"></div>')($rootScope); <add> $rootScope.$digest(); <add> <add> browserTrigger(element, 'touchstart'); <add> browserTrigger(element, 'touchend'); <add> expect($rootScope.event).toBeDefined(); <add> })); <add> <add> <add> it('should not click if the touch is held too long', inject(function($rootScope, $compile, $rootElement) { <add> element = $compile('<div ng-click="count = count + 1"></div>')($rootScope); <add> $rootElement.append(element); <add> $rootScope.count = 0; <add> $rootScope.$digest(); <add> <add> expect($rootScope.count).toBe(0); <add> <add> time = 10; <add> browserTrigger(element, 'touchstart', [], 10, 10); <add> <add> time = 900; <add> browserTrigger(element, 'touchend', [], 10, 10); <add> <add> expect($rootScope.count).toBe(0); <add> })); <add> <add> <add> it('should not click if the touchend is too far away', inject(function($rootScope, $compile, $rootElement) { <add> element = $compile('<div ng-click="tapped = true"></div>')($rootScope); <add> $rootElement.append(element); <add> $rootScope.$digest(); <add> <add> expect($rootScope.tapped).toBeUndefined(); <add> <add> browserTrigger(element, 'touchstart', [], 10, 10); <add> browserTrigger(element, 'touchend', [], 400, 400); <add> <add> expect($rootScope.tapped).toBeUndefined(); <add> })); <add> <add> <add> it('should not click if a touchmove comes before touchend', inject(function($rootScope, $compile, $rootElement) { <add> element = $compile('<div ng-tap="tapped = true"></div>')($rootScope); <add> $rootElement.append(element); <add> $rootScope.$digest(); <add> <add> expect($rootScope.tapped).toBeUndefined(); <add> <add> browserTrigger(element, 'touchstart', [], 10, 10); <add> browserTrigger(element, 'touchmove'); <add> browserTrigger(element, 'touchend', [], 400, 400); <add> <add> expect($rootScope.tapped).toBeUndefined(); <add> })); <add> <add> <add> describe('the clickbuster', function() { <add> var element1, element2; <add> <add> beforeEach(inject(function($rootElement, $document) { <add> $document.find('body').append($rootElement); <add> })); <add> <add> afterEach(inject(function($document) { <add> $document.find('body').html(''); <add> })); <add> <add> <add> it('should cancel the following click event', inject(function($rootScope, $compile, $rootElement, $document) { <add> element = $compile('<div ng-click="count = count + 1"></div>')($rootScope); <add> $rootElement.append(element); <add> <add> $rootScope.count = 0; <add> $rootScope.$digest(); <add> <add> expect($rootScope.count).toBe(0); <add> <add> // Fire touchstart at 10ms, touchend at 50ms, the click at 300ms. <add> time = 10; <add> browserTrigger(element, 'touchstart', [], 10, 10); <add> <add> time = 50; <add> browserTrigger(element, 'touchend', [], 10, 10); <add> <add> expect($rootScope.count).toBe(1); <add> <add> time = 100; <add> browserTrigger(element, 'click', [], 10, 10); <add> <add> expect($rootScope.count).toBe(1); <add> })); <add> <add> <add> it('should cancel the following click event even when the element has changed', inject( <add> function($rootScope, $compile, $rootElement) { <add> $rootElement.append( <add> '<div ng-show="!tapped" ng-click="count1 = count1 + 1; tapped = true">x</div>' + <add> '<div ng-show="tapped" ng-click="count2 = count2 + 1">y</div>' <add> ); <add> $compile($rootElement)($rootScope); <add> <add> element1 = $rootElement.find('div').eq(0); <add> element2 = $rootElement.find('div').eq(1); <add> <add> $rootScope.count1 = 0; <add> $rootScope.count2 = 0; <add> <add> $rootScope.$digest(); <add> <add> expect($rootScope.count1).toBe(0); <add> expect($rootScope.count2).toBe(0); <add> <add> time = 10; <add> browserTrigger(element1, 'touchstart', [], 10, 10); <add> <add> time = 50; <add> browserTrigger(element1, 'touchend', [], 10, 10); <add> <add> expect($rootScope.count1).toBe(1); <add> <add> time = 100; <add> browserTrigger(element2, 'click', [], 10, 10); <add> <add> expect($rootScope.count1).toBe(1); <add> expect($rootScope.count2).toBe(0); <add> })); <add> <add> <add> it('should not cancel clicks on distant elements', inject(function($rootScope, $compile, $rootElement) { <add> $rootElement.append( <add> '<div ng-click="count1 = count1 + 1">x</div>' + <add> '<div ng-click="count2 = count2 + 1">y</div>' <add> ); <add> $compile($rootElement)($rootScope); <add> <add> element1 = $rootElement.find('div').eq(0); <add> element2 = $rootElement.find('div').eq(1); <add> <add> $rootScope.count1 = 0; <add> $rootScope.count2 = 0; <add> <add> $rootScope.$digest(); <add> <add> expect($rootScope.count1).toBe(0); <add> expect($rootScope.count2).toBe(0); <add> <add> time = 10; <add> browserTrigger(element1, 'touchstart', [], 10, 10); <add> <add> time = 50; <add> browserTrigger(element1, 'touchend', [], 10, 10); <add> <add> expect($rootScope.count1).toBe(1); <add> <add> time = 90; <add> browserTrigger(element1, 'click', [], 10, 10); <add> <add> expect($rootScope.count1).toBe(1); <add> <add> time = 100; <add> browserTrigger(element1, 'touchstart', [], 10, 10); <add> <add> time = 130; <add> browserTrigger(element1, 'touchend', [], 10, 10); <add> <add> expect($rootScope.count1).toBe(2); <add> <add> // Click on other element that should go through. <add> time = 150; <add> browserTrigger(element2, 'touchstart', [], 100, 120); <add> browserTrigger(element2, 'touchend', [], 100, 120); <add> browserTrigger(element2, 'click', [], 100, 120); <add> <add> expect($rootScope.count2).toBe(1); <add> <add> // Click event for the element that should be busted. <add> time = 200; <add> browserTrigger(element1, 'click', [], 10, 10); <add> <add> expect($rootScope.count1).toBe(2); <add> expect($rootScope.count2).toBe(1); <add> })); <add> <add> <add> it('should not cancel clicks that come long after', inject(function($rootScope, $compile) { <add> element1 = $compile('<div ng-click="count = count + 1"></div>')($rootScope); <add> <add> $rootScope.count = 0; <add> <add> $rootScope.$digest(); <add> <add> expect($rootScope.count).toBe(0); <add> <add> time = 10; <add> browserTrigger(element1, 'touchstart', [], 10, 10); <add> <add> time = 50; <add> browserTrigger(element1, 'touchend', [], 10, 10); <add> expect($rootScope.count).toBe(1); <add> <add> time = 2700; <add> browserTrigger(element1, 'click', [], 10, 10); <add> <add> expect($rootScope.count).toBe(2); <add> })); <add> <add> <add> it('should not cancel clicks that come long after', inject(function($rootScope, $compile) { <add> element1 = $compile('<div ng-click="count = count + 1"></div>')($rootScope); <add> <add> $rootScope.count = 0; <add> <add> $rootScope.$digest(); <add> <add> expect($rootScope.count).toBe(0); <add> <add> time = 10; <add> browserTrigger(element1, 'touchstart', [], 10, 10); <add> <add> time = 50; <add> browserTrigger(element1, 'touchend', [], 10, 10); <add> <add> expect($rootScope.count).toBe(1); <add> <add> time = 2700; <add> browserTrigger(element1, 'click', [], 10, 10); <add> <add> expect($rootScope.count).toBe(2); <add> })); <add> }); <add> <add> <add> describe('click fallback', function() { <add> <add> it('should treat a click as a tap on desktop', inject(function($rootScope, $compile) { <add> element = $compile('<div ng-click="tapped = true"></div>')($rootScope); <add> $rootScope.$digest(); <add> expect($rootScope.tapped).toBeFalsy(); <add> <add> browserTrigger(element, 'click'); <add> expect($rootScope.tapped).toEqual(true); <add> })); <add> <add> <add> it('should pass event object', inject(function($rootScope, $compile) { <add> element = $compile('<div ng-click="event = $event"></div>')($rootScope); <add> $rootScope.$digest(); <add> <add> browserTrigger(element, 'click'); <add> expect($rootScope.event).toBeDefined(); <add> })); <add> }); <add>});
6
Text
Text
update text to give an explanation of wrapping
f91dea9b5c6ae77b986a64454599eea08b9c0d0a
<ide><path>curriculum/challenges/english/01-responsive-web-design/basic-html-and-html5/introduction-to-html5-elements.english.md <ide> videoUrl: 'https://scrimba.com/p/pVMPUv/c4Ep9Am' <ide> <ide> ## Description <ide> <section id='description'> <del>HTML5 introduces more descriptive HTML tags. These include <code>header</code>, <code>footer</code>, <code>nav</code>, <code>video</code>, <code>article</code>, <code>section</code> and others. <del>These tags make your HTML easier to read, and also help with Search Engine Optimization (SEO) and accessibility. <del>The <code>main</code> HTML5 tag helps search engines and other developers find the main content of your page. <add>HTML5 introduces more descriptive HTML tags. These include <code>main</code>, <code>header</code>, <code>footer</code>, <code>nav</code>, <code>video</code>, <code>article</code>, <code>section</code> and others. <add>These tags give a descriptive structure to your HTML, make your HTML easier to read, and help with Search Engine Optimization (SEO) and accessibility. The <code>main</code> HTML5 tag helps search engines and other developers find the main content of your page. <add>Example usage, a <code>main</code> element with two child elements nested inside it: <add><blockquote>&#60;main&#62; <br>&nbsp;&nbsp;&#60;h1&#62;Hello World&#60;/h1&#62;<br>&nbsp;&nbsp;&#60;p&#62;Hello Paragraph&#60;/p&#62;<br>&#60;/main&#62;</blockquote> <ide> <strong>Note:</strong> Many of the new HTML5 tags and their benefits are covered in the Applied Accessibility section. <ide> </section> <ide> <ide> ## Instructions <ide> <section id='instructions'> <ide> Create a second <code>p</code> element after the existing <code>p</code> element with the following kitty ipsum text: <code>Purr jump eat the grass rip the couch scratched sunbathe, shed everywhere rip the couch sleep in the sink fluffy fur catnip scratched.</code> <del>Wrap the paragraphs with an opening and closing <code>main</code> tag. <add>Then, create a <code>main</code> element and nest the two <code>p</code> elements inside the <code>main</code> element. <ide> </section> <ide> <ide> ## Tests <ide> tests: <ide> ## Solution <ide> <section id='solution'> <ide> <del>```js <del>// solution required <add>```html <add><h2>CatPhotoApp</h2> <add><main> <add> <p>Kitty ipsum dolor sit amet, shed everywhere shed everywhere stretching attack your ankles chase the red dot, hairball run catnip eat the grass sniff.</p> <add> <p>Purr jump eat the grass rip the couch scratched sunbathe, shed everywhere rip the couch sleep in the sink fluffy fur catnip scratched.</p> <add></main> <ide> ``` <ide> </section>
1
Ruby
Ruby
make generic caveats for launchd plist files
faf51f254d912e5e0c39a1f4fa5a696bd67c56c4
<ide><path>Library/Homebrew/formula.rb <ide> def etc; HOMEBREW_PREFIX+'etc' end <ide> def var; HOMEBREW_PREFIX+'var' end <ide> <ide> # override this to provide a plist <del> def startup_plist; nil; end <add> def plist; nil; end <add> alias :startup_plist :plist <ide> # plist name, i.e. the name of the launchd service <ide> def plist_name; 'homebrew.mxcl.'+name end <ide> def plist_path; prefix+(plist_name+'.plist') end <add> def plist_manual; self.class.plist_manual end <add> def plist_startup; self.class.plist_startup end <ide> <ide> def build <ide> self.class.build <ide> def #{attr}(val=nil) <ide> end <ide> <ide> attr_rw :homepage, :keg_only_reason, :skip_clean_all, :cc_failures <add> attr_rw :plist_startup, :plist_manual <ide> <ide> Checksum::TYPES.each do |cksum| <ide> class_eval %Q{ <ide> def option name, description=nil <ide> build.add name, description <ide> end <ide> <add> def plist_options options <add> @plist_startup = options[:startup] <add> @plist_manual = options[:manual] <add> end <add> <ide> def conflicts_with formula, opts={} <ide> dependencies.add ConflictRequirement.new(formula, name, opts) <ide> end <ide><path>Library/Homebrew/formula_installer.rb <ide> def caveats <ide> end <ide> <ide> keg = Keg.new(f.prefix) <del> <ide> if keg.completion_installed? :bash <ide> ohai 'Caveats', <<-EOS.undent <ide> Bash completion has been installed to: <ide> def caveats <ide> #{HOMEBREW_PREFIX}/share/zsh/site-functions <ide> EOS <ide> end <add> <add> if f.plist or keg.plist_installed? <add> if f.plist_startup and false <add> destination = '/Library/LaunchDaemons' <add> else <add> destination = '~/Library/LaunchAgents' <add> end <add> <add> plist_filename = f.plist_path.basename <add> plist_link = "#{destination}/#{plist_filename}" <add> plist_domain = f.plist_path.basename('.plist') <add> launchctl_load = "launchctl load -w #{plist_link}" <add> destination_path = Pathname.new File.expand_path destination <add> plist_path = destination_path/plist_filename <add> s = [] <add> <add> # we readlink because this path probably doesn't exist since caveats <add> # occurs before the link step of installation <add> if not (plist_path).file? and not (plist_path).symlink? <add> s << "To have launchd start #{f.name} at login:" <add> s << " mkdir -p #{destination}" unless destination_path.directory? <add> s << " ln -sfv #{HOMEBREW_PREFIX}/opt/#{f.name}/*.plist #{destination}" #sudo <add> s << "Then to load #{f.name} now:" <add> s << " #{launchctl_load}" <add> if f.plist_manual <add> s << "Or, if you don't want/need launchctl, you can just run:" <add> s << " #{f.plist_manual}" <add> end <add> elsif Kernel.system "/bin/launchctl list #{plist_domain} &>/dev/null" <add> s << "You should reload #{f.name}:" <add> s << " launchctl unload -w #{plist_link}" <add> s << " #{launchctl_load}" <add> else <add> s << "To load #{f.name}:" <add> s << " #{launchctl_load}" <add> end <add> <add> ohai 'Caveats', s <add> end <ide> end <ide> <ide> def finish <ide> def link <ide> end <ide> <ide> def install_plist <del> if f.startup_plist <del> # A plist may already exist if we are installing from a bottle <del> f.plist_path.unlink if f.plist_path.exist? <del> f.plist_path.write f.startup_plist <del> f.plist_path.chmod 0644 <del> end <add> return unless f.plist <add> # A plist may already exist if we are installing from a bottle <add> f.plist_path.unlink if f.plist_path.exist? <add> f.plist_path.write f.plist <add> f.plist_path.chmod 0644 <ide> end <ide> <ide> def fix_install_names <ide><path>Library/Homebrew/keg.rb <ide> def completion_installed? shell <ide> dir.directory? and not dir.children.length.zero? <ide> end <ide> <add> def plist_installed? <add> Dir.chdir self do <add> not Dir.glob("*.plist").empty? <add> end <add> end <add> <ide> def version <ide> require 'version' <ide> Version.new(basename.to_s)
3
Python
Python
clarify tofile requirement
d3820fe823087fff37433fb0b2cb76c0b984fe44
<ide><path>numpy/add_newdocs.py <ide> def luf(lamdaexpr, *args, **kwargs): <ide> machines with different endianness. Some of these problems can be overcome <ide> by outputting the data as text files, at the expense of speed and file <ide> size. <add> <add> When fid is a file object, array contents are directly written to the <add> file, bypassing the file object's ``write`` method. As a result, tofile <add> cannot be used with files objects supporting compression (e.g., GzipFile) <add> or file-like objects that do not support ``fileno()`` (e.g., BytesIO). <ide> <ide> """)) <ide>
1
Python
Python
unify computation of `nbin[i]`
89b402a9dab57c45eca0f942bde699ee6961a1f5
<ide><path>numpy/lib/histograms.py <ide> def histogramdd(sample, bins=10, range=None, normed=False, weights=None): <ide> if bins[i] < 1: <ide> raise ValueError( <ide> '`bins[{}]` must be positive, when an integer'.format(i)) <del> nbin[i] = bins[i] + 2 # +2 for outlier bins <del> edges[i] = np.linspace(smin[i], smax[i], nbin[i]-1, dtype=edge_dt) <add> edges[i] = np.linspace(smin[i], smax[i], bins[i] + 1, dtype=edge_dt) <ide> else: <ide> edges[i] = np.asarray(bins[i], edge_dt) <del> nbin[i] = len(edges[i]) + 1 # +1 for outlier bins <add> nbin[i] = len(edges[i]) + 1 # includes an outlier on each end <ide> dedges[i] = np.diff(edges[i]) <ide> # not just monotonic, due to the use of mindiff below <ide> if np.any(np.asarray(dedges[i]) <= 0):
1
Python
Python
fix duplicate from merge [ci skip]
bfc212e68fae3eef401474794055d901f9db010f
<ide><path>spacy/language.py <ide> def make_doc(self, text: str) -> Doc: <ide> Errors.E088.format(length=len(text), max_length=self.max_length) <ide> ) <ide> return self.tokenizer(text) <del> return self.tokenizer(text) <ide> <ide> def update( <ide> self,
1
Javascript
Javascript
add coverage for breaklength one-column array
f0fc4b8a28ca386df74b1716be3c1f1977c265b4
<ide><path>test/parallel/test-util-inspect.js <ide> assert.strictEqual( <ide> Object.setPrototypeOf(generatorPrototype, originalProtoOfProto); <ide> assert.strictEqual(getProtoOfProto(), originalProtoOfProto); <ide> } <add> <add>{ <add> // Test for when breakLength results in a single column. <add> const obj = Array(9).fill('fhqwhgadshgnsdhjsdbkhsdabkfabkveybvf'); <add> assert.strictEqual( <add> util.inspect(obj, { breakLength: 256 }), <add> '[\n' + <add> " 'fhqwhgadshgnsdhjsdbkhsdabkfabkveybvf',\n" + <add> " 'fhqwhgadshgnsdhjsdbkhsdabkfabkveybvf',\n" + <add> " 'fhqwhgadshgnsdhjsdbkhsdabkfabkveybvf',\n" + <add> " 'fhqwhgadshgnsdhjsdbkhsdabkfabkveybvf',\n" + <add> " 'fhqwhgadshgnsdhjsdbkhsdabkfabkveybvf',\n" + <add> " 'fhqwhgadshgnsdhjsdbkhsdabkfabkveybvf',\n" + <add> " 'fhqwhgadshgnsdhjsdbkhsdabkfabkveybvf',\n" + <add> " 'fhqwhgadshgnsdhjsdbkhsdabkfabkveybvf',\n" + <add> " 'fhqwhgadshgnsdhjsdbkhsdabkfabkveybvf'\n" + <add> ']' <add> ); <add>}
1
Text
Text
add spanish translation
76363247e4e21165e76a4531dcce9251bafa2663
<ide><path>curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/remember-to-set-the-constructor-property-when-changing-the-prototype.spanish.md <ide> videoUrl: '' <ide> localeTitle: Recuerde establecer la propiedad del constructor al cambiar el prototipo <ide> --- <ide> <del>## Description <add>## Descripción <ide> <section id="description"> Hay un efecto secundario crucial de configurar manualmente el <code>prototype</code> en un nuevo objeto. Se borró la propiedad del <code>constructor</code> ! El código del desafío anterior imprimirá lo siguiente para el <code>duck</code> : <blockquote> console.log (duck.constructor) <br> // imprime &#39;indefinido&#39; - ¡Vaya! </blockquote> Para solucionar esto, siempre que un prototipo se establezca manualmente en un nuevo objeto, recuerde definir la propiedad del <code>constructor</code> : <blockquote> Bird.prototype = { <br> constructor: Bird, // define la propiedad del constructor <br> NumLegs: 2, <br> comer: función () { <br> console.log (&quot;nom nom nom&quot;); <br> } <br> describe: function () { <br> console.log (&quot;Mi nombre es&quot; + this.name); <br> } <br> }; </blockquote></section> <ide> <del>## Instructions <add>## Instrucciones <ide> <section id="instructions"> Definir la propiedad del <code>constructor</code> en el <code>prototype</code> <code>Dog</code> . </section> <ide> <del>## Tests <add>## Pruebas <ide> <section id='tests'> <ide> <ide> ```yml <ide> function Dog(name) { <ide> this.name = name; <ide> } <ide> <del>// Modify the code below this line <add>// Modifica el código debajo de esta linea <ide> Dog.prototype = { <ide> <ide> numLegs: 2, <ide> Dog.prototype = { <ide> <ide> </section> <ide> <del>## Solution <add>## Solución <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add>// Solución requerida <ide> ``` <ide> </section>
1
Text
Text
add huggingartists to community notebooks
3157fa3c5330342e8a14c2d13d0678eb9dbcb20e
<ide><path>docs/source/community.md <del># Community <add># Community <ide> <ide> This page regroups resources around 🤗 Transformers developed by the community. <ide> <ide> This page regroups resources around 🤗 Transformers developed by the community <ide> <ide> | Notebook | Description | Author | | <ide> |:----------|:-------------|:-------------|------:| <add>| [Fine-tune a pre-trained Transformer to generate lyrics](https://github.com/AlekseyKorshuk/huggingartists) | How to generate lyrics in the style of your favorite artist by fine-tuning a GPT-2 model | [Aleksey Korshuk](https://github.com/AlekseyKorshuk) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/AlekseyKorshuk/huggingartists/blob/master/huggingartists-demo.ipynb) | <ide> | [Train T5 in Tensorflow 2 ](https://github.com/snapthat/TF-T5-text-to-text) | How to train T5 for any task using Tensorflow 2. This notebook demonstrates a Question & Answer task implemented in Tensorflow 2 using SQUAD | [Muhammad Harris](https://github.com/HarrisDePerceptron) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/snapthat/TF-T5-text-to-text/blob/master/snapthatT5/notebooks/TF-T5-Datasets%20Training.ipynb) | <ide> | [Train T5 on TPU](https://github.com/patil-suraj/exploring-T5/blob/master/T5_on_TPU.ipynb) | How to train T5 on SQUAD with Transformers and Nlp | [Suraj Patil](https://github.com/patil-suraj) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patil-suraj/exploring-T5/blob/master/T5_on_TPU.ipynb#scrollTo=QLGiFCDqvuil) | <ide> | [Fine-tune T5 for Classification and Multiple Choice](https://github.com/patil-suraj/exploring-T5/blob/master/t5_fine_tuning.ipynb) | How to fine-tune T5 for classification and multiple choice tasks using a text-to-text format with PyTorch Lightning | [Suraj Patil](https://github.com/patil-suraj) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patil-suraj/exploring-T5/blob/master/t5_fine_tuning.ipynb) |
1
Javascript
Javascript
fix iterations for take
7217e1d1834c0bcb3487942fbddf66f1e2bbac02
<ide><path>dist/Immutable.js <ide> var $Sequence = Sequence; <ide> } <ide> var iterations = 0; <ide> sequence.__iterate((function(v, k) { <del> if (iterations < amount && fn(v, k, $__0) !== false) { <del> iterations++; <del> } else { <del> return false; <del> } <add> return iterations < amount && ++iterations && fn(v, k, $__0); <ide> })); <ide> return iterations; <ide> }; <ide><path>dist/Immutable.min.js <ide> return s[r]=i,new tn(t,u+1,s)}function H(t,e,n){for(var r=[],i=0;n.length>i;i++) <ide> if(h&&!c)return t;if(n>0){var f=t&&t.array[o],_=ue(f,e,n-we,r,u,s);return _===f?t:(a=se(t,e),a.array[o]=_,a)}return!h&&c&&t.array[o]===u?t:(i(s),a=se(t,e),h&&o===a.array.length-1?a.array.pop():a.array[o]=h?void 0:u,a)}function se(t,e){return e&&t&&e===t.ownerID?t:new vn(t?t.array.slice():[],e)}function ae(t,e){if(e>=ce(t._size))return t._tail;if(1<<t._level+we>e){for(var n=t._root,r=t._level;n&&r>0;)n=n.array[e>>>r&Ie],r-=we;return n}}function he(t,e,n){var r=t.__ownerID||new u,i=t._origin,s=t._size,a=i+e,h=null==n?s:0>n?s+n:i+n;if(a===i&&h===s)return t;if(a>=h)return t.clear();for(var o=t._level,c=t._root,f=0;0>a+f;)c=new vn(c&&c.array.length?[null,c]:[],r),o+=we,f+=1<<o;f&&(a+=f,i+=f,h+=f,s+=f);for(var _=ce(s),l=ce(h);l>=1<<o+we;)c=new vn(c&&c.array.length?[c]:[],r),o+=we;var v=t._tail,g=_>l?ae(t,h-1):l>_?new vn([],r):v;if(v&&l>_&&s>a&&v.array.length){c=se(c,r);for(var p=c,m=o;m>we;m-=we){var d=_>>>m&Ie;p=p.array[d]=se(p.array[d],r)}p.array[_>>>we&Ie]=v}if(s>h&&(g=g&&g.removeAfter(r,0,h)),a>=l)a-=l,h-=l,o=we,c=null,g=g&&g.removeBefore(r,0,a);else if(a>i||_>l){var y,w;f=0;do y=a>>>o&Ie,w=l-1>>>o&Ie,y===w&&(y&&(f+=(1<<o)*y),o-=we,c=c&&c.array[y]);while(c&&y===w);c&&a>i&&(c=c&&c.removeBefore(r,o,a-f)),c&&_>l&&(c=c&&c.removeAfter(r,o,l-f)),f&&(a-=f,h-=f)}return t.__ownerID?(t.length=h-a,t._origin=a,t._size=h,t._level=o,t._root=c,t._tail=g,t.__hash=void 0,t.__altered=!0,t):re(a,h,o,c,g)}function oe(t,e,n){for(var r=[],i=0;n.length>i;i++){var u=n[i];u&&r.push(Pe(u))}var s=Math.max.apply(null,r.map(function(t){return t.length||0}));return s>t.length&&(t=t.setLength(s)),T(t,e,r)}function ce(t){return Se>t?0:t-1>>>we<<we}function fe(t,e){var n=Object.create(wn);return n.length=t?t.length:0,n._map=t,n.__ownerID=e,n}function _e(t,e,n,r){var i=Object.create(In.prototype);return i.length=t?t.length:0,i._map=t,i._vector=e,i.__ownerID=n,i.__hash=r,i}function le(t,e,n){var r=t._map,i=t._vector,u=r.get(e),s=void 0!==u,a=n===ke;if(!s&&a||s&&n===i.get(u)[1])return t;s||(u=i.length);var h=a?r.remove(e):s?r:r.set(e,u),o=a?i.remove(u):i.set(u,[e,n]); <ide> return t.__ownerID?(t.length=h.length,t._map=h,t._vector=o,t.__hash=void 0,t):_e(h,o)}function ve(t,e,n){var r=Object.create(Object.getPrototypeOf(t));return r._map=e,r.__ownerID=n,r}function ge(t,e){return e?pe(e,t,"",{"":t}):me(t)}function pe(t,e,n,r){return e&&(Array.isArray(e)||e.constructor===Object)?t.call(r,n,Pe(e).map(function(n,r){return pe(t,n,r,e)})):e}function me(t){if(t){if(Array.isArray(t))return Pe(t).map(me).toVector();if(t.constructor===Object)return Pe(t).map(me).toMap()}return t}var de=Object,ye={};ye.createClass=t,ye.superCall=e,ye.defaultSuperCall=n;var we=5,Se=1<<we,Ie=Se-1,ke={},Me={value:!1},be={value:!1},qe={value:void 0,done:!1},De="delete",Oe="undefined"!=typeof Symbol?Symbol.iterator:"@@iterator",Ae=2147483647,xe=0,Ce="__immutablehash__";"undefined"!=typeof Symbol&&(Ce=Symbol(Ce));var Ee=!1,je=16,Ue=255,Re=0,We={},Pe=function(t){return Je.from(1===arguments.length?t:Array.prototype.slice.call(arguments))},Je=Pe;ye.createClass(Pe,{toString:function(){return this.__toString("Seq {","}")},__toString:function(t,e){return 0===this.length?t+e:t+" "+this.map(this.__toStringMapper).join(", ")+" "+e},__toStringMapper:function(t,e){return e+": "+A(t)},toJS:function(){return this.map(function(t){return t instanceof Je?t.toJS():t}).__toJS()},toArray:function(){E(this.length);var t=Array(this.length||0);return this.valueSeq().forEach(function(e,n){t[n]=e}),t},toObject:function(){E(this.length);var t={};return this.forEach(function(e,n){t[n]=e}),t},toVector:function(){return E(this.length),fn.from(this)},toMap:function(){return E(this.length),Te.from(this)},toOrderedMap:function(){return E(this.length),In.from(this)},toSet:function(){return E(this.length),dn.from(this)},toKeyedSeq:function(){return this},hashCode:function(){return this.__hash||(this.__hash=1/0===this.length?0:this.reduce(function(t,e,n){return t+(c(e)^(e===n?0:c(n)))&Ae},0))},equals:function(t){if(this===t)return!0;if(!(t instanceof Je))return!1;if(null!=this.length&&null!=t.length){if(this.length!==t.length)return!1;if(0===this.length&&0===t.length)return!0 <ide> }return null!=this.__hash&&null!=t.__hash&&this.__hash!==t.__hash?!1:this.__deepEquals(t)},__deepEquals:function(t){var e=this.cacheResult().entrySeq().toArray(),n=0;return t.every(function(t,r){var i=e[n++];return P(r,i[0])&&P(t,i[1])})},join:function(t){t=void 0!==t?""+t:",";var e="",n=!0;return this.forEach(function(r){n?(n=!1,e+=null!=r?r:""):e+=t+(null!=r?r:"")}),e},count:function(t,e){return t?this.filter(t,e).count():(null==this.length&&(this.length=this.forEach(k)),this.length)},countBy:function(t){var e=this;return In.empty().withMutations(function(n){e.forEach(function(e,r,i){n.update(t(e,r,i),b)})})},concat:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];var n=[this].concat(t.map(function(t){return Je(t)})),r=this.__makeSequence();return r.length=n.reduce(function(t,e){return null!=t&&null!=e.length?t+e.length:void 0},0),r.__iterateUncached=function(t,e){for(var r,i=0,u=n.length-1,s=0;u>=s&&!r;s++){var a=n[e?u-s:s];i+=a.__iterate(function(e,n,i){return t(e,n,i)===!1?(r=!0,!1):void 0},e)}return i},r},reverse:function(){var t=this,e=t.__makeSequence();return e.reverse=function(){return t},e.length=t.length,e.__iterateUncached=function(e,n){return t.__iterate(e,!n)},e},keySeq:function(){return this.flip().valueSeq()},valueSeq:function(){var t=this,e=g(t);return e.length=t.length,e.__iterateUncached=function(e,n,r){var i,u=this,s=0;if(r){var a=this.length-1;i=function(t){return e(t,a-s++,u)!==!1}}else i=function(t){return e(t,s++,u)!==!1};return t.__iterate(i,n),s},e},entrySeq:function(){var t=this;if(t._cache)return Je(t._cache);var e=t.map(I).valueSeq();return e.fromEntries=function(){return t},e},forEach:function(t,e){return this.__iterate(e?t.bind(e):t)},reduce:function(t,e,n){var r,i;return 2>arguments.length?i=!0:r=e,this.forEach(function(e,u,s){i?(i=!1,r=e):r=t.call(n,r,e,u,s)}),r},reduceRight:function(){var t=this.toKeyedSeq().reverse();return t.reduce.apply(t,arguments)},every:function(t,e){var n=!0;return this.forEach(function(r,i,u){return t.call(e,r,i,u)?void 0:(n=!1,!1)}),n <del>},some:function(t,e){return!this.every(O(t),e)},first:function(){return this.find(k)},last:function(){return this.findLast(k)},rest:function(){return this.slice(1)},butLast:function(){return this.slice(0,-1)},has:function(t){return this.get(t,ke)!==ke},get:function(t,e){return this.find(function(e,n){return P(n,t)},null,e)},getIn:function(t,e){return t&&0!==t.length?p(this,t,e,0):this},contains:function(t){return this.find(function(e){return P(e,t)},null,ke)!==ke},find:function(t,e,n){var r=n;return this.forEach(function(n,i,u){return t.call(e,n,i,u)?(r=n,!1):void 0}),r},findKey:function(t,e){var n;return this.forEach(function(r,i,u){return t.call(e,r,i,u)?(n=i,!1):void 0}),n},findLast:function(t,e,n){return this.toKeyedSeq().reverse().find(t,e,n)},findLastKey:function(t,e){return this.toKeyedSeq().reverse().findKey(t,e)},flip:function(){var t=this,e=v();return e.length=t.length,e.flip=function(){return t},e.__iterateUncached=function(e,n){var r=this;return t.__iterate(function(t,n){return e(n,t,r)!==!1},n)},e},map:function(t,e){var n=this,r=n.__makeSequence();return r.length=n.length,r.__iterateUncached=function(r,i){var u=this;return n.__iterate(function(n,i,s){return r(t.call(e,n,i,s),i,u)!==!1},i)},r},mapKeys:function(t,e){var n=this,r=n.__makeSequence();return r.length=n.length,r.__iterateUncached=function(r,i){var u=this;return n.__iterate(function(n,i,s){return r(n,t.call(e,i,n,s),u)!==!1},i)},r},filter:function(t,e){return q(this,t,e,!0)},slice:function(t,e){if(m(t,e,this.length))return this;var n=d(t,this.length),r=y(e,this.length);if(n!==n||r!==r)return this.entrySeq().slice(t,e).fromEntrySeq();var i=0===n?this:this.skip(n);return null==r||r===this.length?i:i.take(r-n)},take:function(t){var e=this;if(t>e.length)return e;var n=e.__makeSequence();return n.__iterateUncached=function(n,r,i){var u=this;if(r)return this.cacheResult().__iterate(n,r,i);var s=0;return e.__iterate(function(e,r){return t>s&&n(e,r,u)!==!1?void s++:!1}),s},n.length=this.length&&Math.min(this.length,t),n},takeLast:function(t){return this.reverse().take(t).reverse() <add>},some:function(t,e){return!this.every(O(t),e)},first:function(){return this.find(k)},last:function(){return this.findLast(k)},rest:function(){return this.slice(1)},butLast:function(){return this.slice(0,-1)},has:function(t){return this.get(t,ke)!==ke},get:function(t,e){return this.find(function(e,n){return P(n,t)},null,e)},getIn:function(t,e){return t&&0!==t.length?p(this,t,e,0):this},contains:function(t){return this.find(function(e){return P(e,t)},null,ke)!==ke},find:function(t,e,n){var r=n;return this.forEach(function(n,i,u){return t.call(e,n,i,u)?(r=n,!1):void 0}),r},findKey:function(t,e){var n;return this.forEach(function(r,i,u){return t.call(e,r,i,u)?(n=i,!1):void 0}),n},findLast:function(t,e,n){return this.toKeyedSeq().reverse().find(t,e,n)},findLastKey:function(t,e){return this.toKeyedSeq().reverse().findKey(t,e)},flip:function(){var t=this,e=v();return e.length=t.length,e.flip=function(){return t},e.__iterateUncached=function(e,n){var r=this;return t.__iterate(function(t,n){return e(n,t,r)!==!1},n)},e},map:function(t,e){var n=this,r=n.__makeSequence();return r.length=n.length,r.__iterateUncached=function(r,i){var u=this;return n.__iterate(function(n,i,s){return r(t.call(e,n,i,s),i,u)!==!1},i)},r},mapKeys:function(t,e){var n=this,r=n.__makeSequence();return r.length=n.length,r.__iterateUncached=function(r,i){var u=this;return n.__iterate(function(n,i,s){return r(n,t.call(e,i,n,s),u)!==!1},i)},r},filter:function(t,e){return q(this,t,e,!0)},slice:function(t,e){if(m(t,e,this.length))return this;var n=d(t,this.length),r=y(e,this.length);if(n!==n||r!==r)return this.entrySeq().slice(t,e).fromEntrySeq();var i=0===n?this:this.skip(n);return null==r||r===this.length?i:i.take(r-n)},take:function(t){var e=this;if(t>e.length)return e;var n=e.__makeSequence();return n.__iterateUncached=function(n,r,i){var u=this;if(r)return this.cacheResult().__iterate(n,r,i);var s=0;return e.__iterate(function(e,r){return t>s&&++s&&n(e,r,u)}),s},n.length=this.length&&Math.min(this.length,t),n},takeLast:function(t){return this.reverse().take(t).reverse() <ide> },takeWhile:function(t,e){var n=this,r=n.__makeSequence();return r.__iterateUncached=function(r,i,u){var s=this;if(i)return this.cacheResult().__iterate(r,i,u);var a=0;return n.__iterate(function(n,i,u){return t.call(e,n,i,u)&&r(n,i,s)!==!1?void a++:!1}),a},r},takeUntil:function(t,e){return this.takeWhile(O(t),e)},skip:function(t){var e=this;if(0===t)return e;var n=e.__makeSequence();return n.__iterateUncached=function(n,r,i){var u=this;if(r)return this.cacheResult().__iterate(n,r,i);var s=!0,a=0,h=0;return e.__iterate(function(e,r){if(!s||!(s=h++<t)){if(n(e,r,u)===!1)return!1;a++}}),a},n.length=this.length&&Math.max(0,this.length-t),n},skipLast:function(t){return this.reverse().skip(t).reverse()},skipWhile:function(t,e){var n=this,r=n.__makeSequence();return r.__iterateUncached=function(r,i,u){var s=this;if(i)return this.cacheResult().__iterate(r,i,u);var a=!0,h=0;return n.__iterate(function(n,i,u){if(!a||!(a=t.call(e,n,i,u))){if(r(n,i,s)===!1)return!1;h++}}),h},r},skipUntil:function(t,e){return this.skipWhile(O(t),e)},groupBy:function(t,e){return D(this,t,e,!0)},sort:function(t){return this.sortBy(S,t)},sortBy:function(t,e){e=e||x;var n=this;return Je(this.entrySeq().entrySeq().toArray().sort(function(r,i){return e(t(r[1][1],r[1][0],n),t(i[1][1],i[1][0],n))||r[0]-i[0]})).fromEntrySeq().valueSeq().fromEntrySeq()},cacheResult:function(){return!this._cache&&this.__iterateUncached&&(E(this.length),this._cache=this.entrySeq().toArray(),null==this.length&&(this.length=this._cache.length)),this},__iterate:function(t,e){var n=this._cache;if(n){for(var r=n.length-1,i=0;r>=i;i++){var u=n[e?r-i:i];if(t(u[1],u[0],this)===!1)break}return i}return this.__iterateUncached(t,e)},__makeSequence:function(){return v()}},{from:function(t){if(t instanceof Je)return t;if(!Array.isArray(t)){if(t&&t.constructor===Object)return new Ne(t);t=[t]}return new Fe(t)}});var ze=Pe.prototype;ze.toJSON=ze.toJS,ze.__toJS=ze.toObject,ze.inspect=ze.toSource=function(){return""+this};var Ke=function(){ye.defaultSuperCall(this,Be.prototype,arguments)},Be=Ke; <ide> ye.createClass(Ke,{toString:function(){return this.__toString("Seq [","]")},toArray:function(){E(this.length);var t=Array(this.length||0);return t.length=this.forEach(function(e,n){t[n]=e}),t},toKeyedSeq:function(){return new Ve(this)},valueSeq:function(){return this},fromEntrySeq:function(){var t=this,e=v();return e.length=t.length,e.entrySeq=function(){return t},e.__iterateUncached=function(e,n){var r=this;return t.__iterate(function(t){return t&&e(t[1],t[0],r)},n)},e},join:function(t){t=void 0!==t?""+t:",";var e="";return this.forEach(function(n,r){e+=(r?t:"")+(null!=n?n:"")}),e},concat:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];var n=[this].concat(t),r=Pe(n).flatten();return r.length=n.reduce(function(t,e){if(void 0!==t){var n=Pe(e).length;if(null!=n)return t+n}},0),r},reverse:function(){var t=this,e=t.__makeSequence();return e.reverse=function(){return t},e.length=t.length,e.__reversedIndices=t.__reversedIndices,e.__iterateUncached=function(e,n,r){var i=this,u=r?this.length:0;return t.__iterate(function(t){return e(t,r?--u:u++,i)!==!1},!n)},e},filter:function(t,e){return q(this,t,e,!1)},get:function(t,e){return t=C(this,t),this.find(function(e,n){return n===t},null,e)},indexOf:function(t){return this.findIndex(function(e){return P(e,t)})},lastIndexOf:function(t){return this.toKeyedSeq().reverse().indexOf(t)},findIndex:function(t,e){var n=this.findKey(t,e);return null==n?-1:n},findLastIndex:function(t,e){return this.toKeyedSeq().reverse().findIndex(t,e)},slice:function(t,e){var n=this;if(m(t,e,n.length))return n;var r=n.__makeSequence(),i=d(t,n.length),u=y(e,n.length);return r.length=n.length&&u-i,r.__reversedIndices=n.__reversedIndices,r.__iterateUncached=function(r,s,a){var h=this;if(s)return this.cacheResult().__iterate(r,s,a);var o=this.__reversedIndices^a;if(i!==i||u!==u||o&&null==n.length){var c=n.count();i=d(t,c),u=y(e,c)}var f=o?n.length-u:i,_=o?n.length-i:u,l=n.__iterate(function(t,e){return o?null!=_&&e>=_||e>=f&&r(t,e-f,h)!==!1:f>e||(null==_||_>e)&&r(t,e-f,h)!==!1},s,a);return null!=this.length?this.length:Math.max(0,l-f) <ide> },r},splice:function(t,e){var n=arguments.length;if(e=Math.max(0|e,0),0===n||2===n&&!e)return this;t=d(t,this.length);var r=this.slice(0,t);return 1===n?r:r.concat(s(arguments,2),this.slice(t+e))},flatten:function(){var t=this,e=this.__makeSequence();return e.__iterateUncached=function(e,n,r){var i=this,u=0,s=this.length-1;return t.__iterate(function(t){var a=!1;return Pe(t).__iterate(function(t){return e(t,r?s-u++:u++,i)===!1?(a=!0,!1):void 0},n),!a},n),u},e},flatMap:function(t,e){return this.map(t,e).flatten()},skip:function(t){var e=this;if(0===t)return e;var n=e.__makeSequence();return n.__iterateUncached=function(n,r,i){var u=this;if(r)return this.cacheResult().__iterate(n,r,i);var s=e.__reversedIndices^i,a=!0,h=0,o=0,c=e.__iterate(function(e,r){return a&&(a=o++<t,a||(h=r)),a||n(e,s?r:r-h,u)!==!1},r,i);return s?h+1:c-h},n.length=this.length&&Math.max(0,this.length-t),n},skipWhile:function(t,e){var n=this,r=n.__makeSequence();return r.__iterateUncached=function(r,i,u){var s=this;if(i)return this.cacheResult().__iterate(r,i,u);var a=n.__reversedIndices^u,h=!0,o=0,c=n.__iterate(function(n,i,u){return h&&(h=t.call(e,n,i,u),h||(o=i)),h||r(n,a?i:i-o,s)!==!1},i,u);return a?o+1:c-o},r},groupBy:function(t,e){return D(this,t,e,!1)},sortBy:function(t,e){e=e||x;var n=this;return Pe(this.entrySeq().toArray().sort(function(r,i){return e(t(r[1],r[0],n),t(i[1],i[0],n))||r[0]-i[0]})).fromEntrySeq().valueSeq()},__iterate:function(t,e,n){var r=this._cache;if(r){n^=e;for(var i=r.length-1,u=0;i>=u;u++){var s=r[e?i-u:u],a=s[0];if(t(s[1],n?i-a:a,this)===!1)break}return u}return n&&!this.length?this.cacheResult().__iterate(t,e,n):this.__iterateUncached(t,e,n)},__makeSequence:function(){return g(this)}},{},Pe);var Le=Ke.prototype;Le.__toJS=Le.toArray,Le.__toStringMapper=A,Le.chain=Le.flatMap;var Ve=function(t){this._seq=t,this.length=t.length};ye.createClass(Ve,{get:function(t,e){return this._seq.get(t,e)},has:function(t){return this._seq.has(t)},__iterate:function(t,e){return this._seq.__iterate(t,e,e)}},{},Pe);var Ne=function(t){var e=Object.keys(t); <ide><path>src/Sequence.js <ide> class Sequence { <ide> return this.cacheResult().__iterate(fn, reverse, flipIndices); <ide> } <ide> var iterations = 0; <del> sequence.__iterate((v, k) => { <del> if (iterations < amount && fn(v, k, this) !== false) { <del> iterations++; <del> } else { <del> return false; <del> } <del> }); <add> sequence.__iterate((v, k) => <add> iterations < amount && ++iterations && fn(v, k, this) <add> ); <ide> return iterations; <ide> }; <ide> takeSequence.length = this.length && Math.min(this.length, amount);
3
Python
Python
set version to v3.0.0a3
1827f22f56a1a6b6541f35a527c304cdf632f0b1
<ide><path>spacy/about.py <ide> # fmt: off <ide> __title__ = "spacy-nightly" <del>__version__ = "3.0.0a2" <add>__version__ = "3.0.0a3" <ide> __release__ = True <ide> __download_url__ = "https://github.com/explosion/spacy-models/releases/download" <ide> __compatibility__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json"
1
PHP
PHP
include test to .0 and .00 decimals
18aa5a040f28ffad5dead569c5c07e6a7cb018c3
<ide><path>lib/Cake/Test/Case/Utility/ValidationTest.php <ide> public function testDecimal() { <ide> $this->assertTrue(Validation::decimal('+1234')); <ide> $this->assertTrue(Validation::decimal(1234.56)); <ide> $this->assertTrue(Validation::decimal(1234.00)); <add> $this->assertTrue(Validation::decimal(.0)); <add> $this->assertTrue(Validation::decimal(.00)); <add> $this->assertTrue(Validation::decimal(.01)); <ide> <ide> $this->assertFalse(Validation::decimal('string')); <ide> }
1
Text
Text
use es6 syntax in fetchposts()
c4c69f33180d27e8f0e081371fe5482a2a1f4c7d
<ide><path>docs/advanced/AsyncActions.md <ide> Here’s what the state shape for our “Reddit headlines” app might look like <ide> { <ide> id: 42, <ide> title: 'Confusion about Flux and Relay' <del> }, <add> }, <ide> { <ide> id: 500, <ide> title: 'Creating a Simple Application Using React JS and Flux Architecture' <ide> export function fetchPosts(reddit) { <ide> // It passes the dispatch method as an argument to the function, <ide> // thus making it able to dispatch actions itself. <ide> <del> return function (dispatch) { <add> return dispatch => { <ide> <ide> // First dispatch: the app state is updated to inform <ide> // that the API call is starting.
1
PHP
PHP
fix bad search replace
b9813be5ca898e1f497c37caeddcef5f5ae826fb
<ide><path>src/Database/Type/DateType.php <ide> class DateType extends DateTimeType <ide> * class is constructed. After that use `useMutable()` or `useImmutable()` instead. <ide> * <ide> * @var string <del> * @deprecated 3.2.0 Use DateTypeFactory::useMutable() or DateTypeFactory::useImmutable() instead. <add> * @deprecated 3.2.0 Use DateType::useMutable() or DateType::useImmutable() instead. <ide> */ <ide> public static $dateTimeClass = 'Cake\I18n\Date'; <ide>
1
Javascript
Javascript
add zh-cn for localization
eb404805a6bc91c8ebaf05511631445e62262cc5
<ide><path>src/locale/zh-CN.js <add>import "locale"; <add> <add>var d3_locale_zhCN = d3.locale({ <add> decimal: ".", <add> thousands: ",", <add> grouping: [3], <add> currency: ["¥", ""], <add> dateTime: "%a %b %e %X %Y", <add> date: "%Y/%-m/%-d", <add> time: "%H:%M:%S", <add> periods: ["上午", "下午"], <add> days: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"], <add> shortDays: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"], <add> months: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"], <add> shortMonths: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"] <add>});
1
Ruby
Ruby
restore connection_id on error
8ca93c78832f4fdc78320e3f73ffd07bb71ce196
<ide><path>activerecord/lib/active_record/query_cache.rb <ide> def call(env) <ide> <ide> response = @app.call(env) <ide> response[2] = Rack::BodyProxy.new(response[2]) do <del> ActiveRecord::Base.connection_id = connection_id <del> ActiveRecord::Base.connection.clear_query_cache <del> ActiveRecord::Base.connection.disable_query_cache! unless enabled <add> restore_query_cache_settings(connection_id, enabled) <ide> end <ide> <ide> response <ide> rescue Exception => e <add> restore_query_cache_settings(connection_id, enabled) <add> raise e <add> end <add> <add> private <add> <add> def restore_query_cache_settings(connection_id, enabled) <add> ActiveRecord::Base.connection_id = connection_id <ide> ActiveRecord::Base.connection.clear_query_cache <ide> ActiveRecord::Base.connection.disable_query_cache! unless enabled <del> raise e <ide> end <add> <ide> end <ide> end <ide><path>activerecord/test/cases/query_cache_test.rb <ide> def test_exceptional_middleware_leaves_enabled_cache_alone <ide> assert ActiveRecord::Base.connection.query_cache_enabled, 'cache on' <ide> end <ide> <add> def test_exceptional_middleware_assigns_original_connection_id_on_error <add> connection_id = ActiveRecord::Base.connection_id <add> <add> mw = ActiveRecord::QueryCache.new lambda { |env| <add> ActiveRecord::Base.connection_id = self.object_id <add> raise "lol borked" <add> } <add> assert_raises(RuntimeError) { mw.call({}) } <add> <add> assert_equal connection_id, ActiveRecord::Base.connection_id <add> end <add> <ide> def test_middleware_delegates <ide> called = false <ide> mw = ActiveRecord::QueryCache.new lambda { |env|
2
Ruby
Ruby
use normal download strategies for casks
d5de9d585b74cc861fcbaf4d43f51da2f113fb27
<ide><path>Library/Homebrew/cask/lib/hbc/download.rb <ide> def perform <ide> attr_accessor :downloaded_path <ide> <ide> def downloader <del> @downloader ||= case cask.url.using <del> when :svn <del> SubversionDownloadStrategy.new(cask) <del> when :post <del> CurlPostDownloadStrategy.new(cask) <del> else <del> CurlDownloadStrategy.new(cask) <add> @downloader ||= begin <add> strategy = DownloadStrategyDetector.detect(cask.url.to_s, cask.url.using) <add> strategy.new(cask.url.to_s, cask.token, cask.version, cache: Cache.path, **cask.url.specs) <ide> end <ide> end <ide> <ide> def clear_cache <ide> end <ide> <ide> def fetch <del> self.downloaded_path = downloader.fetch <add> downloader.fetch <add> @downloaded_path = downloader.cached_location <ide> rescue StandardError => e <ide> raise CaskError, "Download failed on Cask '#{cask}' with message: #{e}" <ide> end <ide><path>Library/Homebrew/cask/lib/hbc/url.rb <ide> class URL <ide> :data <ide> ].freeze <ide> <del> attr_reader :uri <add> attr_reader :uri, :specs <ide> attr_reader(*ATTRIBUTES) <ide> <ide> extend Forwardable <ide> def_delegators :uri, :path, :scheme, :to_s <ide> <del> def initialize(uri, options = {}) <add> def initialize(uri, **options) <ide> @uri = URI(uri) <ide> @user_agent = :default <ide> <ide> ATTRIBUTES.each do |attribute| <ide> next unless options.key?(attribute) <ide> instance_variable_set("@#{attribute}", options[attribute]) <ide> end <add> <add> @specs = options <ide> end <ide> end <ide><path>Library/Homebrew/test/cask/cli/fetch_spec.rb <ide> it_behaves_like "a command that requires a Cask token" <ide> it_behaves_like "a command that handles invalid options" <ide> <del> it "allows download the installer of a Cask" do <add> it "allows downloading the installer of a Cask" do <add> transmission_location = CurlDownloadStrategy.new( <add> local_transmission.url.to_s, local_transmission.token, local_transmission.version, <add> cache: Hbc::Cache.path, **local_transmission.url.specs <add> ).cached_location <add> caffeine_location = CurlDownloadStrategy.new( <add> local_caffeine.url.to_s, local_caffeine.token, local_caffeine.version, <add> cache: Hbc::Cache.path, **local_caffeine.url.specs <add> ).cached_location <add> <add> expect(transmission_location).not_to exist <add> expect(caffeine_location).not_to exist <add> <ide> described_class.run("local-transmission", "local-caffeine") <del> expect(Hbc::CurlDownloadStrategy.new(local_transmission).cached_location).to exist <del> expect(Hbc::CurlDownloadStrategy.new(local_caffeine).cached_location).to exist <add> <add> expect(transmission_location).to exist <add> expect(caffeine_location).to exist <ide> end <ide> <ide> it "prevents double fetch (without nuking existing installation)" do <del> download_stategy = Hbc::CurlDownloadStrategy.new(local_transmission) <add> cached_location = Hbc::Download.new(local_transmission).perform <ide> <del> Hbc::Download.new(local_transmission).perform <del> old_ctime = File.stat(download_stategy.cached_location).ctime <add> old_ctime = File.stat(cached_location).ctime <ide> <ide> described_class.run("local-transmission") <del> new_ctime = File.stat(download_stategy.cached_location).ctime <add> new_ctime = File.stat(cached_location).ctime <ide> <ide> expect(old_ctime.to_i).to eq(new_ctime.to_i) <ide> end <ide> <ide> it "allows double fetch with --force" do <del> Hbc::Download.new(local_transmission).perform <add> cached_location = Hbc::Download.new(local_transmission).perform <ide> <del> download_stategy = Hbc::CurlDownloadStrategy.new(local_transmission) <del> old_ctime = File.stat(download_stategy.cached_location).ctime <add> old_ctime = File.stat(cached_location).ctime <ide> sleep(1) <ide> <ide> described_class.run("local-transmission", "--force") <del> download_stategy = Hbc::CurlDownloadStrategy.new(local_transmission) <del> new_ctime = File.stat(download_stategy.cached_location).ctime <add> new_ctime = File.stat(cached_location).ctime <ide> <ide> expect(new_ctime.to_i).to be > old_ctime.to_i <ide> end
3
Java
Java
scheduler tests (no single() yet)
eddf7156aa164085d1d6b1b32b78fda63b9ba182
<ide><path>src/main/java/io/reactivex/internal/schedulers/ExecutorScheduler.java <ide> public Disposable schedulePeriodicallyDirect(Runnable run, long initialDelay, lo <ide> } <ide> return super.schedulePeriodicallyDirect(run, initialDelay, period, unit); <ide> } <del> <del> static final class ExecutorWorker extends Scheduler.Worker implements Runnable { <add> /* public: test support. */ <add> public static final class ExecutorWorker extends Scheduler.Worker implements Runnable { <ide> final Executor executor; <ide> <ide> final MpscLinkedQueue<Runnable> queue; <ide> static final class ExecutorWorker extends Scheduler.Worker implements Runnable { <ide> static final AtomicIntegerFieldUpdater<ExecutorWorker> WIP = <ide> AtomicIntegerFieldUpdater.newUpdater(ExecutorWorker.class, "wip"); <ide> <add> final SetCompositeResource<Disposable> tasks = new SetCompositeResource<>(Disposable::dispose); <add> <ide> public ExecutorWorker(Executor executor) { <ide> this.executor = executor; <ide> this.queue = new MpscLinkedQueue<>(); <ide> public Disposable schedule(Runnable run, long delay, TimeUnit unit) { <ide> <ide> MultipleAssignmentResource<Disposable> mar = new MultipleAssignmentResource<>(Disposable::dispose, first); <ide> <del> Disposable delayed; <del> <ide> Runnable decoratedRun = RxJavaPlugins.onSchedule(run); <ide> <del> Runnable r = () -> mar.setResource(schedule(decoratedRun)); <add> ScheduledRunnable sr = new ScheduledRunnable(() -> { <add> mar.setResource(schedule(decoratedRun)); <add> }, tasks); <add> tasks.add(sr); <ide> <ide> if (executor instanceof ScheduledExecutorService) { <ide> try { <del> Future<?> f = ((ScheduledExecutorService)executor).schedule(r, delay, unit); <del> delayed = () -> f.cancel(true); <add> Future<?> f = ((ScheduledExecutorService)executor).schedule(sr, delay, unit); <add> sr.setFuture(f); <ide> } catch (RejectedExecutionException ex) { <ide> disposed = true; <ide> RxJavaPlugins.onError(ex); <ide> return EmptyDisposable.INSTANCE; <ide> } <ide> } else { <del> delayed = HELPER.scheduleDirect(r, delay, unit); <add> Disposable d = HELPER.scheduleDirect(sr, delay, unit); <add> sr.setFuture(new Future<Object>() { <add> @Override <add> public boolean cancel(boolean mayInterruptIfRunning) { <add> d.dispose(); <add> return false; <add> } <add> <add> @Override <add> public boolean isCancelled() { <add> return false; <add> } <add> <add> @Override <add> public boolean isDone() { <add> return false; <add> } <add> <add> @Override <add> public Object get() throws InterruptedException, ExecutionException { <add> return null; <add> } <add> <add> @Override <add> public Object get(long timeout, TimeUnit unit) <add> throws InterruptedException, ExecutionException, TimeoutException { <add> return null; <add> } <add> <add> }); <ide> } <ide> <del> first.setResource(delayed); <add> first.setResource(sr); <ide> <ide> return mar; <ide> } <ide> public Disposable schedule(Runnable run, long delay, TimeUnit unit) { <ide> public void dispose() { <ide> if (!disposed) { <ide> disposed = true; <add> tasks.dispose(); <ide> if (WIP.getAndIncrement(this) == 0) { <ide> queue.clear(); <ide> } <ide><path>src/main/java/io/reactivex/schedulers/Schedulers.java <ide> public static Scheduler immediate() { <ide> public static Scheduler from(Executor executor) { <ide> return new ExecutorScheduler(executor); <ide> } <add> <add> public static void shutdown() { <add> computation().shutdown(); <add> io().shutdown(); <add> newThread().shutdown(); <add> single().shutdown(); <add> trampoline().shutdown(); <add> } <add> <add> public static void start() { <add> computation().start(); <add> io().start(); <add> newThread().start(); <add> single().start(); <add> trampoline().start(); <add> } <ide> } <ide><path>src/test/java/io/reactivex/GroupByTests.java <ide> public void testTakeUnsubscribesOnGroupBy() { <ide> .groupBy(event -> event.type) <ide> .take(1) <ide> .toBlocking() <del> .forEach(System.out::println); <add> .forEach(v -> { <add> System.out.println(v); <add> v.take(1).subscribe(); // FIXME groups need consumption to a certain degree to cancel upstream <add> }); <ide> <ide> System.out.println("**** finished"); <ide> } <ide><path>src/test/java/io/reactivex/internal/operators/OperatorConcatTest.java <ide> public void testSimpleAsyncConcat() { <ide> inOrder.verify(observer, times(1)).onNext("six"); <ide> } <ide> <add> @Test <add> public void testNestedAsyncConcatLoop() throws Throwable { <add> for (int i = 0; i < 100; i++) { <add> System.out.println("testNestedAsyncConcat >> " + i); <add> testNestedAsyncConcat(); <add> } <add> } <add> <ide> /** <ide> * Test an async Observable that emits more async Observables <ide> */ <ide> public void run() { <ide> inOrder.verify(observer, times(1)).onNext("eight"); <ide> inOrder.verify(observer, times(1)).onNext("nine"); <ide> <del> inOrder.verify(observer, times(1)).onComplete(); <ide> verify(observer, never()).onError(any(Throwable.class)); <add> inOrder.verify(observer, times(1)).onComplete(); <ide> } <ide> <ide> @Test <ide> public void cancel() { <ide> private final List<T> values; <ide> private Thread t = null; <ide> private int count = 0; <del> private boolean subscribed = true; <add> private volatile boolean subscribed = true; <ide> private final CountDownLatch once; <ide> private final CountDownLatch okToContinue; <ide> private final CountDownLatch threadHasStarted = new CountDownLatch(1); <ide><path>src/test/java/io/reactivex/internal/operators/OperatorOnErrorResumeNextViaObservableTest.java <ide> public String apply(String s) { <ide> <ide> @Test <ide> @Ignore("Publishers should not throw") <del> public void testResumeNextWithFailedOnSubscribe() { <add> public void testResumeNextWithFailureOnSubscribe() { <ide> Observable<String> testObservable = Observable.create(new Publisher<String>() { <ide> <ide> @Override <ide> public void subscribe(Subscriber<? super String> t1) { <ide> <ide> @Test <ide> @Ignore("Publishers should not throw") <del> public void testResumeNextWithFailedOnSubscribeAsync() { <add> public void testResumeNextWithFailureOnSubscribeAsync() { <ide> Observable<String> testObservable = Observable.create(new Publisher<String>() { <ide> <ide> @Override <ide><path>src/test/java/io/reactivex/schedulers/AbstractSchedulerConcurrencyTests.java <add>/** <add> * Copyright 2015 Netflix, Inc. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. 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 distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.schedulers; <add> <add>import static org.junit.Assert.*; <add> <add>import java.util.concurrent.*; <add>import java.util.concurrent.atomic.*; <add>import java.util.function.*; <add> <add>import org.junit.Test; <add>import org.reactivestreams.*; <add> <add>import io.reactivex.*; <add>import io.reactivex.Scheduler.Worker; <add>import io.reactivex.subscribers.AsyncObserver; <add> <add>/** <add> * Base tests for schedulers that involve threads (concurrency). <add> * <add> * These can only run on Schedulers that launch threads since they expect async/concurrent behavior. <add> * <add> * The Current/Immediate schedulers will not work with these tests. <add> */ <add>public abstract class AbstractSchedulerConcurrencyTests extends AbstractSchedulerTests { <add> <add> /** <add> * Bug report: https://github.com/ReactiveX/RxJava/issues/431 <add> */ <add> @Test <add> public final void testUnSubscribeForScheduler() throws InterruptedException { <add> final AtomicInteger countReceived = new AtomicInteger(); <add> final AtomicInteger countGenerated = new AtomicInteger(); <add> final CountDownLatch latch = new CountDownLatch(1); <add> <add> Observable.interval(50, TimeUnit.MILLISECONDS) <add> .map(new Function<Long, Long>() { <add> @Override <add> public Long apply(Long aLong) { <add> countGenerated.incrementAndGet(); <add> return aLong; <add> } <add> }) <add> .subscribeOn(getScheduler()) <add> .observeOn(getScheduler()) <add> .subscribe(new Observer<Long>() { <add> @Override <add> public void onComplete() { <add> System.out.println("--- completed"); <add> } <add> <add> @Override <add> public void onError(Throwable e) { <add> System.out.println("--- onError"); <add> } <add> <add> @Override <add> public void onNext(Long args) { <add> if (countReceived.incrementAndGet() == 2) { <add> cancel(); <add> latch.countDown(); <add> } <add> System.out.println("==> Received " + args); <add> } <add> }); <add> <add> latch.await(1000, TimeUnit.MILLISECONDS); <add> <add> System.out.println("----------- it thinks it is finished ------------------ "); <add> Thread.sleep(100); <add> <add> assertEquals(2, countGenerated.get()); <add> } <add> <add> @Test <add> public void testUnsubscribeRecursiveScheduleFromOutside() throws InterruptedException { <add> final CountDownLatch latch = new CountDownLatch(1); <add> final CountDownLatch unsubscribeLatch = new CountDownLatch(1); <add> final AtomicInteger counter = new AtomicInteger(); <add> final Worker inner = getScheduler().createWorker(); <add> try { <add> inner.schedule(new Runnable() { <add> <add> @Override <add> public void run() { <add> inner.schedule(new Runnable() { <add> <add> int i = 0; <add> <add> @Override <add> public void run() { <add> System.out.println("Run: " + i++); <add> if (i == 10) { <add> latch.countDown(); <add> try { <add> // wait for unsubscribe to finish so we are not racing it <add> unsubscribeLatch.await(); <add> } catch (InterruptedException e) { <add> // we expect the countDown if unsubscribe is not working <add> // or to be interrupted if unsubscribe is successful since <add> // the unsubscribe will interrupt it as it is calling Future.cancel(true) <add> // so we will ignore the stacktrace <add> } <add> } <add> <add> counter.incrementAndGet(); <add> inner.schedule(this); <add> } <add> }); <add> } <add> <add> }); <add> <add> latch.await(); <add> inner.dispose(); <add> unsubscribeLatch.countDown(); <add> Thread.sleep(200); // let time pass to see if the scheduler is still doing work <add> assertEquals(10, counter.get()); <add> } finally { <add> inner.dispose(); <add> } <add> } <add> <add> @Test <add> public void testUnsubscribeRecursiveScheduleFromInside() throws InterruptedException { <add> final CountDownLatch unsubscribeLatch = new CountDownLatch(1); <add> final AtomicInteger counter = new AtomicInteger(); <add> final Worker inner = getScheduler().createWorker(); <add> try { <add> inner.schedule(new Runnable() { <add> <add> @Override <add> public void run() { <add> inner.schedule(new Runnable() { <add> <add> int i = 0; <add> <add> @Override <add> public void run() { <add> System.out.println("Run: " + i++); <add> if (i == 10) { <add> inner.dispose(); <add> } <add> <add> counter.incrementAndGet(); <add> inner.schedule(this); <add> } <add> }); <add> } <add> <add> }); <add> <add> unsubscribeLatch.countDown(); <add> Thread.sleep(200); // let time pass to see if the scheduler is still doing work <add> assertEquals(10, counter.get()); <add> } finally { <add> inner.dispose(); <add> } <add> } <add> <add> @Test <add> public void testUnsubscribeRecursiveScheduleWithDelay() throws InterruptedException { <add> final CountDownLatch latch = new CountDownLatch(1); <add> final CountDownLatch unsubscribeLatch = new CountDownLatch(1); <add> final AtomicInteger counter = new AtomicInteger(); <add> final Worker inner = getScheduler().createWorker(); <add> <add> try { <add> inner.schedule(new Runnable() { <add> <add> @Override <add> public void run() { <add> inner.schedule(new Runnable() { <add> <add> long i = 1L; <add> <add> @Override <add> public void run() { <add> if (i++ == 10) { <add> latch.countDown(); <add> try { <add> // wait for unsubscribe to finish so we are not racing it <add> unsubscribeLatch.await(); <add> } catch (InterruptedException e) { <add> // we expect the countDown if unsubscribe is not working <add> // or to be interrupted if unsubscribe is successful since <add> // the unsubscribe will interrupt it as it is calling Future.cancel(true) <add> // so we will ignore the stacktrace <add> } <add> } <add> <add> counter.incrementAndGet(); <add> inner.schedule(this, 10, TimeUnit.MILLISECONDS); <add> } <add> }, 10, TimeUnit.MILLISECONDS); <add> } <add> }); <add> <add> latch.await(); <add> inner.dispose(); <add> unsubscribeLatch.countDown(); <add> Thread.sleep(200); // let time pass to see if the scheduler is still doing work <add> assertEquals(10, counter.get()); <add> } finally { <add> inner.dispose(); <add> } <add> } <add> <add> @Test <add> public void recursionFromOuterActionAndUnsubscribeInside() throws InterruptedException { <add> final CountDownLatch latch = new CountDownLatch(1); <add> final Worker inner = getScheduler().createWorker(); <add> try { <add> inner.schedule(new Runnable() { <add> <add> int i = 0; <add> <add> @Override <add> public void run() { <add> i++; <add> if (i % 100000 == 0) { <add> System.out.println(i + " Total Memory: " + Runtime.getRuntime().totalMemory() + " Free: " + Runtime.getRuntime().freeMemory()); <add> } <add> if (i < 1000000L) { <add> inner.schedule(this); <add> } else { <add> latch.countDown(); <add> } <add> } <add> }); <add> <add> latch.await(); <add> } finally { <add> inner.dispose(); <add> } <add> } <add> <add> @Test <add> public void testRecursion() throws InterruptedException { <add> final CountDownLatch latch = new CountDownLatch(1); <add> final Worker inner = getScheduler().createWorker(); <add> try { <add> inner.schedule(new Runnable() { <add> <add> private long i = 0; <add> <add> @Override <add> public void run() { <add> i++; <add> if (i % 100000 == 0) { <add> System.out.println(i + " Total Memory: " + Runtime.getRuntime().totalMemory() + " Free: " + Runtime.getRuntime().freeMemory()); <add> } <add> if (i < 1000000L) { <add> inner.schedule(this); <add> } else { <add> latch.countDown(); <add> } <add> } <add> }); <add> <add> latch.await(); <add> } finally { <add> inner.dispose(); <add> } <add> } <add> <add> @Test <add> public void testRecursionAndOuterUnsubscribe() throws InterruptedException { <add> // use latches instead of Thread.sleep <add> final CountDownLatch latch = new CountDownLatch(10); <add> final CountDownLatch completionLatch = new CountDownLatch(1); <add> final Worker inner = getScheduler().createWorker(); <add> try { <add> Observable<Integer> obs = Observable.create(new Publisher<Integer>() { <add> @Override <add> public void subscribe(final Subscriber<? super Integer> observer) { <add> inner.schedule(new Runnable() { <add> @Override <add> public void run() { <add> observer.onNext(42); <add> latch.countDown(); <add> <add> // this will recursively schedule this task for execution again <add> inner.schedule(this); <add> } <add> }); <add> <add> observer.onSubscribe(new Subscription() { <add> <add> @Override <add> public void cancel() { <add> inner.dispose(); <add> observer.onComplete(); <add> completionLatch.countDown(); <add> } <add> <add> @Override <add> public void request(long n) { <add> <add> } <add> }); <add> <add> } <add> }); <add> <add> final AtomicInteger count = new AtomicInteger(); <add> final AtomicBoolean completed = new AtomicBoolean(false); <add> AsyncObserver<Integer> s = new AsyncObserver<Integer>() { <add> @Override <add> public void onComplete() { <add> System.out.println("Completed"); <add> completed.set(true); <add> } <add> <add> @Override <add> public void onError(Throwable e) { <add> System.out.println("Error"); <add> } <add> <add> @Override <add> public void onNext(Integer args) { <add> count.incrementAndGet(); <add> System.out.println(args); <add> } <add> }; <add> obs.subscribe(s); <add> <add> if (!latch.await(5000, TimeUnit.MILLISECONDS)) { <add> fail("Timed out waiting on onNext latch"); <add> } <add> <add> // now unsubscribe and ensure it stops the recursive loop <add> s.dispose(); <add> System.out.println("unsubscribe"); <add> <add> if (!completionLatch.await(5000, TimeUnit.MILLISECONDS)) { <add> fail("Timed out waiting on completion latch"); <add> } <add> <add> // the count can be 10 or higher due to thread scheduling of the unsubscribe vs the scheduler looping to emit the count <add> assertTrue(count.get() >= 10); <add> assertTrue(completed.get()); <add> } finally { <add> inner.dispose(); <add> } <add> } <add> <add> @Test <add> public final void testSubscribeWithScheduler() throws InterruptedException { <add> final Scheduler scheduler = getScheduler(); <add> <add> final AtomicInteger count = new AtomicInteger(); <add> <add> Observable<Integer> o1 = Observable.<Integer> just(1, 2, 3, 4, 5); <add> <add> o1.subscribe(new Consumer<Integer>() { <add> <add> @Override <add> public void accept(Integer t) { <add> System.out.println("Thread: " + Thread.currentThread().getName()); <add> System.out.println("t: " + t); <add> count.incrementAndGet(); <add> } <add> }); <add> <add> // the above should be blocking so we should see a count of 5 <add> assertEquals(5, count.get()); <add> <add> count.set(0); <add> <add> // now we'll subscribe with a scheduler and it should be async <add> <add> final String currentThreadName = Thread.currentThread().getName(); <add> <add> // latches for deterministically controlling the test below across threads <add> final CountDownLatch latch = new CountDownLatch(5); <add> final CountDownLatch first = new CountDownLatch(1); <add> <add> o1.subscribeOn(scheduler).subscribe(new Consumer<Integer>() { <add> <add> @Override <add> public void accept(Integer t) { <add> try { <add> // we block the first one so we can assert this executes asynchronously with a count <add> first.await(1000, TimeUnit.SECONDS); <add> } catch (InterruptedException e) { <add> throw new RuntimeException("The latch should have released if we are async.", e); <add> } <add> <add> assertFalse(Thread.currentThread().getName().equals(currentThreadName)); <add> System.out.println("Thread: " + Thread.currentThread().getName()); <add> System.out.println("t: " + t); <add> count.incrementAndGet(); <add> latch.countDown(); <add> } <add> }); <add> <add> // assert we are async <add> assertEquals(0, count.get()); <add> // release the latch so it can go forward <add> first.countDown(); <add> <add> // wait for all 5 responses <add> latch.await(); <add> assertEquals(5, count.get()); <add> } <add> <add>} <ide>\ No newline at end of file <ide><path>src/test/java/io/reactivex/schedulers/AbstractSchedulerTests.java <add>/** <add> * Copyright 2015 Netflix, Inc. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. 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 distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.schedulers; <add> <add>import static org.junit.Assert.*; <add>import static org.mockito.Mockito.*; <add> <add>import java.util.*; <add>import java.util.concurrent.*; <add>import java.util.concurrent.atomic.*; <add>import java.util.function.*; <add> <add>import org.junit.Test; <add>import org.mockito.InOrder; <add>import org.mockito.invocation.InvocationOnMock; <add>import org.mockito.stubbing.Answer; <add>import org.reactivestreams.*; <add> <add>import io.reactivex.Observable; <add>import io.reactivex.Observer; <add>import io.reactivex.Scheduler; <add>import io.reactivex.internal.subscriptions.*; <add> <add>/** <add> * Base tests for all schedulers including Immediate/Current. <add> */ <add>public abstract class AbstractSchedulerTests { <add> <add> /** <add> * The scheduler to test <add> */ <add> protected abstract Scheduler getScheduler(); <add> <add> @Test <add> public void testNestedActions() throws InterruptedException { <add> Scheduler scheduler = getScheduler(); <add> final Scheduler.Worker inner = scheduler.createWorker(); <add> try { <add> final CountDownLatch latch = new CountDownLatch(1); <add> <add> final Runnable firstStepStart = mock(Runnable.class); <add> final Runnable firstStepEnd = mock(Runnable.class); <add> <add> final Runnable secondStepStart = mock(Runnable.class); <add> final Runnable secondStepEnd = mock(Runnable.class); <add> <add> final Runnable thirdStepStart = mock(Runnable.class); <add> final Runnable thirdStepEnd = mock(Runnable.class); <add> <add> final Runnable firstAction = new Runnable() { <add> @Override <add> public void run() { <add> firstStepStart.run(); <add> firstStepEnd.run(); <add> latch.countDown(); <add> } <add> }; <add> final Runnable secondAction = new Runnable() { <add> @Override <add> public void run() { <add> secondStepStart.run(); <add> inner.schedule(firstAction); <add> secondStepEnd.run(); <add> <add> } <add> }; <add> final Runnable thirdAction = new Runnable() { <add> @Override <add> public void run() { <add> thirdStepStart.run(); <add> inner.schedule(secondAction); <add> thirdStepEnd.run(); <add> } <add> }; <add> <add> InOrder inOrder = inOrder(firstStepStart, firstStepEnd, secondStepStart, secondStepEnd, thirdStepStart, thirdStepEnd); <add> <add> inner.schedule(thirdAction); <add> <add> latch.await(); <add> <add> inOrder.verify(thirdStepStart, times(1)).run(); <add> inOrder.verify(thirdStepEnd, times(1)).run(); <add> inOrder.verify(secondStepStart, times(1)).run(); <add> inOrder.verify(secondStepEnd, times(1)).run(); <add> inOrder.verify(firstStepStart, times(1)).run(); <add> inOrder.verify(firstStepEnd, times(1)).run(); <add> } finally { <add> inner.dispose(); <add> } <add> } <add> <add> @Test <add> public final void testNestedScheduling() { <add> <add> Observable<Integer> ids = Observable.fromIterable(Arrays.asList(1, 2)).subscribeOn(getScheduler()); <add> <add> Observable<String> m = ids.flatMap(new Function<Integer, Observable<String>>() { <add> <add> @Override <add> public Observable<String> apply(Integer id) { <add> return Observable.fromIterable(Arrays.asList("a-" + id, "b-" + id)).subscribeOn(getScheduler()) <add> .map(new Function<String, String>() { <add> <add> @Override <add> public String apply(String s) { <add> return "names=>" + s; <add> } <add> }); <add> } <add> <add> }); <add> <add> List<String> strings = m.toList().toBlocking().last(); <add> <add> assertEquals(4, strings.size()); <add> // because flatMap does a merge there is no guarantee of order <add> assertTrue(strings.contains("names=>a-1")); <add> assertTrue(strings.contains("names=>a-2")); <add> assertTrue(strings.contains("names=>b-1")); <add> assertTrue(strings.contains("names=>b-2")); <add> } <add> <add> /** <add> * The order of execution is nondeterministic. <add> * <add> * @throws InterruptedException <add> */ <add> @SuppressWarnings("rawtypes") <add> @Test <add> public final void testSequenceOfActions() throws InterruptedException { <add> final Scheduler scheduler = getScheduler(); <add> final Scheduler.Worker inner = scheduler.createWorker(); <add> try { <add> final CountDownLatch latch = new CountDownLatch(2); <add> final Runnable first = mock(Runnable.class); <add> final Runnable second = mock(Runnable.class); <add> <add> // make it wait until both the first and second are called <add> doAnswer(new Answer() { <add> <add> @Override <add> public Object answer(InvocationOnMock invocation) throws Throwable { <add> try { <add> return invocation.getMock(); <add> } finally { <add> latch.countDown(); <add> } <add> } <add> }).when(first).run(); <add> doAnswer(new Answer() { <add> <add> @Override <add> public Object answer(InvocationOnMock invocation) throws Throwable { <add> try { <add> return invocation.getMock(); <add> } finally { <add> latch.countDown(); <add> } <add> } <add> }).when(second).run(); <add> <add> inner.schedule(first); <add> inner.schedule(second); <add> <add> latch.await(); <add> <add> verify(first, times(1)).run(); <add> verify(second, times(1)).run(); <add> } finally { <add> inner.dispose(); <add> } <add> } <add> <add> @Test <add> public void testSequenceOfDelayedActions() throws InterruptedException { <add> Scheduler scheduler = getScheduler(); <add> final Scheduler.Worker inner = scheduler.createWorker(); <add> <add> try { <add> final CountDownLatch latch = new CountDownLatch(1); <add> final Runnable first = mock(Runnable.class); <add> final Runnable second = mock(Runnable.class); <add> <add> inner.schedule(new Runnable() { <add> @Override <add> public void run() { <add> inner.schedule(first, 30, TimeUnit.MILLISECONDS); <add> inner.schedule(second, 10, TimeUnit.MILLISECONDS); <add> inner.schedule(new Runnable() { <add> <add> @Override <add> public void run() { <add> latch.countDown(); <add> } <add> }, 40, TimeUnit.MILLISECONDS); <add> } <add> }); <add> <add> latch.await(); <add> InOrder inOrder = inOrder(first, second); <add> <add> inOrder.verify(second, times(1)).run(); <add> inOrder.verify(first, times(1)).run(); <add> } finally { <add> inner.dispose(); <add> } <add> } <add> <add> @Test <add> public void testMixOfDelayedAndNonDelayedActions() throws InterruptedException { <add> Scheduler scheduler = getScheduler(); <add> final Scheduler.Worker inner = scheduler.createWorker(); <add> <add> try { <add> final CountDownLatch latch = new CountDownLatch(1); <add> final Runnable first = mock(Runnable.class); <add> final Runnable second = mock(Runnable.class); <add> final Runnable third = mock(Runnable.class); <add> final Runnable fourth = mock(Runnable.class); <add> <add> inner.schedule(new Runnable() { <add> @Override <add> public void run() { <add> inner.schedule(first); <add> inner.schedule(second, 300, TimeUnit.MILLISECONDS); <add> inner.schedule(third, 100, TimeUnit.MILLISECONDS); <add> inner.schedule(fourth); <add> inner.schedule(new Runnable() { <add> <add> @Override <add> public void run() { <add> latch.countDown(); <add> } <add> }, 400, TimeUnit.MILLISECONDS); <add> } <add> }); <add> <add> latch.await(); <add> InOrder inOrder = inOrder(first, second, third, fourth); <add> <add> inOrder.verify(first, times(1)).run(); <add> inOrder.verify(fourth, times(1)).run(); <add> inOrder.verify(third, times(1)).run(); <add> inOrder.verify(second, times(1)).run(); <add> } finally { <add> inner.dispose(); <add> } <add> } <add> <add> @Test <add> public final void testRecursiveExecution() throws InterruptedException { <add> final Scheduler scheduler = getScheduler(); <add> final Scheduler.Worker inner = scheduler.createWorker(); <add> <add> try { <add> <add> final AtomicInteger i = new AtomicInteger(); <add> final CountDownLatch latch = new CountDownLatch(1); <add> inner.schedule(new Runnable() { <add> <add> @Override <add> public void run() { <add> if (i.incrementAndGet() < 100) { <add> inner.schedule(this); <add> } else { <add> latch.countDown(); <add> } <add> } <add> }); <add> <add> latch.await(); <add> assertEquals(100, i.get()); <add> } finally { <add> inner.dispose(); <add> } <add> } <add> <add> @Test <add> public final void testRecursiveExecutionWithDelayTime() throws InterruptedException { <add> Scheduler scheduler = getScheduler(); <add> final Scheduler.Worker inner = scheduler.createWorker(); <add> <add> try { <add> final AtomicInteger i = new AtomicInteger(); <add> final CountDownLatch latch = new CountDownLatch(1); <add> <add> inner.schedule(new Runnable() { <add> <add> int state = 0; <add> <add> @Override <add> public void run() { <add> i.set(state); <add> if (state++ < 100) { <add> inner.schedule(this, 1, TimeUnit.MILLISECONDS); <add> } else { <add> latch.countDown(); <add> } <add> } <add> <add> }); <add> <add> latch.await(); <add> assertEquals(100, i.get()); <add> } finally { <add> inner.dispose(); <add> } <add> } <add> <add> @Test <add> public final void testRecursiveSchedulerInObservable() { <add> Observable<Integer> obs = Observable.create(new Publisher<Integer>() { <add> @Override <add> public void subscribe(final Subscriber<? super Integer> observer) { <add> final Scheduler.Worker inner = getScheduler().createWorker(); <add> <add> AsyncSubscription as = new AsyncSubscription(); <add> observer.onSubscribe(as); <add> as.setResource(inner); <add> <add> inner.schedule(new Runnable() { <add> int i = 0; <add> <add> @Override <add> public void run() { <add> if (i > 42) { <add> observer.onComplete(); <add> return; <add> } <add> <add> observer.onNext(i++); <add> <add> inner.schedule(this); <add> } <add> }); <add> } <add> }); <add> <add> final AtomicInteger lastValue = new AtomicInteger(); <add> obs.toBlocking().forEach(new Consumer<Integer>() { <add> <add> @Override <add> public void accept(Integer v) { <add> System.out.println("Value: " + v); <add> lastValue.set(v); <add> } <add> }); <add> <add> assertEquals(42, lastValue.get()); <add> } <add> <add> @Test <add> public final void testConcurrentOnNextFailsValidation() throws InterruptedException { <add> final int count = 10; <add> final CountDownLatch latch = new CountDownLatch(count); <add> Observable<String> o = Observable.create(new Publisher<String>() { <add> <add> @Override <add> public void subscribe(final Subscriber<? super String> observer) { <add> observer.onSubscribe(EmptySubscription.INSTANCE); <add> for (int i = 0; i < count; i++) { <add> final int v = i; <add> new Thread(new Runnable() { <add> <add> @Override <add> public void run() { <add> observer.onNext("v: " + v); <add> <add> latch.countDown(); <add> } <add> }).start(); <add> } <add> } <add> }); <add> <add> ConcurrentObserverValidator<String> observer = new ConcurrentObserverValidator<>(); <add> // this should call onNext concurrently <add> o.subscribe(observer); <add> <add> if (!observer.completed.await(3000, TimeUnit.MILLISECONDS)) { <add> fail("timed out"); <add> } <add> <add> if (observer.error.get() == null) { <add> fail("We expected error messages due to concurrency"); <add> } <add> } <add> <add> @Test <add> public final void testObserveOn() throws InterruptedException { <add> final Scheduler scheduler = getScheduler(); <add> <add> Observable<String> o = Observable.fromArray("one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"); <add> <add> ConcurrentObserverValidator<String> observer = new ConcurrentObserverValidator<>(); <add> <add> o.observeOn(scheduler).subscribe(observer); <add> <add> if (!observer.completed.await(3000, TimeUnit.MILLISECONDS)) { <add> fail("timed out"); <add> } <add> <add> if (observer.error.get() != null) { <add> observer.error.get().printStackTrace(); <add> fail("Error: " + observer.error.get().getMessage()); <add> } <add> } <add> <add> @Test <add> public final void testSubscribeOnNestedConcurrency() throws InterruptedException { <add> final Scheduler scheduler = getScheduler(); <add> <add> Observable<String> o = Observable.fromArray("one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten") <add> .flatMap(new Function<String, Observable<String>>() { <add> <add> @Override <add> public Observable<String> apply(final String v) { <add> return Observable.create(new Publisher<String>() { <add> <add> @Override <add> public void subscribe(Subscriber<? super String> observer) { <add> observer.onSubscribe(EmptySubscription.INSTANCE); <add> observer.onNext("value_after_map-" + v); <add> observer.onComplete(); <add> } <add> }).subscribeOn(scheduler); <add> } <add> }); <add> <add> ConcurrentObserverValidator<String> observer = new ConcurrentObserverValidator<>(); <add> <add> o.subscribe(observer); <add> <add> if (!observer.completed.await(3000, TimeUnit.MILLISECONDS)) { <add> fail("timed out"); <add> } <add> <add> if (observer.error.get() != null) { <add> observer.error.get().printStackTrace(); <add> fail("Error: " + observer.error.get().getMessage()); <add> } <add> } <add> <add> /** <add> * Used to determine if onNext is being invoked concurrently. <add> * <add> * @param <T> <add> */ <add> private static class ConcurrentObserverValidator<T> extends Observer<T> { <add> <add> final AtomicInteger concurrentCounter = new AtomicInteger(); <add> final AtomicReference<Throwable> error = new AtomicReference<>(); <add> final CountDownLatch completed = new CountDownLatch(1); <add> <add> @Override <add> public void onComplete() { <add> completed.countDown(); <add> } <add> <add> @Override <add> public void onError(Throwable e) { <add> error.set(e); <add> completed.countDown(); <add> } <add> <add> @Override <add> public void onNext(T args) { <add> int count = concurrentCounter.incrementAndGet(); <add> System.out.println("ConcurrentObserverValidator.onNext: " + args); <add> if (count > 1) { <add> onError(new RuntimeException("we should not have concurrent execution of onNext")); <add> } <add> try { <add> try { <add> // take some time so other onNext calls could pile up (I haven't yet thought of a way to do this without sleeping) <add> Thread.sleep(50); <add> } catch (InterruptedException e) { <add> // ignore <add> } <add> } finally { <add> concurrentCounter.decrementAndGet(); <add> } <add> } <add> <add> } <add> <add>} <ide>\ No newline at end of file <ide><path>src/test/java/io/reactivex/schedulers/CachedThreadSchedulerTest.java <add>/** <add> * Copyright 2015 Netflix, Inc. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. 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 distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.schedulers; <add> <add>import static org.junit.Assert.assertTrue; <add> <add>import java.util.function.*; <add> <add>import org.junit.*; <add> <add>import io.reactivex.*; <add>import io.reactivex.Scheduler.Worker; <add> <add>public class CachedThreadSchedulerTest extends AbstractSchedulerConcurrencyTests { <add> <add> @Override <add> protected Scheduler getScheduler() { <add> return Schedulers.io(); <add> } <add> <add> /** <add> * IO scheduler defaults to using CachedThreadScheduler <add> */ <add> @Test <add> public final void testIOScheduler() { <add> <add> Observable<Integer> o1 = Observable.just(1, 2, 3, 4, 5); <add> Observable<Integer> o2 = Observable.just(6, 7, 8, 9, 10); <add> Observable<String> o = Observable.merge(o1, o2).map(new Function<Integer, String>() { <add> <add> @Override <add> public String apply(Integer t) { <add> assertTrue(Thread.currentThread().getName().startsWith("RxCachedThreadScheduler")); <add> return "Value_" + t + "_Thread_" + Thread.currentThread().getName(); <add> } <add> }); <add> <add> o.subscribeOn(Schedulers.io()).toBlocking().forEach(new Consumer<String>() { <add> <add> @Override <add> public void accept(String t) { <add> System.out.println("t: " + t); <add> } <add> }); <add> } <add> <add> @Test <add> @Ignore("Unhandled errors are no longer thrown") <add> public final void testUnhandledErrorIsDeliveredToThreadHandler() throws InterruptedException { <add> SchedulerTests.testUnhandledErrorIsDeliveredToThreadHandler(getScheduler()); <add> } <add> <add> @Test <add> public final void testHandledErrorIsNotDeliveredToThreadHandler() throws InterruptedException { <add> SchedulerTests.testHandledErrorIsNotDeliveredToThreadHandler(getScheduler()); <add> } <add> <add> @Test(timeout = 30000) <add> public void testCancelledTaskRetention() throws InterruptedException { <add> Worker w = Schedulers.io().createWorker(); <add> try { <add> ExecutorSchedulerTest.testCancelledRetention(w, false); <add> } finally { <add> w.dispose(); <add> } <add> w = Schedulers.io().createWorker(); <add> try { <add> ExecutorSchedulerTest.testCancelledRetention(w, true); <add> } finally { <add> w.dispose(); <add> } <add> } <add> <add>} <ide>\ No newline at end of file <ide><path>src/test/java/io/reactivex/schedulers/ComputationSchedulerTests.java <add>/** <add> * Copyright 2015 Netflix, Inc. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. 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 distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.schedulers; <add> <add>import static org.junit.Assert.*; <add> <add>import java.util.HashMap; <add>import java.util.concurrent.CountDownLatch; <add>import java.util.function.*; <add> <add>import org.junit.*; <add> <add>import io.reactivex.*; <add>import io.reactivex.Scheduler.Worker; <add> <add>public class ComputationSchedulerTests extends AbstractSchedulerConcurrencyTests { <add> <add> @Override <add> protected Scheduler getScheduler() { <add> // this is an implementation of ExecutorScheduler <add> return Schedulers.computation(); <add> } <add> <add> @Test <add> public void testThreadSafetyWhenSchedulerIsHoppingBetweenThreads() { <add> <add> final int NUM = 1000000; <add> final CountDownLatch latch = new CountDownLatch(1); <add> final HashMap<String, Integer> map = new HashMap<>(); <add> <add> final Scheduler.Worker inner = Schedulers.computation().createWorker(); <add> <add> try { <add> inner.schedule(new Runnable() { <add> <add> private HashMap<String, Integer> statefulMap = map; <add> int nonThreadSafeCounter = 0; <add> <add> @Override <add> public void run() { <add> Integer i = statefulMap.get("a"); <add> if (i == null) { <add> i = 1; <add> statefulMap.put("a", i); <add> statefulMap.put("b", i); <add> } else { <add> i++; <add> statefulMap.put("a", i); <add> statefulMap.put("b", i); <add> } <add> nonThreadSafeCounter++; <add> statefulMap.put("nonThreadSafeCounter", nonThreadSafeCounter); <add> if (i < NUM) { <add> inner.schedule(this); <add> } else { <add> latch.countDown(); <add> } <add> } <add> }); <add> <add> try { <add> latch.await(); <add> } catch (InterruptedException e) { <add> e.printStackTrace(); <add> } <add> <add> System.out.println("Count A: " + map.get("a")); <add> System.out.println("Count B: " + map.get("b")); <add> System.out.println("nonThreadSafeCounter: " + map.get("nonThreadSafeCounter")); <add> <add> assertEquals(NUM, map.get("a").intValue()); <add> assertEquals(NUM, map.get("b").intValue()); <add> assertEquals(NUM, map.get("nonThreadSafeCounter").intValue()); <add> } finally { <add> inner.dispose(); <add> } <add> } <add> <add> @Test <add> public final void testComputationThreadPool1() { <add> Observable<Integer> o1 = Observable.<Integer> just(1, 2, 3, 4, 5); <add> Observable<Integer> o2 = Observable.<Integer> just(6, 7, 8, 9, 10); <add> Observable<String> o = Observable.<Integer> merge(o1, o2).map(new Function<Integer, String>() { <add> <add> @Override <add> public String apply(Integer t) { <add> assertTrue(Thread.currentThread().getName().startsWith("RxComputationThreadPool")); <add> return "Value_" + t + "_Thread_" + Thread.currentThread().getName(); <add> } <add> }); <add> <add> o.subscribeOn(Schedulers.computation()).toBlocking().forEach(new Consumer<String>() { <add> <add> @Override <add> public void accept(String t) { <add> System.out.println("t: " + t); <add> } <add> }); <add> } <add> <add> <add> @Test <add> public final void testMergeWithExecutorScheduler() { <add> <add> final String currentThreadName = Thread.currentThread().getName(); <add> <add> Observable<Integer> o1 = Observable.<Integer> just(1, 2, 3, 4, 5); <add> Observable<Integer> o2 = Observable.<Integer> just(6, 7, 8, 9, 10); <add> Observable<String> o = Observable.<Integer> merge(o1, o2).subscribeOn(Schedulers.computation()).map(new Function<Integer, String>() { <add> <add> @Override <add> public String apply(Integer t) { <add> assertFalse(Thread.currentThread().getName().equals(currentThreadName)); <add> assertTrue(Thread.currentThread().getName().startsWith("RxComputationThreadPool")); <add> return "Value_" + t + "_Thread_" + Thread.currentThread().getName(); <add> } <add> }); <add> <add> o.toBlocking().forEach(new Consumer<String>() { <add> <add> @Override <add> public void accept(String t) { <add> System.out.println("t: " + t); <add> } <add> }); <add> } <add> <add> @Test <add> @Ignore("Unhandled errors are no longer thrown") <add> public final void testUnhandledErrorIsDeliveredToThreadHandler() throws InterruptedException { <add> SchedulerTests.testUnhandledErrorIsDeliveredToThreadHandler(getScheduler()); <add> } <add> <add> @Test <add> public final void testHandledErrorIsNotDeliveredToThreadHandler() throws InterruptedException { <add> SchedulerTests.testHandledErrorIsNotDeliveredToThreadHandler(getScheduler()); <add> } <add> <add> @Test(timeout = 30000) <add> public void testCancelledTaskRetention() throws InterruptedException { <add> Worker w = Schedulers.computation().createWorker(); <add> try { <add> ExecutorSchedulerTest.testCancelledRetention(w, false); <add> } finally { <add> w.dispose(); <add> } <add> w = Schedulers.computation().createWorker(); <add> try { <add> ExecutorSchedulerTest.testCancelledRetention(w, true); <add> } finally { <add> w.dispose(); <add> } <add> } <add>} <ide>\ No newline at end of file <ide><path>src/test/java/io/reactivex/schedulers/ExecutorSchedulerTest.java <add>/** <add> * Copyright 2015 Netflix, Inc. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. 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 distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.schedulers; <add> <add>import static org.junit.Assert.*; <add> <add>import java.lang.management.*; <add>import java.util.concurrent.*; <add>import java.util.concurrent.atomic.AtomicInteger; <add> <add>import org.junit.*; <add> <add>import io.reactivex.Scheduler; <add>import io.reactivex.Scheduler.Worker; <add>import io.reactivex.disposables.Disposable; <add>import io.reactivex.internal.schedulers.RxThreadFactory; <add> <add>public class ExecutorSchedulerTest extends AbstractSchedulerConcurrencyTests { <add> <add> final static Executor executor = Executors.newFixedThreadPool(2, new RxThreadFactory("TestCustomPool-")); <add> <add> @Override <add> protected Scheduler getScheduler() { <add> return Schedulers.from(executor); <add> } <add> <add> @Test <add> @Ignore("Unhandled errors are no longer thrown") <add> public final void testUnhandledErrorIsDeliveredToThreadHandler() throws InterruptedException { <add> SchedulerTests.testUnhandledErrorIsDeliveredToThreadHandler(getScheduler()); <add> } <add> <add> @Test <add> public final void testHandledErrorIsNotDeliveredToThreadHandler() throws InterruptedException { <add> SchedulerTests.testHandledErrorIsNotDeliveredToThreadHandler(getScheduler()); <add> } <add> <add> public static void testCancelledRetention(Scheduler.Worker w, boolean periodic) throws InterruptedException { <add> System.out.println("Wait before GC"); <add> Thread.sleep(1000); <add> <add> System.out.println("GC"); <add> System.gc(); <add> <add> Thread.sleep(1000); <add> <add> <add> MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean(); <add> MemoryUsage memHeap = memoryMXBean.getHeapMemoryUsage(); <add> long initial = memHeap.getUsed(); <add> <add> System.out.printf("Starting: %.3f MB%n", initial / 1024.0 / 1024.0); <add> <add> int n = 500 * 1000; <add> if (periodic) { <add> final CountDownLatch cdl = new CountDownLatch(n); <add> final Runnable action = new Runnable() { <add> @Override <add> public void run() { <add> cdl.countDown(); <add> } <add> }; <add> for (int i = 0; i < n; i++) { <add> if (i % 50000 == 0) { <add> System.out.println(" -> still scheduling: " + i); <add> } <add> w.schedulePeriodically(action, 0, 1, TimeUnit.DAYS); <add> } <add> <add> System.out.println("Waiting for the first round to finish..."); <add> cdl.await(); <add> } else { <add> for (int i = 0; i < n; i++) { <add> if (i % 50000 == 0) { <add> System.out.println(" -> still scheduling: " + i); <add> } <add> w.schedule(() -> { }, 1, TimeUnit.DAYS); <add> } <add> } <add> <add> memHeap = memoryMXBean.getHeapMemoryUsage(); <add> long after = memHeap.getUsed(); <add> System.out.printf("Peak: %.3f MB%n", after / 1024.0 / 1024.0); <add> <add> w.dispose(); <add> <add> System.out.println("Wait before second GC"); <add> Thread.sleep(1000 + 2000); <add> <add> System.out.println("Second GC"); <add> System.gc(); <add> <add> Thread.sleep(1000); <add> <add> memHeap = memoryMXBean.getHeapMemoryUsage(); <add> long finish = memHeap.getUsed(); <add> System.out.printf("After: %.3f MB%n", finish / 1024.0 / 1024.0); <add> <add> if (finish > initial * 5) { <add> fail(String.format("Tasks retained: %.3f -> %.3f -> %.3f", initial / 1024 / 1024.0, after / 1024 / 1024.0, finish / 1024 / 1024d)); <add> } <add> } <add> <add> @Test(timeout = 30000) <add> public void testCancelledTaskRetention() throws InterruptedException { <add> ExecutorService exec = Executors.newSingleThreadExecutor(); <add> Scheduler s = Schedulers.from(exec); <add> try { <add> Scheduler.Worker w = s.createWorker(); <add> try { <add> testCancelledRetention(w, false); <add> } finally { <add> w.dispose(); <add> } <add> <add> w = s.createWorker(); <add> try { <add> testCancelledRetention(w, true); <add> } finally { <add> w.dispose(); <add> } <add> } finally { <add> exec.shutdownNow(); <add> } <add> } <add> <add> /** A simple executor which queues tasks and executes them one-by-one if executeOne() is called. */ <add> static final class TestExecutor implements Executor { <add> final ConcurrentLinkedQueue<Runnable> queue = new ConcurrentLinkedQueue<>(); <add> @Override <add> public void execute(Runnable command) { <add> queue.offer(command); <add> } <add> public void executeOne() { <add> Runnable r = queue.poll(); <add> if (r != null) { <add> r.run(); <add> } <add> } <add> public void executeAll() { <add> Runnable r; <add> while ((r = queue.poll()) != null) { <add> r.run(); <add> } <add> } <add> } <add> <add> @Test <add> public void testCancelledTasksDontRun() { <add> final AtomicInteger calls = new AtomicInteger(); <add> Runnable task = new Runnable() { <add> @Override <add> public void run() { <add> calls.getAndIncrement(); <add> } <add> }; <add> TestExecutor exec = new TestExecutor(); <add> Scheduler custom = Schedulers.from(exec); <add> Worker w = custom.createWorker(); <add> try { <add> Disposable s1 = w.schedule(task); <add> Disposable s2 = w.schedule(task); <add> Disposable s3 = w.schedule(task); <add> <add> s1.dispose(); <add> s2.dispose(); <add> s3.dispose(); <add> <add> exec.executeAll(); <add> <add> assertEquals(0, calls.get()); <add> } finally { <add> w.dispose(); <add> } <add> } <add> @Test <add> public void testCancelledWorkerDoesntRunTasks() { <add> final AtomicInteger calls = new AtomicInteger(); <add> Runnable task = new Runnable() { <add> @Override <add> public void run() { <add> calls.getAndIncrement(); <add> } <add> }; <add> TestExecutor exec = new TestExecutor(); <add> Scheduler custom = Schedulers.from(exec); <add> Worker w = custom.createWorker(); <add> try { <add> w.schedule(task); <add> w.schedule(task); <add> w.schedule(task); <add> } finally { <add> w.dispose(); <add> } <add> exec.executeAll(); <add> assertEquals(0, calls.get()); <add> } <add> <add> // FIXME the internal structure changed and these can't be tested <add>// <add>// @Test <add>// public void testNoTimedTaskAfterScheduleRetention() throws InterruptedException { <add>// Executor e = new Executor() { <add>// @Override <add>// public void execute(Runnable command) { <add>// command.run(); <add>// } <add>// }; <add>// ExecutorWorker w = (ExecutorWorker)Schedulers.from(e).createWorker(); <add>// <add>// w.schedule(() -> { }, 50, TimeUnit.MILLISECONDS); <add>// <add>// assertTrue(w.tasks.hasSubscriptions()); <add>// <add>// Thread.sleep(150); <add>// <add>// assertFalse(w.tasks.hasSubscriptions()); <add>// } <add>// <add>// @Test <add>// public void testNoTimedTaskPartRetention() { <add>// Executor e = new Executor() { <add>// @Override <add>// public void execute(Runnable command) { <add>// <add>// } <add>// }; <add>// ExecutorWorker w = (ExecutorWorker)Schedulers.from(e).createWorker(); <add>// <add>// Disposable s = w.schedule(() -> { }, 1, TimeUnit.DAYS); <add>// <add>// assertTrue(w.tasks.hasSubscriptions()); <add>// <add>// s.dispose(); <add>// <add>// assertFalse(w.tasks.hasSubscriptions()); <add>// } <add>// <add>// @Test <add>// public void testNoPeriodicTimedTaskPartRetention() throws InterruptedException { <add>// Executor e = new Executor() { <add>// @Override <add>// public void execute(Runnable command) { <add>// command.run(); <add>// } <add>// }; <add>// ExecutorWorker w = (ExecutorWorker)Schedulers.from(e).createWorker(); <add>// <add>// final CountDownLatch cdl = new CountDownLatch(1); <add>// final Runnable action = new Runnable() { <add>// @Override <add>// public void run() { <add>// cdl.countDown(); <add>// } <add>// }; <add>// <add>// Disposable s = w.schedulePeriodically(action, 0, 1, TimeUnit.DAYS); <add>// <add>// assertTrue(w.tasks.hasSubscriptions()); <add>// <add>// cdl.await(); <add>// <add>// s.dispose(); <add>// <add>// assertFalse(w.tasks.hasSubscriptions()); <add>// } <add>} <ide>\ No newline at end of file <ide><path>src/test/java/io/reactivex/schedulers/NewThreadSchedulerTest.java <add>/** <add> * Copyright 2015 Netflix, Inc. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. 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 distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.schedulers; <add> <add>import org.junit.*; <add> <add>import io.reactivex.Scheduler; <add> <add>public class NewThreadSchedulerTest extends AbstractSchedulerConcurrencyTests { <add> <add> @Override <add> protected Scheduler getScheduler() { <add> return Schedulers.newThread(); <add> } <add> <add> @Test <add> @Ignore("Unhandled errors are no longer thrown") <add> public final void testUnhandledErrorIsDeliveredToThreadHandler() throws InterruptedException { <add> SchedulerTests.testUnhandledErrorIsDeliveredToThreadHandler(getScheduler()); <add> } <add> <add> @Test <add> public final void testHandledErrorIsNotDeliveredToThreadHandler() throws InterruptedException { <add> SchedulerTests.testHandledErrorIsNotDeliveredToThreadHandler(getScheduler()); <add> } <add> <add> // FIXME no longer testable due to internal changes <add>// @Test(timeout = 3000) <add>// public void testNoSelfInterrupt() throws InterruptedException { <add>// Scheduler.Worker worker = Schedulers.newThread().createWorker(); <add>// try { <add>// final CountDownLatch run = new CountDownLatch(1); <add>// final CountDownLatch done = new CountDownLatch(1); <add>// final AtomicReference<Throwable> exception = new AtomicReference<>(); <add>// final AtomicBoolean interruptFlag = new AtomicBoolean(); <add>// <add>// ScheduledRunnable sa = (ScheduledRunnable)worker.schedule(new Runnable() { <add>// @Override <add>// public void run() { <add>// try { <add>// run.await(); <add>// } catch (InterruptedException ex) { <add>// exception.set(ex); <add>// } <add>// } <add>// }); <add>// <add>// sa.add(new Disposable() { <add>// @Override <add>// public void dispose() { <add>// interruptFlag.set(Thread.currentThread().isInterrupted()); <add>// done.countDown(); <add>// } <add>// }); <add>// <add>// run.countDown(); <add>// <add>// done.await(); <add>// <add>// Assert.assertEquals(null, exception.get()); <add>// Assert.assertFalse("Interrupted?!", interruptFlag.get()); <add>// } finally { <add>// worker.dispose(); <add>// } <add>// } <add>} <ide>\ No newline at end of file <ide><path>src/test/java/io/reactivex/schedulers/SchedulerLifecycleTest.java <add>/** <add> * Copyright 2015 Netflix, Inc. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. 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 distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.schedulers; <add> <add>import static org.junit.Assert.*; <add> <add>import java.util.*; <add>import java.util.concurrent.*; <add> <add>import org.junit.Test; <add> <add>import io.reactivex.Scheduler.Worker; <add>import io.reactivex.disposables.CompositeDisposable; <add> <add>public class SchedulerLifecycleTest { <add> @Test <add> public void testShutdown() throws InterruptedException { <add> tryOutSchedulers(); <add> <add> System.out.println("testShutdown >> Giving time threads to spin-up"); <add> Thread.sleep(500); <add> <add> Set<Thread> rxThreads = new HashSet<>(); <add> for (Thread t : Thread.getAllStackTraces().keySet()) { <add> if (t.getName().startsWith("Rx")) { <add> rxThreads.add(t); <add> } <add> } <add> Schedulers.shutdown(); <add> System.out.println("testShutdown >> Giving time to threads to stop"); <add> Thread.sleep(500); <add> <add> StringBuilder b = new StringBuilder(); <add> for (Thread t : rxThreads) { <add> if (t.isAlive()) { <add> b.append("Thread " + t + " failed to shutdown\r\n"); <add> for (StackTraceElement ste : t.getStackTrace()) { <add> b.append(" ").append(ste).append("\r\n"); <add> } <add> } <add> } <add> if (b.length() > 0) { <add> System.out.print(b); <add> System.out.println("testShutdown >> Restarting schedulers..."); <add> Schedulers.start(); // restart them anyways <add> fail("Rx Threads were still alive:\r\n" + b); <add> } <add> <add> System.out.println("testShutdown >> Restarting schedulers..."); <add> Schedulers.start(); <add> <add> tryOutSchedulers(); <add> } <add> <add> private void tryOutSchedulers() throws InterruptedException { <add> final CountDownLatch cdl = new CountDownLatch(4); <add> <add> final Runnable countAction = new Runnable() { <add> @Override <add> public void run() { <add> cdl.countDown(); <add> } <add> }; <add> <add> CompositeDisposable csub = new CompositeDisposable(); <add> <add> try { <add> Worker w1 = Schedulers.computation().createWorker(); <add> csub.add(w1); <add> w1.schedule(countAction); <add> <add> Worker w2 = Schedulers.io().createWorker(); <add> csub.add(w2); <add> w2.schedule(countAction); <add> <add> Worker w3 = Schedulers.newThread().createWorker(); <add> csub.add(w3); <add> w3.schedule(countAction); <add> <add> Worker w4 = Schedulers.single().createWorker(); <add> csub.add(w4); <add> w4.schedule(countAction); <add> <add> <add> if (!cdl.await(3, TimeUnit.SECONDS)) { <add> fail("countAction was not run by every worker"); <add> } <add> } finally { <add> csub.dispose(); <add> } <add> } <add> <add> @Test <add> public void testStartIdempotence() throws InterruptedException { <add> tryOutSchedulers(); <add> <add> System.out.println("testStartIdempotence >> giving some time"); <add> Thread.sleep(500); <add> <add> Set<Thread> rxThreads = new HashSet<>(); <add> for (Thread t : Thread.getAllStackTraces().keySet()) { <add> if (t.getName().startsWith("Rx")) { <add> rxThreads.add(t); <add> System.out.println("testStartIdempotence >> " + t); <add> } <add> } <add> System.out.println("testStartIdempotence >> trying to start again"); <add> Schedulers.start(); <add> System.out.println("testStartIdempotence >> giving some time again"); <add> Thread.sleep(500); <add> <add> Set<Thread> rxThreads2 = new HashSet<>(); <add> for (Thread t : Thread.getAllStackTraces().keySet()) { <add> if (t.getName().startsWith("Rx")) { <add> rxThreads2.add(t); <add> System.out.println("testStartIdempotence >>>> " + t); <add> } <add> } <add> <add> assertEquals(rxThreads, rxThreads2); <add> } <add>} <ide>\ No newline at end of file <ide><path>src/test/java/io/reactivex/schedulers/SchedulerTests.java <add>/** <add> * Copyright 2015 Netflix, Inc. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. 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 distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.schedulers; <add> <add>import static org.junit.Assert.*; <add> <add>import java.util.concurrent.*; <add> <add>import io.reactivex.*; <add> <add>final class SchedulerTests { <add> private SchedulerTests() { <add> // No instances. <add> } <add> <add> /** <add> * Verifies that the given Scheduler delivers unhandled errors to its executing thread's <add> * {@link java.lang.Thread.UncaughtExceptionHandler}. <add> * <p> <add> * Schedulers which execute on a separate thread from their calling thread should exhibit this behavior. Schedulers <add> * which execute on their calling thread may not. <add> */ <add> static void testUnhandledErrorIsDeliveredToThreadHandler(Scheduler scheduler) throws InterruptedException { <add> Thread.UncaughtExceptionHandler originalHandler = Thread.getDefaultUncaughtExceptionHandler(); <add> try { <add> CapturingUncaughtExceptionHandler handler = new CapturingUncaughtExceptionHandler(); <add> Thread.setDefaultUncaughtExceptionHandler(handler); <add> IllegalStateException error = new IllegalStateException("Should be delivered to handler"); <add> Observable.error(error) <add> .subscribeOn(scheduler) <add> .subscribe(); <add> <add> if (!handler.completed.await(3, TimeUnit.SECONDS)) { <add> fail("timed out"); <add> } <add> <add> assertEquals("Should have received exactly 1 exception", 1, handler.count); <add> Throwable cause = handler.caught; <add> while (cause != null) { <add> if (error.equals(cause)) break; <add> if (cause == cause.getCause()) break; <add> cause = cause.getCause(); <add> } <add> assertEquals("Our error should have been delivered to the handler", error, cause); <add> } finally { <add> Thread.setDefaultUncaughtExceptionHandler(originalHandler); <add> } <add> } <add> <add> /** <add> * Verifies that the given Scheduler does not deliver handled errors to its executing Thread's <add> * {@link java.lang.Thread.UncaughtExceptionHandler}. <add> * <p> <add> * This is a companion test to {@link #testUnhandledErrorIsDeliveredToThreadHandler}, and is needed only for the <add> * same Schedulers. <add> */ <add> static void testHandledErrorIsNotDeliveredToThreadHandler(Scheduler scheduler) throws InterruptedException { <add> Thread.UncaughtExceptionHandler originalHandler = Thread.getDefaultUncaughtExceptionHandler(); <add> try { <add> CapturingUncaughtExceptionHandler handler = new CapturingUncaughtExceptionHandler(); <add> CapturingObserver<Object> observer = new CapturingObserver<>(); <add> Thread.setDefaultUncaughtExceptionHandler(handler); <add> IllegalStateException error = new IllegalStateException("Should be delivered to handler"); <add> Observable.error(error) <add> .subscribeOn(scheduler) <add> .subscribe(observer); <add> <add> if (!observer.completed.await(3, TimeUnit.SECONDS)) { <add> fail("timed out"); <add> } <add> <add> assertEquals("Handler should not have received anything", 0, handler.count); <add> assertEquals("Observer should have received an error", 1, observer.errorCount); <add> assertEquals("Observer should not have received a next value", 0, observer.nextCount); <add> <add> Throwable cause = observer.error; <add> while (cause != null) { <add> if (error.equals(cause)) break; <add> if (cause == cause.getCause()) break; <add> cause = cause.getCause(); <add> } <add> assertEquals("Our error should have been delivered to the observer", error, cause); <add> } finally { <add> Thread.setDefaultUncaughtExceptionHandler(originalHandler); <add> } <add> } <add> <add> private static final class CapturingUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler { <add> int count = 0; <add> Throwable caught; <add> CountDownLatch completed = new CountDownLatch(1); <add> <add> @Override <add> public void uncaughtException(Thread t, Throwable e) { <add> count++; <add> caught = e; <add> completed.countDown(); <add> } <add> } <add> <add> private static final class CapturingObserver<T> extends Observer<T> { <add> CountDownLatch completed = new CountDownLatch(1); <add> int errorCount = 0; <add> int nextCount = 0; <add> Throwable error; <add> <add> @Override <add> public void onComplete() { <add> } <add> <add> @Override <add> public void onError(Throwable e) { <add> errorCount++; <add> error = e; <add> completed.countDown(); <add> } <add> <add> @Override <add> public void onNext(T t) { <add> nextCount++; <add> } <add> } <add>} <ide>\ No newline at end of file <ide><path>src/test/java/io/reactivex/schedulers/TestSchedulerTest.java <add>/** <add> * Copyright 2015 Netflix, Inc. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. 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 distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.schedulers; <add> <add>import static org.junit.Assert.assertEquals; <add>import static org.mockito.Matchers.anyLong; <add>import static org.mockito.Mockito.*; <add> <add>import java.util.concurrent.TimeUnit; <add>import java.util.concurrent.atomic.AtomicInteger; <add>import java.util.function.Function; <add> <add>import org.junit.Test; <add>import org.mockito.*; <add>import org.reactivestreams.*; <add> <add>import io.reactivex.*; <add>import io.reactivex.disposables.Disposable; <add>import io.reactivex.internal.subscriptions.BooleanSubscription; <add> <add>public class TestSchedulerTest { <add> <add> @SuppressWarnings("unchecked") <add> // mocking is unchecked, unfortunately <add> @Test <add> public final void testPeriodicScheduling() { <add> final Function<Long, Void> calledOp = mock(Function.class); <add> <add> final TestScheduler scheduler = new TestScheduler(); <add> final Scheduler.Worker inner = scheduler.createWorker(); <add> <add> try { <add> inner.schedulePeriodically(new Runnable() { <add> @Override <add> public void run() { <add> System.out.println(scheduler.now(TimeUnit.MILLISECONDS)); <add> calledOp.apply(scheduler.now(TimeUnit.MILLISECONDS)); <add> } <add> }, 1, 2, TimeUnit.SECONDS); <add> <add> verify(calledOp, never()).apply(anyLong()); <add> <add> InOrder inOrder = Mockito.inOrder(calledOp); <add> <add> scheduler.advanceTimeBy(999L, TimeUnit.MILLISECONDS); <add> inOrder.verify(calledOp, never()).apply(anyLong()); <add> <add> scheduler.advanceTimeBy(1L, TimeUnit.MILLISECONDS); <add> inOrder.verify(calledOp, times(1)).apply(1000L); <add> <add> scheduler.advanceTimeBy(1999L, TimeUnit.MILLISECONDS); <add> inOrder.verify(calledOp, never()).apply(3000L); <add> <add> scheduler.advanceTimeBy(1L, TimeUnit.MILLISECONDS); <add> inOrder.verify(calledOp, times(1)).apply(3000L); <add> <add> scheduler.advanceTimeBy(5L, TimeUnit.SECONDS); <add> inOrder.verify(calledOp, times(1)).apply(5000L); <add> inOrder.verify(calledOp, times(1)).apply(7000L); <add> <add> inner.dispose(); <add> scheduler.advanceTimeBy(11L, TimeUnit.SECONDS); <add> inOrder.verify(calledOp, never()).apply(anyLong()); <add> } finally { <add> inner.dispose(); <add> } <add> } <add> <add> @SuppressWarnings("unchecked") <add> // mocking is unchecked, unfortunately <add> @Test <add> public final void testPeriodicSchedulingUnsubscription() { <add> final Function<Long, Void> calledOp = mock(Function.class); <add> <add> final TestScheduler scheduler = new TestScheduler(); <add> final Scheduler.Worker inner = scheduler.createWorker(); <add> <add> try { <add> final Disposable subscription = inner.schedulePeriodically(new Runnable() { <add> @Override <add> public void run() { <add> System.out.println(scheduler.now(TimeUnit.MILLISECONDS)); <add> calledOp.apply(scheduler.now(TimeUnit.MILLISECONDS)); <add> } <add> }, 1, 2, TimeUnit.SECONDS); <add> <add> verify(calledOp, never()).apply(anyLong()); <add> <add> InOrder inOrder = Mockito.inOrder(calledOp); <add> <add> scheduler.advanceTimeBy(999L, TimeUnit.MILLISECONDS); <add> inOrder.verify(calledOp, never()).apply(anyLong()); <add> <add> scheduler.advanceTimeBy(1L, TimeUnit.MILLISECONDS); <add> inOrder.verify(calledOp, times(1)).apply(1000L); <add> <add> scheduler.advanceTimeBy(1999L, TimeUnit.MILLISECONDS); <add> inOrder.verify(calledOp, never()).apply(3000L); <add> <add> scheduler.advanceTimeBy(1L, TimeUnit.MILLISECONDS); <add> inOrder.verify(calledOp, times(1)).apply(3000L); <add> <add> scheduler.advanceTimeBy(5L, TimeUnit.SECONDS); <add> inOrder.verify(calledOp, times(1)).apply(5000L); <add> inOrder.verify(calledOp, times(1)).apply(7000L); <add> <add> subscription.dispose(); <add> scheduler.advanceTimeBy(11L, TimeUnit.SECONDS); <add> inOrder.verify(calledOp, never()).apply(anyLong()); <add> } finally { <add> inner.dispose(); <add> } <add> } <add> <add> @Test <add> public final void testImmediateUnsubscribes() { <add> TestScheduler s = new TestScheduler(); <add> final Scheduler.Worker inner = s.createWorker(); <add> final AtomicInteger counter = new AtomicInteger(0); <add> <add> try { <add> inner.schedule(new Runnable() { <add> <add> @Override <add> public void run() { <add> counter.incrementAndGet(); <add> System.out.println("counter: " + counter.get()); <add> inner.schedule(this); <add> } <add> <add> }); <add> inner.dispose(); <add> assertEquals(0, counter.get()); <add> } finally { <add> inner.dispose(); <add> } <add> } <add> <add> @Test <add> public final void testImmediateUnsubscribes2() { <add> TestScheduler s = new TestScheduler(); <add> final Scheduler.Worker inner = s.createWorker(); <add> try { <add> final AtomicInteger counter = new AtomicInteger(0); <add> <add> final Disposable subscription = inner.schedule(new Runnable() { <add> <add> @Override <add> public void run() { <add> counter.incrementAndGet(); <add> System.out.println("counter: " + counter.get()); <add> inner.schedule(this); <add> } <add> <add> }); <add> subscription.dispose(); <add> assertEquals(0, counter.get()); <add> } finally { <add> inner.dispose(); <add> } <add> } <add> <add> @Test <add> public final void testNestedSchedule() { <add> final TestScheduler scheduler = new TestScheduler(); <add> final Scheduler.Worker inner = scheduler.createWorker(); <add> <add> try { <add> final Runnable calledOp = mock(Runnable.class); <add> <add> Observable<Object> poller; <add> poller = Observable.create(new Publisher<Object>() { <add> @Override <add> public void subscribe(final Subscriber<? super Object> aSubscriber) { <add> BooleanSubscription bs = new BooleanSubscription(); <add> aSubscriber.onSubscribe(bs); <add> inner.schedule(new Runnable() { <add> @Override <add> public void run() { <add> if (!bs.isCancelled()) { <add> calledOp.run(); <add> inner.schedule(this, 5, TimeUnit.SECONDS); <add> } <add> } <add> }); <add> } <add> }); <add> <add> InOrder inOrder = Mockito.inOrder(calledOp); <add> <add> Disposable sub; <add> sub = poller.subscribe(); <add> <add> scheduler.advanceTimeTo(6, TimeUnit.SECONDS); <add> inOrder.verify(calledOp, times(2)).run(); <add> <add> sub.dispose(); <add> scheduler.advanceTimeTo(11, TimeUnit.SECONDS); <add> inOrder.verify(calledOp, never()).run(); <add> <add> sub = poller.subscribe(); <add> scheduler.advanceTimeTo(12, TimeUnit.SECONDS); <add> inOrder.verify(calledOp, times(1)).run(); <add> } finally { <add> inner.dispose(); <add> } <add> } <add>} <ide>\ No newline at end of file <ide><path>src/test/java/io/reactivex/schedulers/TrampolineSchedulerTest.java <add>/** <add> * Copyright 2015 Netflix, Inc. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. 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 distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.schedulers; <add> <add>import static org.junit.Assert.*; <add> <add>import java.util.*; <add>import java.util.concurrent.TimeUnit; <add>import java.util.function.*; <add> <add>import org.junit.Test; <add>import org.reactivestreams.Subscriber; <add> <add>import io.reactivex.*; <add>import io.reactivex.Observable; <add>import io.reactivex.Scheduler.Worker; <add>import io.reactivex.disposables.*; <add>import io.reactivex.subscribers.TestSubscriber; <add> <add>public class TrampolineSchedulerTest extends AbstractSchedulerTests { <add> <add> @Override <add> protected Scheduler getScheduler() { <add> return Schedulers.trampoline(); <add> } <add> <add> @Test <add> public final void testMergeWithCurrentThreadScheduler1() { <add> <add> final String currentThreadName = Thread.currentThread().getName(); <add> <add> Observable<Integer> o1 = Observable.<Integer> just(1, 2, 3, 4, 5); <add> Observable<Integer> o2 = Observable.<Integer> just(6, 7, 8, 9, 10); <add> Observable<String> o = Observable.<Integer> merge(o1, o2).subscribeOn(Schedulers.trampoline()).map(new Function<Integer, String>() { <add> <add> @Override <add> public String apply(Integer t) { <add> assertTrue(Thread.currentThread().getName().equals(currentThreadName)); <add> return "Value_" + t + "_Thread_" + Thread.currentThread().getName(); <add> } <add> }); <add> <add> o.toBlocking().forEach(new Consumer<String>() { <add> <add> @Override <add> public void accept(String t) { <add> System.out.println("t: " + t); <add> } <add> }); <add> } <add> <add> @Test <add> public void testNestedTrampolineWithUnsubscribe() { <add> final ArrayList<String> workDone = new ArrayList<>(); <add> final CompositeDisposable workers = new CompositeDisposable(); <add> Worker worker = Schedulers.trampoline().createWorker(); <add> try { <add> workers.add(worker); <add> worker.schedule(new Runnable() { <add> <add> @Override <add> public void run() { <add> workers.add(doWorkOnNewTrampoline("A", workDone)); <add> } <add> <add> }); <add> <add> final Worker worker2 = Schedulers.trampoline().createWorker(); <add> workers.add(worker2); <add> worker2.schedule(new Runnable() { <add> <add> @Override <add> public void run() { <add> workers.add(doWorkOnNewTrampoline("B", workDone)); <add> // we unsubscribe worker2 ... it should not affect work scheduled on a separate Trampline.Worker <add> worker2.dispose(); <add> } <add> <add> }); <add> <add> assertEquals(6, workDone.size()); <add> assertEquals(Arrays.asList("A.1", "A.B.1", "A.B.2", "B.1", "B.B.1", "B.B.2"), workDone); <add> } finally { <add> workers.dispose(); <add> } <add> } <add> <add> /** <add> * This is a regression test for #1702. Concurrent work scheduling that is improperly synchronized can cause an <add> * action to be added or removed onto the priority queue during a poll, which can result in NPEs during queue <add> * sifting. While it is difficult to isolate the issue directly, we can easily trigger the behavior by spamming the <add> * trampoline with enqueue requests from multiple threads concurrently. <add> */ <add> @Test <add> public void testTrampolineWorkerHandlesConcurrentScheduling() { <add> final Worker trampolineWorker = Schedulers.trampoline().createWorker(); <add> final Subscriber<Object> observer = TestHelper.mockSubscriber(); <add> final TestSubscriber<Disposable> ts = new TestSubscriber<>(observer); <add> <add> // Spam the trampoline with actions. <add> Observable.range(0, 50) <add> .flatMap(count -> Observable.interval(1, TimeUnit.MICROSECONDS).map( <add> count1 -> trampolineWorker.schedule(() -> {})).take(100)) <add> .subscribeOn(Schedulers.computation()) <add> .subscribe(ts); <add> ts.awaitTerminalEvent(); <add> ts.assertNoErrors(); <add> } <add> <add> private static Worker doWorkOnNewTrampoline(final String key, final ArrayList<String> workDone) { <add> Worker worker = Schedulers.trampoline().createWorker(); <add> worker.schedule(new Runnable() { <add> <add> @Override <add> public void run() { <add> String msg = key + ".1"; <add> workDone.add(msg); <add> System.out.println(msg); <add> Worker worker3 = Schedulers.trampoline().createWorker(); <add> worker3.schedule(createPrintAction(key + ".B.1", workDone)); <add> worker3.schedule(createPrintAction(key + ".B.2", workDone)); <add> } <add> <add> }); <add> return worker; <add> } <add> <add> private static Runnable createPrintAction(final String message, final ArrayList<String> workDone) { <add> return new Runnable() { <add> <add> @Override <add> public void run() { <add> System.out.println(message); <add> workDone.add(message); <add> } <add> <add> }; <add> } <add>} <ide>\ No newline at end of file
15
PHP
PHP
remove unneded phpstan suppression
4700f01313a1c5b08742b3c407453a63913e625d
<ide><path>src/Http/Client.php <ide> protected function _createRequest(string $method, string $url, $data, $options): <ide> $headers['Content-Type'] = 'application/x-www-form-urlencoded'; <ide> } <ide> <del> /** @phpstan-ignore-next-line */ <ide> $request = new Request($url, $method, $headers, $data); <ide> $request = $request->withProtocolVersion($this->getConfig('protocolVersion')); <ide> $cookies = $options['cookies'] ?? [];
1
Ruby
Ruby
add return values to example [ci skip]
5ad722c23b7cae9d2e135ee33eb786e315e62130
<ide><path>actionpack/lib/action_controller/metal/strong_parameters.rb <ide> def fetch(key, *args) <ide> # params.dig(:foo, :zot, :xyz) # => nil <ide> # <ide> # params2 = ActionController::Parameters.new(foo: [10, 11, 12]) <del> # params2.dig(:foo, 1) <add> # params2.dig(:foo, 1) # => 11 <ide> def dig(*keys) <ide> convert_value_to_parameters(@parameters.dig(*keys)) <ide> end
1
Text
Text
fix broken link
ebfbbdb331f8f93d92650cb4689807f67219833d
<ide><path>examples/with-redux-toolkit/README.md <ide> Deploy it to the cloud with [Vercel](https://vercel.com/new?utm_source=github&ut <ide> <ide> ### TypeScript Setup (optional) <ide> <del>If you haven't already added [TypeScript](https://www.typescriptlang.org/) to your project, follow the [steps in the Next.js documentation](https://nextjs.org/docs/basic-features/TypeScript). If you are new to TypeScript, go through the Next.js [learning lesson on TypeScript](https://nextjs.org/learn/excel/TypeScript). <add>If you haven't already added [TypeScript](https://www.typescriptlang.org/) to your project, follow the [steps in the Next.js documentation](https://nextjs.org/docs/basic-features/typescript). If you are new to TypeScript, go through the Next.js [learning lesson on TypeScript](https://nextjs.org/learn/excel/TypeScript). <ide> <ide> Once TypeScript is added, follow the instructions given on the Redux Toolkit [documentation](https://redux-toolkit.js.org/tutorials/TypeScript) to set up and use Redux Toolkit and React-Redux with TypeScript
1
PHP
PHP
allow validatein for type array
331dc60cd7ed387ef264d22899fb3c7c756e4453
<ide><path>src/Illuminate/Validation/Validator.php <ide> protected function getSize($attribute, $value) <ide> */ <ide> protected function validateIn($attribute, $value, $parameters) <ide> { <add> if (is_array($value) && in_array('array', $this->rules[$attribute])) { <add> return count(array_diff($value, $parameters)) == 0; <add> } <add> <ide> return in_array((string) $value, $parameters); <ide> } <ide>
1
Python
Python
use bold for text with bg
555f84b976f03cc601d972c96b91e4014a955040
<ide><path>glances/outputs/glances_curses.py <ide> def _init_colors(self): <ide> self.filter_color = curses.color_pair(10) | A_BOLD <ide> <ide> self.no_color = curses.color_pair(1) <del> self.default_color = curses.color_pair(3) <add> self.default_color = curses.color_pair(3) | A_BOLD <ide> self.nice_color = curses.color_pair(9) <ide> self.cpu_time_color = curses.color_pair(9) <ide> self.ifCAREFUL_color = curses.color_pair(4) | A_BOLD
1
Ruby
Ruby
call the columns hash method
425925b1c6433309fcbaa7242df39394b70280a6
<ide><path>lib/arel/visitors/to_sql.rb <ide> def column_for attr <ide> <ide> return nil unless table_exists? table <ide> <del> column_cache[table][name] <add> column_cache(table)[name] <ide> end <ide> <del> def column_cache <del> @schema_cache.columns_hash <add> def column_cache(table) <add> @schema_cache.columns_hash(table) <ide> end <ide> <ide> def visit_Arel_Nodes_Values o <ide><path>test/support/fake_record.rb <ide> class Column < Struct.new(:name, :type) <ide> end <ide> <ide> class Connection <del> attr_reader :tables, :columns_hash <add> attr_reader :tables <ide> attr_accessor :visitor <ide> <ide> def initialize(visitor = nil) <ide> def initialize(visitor = nil) <ide> @visitor = visitor <ide> end <ide> <add> def columns_hash table_name <add> @columns_hash[table_name] <add> end <add> <ide> def primary_key name <ide> @primary_keys[name.to_s] <ide> end
2
Javascript
Javascript
add test for deepequal float32array
d968e4324b2653866d1718c68281b52da7bcbc24
<ide><path>test/parallel/test-assert-typedarray-deepequal.js <ide> const notEqualArrayPairs = [ <ide> [new Int16Array([-256]), new Uint16Array([0xff00])], // same bits <ide> [new Int32Array([-256]), new Uint32Array([0xffffff00])], // ditto <ide> [new Float32Array([0.1]), new Float32Array([0.0])], <add> [new Float32Array([0.1]), new Float32Array([0.1, 0.2])], <ide> [new Float64Array([0.1]), new Float64Array([0.0])], <ide> [new Uint8Array([1, 2, 3]).buffer, new Uint8Array([4, 5, 6]).buffer], <ide> [
1
Javascript
Javascript
remove trailing whitespace
3f6e2e2983cf571b772afc89d6c52e558dc039bf
<ide><path>tests/test-scale-log.js <ide> var x = d3.scale.log(); <ide> console.log("nice():"); <ide> [ <ide> [1.1, 10.9], [10.9, 1.1], [.7, 11.001], [123.1, 6.7], [0, .49], <del> [.12, 1, 2.5, 3, 10.9] <add> [.12, 1, 2.5, 3, 10.9] <ide> ].forEach(function(d) { <ide> var s = " [" + d.map(f) + " ]"; <ide> while (s.length < 21) s += " ";
1
Ruby
Ruby
store#initialize options [ci-skip]
7e884e299618427c59d778e0868f73c1bc0aa948
<ide><path>activesupport/lib/active_support/cache.rb <ide> def retrieve_pool_options(options) <ide> end <ide> end <ide> <del> # Creates a new cache. The options will be passed to any write method calls <del> # except for <tt>:namespace</tt> which can be used to set the global <del> # namespace for the cache. <add> # Creates a new cache. <add> # <add> # ==== Options <add> # <add> # * +:namespace+ - Sets the namespace for the cache. This option is <add> # especially useful if your application shares a cache with other <add> # applications. <add> # * +:coder+ - Replaces the default cache entry serialization mechanism <add> # with a custom one. The +coder+ must respond to +dump+ and +load+. <add> # Using a custom coder disables automatic compression. <add> # <add> # Any other specified options are treated as default options for the <add> # relevant cache operations, such as #read, #write, and #fetch. <ide> def initialize(options = nil) <ide> @options = options ? normalize_options(options) : {} <ide> @options[:compress] = true unless @options.key?(:compress)
1
Java
Java
fix minor issue in reactormessagechannel
f7f66f2e5c18a614a7d741b5ca3d6a07cb49fd8e
<ide><path>spring-websocket/src/main/java/org/springframework/web/messaging/support/ReactorMessageChannel.java <ide> public boolean unsubscribe(MessageHandler<Message<?>> handler) { <ide> logger.trace("Channel " + getName() + ", removing subscription for handler " + handler); <ide> } <ide> <del> Registration<?> registration = this.registrations.get(handler); <add> Registration<?> registration = this.registrations.remove(handler); <ide> if (registration == null) { <ide> if (logger.isTraceEnabled()) { <ide> logger.trace("Channel " + getName() + ", no subscription for handler " + handler);
1
Javascript
Javascript
move dgram invalid host test to internet tests
402a793012b934447276eacb5052efe5cf041cc2
<ide><path>test/internet/test-dgram-connect.js <add>'use strict'; <add> <add>const common = require('../common'); <add>const { addresses } = require('../common/internet'); <add>const assert = require('assert'); <add>const dgram = require('dgram'); <add> <add>const PORT = 12345; <add> <add>const client = dgram.createSocket('udp4'); <add>client.connect(PORT, addresses.INVALID_HOST, common.mustCall((err) => { <add> assert.ok(err.code === 'ENOTFOUND' || err.code === 'EAI_AGAIN'); <add> <add> client.once('error', common.mustCall((err) => { <add> assert.ok(err.code === 'ENOTFOUND' || err.code === 'EAI_AGAIN'); <add> client.once('connect', common.mustCall(() => client.close())); <add> client.connect(PORT); <add> })); <add> <add> client.connect(PORT, addresses.INVALID_HOST); <add>})); <ide><path>test/parallel/test-dgram-connect.js <ide> 'use strict'; <ide> <ide> const common = require('../common'); <del>const { addresses } = require('../common/internet'); <ide> const assert = require('assert'); <ide> const dgram = require('dgram'); <ide> <ide> client.connect(PORT, common.mustCall(() => { <ide> code: 'ERR_SOCKET_DGRAM_NOT_CONNECTED' <ide> }); <ide> <del> client.connect(PORT, addresses.INVALID_HOST, common.mustCall((err) => { <del> assert.ok(err.code === 'ENOTFOUND' || err.code === 'EAI_AGAIN'); <del> <del> client.once('error', common.mustCall((err) => { <del> assert.ok(err.code === 'ENOTFOUND' || err.code === 'EAI_AGAIN'); <del> client.once('connect', common.mustCall(() => client.close())); <del> client.connect(PORT); <del> })); <del> <del> client.connect(PORT, addresses.INVALID_HOST); <del> })); <add> client.once('connect', common.mustCall(() => client.close())); <add> client.connect(PORT); <ide> })); <ide> <ide> assert.throws(() => {
2
Text
Text
add rmg to collaborators
bd8753aabf58ba71d8a5b2d2c043ad78484f6778
<ide><path>README.md <ide> information about the governance of the Node.js project, see <ide> * [petkaantonov](https://github.com/petkaantonov) - **Petka Antonov** &lt;petka_antonov@hotmail.com&gt; <ide> * [qard](https://github.com/qard) - **Stephen Belanger** &lt;admin@stephenbelanger.com&gt; <ide> * [rlidwka](https://github.com/rlidwka) - **Alex Kocharin** &lt;alex@kocharin.ru&gt; <add>* [rmg](https://github.com/rmg) - **Ryan Graham** &lt;r.m.graham@gmail.com&gt; <ide> * [robertkowalski](https://github.com/robertkowalski) - **Robert Kowalski** &lt;rok@kowalski.gd&gt; <ide> * [romankl](https://github.com/romankl) - **Roman Klauke** &lt;romaaan.git@gmail.com&gt; <ide> * [saghul](https://github.com/saghul) - **Saúl Ibarra Corretgé** &lt;saghul@gmail.com&gt;
1
Ruby
Ruby
add more tests around the polymorphic url api
de6cda5e5fab17bd087b7fd6b6fa7a6cfa738ef1
<ide><path>actionview/test/activerecord/polymorphic_routes_test.rb <ide> def test_with_class <ide> end <ide> end <ide> <add> def test_with_class_list_of_one <add> with_test_routes do <add> assert_url "http://example.com/projects", [@project.class] <add> end <add> end <add> <ide> def test_with_new_record <ide> with_test_routes do <ide> assert_url "http://example.com/projects", @project <ide> def test_with_array_containing_single_name <ide> end <ide> end <ide> <add> def test_with_array_containing_single_string_name <add> with_test_routes do <add> assert_url "http://example.com/projects", ["projects"] <add> end <add> end <add> <ide> def test_with_array_containing_symbols <ide> with_test_routes do <ide> assert_url "http://example.com/series/new", [:new, :series]
1
Python
Python
fix bug in standalone mode [issue 279]
3a07899855af59097c2d4c83035772e966514f8a
<ide><path>glances/glances.py <ide> def displayMem(self, mem, memswap, proclist, offset_x=0): <ide> # get the psutil version installed on the server, if in client mode <ide> if client_tag: <ide> server_psutil_version = stats.getPsutilVersion() <add> else: <add> server_psutil_version = "" <ide> <ide> if (screen_y > self.mem_y + 5 and <ide> screen_x > self.mem_x + offset_x + memblocksize - extblocksize):
1
Java
Java
fix issue with obtaining websocketcontainer
3c6c56fe0de9f31bf5f31e8f414f294fd03624dd
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/server/endpoint/ServerEndpointExporter.java <ide> import org.springframework.context.ApplicationContext; <ide> import org.springframework.context.ApplicationContextAware; <ide> import org.springframework.util.Assert; <del>import org.springframework.util.ClassUtils; <ide> import org.springframework.util.ReflectionUtils; <ide> <ide> /** <ide> */ <ide> public class ServerEndpointExporter implements InitializingBean, BeanPostProcessor, ApplicationContextAware { <ide> <del> private static final boolean isServletApiPresent = <del> ClassUtils.isPresent("javax.servlet.ServletContext", ServerEndpointExporter.class.getClassLoader()); <del> <ide> private static Log logger = LogFactory.getLog(ServerEndpointExporter.class); <ide> <ide> <ide> public void setApplicationContext(ApplicationContext applicationContext) { <ide> } <ide> <ide> protected ServerContainer getServerContainer() { <del> if (isServletApiPresent) { <del> try { <del> Method getter = ReflectionUtils.findMethod(this.applicationContext.getClass(), "getServletContext"); <del> Object servletContext = getter.invoke(this.applicationContext); <ide> <del> Method attrMethod = ReflectionUtils.findMethod(servletContext.getClass(), "getAttribute", String.class); <del> return (ServerContainer) attrMethod.invoke(servletContext, "javax.websocket.server.ServerContainer"); <del> } <del> catch (Exception ex) { <del> throw new IllegalStateException( <del> "Failed to get javax.websocket.server.ServerContainer via ServletContext attribute", ex); <del> } <add> Class<?> servletContextClass; <add> try { <add> servletContextClass = Class.forName("javax.servlet.ServletContext"); <add> } <add> catch (Throwable e) { <add> return null; <add> } <add> <add> try { <add> Method getter = ReflectionUtils.findMethod(this.applicationContext.getClass(), "getServletContext"); <add> Object servletContext = getter.invoke(this.applicationContext); <add> Method attrMethod = ReflectionUtils.findMethod(servletContextClass, "getAttribute", String.class); <add> return (ServerContainer) attrMethod.invoke(servletContext, "javax.websocket.server.ServerContainer"); <add> } <add> catch (Exception ex) { <add> throw new IllegalStateException( <add> "Failed to get javax.websocket.server.ServerContainer via ServletContext attribute", ex); <ide> } <del> return null; <ide> } <ide> <ide> @Override
1
PHP
PHP
add a salt initialization
5cd64beef9c0a84d856b52d967dc58b19d50e784
<ide><path>tests/TestCase/TestSuite/IntegrationTestCaseTest.php <ide> use Cake\Routing\Router; <ide> use Cake\TestSuite\IntegrationTestCase; <ide> use Cake\Test\Fixture\AssertIntegrationTestCase; <add>use Cake\Utility\Security; <ide> <ide> /** <ide> * Self test of the IntegrationTestCase <ide> public function testRequestBuildingQueryParameters() <ide> */ <ide> public function testCookieEncrypted() <ide> { <add> Security::salt('abcdabcdabcdabcdabcdabcdabcdabcdabcd'); <ide> $this->cookieEncrypted('KeyOfCookie', 'Encrypted with aes by default'); <ide> $request = $this->_buildRequest('/tasks/view', 'GET', []); <ide> $this->assertStringStartsWith('Q2FrZQ==.', $request->cookies['KeyOfCookie']);
1
PHP
PHP
take table name in delete()
7aba2d169ac6faf309cce7e03d67c6a6b06f5e24
<ide><path>lib/Cake/Model/Datasource/Database/Query.php <ide> public function update() { <ide> * Can be combined with from(), where() and other methods to <ide> * create delete queries with specific conditions. <ide> * <add> * @param string $table The table to use when deleting. This <ide> * @return Query <ide> */ <del> public function delete() { <add> public function delete($table = null) { <ide> $this->_dirty = true; <ide> $this->_type = 'delete'; <add> if ($table) { <add> $this->from($table); <add> } <ide> return $this; <ide> } <ide> <ide><path>lib/Cake/Test/TestCase/Model/Datasource/Database/QueryTest.php <ide> public function testDecorateResults() { <ide> } <ide> <ide> /** <del> * Test a basic delete. <add> * Test a basic delete using from() <ide> * <ide> * @return void <ide> */ <del> public function testDeleteSimple() { <add> public function testDeleteWithFrom() { <ide> $this->_insertTwoRecords(); <ide> $query = new Query($this->connection); <ide> <ide> public function testDeleteSimple() { <ide> $this->assertCount(2, $result); <ide> } <ide> <add>/** <add> * Test a basic delete with no from() call. <add> * <add> * @return void <add> */ <add> public function testDeleteNoFrom() { <add> $this->_insertTwoRecords(); <add> $query = new Query($this->connection); <add> <add> $query->delete('authors') <add> ->where('1 = 1'); <add> <add> $result = $query->sql(false); <add> $this->assertContains('DELETE FROM authors ', $result); <add> <add> $result = $query->execute(); <add> $this->assertInstanceOf('Cake\Model\Datasource\Database\Statement', $result); <add> $this->assertCount(2, $result); <add> } <add> <ide> /** <ide> * Test setting select() & delete() modes. <ide> * <ide> public function testSelectAndDeleteOnSameQuery() { <ide> $this->_insertTwoRecords(); <ide> $query = new Query($this->connection); <ide> $result = $query->select() <del> ->delete() <del> ->from('authors') <add> ->delete('authors') <ide> ->where('1 = 1'); <ide> $result = $query->sql(false); <ide>
2
Javascript
Javascript
add primordials to adapters
ea92ca1484b0fcea212ee8d0c1fd4f086bf36e08
<ide><path>lib/internal/webstreams/adapters.js <ide> const { <ide> PromiseResolve, <ide> SafePromiseAll, <ide> SafePromisePrototypeFinally, <add> TypedArrayPrototypeGetBuffer, <add> TypedArrayPrototypeGetByteOffset, <add> TypedArrayPrototypeGetByteLength, <ide> Uint8Array, <ide> } = primordials; <ide> <ide> function newStreamWritableFromWritableStream(writableStream, options = kEmptyObj <ide> } else { <ide> chunk = Buffer.from(chunk, encoding); <ide> chunk = new Uint8Array( <del> chunk.buffer, <del> chunk.byteOffset, <del> chunk.byteLength); <add> TypedArrayPrototypeGetBuffer(chunk), <add> TypedArrayPrototypeGetByteOffset(chunk), <add> TypedArrayPrototypeGetByteLength(chunk), <add> ); <ide> } <ide> } <ide> <ide> function newStreamDuplexFromReadableWritablePair(pair = kEmptyObject, options = <ide> } else { <ide> chunk = Buffer.from(chunk, encoding); <ide> chunk = new Uint8Array( <del> chunk.buffer, <del> chunk.byteOffset, <del> chunk.byteLength); <add> TypedArrayPrototypeGetBuffer(chunk), <add> TypedArrayPrototypeGetByteOffset(chunk), <add> TypedArrayPrototypeGetByteLength(chunk), <add> ); <ide> } <ide> } <ide>
1
Python
Python
fix quarentine tests affected by aip-39
975a4e05c98803ce8491d9422516ccb04611082e
<ide><path>airflow/jobs/scheduler_job.py <ide> import time <ide> from collections import defaultdict <ide> from datetime import timedelta <del>from typing import DefaultDict, Dict, Iterable, List, Optional, Tuple <add>from typing import Collection, DefaultDict, Dict, List, Optional, Tuple <ide> <ide> from sqlalchemy import and_, func, not_, or_, tuple_ <ide> from sqlalchemy.exc import OperationalError <ide> def _create_dagruns_for_dags(self, guard, session): <ide> guard.commit() <ide> # END: create dagruns <ide> <del> def _create_dag_runs(self, dag_models: Iterable[DagModel], session: Session) -> None: <add> def _create_dag_runs(self, dag_models: Collection[DagModel], session: Session) -> None: <ide> """ <ide> Unconditionally create a DAG run for the given DAG, and update the dag_model's fields to control <ide> if/when the next DAGRun should be created <ide> def _schedule_dag_run( <ide> unfinished_task_instances = ( <ide> session.query(TI) <ide> .filter(TI.dag_id == dag_run.dag_id) <del> .filter(TI.execution_date == dag_run.execution_date) <add> .filter(TI.run_id == dag_run.run_id) <ide> .filter(TI.state.in_(State.unfinished)) <ide> ) <ide> for task_instance in unfinished_task_instances: <ide><path>tests/cli/commands/test_task_command.py <ide> class TestLogsfromTaskRunCommand(unittest.TestCase): <ide> def setUp(self) -> None: <ide> self.dag_id = "test_logging_dag" <ide> self.task_id = "test_task" <add> self.run_id = "test_run" <ide> self.dag_path = os.path.join(ROOT_FOLDER, "dags", "test_logging_in_dag.py") <ide> reset(self.dag_id) <ide> self.execution_date = timezone.make_aware(datetime(2017, 1, 1)) <ide> def setUp(self) -> None: <ide> self.ti_log_file_path = os.path.join(self.log_dir, self.log_filename) <ide> self.parser = cli_parser.get_parser() <ide> <add> DagBag().get_dag(self.dag_id).create_dagrun( <add> run_id=self.run_id, <add> execution_date=self.execution_date, <add> start_date=timezone.utcnow(), <add> state=State.RUNNING, <add> run_type=DagRunType.MANUAL, <add> ) <add> <ide> root = self.root_logger = logging.getLogger() <ide> self.root_handlers = root.handlers.copy() <ide> self.root_filters = root.filters.copy() <ide> def test_log_file_template_with_run_task(self): <ide> with mock.patch.object(task_command, "_run_task_by_selected_method"): <ide> with conf_vars({('core', 'dags_folder'): self.dag_path}): <ide> # increment the try_number of the task to be run <del> dag = DagBag().get_dag(self.dag_id) <del> task = dag.get_task(self.task_id) <ide> with create_session() as session: <del> dag.create_dagrun( <del> execution_date=self.execution_date, <del> start_date=timezone.utcnow(), <del> state=State.RUNNING, <del> run_type=DagRunType.MANUAL, <del> session=session, <del> ) <del> ti = TaskInstance(task, self.execution_date) <del> ti.refresh_from_db(session=session, lock_for_update=True) <del> ti.try_number = 1 # not running, so starts at 0 <del> session.merge(ti) <add> ti = session.query(TaskInstance).filter_by(run_id=self.run_id) <add> ti.try_number = 1 <ide> <ide> log_file_path = os.path.join(os.path.dirname(self.ti_log_file_path), "2.log") <ide> <ide><path>tests/executors/test_celery_executor.py <ide> def test_send_tasks_to_celery_hang(register_signals): <ide> executor = celery_executor.CeleryExecutor() <ide> <ide> task = MockTask() <del> task_tuples_to_send = [(None, None, None, None, task) for _ in range(26)] <add> task_tuples_to_send = [(None, None, None, task) for _ in range(26)] <ide> <ide> for _ in range(500): <ide> # This loop can hang on Linux if celery_executor does something wrong with <ide><path>tests/jobs/test_scheduler_job.py <ide> import psutil <ide> import pytest <ide> from freezegun import freeze_time <del>from parameterized import parameterized <ide> from sqlalchemy import func <ide> <ide> import airflow.example_dags <ide> def test_scheduler_keeps_scheduling_pool_full(self, dag_maker): <ide> with dag_maker( <ide> dag_id='test_scheduler_keeps_scheduling_pool_full_d1', <ide> start_date=DEFAULT_DATE, <del> ) as dag_d1: <add> ): <ide> BashOperator( <ide> task_id='test_scheduler_keeps_scheduling_pool_full_t1', <ide> pool='test_scheduler_keeps_scheduling_pool_full_p1', <ide> bash_command='echo hi', <ide> ) <add> dag_d1 = dag_maker.dag <ide> <ide> with dag_maker( <ide> dag_id='test_scheduler_keeps_scheduling_pool_full_d2', <ide> start_date=DEFAULT_DATE, <del> ) as dag_d2: <add> ): <ide> BashOperator( <ide> task_id='test_scheduler_keeps_scheduling_pool_full_t2', <ide> pool='test_scheduler_keeps_scheduling_pool_full_p2', <ide> bash_command='echo hi', <ide> ) <add> dag_d2 = dag_maker.dag <ide> <ide> session = settings.Session() <ide> pool_p1 = Pool(pool='test_scheduler_keeps_scheduling_pool_full_p1', slots=1) <ide> def test_verify_integrity_if_dag_changed(self, dag_maker): <ide> session.close() <ide> <ide> @pytest.mark.quarantined <add> @pytest.mark.need_serialized_dag <ide> def test_retry_still_in_executor(self, dag_maker): <ide> """ <ide> Checks if the scheduler does not put a task in limbo, when a task is retried <ide> but is still present in the executor. <ide> """ <ide> executor = MockExecutor(do_update=False) <del> dagbag = DagBag(dag_folder=os.path.join(settings.DAGS_FOLDER, "no_dags.py"), include_examples=False) <del> dagbag.dags.clear() <del> <del> with dag_maker(dag_id='test_retry_still_in_executor', schedule_interval="@once") as dag: <del> dag_task1 = BashOperator( <del> task_id='test_retry_handling_op', <del> bash_command='exit 1', <del> retries=1, <del> ) <ide> <ide> with create_session() as session: <del> orm_dag = DagModel(dag_id=dag.dag_id) <del> orm_dag.is_paused = False <del> session.merge(orm_dag) <add> with dag_maker( <add> dag_id='test_retry_still_in_executor', <add> schedule_interval="@once", <add> session=session, <add> ): <add> dag_task1 = BashOperator( <add> task_id='test_retry_handling_op', <add> bash_command='exit 1', <add> retries=1, <add> ) <add> dag_maker.dag_model.calculate_dagrun_date_fields(dag_maker.dag, None) <ide> <del> @mock.patch('airflow.dag_processing.processor.DagBag', return_value=dagbag) <del> def do_schedule(mock_dagbag): <add> @provide_session <add> def do_schedule(session): <ide> # Use a empty file since the above mock will return the <ide> # expected DAGs. Also specify only a single file so that it doesn't <ide> # try to schedule the above DAG repeatedly. <del> self.scheduler_job = SchedulerJob( <del> num_runs=1, executor=executor, subdir=os.path.join(settings.DAGS_FOLDER, "no_dags.py") <del> ) <add> self.scheduler_job = SchedulerJob(num_runs=1, executor=executor, subdir=os.devnull) <add> self.scheduler_job.dagbag = dag_maker.dagbag <ide> self.scheduler_job.heartrate = 0 <del> self.scheduler_job.run() <add> # Since the DAG is not in the directory watched by scheduler job, <add> # it would've been marked as deleted and not being scheduled. <add> with mock.patch.object(DagModel, "deactivate_deleted_dags"): <add> self.scheduler_job.run() <ide> <ide> do_schedule() <ide> with create_session() as session: <ide> def do_schedule(mock_dagbag): <ide> ) <ide> .first() <ide> ) <add> assert ti is not None, "Task not created by scheduler" <ide> ti.task = dag_task1 <ide> <ide> def run_with_error(ti, ignore_ti_state=False): <ide> def per_test(self) -> None: <ide> self.scheduler_job = None <ide> self.clean_db() <ide> <del> @parameterized.expand( <add> @pytest.mark.parametrize( <add> "expected_query_count, dag_count, task_count", <ide> [ <del> # expected, dag_count, task_count <del> # One DAG with one task per DAG file <del> (24, 1, 1), <del> # One DAG with five tasks per DAG file <del> (28, 1, 5), <del> # 10 DAGs with 10 tasks per DAG file <del> (195, 10, 10), <del> ] <add> (20, 1, 1), # One DAG with one task per DAG file. <add> (20, 1, 5), # One DAG with five tasks per DAG file. <add> (83, 10, 10), # 10 DAGs with 10 tasks per DAG file. <add> ], <ide> ) <ide> def test_execute_queries_count_with_harvested_dags(self, expected_query_count, dag_count, task_count): <ide> with mock.patch.dict( <ide> def test_execute_queries_count_with_harvested_dags(self, expected_query_count, d <ide> <ide> self.scheduler_job._run_scheduler_loop() <ide> <del> @parameterized.expand( <add> @pytest.mark.parametrize( <add> "expected_query_counts, dag_count, task_count, start_ago, schedule_interval, shape", <ide> [ <del> # expected, dag_count, task_count, start_ago, schedule_interval, shape <del> # One DAG with one task per DAG file <del> ([9, 9, 9, 9], 1, 1, "1d", "None", "no_structure"), <del> ([9, 9, 9, 9], 1, 1, "1d", "None", "linear"), <del> ([21, 12, 12, 12], 1, 1, "1d", "@once", "no_structure"), <del> ([21, 12, 12, 12], 1, 1, "1d", "@once", "linear"), <del> ([21, 22, 24, 26], 1, 1, "1d", "30m", "no_structure"), <del> ([21, 22, 24, 26], 1, 1, "1d", "30m", "linear"), <del> ([21, 22, 24, 26], 1, 1, "1d", "30m", "binary_tree"), <del> ([21, 22, 24, 26], 1, 1, "1d", "30m", "star"), <del> ([21, 22, 24, 26], 1, 1, "1d", "30m", "grid"), <del> # One DAG with five tasks per DAG file <del> ([9, 9, 9, 9], 1, 5, "1d", "None", "no_structure"), <del> ([9, 9, 9, 9], 1, 5, "1d", "None", "linear"), <del> ([21, 12, 12, 12], 1, 5, "1d", "@once", "no_structure"), <del> ([22, 13, 13, 13], 1, 5, "1d", "@once", "linear"), <del> ([21, 22, 24, 26], 1, 5, "1d", "30m", "no_structure"), <del> ([22, 24, 27, 30], 1, 5, "1d", "30m", "linear"), <del> ([22, 24, 27, 30], 1, 5, "1d", "30m", "binary_tree"), <del> ([22, 24, 27, 30], 1, 5, "1d", "30m", "star"), <del> ([22, 24, 27, 30], 1, 5, "1d", "30m", "grid"), <del> # 10 DAGs with 10 tasks per DAG file <del> ([9, 9, 9, 9], 10, 10, "1d", "None", "no_structure"), <del> ([9, 9, 9, 9], 10, 10, "1d", "None", "linear"), <del> ([84, 27, 27, 27], 10, 10, "1d", "@once", "no_structure"), <del> ([94, 40, 40, 40], 10, 10, "1d", "@once", "linear"), <del> ([84, 88, 88, 88], 10, 10, "1d", "30m", "no_structure"), <del> ([94, 114, 114, 114], 10, 10, "1d", "30m", "linear"), <del> ([94, 108, 108, 108], 10, 10, "1d", "30m", "binary_tree"), <del> ([94, 108, 108, 108], 10, 10, "1d", "30m", "star"), <del> ([94, 108, 108, 108], 10, 10, "1d", "30m", "grid"), <del> ] <add> # One DAG with one task per DAG file. <add> ([10, 10, 10, 10], 1, 1, "1d", "None", "no_structure"), <add> ([10, 10, 10, 10], 1, 1, "1d", "None", "linear"), <add> ([23, 13, 13, 13], 1, 1, "1d", "@once", "no_structure"), <add> ([23, 13, 13, 13], 1, 1, "1d", "@once", "linear"), <add> ([23, 24, 26, 28], 1, 1, "1d", "30m", "no_structure"), <add> ([23, 24, 26, 28], 1, 1, "1d", "30m", "linear"), <add> ([23, 24, 26, 28], 1, 1, "1d", "30m", "binary_tree"), <add> ([23, 24, 26, 28], 1, 1, "1d", "30m", "star"), <add> ([23, 24, 26, 28], 1, 1, "1d", "30m", "grid"), <add> # One DAG with five tasks per DAG file. <add> ([10, 10, 10, 10], 1, 5, "1d", "None", "no_structure"), <add> ([10, 10, 10, 10], 1, 5, "1d", "None", "linear"), <add> ([23, 13, 13, 13], 1, 5, "1d", "@once", "no_structure"), <add> ([24, 14, 14, 14], 1, 5, "1d", "@once", "linear"), <add> ([23, 24, 26, 28], 1, 5, "1d", "30m", "no_structure"), <add> ([24, 26, 29, 32], 1, 5, "1d", "30m", "linear"), <add> ([24, 26, 29, 32], 1, 5, "1d", "30m", "binary_tree"), <add> ([24, 26, 29, 32], 1, 5, "1d", "30m", "star"), <add> ([24, 26, 29, 32], 1, 5, "1d", "30m", "grid"), <add> # 10 DAGs with 10 tasks per DAG file. <add> ([10, 10, 10, 10], 10, 10, "1d", "None", "no_structure"), <add> ([10, 10, 10, 10], 10, 10, "1d", "None", "linear"), <add> ([95, 28, 28, 28], 10, 10, "1d", "@once", "no_structure"), <add> ([105, 41, 41, 41], 10, 10, "1d", "@once", "linear"), <add> ([95, 99, 99, 99], 10, 10, "1d", "30m", "no_structure"), <add> ([105, 125, 125, 125], 10, 10, "1d", "30m", "linear"), <add> ([105, 119, 119, 119], 10, 10, "1d", "30m", "binary_tree"), <add> ([105, 119, 119, 119], 10, 10, "1d", "30m", "star"), <add> ([105, 119, 119, 119], 10, 10, "1d", "30m", "grid"), <add> ], <ide> ) <ide> def test_process_dags_queries_count( <ide> self, expected_query_counts, dag_count, task_count, start_ago, schedule_interval, shape <ide> def test_process_dags_queries_count( <ide> self.scheduler_job.executor = MockExecutor(do_update=False) <ide> self.scheduler_job.heartbeat = mock.MagicMock() <ide> self.scheduler_job.processor_agent = mock_agent <add> <add> failures = [] # Collects assertion errors and report all of them at the end. <add> message = "Expected {expected_count} query, but got {current_count} located at:" <ide> for expected_query_count in expected_query_counts: <ide> with create_session() as session: <del> with assert_queries_count(expected_query_count): <del> self.scheduler_job._do_scheduling(session) <add> try: <add> with assert_queries_count(expected_query_count, message): <add> self.scheduler_job._do_scheduling(session) <add> except AssertionError as e: <add> failures.append(str(e)) <add> if failures: <add> prefix = "Collected database query count mismatches:" <add> joined = "\n\n".join(failures) <add> raise AssertionError(f"{prefix}\n\n{joined}") <ide> <ide> def test_should_mark_dummy_task_as_success(self): <ide> dag_file = os.path.join( <ide> def test_should_mark_dummy_task_as_success(self): <ide> dagbag = DagBag(dag_folder=dag_file, include_examples=False, read_dags_from_db=False) <ide> dagbag.sync_to_db() <ide> <del> self.scheduler_job_job = SchedulerJob(subdir=os.devnull) <del> self.scheduler_job_job.processor_agent = mock.MagicMock() <del> dag = self.scheduler_job_job.dagbag.get_dag("test_only_dummy_tasks") <add> self.scheduler_job = SchedulerJob(subdir=os.devnull) <add> self.scheduler_job.processor_agent = mock.MagicMock() <add> dag = self.scheduler_job.dagbag.get_dag("test_only_dummy_tasks") <ide> <ide> # Create DagRun <ide> session = settings.Session() <ide> orm_dag = session.query(DagModel).get(dag.dag_id) <del> self.scheduler_job_job._create_dag_runs([orm_dag], session) <add> self.scheduler_job._create_dag_runs([orm_dag], session) <ide> <ide> drs = DagRun.find(dag_id=dag.dag_id, session=session) <ide> assert len(drs) == 1 <ide> dr = drs[0] <ide> <ide> # Schedule TaskInstances <del> self.scheduler_job_job._schedule_dag_run(dr, session) <add> self.scheduler_job._schedule_dag_run(dr, session) <ide> with create_session() as session: <ide> tis = session.query(TaskInstance).all() <ide> <del> dags = self.scheduler_job_job.dagbag.dags.values() <add> dags = self.scheduler_job.dagbag.dags.values() <ide> assert ['test_only_dummy_tasks'] == [dag.dag_id for dag in dags] <ide> assert 5 == len(tis) <ide> assert { <ide> def test_should_mark_dummy_task_as_success(self): <ide> assert end_date is None <ide> assert duration is None <ide> <del> self.scheduler_job_job._schedule_dag_run(dr, session) <add> self.scheduler_job._schedule_dag_run(dr, session) <ide> with create_session() as session: <ide> tis = session.query(TaskInstance).all() <ide>
4
Javascript
Javascript
throw error when unexpected state has been found
7ebe12dde12a62301fb8979917592fdd5a51012a
<ide><path>lib/RuntimeTemplate.js <ide> module.exports = class RuntimeTemplate { <ide> } <ide> <ide> moduleId({ module, request }) { <del> if (!module) <add> if (!module) { <ide> return this.missingModule({ <ide> request <ide> }); <add> } <add> if (module.id === null) { <add> throw new Error( <add> `RuntimeTemplate.moduleId(): Module ${module.identifier()} has no id. This should not happen.` <add> ); <add> } <ide> return `${this.comment({ request })}${JSON.stringify(module.id)}`; <ide> } <ide> <ide> module.exports = class RuntimeTemplate { <ide> } <ide> <ide> moduleNamespacePromise({ block, module, request, message, strict, weak }) { <del> if (!module) <add> if (!module) { <ide> return this.missingModulePromise({ <ide> request <ide> }); <add> } <add> if (module.id === null) { <add> throw new Error( <add> `RuntimeTemplate.moduleNamespacePromise(): Module ${module.identifier()} has no id. This should not happen.` <add> ); <add> } <ide> const promise = this.blockPromise({ <ide> block, <ide> message <ide> module.exports = class RuntimeTemplate { <ide> } <ide> <ide> importStatement({ update, module, request, importVar, originModule }) { <del> if (!module) <add> if (!module) { <ide> return this.missingModuleStatement({ <ide> request <ide> }); <add> } <add> if (module.id === null) { <add> throw new Error( <add> `RuntimeTemplate.importStatement(): Module ${module.identifier()} has no id. This should not happen.` <add> ); <add> } <ide> const comment = this.comment({ <ide> request <ide> });
1
Ruby
Ruby
move route reloading into railties
5f8e48cbd297aca4add4b48efa2136ba6ac851b1
<ide><path>actionpack/lib/action_controller/dispatch/dispatcher.rb <ide> def define_dispatcher_callbacks(cache_classes) <ide> # Run prepare callbacks before every request in development mode <ide> self.prepare_each_request = true <ide> <del> # Development mode callbacks <del> ActionDispatch::Callbacks.before_dispatch do |app| <del> ActionController::Routing::Routes.reload <del> end <del> <ide> ActionDispatch::Callbacks.after_dispatch do <ide> # Cleanup the application before processing the current request. <ide> ActiveRecord::Base.reset_subclasses if defined?(ActiveRecord) <ide><path>actionpack/lib/action_dispatch/routing/route_set.rb <ide> def formatted_#{selector}(*args) # <ide> end <ide> end <ide> <del> attr_accessor :routes, :named_routes, :configuration_files, :controller_paths <add> attr_accessor :routes, :named_routes <add> attr_accessor :disable_clear_and_finalize <ide> <ide> def initialize <del> self.configuration_files = [] <del> self.controller_paths = [] <del> <ide> self.routes = [] <ide> self.named_routes = NamedRouteCollection.new <ide> <del> @clear_before_draw = true <del> @finalize_set_on_draw = true <del> <del> clear! <add> @disable_clear_and_finalize = false <ide> end <ide> <ide> def draw(&block) <del> clear! if @clear_before_draw <add> clear! unless @disable_clear_and_finalize <ide> <ide> mapper = Mapper.new(self) <ide> if block.arity == 1 <ide> def draw(&block) <ide> mapper.instance_exec(&block) <ide> end <ide> <del> if @finalize_set_on_draw <del> @set.add_route(NotFound) <del> install_helpers <del> @set.freeze <del> end <add> finalize! unless @disable_clear_and_finalize <ide> <ide> nil <ide> end <ide> <add> def finalize! <add> @set.add_route(NotFound) <add> install_helpers <add> @set.freeze <add> end <add> <ide> def clear! <add> # Clear the controller cache so we may discover new ones <add> @controller_constraints = nil <ide> routes.clear <ide> named_routes.clear <ide> @set = ::Rack::Mount::RouteSet.new(:parameters_key => PARAMETERS_KEY) <ide> def empty? <ide> routes.empty? <ide> end <ide> <del> def add_configuration_file(path) <del> self.configuration_files << path <del> end <del> <del> # Deprecated accessor <del> def configuration_file=(path) <del> add_configuration_file(path) <del> end <del> <del> # Deprecated accessor <del> def configuration_file <del> configuration_files <del> end <del> <del> def load! <del> # Clear the controller cache so we may discover new ones <del> @controller_constraints = nil <del> <del> load_routes! <del> end <del> <del> # reload! will always force a reload whereas load checks the timestamp first <del> alias reload! load! <del> <del> def reload <del> if configuration_files.any? && @routes_last_modified <del> if routes_changed_at == @routes_last_modified <del> return # routes didn't change, don't reload <del> else <del> @routes_last_modified = routes_changed_at <del> end <del> end <del> <del> load! <del> end <del> <del> def load_routes! <del> if configuration_files.any? <del> @finalize_set_on_draw = false <del> configuration_files.each_with_index do |config, index| <del> @finalize_set_on_draw = true if index == (configuration_files.length - 1) <del> load(config) <del> @clear_before_draw = false if index == 0 <del> end <del> @clear_before_draw = true <del> @finalize_set_on_draw = true <del> <del> @routes_last_modified = routes_changed_at <del> else <del> draw do |map| <del> map.connect ":controller/:action/:id" <del> end <del> end <del> end <del> <del> def routes_changed_at <del> routes_changed_at = nil <del> <del> configuration_files.each do |config| <del> config_changed_at = File.stat(config).mtime <del> <del> if routes_changed_at.nil? || config_changed_at > routes_changed_at <del> routes_changed_at = config_changed_at <del> end <del> end <del> <del> routes_changed_at <del> end <del> <ide> CONTROLLER_REGEXP = /[_a-zA-Z0-9]+/ <ide> <ide> def controller_constraints <ide> def controller_namespaces <ide> namespaces << controller_name.split('/')[0...-1].join('/') <ide> end <ide> <del> # Find namespaces in controllers/ directory <del> controller_paths.each do |load_path| <del> load_path = File.expand_path(load_path) <del> Dir["#{load_path}/**/*_controller.rb"].collect do |path| <del> namespaces << File.dirname(path).sub(/#{load_path}\/?/, '') <add> # TODO: Move this into Railties <add> if defined?(Rails.application) <add> # Find namespaces in controllers/ directory <add> Rails.application.configuration.controller_paths.each do |load_path| <add> load_path = File.expand_path(load_path) <add> Dir["#{load_path}/**/*_controller.rb"].collect do |path| <add> namespaces << File.dirname(path).sub(/#{load_path}\/?/, '') <add> end <ide> end <ide> end <ide> <ide><path>actionpack/lib/action_dispatch/testing/assertions/routing.rb <ide> def assert_recognizes(expected_options, path, extras={}, message=nil) <ide> request_method = nil <ide> end <ide> <del> ActionController::Routing::Routes.reload if ActionController::Routing::Routes.empty? <ide> request = recognized_request_for(path, request_method) <ide> <ide> expected_options = expected_options.clone <ide> def assert_recognizes(expected_options, path, extras={}, message=nil) <ide> def assert_generates(expected_path, options, defaults={}, extras = {}, message=nil) <ide> expected_path = "/#{expected_path}" unless expected_path[0] == ?/ <ide> # Load routes.rb if it hasn't been loaded. <del> ActionController::Routing::Routes.reload if ActionController::Routing::Routes.empty? <ide> <ide> generated_path, extra_keys = ActionController::Routing::Routes.generate_extras(options, defaults) <ide> found_extras = options.reject {|k, v| ! extra_keys.include? k} <ide><path>actionpack/test/controller/dispatcher_test.rb <ide> def setup <ide> ActionDispatch::Callbacks.reset_callbacks(:call) <ide> <ide> ActionController::Routing::Routes.stubs(:call).returns([200, {}, 'response']) <del> ActionController::Routing::Routes.stubs(:reload) <ide> Dispatcher.stubs(:require_dependency) <ide> end <ide> <ide> def test_clears_dependencies_after_dispatch_if_in_loading_mode <ide> dispatch(false) <ide> end <ide> <del> def test_reloads_routes_before_dispatch_if_in_loading_mode <del> ActionController::Routing::Routes.expects(:reload).once <del> dispatch(false) <del> end <del> <del> def test_leaves_dependencies_after_dispatch_if_not_in_loading_mode <del> ActionController::Routing::Routes.expects(:reload).never <del> ActiveSupport::Dependencies.expects(:clear).never <del> <del> dispatch <del> end <del> <ide> def test_prepare_callbacks <ide> a = b = c = nil <ide> ActionDispatch::Callbacks.to_prepare { |*args| a = b = c = 1 } <ide><path>railties/lib/rails/application.rb <ide> def call(env) <ide> end <ide> end <ide> <add> attr_reader :route_configuration_files <add> <ide> def initialize <ide> Rails.application ||= self <add> <add> @route_configuration_files = [] <add> <ide> run_initializers(self) <ide> end <ide> <ide> def routes <ide> ActionController::Routing::Routes <ide> end <ide> <add> def routes_changed_at <add> routes_changed_at = nil <add> <add> route_configuration_files.each do |config| <add> config_changed_at = File.stat(config).mtime <add> <add> if routes_changed_at.nil? || config_changed_at > routes_changed_at <add> routes_changed_at = config_changed_at <add> end <add> end <add> <add> routes_changed_at <add> end <add> <add> def reload_routes! <add> routes.disable_clear_and_finalize = true <add> <add> routes.clear! <add> route_configuration_files.each { |config| load(config) } <add> routes.finalize! <add> <add> nil <add> ensure <add> routes.disable_clear_and_finalize = false <add> end <add> <ide> def initializers <ide> initializers = super <ide> plugins.each { |p| initializers += p.initializers } <ide> def call(env) <ide> next unless configuration.frameworks.include?(:action_controller) <ide> require 'rails/dispatcher' unless defined?(::Dispatcher) <ide> Dispatcher.define_dispatcher_callbacks(configuration.cache_classes) <add> <add> unless configuration.cache_classes <add> # Setup dev mode route reloading <add> routes_last_modified = routes_changed_at <add> reload_routes = lambda do <add> unless routes_changed_at == routes_last_modified <add> routes_last_modified = routes_changed_at <add> reload_routes! <add> end <add> end <add> ActionDispatch::Callbacks.before_dispatch { |callbacks| reload_routes } <add> end <ide> end <ide> <ide> # Routing must be initialized after plugins to allow the former to extend the routes <ide> def call(env) <ide> # loading module used to lazily load controllers (Configuration#controller_paths). <ide> initializer :initialize_routing do <ide> next unless configuration.frameworks.include?(:action_controller) <del> <del> ActionController::Routing::Routes.controller_paths += configuration.controller_paths <del> ActionController::Routing::Routes.add_configuration_file(configuration.routes_configuration_file) <del> ActionController::Routing::Routes.reload! <add> route_configuration_files << configuration.routes_configuration_file <add> reload_routes! <ide> end <ide> # <ide> # # Observers are loaded after plugins in case Observers or observed models are modified by plugins. <ide><path>railties/lib/rails/console_app.rb <ide> def new_session <ide> def reload! <ide> puts "Reloading..." <ide> ActionDispatch::Callbacks.new(lambda {}, true) <del> ActionController::Routing::Routes.reload <add> Rails.application.reload_routes! <ide> true <ide> end <ide><path>railties/lib/rails/plugin.rb <ide> def load_paths <ide> initializer :add_routing_file, :after => :initialize_routing do |app| <ide> routing_file = "#{path}/config/routes.rb" <ide> if File.exist?(routing_file) <del> app.routes.add_configuration_file(routing_file) <del> app.routes.reload! <add> app.route_configuration_files << routing_file <add> app.reload_routes! <ide> end <ide> end <ide> end
7
PHP
PHP
add `abilities` method to gate contract
f7fa463291a72f69aba8c03123078fddd5d039d1
<ide><path>src/Illuminate/Contracts/Auth/Access/Gate.php <ide> public function getPolicyFor($class); <ide> * @return static <ide> */ <ide> public function forUser($user); <add> <add> /** <add> * Get all of the defined abilities. <add> * <add> * @return array <add> */ <add> public function abilities(); <ide> }
1
Ruby
Ruby
add missing autoload `type`
24b59434e6aca9679b9f86a41cfbb1a33e3d5619
<ide><path>activemodel/lib/active_model.rb <ide> module ActiveModel <ide> autoload :SecurePassword <ide> autoload :Serialization <ide> autoload :Translation <add> autoload :Type <ide> autoload :Validations <ide> autoload :Validator <ide> <ide><path>activemodel/lib/active_model/attribute.rb <ide> # frozen_string_literal: true <ide> <ide> require "active_support/core_ext/object/duplicable" <del>require "active_model/type" <ide> <ide> module ActiveModel <ide> class Attribute # :nodoc: <ide><path>activemodel/lib/active_model/attributes.rb <ide> # frozen_string_literal: true <ide> <ide> require "active_support/core_ext/object/deep_dup" <del>require "active_model/type" <ide> require "active_model/attribute_set" <ide> require "active_model/attribute/user_provided_default" <ide> <ide><path>activemodel/test/cases/attribute_set_test.rb <ide> <ide> require "cases/helper" <ide> require "active_model/attribute_set" <del>require "active_model/type" <ide> <ide> module ActiveModel <ide> class AttributeSetTest < ActiveModel::TestCase <ide><path>activemodel/test/cases/type/big_integer_test.rb <ide> # frozen_string_literal: true <ide> <ide> require "cases/helper" <del>require "active_model/type" <ide> <ide> module ActiveModel <ide> module Type <ide><path>activemodel/test/cases/type/binary_test.rb <ide> # frozen_string_literal: true <ide> <ide> require "cases/helper" <del>require "active_model/type" <ide> <ide> module ActiveModel <ide> module Type <ide><path>activemodel/test/cases/type/boolean_test.rb <ide> # frozen_string_literal: true <ide> <ide> require "cases/helper" <del>require "active_model/type" <ide> <ide> module ActiveModel <ide> module Type <ide><path>activemodel/test/cases/type/date_test.rb <ide> # frozen_string_literal: true <ide> <ide> require "cases/helper" <del>require "active_model/type" <ide> <ide> module ActiveModel <ide> module Type <ide><path>activemodel/test/cases/type/date_time_test.rb <ide> # frozen_string_literal: true <ide> <ide> require "cases/helper" <del>require "active_model/type" <ide> <ide> module ActiveModel <ide> module Type <ide><path>activemodel/test/cases/type/decimal_test.rb <ide> # frozen_string_literal: true <ide> <ide> require "cases/helper" <del>require "active_model/type" <ide> <ide> module ActiveModel <ide> module Type <ide><path>activemodel/test/cases/type/float_test.rb <ide> # frozen_string_literal: true <ide> <ide> require "cases/helper" <del>require "active_model/type" <ide> <ide> module ActiveModel <ide> module Type <ide><path>activemodel/test/cases/type/immutable_string_test.rb <ide> # frozen_string_literal: true <ide> <ide> require "cases/helper" <del>require "active_model/type" <ide> <ide> module ActiveModel <ide> module Type <ide><path>activemodel/test/cases/type/integer_test.rb <ide> # frozen_string_literal: true <ide> <ide> require "cases/helper" <del>require "active_model/type" <ide> require "active_support/core_ext/numeric/time" <ide> <ide> module ActiveModel <ide><path>activemodel/test/cases/type/registry_test.rb <ide> # frozen_string_literal: true <ide> <ide> require "cases/helper" <del>require "active_model/type" <ide> <ide> module ActiveModel <ide> module Type <ide><path>activemodel/test/cases/type/string_test.rb <ide> # frozen_string_literal: true <ide> <ide> require "cases/helper" <del>require "active_model/type" <ide> <ide> module ActiveModel <ide> module Type <ide><path>activemodel/test/cases/type/time_test.rb <ide> # frozen_string_literal: true <ide> <ide> require "cases/helper" <del>require "active_model/type" <ide> <ide> module ActiveModel <ide> module Type <ide><path>activemodel/test/cases/type/value_test.rb <ide> # frozen_string_literal: true <ide> <ide> require "cases/helper" <del>require "active_model/type" <ide> <ide> module ActiveModel <ide> module Type <ide><path>activerecord/lib/active_record.rb <ide> module ActiveRecord <ide> <ide> autoload :Result <ide> autoload :TableMetadata <add> autoload :Type <ide> end <ide> <ide> module Coders <ide><path>activerecord/lib/active_record/connection_adapters/abstract_adapter.rb <ide> # frozen_string_literal: true <ide> <del>require "active_record/type" <ide> require "active_record/connection_adapters/determine_if_preparable_visitor" <ide> require "active_record/connection_adapters/schema_cache" <ide> require "active_record/connection_adapters/sql_type_metadata"
19
Go
Go
support driver labels
421ef35df298c704b794bceb8780f17941f3c1d5
<ide><path>libnetwork/controller.go <ide> Package libnetwork provides the basic functionality and extension points to <ide> create network namespaces and allocate interfaces for containers to use. <ide> <del> // Create a new controller instance <del> controller, _err := libnetwork.New(nil) <del> <del> // Select and configure the network driver <del> networkType := "bridge" <del> <del> driverOptions := options.Generic{} <del> genericOption := make(map[string]interface{}) <del> genericOption[netlabel.GenericData] = driverOptions <del> err := controller.ConfigureNetworkDriver(networkType, genericOption) <del> if err != nil { <del> return <del> } <del> <del> // Create a network for containers to join. <del> // NewNetwork accepts Variadic optional arguments that libnetwork and Drivers can make of <del> network, err := controller.NewNetwork(networkType, "network1") <del> if err != nil { <del> return <del> } <del> <del> // For each new container: allocate IP and interfaces. The returned network <del> // settings will be used for container infos (inspect and such), as well as <del> // iptables rules for port publishing. This info is contained or accessible <del> // from the returned endpoint. <del> ep, err := network.CreateEndpoint("Endpoint1") <del> if err != nil { <del> return <del> } <del> <del> // A container can join the endpoint by providing the container ID to the join <del> // api. <del> // Join acceps Variadic arguments which will be made use of by libnetwork and Drivers <del> err = ep.Join("container1", <del> libnetwork.JoinOptionHostname("test"), <del> libnetwork.JoinOptionDomainname("docker.io")) <del> if err != nil { <del> return <del> } <add> // Create a new controller instance <add> controller, _err := libnetwork.New(nil) <add> <add> // Select and configure the network driver <add> networkType := "bridge" <add> <add> driverOptions := options.Generic{} <add> genericOption := make(map[string]interface{}) <add> genericOption[netlabel.GenericData] = driverOptions <add> err := controller.ConfigureNetworkDriver(networkType, genericOption) <add> if err != nil { <add> return <add> } <add> <add> // Create a network for containers to join. <add> // NewNetwork accepts Variadic optional arguments that libnetwork and Drivers can make of <add> network, err := controller.NewNetwork(networkType, "network1") <add> if err != nil { <add> return <add> } <add> <add> // For each new container: allocate IP and interfaces. The returned network <add> // settings will be used for container infos (inspect and such), as well as <add> // iptables rules for port publishing. This info is contained or accessible <add> // from the returned endpoint. <add> ep, err := network.CreateEndpoint("Endpoint1") <add> if err != nil { <add> return <add> } <add> <add> // A container can join the endpoint by providing the container ID to the join <add> // api. <add> // Join acceps Variadic arguments which will be made use of by libnetwork and Drivers <add> err = ep.Join("container1", <add> libnetwork.JoinOptionHostname("test"), <add> libnetwork.JoinOptionDomainname("docker.io")) <add> if err != nil { <add> return <add> } <ide> */ <ide> package libnetwork <ide> <ide> import ( <ide> "fmt" <ide> "net" <add> "strings" <ide> "sync" <ide> <ide> log "github.com/Sirupsen/logrus" <ide> import ( <ide> "github.com/docker/libnetwork/datastore" <ide> "github.com/docker/libnetwork/driverapi" <ide> "github.com/docker/libnetwork/hostdiscovery" <add> "github.com/docker/libnetwork/netlabel" <ide> "github.com/docker/libnetwork/sandbox" <ide> "github.com/docker/libnetwork/types" <ide> ) <ide> func (c *controller) ConfigureNetworkDriver(networkType string, options map[stri <ide> <ide> func (c *controller) RegisterDriver(networkType string, driver driverapi.Driver, capability driverapi.Capability) error { <ide> c.Lock() <del> defer c.Unlock() <ide> if !config.IsValidName(networkType) { <add> c.Unlock() <ide> return ErrInvalidName(networkType) <ide> } <ide> if _, ok := c.drivers[networkType]; ok { <add> c.Unlock() <ide> return driverapi.ErrActiveRegistration(networkType) <ide> } <ide> c.drivers[networkType] = &driverData{driver, capability} <add> <add> if c.cfg == nil { <add> c.Unlock() <add> return nil <add> } <add> <add> opt := make(map[string]interface{}) <add> for _, label := range c.cfg.Daemon.Labels { <add> if strings.HasPrefix(label, netlabel.DriverPrefix+"."+networkType) { <add> opt[netlabel.Key(label)] = netlabel.Value(label) <add> } <add> } <add> <add> if capability.Scope == driverapi.GlobalScope { <add> opt[netlabel.KVProvider] = c.cfg.Datastore.Client.Provider <add> opt[netlabel.KVProviderURL] = c.cfg.Datastore.Client.Address <add> } <add> <add> c.Unlock() <add> <add> if len(opt) != 0 { <add> if err := driver.Config(opt); err != nil { <add> return err <add> } <add> } <add> <ide> return nil <ide> } <ide>
1
Text
Text
update the doc of build-bridges.md
0ba6a128eeee3f1519fa3842a6847402a7eafa05
<ide><path>docs/userguide/networking/default_network/build-bridges.md <ide> parent = "smn_networking_def" <ide> <ide> # Build your own bridge <ide> <del>This section explains building your own bridge to replaced the Docker default <add>This section explains how to build your own bridge to replace the Docker default <ide> bridge. This is a `bridge` network named `bridge` created automatically when you <ide> install Docker. <ide> <ide> > **Note**: The [Docker networks feature](../dockernetworks.md) allows you to <ide> create user-defined networks in addition to the default bridge network. <ide> <ide> You can set up your own bridge before starting Docker and use `-b BRIDGE` or <del>`--bridge=BRIDGE` to tell Docker to use your bridge instead. If you already <del>have Docker up and running with its default `docker0` still configured, you will <del>probably want to begin by stopping the service and removing the interface: <add>`--bridge=BRIDGE` to tell Docker to use your bridge instead. If you already <add>have Docker up and running with its default `docker0` still configured, <add>you can directly create your bridge and restart Docker with it or want to begin by <add>stopping the service and removing the interface: <ide> <ide> ``` <ide> # Stopping Docker and removing docker0 <ide> $ sudo iptables -t nat -F POSTROUTING <ide> ``` <ide> <ide> Then, before starting the Docker service, create your own bridge and give it <del>whatever configuration you want. Here we will create a simple enough bridge <add>whatever configuration you want. Here we will create a simple enough bridge <ide> that we really could just have used the options in the previous section to <ide> customize `docker0`, but it will be enough to illustrate the technique. <ide> <ide> MASQUERADE all -- 192.168.5.0/24 0.0.0.0/0 <ide> ``` <ide> <ide> The result should be that the Docker server starts successfully and is now <del>prepared to bind containers to the new bridge. After pausing to verify the <add>prepared to bind containers to the new bridge. After pausing to verify the <ide> bridge's configuration, try creating a container -- you will see that its IP <ide> address is in your new IP address range, which Docker will have auto-detected. <ide>
1
Python
Python
remove scipy.org from the breadcrumb formattiong
b176563629800d2ae38832644b9ef1e1828a9d92
<ide><path>doc/source/conf.py <ide> def setup(app): <ide> "scipy_org_logo": False, <ide> "rootlinks": [("https://numpy.org/", "NumPy.org"), <ide> ("https://numpy.org/doc", "Docs"), <del> ("https://scipy.org/", "Scipy.org"), <ide> ] <ide> } <ide> html_sidebars = {'index': ['indexsidebar.html', 'searchbox.html']}
1
Javascript
Javascript
do global clean up in teardown function
9475e31d32544c275ee79155b223322f132f3f1a
<ide><path>test/data/testrunner.js <ide> window.moduleTeardown = function() { <ide> oldActive = jQuery.active; <ide> } <ide> <add> Globals.cleanup(); <add> <ide> for ( i in jQuery.cache ) { <ide> ++cacheLength; <ide> }
1
Javascript
Javascript
use common.fixtures module
b9ad14d69d23c53bc65efb178c461f523b244ae1
<ide><path>test/parallel/test-eval-require.js <ide> <ide> 'use strict'; <ide> const common = require('../common'); <add>const { fixturesDir } = require('../common/fixtures'); <ide> const assert = require('assert'); <ide> const spawn = require('child_process').spawn; <ide> <ide> const options = { <del> cwd: common.fixturesDir <add> cwd: fixturesDir <ide> }; <ide> const child = spawn(process.execPath, ['-e', 'require("foo")'], options); <ide> child.on('exit', common.mustCall((code) => {
1
Javascript
Javascript
consider newlines for cursor position
93c3674ff7115fb2a3dbb5b4ffd22f4d5ed9a472
<ide><path>lib/readline.js <ide> Interface.prototype._historyPrev = function() { <ide> Interface.prototype._getDisplayPos = function(str) { <ide> var offset = 0; <ide> var col = this.columns; <add> var row = 0; <ide> var code; <ide> str = stripVTControlCharacters(str); <ide> for (var i = 0, len = str.length; i < len; i++) { <ide> code = codePointAt(str, i); <ide> if (code >= 0x10000) { // surrogates <ide> i++; <ide> } <add> if (code === 0x0a) { // new line \n <add> offset = 0; <add> row += 1; <add> continue; <add> } <ide> if (isFullWidthCodePoint(code)) { <ide> if ((offset + 1) % col === 0) { <ide> offset++; <ide> Interface.prototype._getDisplayPos = function(str) { <ide> } <ide> } <ide> var cols = offset % col; <del> var rows = (offset - cols) / col; <add> var rows = row + (offset - cols) / col; <ide> return {cols: cols, rows: rows}; <ide> }; <ide> <ide><path>test/simple/test-readline-interface.js <ide> FakeInput.prototype.end = function() {}; <ide> assert.equal(callCount, 1); <ide> rli.close(); <ide> <add> if (terminal) { <add> // question <add> fi = new FakeInput(); <add> rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); <add> expectedLines = ['foo']; <add> rli.question(expectedLines[0], function() { <add> rli.close(); <add> }); <add> var cursorPos = rli._getCursorPos(); <add> assert.equal(cursorPos.rows, 0); <add> assert.equal(cursorPos.cols, expectedLines[0].length); <add> rli.close(); <add> <add> // sending a multi-line question <add> fi = new FakeInput(); <add> rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); <add> expectedLines = ['foo', 'bar']; <add> rli.question(expectedLines.join('\n'), function() { <add> rli.close(); <add> }); <add> var cursorPos = rli._getCursorPos(); <add> assert.equal(cursorPos.rows, expectedLines.length - 1); <add> assert.equal(cursorPos.cols, expectedLines.slice(-1)[0].length); <add> rli.close(); <add> } <add> <ide> // wide characters should be treated as two columns. <ide> assert.equal(readline.isFullWidthCodePoint('a'.charCodeAt(0)), false); <ide> assert.equal(readline.isFullWidthCodePoint('あ'.charCodeAt(0)), true);
2
Text
Text
add xray status
caa7ed543887a9da6d3d3c99f4da8e87c5aad0e3
<ide><path>docs/focus/2018-03-05.md <ide> - Fixed issues with the Bash parser <ide> - Fixed a bug found during constant fuzzing by the security team: https://github.com/tree-sitter/tree-sitter/issues/133 <ide> - Xray <add> - Decided not to run all text through HarfBuzz for performance reasons, and came up with a plan for addressing mandatory text shaping issues in the future. <add> - Implemented anchors, selections, and basic selection movement. <add> - Partially implemented selection rendering. <add> - For more details, see the [detailed update](https://github.com/atom/xray/blob/master/docs/updates/2018_03_05.md) in the Xray repository. <ide> - Reactor Duty <ide> <ide> ## Focus for week ahead <ide> - Optimize syntax tree updates in the presence of syntax errors. This will improve performance across the board but also make Tree-sitter usable in edge cases where the wrong language is being used to parse a document. <ide> - Start work on allowing parsing to take place on a background thread <ide> - Xray <add> - Finish selection rendering <add> - Wire up enough of the key bindings / commands system to move cursors/selections <add> - Start on editing <add> - For more details, see [the detailed update](https://github.com/atom/xray/blob/master/docs/updates/2018_03_05.md) <ide> - Reactor Duty
1
Javascript
Javascript
fix typo error
8578fcce8c582fe17fc05b9daacef07b1d78ce7f
<ide><path>src/renderers/webgl/WebGLProgram.js <ide> function getEncodingComponents( encoding ) { <ide> case GammaEncoding: <ide> return [ 'Gamma', '( value, float( GAMMA_FACTOR ) )' ]; <ide> case LogLuvEncoding: <del> return [ 'LogLuv', '( value )']; <add> return [ 'LogLuv', '( value )' ]; <ide> default: <ide> throw new Error( 'unsupported encoding: ' + encoding ); <ide>
1
PHP
PHP
add @throws tag to docblock
e8df362ca56b8f02c134fbf53803cfbacd174914
<ide><path>src/Validation/ValidatorAwareTrait.php <ide> trait ValidatorAwareTrait <ide> * @param \Cake\Validation\Validator|null $validator The validator instance to store, <ide> * use null to get a validator. <ide> * @return \Cake\Validation\Validator <add> * @throws \RuntimeException <ide> */ <ide> public function validator($name = null, Validator $validator = null) <ide> {
1
Javascript
Javascript
fix typos on $new
b01c28c9004a693f6990ed0b44738ddd0c8fc241
<ide><path>src/ng/rootScope.js <ide> function $RootScopeProvider(){ <ide> * the scope and its child scopes to be permanently detached from the parent and thus stop <ide> * participating in model change detection and listener notification by invoking. <ide> * <del> * @param {boolean} isolate if true then the scoped does not prototypically inherit from the <del> * parent scope. The scope is isolated, as it can not se parent scope properties. <del> * When creating widgets it is useful for the widget to not accidently read parent <add> * @param {boolean} isolate if true then the scope does not prototypically inherit from the <add> * parent scope. The scope is isolated, as it can not see parent scope properties. <add> * When creating widgets it is useful for the widget to not accidentally read parent <ide> * state. <ide> * <ide> * @returns {Object} The newly created child scope.
1
Python
Python
add id attribute to kubernetespod
e59a88cc12650ac139d154c216b2ee6a8244a2ea
<ide><path>libcloud/container/drivers/kubernetes.py <ide> <ide> <ide> class KubernetesPod(object): <del> def __init__(self, name, containers, namespace): <add> def __init__(self, id, name, containers, namespace): <ide> """ <ide> A Kubernetes pod <ide> """ <add> self.id = id <ide> self.name = name <ide> self.containers = containers <ide> self.namespace = namespace <ide> def _to_pod(self, data): <ide> spec = container_statuses <ide> containers.append(self._to_container(container, spec, data)) <ide> return KubernetesPod( <add> id=data["metadata"]["uid"], <ide> name=data["metadata"]["name"], <ide> namespace=data["metadata"]["namespace"], <ide> containers=containers,
1
Ruby
Ruby
implement more of @reitermarkus's comments
7ee98eb421380afd45144ef8df1656cb22d4bb66
<ide><path>Library/Homebrew/cask/lib/hbc/cli/upgrade.rb <ide> def initialize(*) <ide> end <ide> <ide> def run <del> outdated_casks = casks(alternative: -> { Hbc.installed }).select { |cask| cask.outdated?(greedy?) || (args.include?(cask.token) && cask.outdated?(true)) } <add> outdated_casks = casks(alternative: -> { Hbc.installed.select { |cask| <add> cask.outdated?(greedy?) } }).select { |cask| cask.outdated?(true) } <ide> <ide> if outdated_casks.empty? <ide> oh1 "No Casks to upgrade" <ide><path>Library/Homebrew/test/cask/cli/upgrade_spec.rb <ide> it_behaves_like "a command that handles invalid options" <ide> <ide> shared_context "Proper Casks" do <del> before(:example) do <del> installed = <del> [ <del> "outdated/local-caffeine", <del> "outdated/local-transmission", <del> "outdated/auto-updates", <del> ] <add> let(:installed) { <add> [ <add> "outdated/local-caffeine", <add> "outdated/local-transmission", <add> "outdated/auto-updates", <add> ] <add> } <ide> <add> before(:example) do <ide> installed.each { |cask| Hbc::CLI::Install.run(cask) } <ide> <ide> allow_any_instance_of(described_class).to receive(:verbose?).and_return(true) <ide> end <ide> end <ide> <ide> shared_context "Casks that will fail upon upgrade" do <del> before(:example) do <del> installed = <del> [ <del> "outdated/bad-checksum", <del> "outdated/will-fail-if-upgraded", <del> ] <add> let(:installed) { <add> [ <add> "outdated/bad-checksum", <add> "outdated/will-fail-if-upgraded", <add> ] <add> } <ide> <add> before(:example) do <ide> installed.each { |cask| Hbc::CLI::Install.run(cask) } <ide> <ide> allow_any_instance_of(described_class).to receive(:verbose?).and_return(true) <ide> expect(Hbc::CaskLoader.load("local-transmission").versions).to include("2.60") <ide> end <ide> <del> it 'but updates "auto_updates" and "latest" Casks when their tokens are provided in the command line' do <add> it 'updates "auto_updates" and "latest" Casks when their tokens are provided in the command line' do <ide> expect(Hbc::CaskLoader.load("local-caffeine")).to be_installed <ide> expect(Hbc.appdir.join("Caffeine.app")).to be_a_directory <ide> expect(Hbc::CaskLoader.load("local-caffeine").versions).to include("1.2.2") <ide> Warning: Reverting upgrade for Cask .* <ide> EOS <ide> <del> it "by restoring the old Cask if the upgrade's install failed" do <add> it "restores the old Cask if the upgrade failed" do <ide> expect(Hbc::CaskLoader.load("will-fail-if-upgraded")).to be_installed <ide> expect(Hbc.appdir.join("container")).to be_a_file <ide> expect(Hbc::CaskLoader.load("will-fail-if-upgraded").versions).to include("1.2.2") <ide> <ide> expect { <del> expect { <del> described_class.run("will-fail-if-upgraded") <del> }.to raise_error(Hbc::CaskError) <del> }.to output(output_reverted).to_stderr <add> described_class.run("will-fail-if-upgraded") <add> }.to raise_error(Hbc::CaskError).and output(output_reverted).to_stderr <ide> <ide> expect(Hbc::CaskLoader.load("will-fail-if-upgraded")).to be_installed <ide> expect(Hbc.appdir.join("container")).to be_a_file <ide> expect(Hbc::CaskLoader.load("bad-checksum").versions).to include("1.2.2") <ide> <ide> expect { <del> expect { <del> described_class.run("bad-checksum") <del> }.to raise_error(Hbc::CaskSha256MismatchError) <del> }.to_not output(output_reverted).to_stderr <add> described_class.run("bad-checksum") <add> }.to raise_error(Hbc::CaskSha256MismatchError).and (not_to_output output_reverted).to_stderr <ide> <ide> expect(Hbc::CaskLoader.load("bad-checksum")).to be_installed <ide> expect(Hbc.appdir.join("Caffeine.app")).to be_a_directory
2
Text
Text
fix docs about `sudo docker login`
d6007b4db0c2dc788fc0b1d2e2c5e95a5fa0701f
<ide><path>docs/reference/commandline/login.md <ide> You can log into any public or private repository for which you have <ide> credentials. When you log in, the command stores encoded credentials in <ide> `$HOME/.docker/config.json` on Linux or `%USERPROFILE%/.docker/config.json` on Windows. <ide> <del>> **Note**: When running `sudo docker login` credentials are saved in `/root/.docker/config.json`. <del>> <del> <ide> ## Credentials store <ide> <ide> The Docker Engine can keep user credentials in an external credentials store, <ide><path>man/docker-login.1.md <ide> You can log into any public or private repository for which you have <ide> credentials. When you log in, the command stores encoded credentials in <ide> `$HOME/.docker/config.json` on Linux or `%USERPROFILE%/.docker/config.json` on Windows. <ide> <del>> **Note**: When running `sudo docker login` credentials are saved in `/root/.docker/config.json`. <del>> <del> <ide> # OPTIONS <ide> **--help** <ide> Print usage statement
2
Text
Text
update readme to link to master research models
9b401346a5c3b4da2e0b7f1ed5ad7deac48df68e
<ide><path>README.md <ide> This repository contains a number of different models implemented in [TensorFlow <ide> <ide> The [official models](official) are a collection of example models that use TensorFlow's high-level APIs. They are intended to be well-maintained, tested, and kept up to date with the latest stable TensorFlow API. They should also be reasonably optimized for fast performance while still being easy to read. We especially recommend newer TensorFlow users to start here. <ide> <del>The [research models](research) are a large collection of models implemented in TensorFlow by researchers. It is up to the individual researchers to maintain the models and/or provide support on issues and pull requests. <add>The [research models](https://github.com/tensorflow/models/tree/master/research) are a large collection of models implemented in TensorFlow by researchers. They are not officially supported or available in release branches; it is up to the individual researchers to maintain the models and/or provide support on issues and pull requests. <ide> <ide> The [samples folder](samples) contains code snippets and smaller models that demonstrate features of TensorFlow, including code presented in various blog posts. <ide>
1
Ruby
Ruby
fix escape_javascript for unicode character \u2028
f6ceb944eaea525362db38aa990cac3e6f76ac5a
<ide><path>actionpack/lib/action_view/helpers/javascript_helper.rb <ide> module JavaScriptHelper <ide> "\n" => '\n', <ide> "\r" => '\n', <ide> '"' => '\\"', <del> "'" => "\\'" } <add> "'" => "\\'", <add> "\342\200\250" => '&#x2028;' } <ide> <ide> # Escape carrier returns and single and double quotes for JavaScript segments. <ide> # Also available through the alias j(). This is particularly helpful in JavaScript responses, like: <ide> # <ide> # $('some_element').replaceWith('<%=j render 'some/element_template' %>'); <ide> def escape_javascript(javascript) <ide> if javascript <del> result = javascript.gsub(/(\\|<\/|\r\n|[\n\r"'])/) {|match| JS_ESCAPE_MAP[match] } <add> result = javascript.gsub(/(\\|<\/|\r\n|\342\200\250|[\n\r"'])/) {|match| JS_ESCAPE_MAP[match] } <ide> javascript.html_safe? ? result.html_safe : result <ide> else <ide> '' <ide><path>actionpack/test/template/javascript_helper_test.rb <ide> def test_escape_javascript <ide> assert_equal %(This \\"thing\\" is really\\n netos\\'), escape_javascript(%(This "thing" is really\n netos')) <ide> assert_equal %(backslash\\\\test), escape_javascript( %(backslash\\test) ) <ide> assert_equal %(dont <\\/close> tags), escape_javascript(%(dont </close> tags)) <add> assert_equal %(unicode &#x2028; newline), escape_javascript(%(unicode \342\200\250 newline)) <ide> assert_equal %(dont <\\/close> tags), j(%(dont </close> tags)) <ide> end <ide>
2
Ruby
Ruby
fix assert_redirected_to so it works with symbols
b0189f3f2ffd9de95ba2332cdcfaf48d28081e18
<ide><path>actionpack/lib/action_controller/assertions.rb <ide> def assert_redirected_to(options = {}, message=nil) <ide> assert_equal(eurl, url, msg) if eurl && url <ide> assert_equal(epath, path, msg) if epath && path <ide> else <del> @response_diff = options.diff(@response.redirected_to) if @response.redirected_to <del> msg = build_message(message, "response is not a redirection to all of the options supplied (redirection is <?>), difference: <?>", <add> @response_diff = options.diff(@response.redirected_to) if options.is_a?(Hash) && @response.redirected_to.is_a?(Hash) <add> msg = build_message(message, "response is not a redirection to all of the options supplied (redirection is <?>)#{', difference: <?>' if @response_diff}", <ide> @response.redirected_to || @response.redirect_url, @response_diff) <ide> <ide> assert_block(msg) do <ide><path>actionpack/test/controller/test_test.rb <ide> def set_flash <ide> flash["test"] = ">#{flash["test"]}<" <ide> render :text => 'ignore me' <ide> end <del> <add> <ide> def render_raw_post <ide> raise Test::Unit::AssertionFailedError, "#raw_post is blank" if request.raw_post.blank? <ide> render :text => request.raw_post <ide> def test_file_upload <ide> render :text => params[:file].size <ide> end <ide> <del> def rescue_action(e) <del> raise e <add> def redirect_to_symbol <add> redirect_to :generate_url, :id => 5 <ide> end <add> <add> private <add> <add> def rescue_action(e) <add> raise e <add> end <add> <add> def generate_url(opts) <add> url_for(opts.merge(:action => "test_uri")) <add> end <ide> end <ide> <ide> def setup <ide> def test_fixture_file_upload <ide> def test_test_uploaded_file_exception_when_file_doesnt_exist <ide> assert_raise(RuntimeError) { ActionController::TestUploadedFile.new('non_existent_file') } <ide> end <add> <add> def test_assert_redirected_to_symbol <add> get :redirect_to_symbol <add> assert_redirected_to :generate_url <add> end <ide> end
2
Python
Python
fix empty and_query
0906bf2c08e67eb43789ef976a784a4da01a08bc
<ide><path>rest_framework/filters.py <ide> def filter_queryset(self, request, queryset, view): <ide> for orm_lookup in orm_lookups] <ide> and_queries.append(reduce(operator.or_, or_queries)) <ide> <del> if settings.DATABASES[queryset.db]["ENGINE"] == "django.db.backends.oracle": <del> pk_list = queryset.filter(reduce(operator.and_, and_queries)).values_list('pk', flat=True) <del> return queryset.filter(pk__in=frozenset(pk_list)) <del> else: <del> return queryset.filter(reduce(operator.and_, and_queries)).distinct() <add> if and_queries: <add> if settings.DATABASES[queryset.db]["ENGINE"] == "django.db.backends.oracle": <add> pk_list = queryset.filter(reduce(operator.and_, and_queries)).values_list('pk', flat=True) <add> return queryset.filter(pk__in=frozenset(pk_list)) <add> else: <add> return queryset.filter(reduce(operator.and_, and_queries)).distinct() <add> return queryset <ide> <ide> <ide> class OrderingFilter(BaseFilterBackend):
1
PHP
PHP
add unverified state to userfactory
eaf7289523b0730b3d0c5a7146ab0f078019a987
<ide><path>database/factories/UserFactory.php <ide> public function definition() <ide> 'remember_token' => Str::random(10), <ide> ]; <ide> } <add> <add> /** <add> * Define the model's unverified state. <add> * <add> * @return \Illuminate\Database\Eloquent\Factories\Factory <add> */ <add> public function unverified() <add> { <add> return $this->state(function (array $attributes) { <add> return [ <add> 'email_verified_at' => null, <add> ]; <add> }); <add> } <ide> }
1
Python
Python
patch view.head() only for django < 1.4
fe262ef3537fa67ecda374825a295ff854f027a3
<ide><path>djangorestframework/compat.py <ide> def request(self, **request): <ide> environ.update(request) <ide> return WSGIRequest(environ) <ide> <del># django.views.generic.View (Django >= 1.3) <add># django.views.generic.View (1.3 <= Django < 1.4) <ide> try: <ide> from django.views.generic import View <del> from django.utils.decorators import classonlymethod <del> from django.utils.functional import update_wrapper <ide> <del> if not hasattr(View, 'head'): <add> if django.VERSION < (1, 4): <add> from django.utils.decorators import classonlymethod <add> from django.utils.functional import update_wrapper <add> <ide> # First implementation of Django class-based views did not include head method <ide> # in base View class - https://code.djangoproject.com/ticket/15668 <ide> class ViewPlusHead(View):
1
PHP
PHP
add debug flag to flush output
b3396538b71340a3ca091af01845a40cc54d148f
<ide><path>lib/Cake/TestSuite/CakeTestCase.php <ide> public function tearDown() { <ide> ClassRegistry::flush(); <ide> } <ide> Configure::write($this->_configure); <add> if (isset($_GET['debug']) && $_GET['debug']) { <add> ob_flush(); <add> } <ide> } <ide> <ide> /**
1
PHP
PHP
add comment to queue listen command
81bf19b1e413164349e98b8e09c0603abaa5af33
<ide><path>src/Illuminate/Queue/Console/ListenCommand.php <ide> public function fire() <ide> <ide> $timeout = $this->input->getOption('timeout'); <ide> <add> // We need to get the right queue for the connection which is set in the queue <add> // configuration file for the application. We will pull it based on the set <add> // connection being run for the queue operation currently being executed. <ide> $queue = $this->getQueue($connection); <ide> <ide> $this->listener->listen($connection, $queue, $delay, $memory, $timeout);
1
Text
Text
fix url bug in docs
c7a09096eebefe345186b4f7b76cfe66085ab9c6
<ide><path>docs/recipes/MigratingToRedux.md <ide> We don't want to lock you in! <ide> <ide> Your process will look like this: <ide> <del>- Create a function called `createFluxStore(reducer)` that creates a Flux store compatible with your existing app from a reducer function. Internally it might look similar to [`createStore`](../api/createStore.md) ([source](https://github.com/reduxjs/redux/blob/master/src/createStore.js)) implementation from Redux. Its dispatch handler should just call the `reducer` for any action, store the next state, and emit change. <add>- Create a function called `createFluxStore(reducer)` that creates a Flux store compatible with your existing app from a reducer function. Internally it might look similar to [`createStore`](../api/createStore.md) ([source](https://github.com/reduxjs/redux/blob/master/src/createStore.ts)) implementation from Redux. Its dispatch handler should just call the `reducer` for any action, store the next state, and emit change. <ide> <ide> - This allows you to gradually rewrite every Flux Store in your app as a reducer, but still export `createFluxStore(reducer)` so the rest of your app is not aware that this is happening and sees the Flux stores. <ide> <ide><path>docs/recipes/Troubleshooting.md <ide> It's possible you're correctly dispatching an action and applying your reducer b <ide> ## Something else doesn't work <ide> <ide> Ask around on the **#redux** [Reactiflux](http://reactiflux.com/) Discord channel, or [create an issue](https://github.com/reduxjs/redux/issues). <del>If you figure it out, [edit this document](https://github.com/reduxjs/redux/edit/master/docs/Troubleshooting.md) as a courtesy to the next person having the same problem. <add>If you figure it out, [edit this document](https://github.com/reduxjs/redux/edit/master/docs/recipes/Troubleshooting.md) as a courtesy to the next person having the same problem.
2
Javascript
Javascript
add prop types
46e8281e89915d03d9462187b6866a7185699ef5
<ide><path>examples/todo/Body.js <del>import React from 'react'; <add>import React, { PropTypes } from 'react'; <ide> <ide> export default class Body { <add> static propTypes = { <add> todos: PropTypes.array.isRequired <add> }; <add> <ide> render() { <ide> return ( <ide> <div> <ide><path>examples/todo/Header.js <del>import React from 'react'; <add>import React, { PropTypes } from 'react'; <ide> <ide> export default class Header { <add> static propTypes = { <add> addTodo: PropTypes.func.isRequired <add> }; <add> <ide> render() { <ide> return ( <ide> <div>
2
PHP
PHP
add dynamic component
f66c103a9457328f0984a010c27afdf889b3c562
<ide><path>src/Illuminate/View/DynamicComponent.php <add><?php <add> <add>namespace Illuminate\View; <add> <add>use Illuminate\Container\Container; <add>use Illuminate\Support\Str; <add>use Illuminate\View\Compilers\ComponentTagCompiler; <add> <add>class DynamicComponent extends Component <add>{ <add> /** <add> * The name of the component. <add> * <add> * @var string <add> */ <add> public $component; <add> <add> /** <add> * The component tag compiler instance. <add> * <add> * @var \Illuminate\View\Compilers\BladeTagCompiler <add> */ <add> protected static $compiler; <add> <add> /** <add> * The cached component classes. <add> * <add> * @var array <add> */ <add> protected static $componentClasses = []; <add> <add> /** <add> * The cached binding keys for component classes. <add> * <add> * @var array <add> */ <add> protected static $bindings = []; <add> <add> /** <add> * Create a new component instance. <add> * <add> * @return void <add> */ <add> public function __construct(string $component) <add> { <add> $this->component = $component; <add> } <add> <add> /** <add> * Get the view / contents that represent the component. <add> * <add> * @return \Illuminate\View\View|string <add> */ <add> public function render() <add> { <add> $template = <<<'EOF' <add><?php extract(collect($attributes->getAttributes())->mapWithKeys(function ($value, $key) { return [Illuminate\Support\Str::camel($key) => $value]; })->all(), EXTR_SKIP); ?> <add>{{ props }} <add><x-{{ component }} {{ bindings }} {{ attributes }}> <add>{{ slots }} <add>{{ defaultSlot }} <add></x-{{ component }}> <add>EOF; <add> <add> return function ($data) use ($template) { <add> $bindings = $this->bindings($class = $this->classForComponent()); <add> <add> return str_replace( <add> [ <add> '{{ component }}', <add> '{{ props }}', <add> '{{ bindings }}', <add> '{{ attributes }}', <add> '{{ slots }}', <add> '{{ defaultSlot }}', <add> ], <add> [ <add> $this->component, <add> $this->compileProps($bindings), <add> $this->compileBindings($bindings), <add> class_exists($class) ? '{{ $attributes }}' : '', <add> $this->compileSlots($data['__laravel_slots']), <add> '{{ $slot ?? "" }}', <add> ], <add> $template <add> ); <add> }; <add> } <add> <add> /** <add> * Compile the @props directive for the component. <add> * <add> * @param array $bindings <add> * @return string <add> */ <add> protected function compileProps(array $bindings) <add> { <add> if (empty($bindings)) { <add> return ''; <add> } <add> <add> return '@props('.'[\''.implode('\',\'', collect($bindings)->map(function ($dataKey) { <add> return Str::camel($dataKey); <add> })->all()).'\']'.')'; <add> } <add> <add> /** <add> * Compile the bindings for the component. <add> * <add> * @param array $bindings <add> * @return string <add> */ <add> protected function compileBindings(array $bindings) <add> { <add> return collect($bindings)->map(function ($key) { <add> return ':'.$key.'="$'.Str::camel($key).'"'; <add> })->implode(' '); <add> } <add> <add> /** <add> * Compile the slots for the component. <add> * <add> * @param array $slots <add> * @return string <add> */ <add> protected function compileSlots(array $slots) <add> { <add> return collect($slots)->map(function ($slot, $name) { <add> return $name === '__default' ? null : '<x-slot name="'.$name.'">{{ $'.$name.' }}</x-slot>'; <add> })->filter()->implode(PHP_EOL); <add> } <add> <add> /** <add> * Get the class for the current component. <add> * <add> * @return string <add> */ <add> protected function classForComponent() <add> { <add> if (isset(static::$componentClasses[$this->component])) { <add> return static::$componentClasses[$this->component]; <add> } <add> <add> return static::$componentClasses[$this->component] = <add> $this->compiler()->componentClass($this->component); <add> } <add> <add> /** <add> * Get the names of the variables that should be bound to the component. <add> * <add> * @param string $class <add> * @return array <add> */ <add> protected function bindings(string $class) <add> { <add> if (! isset(static::$bindings[$class])) { <add> [$data, $attributes] = $this->compiler()->partitionDataAndAttributes($class, $this->attributes->getAttributes()); <add> <add> static::$bindings[$class] = array_keys($data->all()); <add> } <add> <add> return static::$bindings[$class]; <add> } <add> <add> /** <add> * Get an instance of the Blade tag compiler. <add> * <add> * @return \Illuminate\View\Compilers\ComponentTagCompiler <add> */ <add> protected function compiler() <add> { <add> if (! static::$compiler) { <add> static::$compiler = new ComponentTagCompiler( <add> Container::getInstance()->make('blade.compiler')->getClassComponentAliases(), <add> Container::getInstance()->make('blade.compiler') <add> ); <add> } <add> <add> return static::$compiler; <add> } <add>} <ide><path>src/Illuminate/View/ViewServiceProvider.php <ide> public function registerViewFinder() <ide> public function registerBladeCompiler() <ide> { <ide> $this->app->singleton('blade.compiler', function ($app) { <del> return new BladeCompiler($app['files'], $app['config']['view.compiled']); <add> return tap(new BladeCompiler($app['files'], $app['config']['view.compiled']), function ($blade) { <add> $blade->component('dynamic-component', DynamicComponent::class); <add> }); <ide> }); <ide> } <ide> <ide><path>tests/Integration/View/BladeTest.php <add><?php <add> <add>namespace Illuminate\Tests\Integration\View; <add> <add>use Illuminate\Support\Facades\View; <add>use Orchestra\Testbench\TestCase; <add> <add>/** <add> * @group integration <add> */ <add>class BladeTest extends TestCase <add>{ <add> public function test_basic_blade_rendering() <add> { <add> $view = View::make('hello', ['name' => 'Taylor'])->render(); <add> <add> $this->assertEquals('Hello Taylor', trim($view)); <add> } <add> <add> public function test_rendering_a_component() <add> { <add> $view = View::make('uses-panel', ['name' => 'Taylor'])->render(); <add> <add> $this->assertEquals('<div class="ml-2"> <add> Hello Taylor <add></div>', trim($view)); <add> } <add> <add> public function test_rendering_a_dynamic_component() <add> { <add> $view = View::make('uses-panel-dynamically', ['name' => 'Taylor'])->render(); <add> <add> $this->assertEquals('<div class="ml-2"> <add> Hello Taylor <add></div>', trim($view)); <add> } <add> <add> protected function getEnvironmentSetUp($app) <add> { <add> $app['config']->set('view.paths', [__DIR__.'/templates']); <add> } <add>} <ide><path>tests/Integration/View/templates/components/panel.blade.php <add>@props(['name']) <add> <add><div {{ $attributes }}> <add> Hello {{ $name }} <add></div> <ide><path>tests/Integration/View/templates/hello.blade.php <add>Hello {{ $name }} <ide><path>tests/Integration/View/templates/uses-panel-dynamically.blade.php <add><x-dynamic-component component="panel" class="ml-2" :name="$name"> <add> Panel contents <add></x-dynamic-component> <ide><path>tests/Integration/View/templates/uses-panel.blade.php <add><x-panel class="ml-2" :name="$name"> <add> Panel contents <add></x-panel>
7
Text
Text
update 8.5.0 changelog
cba206fa24e6ab15cad23ee7d44fa444f110582e
<ide><path>doc/api/assert.md <ide> changes: <ide> - version: REPLACEME <ide> pr-url: https://github.com/nodejs/node/pull/15001 <ide> - version: v8.5.0 <del> pr-url: https://github.com/nodejs/node/pull/12142 <add> pr-url: https://github.com/nodejs/node/pull/15001 <ide> description: Error names and messages are now properly compared <ide> - version: v8.0.0 <ide> pr-url: https://github.com/nodejs/node/pull/12142 <ide><path>doc/changelogs/CHANGELOG_V8.md <ide> * **perf_hooks** <ide> * An initial implementation of the Performance Timing API for Node.js. This is the <ide> same Performance Timing API implemented by modern browsers with a number of Node.js <del> specific properties. The User Timing mark() and measure() APIs are implemented, <del> as is a Node.js specific flavor of the Frame Timing for measuring event loop duration. <add> specific properties. The User Timing mark() and measure() APIs are implemented. <ide> [#14680](https://github.com/nodejs/node/pull/14680) <ide> * **tls** <ide> * multiple PFX in createSecureContext
2
Java
Java
add support for @exceptionhandler methods
34eb6d54263cd0ae426f021f98092e6daacbcd70
<ide><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/ReactorServerHttpResponse.java <ide> <ide> import org.springframework.http.HttpHeaders; <ide> import org.springframework.http.HttpStatus; <del>import org.springframework.http.server.reactive.ServerHttpResponse; <ide> import org.springframework.util.Assert; <ide> <ide> /** <ide> public Publisher<Void> writeHeaders() { <ide> } <ide> <ide> @Override <del> public Publisher<Void> setBody(Publisher<ByteBuffer> contentPublisher) { <del> applyHeaders(); <del> return this.channel.writeWith(Publishers.map(contentPublisher, Buffer::new)); <add> public Publisher<Void> setBody(Publisher<ByteBuffer> publisher) { <add> return Publishers.lift(publisher, new WriteWithOperator<>(writePublisher -> { <add> applyHeaders(); <add> return this.channel.writeWith(Publishers.map(writePublisher, Buffer::new)); <add> })); <ide> } <ide> <ide> private void applyHeaders() { <ide><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/RxNettyServerHttpRequest.java <ide> <ide> import org.springframework.http.HttpHeaders; <ide> import org.springframework.http.HttpMethod; <del>import org.springframework.http.server.reactive.ServerHttpRequest; <ide> import org.springframework.util.Assert; <ide> <ide> /** <ide><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/RxNettyServerHttpResponse.java <ide> <ide> import org.springframework.http.HttpHeaders; <ide> import org.springframework.http.HttpStatus; <del>import org.springframework.http.server.reactive.ServerHttpResponse; <ide> import org.springframework.util.Assert; <ide> <ide> /** <ide> public Publisher<Void> writeHeaders() { <ide> <ide> @Override <ide> public Publisher<Void> setBody(Publisher<ByteBuffer> publisher) { <del> applyHeaders(); <del> Observable<byte[]> observable = RxJava1Converter.from(publisher).map( <del> content -> new Buffer(content).asBytes()); <del> return RxJava1Converter.from(this.response.writeBytes(observable)); <add> return Publishers.lift(publisher, new WriteWithOperator<>(writePublisher -> { <add> applyHeaders(); <add> Observable<byte[]> observable = RxJava1Converter.from(writePublisher) <add> .map(buffer -> new Buffer(buffer).asBytes()); <add> return RxJava1Converter.from(this.response.writeBytes(observable)); <add> })); <ide> } <ide> <ide> private void applyHeaders() { <ide><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/ServletServerHttpResponse.java <ide> public Publisher<Void> writeHeaders() { <ide> } <ide> <ide> @Override <del> public Publisher<Void> setBody(final Publisher<ByteBuffer> contentPublisher) { <del> applyHeaders(); <del> return (s -> contentPublisher.subscribe(subscriber)); <add> public Publisher<Void> setBody(final Publisher<ByteBuffer> publisher) { <add> return Publishers.lift(publisher, new WriteWithOperator<>(writePublisher -> { <add> applyHeaders(); <add> return (s -> writePublisher.subscribe(subscriber)); <add> })); <ide> } <ide> <ide> private void applyHeaders() { <ide><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/UndertowServerHttpResponse.java <ide> import org.reactivestreams.Subscription; <ide> import org.xnio.ChannelListener; <ide> import org.xnio.channels.StreamSinkChannel; <add>import reactor.Publishers; <ide> import reactor.core.subscriber.BaseSubscriber; <ide> <ide> import static org.xnio.ChannelListeners.closingChannelExceptionHandler; <ide> public void setStatusCode(HttpStatus status) { <ide> this.exchange.setStatusCode(status.value()); <ide> } <ide> <del> <del> @Override <del> public Publisher<Void> setBody(Publisher<ByteBuffer> bodyPublisher) { <del> applyHeaders(); <del> return (subscriber -> bodyPublisher.subscribe(bodySubscriber)); <del> } <del> <ide> @Override <ide> public HttpHeaders getHeaders() { <ide> return (this.headersWritten ? HttpHeaders.readOnlyHttpHeaders(this.headers) : this.headers); <ide> private void applyHeaders() { <ide> } <ide> } <ide> <add> @Override <add> public Publisher<Void> setBody(Publisher<ByteBuffer> publisher) { <add> return Publishers.lift(publisher, new WriteWithOperator<>(writePublisher -> { <add> applyHeaders(); <add> return (subscriber -> writePublisher.subscribe(bodySubscriber)); <add> })); <add> } <add> <ide> <ide> private class ResponseBodySubscriber extends BaseSubscriber<ByteBuffer> <ide> implements ChannelListener<StreamSinkChannel> { <ide><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/WriteWithOperator.java <ide> public void doNext(T item) { <ide> else if (this.beforeFirstEmission) { <ide> this.item = item; <ide> this.beforeFirstEmission = false; <del> writeFunction.apply(this).subscribe(downstream()); <add> writeFunction.apply(this).subscribe(new DownstreamBridge(downstream())); <ide> } <ide> else { <ide> subscription.cancel(); <ide> public void doComplete() { <ide> else if (this.beforeFirstEmission) { <ide> this.completed = true; <ide> this.beforeFirstEmission = false; <del> writeFunction.apply(this).subscribe(downstream()); <add> writeFunction.apply(this).subscribe(new DownstreamBridge(downstream())); <ide> } <ide> else { <ide> this.completed = true; <ide> else if (this.beforeFirstEmission) { <ide> } <ide> <ide> @Override <del> public void subscribe(Subscriber<? super T> subscriber) { <add> public void subscribe(Subscriber<? super T> writeSubscriber) { <ide> synchronized (this) { <ide> Assert.isNull(this.writeSubscriber, "Only one writeSubscriber supported."); <del> this.writeSubscriber = subscriber; <add> this.writeSubscriber = writeSubscriber; <ide> <ide> if (this.error != null || this.completed) { <ide> this.writeSubscriber.onSubscribe(NO_OP_SUBSCRIPTION); <ide> private boolean emitCachedSignals() { <ide> <ide> @Override <ide> protected void doRequest(long n) { <del> if (this.readyToWrite) { <add> if (readyToWrite) { <ide> super.doRequest(n); <ide> return; <ide> } <ide> protected void doRequest(long n) { <ide> } <ide> } <ide> <add> private class DownstreamBridge implements Subscriber<Void> { <add> <add> private final Subscriber<? super Void> downstream; <add> <add> public DownstreamBridge(Subscriber<? super Void> downstream) { <add> this.downstream = downstream; <add> } <add> <add> @Override <add> public void onSubscribe(Subscription subscription) { <add> subscription.request(Long.MAX_VALUE); <add> } <add> <add> @Override <add> public void onNext(Void aVoid) { <add> } <add> <add> @Override <add> public void onError(Throwable ex) { <add> this.downstream.onError(ex); <add> } <add> <add> @Override <add> public void onComplete() { <add> this.downstream.onComplete(); <add> } <add> } <add> <ide> private final static Subscription NO_OP_SUBSCRIPTION = new Subscription() { <ide> <ide> @Override <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/DispatcherHandler.java <ide> public Publisher<Void> handle(ServerHttpRequest request, ServerHttpResponse resp <ide> }); <ide> <ide> Publisher<Void> completionPublisher = Publishers.concatMap(resultPublisher, result -> { <del> HandlerResultHandler handler = getResultHandler(result); <del> return handler.handleResult(request, response, result); <add> Publisher<Void> publisher; <add> if (result.hasError()) { <add> publisher = Publishers.error(result.getError()); <add> } <add> else { <add> HandlerResultHandler handler = getResultHandler(result); <add> publisher = handler.handleResult(request, response, result); <add> } <add> if (result.hasExceptionMapper()) { <add> return Publishers.onErrorResumeNext(publisher, ex -> { <add> return Publishers.concatMap(result.getExceptionMapper().apply(ex), <add> errorResult -> { <add> HandlerResultHandler handler = getResultHandler(errorResult); <add> return handler.handleResult(request, response, errorResult); <add> }); <add> }); <add> } <add> return publisher; <ide> }); <ide> <ide> return mapError(completionPublisher, this.errorMapper); <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/HandlerResult.java <ide> <ide> package org.springframework.web.reactive; <ide> <add>import java.util.function.Function; <add>import java.util.logging.Handler; <add> <add>import org.reactivestreams.Publisher; <add>import reactor.Publishers; <add> <ide> import org.springframework.core.ResolvableType; <ide> import org.springframework.util.Assert; <ide> <ide> /** <del> * Represent the result of the invocation of an handler. <add> * Represent the result of the invocation of a handler. <ide> * <ide> * @author Rossen Stoyanchev <ide> */ <ide> public class HandlerResult { <ide> <ide> private final ResolvableType resultType; <ide> <add> private final Throwable error; <add> <add> private Function<Throwable, Publisher<HandlerResult>> exceptionMapper; <add> <ide> <ide> public HandlerResult(Object handler, Object result, ResolvableType resultType) { <ide> Assert.notNull(handler, "'handler' is required"); <ide> Assert.notNull(handler, "'resultType' is required"); <ide> this.handler = handler; <ide> this.result = result; <ide> this.resultType = resultType; <add> this.error = null; <add> } <add> <add> public HandlerResult(Object handler, Throwable error) { <add> Assert.notNull(handler, "'handler' is required"); <add> Assert.notNull(error, "'error' is required"); <add> this.handler = handler; <add> this.result = null; <add> this.resultType = null; <add> this.error = error; <ide> } <ide> <ide> <ide> public ResolvableType getResultType() { <ide> return this.resultType; <ide> } <ide> <add> public Throwable getError() { <add> return this.error; <add> } <add> <add> /** <add> * Whether handler invocation produced a result or failed with an error. <add> * <p>If {@code true} the {@link #getError()} returns the error while <add> * {@link #getResult()} and {@link #getResultType()} return {@code null} <add> * and vice versa. <add> * @return whether this instance contains a result or an error. <add> */ <add> public boolean hasError() { <add> return (this.error != null); <add> } <add> <add> /** <add> * Configure a function for selecting an alternate {@code HandlerResult} in <add> * case of an {@link #hasError() error result} or in case of an async result <add> * that results in an error. <add> * @param function the exception resolving function <add> */ <add> public HandlerResult setExceptionMapper(Function<Throwable, Publisher<HandlerResult>> function) { <add> this.exceptionMapper = function; <add> return this; <add> } <add> <add> public Function<Throwable, Publisher<HandlerResult>> getExceptionMapper() { <add> return this.exceptionMapper; <add> } <add> <add> public boolean hasExceptionMapper() { <add> return (this.exceptionMapper != null); <add> } <add> <ide> } <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/method/InvocableHandlerMethod.java <ide> public InvocableHandlerMethod(HandlerMethod handlerMethod) { <ide> super(handlerMethod); <ide> } <ide> <add> public InvocableHandlerMethod(Object bean, Method method) { <add> super(bean, method); <add> } <add> <ide> <ide> public void setHandlerMethodArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) { <ide> this.resolvers.clear(); <ide> protected Method getBridgedMethod() { <ide> <ide> <ide> /** <del> * <del> * @param request <del> * @param providedArgs <add> * Invoke the method and return a Publisher for the return value. <add> * @param request the current request <add> * @param providedArgs optional list of argument values to check by type <add> * (via {@code instanceof}) for resolving method arguments. <ide> * @return Publisher that produces a single HandlerResult or an error signal; <ide> * never throws an exception. <ide> */ <ide> public Publisher<HandlerResult> invokeForRequest(ServerHttpRequest request, Obje <ide> return Publishers.concatMap(argsPublisher, args -> { <ide> try { <ide> Object value = doInvoke(args); <del> <del> HandlerMethod handlerMethod = InvocableHandlerMethod.this; <del> ResolvableType type = ResolvableType.forMethodParameter(handlerMethod.getReturnType()); <del> HandlerResult handlerResult = new HandlerResult(handlerMethod, value, type); <del> <add> ResolvableType type = ResolvableType.forMethodParameter(getReturnType()); <add> HandlerResult handlerResult = new HandlerResult(this, value, type); <ide> return Publishers.just(handlerResult); <ide> } <ide> catch (InvocationTargetException ex) { <ide> private static <E> Publisher<E> first(Publisher<E> source) { <ide> } <ide> <ide> private static <E> Publisher<E> mapError(Publisher<E> source, Function<Throwable, Throwable> function) { <del> return Publishers.lift(source, null, (throwable, subscriber) -> { <del> subscriber.onError(function.apply(throwable)); <del> }, null); <add> return Publishers.lift(source, null, <add> (throwable, subscriber) -> subscriber.onError(function.apply(throwable)), null); <ide> } <ide> <ide> } <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/method/annotation/RequestMappingHandlerAdapter.java <ide> <ide> package org.springframework.web.reactive.method.annotation; <ide> <add>import java.lang.reflect.Method; <ide> import java.util.ArrayList; <ide> import java.util.Arrays; <ide> import java.util.List; <add>import java.util.Map; <add>import java.util.concurrent.ConcurrentHashMap; <ide> <add>import org.apache.commons.logging.Log; <add>import org.apache.commons.logging.LogFactory; <ide> import org.reactivestreams.Publisher; <ide> import reactor.Publishers; <ide> <ide> import org.springframework.beans.factory.InitializingBean; <del>import org.springframework.core.ResolvableType; <del>import org.springframework.core.convert.ConversionService; <del>import org.springframework.core.convert.support.DefaultConversionService; <del>import org.springframework.http.server.reactive.ServerHttpRequest; <del>import org.springframework.http.server.reactive.ServerHttpResponse; <del>import org.springframework.core.codec.support.ByteBufferDecoder; <ide> import org.springframework.core.codec.Decoder; <add>import org.springframework.core.codec.support.ByteBufferDecoder; <ide> import org.springframework.core.codec.support.JacksonJsonDecoder; <ide> import org.springframework.core.codec.support.JsonObjectDecoder; <ide> import org.springframework.core.codec.support.StringDecoder; <add>import org.springframework.core.convert.ConversionService; <add>import org.springframework.core.convert.support.DefaultConversionService; <add>import org.springframework.http.server.reactive.ServerHttpRequest; <add>import org.springframework.http.server.reactive.ServerHttpResponse; <ide> import org.springframework.util.ObjectUtils; <add>import org.springframework.web.method.HandlerMethod; <add>import org.springframework.web.method.annotation.ExceptionHandlerMethodResolver; <ide> import org.springframework.web.reactive.HandlerAdapter; <ide> import org.springframework.web.reactive.HandlerResult; <ide> import org.springframework.web.reactive.method.HandlerMethodArgumentResolver; <ide> import org.springframework.web.reactive.method.InvocableHandlerMethod; <del>import org.springframework.web.method.HandlerMethod; <ide> <ide> <ide> /** <ide> * @author Rossen Stoyanchev <ide> */ <ide> public class RequestMappingHandlerAdapter implements HandlerAdapter, InitializingBean { <ide> <add> private static Log logger = LogFactory.getLog(RequestMappingHandlerAdapter.class); <add> <add> <ide> private final List<HandlerMethodArgumentResolver> argumentResolvers = new ArrayList<>(); <ide> <ide> private ConversionService conversionService = new DefaultConversionService(); <ide> <add> private final Map<Class<?>, ExceptionHandlerMethodResolver> exceptionHandlerCache = <add> new ConcurrentHashMap<Class<?>, ExceptionHandlerMethodResolver>(64); <ide> <add> <add> /** <add> * Configure the complete list of supported argument types thus overriding <add> * the resolvers that would otherwise be configured by default. <add> */ <ide> public void setArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) { <ide> this.argumentResolvers.clear(); <ide> this.argumentResolvers.addAll(resolvers); <ide> } <ide> <add> /** <add> * Return the configured argument resolvers. <add> */ <ide> public List<HandlerMethodArgumentResolver> getArgumentResolvers() { <ide> return this.argumentResolvers; <ide> } <ide> public boolean supports(Object handler) { <ide> public Publisher<HandlerResult> handle(ServerHttpRequest request, <ide> ServerHttpResponse response, Object handler) { <ide> <del> InvocableHandlerMethod handlerMethod = new InvocableHandlerMethod((HandlerMethod) handler); <del> handlerMethod.setHandlerMethodArgumentResolvers(this.argumentResolvers); <del> return handlerMethod.invokeForRequest(request); <add> HandlerMethod handlerMethod = (HandlerMethod) handler; <add> <add> InvocableHandlerMethod invocable = new InvocableHandlerMethod(handlerMethod); <add> invocable.setHandlerMethodArgumentResolvers(this.argumentResolvers); <add> <add> Publisher<HandlerResult> publisher = invocable.invokeForRequest(request); <add> <add> publisher = Publishers.onErrorResumeNext(publisher, ex -> { <add> return Publishers.just(new HandlerResult(handler, ex)); <add> }); <add> <add> publisher = Publishers.map(publisher, <add> result -> result.setExceptionMapper( <add> ex -> mapException((Exception) ex, handlerMethod, request, response))); <add> <add> return publisher; <add> } <add> <add> private Publisher<HandlerResult> mapException(Throwable ex, HandlerMethod handlerMethod, <add> ServerHttpRequest request, ServerHttpResponse response) { <add> <add> if (ex instanceof Exception) { <add> InvocableHandlerMethod invocable = findExceptionHandler(handlerMethod, (Exception) ex); <add> if (invocable != null) { <add> try { <add> if (logger.isDebugEnabled()) { <add> logger.debug("Invoking @ExceptionHandler method: " + invocable); <add> } <add> invocable.setHandlerMethodArgumentResolvers(getArgumentResolvers()); <add> return invocable.invokeForRequest(request, response, ex); <add> } <add> catch (Exception invocationEx) { <add> if (logger.isErrorEnabled()) { <add> logger.error("Failed to invoke @ExceptionHandler method: " + invocable, invocationEx); <add> } <add> } <add> } <add> } <add> return Publishers.error(ex); <add> } <add> <add> protected InvocableHandlerMethod findExceptionHandler(HandlerMethod handlerMethod, Exception exception) { <add> if (handlerMethod == null) { <add> return null; <add> } <add> Class<?> handlerType = handlerMethod.getBeanType(); <add> ExceptionHandlerMethodResolver resolver = this.exceptionHandlerCache.get(handlerType); <add> if (resolver == null) { <add> resolver = new ExceptionHandlerMethodResolver(handlerType); <add> this.exceptionHandlerCache.put(handlerType, resolver); <add> } <add> Method method = resolver.resolveMethod(exception); <add> return (method != null ? new InvocableHandlerMethod(handlerMethod.getBean(), method) : null); <ide> } <ide> <ide> } <ide>\ No newline at end of file <ide><path>spring-web-reactive/src/test/java/org/springframework/http/server/reactive/AbstractHttpHandlerIntegrationTests.java <ide> import org.junit.runner.RunWith; <ide> import org.junit.runners.Parameterized; <ide> <del>import org.springframework.http.server.reactive.HttpHandler; <ide> import org.springframework.http.server.reactive.boot.HttpServer; <ide> import org.springframework.http.server.reactive.boot.JettyHttpServer; <ide> import org.springframework.http.server.reactive.boot.ReactorHttpServer; <ide><path>spring-web-reactive/src/test/java/org/springframework/http/server/reactive/WriteWithOperatorTests.java <ide> import reactor.core.publisher.PublisherFactory; <ide> import reactor.core.subscriber.SubscriberBarrier; <ide> import reactor.rx.Streams; <del>import reactor.rx.action.Signal; <add>import reactor.rx.stream.Signal; <ide> <ide> import static org.junit.Assert.assertEquals; <ide> import static org.junit.Assert.assertFalse; <ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/method/annotation/RequestMappingIntegrationTests.java <ide> import org.springframework.http.server.reactive.AbstractHttpHandlerIntegrationTests; <ide> import org.springframework.http.server.reactive.HttpHandler; <ide> import org.springframework.stereotype.Controller; <add>import org.springframework.web.bind.annotation.ExceptionHandler; <ide> import org.springframework.web.bind.annotation.RequestBody; <ide> import org.springframework.web.bind.annotation.RequestMapping; <ide> import org.springframework.web.bind.annotation.RequestParam; <ide> public void rawHelloResponse() throws Exception { <ide> assertEquals("Hello!", response.getBody()); <ide> } <ide> <add> @Test <add> public void handleWithThrownException() throws Exception { <add> <add> RestTemplate restTemplate = new RestTemplate(); <add> <add> URI url = new URI("http://localhost:" + port + "/thrown-exception"); <add> RequestEntity<Void> request = RequestEntity.get(url).build(); <add> ResponseEntity<String> response = restTemplate.exchange(request, String.class); <add> <add> assertEquals("Recovered from error: Boo", response.getBody()); <add> } <add> <add> @Test <add> public void handleWithErrorSignal() throws Exception { <add> <add> RestTemplate restTemplate = new RestTemplate(); <add> <add> URI url = new URI("http://localhost:" + port + "/error-signal"); <add> RequestEntity<Void> request = RequestEntity.get(url).build(); <add> ResponseEntity<String> response = restTemplate.exchange(request, String.class); <add> <add> assertEquals("Recovered from error: Boo", response.getBody()); <add> } <add> <ide> @Test <ide> public void serializeAsPojo() throws Exception { <ide> serializeAsPojo("http://localhost:" + port + "/person"); <ide> public Observable<Void> observableCreate(@RequestBody Observable<Person> personS <ide> return personStream.toList().doOnNext(persons::addAll).flatMap(document -> Observable.empty()); <ide> } <ide> <add> @RequestMapping("/thrown-exception") <add> @ResponseBody <add> public Publisher<String> handleAndThrowException() { <add> throw new IllegalStateException("Boo"); <add> } <add> <add> @RequestMapping("/error-signal") <add> @ResponseBody <add> public Publisher<String> handleWithError() { <add> return Publishers.error(new IllegalStateException("Boo")); <add> } <add> <add> @ExceptionHandler <add> @ResponseBody <add> public Publisher<String> handleException(IllegalStateException ex) { <add> return Streams.just("Recovered from error: " + ex.getMessage()); <add> } <add> <ide> //TODO add mixed and T request mappings tests <ide> <ide> }
13
Javascript
Javascript
clarify the use of object map
8eb8c4a32fa6f61a84ee476ac0755d9263f84050
<ide><path>src/ng/directive/ngClass.js <ide> function classDirective(name, selector) { <ide> * @element ANY <ide> * @param {expression} ngClass {@link guide/expression Expression} to eval. The result <ide> * of the evaluation can be a string representing space delimited class <del> * names, an array, or a map of class names to boolean values. <add> * names, an array, or a map of class names to boolean values. In the case of a map, the <add> * names of the properties whose values are truthy will be added as css classes to the <add> * element. <ide> * <ide> * @example <ide> <example>
1
Javascript
Javascript
fix potential null reference
1cefeae8a1939f71f24c80e6e3017a9f1eda1a27
<ide><path>src/loaders/ObjectLoader.js <ide> THREE.ObjectLoader.prototype = { <ide> <ide> } <ide> <del> if( data.animations ) { <add> if( data.animations && data.animations.tracks ) { <ide> <ide> var dataTracks = data.animations.tracks; <ide>
1
PHP
PHP
prefer old input data over form field values
8be20fde8c25545677367908d25da4e222da2d17
<ide><path>src/Illuminate/Html/FormBuilder.php <ide> protected function getIdAttribute($name, $attributes) <ide> /** <ide> * Get the value that should be assigned to the field. <ide> * <add> * This returns either old input for this field, the <add> * value passed to this method or the equally-named attribute of the <add> * current model instance (in this order of precedence). <add> * <ide> * @param string $name <ide> * @param string $value <ide> * @return string <ide> */ <ide> protected function getValueAttribute($name, $value) <ide> { <del> if ( ! is_null($value)) return $value; <del> <ide> if (isset($this->session) and $this->session->hasOldInput($name)) <ide> { <ide> return $this->session->getOldInput($name); <ide> } <ide> <add> if ( ! is_null($value)) return $value; <add> <ide> if (isset($this->model) and isset($this->model[$name])) <ide> { <ide> return $this->model[$name];
1
Python
Python
pass oauth_timestamp to oauth_provider
5239362951956f130a1ef91d12d6b7d680220104
<ide><path>rest_framework/authentication.py <ide> def check_nonce(self, request, oauth_request): <ide> """ <ide> Checks nonce of request, and return True if valid. <ide> """ <del> return oauth_provider_store.check_nonce(request, oauth_request, oauth_request['oauth_nonce']) <add> return oauth_provider_store.check_nonce(request, oauth_request, <add> oauth_request['oauth_nonce'], oauth_request['oauth_timestamp']) <ide> <ide> <ide> class OAuth2Authentication(BaseAuthentication):
1
Text
Text
remove old docs sections
81cc1c5852ff814d5d2fa675b6480469fef3ca3d
<ide><path>docs/api-reference/next.config.js/custom-webpack-config.md <ide> Before continuing to add custom webpack configuration to your application make s <ide> <ide> Some commonly asked for features are available as plugins: <ide> <del>- [@zeit/next-less](https://github.com/vercel/next-plugins/tree/master/packages/next-less) <ide> - [@next/mdx](https://github.com/vercel/next.js/tree/canary/packages/next-mdx) <ide> - [@next/bundle-analyzer](https://github.com/vercel/next.js/tree/canary/packages/next-bundle-analyzer) <ide> <ide><path>docs/basic-features/built-in-css-support.md <ide> module.exports = { <ide> } <ide> ``` <ide> <del>## Less and Stylus Support <del> <del>To support importing `.less` or `.styl` files you can use the following plugins: <del> <del>- [@zeit/next-less](https://github.com/vercel/next-plugins/tree/master/packages/next-less) <del>- [@zeit/next-stylus](https://github.com/vercel/next-plugins/tree/master/packages/next-stylus) <del> <del>If using the less plugin, don't forget to add a dependency on less as well, otherwise you'll see an error like: <del> <del>```bash <del>Error: Cannot find module 'less' <del>``` <del> <ide> ## CSS-in-JS <ide> <ide> <details>
2
Text
Text
fix url leak in application templates guide
80dbcf629c2d6a28109edafb15c144c3f83e8be8
<ide><path>guides/source/rails_application_templates.md <ide> end <ide> <ide> Adds the given source to the generated application's `Gemfile`. <ide> <del>For example, if you need to source a gem from "http://code.whytheluckystiff.net": <add>For example, if you need to source a gem from "[http://code.whytheluckystiff.net](http://code.whytheluckystiff.net)": <ide> <ide> ```ruby <ide> add_source "http://code.whytheluckystiff.net"
1
Javascript
Javascript
improve sortableset performance
645f98ae2d91ea2cfbf9d8e7a1df7ac43f19df99
<ide><path>lib/util/SortableSet.js <ide> class SortableSet extends Set { <ide> } <ide> <ide> sortWith(/** @type {(a: any, b: any) => number} */ sortFn) { <del> if (this.size === 0 || sortFn === this._lastActiveSortFn) { <add> if (this.size <= 1 || sortFn === this._lastActiveSortFn) { <ide> // already sorted - nothing to do <ide> return; <ide> }
1
Text
Text
update a link
a6ff7bd66101f63bf641a1f4b0a59a070aa4d172
<ide><path>docs/basic-features/data-fetching.md <ide> This approach works well for user dashboard pages, for example. Because a dashbo <ide> <ide> ### SWR <ide> <del>The team behind Next.js has created a React hook for data fetching called [**SWR**](https://swr.now.sh/). We highly recommend it if you’re fetching data on the client side. It handles caching, revalidation, focus tracking, refetching on interval, and more. And you can use it like so: <add>The team behind Next.js has created a React hook for data fetching called [**SWR**](https://swr.vercel.app/). We highly recommend it if you’re fetching data on the client side. It handles caching, revalidation, focus tracking, refetching on interval, and more. And you can use it like so: <ide> <ide> ```jsx <ide> import useSWR from 'swr'
1
Python
Python
use arg overwrite_cache
d9ece8233d584cdc2eeae5165dd3329328fae328
<ide><path>examples/language-modeling/run_language_modeling.py <ide> def get_dataset(args: DataTrainingArguments, tokenizer: PreTrainedTokenizer, eva <ide> if args.line_by_line: <ide> return LineByLineTextDataset(tokenizer=tokenizer, file_path=file_path, block_size=args.block_size) <ide> else: <del> return TextDataset(tokenizer=tokenizer, file_path=file_path, block_size=args.block_size) <add> return TextDataset( <add> tokenizer=tokenizer, file_path=file_path, block_size=args.block_size, overwrite_cache=args.overwrite_cache <add> ) <ide> <ide> <ide> def main(): <ide> def main(): <ide> data_args.block_size = min(data_args.block_size, tokenizer.max_len) <ide> <ide> # Get datasets <add> <ide> train_dataset = get_dataset(data_args, tokenizer=tokenizer) if training_args.do_train else None <ide> eval_dataset = get_dataset(data_args, tokenizer=tokenizer, evaluate=True) if training_args.do_eval else None <ide> data_collator = DataCollatorForLanguageModeling(
1
Go
Go
normalize comment formatting
580d3677c80398fb0fffb12a6a7db784ec1a135d
<ide><path>integration-cli/docker_api_build_test.go <ide> func (s *DockerSuite) TestBuildAPIUnnormalizedTarPaths(c *testing.T) { <ide> Name: "Dockerfile", <ide> Size: int64(len(dockerfile)), <ide> }) <del> //failed to write tar file header <del> assert.NilError(c, err) <add> assert.NilError(c, err, "failed to write tar file header") <ide> <ide> _, err = tw.Write(dockerfile) <del> // failed to write Dockerfile in tar file content <del> assert.NilError(c, err) <add> assert.NilError(c, err, "failed to write Dockerfile in tar file content") <ide> <ide> err = tw.WriteHeader(&tar.Header{ <ide> Name: "dir/./file", <ide> Size: int64(len(fileContents)), <ide> }) <del> //failed to write tar file header <del> assert.NilError(c, err) <add> assert.NilError(c, err, "failed to write tar file header") <ide> <ide> _, err = tw.Write(fileContents) <del> // failed to write file contents in tar file content <del> assert.NilError(c, err) <add> assert.NilError(c, err, "failed to write file contents in tar file content") <ide> <del> // failed to close tar archive <del> assert.NilError(c, tw.Close()) <add> assert.NilError(c, tw.Close(), "failed to close tar archive") <ide> <ide> res, body, err := request.Post("/build", request.RawContent(ioutil.NopCloser(buffer)), request.ContentType("application/x-tar")) <ide> assert.NilError(c, err) <ide><path>integration-cli/docker_api_containers_test.go <ide> func (s *DockerSuite) TestContainerAPIVerifyHeader(c *testing.T) { <ide> body.Close() <ide> } <ide> <del>//Issue 14230. daemon should return 500 for invalid port syntax <add>// Issue 14230. daemon should return 500 for invalid port syntax <ide> func (s *DockerSuite) TestContainerAPIInvalidPortSyntax(c *testing.T) { <ide> config := `{ <ide> "Image": "busybox", <ide><path>integration-cli/docker_api_images_test.go <ide> func (s *DockerSuite) TestAPIImagesFilter(c *testing.T) { <ide> return images <ide> } <ide> <del> //incorrect number of matches returned <add> // incorrect number of matches returned <ide> images := getImages("utest*/*") <ide> assert.Equal(c, len(images[0].RepoTags), 2) <ide> <ide><path>integration-cli/docker_api_swarm_service_test.go <ide> func (s *DockerSwarmSuite) TestAPISwarmServiceConstraintRole(c *testing.T) { <ide> node := daemons[0].GetNode(c, task.NodeID) <ide> assert.Equal(c, node.Spec.Role, swarm.NodeRoleWorker) <ide> } <del> //remove service <add> // remove service <ide> daemons[0].RemoveService(c, id) <ide> <ide> // create service <ide> func (s *DockerSwarmSuite) TestAPISwarmServiceConstraintRole(c *testing.T) { <ide> node := daemons[0].GetNode(c, task.NodeID) <ide> assert.Equal(c, node.Spec.Role, swarm.NodeRoleManager) <ide> } <del> //remove service <add> // remove service <ide> daemons[0].RemoveService(c, id) <ide> <ide> // create service <ide> func (s *DockerSwarmSuite) TestAPISwarmServiceConstraintLabel(c *testing.T) { <ide> for _, task := range tasks { <ide> assert.Assert(c, task.NodeID == nodes[0].ID) <ide> } <del> //remove service <add> // remove service <ide> daemons[0].RemoveService(c, id) <ide> <ide> // create service <ide> func (s *DockerSwarmSuite) TestAPISwarmServiceConstraintLabel(c *testing.T) { <ide> for _, task := range tasks { <ide> assert.Assert(c, task.NodeID != nodes[0].ID) <ide> } <del> //remove service <add> // remove service <ide> daemons[0].RemoveService(c, id) <ide> <ide> constraints = []string{"node.labels.security==medium"} <ide> func (s *DockerSwarmSuite) TestAPISwarmServiceConstraintLabel(c *testing.T) { <ide> for _, task := range tasks { <ide> assert.Assert(c, task.NodeID == "") <ide> } <del> //remove service <add> // remove service <ide> daemons[0].RemoveService(c, id) <ide> <ide> // multiple constraints <ide><path>integration-cli/docker_cli_by_digest_test.go <ide> func (s *DockerRegistrySuite) TestRemoveImageByDigest(c *testing.T) { <ide> <ide> // try to inspect again - it should error this time <ide> _, err = inspectFieldWithError(imageReference, "Id") <del> //unexpected nil err trying to inspect what should be a non-existent image <add> // unexpected nil err trying to inspect what should be a non-existent image <ide> assert.ErrorContains(c, err, "No such object") <ide> } <ide> <ide> func (s *DockerRegistrySuite) TestListImagesWithDigests(c *testing.T) { <ide> assert.Assert(c, re1.MatchString(out), "expected %q: %s", re1.String(), out) <ide> // setup image2 <ide> digest2, err := setupImageWithTag(c, "tag2") <del> //error setting up image <del> assert.NilError(c, err) <add> assert.NilError(c, err, "error setting up image") <ide> imageReference2 := fmt.Sprintf("%s@%s", repoName, digest2) <ide> c.Logf("imageReference2 = %s", imageReference2) <ide> <ide><path>integration-cli/docker_cli_commit_test.go <ide> func (s *DockerSuite) TestCommitWithoutPause(c *testing.T) { <ide> dockerCmd(c, "inspect", cleanedImageID) <ide> } <ide> <del>//test commit a paused container should not unpause it after commit <add>// TestCommitPausedContainer tests that a paused container is not unpaused after being committed <ide> func (s *DockerSuite) TestCommitPausedContainer(c *testing.T) { <ide> testRequires(c, DaemonIsLinux) <ide> out, _ := dockerCmd(c, "run", "-i", "-d", "busybox") <ide><path>integration-cli/docker_cli_daemon_test.go <ide> func (s *DockerDaemonSuite) TestDaemonRestartWithInvalidBasesize(c *testing.T) { <ide> s.d.Start(c) <ide> <ide> oldBasesizeBytes := getBaseDeviceSize(c, s.d) <del> var newBasesizeBytes int64 = 1073741824 //1GB in bytes <add> var newBasesizeBytes int64 = 1073741824 // 1GB in bytes <ide> <ide> if newBasesizeBytes < oldBasesizeBytes { <ide> err := s.d.RestartWithError("--storage-opt", fmt.Sprintf("dm.basesize=%d", newBasesizeBytes)) <ide> func (s *DockerDaemonSuite) TestDaemonRestartWithIncreasedBasesize(c *testing.T) <ide> <ide> oldBasesizeBytes := getBaseDeviceSize(c, s.d) <ide> <del> var newBasesizeBytes int64 = 53687091200 //50GB in bytes <add> var newBasesizeBytes int64 = 53687091200 // 50GB in bytes <ide> <ide> if newBasesizeBytes < oldBasesizeBytes { <ide> c.Skip(fmt.Sprintf("New base device size (%v) must be greater than (%s)", units.HumanSize(float64(newBasesizeBytes)), units.HumanSize(float64(oldBasesizeBytes)))) <ide> func (s *DockerDaemonSuite) TestDaemonKeyGeneration(c *testing.T) { <ide> // Note that this explicitly tests the conflict of {-b,--bridge} and {--bip} options as the means <ide> // to get a daemon init failure; no other tests for -b/--bip conflict are therefore required <ide> func (s *DockerDaemonSuite) TestDaemonExitOnFailure(c *testing.T) { <del> //attempt to start daemon with incorrect flags (we know -b and --bip conflict) <add> // attempt to start daemon with incorrect flags (we know -b and --bip conflict) <ide> if err := s.d.StartWithError("--bridge", "nosuchbridge", "--bip", "1.1.1.1"); err != nil { <del> //verify we got the right error <add> // verify we got the right error <ide> if !strings.Contains(err.Error(), "daemon exited") { <ide> c.Fatalf("Expected daemon not to start, got %v", err) <ide> } <ide> // look in the log and make sure we got the message that daemon is shutting down <ide> icmd.RunCommand("grep", "failed to start daemon", s.d.LogFileName()).Assert(c, icmd.Success) <ide> } else { <del> //if we didn't get an error and the daemon is running, this is a failure <add> // if we didn't get an error and the daemon is running, this is a failure <ide> c.Fatal("Conflicting options should cause the daemon to error out with a failure") <ide> } <ide> } <ide> func (s *DockerDaemonSuite) TestDaemonRestartWithBridgeIPChange(c *testing.T) { <ide> <ide> s.d.Start(c, "--bip", bridgeIP) <ide> <del> //check if the iptables contains new bridgeIP MASQUERADE rule <add> // check if the iptables contains new bridgeIP MASQUERADE rule <ide> ipTablesSearchString := bridgeIPNet.String() <ide> icmd.RunCommand("iptables", "-t", "nat", "-nvL").Assert(c, icmd.Expected{ <ide> Out: ipTablesSearchString, <ide> func (s *DockerDaemonSuite) TestDaemonWithWrongkey(c *testing.T) { <ide> c.Fatalf("Error Unmarshal: %s", err) <ide> } <ide> <del> //replace config.Kid with the fake value <add> // replace config.Kid with the fake value <ide> config.Kid = "VSAJ:FUYR:X3H2:B2VZ:KZ6U:CJD5:K7BX:ZXHY:UZXT:P4FT:MJWG:HRJ4" <ide> <ide> // NEW Data-Struct to byte[] <ide><path>integration-cli/docker_cli_events_test.go <ide> func (s *DockerSuite) TestEventsTimestampFormats(c *testing.T) { <ide> events = events[:len(events)-1] <ide> <ide> nEvents := len(events) <del> assert.Assert(c, nEvents >= 5) //Missing expected event <add> assert.Assert(c, nEvents >= 5) <ide> containerEvents := eventActionsByIDAndType(c, events, name, "container") <ide> assert.Assert(c, is.DeepEqual(containerEvents, []string{"create", "attach", "start", "die", "destroy"}), out) <ide> } <ide> func (s *DockerSuite) TestEventsContainerEventsAttrSort(c *testing.T) { <ide> events := strings.Split(out, "\n") <ide> <ide> nEvents := len(events) <del> assert.Assert(c, nEvents >= 3) //Missing expected event <add> assert.Assert(c, nEvents >= 3) <ide> matchedEvents := 0 <ide> for _, event := range events { <ide> matches := eventstestutils.ScanMap(event) <ide> func (s *DockerSuite) TestEventsContainerEventsSinceUnixEpoch(c *testing.T) { <ide> events = events[:len(events)-1] <ide> <ide> nEvents := len(events) <del> assert.Assert(c, nEvents >= 5) //Missing expected event <add> assert.Assert(c, nEvents >= 5) <ide> containerEvents := eventActionsByIDAndType(c, events, "since-epoch-test", "container") <ide> assert.Assert(c, is.DeepEqual(containerEvents, []string{"create", "attach", "start", "die", "destroy"}), out) <ide> } <ide> func (s *DockerSuite) TestEventsContainerRestart(c *testing.T) { <ide> events := strings.Split(strings.TrimSpace(out), "\n") <ide> <ide> nEvents := len(events) <del> assert.Assert(c, nEvents >= 1) //Missing expected event <add> assert.Assert(c, nEvents >= 1) <ide> actions := eventActionsByIDAndType(c, events, "testEvent", "container") <ide> <ide> for _, a := range actions { <ide><path>integration-cli/docker_cli_events_unix_test.go <ide> func (s *DockerSuite) TestEventsContainerWithMultiNetwork(c *testing.T) { <ide> assert.Assert(c, strings.Contains(netEvents[0], "disconnect")) <ide> assert.Assert(c, strings.Contains(netEvents[1], "disconnect")) <ide> <del> //both networks appeared in the network event output <add> // both networks appeared in the network event output <ide> assert.Assert(c, strings.Contains(out, "test-event-network-local-1")) <ide> assert.Assert(c, strings.Contains(out, "test-event-network-local-2")) <ide> } <ide><path>integration-cli/docker_cli_images_test.go <ide> func (s *DockerSuite) TestImagesEnsureDanglingImageOnlyListedOnce(c *testing.T) <ide> assert.Equal(c, strings.Count(out, imageID), 1) <ide> <ide> out, _ = dockerCmd(c, "images", "-q", "-f", "dangling=false") <del> //dangling=false would not include dangling images <add> // dangling=false would not include dangling images <ide> assert.Assert(c, !strings.Contains(out, imageID)) <ide> out, _ = dockerCmd(c, "images") <del> //docker images still include dangling images <add> // docker images still include dangling images <ide> assert.Assert(c, strings.Contains(out, imageID)) <ide> } <ide> <ide><path>integration-cli/docker_cli_inspect_test.go <ide> func (s *DockerSuite) TestInspectInt64(c *testing.T) { <ide> } <ide> <ide> func (s *DockerSuite) TestInspectDefault(c *testing.T) { <del> //Both the container and image are named busybox. docker inspect will fetch the container JSON. <del> //If the container JSON is not available, it will go for the image JSON. <add> // Both the container and image are named busybox. docker inspect will fetch the container JSON. <add> // If the container JSON is not available, it will go for the image JSON. <ide> <ide> out, _ := dockerCmd(c, "run", "--name=busybox", "-d", "busybox", "true") <ide> containerID := strings.TrimSpace(out) <ide> func (s *DockerSuite) TestInspectStatus(c *testing.T) { <ide> } <ide> <ide> func (s *DockerSuite) TestInspectTypeFlagContainer(c *testing.T) { <del> //Both the container and image are named busybox. docker inspect will fetch container <del> //JSON State.Running field. If the field is true, it's a container. <add> // Both the container and image are named busybox. docker inspect will fetch container <add> // JSON State.Running field. If the field is true, it's a container. <ide> runSleepingContainer(c, "--name=busybox", "-d") <ide> <ide> formatStr := "--format={{.State.Running}}" <ide> func (s *DockerSuite) TestInspectTypeFlagContainer(c *testing.T) { <ide> } <ide> <ide> func (s *DockerSuite) TestInspectTypeFlagWithNoContainer(c *testing.T) { <del> //Run this test on an image named busybox. docker inspect will try to fetch container <del> //JSON. Since there is no container named busybox and --type=container, docker inspect will <del> //not try to get the image JSON. It will throw an error. <add> // Run this test on an image named busybox. docker inspect will try to fetch container <add> // JSON. Since there is no container named busybox and --type=container, docker inspect will <add> // not try to get the image JSON. It will throw an error. <ide> <ide> dockerCmd(c, "run", "-d", "busybox", "true") <ide> <ide> func (s *DockerSuite) TestInspectTypeFlagWithNoContainer(c *testing.T) { <ide> } <ide> <ide> func (s *DockerSuite) TestInspectTypeFlagWithImage(c *testing.T) { <del> //Both the container and image are named busybox. docker inspect will fetch image <del> //JSON as --type=image. if there is no image with name busybox, docker inspect <del> //will throw an error. <add> // Both the container and image are named busybox. docker inspect will fetch image <add> // JSON as --type=image. if there is no image with name busybox, docker inspect <add> // will throw an error. <ide> <ide> dockerCmd(c, "run", "--name=busybox", "-d", "busybox", "true") <ide> <ide> func (s *DockerSuite) TestInspectTypeFlagWithImage(c *testing.T) { <ide> } <ide> <ide> func (s *DockerSuite) TestInspectTypeFlagWithInvalidValue(c *testing.T) { <del> //Both the container and image are named busybox. docker inspect will fail <del> //as --type=foobar is not a valid value for the flag. <add> // Both the container and image are named busybox. docker inspect will fail <add> // as --type=foobar is not a valid value for the flag. <ide> <ide> dockerCmd(c, "run", "--name=busybox", "-d", "busybox", "true") <ide> <ide> func (s *DockerSuite) TestInspectLogConfigNoType(c *testing.T) { <ide> } <ide> <ide> func (s *DockerSuite) TestInspectNoSizeFlagContainer(c *testing.T) { <del> <del> //Both the container and image are named busybox. docker inspect will fetch container <del> //JSON SizeRw and SizeRootFs field. If there is no flag --size/-s, there are no size fields. <add> // Both the container and image are named busybox. docker inspect will fetch container <add> // JSON SizeRw and SizeRootFs field. If there is no flag --size/-s, there are no size fields. <ide> <ide> runSleepingContainer(c, "--name=busybox", "-d") <ide> <ide><path>integration-cli/docker_cli_ps_test.go <ide> func (s *DockerSuite) TestPsListContainersFilterNetwork(c *testing.T) { <ide> // skip header <ide> lines = lines[1:] <ide> <del> //ps output should have both the containers <add> // ps output should have both the containers <ide> assert.Equal(c, len(RemoveLinesForExistingElements(lines, existing)), 2) <ide> <ide> // Making sure onbridgenetwork and onnonenetwork is on the output <ide><path>integration-cli/docker_cli_run_test.go <ide> func (s *DockerSuite) TestRunWithoutNetworking(c *testing.T) { <ide> } <ide> } <ide> <del>//test --link use container name to link target <add>// test --link use container name to link target <ide> func (s *DockerSuite) TestRunLinksContainerWithContainerName(c *testing.T) { <ide> // TODO Windows: This test cannot run on a Windows daemon as the networking <ide> // settings are not populated back yet on inspect. <ide> func (s *DockerSuite) TestRunLinksContainerWithContainerName(c *testing.T) { <ide> } <ide> } <ide> <del>//test --link use container id to link target <add>// test --link use container id to link target <ide> func (s *DockerSuite) TestRunLinksContainerWithContainerID(c *testing.T) { <ide> // TODO Windows: This test cannot run on a Windows daemon as the networking <ide> // settings are not populated back yet on inspect. <ide> func (s *DockerSuite) TestRunResolvconfUpdate(c *testing.T) { <ide> tmpResolvConf := []byte("search pommesfrites.fr\nnameserver 12.34.56.78\n") <ide> tmpLocalhostResolvConf := []byte("nameserver 127.0.0.1") <ide> <del> //take a copy of resolv.conf for restoring after test completes <add> // take a copy of resolv.conf for restoring after test completes <ide> resolvConfSystem, err := ioutil.ReadFile("/etc/resolv.conf") <ide> if err != nil { <ide> c.Fatal(err) <ide> func (s *DockerSuite) TestRunResolvconfUpdate(c *testing.T) { <ide> icmd.RunCommand("umount", "/etc/resolv.conf").Assert(c, icmd.Success) <ide> } <ide> <del> //cleanup <add> // cleanup <ide> defer func() { <ide> if err := ioutil.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil { <ide> c.Fatal(err) <ide> } <ide> }() <ide> <del> //1. test that a restarting container gets an updated resolv.conf <add> // 1. test that a restarting container gets an updated resolv.conf <ide> dockerCmd(c, "run", "--name=first", "busybox", "true") <ide> containerID1 := getIDByName(c, "first") <ide> <ide> func (s *DockerSuite) TestRunResolvconfUpdate(c *testing.T) { <ide> c.Fatalf("Restarted container does not have updated resolv.conf; expected %q, got %q", tmpResolvConf, string(containerResolv)) <ide> } <ide> <del> /* //make a change to resolv.conf (in this case replacing our tmp copy with orig copy) <add> /* // make a change to resolv.conf (in this case replacing our tmp copy with orig copy) <ide> if err := ioutil.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil { <ide> c.Fatal(err) <ide> } */ <del> //2. test that a restarting container does not receive resolv.conf updates <add> // 2. test that a restarting container does not receive resolv.conf updates <ide> // if it modified the container copy of the starting point resolv.conf <ide> dockerCmd(c, "run", "--name=second", "busybox", "sh", "-c", "echo 'search mylittlepony.com' >>/etc/resolv.conf") <ide> containerID2 := getIDByName(c, "second") <ide> <del> //make a change to resolv.conf (in this case replacing our tmp copy with orig copy) <add> // make a change to resolv.conf (in this case replacing our tmp copy with orig copy) <ide> if err := ioutil.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil { <ide> c.Fatal(err) <ide> } <ide> func (s *DockerSuite) TestRunResolvconfUpdate(c *testing.T) { <ide> c.Fatalf("Container's resolv.conf should not have been updated with host resolv.conf: %q", string(containerResolv)) <ide> } <ide> <del> //3. test that a running container's resolv.conf is not modified while running <add> // 3. test that a running container's resolv.conf is not modified while running <ide> out, _ := dockerCmd(c, "run", "-d", "busybox", "top") <ide> runningContainerID := strings.TrimSpace(out) <ide> <ide> func (s *DockerSuite) TestRunResolvconfUpdate(c *testing.T) { <ide> c.Fatalf("Running container should not have updated resolv.conf; expected %q, got %q", string(resolvConfSystem), string(containerResolv)) <ide> } <ide> <del> //4. test that a running container's resolv.conf is updated upon restart <add> // 4. test that a running container's resolv.conf is updated upon restart <ide> // (the above container is still running..) <ide> dockerCmd(c, "restart", runningContainerID) <ide> <ide> func (s *DockerSuite) TestRunResolvconfUpdate(c *testing.T) { <ide> c.Fatalf("Restarted container should have updated resolv.conf; expected %q, got %q", string(tmpResolvConf), string(containerResolv)) <ide> } <ide> <del> //5. test that additions of a localhost resolver are cleaned from <add> // 5. test that additions of a localhost resolver are cleaned from <ide> // host resolv.conf before updating container's resolv.conf copies <ide> <ide> // replace resolv.conf with a localhost-only nameserver copy <ide> func (s *DockerSuite) TestRunResolvconfUpdate(c *testing.T) { <ide> c.Fatalf("Container does not have cleaned/replaced DNS in resolv.conf; expected %q, got %q", expected, string(containerResolv)) <ide> } <ide> <del> //6. Test that replacing (as opposed to modifying) resolv.conf triggers an update <add> // 6. Test that replacing (as opposed to modifying) resolv.conf triggers an update <ide> // of containers' resolv.conf. <ide> <ide> // Restore the original resolv.conf <ide> func (s *DockerSuite) TestRunResolvconfUpdate(c *testing.T) { <ide> c.Fatalf("Stopped container does not have updated resolv.conf; expected\n%q\n got\n%q", tmpResolvConf, string(containerResolv)) <ide> } <ide> <del> //cleanup, restore original resolv.conf happens in defer func() <add> // cleanup, restore original resolv.conf happens in defer func() <ide> } <ide> <ide> func (s *DockerSuite) TestRunAddHost(c *testing.T) { <ide> func (s *DockerSuite) TestRunCidFileCleanupIfEmpty(c *testing.T) { <ide> } <ide> <ide> // #2098 - Docker cidFiles only contain short version of the containerId <del>//sudo docker run --cidfile /tmp/docker_tesc.cid ubuntu echo "test" <add>// sudo docker run --cidfile /tmp/docker_tesc.cid ubuntu echo "test" <ide> // TestRunCidFile tests that run --cidfile returns the longid <ide> func (s *DockerSuite) TestRunCidFileCheckIDLength(c *testing.T) { <ide> tmpDir, err := ioutil.TempDir("", "TestRunCidFile") <ide> func (s *DockerSuite) TestRunInspectMacAddress(c *testing.T) { <ide> // test docker run use an invalid mac address <ide> func (s *DockerSuite) TestRunWithInvalidMacAddress(c *testing.T) { <ide> out, _, err := dockerCmdWithError("run", "--mac-address", "92:d0:c6:0a:29", "busybox") <del> //use an invalid mac address should with an error out <add> // use an invalid mac address should with an error out <ide> if err == nil || !strings.Contains(out, "is not a valid mac address") { <ide> c.Fatalf("run with an invalid --mac-address should with error out") <ide> } <ide> func (s *DockerSuite) TestRunReuseBindVolumeThatIsSymlink(c *testing.T) { <ide> dockerCmd(c, "run", "-v", fmt.Sprintf("%s:"+prefix+"/tmp/test", linkPath), "busybox", "ls", prefix+"/tmp/test") <ide> } <ide> <del>//GH#10604: Test an "/etc" volume doesn't overlay special bind mounts in container <add>// GH#10604: Test an "/etc" volume doesn't overlay special bind mounts in container <ide> func (s *DockerSuite) TestRunCreateVolumeEtc(c *testing.T) { <ide> // While Windows supports volumes, it does not support --add-host hence <ide> // this test is not applicable on Windows. <ide><path>integration-cli/docker_cli_save_load_unix_test.go <ide> func (s *DockerSuite) TestSaveAndLoadRepoStdout(c *testing.T) { <ide> buf := make([]byte, 1024) <ide> <ide> n, err := pty.Read(buf) <del> assert.NilError(c, err) //could not read tty output <add> assert.NilError(c, err, "could not read tty output") <ide> assert.Assert(c, strings.Contains(string(buf[:n]), "cowardly refusing"), "help output is not being yielded") <ide> } <ide> <ide><path>integration-cli/docker_cli_search_test.go <ide> func (s *DockerSuite) TestSearchCmdOptions(c *testing.T) { <ide> outSearchCmd, _ := dockerCmd(c, "search", "busybox") <ide> assert.Assert(c, strings.Count(outSearchCmd, "\n") > 3, outSearchCmd) <ide> <del> outSearchCmdautomated, _ := dockerCmd(c, "search", "--filter", "is-automated=true", "busybox") //The busybox is a busybox base image, not an AUTOMATED image. <add> outSearchCmdautomated, _ := dockerCmd(c, "search", "--filter", "is-automated=true", "busybox") // The busybox is a busybox base image, not an AUTOMATED image. <ide> outSearchCmdautomatedSlice := strings.Split(outSearchCmdautomated, "\n") <ide> for i := range outSearchCmdautomatedSlice { <ide> assert.Assert(c, !strings.HasPrefix(outSearchCmdautomatedSlice[i], "busybox "), "The busybox is not an AUTOMATED image: %s", outSearchCmdautomated) <ide> } <ide> <del> outSearchCmdNotOfficial, _ := dockerCmd(c, "search", "--filter", "is-official=false", "busybox") //The busybox is a busybox base image, official image. <add> outSearchCmdNotOfficial, _ := dockerCmd(c, "search", "--filter", "is-official=false", "busybox") // The busybox is a busybox base image, official image. <ide> outSearchCmdNotOfficialSlice := strings.Split(outSearchCmdNotOfficial, "\n") <ide> for i := range outSearchCmdNotOfficialSlice { <ide> assert.Assert(c, !strings.HasPrefix(outSearchCmdNotOfficialSlice[i], "busybox "), "The busybox is not an OFFICIAL image: %s", outSearchCmdNotOfficial) <ide> } <ide> <del> outSearchCmdOfficial, _ := dockerCmd(c, "search", "--filter", "is-official=true", "busybox") //The busybox is a busybox base image, official image. <add> outSearchCmdOfficial, _ := dockerCmd(c, "search", "--filter", "is-official=true", "busybox") // The busybox is a busybox base image, official image. <ide> outSearchCmdOfficialSlice := strings.Split(outSearchCmdOfficial, "\n") <ide> assert.Equal(c, len(outSearchCmdOfficialSlice), 3) // 1 header, 1 line, 1 carriage return <ide> assert.Assert(c, strings.HasPrefix(outSearchCmdOfficialSlice[1], "busybox "), "The busybox is an OFFICIAL image: %s", outSearchCmdOfficial)
15
Java
Java
add wrapper class for async storage
4b6af5fa63909060225b8756319273fcedcd0898
<ide><path>ReactAndroid/src/main/java/com/facebook/react/modules/storage/AsyncLocalStorageUtil.java <ide> /** <ide> * Helper for database operations. <ide> */ <del>/* package */ class AsyncLocalStorageUtil { <add>public class AsyncLocalStorageUtil { <ide> <ide> /** <ide> * Build the String required for an SQL select statement: <ide> /** <ide> * Returns the value of the given key, or null if not found. <ide> */ <del> /* package */ static @Nullable String getItemImpl(SQLiteDatabase db, String key) { <add> public static @Nullable String getItemImpl(SQLiteDatabase db, String key) { <ide> String[] columns = {VALUE_COLUMN}; <ide> String[] selectionArgs = {key}; <ide> <ide><path>ReactAndroid/src/main/java/com/facebook/react/modules/storage/ReactDatabaseSupplier.java <ide> public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { <ide> /** <ide> * Create and/or open the database. <ide> */ <del> /* package */ synchronized SQLiteDatabase get() { <add> public synchronized SQLiteDatabase get() { <ide> ensureDatabase(); <ide> return mDb; <ide> }
2
Java
Java
improve javadoc for contextcache#clearstatistics()
31a9694fc88e0a5b9343d2cca1cf008aef26830d
<ide><path>spring-test/src/main/java/org/springframework/test/context/cache/ContextCache.java <ide> /* <del> * Copyright 2002-2018 the original author or authors. <add> * Copyright 2002-2022 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public interface ContextCache { <ide> void clear(); <ide> <ide> /** <del> * Clear hit-and-miss count statistics for the cache (i.e., reset counters to zero). <add> * Clear {@linkplain #getHitCount() hit count} and {@linkplain #getMissCount() <add> * miss count} statistics for the cache (i.e., reset counters to zero). <ide> */ <ide> void clearStatistics(); <ide>
1
Python
Python
fix morphological features in de tag_map
3a667833d1a37ffa826ebb3ca76b057c1ce712e3
<ide><path>spacy/lang/de/tag_map.py <ide> "$,": {POS: PUNCT, "PunctType": "comm"}, <ide> "$.": {POS: PUNCT, "PunctType": "peri"}, <ide> "ADJA": {POS: ADJ}, <del> "ADJD": {POS: ADJ, "Variant": "short"}, <add> "ADJD": {POS: ADJ}, <ide> "ADV": {POS: ADV}, <ide> "APPO": {POS: ADP, "AdpType": "post"}, <ide> "APPR": {POS: ADP, "AdpType": "prep"}, <ide> "PDAT": {POS: DET, "PronType": "dem"}, <ide> "PDS": {POS: PRON, "PronType": "dem"}, <ide> "PIAT": {POS: DET, "PronType": "ind|neg|tot"}, <del> "PIDAT": {POS: DET, "AdjType": "pdt", "PronType": "ind|neg|tot"}, <add> "PIDAT": {POS: DET, "PronType": "ind|neg|tot"}, <ide> "PIS": {POS: PRON, "PronType": "ind|neg|tot"}, <ide> "PPER": {POS: PRON, "PronType": "prs"}, <ide> "PPOSAT": {POS: DET, "Poss": "yes", "PronType": "prs"}, <ide> "PRF": {POS: PRON, "PronType": "prs", "Reflex": "yes"}, <ide> "PTKA": {POS: PART}, <ide> "PTKANT": {POS: PART, "PartType": "res"}, <del> "PTKNEG": {POS: PART, "Polarity": "Neg"}, <add> "PTKNEG": {POS: PART, "Polarity": "neg"}, <ide> "PTKVZ": {POS: PART, "PartType": "vbp"}, <ide> "PTKZU": {POS: PART, "PartType": "inf"}, <ide> "PWAT": {POS: DET, "PronType": "int"},
1
Ruby
Ruby
remove superfluous branch
fa64a17ae9d5c09c3dac84accaa76eb8e3478ea3
<ide><path>Library/Homebrew/livecheck/livecheck.rb <ide> def run_checks(formulae_and_casks_to_check, args) <ide> livecheck_version = formula_or_cask.livecheck.version <ide> current = if livecheck_version.is_a?(String) <ide> Version.new(livecheck_version) <del> elsif livecheck_version.is_a?(Array) <del> separator, method = livecheck_version <del> Version.new(formula_or_cask.version.to_s.split(separator, 2).try(method)) <ide> elsif formula <ide> if formula.head_only? <ide> formula.any_installed_version.version.commit
1
Ruby
Ruby
remove redundent line and reword comments slightly
80c090aaaeefb0d573ec2c633795eba5b2a4a900
<ide><path>Library/Homebrew/extend/ENV.rb <ide> def setup_build_environment <ide> xcode_path = "/Developer" if xcode_path.to_s.empty? <ide> ENV['CC'] = "#{xcode_path}/usr/bin/llvm-gcc" <ide> ENV['CXX'] = "#{xcode_path}/usr/bin/llvm-g++" <del> ENV['LD'] = ENV['CC'] <ide> cflags = ['-O4'] # link time optimisation baby! <ide> else <del> # if we don't set these, many formula fail to build <add> # If these aren't set, many formulae fail to build <ide> ENV['CC'] = '/usr/bin/cc' <ide> ENV['CXX'] = '/usr/bin/c++' <ide> cflags = ['-O3'] <ide> end <ide> <del> # in rare cases this may break your builds, as the tool for some reason wants <del> # to use a specific linker, however doing this in general causes formula to <add> # In rare cases this may break your builds, as the tool for some reason wants <add> # to use a specific linker. However doing this in general causes formula to <ide> # build more successfully because we are changing CC and many build systems <del> # don't react properly to that <add> # don't react properly to that. <ide> ENV['LD'] = ENV['CC'] <ide> <ide> # optimise all the way to eleven, references: <ide> def setup_build_environment <ide> <ide> ENV['CFLAGS'] = ENV['CXXFLAGS'] = "#{cflags*' '} #{SAFE_CFLAGS_FLAGS}" <ide> end <del> <add> <ide> def deparallelize <ide> remove 'MAKEFLAGS', /-j\d+/ <ide> end
1