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
PHP
PHP
add tests for idempotent methods and csrf tokens
322ebd49971578c955c0600307d3399d5c755e5e
<ide><path>tests/TestCase/Controller/Component/CsrfComponentTest.php <ide> public function testSettingCookie() <ide> $this->assertEquals($cookie['value'], $controller->request->params['_csrfToken']); <ide> } <ide> <add> /** <add> * Data provider for HTTP method tests. <add> * <add> * @return void <add> */ <add> public static function safeHttpMethodProvider() <add> { <add> return [ <add> ['GET'], ['OPTIONS'], ['HEAD'] <add> ]; <add> } <add> <add> /** <add> * Test that the CSRF tokens are not required for idempotent operations <add> * <add> * @dataProvider safeHttpMethodProvider <add> * @return void <add> */ <add> public function testSafeMethodNoCsrfRequired($method) <add> { <add> $controller = $this->getMock('Cake\Controller\Controller', ['redirect']); <add> $controller->request = new Request([ <add> 'environment' => [ <add> 'REQUEST_METHOD' => $method, <add> 'HTTP_X_CSRF_TOKEN' => 'nope', <add> ], <add> 'cookies' => ['csrfToken' => 'testing123'] <add> ]); <add> $controller->response = new Response(); <add> <add> $event = new Event('Controller.startup', $controller); <add> $result = $this->component->startup($event); <add> $this->assertNull($result, 'No exception means valid.'); <add> } <add> <ide> /** <ide> * Data provider for HTTP method tests. <ide> *
1
PHP
PHP
fix corrupted global state
75207a00c1b98c1b1240b6f82fe01082ad58249f
<ide><path>tests/TestCase/Routing/Filter/LocaleSelectorFilterTest.php <ide> */ <ide> class LocaleSelectorFilterTest extends TestCase { <ide> <add>/** <add> * setup <add> * <add> * @return void <add> */ <add> public function setUp() { <add> parent::setUp(); <add> $this->locale = Locale::getDefault(); <add> } <add> <ide> /** <ide> * Resets the default locale <ide> * <ide> * @return void <ide> */ <ide> public function tearDown() { <ide> parent::tearDown(); <del> Locale::setDefault(''); <add> Locale::setDefault($this->locale); <ide> } <ide> <ide> /** <ide> public function testSimpleSelection() { <ide> * @return void <ide> */ <ide> public function testWithWhitelist() { <add> Locale::setDefault('en_US'); <ide> $filter = new LocaleSelectorFilter([ <ide> 'locales' => ['en_CA', 'en_IN', 'es_VE'] <ide> ]); <ide> public function testWithWhitelist() { <ide> ]); <ide> $filter->beforeDispatch(new Event('name', null, ['request' => $request])); <ide> $this->assertEquals('es_VE', Locale::getDefault()); <del> Locale::setDefault(''); <ide> <add> Locale::setDefault('en_US'); <ide> $request = new Request([ <ide> 'environment' => [ <ide> 'HTTP_ACCEPT_LANGUAGE' => 'en-GB;q=0.8,es-ES;q=0.9,da-DK;q=0.4'
1
PHP
PHP
add missing tests
5b2bc35ecd271eaf7d4dc8f37f1399811edd2a37
<ide><path>tests/Foundation/FoundationApplicationTest.php <ide> public function testBeforeBootstrappingAddsClosure() <ide> $this->assertArrayHasKey(0, $app['events']->getListeners('bootstrapping: Illuminate\Foundation\Bootstrap\RegisterFacades')); <ide> } <ide> <add> public function testTerminationTests() <add> { <add> $app = new Application; <add> <add> $counter = 0; <add> $callback1 = function () use (&$counter) { <add> $counter++; <add> }; <add> <add> $callback2 = function () use (&$counter) { <add> $counter++; <add> }; <add> <add> $callback3 = function () use (&$counter) { <add> $counter++; <add> }; <add> <add> $app->terminating($callback1); <add> $app->terminating($callback2); <add> $app->terminating($callback3); <add> <add> $app->terminate(); <add> <add> $this->assertEquals(3, $counter); <add> } <add> <ide> public function testAfterBootstrappingAddsClosure() <ide> { <ide> $app = new Application;
1
Python
Python
change description in image
a3dfe223dc98151e9eb85fb04e72a867576e9b16
<ide><path>libcloud/compute/drivers/outscale.py <ide> def ex_create_image_export_task( <ide> <ide> :param osu_export_api_secret_key: The secret key of the <ide> OSU account that enables you to access the bucket. <del> :type osu_export_api_secret_key: ``bool`` <add> :type osu_export_api_secret_key: ``str`` <ide> <ide> :param osu_export_bucket: The name of the OSU bucket <ide> you want to export the object to. (required) <del> :type osu_export_bucket: ``bool`` <add> :type osu_export_bucket: ``str`` <ide> <ide> :param osu_export_manifest_url: The URL of the manifest file. <del> :type osu_export_manifest_url: ``bool`` <add> :type osu_export_manifest_url: ``str`` <ide> <ide> :param osu_export_prefix: The prefix for the key of <ide> the OSU object. This key follows this format: <ide> prefix + object_export_task_id + '.' + disk_image_format. <del> :type osu_export_prefix: ``bool`` <add> :type osu_export_prefix: ``str`` <ide> <ide> :return: the created image export task <ide> :rtype: ``dict`` <ide> def ex_update_image( <ide> <ide> :param perm_to_launch_addition_global_permission: <ide> If true, the resource is public. If false, the resource is private. <del> :type permission_to_launch_addition_global_permission: ``boolean`` <add> :type permission_to_launch_addition_global_permission: <add> ``boolean`` <ide> <ide> :param perm_to_launch_removals_account_ids: The account <ide> ID of one or more users who have permissions for the resource.
1
Javascript
Javascript
remove temp files
d87fb0e29d21eaab5c1548c821462663f7ebad94
<ide><path>test/fixtures/temp-1000/file.js <del>require('./file2') <ide>\ No newline at end of file <ide><path>test/fixtures/temp-1000/file2.js <del>original <ide>\ No newline at end of file
2
PHP
PHP
expand complex conditional
388940cd8be7d378a18ed557bdbad97f94f1ae4b
<ide><path>src/Database/Expression/QueryExpression.php <ide> public function __call($method, $args) <ide> */ <ide> public function isCallable($c) <ide> { <del> return ( <del> !is_string($c) && <del> ( <del> (is_array($c) && isset($c[0]) && is_object($c[0]) && is_callable($c)) || <del> (is_object($c) && is_callable($c)) <del> ) <del> ); <add> if (is_string($c)) { <add> return false; <add> } <add> if (is_object($c) && is_callable($c)) { <add> return true; <add> } <add> if (is_array($c) && isset($c[0]) && is_object($c[0]) && is_callable($c)) { <add> return true; <add> } <add> return false; <ide> } <ide> <ide> /**
1
Ruby
Ruby
remove deprecated calls from the tests
0507bc3f58b7d6a36d93dcd5c21d7f40e9322c80
<ide><path>lib/arel/visitors/mssql.rb <ide> def select_count? x <ide> x.projections.length == 1 && Arel::Nodes::Count === x.projections.first <ide> end <ide> <del> # fixme raise exception of there is no pk? <del> # fixme!! Table.primary_key will be depricated. What is the replacement?? <add> # FIXME raise exception of there is no pk? <add> # FIXME!! Table.primary_key will be deprecated. What is the replacement?? <ide> def find_left_table_pk o, a <ide> return visit o.primary_key, a if o.instance_of? Arel::Table <ide> find_left_table_pk o.left, a if o.kind_of? Arel::Nodes::Join <ide><path>test/test_crud.rb <ide> def initialize engine = FakeEngine.new <ide> table = Table.new :users <ide> fc = FakeCrudder.new <ide> fc.from table <del> stmt = fc.compile_update [[table[:id], 'foo']], table.primary_key <add> stmt = fc.compile_update [[table[:id], 'foo']], Arel::Attributes::Attribute.new(table, 'id') <ide> assert_instance_of Arel::UpdateManager, stmt <ide> end <ide> end <ide><path>test/test_select_manager.rb <ide> def test_join_sources <ide> manager = Arel::SelectManager.new engine <ide> manager.from table <ide> manager.take 1 <del> stmt = manager.compile_update(SqlLiteral.new('foo = bar'), table.primary_key) <add> stmt = manager.compile_update(SqlLiteral.new('foo = bar'), Arel::Attributes::Attribute.new(table, 'id')) <ide> stmt.key = table['id'] <ide> <ide> stmt.to_sql.must_be_like %{ <ide> def test_join_sources <ide> manager = Arel::SelectManager.new engine <ide> manager.from table <ide> manager.order :foo <del> stmt = manager.compile_update(SqlLiteral.new('foo = bar'), table.primary_key) <add> stmt = manager.compile_update(SqlLiteral.new('foo = bar'), Arel::Attributes::Attribute.new(table, 'id')) <ide> stmt.key = table['id'] <ide> <ide> stmt.to_sql.must_be_like %{ <ide> def test_join_sources <ide> table = Table.new :users <ide> manager = Arel::SelectManager.new engine <ide> manager.from table <del> stmt = manager.compile_update(SqlLiteral.new('foo = bar'), table.primary_key) <add> stmt = manager.compile_update(SqlLiteral.new('foo = bar'), Arel::Attributes::Attribute.new(table, 'id')) <ide> <ide> stmt.to_sql.must_be_like %{ UPDATE "users" SET foo = bar } <ide> end <ide> def test_join_sources <ide> manager = Arel::SelectManager.new engine <ide> manager.where table[:id].eq 10 <ide> manager.from table <del> stmt = manager.compile_update({table[:id] => 1}, table.primary_key) <add> stmt = manager.compile_update({table[:id] => 1}, Arel::Attributes::Attribute.new(table, 'id')) <ide> <ide> stmt.to_sql.must_be_like %{ <ide> UPDATE "users" SET "id" = 1 WHERE "users"."id" = 10 <ide> def test_join_sources <ide> manager.where table[:foo].eq 10 <ide> manager.take 42 <ide> manager.from table <del> stmt = manager.compile_update({table[:id] => 1}, table.primary_key) <add> stmt = manager.compile_update({table[:id] => 1}, Arel::Attributes::Attribute.new(table, 'id')) <ide> <ide> stmt.to_sql.must_be_like %{ <ide> UPDATE "users" SET "id" = 1 WHERE "users"."id" IN (SELECT "users"."id" FROM "users" WHERE "users"."foo" = 10 LIMIT 42) <ide> def test_join_sources <ide> table = Table.new :users <ide> manager = Arel::SelectManager.new engine <ide> manager.from table <del> stmt = manager.compile_update({table[:id] => 1}, table.primary_key) <add> stmt = manager.compile_update({table[:id] => 1}, Arel::Attributes::Attribute.new(table, 'id')) <ide> <ide> stmt.to_sql.must_be_like %{ <ide> UPDATE "users" SET "id" = 1
3
Javascript
Javascript
add more benchmark cases
78839b2352d48b9025ae85aa550fd722bf820133
<ide><path>test/benchmarkCases/libraries/webpack.config.js <add>module.exports = { <add> entry: ["react", "react-dom", "lodash"] <add>} <ide><path>test/benchmarkCases/many-modules-source-map/a.js <add>require("./b?0" + __resourceQuery); <add>require("./b?1" + __resourceQuery); <add>require("./b?2" + __resourceQuery); <add>require("./b?3" + __resourceQuery); <add>require("./b?4" + __resourceQuery); <add>require("./b?5" + __resourceQuery); <add>require("./b?6" + __resourceQuery); <add>require("./b?7" + __resourceQuery); <add>require("./b?8" + __resourceQuery); <add>require("./b?9" + __resourceQuery); <ide><path>test/benchmarkCases/many-modules-source-map/b.js <add>require("./c?0" + __resourceQuery); <add>require("./c?1" + __resourceQuery); <add>require("./c?2" + __resourceQuery); <add>require("./c?3" + __resourceQuery); <add>require("./c?4" + __resourceQuery); <add>require("./c?5" + __resourceQuery); <add>require("./c?6" + __resourceQuery); <add>require("./c?7" + __resourceQuery); <add>require("./c?8" + __resourceQuery); <add>require("./c?9" + __resourceQuery); <add>require("./a" + __resourceQuery.substr(0, 2)); <ide><path>test/benchmarkCases/many-modules-source-map/c.js <add>// content <ide><path>test/benchmarkCases/many-modules-source-map/index.js <add>import "./a?0"; <add>import "./a?1"; <add>import "./a?2"; <add>import "./a?3"; <add>import "./a?4"; <add>import "./a?5"; <add>import "./a?6"; <add>import "./a?7"; <add>import "./a?8"; <add>import "./a?9"; <ide><path>test/benchmarkCases/many-modules-source-map/webpack.config.js <add>module.exports = { <add> entry: "./index", <add> devtool: "eval-cheap-module-source-map" <add>} <ide><path>test/benchmarkCases/many-modules/a.js <add>require("./b?0" + __resourceQuery); <add>require("./b?1" + __resourceQuery); <add>require("./b?2" + __resourceQuery); <add>require("./b?3" + __resourceQuery); <add>require("./b?4" + __resourceQuery); <add>require("./b?5" + __resourceQuery); <add>require("./b?6" + __resourceQuery); <add>require("./b?7" + __resourceQuery); <add>require("./b?8" + __resourceQuery); <add>require("./b?9" + __resourceQuery); <ide><path>test/benchmarkCases/many-modules/b.js <add>require("./c?0" + __resourceQuery); <add>require("./c?1" + __resourceQuery); <add>require("./c?2" + __resourceQuery); <add>require("./c?3" + __resourceQuery); <add>require("./c?4" + __resourceQuery); <add>require("./c?5" + __resourceQuery); <add>require("./c?6" + __resourceQuery); <add>require("./c?7" + __resourceQuery); <add>require("./c?8" + __resourceQuery); <add>require("./c?9" + __resourceQuery); <add>require("./a" + __resourceQuery.substr(0, 2)); <ide><path>test/benchmarkCases/many-modules/c.js <add>// content <ide><path>test/benchmarkCases/many-modules/index.js <add>import "./a?0"; <add>import "./a?1"; <add>import "./a?2"; <add>import "./a?3"; <add>import "./a?4"; <add>import "./a?5"; <add>import "./a?6"; <add>import "./a?7"; <add>import "./a?8"; <add>import "./a?9"; <add><path>test/benchmarkCases/many-modules/webpack.config.js <del><path>test/benchmarkCases/lodash/webpack.config.js <ide> module.exports = { <del> entry: "lodash" <add> entry: "./index" <ide> } <ide><path>test/benchmarkCases/react/webpack.config.js <del>module.exports = { <del> entry: ["react", "react-dom"] <del>}
12
Python
Python
update the train script, fixing gpu memory leak
3376d4d6e85ae1da26f0c86711f5c12b3ad3b1b3
<ide><path>spacy/cli/train.py <ide> <ide> <ide> def train(language, output_dir, train_data, dev_data, n_iter, n_sents, <del> use_gpu, tagger, parser, ner, parser_L1): <add> use_gpu, no_tagger, no_parser, no_entities, parser_L1): <ide> output_path = util.ensure_path(output_dir) <ide> train_path = util.ensure_path(train_data) <ide> dev_path = util.ensure_path(dev_data) <ide> def train(language, output_dir, train_data, dev_data, n_iter, n_sents, <ide> 'lang': language, <ide> 'features': lang.Defaults.tagger_features} <ide> gold_train = list(read_gold_json(train_path, limit=n_sents)) <del> gold_dev = list(read_gold_json(dev_path, limit=n_sents)) if dev_path else None <add> gold_dev = list(read_gold_json(dev_path, limit=n_sents)) <ide> <del> train_model(lang, gold_train, gold_dev, output_path, n_iter, use_gpu=use_gpu) <add> train_model(lang, gold_train, gold_dev, output_path, n_iter, <add> no_tagger=no_tagger, no_parser=no_parser, no_entities=no_entities, <add> use_gpu=use_gpu) <ide> if gold_dev: <ide> scorer = evaluate(lang, gold_dev, output_path) <ide> print_results(scorer) <ide> def train_config(config): <ide> def train_model(Language, train_data, dev_data, output_path, n_iter, **cfg): <ide> print("Itn.\tDep. Loss\tUAS\tNER F.\tTag %\tToken %") <ide> <del> nlp = Language(pipeline=['token_vectors', 'tags', 'dependencies']) <add> pipeline = ['token_vectors', 'tags', 'dependencies', 'entities'] <add> if cfg.get('no_tagger') and 'tags' in pipeline: <add> pipeline.remove('tags') <add> if cfg.get('no_parser') and 'dependencies' in pipeline: <add> pipeline.remove('dependencies') <add> if cfg.get('no_entities') and 'entities' in pipeline: <add> pipeline.remove('entities') <add> print(pipeline) <add> nlp = Language(pipeline=pipeline) <ide> dropout = util.env_opt('dropout', 0.0) <ide> # TODO: Get spaCy using Thinc's trainer and optimizer <ide> with nlp.begin_training(train_data, **cfg) as (trainer, optimizer): <del> for itn, epoch in enumerate(trainer.epochs(n_iter, gold_preproc=True)): <add> for itn, epoch in enumerate(trainer.epochs(n_iter, gold_preproc=False)): <ide> losses = defaultdict(float) <del> to_render = [] <ide> for i, (docs, golds) in enumerate(epoch): <del> state = nlp.update(docs, golds, drop=dropout, sgd=optimizer) <del> losses['dep_loss'] += state.get('parser_loss', 0.0) <del> losses['tag_loss'] += state.get('tag_loss', 0.0) <del> to_render.insert(0, nlp(docs[-1].text)) <del> to_render[0].user_data['title'] = "Batch %d" % i <del> with Path('/tmp/entities.html').open('w') as file_: <del> html = displacy.render(to_render[:5], style='ent', page=True) <del> file_.write(html) <del> with Path('/tmp/parses.html').open('w') as file_: <del> html = displacy.render(to_render[:5], style='dep', page=True) <del> file_.write(html) <add> nlp.update(docs, golds, drop=dropout, sgd=optimizer) <add> for doc in docs: <add> doc.tensor = None <add> doc._py_tokens = [] <ide> if dev_data: <ide> with nlp.use_params(optimizer.averages): <del> dev_scores = trainer.evaluate(dev_data).scores <add> dev_scores = trainer.evaluate(dev_data, gold_preproc=False).scores <ide> else: <ide> dev_scores = defaultdict(float) <ide> print_progress(itn, losses, dev_scores) <ide> with (output_path / 'model.bin').open('wb') as file_: <ide> dill.dump(nlp, file_, -1) <del> #nlp.to_disk(output_path, tokenizer=False) <add> <add> <add>def _render_parses(i, to_render): <add> to_render[0].user_data['title'] = "Batch %d" % i <add> with Path('/tmp/entities.html').open('w') as file_: <add> html = displacy.render(to_render[:5], style='ent', page=True) <add> file_.write(html) <add> with Path('/tmp/parses.html').open('w') as file_: <add> html = displacy.render(to_render[:5], style='dep', page=True) <add> file_.write(html) <ide> <ide> <ide> def evaluate(Language, gold_tuples, path):
1
Javascript
Javascript
tune a worker executor
cc0b504224415bf9ad2dd338fb61c627f1d3c929
<ide><path>client/src/templates/Challenges/rechallenge/transformers.js <ide> async function transformSASS(element) { <ide> await Promise.all( <ide> [].map.call(styleTags, async style => { <ide> style.type = 'text/css'; <del> style.innerHTML = await sassWorker.execute(style.innerHTML, 2000); <add> style.innerHTML = await sassWorker.execute(style.innerHTML, 5000); <ide> }) <ide> ); <ide> } <ide> export const composeHTML = cond([ <ide> [ <ide> testHTML, <ide> flow( <del> partial( <del> vinyl.transformHeadTailAndContents, <del> source => { <del> const div = document.createElement('div'); <del> div.innerHTML = source; <del> return div.innerHTML; <del> } <del> ), <add> partial(vinyl.transformHeadTailAndContents, source => { <add> const div = document.createElement('div'); <add> div.innerHTML = source; <add> return div.innerHTML; <add> }), <ide> partial(vinyl.compileHeadTail, '') <ide> ) <ide> ], <ide><path>client/src/templates/Challenges/utils/worker-executor.js <add>import { homeLocation } from '../../../../config/env.json'; <add> <ide> export default class WorkerExecutor { <ide> constructor(workerName) { <ide> this.workerName = workerName; <ide> export default class WorkerExecutor { <ide> <ide> getWorker() { <ide> if (this.worker === null) { <del> this.worker = new Worker(`js/${this.workerName}.js`); <add> this.worker = new Worker(`${homeLocation}/js/${this.workerName}.js`); <ide> } <ide> <ide> return this.worker;
2
Ruby
Ruby
improve error when no url given
5193d835a443d6901bb28cbe451aaa0c08e299e7
<ide><path>Library/Homebrew/formula.rb <ide> def initialize name='__UNKNOWN__' <ide> @version='HEAD' <ide> end <ide> <del> raise if @url.nil? <add> raise "No url provided for formula #{name}" if @url.nil? <ide> @name=name <ide> validate_variable :name <ide>
1
Javascript
Javascript
add .extend test for defined accessor properties
9748e436ad80d6a2e1661ba4cf8d7391ed87c3ad
<ide><path>test/unit/core.js <ide> QUnit.test( "jQuery.extend(Object, Object)", function( assert ) { <ide> assert.deepEqual( options2, options2Copy, "Check if not modified: options2 must not be modified" ); <ide> } ); <ide> <add>QUnit.test( "jQuery.extend(Object, Object {created with \"defineProperties\"})", function( assert ) { <add> assert.expect( 2 ); <add> <add> var definedObj = Object.defineProperties({}, { <add> "enumerableProp": { <add> get: function () { <add> return true; <add> }, <add> enumerable: true <add> }, <add> "nonenumerableProp": { <add> get: function () { <add> return true; <add> } <add> } <add> }), <add> accessorObj = {}; <add> <add> jQuery.extend( accessorObj, definedObj ); <add> assert.equal( accessorObj.enumerableProp, true, "Verify that getters are transferred" ); <add> assert.equal( accessorObj.nonenumerableProp, undefined, "Verify that non-enumerable getters are ignored" ); <add>} ); <add> <ide> QUnit.test( "jQuery.extend(true,{},{a:[], o:{}}); deep copy with array, followed by object", function( assert ) { <ide> assert.expect( 2 ); <ide>
1
Python
Python
use the yield syntax in pytest's fixtures
5963cb5a5172bce3a1ff7b0f8c64230f043c9cfd
<ide><path>examples/minitwit/tests/test_minitwit.py <ide> <ide> <ide> @pytest.fixture <del>def client(request): <add>def client(): <ide> db_fd, minitwit.app.config['DATABASE'] = tempfile.mkstemp() <ide> client = minitwit.app.test_client() <ide> with minitwit.app.app_context(): <ide> minitwit.init_db() <ide> <del> def teardown(): <del> """Get rid of the database again after each test.""" <del> os.close(db_fd) <del> os.unlink(minitwit.app.config['DATABASE']) <del> request.addfinalizer(teardown) <del> return client <add> yield client <add> <add> os.close(db_fd) <add> os.unlink(minitwit.app.config['DATABASE']) <ide> <ide> <ide> def register(client, username, password, password2=None, email=None): <ide><path>tests/conftest.py <ide> def test_apps(monkeypatch): <ide> os.path.dirname(__file__), 'test_apps')) <ide> ) <ide> <add> <ide> @pytest.fixture(autouse=True) <del>def leak_detector(request): <del> def ensure_clean_request_context(): <del> # make sure we're not leaking a request context since we are <del> # testing flask internally in debug mode in a few cases <del> leaks = [] <del> while flask._request_ctx_stack.top is not None: <del> leaks.append(flask._request_ctx_stack.pop()) <del> assert leaks == [] <del> request.addfinalizer(ensure_clean_request_context) <add>def leak_detector(): <add> yield <add> <add> # make sure we're not leaking a request context since we are <add> # testing flask internally in debug mode in a few cases <add> leaks = [] <add> while flask._request_ctx_stack.top is not None: <add> leaks.append(flask._request_ctx_stack.pop()) <add> assert leaks == [] <ide> <ide> <ide> @pytest.fixture(params=(True, False)) <ide><path>tests/test_ext.py <ide> <ide> <ide> @pytest.fixture(autouse=True) <del>def disable_extwarnings(request, recwarn): <add>def disable_extwarnings(recwarn): <ide> from flask.exthook import ExtDeprecationWarning <ide> <del> def inner(): <del> assert set(w.category for w in recwarn.list) \ <del> <= set([ExtDeprecationWarning]) <del> recwarn.clear() <add> yield <ide> <del> request.addfinalizer(inner) <add> assert set(w.category for w in recwarn.list) \ <add> <= set([ExtDeprecationWarning]) <add> recwarn.clear() <ide> <ide> <ide> @pytest.fixture(autouse=True) <del>def importhook_setup(monkeypatch, request): <add>def importhook_setup(monkeypatch): <ide> # we clear this out for various reasons. The most important one is <ide> # that a real flaskext could be in there which would disable our <ide> # fake package. Secondly we want to make sure that the flaskext <ide> def importhook_setup(monkeypatch, request): <ide> import_hooks += 1 <ide> assert import_hooks == 1 <ide> <del> def teardown(): <del> from flask import ext <del> for key in ext.__dict__: <del> assert '.' not in key <add> yield <ide> <del> request.addfinalizer(teardown) <add> from flask import ext <add> for key in ext.__dict__: <add> assert '.' not in key <ide> <ide> <ide> @pytest.fixture
3
Python
Python
fix bad use of .dtype
ee91d88c01947723ae6ee7f0255f8357f7d8845c
<ide><path>numpy/lib/polynomial.py <ide> def poly(seq_of_zeros): <ide> for k in range(len(seq_of_zeros)): <ide> a = NX.convolve(a, [1, -seq_of_zeros[k]], mode='full') <ide> <del> if issubclass(a.dtype, NX.complexfloating): <add> if issubclass(a.dtype.type, NX.complexfloating): <ide> # if complex roots are all complex conjugates, the roots are real. <ide> roots = NX.asarray(seq_of_zeros, complex) <ide> pos_roots = sort_complex(NX.compress(roots.imag > 0, roots)) <ide> def roots(p): <ide> p = p[int(non_zero[0]):int(non_zero[-1])+1] <ide> <ide> # casting: if incoming array isn't floating point, make it floating point. <del> if not issubclass(p.dtype, (NX.floating, NX.complexfloating)): <add> if not issubclass(p.dtype.type, (NX.floating, NX.complexfloating)): <ide> p = p.astype(float) <ide> <ide> N = len(p)
1
Java
Java
introduce alias for 'value' attribute in @scope
2d23f42609c2e6a2ee6b0507f4b800870a63ca26
<ide><path>spring-context/src/main/java/org/springframework/context/annotation/AnnotationScopeMetadataResolver.java <ide> /* <del> * Copyright 2002-2013 the original author or authors. <add> * Copyright 2002-2015 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> <ide> /** <ide> * A {@link ScopeMetadataResolver} implementation that by default checks for <del> * the presence of Spring's {@link Scope} annotation on the bean class. <add> * the presence of Spring's {@link Scope @Scope} annotation on the bean class. <ide> * <del> * <p>The exact type of annotation that is checked for is configurable via the <del> * {@link #setScopeAnnotationType(Class)} property. <add> * <p>The exact type of annotation that is checked for is configurable via <add> * {@link #setScopeAnnotationType(Class)}. <ide> * <ide> * @author Mark Fisher <ide> * @author Juergen Hoeller <add> * @author Sam Brannen <ide> * @since 2.5 <ide> * @see org.springframework.context.annotation.Scope <ide> */ <ide> public class AnnotationScopeMetadataResolver implements ScopeMetadataResolver { <ide> <ide> <ide> /** <del> * Create a new instance of the {@code AnnotationScopeMetadataResolver} class. <add> * Construct a new {@code AnnotationScopeMetadataResolver}. <ide> * @see #AnnotationScopeMetadataResolver(ScopedProxyMode) <ide> * @see ScopedProxyMode#NO <ide> */ <ide> public AnnotationScopeMetadataResolver() { <del> this.defaultProxyMode = ScopedProxyMode.NO; <add> this(ScopedProxyMode.NO); <ide> } <ide> <ide> /** <del> * Create a new instance of the {@code AnnotationScopeMetadataResolver} class. <del> * @param defaultProxyMode the desired scoped-proxy mode <add> * Construct a new {@code AnnotationScopeMetadataResolver} using the <add> * supplied default {@link ScopedProxyMode}. <add> * @param defaultProxyMode the default scoped-proxy mode <ide> */ <ide> public AnnotationScopeMetadataResolver(ScopedProxyMode defaultProxyMode) { <ide> Assert.notNull(defaultProxyMode, "'defaultProxyMode' must not be null"); <ide> this.defaultProxyMode = defaultProxyMode; <ide> } <ide> <del> <ide> /** <ide> * Set the type of annotation that is checked for by this <del> * {@link AnnotationScopeMetadataResolver}. <add> * {@code AnnotationScopeMetadataResolver}. <ide> * @param scopeAnnotationType the target annotation type <ide> */ <ide> public void setScopeAnnotationType(Class<? extends Annotation> scopeAnnotationType) { <ide> Assert.notNull(scopeAnnotationType, "'scopeAnnotationType' must not be null"); <ide> this.scopeAnnotationType = scopeAnnotationType; <ide> } <ide> <del> <ide> @Override <ide> public ScopeMetadata resolveScopeMetadata(BeanDefinition definition) { <ide> ScopeMetadata metadata = new ScopeMetadata(); <ide> if (definition instanceof AnnotatedBeanDefinition) { <ide> AnnotatedBeanDefinition annDef = (AnnotatedBeanDefinition) definition; <ide> AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(annDef.getMetadata(), this.scopeAnnotationType); <ide> if (attributes != null) { <del> metadata.setScopeName(attributes.getString("value")); <add> metadata.setScopeName(attributes.getAliasedString("value", this.scopeAnnotationType, definition.getSource())); <ide> ScopedProxyMode proxyMode = attributes.getEnum("proxyMode"); <del> if (proxyMode == null || proxyMode == ScopedProxyMode.DEFAULT) { <add> if ((proxyMode == null) || (proxyMode == ScopedProxyMode.DEFAULT)) { <ide> proxyMode = this.defaultProxyMode; <ide> } <ide> metadata.setScopedProxyMode(proxyMode); <ide><path>spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassBeanDefinitionReader.java <ide> * @author Chris Beams <ide> * @author Juergen Hoeller <ide> * @author Phillip Webb <add> * @author Sam Brannen <ide> * @since 3.0 <ide> * @see ConfigurationClassParser <ide> */ <ide> private void loadBeanDefinitionsForBeanMethod(BeanMethod beanMethod) { <ide> <ide> // Consider scoping <ide> ScopedProxyMode proxyMode = ScopedProxyMode.NO; <del> AnnotationAttributes scope = AnnotationConfigUtils.attributesFor(metadata, Scope.class); <del> if (scope != null) { <del> beanDef.setScope(scope.getString("value")); <del> proxyMode = scope.getEnum("proxyMode"); <add> // TODO Determine why type is hard coded to org.springframework.context.annotation.Scope, <add> // since AnnotationScopeMetadataResolver supports a custom scope annotation type. <add> AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(metadata, Scope.class); <add> if (attributes != null) { <add> beanDef.setScope(attributes.getAliasedString("value", Scope.class, configClass.getResource())); <add> proxyMode = attributes.getEnum("proxyMode"); <ide> if (proxyMode == ScopedProxyMode.DEFAULT) { <ide> proxyMode = ScopedProxyMode.NO; <ide> } <ide><path>spring-context/src/main/java/org/springframework/context/annotation/Scope.java <ide> import java.lang.annotation.Target; <ide> <ide> import org.springframework.beans.factory.config.ConfigurableBeanFactory; <add>import org.springframework.core.annotation.AliasFor; <ide> <ide> /** <ide> * When used as a type-level annotation in conjunction with <ide> public @interface Scope { <ide> <ide> /** <del> * Specifies the scope to use for the annotated component/bean. <del> * <p>Defaults to {@link ConfigurableBeanFactory#SCOPE_SINGLETON SCOPE_SINGLETON}. <del> * @see ConfigurableBeanFactory#SCOPE_SINGLETON <add> * Alias for {@link #name}. <add> * @see #name <add> */ <add> @AliasFor(attribute = "name") <add> String value() default ""; <add> <add> /** <add> * Specifies the name of the scope to use for the annotated component/bean. <add> * <p>Defaults to an empty string ({@code ""}) which implies <add> * {@link ConfigurableBeanFactory#SCOPE_SINGLETON SCOPE_SINGLETON}. <add> * @since 4.2 <ide> * @see ConfigurableBeanFactory#SCOPE_PROTOTYPE <add> * @see ConfigurableBeanFactory#SCOPE_SINGLETON <ide> * @see org.springframework.web.context.WebApplicationContext#SCOPE_REQUEST <ide> * @see org.springframework.web.context.WebApplicationContext#SCOPE_SESSION <add> * @see #value <ide> */ <del> String value() default ConfigurableBeanFactory.SCOPE_SINGLETON; <add> @AliasFor(attribute = "value") <add> String name() default ""; <ide> <ide> /** <ide> * Specifies whether a component should be configured as a scoped proxy <ide><path>spring-context/src/test/java/org/springframework/context/annotation/AnnotationScopeMetadataResolverTests.java <ide> /* <del> * Copyright 2002-2014 the original author or authors. <add> * Copyright 2002-2015 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> package org.springframework.context.annotation; <ide> <ide> import java.io.IOException; <del>import java.lang.annotation.ElementType; <ide> import java.lang.annotation.Retention; <ide> import java.lang.annotation.RetentionPolicy; <del>import java.lang.annotation.Target; <ide> <del>import org.junit.Before; <ide> import org.junit.Test; <ide> <ide> import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition; <ide> import org.springframework.core.type.classreading.SimpleMetadataReaderFactory; <ide> <ide> import static org.junit.Assert.*; <add>import static org.springframework.context.annotation.ScopedProxyMode.*; <ide> <ide> /** <add> * Unit tests for {@link AnnotationScopeMetadataResolver}. <add> * <ide> * @author Rick Evans <ide> * @author Chris Beams <ide> * @author Juergen Hoeller <add> * @author Sam Brannen <ide> */ <del>public final class AnnotationScopeMetadataResolverTests { <del> <del> private AnnotationScopeMetadataResolver scopeMetadataResolver; <del> <del> <del> @Before <del> public void setUp() throws Exception { <del> this.scopeMetadataResolver = new AnnotationScopeMetadataResolver(); <del> } <add>public class AnnotationScopeMetadataResolverTests { <ide> <add> private AnnotationScopeMetadataResolver scopeMetadataResolver = new AnnotationScopeMetadataResolver(); <ide> <ide> @Test <del> public void testThatResolveScopeMetadataDoesNotApplyScopedProxyModeToASingleton() { <add> public void resolveScopeMetadataShouldNotApplyScopedProxyModeToSingleton() { <ide> AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition(AnnotatedWithSingletonScope.class); <ide> ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(bd); <ide> assertNotNull("resolveScopeMetadata(..) must *never* return null.", scopeMetadata); <ide> assertEquals(BeanDefinition.SCOPE_SINGLETON, scopeMetadata.getScopeName()); <del> assertEquals(ScopedProxyMode.NO, scopeMetadata.getScopedProxyMode()); <add> assertEquals(NO, scopeMetadata.getScopedProxyMode()); <ide> } <ide> <ide> @Test <del> public void testThatResolveScopeMetadataDoesApplyScopedProxyModeToAPrototype() { <del> this.scopeMetadataResolver = new AnnotationScopeMetadataResolver(ScopedProxyMode.INTERFACES); <add> public void resolveScopeMetadataShouldApplyScopedProxyModeToPrototype() { <add> this.scopeMetadataResolver = new AnnotationScopeMetadataResolver(INTERFACES); <ide> AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition(AnnotatedWithPrototypeScope.class); <ide> ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(bd); <ide> assertNotNull("resolveScopeMetadata(..) must *never* return null.", scopeMetadata); <ide> assertEquals(BeanDefinition.SCOPE_PROTOTYPE, scopeMetadata.getScopeName()); <del> assertEquals(ScopedProxyMode.INTERFACES, scopeMetadata.getScopedProxyMode()); <add> assertEquals(INTERFACES, scopeMetadata.getScopedProxyMode()); <ide> } <ide> <ide> @Test <del> public void testThatResolveScopeMetadataDoesReadScopedProxyModeFromTheAnnotation() { <add> public void resolveScopeMetadataShouldReadScopedProxyModeFromAnnotation() { <ide> this.scopeMetadataResolver = new AnnotationScopeMetadataResolver(); <ide> AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition(AnnotatedWithScopedProxy.class); <ide> ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(bd); <ide> assertNotNull("resolveScopeMetadata(..) must *never* return null.", scopeMetadata); <ide> assertEquals("request", scopeMetadata.getScopeName()); <del> assertEquals(ScopedProxyMode.TARGET_CLASS, scopeMetadata.getScopedProxyMode()); <add> assertEquals(TARGET_CLASS, scopeMetadata.getScopedProxyMode()); <ide> } <ide> <ide> @Test <del> public void testCustomRequestScope() { <add> public void customRequestScope() { <ide> AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition(AnnotatedWithCustomRequestScope.class); <ide> ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(bd); <ide> assertNotNull("resolveScopeMetadata(..) must *never* return null.", scopeMetadata); <ide> assertEquals("request", scopeMetadata.getScopeName()); <del> assertEquals(ScopedProxyMode.NO, scopeMetadata.getScopedProxyMode()); <add> assertEquals(NO, scopeMetadata.getScopedProxyMode()); <ide> } <ide> <ide> @Test <del> public void testCustomRequestScopeViaAsm() throws IOException { <add> public void customRequestScopeViaAsm() throws IOException { <ide> MetadataReaderFactory readerFactory = new SimpleMetadataReaderFactory(); <ide> MetadataReader reader = readerFactory.getMetadataReader(AnnotatedWithCustomRequestScope.class.getName()); <ide> AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition(reader.getAnnotationMetadata()); <ide> ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(bd); <ide> assertNotNull("resolveScopeMetadata(..) must *never* return null.", scopeMetadata); <ide> assertEquals("request", scopeMetadata.getScopeName()); <del> assertEquals(ScopedProxyMode.NO, scopeMetadata.getScopedProxyMode()); <add> assertEquals(NO, scopeMetadata.getScopedProxyMode()); <ide> } <ide> <ide> @Test <del> public void testCustomRequestScopeWithAttribute() { <del> AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition(AnnotatedWithCustomRequestScopeWithAttribute.class); <add> public void customRequestScopeWithAttribute() { <add> AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition( <add> AnnotatedWithCustomRequestScopeWithAttributeOverride.class); <ide> ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(bd); <ide> assertNotNull("resolveScopeMetadata(..) must *never* return null.", scopeMetadata); <ide> assertEquals("request", scopeMetadata.getScopeName()); <del> assertEquals(ScopedProxyMode.TARGET_CLASS, scopeMetadata.getScopedProxyMode()); <add> assertEquals(TARGET_CLASS, scopeMetadata.getScopedProxyMode()); <ide> } <ide> <ide> @Test <del> public void testCustomRequestScopeWithAttributeViaAsm() throws IOException { <add> public void customRequestScopeWithAttributeViaAsm() throws IOException { <ide> MetadataReaderFactory readerFactory = new SimpleMetadataReaderFactory(); <del> MetadataReader reader = readerFactory.getMetadataReader(AnnotatedWithCustomRequestScopeWithAttribute.class.getName()); <add> MetadataReader reader = readerFactory.getMetadataReader(AnnotatedWithCustomRequestScopeWithAttributeOverride.class.getName()); <ide> AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition(reader.getAnnotationMetadata()); <ide> ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(bd); <ide> assertNotNull("resolveScopeMetadata(..) must *never* return null.", scopeMetadata); <ide> assertEquals("request", scopeMetadata.getScopeName()); <del> assertEquals(ScopedProxyMode.TARGET_CLASS, scopeMetadata.getScopedProxyMode()); <add> assertEquals(TARGET_CLASS, scopeMetadata.getScopedProxyMode()); <ide> } <ide> <del> @Test(expected=IllegalArgumentException.class) <del> public void testCtorWithNullScopedProxyMode() { <add> @Test(expected = IllegalArgumentException.class) <add> public void ctorWithNullScopedProxyMode() { <ide> new AnnotationScopeMetadataResolver(null); <ide> } <ide> <del> @Test(expected=IllegalArgumentException.class) <del> public void testSetScopeAnnotationTypeWithNullType() { <add> @Test(expected = IllegalArgumentException.class) <add> public void setScopeAnnotationTypeWithNullType() { <ide> scopeMetadataResolver.setScopeAnnotationType(null); <ide> } <ide> <ide> <del> @Scope("singleton") <del> private static final class AnnotatedWithSingletonScope { <del> } <del> <del> @Scope("prototype") <del> private static final class AnnotatedWithPrototypeScope { <del> } <del> <del> @Scope(value="request", proxyMode = ScopedProxyMode.TARGET_CLASS) <del> private static final class AnnotatedWithScopedProxy { <add> @Retention(RetentionPolicy.RUNTIME) <add> @Scope("request") <add> @interface CustomRequestScope { <ide> } <ide> <del> <del> @Target({ElementType.TYPE, ElementType.METHOD}) <ide> @Retention(RetentionPolicy.RUNTIME) <ide> @Scope("request") <del> public @interface CustomRequestScope { <add> @interface CustomRequestScopeWithAttributeOverride { <add> ScopedProxyMode proxyMode(); <ide> } <ide> <del> @CustomRequestScope <del> private static final class AnnotatedWithCustomRequestScope { <add> @Scope("singleton") <add> private static class AnnotatedWithSingletonScope { <ide> } <ide> <add> @Scope("prototype") <add> private static class AnnotatedWithPrototypeScope { <add> } <ide> <del> @Target({ElementType.TYPE, ElementType.METHOD}) <del> @Retention(RetentionPolicy.RUNTIME) <del> @Scope("request") <del> public @interface CustomRequestScopeWithAttribute { <add> @Scope(name = "request", proxyMode = TARGET_CLASS) <add> private static class AnnotatedWithScopedProxy { <add> } <ide> <del> ScopedProxyMode proxyMode(); <add> @CustomRequestScope <add> private static class AnnotatedWithCustomRequestScope { <ide> } <ide> <del> @CustomRequestScopeWithAttribute(proxyMode = ScopedProxyMode.TARGET_CLASS) <del> private static final class AnnotatedWithCustomRequestScopeWithAttribute { <add> @CustomRequestScopeWithAttributeOverride(proxyMode = TARGET_CLASS) <add> private static class AnnotatedWithCustomRequestScopeWithAttributeOverride { <ide> } <ide> <ide> } <ide><path>spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostProcessorTests.java <ide> public String toString() { <ide> public static class ScopedProxyRepositoryConfiguration { <ide> <ide> @Bean <del> @Scope(value = "prototype", proxyMode = ScopedProxyMode.TARGET_CLASS) <add> @Scope(name = "prototype", proxyMode = ScopedProxyMode.TARGET_CLASS) <ide> public Repository<String> stringRepo() { <ide> return new Repository<String>() { <ide> @Override <ide> public String toString() { <ide> } <ide> <ide> @Bean <del> @Scope(value = "prototype", proxyMode = ScopedProxyMode.TARGET_CLASS) <add> @Scope(name = "prototype", proxyMode = ScopedProxyMode.TARGET_CLASS) <ide> public Repository<Integer> integerRepo() { <ide> return new Repository<Integer>() { <ide> @Override
5
Javascript
Javascript
fix occasional test failures
7038b623e07aa2f4f08a4b6c8115020ee940c57f
<ide><path>run-tests.js <ide> const UNIT_TEST_EXT = '.unit.test.js' <ide> const DEV_TEST_EXT = '.dev.test.js' <ide> const PROD_TEST_EXT = '.prod.test.js' <ide> <add>const NON_CONCURRENT_TESTS = ['test/integration/basic/test/index.test.js'] <add> <ide> // which types we have configured to run separate <ide> const configuredTestTypes = [UNIT_TEST_EXT] <ide> <ide> async function main() { <ide> }) <ide> }) <ide> <add> const nonConcurrentTestNames = [] <add> <add> testNames = testNames.filter((testName) => { <add> if (NON_CONCURRENT_TESTS.includes(testName)) { <add> nonConcurrentTestNames.push(testName) <add> return false <add> } <add> return true <add> }) <add> <add> // run non-concurrent test names separately and before <add> // concurrent ones <add> for (const test of nonConcurrentTestNames) { <add> let passed = false <add> <add> for (let i = 0; i < NUM_RETRIES + 1; i++) { <add> try { <add> const time = await runTest(test, i > 0) <add> timings.push({ <add> file: test, <add> time, <add> }) <add> passed = true <add> break <add> } catch (err) { <add> if (i < NUM_RETRIES) { <add> try { <add> const testDir = path.dirname(path.join(__dirname, test)) <add> console.log('Cleaning test files at', testDir) <add> await exec(`git clean -fdx "${testDir}"`) <add> await exec(`git checkout "${testDir}"`) <add> } catch (err) {} <add> } <add> } <add> } <add> if (!passed) { <add> console.error(`${test} failed to pass within ${NUM_RETRIES} retries`) <add> children.forEach((child) => child.kill()) <add> <add> if (isTestJob) { <add> try { <add> const testsOutput = await fs.readFile(`${test}${RESULTS_EXT}`, 'utf8') <add> console.log( <add> `--test output start--`, <add> testsOutput, <add> `--test output end--` <add> ) <add> } catch (err) { <add> console.log(`Failed to load test output`, err) <add> } <add> } <add> process.exit(1) <add> } <add> } <add> <ide> await Promise.all( <ide> testNames.map(async (test) => { <ide> await sema.acquire() <ide><path>test/integration/rewrite-with-browser-history/test/index.test.js <ide> const runTests = () => { <ide> .click() <ide> .waitForElementByCss('#index') <ide> <del> await browser.back() <add> await browser.back().waitForElementByCss('#another') <ide> <ide> expect(await browser.elementByCss('#another').text()).toBe('another page') <ide>
2
Text
Text
fix typo on api.md
f5c51afd5186b2389250159a333a1160c09aee4b
<ide><path>docs/developers/api.md <ide> To get an item that was clicked on, `getElementsAtEventForMode` can be used. <ide> <ide> ```javascript <ide> function clickHandler(evt) { <del> const points = myChart.getElementAtEventForMode(evt, 'nearest', { intersect: true }, true); <add> const points = myChart.getElementsAtEventForMode(evt, 'nearest', { intersect: true }, true); <ide> <ide> if (points.length) { <ide> const firstPoint = points[0];
1
Javascript
Javascript
add special values to legacy `{{each}}`s' keypath
930513b5c86007baa3e81c4d94f6ea8715a17880
<ide><path>packages/ember-htmlbars/lib/helpers/-legacy-each-with-controller.js <ide> import { get } from "ember-metal/property_get"; <ide> import { forEach } from "ember-metal/enumerable_utils"; <ide> import normalizeSelf from "ember-htmlbars/utils/normalize-self"; <add>import decodeEachKey from "ember-htmlbars/utils/decode-each-key"; <ide> <ide> export default function legacyEachWithControllerHelper(params, hash, blocks) { <ide> var list = params[0]; <ide> export default function legacyEachWithControllerHelper(params, hash, blocks) { <ide> self = bindController(self, true); <ide> } <ide> <del> var key = keyPath ? get(item, keyPath) : String(i); <add> var key = decodeEachKey(item, keyPath, i); <ide> blocks.template.yieldItem(key, [item, i], self); <ide> }); <ide> } <ide><path>packages/ember-htmlbars/lib/helpers/-legacy-each-with-keyword.js <del>import { get } from "ember-metal/property_get"; <ide> import { forEach } from "ember-metal/enumerable_utils"; <ide> import shouldDisplay from "ember-views/streams/should_display"; <add>import decodeEachKey from "ember-htmlbars/utils/decode-each-key"; <ide> <ide> export default function legacyEachWithKeywordHelper(params, hash, blocks) { <ide> var list = params[0]; <ide> export default function legacyEachWithKeywordHelper(params, hash, blocks) { <ide> self = bindKeyword(self, legacyKeyword, item); <ide> } <ide> <del> var key = keyPath ? get(item, keyPath) : String(i); <add> var key = decodeEachKey(item, keyPath, i); <ide> blocks.template.yieldItem(key, [item, i], self); <ide> }); <ide> } else if (blocks.inverse.yield) { <ide><path>packages/ember-htmlbars/lib/helpers/each.js <del>import { get } from "ember-metal/property_get"; <ide> import { forEach } from "ember-metal/enumerable_utils"; <del>import { guidFor } from "ember-metal/utils"; <ide> import normalizeSelf from "ember-htmlbars/utils/normalize-self"; <ide> import shouldDisplay from "ember-views/streams/should_display"; <add>import decodeEachKey from "ember-htmlbars/utils/decode-each-key"; <ide> <ide> /** <ide> The `{{#each}}` helper loops over elements in a collection. It is an extension <ide> export default function eachHelper(params, hash, blocks) { <ide> self = normalizeSelf(item); <ide> } <ide> <del> var key; <del> switch (keyPath) { <del> case '@index': <del> key = i; <del> break; <del> case '@guid': <del> key = guidFor(item); <del> break; <del> case '@item': <del> key = item; <del> break; <del> default: <del> key = keyPath ? get(item, keyPath) : i; <del> } <del> <del> if (typeof key === 'number') { <del> key = String(key); <del> } <del> <add> var key = decodeEachKey(item, keyPath, i); <ide> blocks.template.yieldItem(key, [item, i], self); <ide> }); <ide> } else if (blocks.inverse.yield) { <ide><path>packages/ember-htmlbars/lib/utils/decode-each-key.js <add>import { get } from "ember-metal/property_get"; <add>import { guidFor } from "ember-metal/utils"; <add> <add>export default function decodeEachKey(item, keyPath, index) { <add> var key; <add> <add> switch (keyPath) { <add> case '@index': <add> key = index; <add> break; <add> case '@guid': <add> key = guidFor(item); <add> break; <add> case '@item': <add> key = item; <add> break; <add> default: <add> key = keyPath ? get(item, keyPath) : index; <add> } <add> <add> if (typeof key === 'number') { <add> key = String(key); <add> } <add> <add> return key; <add>}
4
Javascript
Javascript
set listener first, emit 'data' later
45941811dce8988a4cc296436a8843d511ae35af
<ide><path>lib/_stream_readable.js <ide> Readable.prototype.unpipe = function(dest) { <ide> // This is *not* part of the new readable stream interface. <ide> // It is an ugly unfortunate mess of history. <ide> Readable.prototype.on = function(ev, fn) { <add> var res = Stream.prototype.on.call(this, ev, fn); <add> <ide> // https://github.com/isaacs/readable-stream/issues/16 <ide> // if we're already flowing, then no need to set up data events. <ide> if (ev === 'data' && !this._readableState.flowing) <ide> emitDataEvents(this); <ide> <del> return Stream.prototype.on.call(this, ev, fn); <add> return res; <ide> }; <ide> Readable.prototype.addListener = Readable.prototype.on; <ide> <ide><path>test/simple/test-stream2-compatibility.js <add>// Copyright Joyent, Inc. and other Node contributors. <add>// <add>// Permission is hereby granted, free of charge, to any person obtaining a <add>// copy of this software and associated documentation files (the <add>// "Software"), to deal in the Software without restriction, including <add>// without limitation the rights to use, copy, modify, merge, publish, <add>// distribute, sublicense, and/or sell copies of the Software, and to permit <add>// persons to whom the Software is furnished to do so, subject to the <add>// following conditions: <add>// <add>// The above copyright notice and this permission notice shall be included <add>// in all copies or substantial portions of the Software. <add>// <add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS <add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF <add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN <add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, <add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR <add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE <add>// USE OR OTHER DEALINGS IN THE SOFTWARE. <add> <add> <add>var common = require('../common.js'); <add>var R = require('_stream_readable'); <add>var assert = require('assert'); <add> <add>var util = require('util'); <add>var EE = require('events').EventEmitter; <add> <add>var ondataCalled = 0; <add> <add>function TestReader() { <add> R.apply(this); <add> this._buffer = new Buffer(100); <add> this._buffer.fill('x'); <add> <add> this.on('data', function() { <add> ondataCalled++; <add> }); <add>} <add> <add>util.inherits(TestReader, R); <add> <add>TestReader.prototype._read = function(n, cb) { <add> cb(null, this._buffer); <add> this._buffer = new Buffer(0); <add>}; <add> <add>var reader = new TestReader(); <add>assert.equal(ondataCalled, 1);
2
Mixed
Ruby
add missing keys from journey on failed url format
0b6175ac2df96ebfca1baac89c20deaa13e61142
<ide><path>actionpack/CHANGELOG.md <ide> ## Rails 4.0.0 (unreleased) ## <ide> <add>* When building a URL fails, add missing keys provided by Journey. Failed URL <add> generation now returns a 500 status instead of a 404. <add> <add> *Richard Schneeman* <add> <ide> * Deprecate availbility of ActionView::RecordIdentifier in controllers by default. <ide> It's view specific and can be easily included in controller manually if someone <ide> really needs it. RecordIdentifier will be removed from ActionController::Base <ide><path>actionpack/lib/action_controller/metal/exceptions.rb <ide> def initialize(message, failures=[]) <ide> end <ide> end <ide> <add> class ActionController::UrlGenerationError < RoutingError #:nodoc: <add> end <add> <ide> class MethodNotAllowed < ActionControllerError #:nodoc: <ide> def initialize(*allowed_methods) <ide> super("Only #{allowed_methods.to_sentence(:locale => :en)} requests are allowed.") <ide><path>actionpack/lib/action_dispatch/routing/route_set.rb <ide> def generate <ide> return [path, params.keys] if @extras <ide> <ide> [path, params] <del> rescue Journey::Router::RoutingError <del> raise_routing_error <add> rescue Journey::Router::RoutingError => e <add> raise_routing_error(e.message) <ide> end <ide> <del> def raise_routing_error <del> raise ActionController::RoutingError, "No route matches #{options.inspect}" <add> def raise_routing_error(message) <add> raise ActionController::UrlGenerationError, "No route matches #{options.inspect} #{message}" <ide> end <ide> <ide> def different_controller? <ide><path>actionpack/test/controller/routing_test.rb <ide> def test_specific_controller_action_failure <ide> mount lambda {} => "/foo" <ide> end <ide> <del> assert_raises(ActionController::RoutingError) do <add> assert_raises(ActionController::UrlGenerationError) do <ide> url_for(rs, :controller => "omg", :action => "lol") <ide> end <ide> end <ide> def test_should_list_options_diff_when_routing_constraints_dont_match <ide> rs.draw do <ide> get 'post/:id' => 'post#show', :constraints => { :id => /\d+/ }, :as => 'post' <ide> end <del> assert_raise(ActionController::RoutingError) do <add> assert_raise(ActionController::UrlGenerationError) do <ide> url_for(rs, { :controller => 'post', :action => 'show', :bad_param => "foo", :use_route => "post" }) <ide> end <ide> end <ide> def test_requirement_should_prevent_optional_id <ide> <ide> assert_equal '/post/10', url_for(rs, { :controller => 'post', :action => 'show', :id => 10 }) <ide> <del> assert_raise ActionController::RoutingError do <add> assert_raise(ActionController::UrlGenerationError) do <ide> url_for(rs, { :controller => 'post', :action => 'show' }) <ide> end <ide> end <ide> def test_failed_constraints_raises_exception_with_violated_constraints <ide> get 'foos/:id' => 'foos#show', :as => 'foo_with_requirement', :constraints => { :id => /\d+/ } <ide> end <ide> <del> assert_raise(ActionController::RoutingError) do <add> assert_raise(ActionController::UrlGenerationError) do <ide> setup_for_named_route.send(:foo_with_requirement_url, "I am Against the constraints") <ide> end <ide> end <ide> def test_route_error_with_missing_controller <ide> set.draw do <ide> get "/people" => "missing#index" <ide> end <del> <add> <ide> assert_raise(ActionController::RoutingError) { <ide> set.recognize_path("/people", :method => :get) <ide> } <ide> def test_route_requirement_generate_with_ignore_case <ide> <ide> url = url_for(set, { :controller => 'pages', :action => 'show', :name => 'david' }) <ide> assert_equal "/page/david", url <del> assert_raise ActionController::RoutingError do <add> assert_raise(ActionController::UrlGenerationError) do <ide> url_for(set, { :controller => 'pages', :action => 'show', :name => 'davidjamis' }) <ide> end <ide> url = url_for(set, { :controller => 'pages', :action => 'show', :name => 'JAMIS' }) <ide><path>actionpack/test/dispatch/debug_exceptions_test.rb <ide> def call(env) <ide> raise ActionView::Template::Error.new('template', AbstractController::ActionNotFound.new) <ide> when "/bad_request" <ide> raise ActionController::BadRequest <add> when "/missing_keys" <add> raise ActionController::UrlGenerationError, "No route matches" <ide> else <ide> raise "puke!" <ide> end <ide> def call(env) <ide> assert_match(/AbstractController::ActionNotFound/, body) <ide> end <ide> <add> test "named urls missing keys raise 500 level error" do <add> @app = DevelopmentApp <add> <add> get "/missing_keys", {}, {'action_dispatch.show_exceptions' => true} <add> assert_response 500 <add> <add> assert_match(/ActionController::UrlGenerationError/, body) <add> end <add> <ide> test "show the controller name in the diagnostics template when controller name is present" do <ide> @app = DevelopmentApp <ide> get("/runtime_error", {}, { <ide><path>actionpack/test/dispatch/routing_test.rb <ide> def test_constraints_are_merged_from_scope <ide> <ide> get '/movies/00001' <ide> assert_equal 'Not Found', @response.body <del> assert_raises(ActionController::RoutingError){ movie_path(:id => '00001') } <add> assert_raises(ActionController::UrlGenerationError){ movie_path(:id => '00001') } <ide> <ide> get '/movies/0001/reviews' <ide> assert_equal 'reviews#index', @response.body <ide> assert_equal '/movies/0001/reviews', movie_reviews_path(:movie_id => '0001') <ide> <ide> get '/movies/00001/reviews' <ide> assert_equal 'Not Found', @response.body <del> assert_raises(ActionController::RoutingError){ movie_reviews_path(:movie_id => '00001') } <add> assert_raises(ActionController::UrlGenerationError){ movie_reviews_path(:movie_id => '00001') } <ide> <ide> get '/movies/0001/reviews/0001' <ide> assert_equal 'reviews#show', @response.body <ide> assert_equal '/movies/0001/reviews/0001', movie_review_path(:movie_id => '0001', :id => '0001') <ide> <ide> get '/movies/00001/reviews/0001' <ide> assert_equal 'Not Found', @response.body <del> assert_raises(ActionController::RoutingError){ movie_path(:movie_id => '00001', :id => '00001') } <add> assert_raises(ActionController::UrlGenerationError){ movie_path(:movie_id => '00001', :id => '00001') } <ide> <ide> get '/movies/0001/trailer' <ide> assert_equal 'trailers#show', @response.body <ide> assert_equal '/movies/0001/trailer', movie_trailer_path(:movie_id => '0001') <ide> <ide> get '/movies/00001/trailer' <ide> assert_equal 'Not Found', @response.body <del> assert_raises(ActionController::RoutingError){ movie_trailer_path(:movie_id => '00001') } <add> assert_raises(ActionController::UrlGenerationError){ movie_trailer_path(:movie_id => '00001') } <ide> end <ide> <ide> def test_only_should_be_read_from_scope <ide> def test_nested_resource_constraints <ide> <ide> get '/lists/2/todos/1' <ide> assert_equal 'Not Found', @response.body <del> assert_raises(ActionController::RoutingError){ list_todo_path(:list_id => '2', :id => '1') } <add> assert_raises(ActionController::UrlGenerationError){ list_todo_path(:list_id => '2', :id => '1') } <ide> end <ide> <ide> def test_named_routes_collision_is_avoided_unless_explicitly_given_as <ide> def app; Routes end <ide> <ide> get "/categories/1" <ide> assert_response :success <del> assert_raises(ActionController::RoutingError) { product_path(nil) } <add> assert_raises(ActionController::UrlGenerationError) { product_path(nil) } <ide> end <ide> end <ide>
6
Ruby
Ruby
fix github & gitlab url processing
74fd700445c94b76a72fc67452fec934645e0389
<ide><path>Library/Homebrew/livecheck/livecheck.rb <ide> module Homebrew <ide> module Livecheck <ide> module_function <ide> <add> GITEA_INSTANCES = %w[ <add> codeberg.org <add> gitea.com <add> opendev.org <add> tildegit.org <add> ].freeze <add> <add> GOGS_INSTANCES = %w[ <add> lolg.it <add> ].freeze <add> <ide> UNSTABLE_VERSION_KEYWORDS = %w[ <ide> alpha <ide> beta <ide> def checkable_urls(formula) <ide> # @return [String] <ide> def preprocess_url(url) <ide> uri = URI.parse url <del> host = uri.host <add> host = uri.host == "github.s3.amazonaws.com" ? "github.com" : uri.host <ide> path = uri.path.delete_prefix("/").delete_suffix(".git") <add> scheme = uri.scheme <ide> <del> if host == "github.s3.amazonaws.com" <del> owner, repo = path.sub(%r{^downloads/}, "").split("/") <del> return "https://github.com/#{owner}/#{repo}.git" <del> end <add> if host == "github.com" <add> return url if path.match? %r{/releases/latest/?$} <ide> <del> if ["github.com", "tildegit.org", "gitlab.com"].include? host <add> owner, repo = path.delete_prefix("downloads/").split("/") <add> url = "#{scheme}://#{host}/#{owner}/#{repo}.git" <add> elsif GITEA_INSTANCES.include? host <ide> return url if path.match? %r{/releases/latest/?$} <ide> <ide> owner, repo = path.split("/") <del> url = "https://#{host}/#{owner}/#{repo}.git" <add> url = "#{scheme}://#{host}/#{owner}/#{repo}.git" <add> elsif GOGS_INSTANCES.include? host <add> owner, repo = path.split("/") <add> url = "#{scheme}://#{host}/#{owner}/#{repo}.git" <add> # sourcehut <ide> elsif host == "git.sr.ht" <ide> owner, repo = path.split("/") <del> url = "https://#{host}/#{owner}/#{repo}" <add> url = "#{scheme}://#{host}/#{owner}/#{repo}" <add> # gitlab <add> elsif path.include?("/-/archive/") <add> url = url.sub(%r{/-/archive/.*$}i, ".git") <ide> end <ide> <ide> url
1
PHP
PHP
fix flash handling to be vastly simpler
a761f383373db8863a4f5a93673ad8bd6cf60be7
<ide><path>src/Illuminate/Session/FlashBag.php <del><?php namespace Illuminate\Session; <del> <del>/* <del> * This file is part of the Symfony package. <del> * <del> * (c) Fabien Potencier <fabien@symfony.com> <del> * <del> * For the full copyright and license information, please view the LICENSE <del> * file that was distributed with this source code. <del> * <del> * ADDITIONS (@taylorotwell): "peek" function now will return values from "display" and "new". <del> */ <del> <del>use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface; <del> <del>/** <del> * AutoExpireFlashBag flash message container. <del> * <del> * @author Drak <drak@zikula.org> <del> */ <del>class FlashBag implements FlashBagInterface <del>{ <del> private $name = 'flashes'; <del> <del> /** <del> * Flash messages. <del> * <del> * @var array <del> */ <del> private $flashes = array(); <del> <del> /** <del> * The storage key for flashes in the session <del> * <del> * @var string <del> */ <del> private $storageKey; <del> <del> /** <del> * Constructor. <del> * <del> * @param string $storageKey The key used to store flashes in the session. <del> */ <del> public function __construct($storageKey = '_sf2_flashes') <del> { <del> $this->storageKey = $storageKey; <del> $this->flashes = array('display' => array(), 'new' => array()); <del> } <del> <del> /** <del> * {@inheritdoc} <del> */ <del> public function getName() <del> { <del> return $this->name; <del> } <del> <del> public function setName($name) <del> { <del> $this->name = $name; <del> } <del> <del> /** <del> * {@inheritdoc} <del> */ <del> public function initialize(array &$flashes) <del> { <del> $this->flashes = &$flashes; <del> <del> // The logic: messages from the last request will be stored in new, so we move them to previous <del> // This request we will show what is in 'display'. What is placed into 'new' this time round will <del> // be moved to display next time round. <del> $this->flashes['display'] = array_key_exists('new', $this->flashes) ? $this->flashes['new'] : array(); <del> $this->flashes['new'] = array(); <del> } <del> <del> /** <del> * {@inheritdoc} <del> */ <del> public function add($type, $message) <del> { <del> $this->flashes['new'][$type][] = $message; <del> } <del> <del> /** <del> * {@inheritdoc} <del> */ <del> public function peek($type, array $default = array()) <del> { <del> $value = $this->has($type) ? $this->flashes['display'][$type] : $default; <del> <del> return $value ?: $this->peekNew($type, $default); <del> } <del> <del> /** <del> * Peek a "new" value from the flash bag. <del> * <del> * @param string $type <del> * @param array $default <del> * @return array <del> */ <del> public function peekNew($type, array $default = array()) <del> { <del> return $this->hasNew($type) ? $this->flashes['new'][$type] : $default; <del> } <del> <del> /** <del> * {@inheritdoc} <del> */ <del> public function peekAll() <del> { <del> return array_key_exists('display', $this->flashes) ? (array) $this->flashes['display'] : array(); <del> } <del> <del> /** <del> * {@inheritdoc} <del> */ <del> public function get($type, array $default = array()) <del> { <del> $return = $default; <del> <del> if (!$this->has($type)) { <del> return $return; <del> } <del> <del> if (isset($this->flashes['display'][$type])) { <del> $return = $this->flashes['display'][$type]; <del> unset($this->flashes['display'][$type]); <del> } <del> <del> return $return; <del> } <del> <del> /** <del> * {@inheritdoc} <del> */ <del> public function all() <del> { <del> $return = array_merge($this->flashes['display'], $this->flashes['new']); <del> $this->flashes = array('new' => array(), 'display' => array()); <del> <del> return $return; <del> } <del> <del> /** <del> * {@inheritdoc} <del> */ <del> public function setAll(array $messages) <del> { <del> $this->flashes['new'] = $messages; <del> } <del> <del> /** <del> * {@inheritdoc} <del> */ <del> public function set($type, $messages) <del> { <del> $this->flashes['new'][$type] = is_object($messages) ? array($messages) : (array) $messages; <del> } <del> <del> /** <del> * {@inheritdoc} <del> */ <del> public function has($type) <del> { <del> return array_key_exists($type, $this->flashes['display']) && $this->flashes['display'][$type]; <del> } <del> <del> /** <del> * Determine if the flash has a "new" item. <del> * <del> * @param string $type <del> * @return bool <del> */ <del> public function hasNew($type) <del> { <del> return array_key_exists($type, $this->flashes['new']) && $this->flashes['new'][$type]; <del> } <del> <del> /** <del> * {@inheritdoc} <del> */ <del> public function keys() <del> { <del> return array_keys($this->flashes['display']); <del> } <del> <del> /** <del> * {@inheritdoc} <del> */ <del> public function getStorageKey() <del> { <del> return $this->storageKey; <del> } <del> <del> /** <del> * {@inheritdoc} <del> */ <del> public function clear() <del> { <del> return $this->all(); <del> } <del>} <ide><path>src/Illuminate/Session/SessionManager.php <ide> protected function callCustomCreator($driver) <ide> */ <ide> protected function createArrayDriver() <ide> { <del> return new Store(new MockArraySessionStorage, null, new FlashBag); <add> return new Store(new MockArraySessionStorage); <ide> } <ide> <ide> /** <ide> protected function createCacheBased($driver) <ide> */ <ide> protected function buildSession($handler) <ide> { <del> $storage = new NativeSessionStorage($this->getOptions(), $handler); <del> <del> return new Store($storage, null, new FlashBag); <add> return new Store(new NativeSessionStorage($this->getOptions(), $handler)); <ide> } <ide> <ide> /** <ide><path>src/Illuminate/Session/Store.php <ide> public function start() <ide> /** <ide> * {@inheritdoc} <ide> */ <del> public function has($name) <add> public function save() <ide> { <del> return parent::has($name) or $this->hasFlash($name); <add> $this->ageFlashData(); <add> <add> return parent::save(); <ide> } <ide> <ide> /** <del> * {@inheritdoc} <add> * Age the flash data for the session. <add> * <add> * @return void <ide> */ <del> public function get($name, $default = null) <add> protected function ageFlashData() <ide> { <del> if ( ! is_null($value = parent::get($name))) return $value; <add> foreach ($this->get('flash.old', array()) as $old) { $this->forget($old); } <add> <add> $this->put('flash.old', $this->get('flash.new')); <ide> <del> return $this->getFlash($name, $default); <add> $this->put('flash.new', array()); <ide> } <ide> <ide> /** <del> * Determine if the session has a flash item. <del> * <del> * @param string $name <del> * @return bool <add> * {@inheritdoc} <ide> */ <del> public function hasFlash($name) <add> public function get($name, $default = null) <ide> { <del> return ! is_null($this->getFlash($name)); <add> return parent::get($name) ?: value($default); <ide> } <ide> <ide> /** <del> * Get an item from the flashed session data. <add> * Determine if the session has a flash item. <ide> * <ide> * @param string $name <del> * @param mixed $default <del> * @return mixed <add> * @return bool <ide> */ <del> public function getFlash($name, $default = null) <add> public function hasFlash($name) <ide> { <del> $value = $this->getFlashBag()->peek($name); <del> <del> return count($value) > 0 ? $value[0] : value($default); <add> return $this->has($name); <ide> } <ide> <ide> /** <ide> public function put($key, $value) <ide> } <ide> <ide> /** <del> * Flash a key / value pair to the session. <add> * Push a value onto a session array. <ide> * <ide> * @param string $key <ide> * @param mixed $value <ide> * @return void <ide> */ <del> public function flash($key, $value) <add> public function push($key, $value) <ide> { <del> $this->getFlashBag()->set($key, $value); <del> } <add> $array = $this->get($key, array()); <ide> <del> /** <del> * Flash an input array to the session. <del> * <del> * @param array $value <del> * @return void <del> */ <del> public function flashInput(array $value) <del> { <del> return $this->flash('_old_input', $value); <add> $array[] = $value; <add> <add> $this->put($key, $array); <ide> } <ide> <ide> /** <del> * Keep all of the session flash data from expiring. <add> * Flash a key / value pair to the session. <ide> * <add> * @param string $key <add> * @param mixed $value <ide> * @return void <ide> */ <del> public function reflash() <add> public function flash($key, $value) <ide> { <del> foreach ($this->getFlashBag()->peekAll() as $key => $value) <del> { <del> $this->getFlashBag()->set($key, $value); <del> } <add> $this->put($key, $value); <add> <add> $this->push('flash.new', $key); <ide> } <ide> <ide> /** <del> * Keep a session flash item from expiring. <add> * Flash an input array to the session. <ide> * <del> * @param string|array $keys <add> * @param array $value <ide> * @return void <ide> */ <del> public function keep($keys) <add> public function flashInput(array $value) <ide> { <del> foreach (array_only($this->getFlashBag()->peekAll(), $keys) as $key => $value) <del> { <del> $this->getFlashBag()->set($key, $value); <del> } <add> return $this->flash('_old_input', $value); <ide> } <ide> <ide> /** <ide><path>tests/Session/SessionStoreTest.php <del><?php <del> <del>use Mockery as m; <del> <del>class SessionStoreTest extends PHPUnit_Framework_TestCase { <del> <del> public function tearDown() <del> { <del> m::close(); <del> } <del> <del> <del> public function testFlashBagReturnsItemsCorrectly() <del> { <del> $flash = new Illuminate\Session\FlashBag; <del> $data = array('new' => array('name' => array('Taylor')), 'display' => array('foo' => array('bar'))); <del> $flash->initialize($data); <del> <del> $this->assertEquals(array('Taylor'), $flash->get('name')); <del> } <del> <del> <del> public function testPeekNewReturnsValuesFromNew() <del> { <del> $flash = new Illuminate\Session\FlashBag; <del> $data = array('new' => array('name' => array('Taylor')), 'display' => array('foo' => array('bar'))); <del> $flash->initialize($data); <del> $flash->set('age', 25); <del> <del> $this->assertEquals(array(25), $flash->peek('age')); <del> $this->assertEquals(array(25), $flash->peekNew('age')); <del> $this->assertTrue($flash->hasNew('age')); <del> } <del> <del>} <ide>\ No newline at end of file
4
PHP
PHP
wrap long lines and fix incorrect assertions
fad068d84552c95bd1079dd825f6953ff2293f82
<ide><path>tests/TestCase/ORM/AssociationTest.php <ide> public function testTargetPlugin() <ide> $table = $this->association->target(); <ide> $this->assertInstanceOf('TestPlugin\Model\Table\CommentsTable', $table); <ide> <del> $this->assertTrue(TableRegistry::exists('TestPlugin.ThisAssociationName'), 'The association class will use this registry key'); <del> $this->assertFalse(TableRegistry::exists('TestPlugin.Comments', 'The association clas will NOT use this key')); <del> $this->assertFalse(TableRegistry::exists('Comments', 'Should also not be set')); <del> $this->assertFalse(TableRegistry::exists('ThisAssociationName', 'Should also not be set')); <add> $this->assertTrue( <add> TableRegistry::exists('TestPlugin.ThisAssociationName'), <add> 'The association class will use this registry key' <add> ); <add> $this->assertFalse(TableRegistry::exists('TestPlugin.Comments'), 'The association class will NOT use this key'); <add> $this->assertFalse(TableRegistry::exists('Comments'), 'Should also not be set'); <add> $this->assertFalse(TableRegistry::exists('ThisAssociationName'), 'Should also not be set'); <ide> <ide> $plugin = TableRegistry::get('TestPlugin.ThisAssociationName'); <ide> $this->assertSame($table, $plugin, 'Should be an instance of TestPlugin.Comments');
1
Go
Go
remove unnecessary line
145dfd924c8489cb2099bc1a86a01cd1fff19b70
<ide><path>plugin/backend_linux.go <ide> func (pm *Manager) Upgrade(ctx context.Context, ref reference.Named, name string <ide> defer pm.muGC.RUnlock() <ide> <ide> // revalidate because Pull is public <del> nameref, err := reference.ParseNormalizedNamed(name) <del> if err != nil { <add> if _, err := reference.ParseNormalizedNamed(name); err != nil { <ide> return errors.Wrapf(err, "failed to parse %q", name) <ide> } <del> name = reference.FamiliarString(reference.TagNameOnly(nameref)) <ide> <ide> tmpRootFSDir, err := ioutil.TempDir(pm.tmpDir(), ".rootfs") <ide> if err != nil {
1
Go
Go
remove unnecessary string formats
23ac56fdd0edf55b1bd8d90e4774a10975384571
<ide><path>libnetwork/api/api_test.go <ide> func TestSandboxOptionParser(t *testing.T) { <ide> } <ide> <ide> if len(sb.parseOptions()) != 9 { <del> t.Fatalf("Failed to generate all libnetwork.SandboxOption methods") <add> t.Fatal("Failed to generate all libnetwork.SandboxOption methods") <ide> } <ide> } <ide> <ide> func TestCreateDeleteNetwork(t *testing.T) { <ide> vars := make(map[string]string) <ide> _, errRsp := procCreateNetwork(c, nil, badBody) <ide> if errRsp == &createdResponse { <del> t.Fatalf("Expected to fail but succeeded") <add> t.Fatal("Expected to fail but succeeded") <ide> } <ide> if errRsp.StatusCode != http.StatusBadRequest { <ide> t.Fatalf("Expected StatusBadRequest status code, got: %v", errRsp) <ide> func TestCreateDeleteNetwork(t *testing.T) { <ide> <ide> _, errRsp = procCreateNetwork(c, vars, incompleteBody) <ide> if errRsp == &createdResponse { <del> t.Fatalf("Expected to fail but succeeded") <add> t.Fatal("Expected to fail but succeeded") <ide> } <ide> if errRsp.StatusCode != http.StatusBadRequest { <ide> t.Fatalf("Expected StatusBadRequest status code, got: %v", errRsp) <ide> func TestCreateDeleteNetwork(t *testing.T) { <ide> vars[urlNwName] = "" <ide> _, errRsp = procDeleteNetwork(c, vars, nil) <ide> if errRsp == &successResponse { <del> t.Fatalf("Expected to fail but succeeded") <add> t.Fatal("Expected to fail but succeeded") <ide> } <ide> <ide> vars[urlNwName] = "abc" <ide> _, errRsp = procDeleteNetwork(c, vars, nil) <ide> if errRsp == &successResponse { <del> t.Fatalf("Expected to fail but succeeded") <add> t.Fatal("Expected to fail but succeeded") <ide> } <ide> <ide> vars[urlNwName] = "network_1" <ide> func TestGetNetworksAndEndpoints(t *testing.T) { <ide> t.Fatalf("Did not return the expected number (2) of endpoint resources: %d", len(epList)) <ide> } <ide> if "sh" != epList[0].Network || "sh" != epList[1].Network { <del> t.Fatalf("Did not find expected network name in endpoint resources") <add> t.Fatal("Did not find expected network name in endpoint resources") <ide> } <ide> <ide> vars = make(map[string]string) <ide> func TestGetNetworksAndEndpoints(t *testing.T) { <ide> } <ide> netList := i2nL(iList) <ide> if len(netList) != 1 { <del> t.Fatalf("Did not return the expected number of network resources") <add> t.Fatal("Did not return the expected number of network resources") <ide> } <ide> if nid != netList[0].ID { <ide> t.Fatalf("Did not find expected network %s: %v", nid, netList) <ide> func TestGetNetworksAndEndpoints(t *testing.T) { <ide> } <ide> netList = i2nL(iList) <ide> if len(netList) != 0 { <del> t.Fatalf("Did not return the expected number of network resources") <add> t.Fatal("Did not return the expected number of network resources") <ide> } <ide> } <ide> <ide> func TestProcGetService(t *testing.T) { <ide> vars := map[string]string{urlEpID: ""} <ide> _, errRsp := procGetService(c, vars, nil) <ide> if errRsp.isOK() { <del> t.Fatalf("Expected failure, but succeeded") <add> t.Fatal("Expected failure, but succeeded") <ide> } <ide> if errRsp.StatusCode != http.StatusBadRequest { <ide> t.Fatalf("Expected %d, but got: %d", http.StatusBadRequest, errRsp.StatusCode) <ide> func TestProcGetService(t *testing.T) { <ide> vars[urlEpID] = "unknown-service-id" <ide> _, errRsp = procGetService(c, vars, nil) <ide> if errRsp.isOK() { <del> t.Fatalf("Expected failure, but succeeded") <add> t.Fatal("Expected failure, but succeeded") <ide> } <ide> if errRsp.StatusCode != http.StatusNotFound { <ide> t.Fatalf("Expected %d, but got: %d. (%v)", http.StatusNotFound, errRsp.StatusCode, errRsp) <ide> func TestProcPublishUnpublishService(t *testing.T) { <ide> } <ide> _, errRsp := procPublishService(c, vars, vbad) <ide> if errRsp == &createdResponse { <del> t.Fatalf("Expected to fail but succeeded") <add> t.Fatal("Expected to fail but succeeded") <ide> } <ide> if errRsp.StatusCode != http.StatusBadRequest { <ide> t.Fatalf("Expected %d. Got: %v", http.StatusBadRequest, errRsp) <ide> func TestProcPublishUnpublishService(t *testing.T) { <ide> } <ide> _, errRsp = procPublishService(c, vars, b) <ide> if errRsp == &createdResponse { <del> t.Fatalf("Expected to fail but succeeded") <add> t.Fatal("Expected to fail but succeeded") <ide> } <ide> if errRsp.StatusCode != http.StatusBadRequest { <ide> t.Fatalf("Expected %d. Got: %v", http.StatusBadRequest, errRsp) <ide> func TestProcPublishUnpublishService(t *testing.T) { <ide> } <ide> _, errRsp = procPublishService(c, vars, b) <ide> if errRsp == &createdResponse { <del> t.Fatalf("Expected to fail but succeeded") <add> t.Fatal("Expected to fail but succeeded") <ide> } <ide> if errRsp.StatusCode != http.StatusBadRequest { <ide> t.Fatalf("Expected %d. Got: %v", http.StatusBadRequest, errRsp) <ide> func TestProcPublishUnpublishService(t *testing.T) { <ide> } <ide> _, errRsp = procPublishService(c, vars, b) <ide> if errRsp == &createdResponse { <del> t.Fatalf("Expected to fail but succeeded") <add> t.Fatal("Expected to fail but succeeded") <ide> } <ide> if errRsp.StatusCode != http.StatusNotFound { <ide> t.Fatalf("Expected %d. Got: %v", http.StatusNotFound, errRsp) <ide> func TestProcPublishUnpublishService(t *testing.T) { <ide> } <ide> _, errRsp = procPublishService(c, vars, b) <ide> if errRsp == &createdResponse { <del> t.Fatalf("Expected to fail but succeeded") <add> t.Fatal("Expected to fail but succeeded") <ide> } <ide> if errRsp.StatusCode != http.StatusBadRequest { <ide> t.Fatalf("Expected %d. Got: %v", http.StatusBadRequest, errRsp) <ide> func TestProcPublishUnpublishService(t *testing.T) { <ide> vars[urlEpID] = "" <ide> _, errRsp = procUnpublishService(c, vars, nil) <ide> if errRsp.isOK() { <del> t.Fatalf("Expected failure but succeeded") <add> t.Fatal("Expected failure but succeeded") <ide> } <ide> if errRsp.StatusCode != http.StatusBadRequest { <ide> t.Fatalf("Expected %d. Got: %v", http.StatusBadRequest, errRsp) <ide> func TestProcPublishUnpublishService(t *testing.T) { <ide> vars[urlEpID] = "unknown-service-id" <ide> _, errRsp = procUnpublishService(c, vars, nil) <ide> if errRsp.isOK() { <del> t.Fatalf("Expected failure but succeeded") <add> t.Fatal("Expected failure but succeeded") <ide> } <ide> if errRsp.StatusCode != http.StatusNotFound { <ide> t.Fatalf("Expected %d. Got: %v", http.StatusNotFound, errRsp) <ide> func TestProcPublishUnpublishService(t *testing.T) { <ide> <ide> _, errRsp = procGetService(c, vars, nil) <ide> if errRsp.isOK() { <del> t.Fatalf("Expected failure, but succeeded") <add> t.Fatal("Expected failure, but succeeded") <ide> } <ide> if errRsp.StatusCode != http.StatusNotFound { <ide> t.Fatalf("Expected %d, but got: %d. (%v)", http.StatusNotFound, errRsp.StatusCode, errRsp) <ide> func TestAttachDetachBackend(t *testing.T) { <ide> <ide> _, errRsp = procUnpublishService(c, vars, nil) <ide> if errRsp.isOK() { <del> t.Fatalf("Expected failure but succeeded") <add> t.Fatal("Expected failure but succeeded") <ide> } <ide> if errRsp.StatusCode != http.StatusForbidden { <ide> t.Fatalf("Expected %d. Got: %v", http.StatusForbidden, errRsp) <ide> func TestFindNetworkUtil(t *testing.T) { <ide> <ide> _, errRsp := findNetwork(c, "", byName) <ide> if errRsp == &successResponse { <del> t.Fatalf("Expected to fail but succeeded") <add> t.Fatal("Expected to fail but succeeded") <ide> } <ide> if errRsp.StatusCode != http.StatusBadRequest { <ide> t.Fatalf("Expected %d, but got: %d", http.StatusBadRequest, errRsp.StatusCode) <ide> func TestFindNetworkUtil(t *testing.T) { <ide> t.Fatalf("Unexpected failure: %v", errRsp) <ide> } <ide> if n == nil { <del> t.Fatalf("Unexpected nil libnetwork.Network") <add> t.Fatal("Unexpected nil libnetwork.Network") <ide> } <ide> if nid != n.ID() { <ide> t.Fatalf("Incorrect libnetwork.Network resource. It has different id: %v", n) <ide> func TestFindNetworkUtil(t *testing.T) { <ide> t.Fatalf("Unexpected failure: %v", errRsp) <ide> } <ide> if n == nil { <del> t.Fatalf("Unexpected nil libnetwork.Network") <add> t.Fatal("Unexpected nil libnetwork.Network") <ide> } <ide> if nid != n.ID() { <ide> t.Fatalf("Incorrect libnetwork.Network resource. It has different id: %v", n) <ide> func TestFindNetworkUtil(t *testing.T) { <ide> <ide> _, errRsp = findNetwork(c, nid, byID) <ide> if errRsp == &successResponse { <del> t.Fatalf("Expected to fail but succeeded") <add> t.Fatal("Expected to fail but succeeded") <ide> } <ide> if errRsp.StatusCode != http.StatusNotFound { <ide> t.Fatalf("Expected %d, but got: %d", http.StatusNotFound, errRsp.StatusCode) <ide> } <ide> <ide> _, errRsp = findNetwork(c, "network", byName) <ide> if errRsp == &successResponse { <del> t.Fatalf("Expected to fail but succeeded") <add> t.Fatal("Expected to fail but succeeded") <ide> } <ide> if errRsp.StatusCode != http.StatusNotFound { <ide> t.Fatalf("Expected %d, but got: %d", http.StatusNotFound, errRsp.StatusCode) <ide> func TestCreateDeleteEndpoints(t *testing.T) { <ide> vars[urlNwName] = "firstNet" <ide> _, errRsp = procCreateEndpoint(c, vars, vbad) <ide> if errRsp == &createdResponse { <del> t.Fatalf("Expected to fail but succeeded") <add> t.Fatal("Expected to fail but succeeded") <ide> } <ide> <ide> b, err := json.Marshal(endpointCreate{Name: ""}) <ide> func TestCreateDeleteEndpoints(t *testing.T) { <ide> vars[urlNwName] = "secondNet" <ide> _, errRsp = procCreateEndpoint(c, vars, b) <ide> if errRsp == &createdResponse { <del> t.Fatalf("Expected to fail but succeeded") <add> t.Fatal("Expected to fail but succeeded") <ide> } <ide> <ide> vars[urlNwName] = "firstNet" <ide> func TestJoinLeave(t *testing.T) { <ide> <ide> keyStr := i2s(key) <ide> if keyStr == "" { <del> t.Fatalf("Empty sandbox key") <add> t.Fatal("Empty sandbox key") <ide> } <ide> _, errRsp = procDeleteEndpoint(c, vars, nil) <ide> if errRsp == &successResponse { <ide> func TestFindEndpointUtil(t *testing.T) { <ide> <ide> if ep0.ID() != ep1.ID() || ep0.ID() != ep2.ID() || <ide> ep0.ID() != ep3.ID() || ep0.ID() != ep4.ID() || ep0.ID() != ep5.ID() { <del> t.Fatalf("Diffenrent queries returned different endpoints") <add> t.Fatal("Diffenrent queries returned different endpoints") <ide> } <ide> <ide> ep.Delete(false) <ide> func checkPanic(t *testing.T) { <ide> panic(r) <ide> } <ide> } else { <del> t.Fatalf("Expected to panic, but succeeded") <add> t.Fatal("Expected to panic, but succeeded") <ide> } <ide> } <ide> <ide> func TestResponseStatus(t *testing.T) { <ide> <ide> r := responseStatus{StatusCode: http.StatusOK} <ide> if !r.isOK() { <del> t.Fatalf("isOK() failed") <add> t.Fatal("isOK() failed") <ide> } <ide> <ide> r = responseStatus{StatusCode: http.StatusCreated} <ide> if !r.isOK() { <del> t.Fatalf("isOK() failed") <add> t.Fatal("isOK() failed") <ide> } <ide> } <ide> <ide> func (l *localReader) Read(p []byte) (n int, err error) { <ide> return 0, errors.New("I am a bad reader") <ide> } <ide> if p == nil { <del> return -1, fmt.Errorf("nil buffer passed") <add> return -1, errors.New("nil buffer passed") <ide> } <ide> if l.data == nil || len(l.data) == 0 { <ide> return 0, io.EOF <ide> func (f *localResponseWriter) Header() http.Header { <ide> <ide> func (f *localResponseWriter) Write(data []byte) (int, error) { <ide> if data == nil { <del> return -1, fmt.Errorf("nil data passed") <add> return -1, errors.New("nil data passed") <ide> } <ide> <ide> f.body = make([]byte, len(data)) <ide> func TestHttpHandlerUninit(t *testing.T) { <ide> h := &httpHandler{c: c} <ide> h.initRouter() <ide> if h.r == nil { <del> t.Fatalf("initRouter() did not initialize the router") <add> t.Fatal("initRouter() did not initialize the router") <ide> } <ide> <ide> rsp := newWriter() <ide> func TestHttpHandlerUninit(t *testing.T) { <ide> t.Fatalf("Unexpectded failure: (%d): %s", rsp.statusCode, rsp.body) <ide> } <ide> if len(rsp.body) == 0 { <del> t.Fatalf("Empty list of networks") <add> t.Fatal("Empty list of networks") <ide> } <ide> if bytes.Equal(rsp.body, expected) { <del> t.Fatalf("Incorrect list of networks in response's body") <add> t.Fatal("Incorrect list of networks in response's body") <ide> } <ide> } <ide> <ide> func TestEndToEnd(t *testing.T) { <ide> t.Fatalf("Unexpectded status code. Expected (%d). Got (%d): %s.", http.StatusCreated, rsp.statusCode, string(rsp.body)) <ide> } <ide> if len(rsp.body) == 0 { <del> t.Fatalf("Empty response body") <add> t.Fatal("Empty response body") <ide> } <ide> <ide> var nid string <ide> func TestEndToEnd(t *testing.T) { <ide> } <ide> <ide> if !bytes.Equal(b0, rsp.body) { <del> t.Fatalf("Expected same body from GET /networks and GET /networks?name=<nw> when only network <nw> exist.") <add> t.Fatal("Expected same body from GET /networks and GET /networks?name=<nw> when only network <nw> exist.") <ide> } <ide> <ide> // Query network by name <ide> func TestEndToEnd(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> if len(list) == 0 { <del> t.Fatalf("Expected non empty list") <add> t.Fatal("Expected non empty list") <ide> } <ide> if list[0].Name != "network-fiftyfive" || nid != list[0].ID { <ide> t.Fatalf("Incongruent resource found: %v", list[0]) <ide> func TestEndToEnd(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> if len(list) == 0 { <del> t.Fatalf("Expected non empty list") <add> t.Fatal("Expected non empty list") <ide> } <ide> if list[0].Name != "network-fiftyfive" || nid != list[0].ID { <ide> t.Fatalf("Incongruent resource found: %v", list[0]) <ide> func TestEndToEnd(t *testing.T) { <ide> t.Fatalf("Unexpectded status code. Expected (%d). Got (%d): %s.", http.StatusCreated, rsp.statusCode, string(rsp.body)) <ide> } <ide> if len(rsp.body) == 0 { <del> t.Fatalf("Empty response body") <add> t.Fatal("Empty response body") <ide> } <ide> <ide> var eid string <ide> func TestEndToEnd(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> if len(epList) == 0 { <del> t.Fatalf("Empty response body") <add> t.Fatal("Empty response body") <ide> } <ide> if epList[0].Name != "ep-TwentyTwo" || eid != epList[0].ID { <ide> t.Fatalf("Incongruent resource found: %v", epList[0]) <ide> func TestEndToEnd(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> if len(epList) == 0 { <del> t.Fatalf("Empty response body") <add> t.Fatal("Empty response body") <ide> } <ide> if epList[0].Name != "ep-TwentyTwo" || eid != epList[0].ID { <ide> t.Fatalf("Incongruent resource found: %v", epList[0]) <ide> func TestEndToEnd(t *testing.T) { <ide> t.Fatalf("Unexpectded status code. Expected (%d). Got (%d): %s.", http.StatusCreated, rsp.statusCode, string(rsp.body)) <ide> } <ide> if len(rsp.body) == 0 { <del> t.Fatalf("Empty response body") <add> t.Fatal("Empty response body") <ide> } <ide> // Get sandbox id and partial id <ide> var sid1 string <ide> func TestEndToEnd(t *testing.T) { <ide> t.Fatalf("Unexpectded status code. Expected (%d). Got (%d): %s.", http.StatusCreated, rsp.statusCode, string(rsp.body)) <ide> } <ide> if len(rsp.body) == 0 { <del> t.Fatalf("Empty response body") <add> t.Fatal("Empty response body") <ide> } <ide> // Get sandbox id and partial id <ide> var sid2 string <ide> func TestEndToEnd(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> if len(sbList) == 0 { <del> t.Fatalf("Empty response body") <add> t.Fatal("Empty response body") <ide> } <ide> if sbList[0].ID != sid2 { <ide> t.Fatalf("Incongruent resource found: %v", sbList[0]) <ide> func TestEndToEnd(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> if len(sbList) == 0 { <del> t.Fatalf("Empty response body") <add> t.Fatal("Empty response body") <ide> } <ide> if sbList[0].ContainerID != cid2 { <ide> t.Fatalf("Incongruent resource found: %v", sbList[0]) <ide> func TestEndToEnd(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> if len(sbList) == 0 { <del> t.Fatalf("Empty response body") <add> t.Fatal("Empty response body") <ide> } <ide> if sbList[0].ContainerID != cid1 { <ide> t.Fatalf("Incongruent resource found: %v", sbList[0]) <ide> func TestEndToEndErrorMessage(t *testing.T) { <ide> handleRequest(rsp, req) <ide> <ide> if len(rsp.body) == 0 { <del> t.Fatalf("Empty response body.") <add> t.Fatal("Empty response body.") <ide> } <ide> empty := []byte("\"\"") <ide> if bytes.Equal(empty, bytes.TrimSpace(rsp.body)) { <del> t.Fatalf("Empty response error message.") <add> t.Fatal("Empty response error message.") <ide> } <ide> } <ide> <ide> func (noc *notclassified) Error() string { <ide> <ide> func TestErrorConversion(t *testing.T) { <ide> if convertNetworkError(new(bre)).StatusCode != http.StatusBadRequest { <del> t.Fatalf("Failed to recognize BadRequest error") <add> t.Fatal("Failed to recognize BadRequest error") <ide> } <ide> <ide> if convertNetworkError(new(nfe)).StatusCode != http.StatusNotFound { <del> t.Fatalf("Failed to recognize NotFound error") <add> t.Fatal("Failed to recognize NotFound error") <ide> } <ide> <ide> if convertNetworkError(new(forb)).StatusCode != http.StatusForbidden { <del> t.Fatalf("Failed to recognize Forbidden error") <add> t.Fatal("Failed to recognize Forbidden error") <ide> } <ide> <ide> if convertNetworkError(new(notimpl)).StatusCode != http.StatusNotImplemented { <del> t.Fatalf("Failed to recognize NotImplemented error") <add> t.Fatal("Failed to recognize NotImplemented error") <ide> } <ide> <ide> if convertNetworkError(new(inter)).StatusCode != http.StatusInternalServerError { <del> t.Fatalf("Failed to recognize Internal error") <add> t.Fatal("Failed to recognize Internal error") <ide> } <ide> <ide> if convertNetworkError(new(tout)).StatusCode != http.StatusRequestTimeout { <del> t.Fatalf("Failed to recognize Timeout error") <add> t.Fatal("Failed to recognize Timeout error") <ide> } <ide> <ide> if convertNetworkError(new(noserv)).StatusCode != http.StatusServiceUnavailable { <del> t.Fatalf("Failed to recognize No Service error") <add> t.Fatal("Failed to recognize No Service error") <ide> } <ide> <ide> if convertNetworkError(new(notclassified)).StatusCode != http.StatusInternalServerError { <del> t.Fatalf("Failed to recognize not classified error as Internal error") <add> t.Fatal("Failed to recognize not classified error as Internal error") <ide> } <ide> } <ide> <ide> func TestFieldRegex(t *testing.T) { <ide> qr := regexp.MustCompile(`^` + qregx + `$`) // mux compiles it like this <ide> <ide> if pr.MatchString("") { <del> t.Fatalf("Unexpected match") <add> t.Fatal("Unexpected match") <ide> } <ide> if !qr.MatchString("") { <del> t.Fatalf("Unexpected match failure") <add> t.Fatal("Unexpected match failure") <ide> } <ide> <ide> if pr.MatchString(":") { <del> t.Fatalf("Unexpected match") <add> t.Fatal("Unexpected match") <ide> } <ide> if qr.MatchString(":") { <del> t.Fatalf("Unexpected match") <add> t.Fatal("Unexpected match") <ide> } <ide> <ide> if pr.MatchString(".") { <del> t.Fatalf("Unexpected match") <add> t.Fatal("Unexpected match") <ide> } <ide> if qr.MatchString(".") { <del> t.Fatalf("Unexpected match") <add> t.Fatal("Unexpected match") <ide> } <ide> } <ide><path>libnetwork/bitseq/sequence.go <ide> package bitseq <ide> import ( <ide> "encoding/binary" <ide> "encoding/json" <add> "errors" <ide> "fmt" <ide> "sync" <ide> <ide> const ( <ide> <ide> var ( <ide> // ErrNoBitAvailable is returned when no more bits are available to set <del> ErrNoBitAvailable = fmt.Errorf("no bit available") <add> ErrNoBitAvailable = errors.New("no bit available") <ide> // ErrBitAllocated is returned when the specific bit requested is already set <del> ErrBitAllocated = fmt.Errorf("requested bit is already allocated") <add> ErrBitAllocated = errors.New("requested bit is already allocated") <ide> ) <ide> <ide> // Handle contains the sequece representing the bitmask and its identifier <ide> func (h *Handle) validateOrdinal(ordinal uint64) error { <ide> h.Lock() <ide> defer h.Unlock() <ide> if ordinal >= h.bits { <del> return fmt.Errorf("bit does not belong to the sequence") <add> return errors.New("bit does not belong to the sequence") <ide> } <ide> return nil <ide> } <ide> func (h *Handle) ToByteArray() ([]byte, error) { <ide> // FromByteArray reads his handle's data from a byte array <ide> func (h *Handle) FromByteArray(ba []byte) error { <ide> if ba == nil { <del> return fmt.Errorf("nil byte array") <add> return errors.New("nil byte array") <ide> } <ide> <ide> nh := &sequence{} <ide><path>libnetwork/bitseq/sequence_test.go <ide> func TestSequenceCopy(t *testing.T) { <ide> s := getTestSequence() <ide> n := s.getCopy() <ide> if !s.equal(n) { <del> t.Fatalf("copy of s failed") <add> t.Fatal("copy of s failed") <ide> } <ide> if n == s { <del> t.Fatalf("not true copy of s") <add> t.Fatal("not true copy of s") <ide> } <ide> } <ide> <ide> func TestSet(t *testing.T) { <ide> } <ide> <ide> if err := hnd.Set(0); err == nil { <del> t.Fatalf("Expected failure, but succeeded") <add> t.Fatal("Expected failure, but succeeded") <ide> } <ide> <ide> os, err := hnd.SetAny() <ide> func TestSet(t *testing.T) { <ide> } <ide> <ide> if err := hnd.Set(last); err == nil { <del> t.Fatalf("Expected failure, but succeeded") <add> t.Fatal("Expected failure, but succeeded") <ide> } <ide> } <ide> <ide> func TestSetUnset(t *testing.T) { <ide> } <ide> <ide> if err := hnd.Set(uint64(32 * blockLen)); err == nil { <del> t.Fatalf("Expected failure, but succeeded") <add> t.Fatal("Expected failure, but succeeded") <ide> } <ide> if err := hnd.Unset(uint64(32 * blockLen)); err == nil { <del> t.Fatalf("Expected failure, but succeeded") <add> t.Fatal("Expected failure, but succeeded") <ide> } <ide> <ide> // set and unset all one by one <ide> func TestSetUnset(t *testing.T) { <ide> } <ide> } <ide> if _, err := hnd.SetAny(); err != ErrNoBitAvailable { <del> t.Fatalf("Expected error. Got success") <add> t.Fatal("Expected error. Got success") <ide> } <ide> if _, err := hnd.SetAnyInRange(10, 20); err != ErrNoBitAvailable { <del> t.Fatalf("Expected error. Got success") <add> t.Fatal("Expected error. Got success") <ide> } <ide> if err := hnd.Set(50); err != ErrBitAllocated { <ide> t.Fatalf("Expected error. Got %v: %s", err, hnd) <ide><path>libnetwork/client/client_service_test.go <ide> func TestClientServiceInvalidCommand(t *testing.T) { <ide> <ide> err := cli.Cmd("docker", "service", "invalid") <ide> if err == nil { <del> t.Fatalf("Passing invalid commands must fail") <add> t.Fatal("Passing invalid commands must fail") <ide> } <ide> } <ide> <ide><path>libnetwork/client/client_test.go <ide> func TestClientDummyCommand(t *testing.T) { <ide> <ide> err := cli.Cmd("docker", "dummy") <ide> if err == nil { <del> t.Fatalf("Incorrect Command must fail") <add> t.Fatal("Incorrect Command must fail") <ide> } <ide> } <ide> <ide> func TestClientNetworkInvalidCommand(t *testing.T) { <ide> <ide> err := cli.Cmd("docker", "network", "invalid") <ide> if err == nil { <del> t.Fatalf("Passing invalid commands must fail") <add> t.Fatal("Passing invalid commands must fail") <ide> } <ide> } <ide> <ide> func TestClientNetworkCreateWithDriver(t *testing.T) { <ide> <ide> err := cli.Cmd("docker", "network", "create", "-f=dummy", mockNwName) <ide> if err == nil { <del> t.Fatalf("Passing incorrect flags to the create command must fail") <add> t.Fatal("Passing incorrect flags to the create command must fail") <ide> } <ide> <ide> err = cli.Cmd("docker", "network", "create", "-d=dummy", mockNwName) <ide><path>libnetwork/client/mflag/flag_test.go <ide> func TestEverything(t *testing.T) { <ide> m = make(map[string]*Flag) <ide> Visit(visitor) <ide> if len(m) != 0 { <del> t.Errorf("Visit sees unset flags") <add> t.Error("Visit sees unset flags") <ide> for k, v := range m { <ide> t.Log(k, *v) <ide> } <ide><path>libnetwork/client/service.go <ide> package client <ide> import ( <ide> "bytes" <ide> "encoding/json" <add> "errors" <ide> "fmt" <ide> "net/http" <ide> "strings" <ide> func lookupContainerID(cli *NetworkCli, cnNameID string) (string, error) { <ide> if id, ok := iid.(string); ok { <ide> return id, nil <ide> } <del> return "", fmt.Errorf("Unexpected data type for container ID in json response") <add> return "", errors.New("Unexpected data type for container ID in json response") <ide> } <del> return "", fmt.Errorf("Cannot find container ID in json response") <add> return "", errors.New("Cannot find container ID in json response") <ide> } <ide> <ide> func lookupSandboxID(cli *NetworkCli, containerID string) (string, error) { <ide><path>libnetwork/cmd/dnet/cmd.go <ide> var ( <ide> <ide> func runContainerCreate(c *cli.Context) { <ide> if len(c.Args()) == 0 { <del> fmt.Printf("Please provide container id argument\n") <add> fmt.Print("Please provide container id argument\n") <ide> os.Exit(1) <ide> } <ide> <ide> func runContainerRm(c *cli.Context) { <ide> var sbList []*client.SandboxResource <ide> <ide> if len(c.Args()) == 0 { <del> fmt.Printf("Please provide container id argument\n") <add> fmt.Print("Please provide container id argument\n") <ide> os.Exit(1) <ide> } <ide> <ide><path>libnetwork/cmd/dnet/dnet.go <ide> func processConfig(cfg *config.Config) []config.Option { <ide> <ide> func startDiscovery(cfg *config.ClusterCfg) ([]config.Option, error) { <ide> if cfg == nil { <del> return nil, fmt.Errorf("discovery requires a valid configuration") <add> return nil, errors.New("discovery requires a valid configuration") <ide> } <ide> <ide> hb := time.Duration(cfg.Heartbeat) * time.Second <ide> func startTestDriver() error { <ide> mux := http.NewServeMux() <ide> server := httptest.NewServer(mux) <ide> if server == nil { <del> return fmt.Errorf("Failed to start an HTTP Server") <add> return errors.New("Failed to start an HTTP Server") <ide> } <ide> <ide> mux.HandleFunc("/Plugin.Activate", func(w http.ResponseWriter, r *http.Request) { <ide> func startTestDriver() error { <ide> <ide> mux.HandleFunc(fmt.Sprintf("/%s.GetCapabilities", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) { <ide> w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json") <del> fmt.Fprintf(w, `{"Scope":"global"}`) <add> fmt.Fprint(w, `{"Scope":"global"}`) <ide> }) <ide> <ide> mux.HandleFunc(fmt.Sprintf("/%s.CreateNetwork", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) { <ide> w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json") <del> fmt.Fprintf(w, "null") <add> fmt.Fprint(w, "null") <ide> }) <ide> <ide> mux.HandleFunc(fmt.Sprintf("/%s.DeleteNetwork", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) { <ide> w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json") <del> fmt.Fprintf(w, "null") <add> fmt.Fprint(w, "null") <ide> }) <ide> <ide> mux.HandleFunc(fmt.Sprintf("/%s.CreateEndpoint", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) { <ide> w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json") <del> fmt.Fprintf(w, "null") <add> fmt.Fprint(w, "null") <ide> }) <ide> <ide> mux.HandleFunc(fmt.Sprintf("/%s.DeleteEndpoint", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) { <ide> w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json") <del> fmt.Fprintf(w, "null") <add> fmt.Fprint(w, "null") <ide> }) <ide> <ide> mux.HandleFunc(fmt.Sprintf("/%s.Join", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) { <ide> w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json") <del> fmt.Fprintf(w, "null") <add> fmt.Fprint(w, "null") <ide> }) <ide> <ide> mux.HandleFunc(fmt.Sprintf("/%s.Leave", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) { <ide> w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json") <del> fmt.Fprintf(w, "null") <add> fmt.Fprint(w, "null") <ide> }) <ide> <ide> if err := os.MkdirAll("/etc/docker/plugins", 0755); err != nil { <ide> func newDnetConnection(val string) (*dnetConnection, error) { <ide> } <ide> protoAddrParts := strings.SplitN(url, "://", 2) <ide> if len(protoAddrParts) != 2 { <del> return nil, fmt.Errorf("bad format, expected tcp://ADDR") <add> return nil, errors.New("bad format, expected tcp://ADDR") <ide> } <ide> if strings.ToLower(protoAddrParts[0]) != "tcp" { <del> return nil, fmt.Errorf("dnet currently only supports tcp transport") <add> return nil, errors.New("dnet currently only supports tcp transport") <ide> } <ide> <ide> return &dnetConnection{protoAddrParts[0], protoAddrParts[1], &NetworkOrchestration{}, make(chan struct{}, 10)}, nil <ide><path>libnetwork/cmd/proxy/proxy.go <ide> package main <ide> <ide> import ( <del> "fmt" <add> "errors" <ide> "net" <ide> ) <ide> <ide> func NewProxy(frontendAddr, backendAddr net.Addr) (Proxy, error) { <ide> case *net.TCPAddr: <ide> return NewTCPProxy(frontendAddr.(*net.TCPAddr), backendAddr.(*net.TCPAddr)) <ide> default: <del> panic(fmt.Errorf("Unsupported protocol")) <add> panic(errors.New("Unsupported protocol")) <ide> } <ide> } <ide><path>libnetwork/cmd/readme_test/readme.go <ide> func main() { <ide> <ide> macAddress, ok := epInfo[netlabel.MacAddress] <ide> if !ok { <del> log.Fatalf("failed to get mac address from endpoint info") <add> log.Fatal("failed to get mac address from endpoint info") <ide> } <ide> <ide> fmt.Printf("Joined endpoint %s (%s) to sandbox %s (%s)\n", ep.Name(), macAddress, sbx.ContainerID(), sbx.Key()) <ide><path>libnetwork/datastore/cache.go <ide> package datastore <ide> <ide> import ( <add> "errors" <ide> "fmt" <ide> "sync" <ide> <ide> func (c *cache) kmap(kvObject KVObject) (kvMap, error) { <ide> // Bail out right away if the kvObject does not implement KVConstructor <ide> ctor, ok := kvObject.(KVConstructor) <ide> if !ok { <del> return nil, fmt.Errorf("error while populating kmap, object does not implement KVConstructor interface") <add> return nil, errors.New("error while populating kmap, object does not implement KVConstructor interface") <ide> } <ide> <ide> kvList, err := c.ds.store.List(keyPrefix) <ide> func (c *cache) get(key string, kvObject KVObject) error { <ide> <ide> ctor, ok := o.(KVConstructor) <ide> if !ok { <del> return fmt.Errorf("kvobject does not implement KVConstructor interface. could not get object") <add> return errors.New("kvobject does not implement KVConstructor interface. could not get object") <ide> } <ide> <ide> return ctor.CopyTo(kvObject) <ide><path>libnetwork/datastore/datastore_test.go <ide> func TestKVObjectFlatKey(t *testing.T) { <ide> var n dummyObject <ide> json.Unmarshal(data.Value, &n) <ide> if n.Name != expected.Name { <del> t.Fatalf("Dummy object doesn't match the expected object") <add> t.Fatal("Dummy object doesn't match the expected object") <ide> } <ide> } <ide> <ide><path>libnetwork/driverapi/driverapi_test.go <ide> func TestValidateAndIsV6(t *testing.T) { <ide> <ide> // Check ip version <ide> if i.IsV6() { <del> t.Fatalf("incorrect ip version returned") <add> t.Fatal("incorrect ip version returned") <ide> } <ide> orig := i.Pool <ide> if i.Pool, err = types.ParseCIDR("2001:db8::33/64"); err != nil { <ide> t.Fatal(err) <ide> } <ide> if !i.IsV6() { <del> t.Fatalf("incorrect ip version returned") <add> t.Fatal("incorrect ip version returned") <ide> } <ide> i.Pool = orig <ide> <ide> func TestValidateAndIsV6(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> if err = i.Validate(); err == nil { <del> t.Fatalf("expected error but succeeded") <add> t.Fatal("expected error but succeeded") <ide> } <ide> i.Gateway = nil <ide> <ide> func TestValidateAndIsV6(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> if err = i.Validate(); err == nil { <del> t.Fatalf("expected error but succeeded") <add> t.Fatal("expected error but succeeded") <ide> } <ide> delete(i.AuxAddresses, "ip2") <ide> <ide> func TestValidateAndIsV6(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> if err = i.Validate(); err == nil { <del> t.Fatalf("expected error but succeeded") <add> t.Fatal("expected error but succeeded") <ide> } <ide> i.Gateway = nil <ide> <ide> func TestValidateAndIsV6(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> if err = i.Validate(); err == nil { <del> t.Fatalf("expected error but succeeded") <add> t.Fatal("expected error but succeeded") <ide> } <ide> } <ide><path>libnetwork/drivers/bridge/bridge.go <ide> func (c *networkConfiguration) Validate() error { <ide> // Conflicts check if two NetworkConfiguration objects overlap <ide> func (c *networkConfiguration) Conflicts(o *networkConfiguration) error { <ide> if o == nil { <del> return fmt.Errorf("same configuration") <add> return errors.New("same configuration") <ide> } <ide> <ide> // Also empty, because only one network with empty name is allowed <ide> if c.BridgeName == o.BridgeName { <del> return fmt.Errorf("networks have same bridge name") <add> return errors.New("networks have same bridge name") <ide> } <ide> <ide> // They must be in different subnets <ide> if (c.AddressIPv4 != nil && o.AddressIPv4 != nil) && <ide> (c.AddressIPv4.Contains(o.AddressIPv4.IP) || o.AddressIPv4.Contains(c.AddressIPv4.IP)) { <del> return fmt.Errorf("networks have overlapping IPv4") <add> return errors.New("networks have overlapping IPv4") <ide> } <ide> <ide> // They must be in different v6 subnets <ide> if (c.AddressIPv6 != nil && o.AddressIPv6 != nil) && <ide> (c.AddressIPv6.Contains(o.AddressIPv6.IP) || o.AddressIPv6.Contains(c.AddressIPv6.IP)) { <del> return fmt.Errorf("networks have overlapping IPv6") <add> return errors.New("networks have overlapping IPv6") <ide> } <ide> <ide> return nil <ide><path>libnetwork/drivers/bridge/bridge_test.go <ide> func TestCreateFullOptionsLabels(t *testing.T) { <ide> <ide> nw, ok := d.networks["dummy"] <ide> if !ok { <del> t.Fatalf("Cannot find dummy network in bridge driver") <add> t.Fatal("Cannot find dummy network in bridge driver") <ide> } <ide> <ide> if nw.config.BridgeName != DefaultBridgeName { <del> t.Fatalf("incongruent name in bridge network") <add> t.Fatal("incongruent name in bridge network") <ide> } <ide> <ide> if !nw.config.EnableIPv6 { <del> t.Fatalf("incongruent EnableIPv6 in bridge network") <add> t.Fatal("incongruent EnableIPv6 in bridge network") <ide> } <ide> <ide> if !nw.config.EnableICC { <del> t.Fatalf("incongruent EnableICC in bridge network") <add> t.Fatal("incongruent EnableICC in bridge network") <ide> } <ide> <ide> if !nw.config.EnableIPMasquerade { <del> t.Fatalf("incongruent EnableIPMasquerade in bridge network") <add> t.Fatal("incongruent EnableIPMasquerade in bridge network") <ide> } <ide> <ide> bndIP := net.ParseIP(bndIPs) <ide> func TestCreate(t *testing.T) { <ide> <ide> err := d.CreateNetwork("dummy", genericOption, nil, getIPv4Data(t, ""), nil) <ide> if err == nil { <del> t.Fatalf("Expected bridge driver to refuse creation of second network with default name") <add> t.Fatal("Expected bridge driver to refuse creation of second network with default name") <ide> } <ide> if _, ok := err.(types.ForbiddenError); !ok { <del> t.Fatalf("Creation of second network with default name failed with unexpected error type") <add> t.Fatal("Creation of second network with default name failed with unexpected error type") <ide> } <ide> } <ide> <ide> func testQueryEndpointInfo(t *testing.T, ulPxyEnabled bool) { <ide> } <ide> pmd, ok := data[netlabel.PortMap] <ide> if !ok { <del> t.Fatalf("Endpoint operational data does not contain port mapping data") <add> t.Fatal("Endpoint operational data does not contain port mapping data") <ide> } <ide> pm, ok := pmd.([]types.PortBinding) <ide> if !ok { <del> t.Fatalf("Unexpected format for port mapping in endpoint operational data") <add> t.Fatal("Unexpected format for port mapping in endpoint operational data") <ide> } <ide> if len(ep.portMapping) != len(pm) { <del> t.Fatalf("Incomplete data for port mapping in endpoint operational data") <add> t.Fatal("Incomplete data for port mapping in endpoint operational data") <ide> } <ide> for i, pb := range ep.portMapping { <ide> if !pb.Equal(&pm[i]) { <del> t.Fatalf("Unexpected data for port mapping in endpoint operational data") <add> t.Fatal("Unexpected data for port mapping in endpoint operational data") <ide> } <ide> } <ide> <ide> func TestLinkContainers(t *testing.T) { <ide> <ide> addr1 := te1.iface.addr <ide> if addr1.IP.To4() == nil { <del> t.Fatalf("No Ipv4 address assigned to the endpoint: ep1") <add> t.Fatal("No Ipv4 address assigned to the endpoint: ep1") <ide> } <ide> <ide> te2 := newTestEndpoint(ipdList[0].Pool, 22) <ide> func TestLinkContainers(t *testing.T) { <ide> <ide> addr2 := te2.iface.addr <ide> if addr2.IP.To4() == nil { <del> t.Fatalf("No Ipv4 address assigned to the endpoint: ep2") <add> t.Fatal("No Ipv4 address assigned to the endpoint: ep2") <ide> } <ide> <ide> sbOptions = make(map[string]interface{}) <ide> func TestLinkContainers(t *testing.T) { <ide> <ide> err = d.Join("net1", "ep2", "", te2, sbOptions) <ide> if err != nil { <del> t.Fatalf("Failed to link ep1 and ep2") <add> t.Fatal("Failed to link ep1 and ep2") <ide> } <ide> <ide> err = d.ProgramExternalConnectivity("net1", "ep2", sbOptions) <ide> func TestLinkContainers(t *testing.T) { <ide> <ide> err = d.Leave("net1", "ep2") <ide> if err != nil { <del> t.Fatalf("Failed to unlink ep1 and ep2") <add> t.Fatal("Failed to unlink ep1 and ep2") <ide> } <ide> <ide> out, err = iptables.Raw("-L", DockerChain) <ide> func TestLinkContainers(t *testing.T) { <ide> } <ide> } <ide> } else { <del> t.Fatalf("Expected Join to fail given link conditions are not satisfied") <add> t.Fatal("Expected Join to fail given link conditions are not satisfied") <ide> } <ide> } <ide> <ide> func TestValidateConfig(t *testing.T) { <ide> c := networkConfiguration{Mtu: -2} <ide> err := c.Validate() <ide> if err == nil { <del> t.Fatalf("Failed to detect invalid MTU number") <add> t.Fatal("Failed to detect invalid MTU number") <ide> } <ide> <ide> c.Mtu = 9000 <ide> err = c.Validate() <ide> if err != nil { <del> t.Fatalf("unexpected validation error on MTU number") <add> t.Fatal("unexpected validation error on MTU number") <ide> } <ide> <ide> // Bridge network <ide> func TestValidateConfig(t *testing.T) { <ide> c.DefaultGatewayIPv4 = net.ParseIP("172.27.30.234") <ide> err = c.Validate() <ide> if err == nil { <del> t.Fatalf("Failed to detect invalid default gateway") <add> t.Fatal("Failed to detect invalid default gateway") <ide> } <ide> <ide> c.DefaultGatewayIPv4 = net.ParseIP("172.28.30.234") <ide> err = c.Validate() <ide> if err != nil { <del> t.Fatalf("Unexpected validation error on default gateway") <add> t.Fatal("Unexpected validation error on default gateway") <ide> } <ide> <ide> // Test v6 gw <ide> func TestValidateConfig(t *testing.T) { <ide> } <ide> err = c.Validate() <ide> if err == nil { <del> t.Fatalf("Failed to detect invalid v6 default gateway") <add> t.Fatal("Failed to detect invalid v6 default gateway") <ide> } <ide> <ide> c.DefaultGatewayIPv6 = net.ParseIP("2001:db8:ae:b004::bad:a55") <ide> err = c.Validate() <ide> if err != nil { <del> t.Fatalf("Unexpected validation error on v6 default gateway") <add> t.Fatal("Unexpected validation error on v6 default gateway") <ide> } <ide> <ide> c.AddressIPv6 = nil <ide> err = c.Validate() <ide> if err == nil { <del> t.Fatalf("Failed to detect invalid v6 default gateway") <add> t.Fatal("Failed to detect invalid v6 default gateway") <ide> } <ide> <ide> c.AddressIPv6 = nil <ide> err = c.Validate() <ide> if err == nil { <del> t.Fatalf("Failed to detect invalid v6 default gateway") <add> t.Fatal("Failed to detect invalid v6 default gateway") <ide> } <ide> } <ide> <ide> func TestCreateWithExistingBridge(t *testing.T) { <ide> } <ide> <ide> if _, err := netlink.LinkByName(brName); err != nil { <del> t.Fatalf("Deleting bridge network that using existing bridge interface unexpectedly deleted the bridge interface") <add> t.Fatal("Deleting bridge network that using existing bridge interface unexpectedly deleted the bridge interface") <ide> } <ide> } <ide><path>libnetwork/drivers/bridge/network_test.go <ide> func TestLinkCreate(t *testing.T) { <ide> t.Fatalf("Failed with a wrong error :%s", err.Error()) <ide> } <ide> } else { <del> t.Fatalf("Failed to detect invalid config") <add> t.Fatal("Failed to detect invalid config") <ide> } <ide> <ide> // Good endpoint creation <ide> func TestLinkCreate(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> if mtu != sboxLnk.Attrs().MTU { <del> t.Fatalf("Sandbox endpoint interface did not inherit bridge interface MTU config") <add> t.Fatal("Sandbox endpoint interface did not inherit bridge interface MTU config") <ide> } <ide> // TODO: if we could get peer name from (sboxLnk.(*netlink.Veth)).PeerName <ide> // then we could check the MTU on hostLnk as well. <ide> <ide> te1 := newTestEndpoint(ipdList[0].Pool, 11) <ide> err = d.CreateEndpoint("dummy", "ep", te1.Interface(), nil) <ide> if err == nil { <del> t.Fatalf("Failed to detect duplicate endpoint id on same network") <add> t.Fatal("Failed to detect duplicate endpoint id on same network") <ide> } <ide> <ide> if te.iface.dstName == "" { <ide> func TestLinkCreateTwo(t *testing.T) { <ide> t.Fatalf("Failed with a wrong error: %s", err.Error()) <ide> } <ide> } else { <del> t.Fatalf("Expected to fail while trying to add same endpoint twice") <add> t.Fatal("Expected to fail while trying to add same endpoint twice") <ide> } <ide> } <ide> <ide> func TestLinkDelete(t *testing.T) { <ide> t.Fatalf("Failed with a wrong error :%s", err.Error()) <ide> } <ide> } else { <del> t.Fatalf("Failed to detect invalid config") <add> t.Fatal("Failed to detect invalid config") <ide> } <ide> <ide> err = d.DeleteEndpoint("dummy", "ep1") <ide><path>libnetwork/drivers/bridge/port_mapping_test.go <ide> func TestPortMappingConfig(t *testing.T) { <ide> } <ide> if ep.portMapping[0].Proto != binding1.Proto || ep.portMapping[0].Port != binding1.Port || <ide> ep.portMapping[1].Proto != binding2.Proto || ep.portMapping[1].Port != binding2.Port { <del> t.Fatalf("bridgeEndpoint has incorrect port mapping values") <add> t.Fatal("bridgeEndpoint has incorrect port mapping values") <ide> } <ide> if ep.portMapping[0].HostIP == nil || ep.portMapping[0].HostPort == 0 || <ide> ep.portMapping[1].HostIP == nil || ep.portMapping[1].HostPort == 0 { <del> t.Fatalf("operational port mapping data not found on bridgeEndpoint") <add> t.Fatal("operational port mapping data not found on bridgeEndpoint") <ide> } <ide> <ide> // release host mapped ports <ide><path>libnetwork/drivers/bridge/setup_bridgenetfiltering.go <ide> package bridge <ide> <ide> import ( <add> "errors" <ide> "fmt" <ide> "io/ioutil" <ide> "os" <ide> func setupBridgeNetFiltering(config *networkConfiguration, i *bridgeInterface) e <ide> logrus.Warnf("running inside docker container, ignoring missing kernel params: %v", err) <ide> err = nil <ide> } else { <del> err = fmt.Errorf("please ensure that br_netfilter kernel module is loaded") <add> err = errors.New("please ensure that br_netfilter kernel module is loaded") <ide> } <ide> } <ide> } <ide><path>libnetwork/drivers/bridge/setup_device_test.go <ide> func TestSetupNewBridge(t *testing.T) { <ide> t.Fatalf("Failed to retrieve bridge device: %v", err) <ide> } <ide> if br.Link.Attrs().Flags&net.FlagUp == net.FlagUp { <del> t.Fatalf("bridgeInterface should be created down") <add> t.Fatal("bridgeInterface should be created down") <ide> } <ide> } <ide> <ide> func TestSetupDeviceUp(t *testing.T) { <ide> <ide> lnk, _ := nh.LinkByName(DefaultBridgeName) <ide> if lnk.Attrs().Flags&net.FlagUp != net.FlagUp { <del> t.Fatalf("bridgeInterface should be up") <add> t.Fatal("bridgeInterface should be up") <ide> } <ide> } <ide> <ide><path>libnetwork/drivers/bridge/setup_ip_forwarding_test.go <ide> func TestSetupIPForwarding(t *testing.T) { <ide> // Read new setting <ide> procSetting = readCurrentIPForwardingSetting(t) <ide> if bytes.Compare(procSetting, []byte("1\n")) != 0 { <del> t.Fatalf("Failed to effectively setup IP forwarding") <add> t.Fatal("Failed to effectively setup IP forwarding") <ide> } <ide> } <ide> <ide><path>libnetwork/drivers/bridge/setup_ip_tables.go <ide> package bridge <ide> <ide> import ( <add> "errors" <ide> "fmt" <ide> "net" <ide> <ide> const ( <ide> func setupIPChains(config *configuration) (*iptables.ChainInfo, *iptables.ChainInfo, *iptables.ChainInfo, error) { <ide> // Sanity check. <ide> if config.EnableIPTables == false { <del> return nil, nil, nil, fmt.Errorf("cannot create new chains, EnableIPTable is disabled") <add> return nil, nil, nil, errors.New("cannot create new chains, EnableIPTable is disabled") <ide> } <ide> <ide> hairpinMode := !config.EnableUserlandProxy <ide> func (n *bridgeNetwork) setupIPTables(config *networkConfiguration, i *bridgeInt <ide> <ide> // Sanity check. <ide> if driverConfig.EnableIPTables == false { <del> return fmt.Errorf("Cannot program chains, EnableIPTable is disabled") <add> return errors.New("Cannot program chains, EnableIPTable is disabled") <ide> } <ide> <ide> // Pickup this configuraton option from driver <ide><path>libnetwork/drivers/bridge/setup_ipv4.go <ide> package bridge <ide> <ide> import ( <add> "errors" <ide> "fmt" <ide> "io/ioutil" <ide> "net" <ide> import ( <ide> <ide> func selectIPv4Address(addresses []netlink.Addr, selector *net.IPNet) (netlink.Addr, error) { <ide> if len(addresses) == 0 { <del> return netlink.Addr{}, fmt.Errorf("unable to select an address as the address pool is empty") <add> return netlink.Addr{}, errors.New("unable to select an address as the address pool is empty") <ide> } <ide> if selector != nil { <ide> for _, addr := range addresses { <ide><path>libnetwork/drivers/host/host_test.go <ide> func TestDriver(t *testing.T) { <ide> d := &driver{} <ide> <ide> if d.Type() != networkType { <del> t.Fatalf("Unexpected network type returned by driver") <add> t.Fatal("Unexpected network type returned by driver") <ide> } <ide> <ide> err := d.CreateNetwork("first", nil, nil, nil, nil) <ide> func TestDriver(t *testing.T) { <ide> } <ide> <ide> if d.network != "first" { <del> t.Fatalf("Unexpected network id stored") <add> t.Fatal("Unexpected network id stored") <ide> } <ide> <ide> err = d.CreateNetwork("second", nil, nil, nil, nil) <ide> if err == nil { <del> t.Fatalf("Second network creation should fail on this driver") <add> t.Fatal("Second network creation should fail on this driver") <ide> } <ide> if _, ok := err.(types.ForbiddenError); !ok { <del> t.Fatalf("Second network creation failed with unexpected error type") <add> t.Fatal("Second network creation failed with unexpected error type") <ide> } <ide> <ide> err = d.DeleteNetwork("first") <ide> if err == nil { <del> t.Fatalf("network deletion should fail on this driver") <add> t.Fatal("network deletion should fail on this driver") <ide> } <ide> if _, ok := err.(types.ForbiddenError); !ok { <del> t.Fatalf("network deletion failed with unexpected error type") <add> t.Fatal("network deletion failed with unexpected error type") <ide> } <ide> <ide> // we don't really check if it is there or not, delete is not allowed for this driver, period. <ide> err = d.DeleteNetwork("unknown") <ide> if err == nil { <del> t.Fatalf("any network deletion should fail on this driver") <add> t.Fatal("any network deletion should fail on this driver") <ide> } <ide> if _, ok := err.(types.ForbiddenError); !ok { <del> t.Fatalf("any network deletion failed with unexpected error type") <add> t.Fatal("any network deletion failed with unexpected error type") <ide> } <ide> } <ide><path>libnetwork/drivers/remote/driver.go <ide> package remote <ide> <ide> import ( <add> "errors" <ide> "fmt" <ide> "net" <ide> <ide> func (d *driver) DeleteNetwork(nid string) error { <ide> <ide> func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo, epOptions map[string]interface{}) error { <ide> if ifInfo == nil { <del> return fmt.Errorf("must not be called with nil InterfaceInfo") <add> return errors.New("must not be called with nil InterfaceInfo") <ide> } <ide> <ide> reqIface := &api.EndpointInterface{} <ide><path>libnetwork/drivers/remote/driver_test.go <ide> package remote <ide> import ( <ide> "bytes" <ide> "encoding/json" <add> "errors" <ide> "fmt" <ide> "io" <ide> "io/ioutil" <ide> func TestDriverError(t *testing.T) { <ide> driver := newDriver(plugin, p.Client()) <ide> <ide> if err := driver.CreateEndpoint("dummy", "dummy", &testEndpoint{t: t}, map[string]interface{}{}); err == nil { <del> t.Fatalf("Expected error from driver") <add> t.Fatal("Expected error from driver") <ide> } <ide> } <ide> <ide> func (r *rollbackEndpoint) AddressIPv6() *net.IPNet { <ide> } <ide> <ide> func (r *rollbackEndpoint) SetMacAddress(mac net.HardwareAddr) error { <del> return fmt.Errorf("invalid mac") <add> return errors.New("invalid mac") <ide> } <ide> <ide> func (r *rollbackEndpoint) SetIPAddress(ip *net.IPNet) error { <del> return fmt.Errorf("invalid ip") <add> return errors.New("invalid ip") <ide> } <ide> <ide> func TestRollback(t *testing.T) { <ide> func TestRollback(t *testing.T) { <ide> ep := &rollbackEndpoint{} <ide> <ide> if err := driver.CreateEndpoint("dummy", "dummy", ep.Interface(), map[string]interface{}{}); err == nil { <del> t.Fatalf("Expected error from driver") <add> t.Fatal("Expected error from driver") <ide> } <ide> if !rolledback { <del> t.Fatalf("Expected to have had DeleteEndpoint called") <add> t.Fatal("Expected to have had DeleteEndpoint called") <ide> } <ide> } <ide><path>libnetwork/drvregistry/drvregistry.go <ide> package drvregistry <ide> <ide> import ( <add> "errors" <ide> "fmt" <ide> "strings" <ide> "sync" <ide> func (r *DrvRegistry) GetPluginGetter() plugingetter.PluginGetter { <ide> // RegisterDriver registers the network driver when it gets discovered. <ide> func (r *DrvRegistry) RegisterDriver(ntype string, driver driverapi.Driver, capability driverapi.Capability) error { <ide> if strings.TrimSpace(ntype) == "" { <del> return fmt.Errorf("network type string cannot be empty") <add> return errors.New("network type string cannot be empty") <ide> } <ide> <ide> r.Lock() <ide> func (r *DrvRegistry) RegisterDriver(ntype string, driver driverapi.Driver, capa <ide> <ide> func (r *DrvRegistry) registerIpamDriver(name string, driver ipamapi.Ipam, caps *ipamapi.Capability) error { <ide> if strings.TrimSpace(name) == "" { <del> return fmt.Errorf("ipam driver name string cannot be empty") <add> return errors.New("ipam driver name string cannot be empty") <ide> } <ide> <ide> r.Lock() <ide><path>libnetwork/hostdiscovery/hostdiscovery_test.go <ide> func TestAddedCallback(t *testing.T) { <ide> removed := false <ide> hd.processCallback(update, func() {}, func(hosts []net.IP) { added = true }, func(hosts []net.IP) { removed = true }) <ide> if !added { <del> t.Fatalf("Expecting an Added callback notification. But none received") <add> t.Fatal("Expecting an Added callback notification. But none received") <ide> } <ide> } <ide> <ide> func TestRemovedCallback(t *testing.T) { <ide> removed := false <ide> hd.processCallback(update, func() {}, func(hosts []net.IP) { added = true }, func(hosts []net.IP) { removed = true }) <ide> if !removed { <del> t.Fatalf("Expecting a Removed callback notification. But none received") <add> t.Fatal("Expecting a Removed callback notification. But none received") <ide> } <ide> } <ide> <ide> func TestNoCallback(t *testing.T) { <ide> removed := false <ide> hd.processCallback(update, func() {}, func(hosts []net.IP) { added = true }, func(hosts []net.IP) { removed = true }) <ide> if added || removed { <del> t.Fatalf("Not expecting any callback notification. But received a callback") <add> t.Fatal("Not expecting any callback notification. But received a callback") <ide> } <ide> } <ide><path>libnetwork/idm/idm.go <ide> package idm <ide> <ide> import ( <add> "errors" <ide> "fmt" <ide> <ide> "github.com/docker/libnetwork/bitseq" <ide> type Idm struct { <ide> // New returns an instance of id manager for a set of [start-end] numerical ids <ide> func New(ds datastore.DataStore, id string, start, end uint64) (*Idm, error) { <ide> if id == "" { <del> return nil, fmt.Errorf("Invalid id") <add> return nil, errors.New("Invalid id") <ide> } <ide> if end <= start { <ide> return nil, fmt.Errorf("Invalid set range: [%d, %d]", start, end) <ide> func New(ds datastore.DataStore, id string, start, end uint64) (*Idm, error) { <ide> // GetID returns the first available id in the set <ide> func (i *Idm) GetID() (uint64, error) { <ide> if i.handle == nil { <del> return 0, fmt.Errorf("ID set is not initialized") <add> return 0, errors.New("ID set is not initialized") <ide> } <ide> ordinal, err := i.handle.SetAny() <ide> return i.start + ordinal, err <ide> func (i *Idm) GetID() (uint64, error) { <ide> // GetSpecificID tries to reserve the specified id <ide> func (i *Idm) GetSpecificID(id uint64) error { <ide> if i.handle == nil { <del> return fmt.Errorf("ID set is not initialized") <add> return errors.New("ID set is not initialized") <ide> } <ide> <ide> if id < i.start || id > i.end { <del> return fmt.Errorf("Requested id does not belong to the set") <add> return errors.New("Requested id does not belong to the set") <ide> } <ide> <ide> return i.handle.Set(id - i.start) <ide> func (i *Idm) GetSpecificID(id uint64) error { <ide> // GetIDInRange returns the first available id in the set within a range <ide> func (i *Idm) GetIDInRange(start, end uint64) (uint64, error) { <ide> if i.handle == nil { <del> return 0, fmt.Errorf("ID set is not initialized") <add> return 0, errors.New("ID set is not initialized") <ide> } <ide> <ide> if start < i.start || end > i.end { <del> return 0, fmt.Errorf("Requested range does not belong to the set") <add> return 0, errors.New("Requested range does not belong to the set") <ide> } <ide> <ide> return i.handle.SetAnyInRange(start, end-start) <ide><path>libnetwork/idm/idm_test.go <ide> import ( <ide> func TestNew(t *testing.T) { <ide> _, err := New(nil, "", 0, 1) <ide> if err == nil { <del> t.Fatalf("Expected failure, but succeeded") <add> t.Fatal("Expected failure, but succeeded") <ide> } <ide> <ide> _, err = New(nil, "myset", 1<<10, 0) <ide> if err == nil { <del> t.Fatalf("Expected failure, but succeeded") <add> t.Fatal("Expected failure, but succeeded") <ide> } <ide> <ide> i, err := New(nil, "myset", 0, 10) <ide> if err != nil { <ide> t.Fatalf("Unexpected failure: %v", err) <ide> } <ide> if i.handle == nil { <del> t.Fatalf("set is not initialized") <add> t.Fatal("set is not initialized") <ide> } <ide> if i.start != 0 { <del> t.Fatalf("unexpected start") <add> t.Fatal("unexpected start") <ide> } <ide> if i.end != 10 { <del> t.Fatalf("unexpected end") <add> t.Fatal("unexpected end") <ide> } <ide> } <ide> <ide> func TestAllocate(t *testing.T) { <ide> } <ide> <ide> if err = i.GetSpecificID(49); err == nil { <del> t.Fatalf("Expected failure but succeeded") <add> t.Fatal("Expected failure but succeeded") <ide> } <ide> <ide> if err = i.GetSpecificID(53); err == nil { <del> t.Fatalf("Expected failure but succeeded") <add> t.Fatal("Expected failure but succeeded") <ide> } <ide> <ide> o, err := i.GetID() <ide> func TestAllocate(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> if o != 50 { <del> t.Fatalf("Unexpected id returned") <add> t.Fatal("Unexpected id returned") <ide> } <ide> <ide> i.Release(52) <ide> func TestUninitialized(t *testing.T) { <ide> i := &Idm{} <ide> <ide> if _, err := i.GetID(); err == nil { <del> t.Fatalf("Expected failure but succeeded") <add> t.Fatal("Expected failure but succeeded") <ide> } <ide> <ide> if err := i.GetSpecificID(44); err == nil { <del> t.Fatalf("Expected failure but succeeded") <add> t.Fatal("Expected failure but succeeded") <ide> } <ide> } <ide><path>libnetwork/ipam/allocator_test.go <ide> func TestInt2IP2IntConversion(t *testing.T) { <ide> <ide> func TestGetAddressVersion(t *testing.T) { <ide> if v4 != getAddressVersion(net.ParseIP("172.28.30.112")) { <del> t.Fatalf("Failed to detect IPv4 version") <add> t.Fatal("Failed to detect IPv4 version") <ide> } <ide> if v4 != getAddressVersion(net.ParseIP("0.0.0.1")) { <del> t.Fatalf("Failed to detect IPv4 version") <add> t.Fatal("Failed to detect IPv4 version") <ide> } <ide> if v6 != getAddressVersion(net.ParseIP("ff01::1")) { <del> t.Fatalf("Failed to detect IPv6 version") <add> t.Fatal("Failed to detect IPv6 version") <ide> } <ide> if v6 != getAddressVersion(net.ParseIP("2001:db8::76:51")) { <del> t.Fatalf("Failed to detect IPv6 version") <add> t.Fatal("Failed to detect IPv6 version") <ide> } <ide> } <ide> <ide> func TestPoolDataMarshal(t *testing.T) { <ide> } <ide> <ide> if q.Range != nil { <del> t.Fatalf("Unexpected Range") <add> t.Fatal("Unexpected Range") <ide> } <ide> } <ide> <ide> func TestAddSubnets(t *testing.T) { <ide> <ide> pid0, _, _, err := a.RequestPool(localAddressSpace, "10.0.0.0/8", "", nil, false) <ide> if err != nil { <del> t.Fatalf("Unexpected failure in adding subnet") <add> t.Fatal("Unexpected failure in adding subnet") <ide> } <ide> <ide> pid1, _, _, err := a.RequestPool("abc", "10.0.0.0/8", "", nil, false) <ide> func TestAddSubnets(t *testing.T) { <ide> } <ide> <ide> if pid0 == pid1 { <del> t.Fatalf("returned same pool id for same subnets in different namespaces") <add> t.Fatal("returned same pool id for same subnets in different namespaces") <ide> } <ide> <ide> pid, _, _, err := a.RequestPool("abc", "10.0.0.0/8", "", nil, false) <ide> if err != nil { <ide> t.Fatalf("Unexpected failure requesting existing subnet: %v", err) <ide> } <ide> if pid != pid1 { <del> t.Fatalf("returned different pool id for same subnet requests") <add> t.Fatal("returned different pool id for same subnet requests") <ide> } <ide> <ide> _, _, _, err = a.RequestPool("abc", "10.128.0.0/9", "", nil, false) <ide> if err == nil { <del> t.Fatalf("Expected failure on adding overlapping base subnet") <add> t.Fatal("Expected failure on adding overlapping base subnet") <ide> } <ide> <ide> pid2, _, _, err := a.RequestPool("abc", "10.0.0.0/8", "10.128.0.0/9", nil, false) <ide> func TestAddSubnets(t *testing.T) { <ide> t.Fatalf("Unexpected failure on adding overlapping sub pool: %v", err) <ide> } <ide> if pid2 != pid3 { <del> t.Fatalf("returned different pool id for same sub pool requests") <add> t.Fatal("returned different pool id for same sub pool requests") <ide> } <ide> <ide> pid, _, _, err = a.RequestPool(localAddressSpace, "10.20.2.0/24", "", nil, false) <ide> if err == nil { <del> t.Fatalf("Failed to detect overlapping subnets") <add> t.Fatal("Failed to detect overlapping subnets") <ide> } <ide> <ide> _, _, _, err = a.RequestPool(localAddressSpace, "10.128.0.0/9", "", nil, false) <ide> if err == nil { <del> t.Fatalf("Failed to detect overlapping subnets") <add> t.Fatal("Failed to detect overlapping subnets") <ide> } <ide> <ide> _, _, _, err = a.RequestPool(localAddressSpace, "1003:1:2:3:4:5:6::/112", "", nil, false) <ide> func TestAddSubnets(t *testing.T) { <ide> <ide> _, _, _, err = a.RequestPool(localAddressSpace, "1003:1:2:3::/64", "", nil, false) <ide> if err == nil { <del> t.Fatalf("Failed to detect overlapping v6 subnet") <add> t.Fatal("Failed to detect overlapping v6 subnet") <ide> } <ide> } <ide> <ide> func TestAddReleasePoolID(t *testing.T) { <ide> subnets := aSpace.subnets <ide> pid0, _, _, err := a.RequestPool(localAddressSpace, "10.0.0.0/8", "", nil, false) <ide> if err != nil { <del> t.Fatalf("Unexpected failure in adding pool") <add> t.Fatal("Unexpected failure in adding pool") <ide> } <ide> if err := k0.FromString(pid0); err != nil { <ide> t.Fatal(err) <ide> func TestAddReleasePoolID(t *testing.T) { <ide> <ide> pid1, _, _, err := a.RequestPool(localAddressSpace, "10.0.0.0/8", "10.0.0.0/16", nil, false) <ide> if err != nil { <del> t.Fatalf("Unexpected failure in adding sub pool") <add> t.Fatal("Unexpected failure in adding sub pool") <ide> } <ide> if err := k1.FromString(pid1); err != nil { <ide> t.Fatal(err) <ide> func TestAddReleasePoolID(t *testing.T) { <ide> <ide> pid2, _, _, err := a.RequestPool(localAddressSpace, "10.0.0.0/8", "10.0.0.0/16", nil, false) <ide> if err != nil { <del> t.Fatalf("Unexpected failure in adding sub pool") <add> t.Fatal("Unexpected failure in adding sub pool") <ide> } <ide> if pid0 == pid1 || pid0 == pid2 || pid1 != pid2 { <ide> t.Fatalf("Incorrect poolIDs returned %s, %s, %s", pid0, pid1, pid2) <ide> func TestAddReleasePoolID(t *testing.T) { <ide> <ide> pid00, _, _, err := a.RequestPool(localAddressSpace, "10.0.0.0/8", "", nil, false) <ide> if err != nil { <del> t.Fatalf("Unexpected failure in adding pool") <add> t.Fatal("Unexpected failure in adding pool") <ide> } <ide> if pid00 != pid0 { <del> t.Fatalf("main pool should still exist") <add> t.Fatal("main pool should still exist") <ide> } <ide> <ide> aSpace, err = a.getAddrSpace(localAddressSpace) <ide> func TestAddReleasePoolID(t *testing.T) { <ide> <ide> _, _, _, err = a.RequestPool(localAddressSpace, "10.0.0.0/8", "", nil, false) <ide> if err != nil { <del> t.Fatalf("Unexpected failure in adding pool") <add> t.Fatal("Unexpected failure in adding pool") <ide> } <ide> <ide> aSpace, err = a.getAddrSpace(localAddressSpace) <ide> func TestPredefinedPool(t *testing.T) { <ide> } <ide> <ide> if _, err := a.getPredefinedPool("blue", false); err == nil { <del> t.Fatalf("Expected failure for non default addr space") <add> t.Fatal("Expected failure for non default addr space") <ide> } <ide> <ide> pid, nw, _, err := a.RequestPool(localAddressSpace, "", "", nil, false) <ide> func TestRequestSyntaxCheck(t *testing.T) { <ide> <ide> _, _, _, err = a.RequestPool("", pool, "", nil, false) <ide> if err == nil { <del> t.Fatalf("Failed to detect wrong request: empty address space") <add> t.Fatal("Failed to detect wrong request: empty address space") <ide> } <ide> <ide> _, _, _, err = a.RequestPool("", pool, subPool, nil, false) <ide> if err == nil { <del> t.Fatalf("Failed to detect wrong request: empty address space") <add> t.Fatal("Failed to detect wrong request: empty address space") <ide> } <ide> <ide> _, _, _, err = a.RequestPool(as, "", subPool, nil, false) <ide> if err == nil { <del> t.Fatalf("Failed to detect wrong request: subPool specified and no pool") <add> t.Fatal("Failed to detect wrong request: subPool specified and no pool") <ide> } <ide> <ide> pid, _, _, err := a.RequestPool(as, pool, subPool, nil, false) <ide> func TestRequestSyntaxCheck(t *testing.T) { <ide> <ide> _, _, err = a.RequestAddress("", nil, nil) <ide> if err == nil { <del> t.Fatalf("Failed to detect wrong request: no pool id specified") <add> t.Fatal("Failed to detect wrong request: no pool id specified") <ide> } <ide> <ide> ip := net.ParseIP("172.17.0.23") <ide> _, _, err = a.RequestAddress(pid, ip, nil) <ide> if err == nil { <del> t.Fatalf("Failed to detect wrong request: requested IP from different subnet") <add> t.Fatal("Failed to detect wrong request: requested IP from different subnet") <ide> } <ide> <ide> ip = net.ParseIP("192.168.0.50") <ide> func TestRequestSyntaxCheck(t *testing.T) { <ide> <ide> err = a.ReleaseAddress("", ip) <ide> if err == nil { <del> t.Fatalf("Failed to detect wrong request: no pool id specified") <add> t.Fatal("Failed to detect wrong request: no pool id specified") <ide> } <ide> <ide> err = a.ReleaseAddress(pid, nil) <ide> if err == nil { <del> t.Fatalf("Failed to detect wrong request: no pool id specified") <add> t.Fatal("Failed to detect wrong request: no pool id specified") <ide> } <ide> <ide> err = a.ReleaseAddress(pid, ip) <ide><path>libnetwork/ipams/builtin/builtin_unix.go <ide> package builtin <ide> <ide> import ( <del> "fmt" <add> "errors" <ide> <ide> "github.com/docker/libnetwork/datastore" <ide> "github.com/docker/libnetwork/ipam" <ide> func Init(ic ipamapi.Callback, l, g interface{}) error { <ide> <ide> if l != nil { <ide> if localDs, ok = l.(datastore.DataStore); !ok { <del> return fmt.Errorf("incorrect local datastore passed to built-in ipam init") <add> return errors.New("incorrect local datastore passed to built-in ipam init") <ide> } <ide> } <ide> <ide> if g != nil { <ide> if globalDs, ok = g.(datastore.DataStore); !ok { <del> return fmt.Errorf("incorrect global datastore passed to built-in ipam init") <add> return errors.New("incorrect global datastore passed to built-in ipam init") <ide> } <ide> } <ide> <ide><path>libnetwork/ipams/builtin/builtin_windows.go <ide> package builtin <ide> <ide> import ( <del> "fmt" <add> "errors" <ide> <ide> "github.com/docker/libnetwork/datastore" <ide> "github.com/docker/libnetwork/ipam" <ide> func InitDockerDefault(ic ipamapi.Callback, l, g interface{}) error { <ide> <ide> if l != nil { <ide> if localDs, ok = l.(datastore.DataStore); !ok { <del> return fmt.Errorf("incorrect local datastore passed to built-in ipam init") <add> return errors.New("incorrect local datastore passed to built-in ipam init") <ide> } <ide> } <ide> <ide> if g != nil { <ide> if globalDs, ok = g.(datastore.DataStore); !ok { <del> return fmt.Errorf("incorrect global datastore passed to built-in ipam init") <add> return errors.New("incorrect global datastore passed to built-in ipam init") <ide> } <ide> } <ide> <ide><path>libnetwork/ipams/null/null_test.go <ide> func TestPoolRequest(t *testing.T) { <ide> <ide> _, _, _, err = a.RequestPool("default", "", "", nil, false) <ide> if err == nil { <del> t.Fatalf("Unexpected success") <add> t.Fatal("Unexpected success") <ide> } <ide> <ide> _, _, _, err = a.RequestPool(defaultAS, "192.168.0.0/16", "", nil, false) <ide> if err == nil { <del> t.Fatalf("Unexpected success") <add> t.Fatal("Unexpected success") <ide> } <ide> <ide> _, _, _, err = a.RequestPool(defaultAS, "", "192.168.0.0/24", nil, false) <ide> if err == nil { <del> t.Fatalf("Unexpected success") <add> t.Fatal("Unexpected success") <ide> } <ide> <ide> _, _, _, err = a.RequestPool(defaultAS, "", "", nil, true) <ide> if err == nil { <del> t.Fatalf("Unexpected success") <add> t.Fatal("Unexpected success") <ide> } <ide> } <ide> <ide> func TestOtherRequests(t *testing.T) { <ide> <ide> _, _, err = a.RequestAddress("anypid", nil, nil) <ide> if err == nil { <del> t.Fatalf("Unexpected success") <add> t.Fatal("Unexpected success") <ide> } <ide> <ide> } <ide><path>libnetwork/ipams/remote/remote_test.go <ide> func TestRemoteDriver(t *testing.T) { <ide> <ide> handle(t, mux, "ReleasePool", func(msg map[string]interface{}) interface{} { <ide> if _, ok := msg["PoolID"]; !ok { <del> t.Fatalf("Missing PoolID in Release request") <add> t.Fatal("Missing PoolID in Release request") <ide> } <ide> return map[string]interface{}{} <ide> }) <ide> <ide> handle(t, mux, "RequestAddress", func(msg map[string]interface{}) interface{} { <ide> if _, ok := msg["PoolID"]; !ok { <del> t.Fatalf("Missing PoolID in address request") <add> t.Fatal("Missing PoolID in address request") <ide> } <ide> prefAddr := "" <ide> if v, ok := msg["Address"]; ok { <ide> func TestRemoteDriver(t *testing.T) { <ide> <ide> handle(t, mux, "ReleaseAddress", func(msg map[string]interface{}) interface{} { <ide> if _, ok := msg["PoolID"]; !ok { <del> t.Fatalf("Missing PoolID in address request") <add> t.Fatal("Missing PoolID in address request") <ide> } <ide> if _, ok := msg["Address"]; !ok { <del> t.Fatalf("Missing Address in release address request") <add> t.Fatal("Missing Address in release address request") <ide> } <ide> return map[string]interface{}{} <ide> }) <ide> func TestRemoteDriver(t *testing.T) { <ide> t.Fatalf("Unexpected pool: %s", pool2) <ide> } <ide> if dns, ok := ops["DNS"]; !ok || dns != "8.8.8.8" { <del> t.Fatalf("Missing options") <add> t.Fatal("Missing options") <ide> } <ide> <ide> // Request specific pool and subpool <ide><path>libnetwork/iptables/firewalld_test.go <ide> func TestReloaded(t *testing.T) { <ide> "-j", "ACCEPT"} <ide> <ide> if !Exists(fwdChain.Table, fwdChain.Name, rule1...) { <del> t.Fatalf("rule1 does not exist") <add> t.Fatal("rule1 does not exist") <ide> } <ide> <ide> // flush all rules <ide> func TestReloaded(t *testing.T) { <ide> <ide> // make sure the rules have been recreated <ide> if !Exists(fwdChain.Table, fwdChain.Name, rule1...) { <del> t.Fatalf("rule1 hasn't been recreated") <add> t.Fatal("rule1 hasn't been recreated") <ide> } <ide> } <ide> <ide> func TestPassthrough(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> if !Exists(Filter, "INPUT", rule1...) { <del> t.Fatalf("rule1 does not exist") <add> t.Fatal("rule1 does not exist") <ide> } <ide> } <ide> <ide><path>libnetwork/iptables/iptables.go <ide> func NewChain(name string, table Table, hairpinMode bool) (*ChainInfo, error) { <ide> // ProgramChain is used to add rules to a chain <ide> func ProgramChain(c *ChainInfo, bridgeName string, hairpinMode, enable bool) error { <ide> if c.Name == "" { <del> return fmt.Errorf("Could not program chain, missing chain name") <add> return errors.New("Could not program chain, missing chain name") <ide> } <ide> <ide> switch c.Table { <ide><path>libnetwork/iptables/iptables_test.go <ide> func TestForward(t *testing.T) { <ide> } <ide> <ide> if !Exists(natChain.Table, natChain.Name, dnatRule...) { <del> t.Fatalf("DNAT rule does not exist") <add> t.Fatal("DNAT rule does not exist") <ide> } <ide> <ide> filterRule := []string{ <ide> func TestForward(t *testing.T) { <ide> } <ide> <ide> if !Exists(filterChain.Table, filterChain.Name, filterRule...) { <del> t.Fatalf("filter rule does not exist") <add> t.Fatal("filter rule does not exist") <ide> } <ide> <ide> masqRule := []string{ <ide> func TestForward(t *testing.T) { <ide> } <ide> <ide> if !Exists(natChain.Table, "POSTROUTING", masqRule...) { <del> t.Fatalf("MASQUERADE rule does not exist") <add> t.Fatal("MASQUERADE rule does not exist") <ide> } <ide> } <ide> <ide> func TestLink(t *testing.T) { <ide> "-j", "ACCEPT"} <ide> <ide> if !Exists(filterChain.Table, filterChain.Name, rule1...) { <del> t.Fatalf("rule1 does not exist") <add> t.Fatal("rule1 does not exist") <ide> } <ide> <ide> rule2 := []string{ <ide> func TestLink(t *testing.T) { <ide> "-j", "ACCEPT"} <ide> <ide> if !Exists(filterChain.Table, filterChain.Name, rule2...) { <del> t.Fatalf("rule2 does not exist") <add> t.Fatal("rule2 does not exist") <ide> } <ide> } <ide> <ide> func TestPrerouting(t *testing.T) { <ide> } <ide> <ide> if !Exists(natChain.Table, "PREROUTING", args...) { <del> t.Fatalf("rule does not exist") <add> t.Fatal("rule does not exist") <ide> } <ide> <ide> delRule := append([]string{"-D", "PREROUTING", "-t", string(Nat)}, args...) <ide> func TestOutput(t *testing.T) { <ide> } <ide> <ide> if !Exists(natChain.Table, "OUTPUT", args...) { <del> t.Fatalf("rule does not exist") <add> t.Fatal("rule does not exist") <ide> } <ide> <ide> delRule := append([]string{"-D", "OUTPUT", "-t", <ide> func TestExistsRaw(t *testing.T) { <ide> func TestGetVersion(t *testing.T) { <ide> mj, mn, mc := parseVersionNumbers("iptables v1.4.19.1-alpha") <ide> if mj != 1 || mn != 4 || mc != 19 { <del> t.Fatalf("Failed to parse version numbers") <add> t.Fatal("Failed to parse version numbers") <ide> } <ide> } <ide> <ide><path>libnetwork/netutils/utils.go <ide> func ReverseIP(IP string) string { <ide> // ParseAlias parses and validates the specified string as an alias format (name:alias) <ide> func ParseAlias(val string) (string, string, error) { <ide> if val == "" { <del> return "", "", fmt.Errorf("empty string specified for alias") <add> return "", "", errors.New("empty string specified for alias") <ide> } <ide> arr := strings.Split(val, ":") <ide> if len(arr) > 2 { <ide><path>libnetwork/netutils/utils_test.go <ide> func TestCheckRouteOverlaps(t *testing.T) { <ide> <ide> _, netX, _ = net.ParseCIDR("10.0.2.0/24") <ide> if err := CheckRouteOverlaps(netX); err == nil { <del> t.Fatalf("10.0.2.0/24 and 10.0.2.0 should overlap but it doesn't") <add> t.Fatal("10.0.2.0/24 and 10.0.2.0 should overlap but it doesn't") <ide> } <ide> } <ide> <ide> func TestElectInterfaceAddressMultipleAddresses(t *testing.T) { <ide> } <ide> <ide> if len(ipv4NwList) == 0 { <del> t.Fatalf("unexpected empty ipv4 network addresses") <add> t.Fatal("unexpected empty ipv4 network addresses") <ide> } <ide> <ide> if len(ipv6NwList) == 0 { <del> t.Fatalf("unexpected empty ipv6 network addresses") <add> t.Fatal("unexpected empty ipv6 network addresses") <ide> } <ide> <ide> nwList := []string{} <ide> func TestElectInterfaceAddress(t *testing.T) { <ide> } <ide> <ide> if len(ipv4Nw) == 0 { <del> t.Fatalf("unexpected empty ipv4 network addresses") <add> t.Fatal("unexpected empty ipv4 network addresses") <ide> } <ide> <ide> if len(ipv6Nw) == 0 { <del> t.Fatalf("unexpected empty ipv6 network addresses") <add> t.Fatal("unexpected empty ipv6 network addresses") <ide> } <ide> <ide> if nws != ipv4Nw[0].String() { <ide><path>libnetwork/networkdb/broadcast.go <ide> package networkdb <ide> <ide> import ( <del> "fmt" <add> "errors" <ide> "time" <ide> <ide> "github.com/hashicorp/memberlist" <ide> func (nDB *NetworkDB) sendNodeEvent(event NodeEvent_Type) error { <ide> select { <ide> case <-notifyCh: <ide> case <-time.After(broadcastTimeout): <del> return fmt.Errorf("timed out broadcasting node event") <add> return errors.New("timed out broadcasting node event") <ide> } <ide> <ide> return nil <ide><path>libnetwork/networkdb/networkdb_test.go <ide> func TestNetworkDBCRUDMediumCluster(t *testing.T) { <ide> dbs[i].verifyEntryExistence(t, "test_table", "network1", "test_key", "", false) <ide> } <ide> <del> log.Printf("Closing DB instances...") <add> log.Print("Closing DB instances...") <ide> closeNetworkDBInstances(dbs) <ide> }
42
Javascript
Javascript
propagate signal.reason in awaitable question
07fbed3d5f5520a97c7c0521f76addc6550b8fcb
<ide><path>lib/readline.js <ide> Interface.prototype.question[promisify.custom] = function(query, options) { <ide> options = typeof options === 'object' && options !== null ? options : {}; <ide> <ide> if (options.signal && options.signal.aborted) { <del> return PromiseReject(new AbortError()); <add> return PromiseReject( <add> new AbortError(undefined, { cause: options.signal.reason })); <ide> } <ide> <ide> return new Promise((resolve, reject) => { <ide> let cb = resolve; <ide> <ide> if (options.signal) { <ide> const onAbort = () => { <del> reject(new AbortError()); <add> reject(new AbortError(undefined, { cause: options.signal.reason })); <ide> }; <ide> options.signal.addEventListener('abort', onAbort, { once: true }); <ide> cb = (answer) => { <ide><path>lib/readline/promises.js <ide> class Interface extends _Interface { <ide> if (options?.signal) { <ide> validateAbortSignal(options.signal, 'options.signal'); <ide> if (options.signal.aborted) { <del> return reject(new AbortError()); <add> return reject( <add> new AbortError(undefined, { cause: options.signal.reason })); <ide> } <ide> <ide> const onAbort = () => { <ide> this[kQuestionCancel](); <del> reject(new AbortError()); <add> reject(new AbortError(undefined, { cause: options.signal.reason })); <ide> }; <ide> options.signal.addEventListener('abort', onAbort, { once: true }); <ide> cb = (answer) => { <ide><path>test/parallel/test-readline-promises-interface.js <ide> for (let i = 0; i < 12; i++) { <ide> rli.close(); <ide> } <ide> <add> (async () => { <add> const [rli] = getInterface({ terminal }); <add> const signal = AbortSignal.abort('boom'); <add> await assert.rejects(rli.question('hello', { signal }), { <add> cause: 'boom', <add> }); <add> rli.close(); <add> })().then(common.mustCall()); <add> <ide> // Throw an error when question is executed with an aborted signal <ide> { <ide> const ac = new AbortController();
3
Ruby
Ruby
move the mime registration code to setup so that
cdbbf6fd6bef3f286503859c585ada8fe66a3875
<ide><path>actionpack/test/controller/mime_responds_test.rb <ide> def custom_type_handling <ide> end <ide> end <ide> <del> Mime::Type.register("text/x-mobile", :mobile) <ide> <ide> def custom_constant_handling <ide> respond_to do |type| <ide> def all_types_with_layout <ide> end <ide> end <ide> <del> Mime::Type.register_alias("text/html", :iphone) <ide> <ide> def iphone_with_html_response_type <ide> request.format = :iphone if request.env["HTTP_ACCEPT"] == "text/iphone" <ide> class RespondToControllerTest < ActionController::TestCase <ide> def setup <ide> super <ide> @request.host = "www.example.com" <add> Mime::Type.register_alias("text/html", :iphone) <add> Mime::Type.register("text/x-mobile", :mobile) <ide> end <ide> <ide> def teardown <ide> super <add> Mime.module_eval { remove_const :IPHONE if const_defined?(:IPHONE) } <add> Mime.module_eval { remove_const :MOBILE if const_defined?(:MOBILE) } <add> Mime::LOOKUP.reject!{|key,_| key == 'text/x-mobile'} <add> Mime::LOOKUP.reject!{|key,_| key == 'text/iphone'} <ide> end <ide> <ide> def test_html <ide> def setup <ide> <ide> def teardown <ide> super <add> Mime.module_eval { remove_const :IPHONE if const_defined?(:IPHONE) } <add> Mime.module_eval { remove_const :MOBILE if const_defined?(:MOBILE) } <add> Mime::LOOKUP.reject!{|key,_| key == 'text/x-mobile'} <add> Mime::LOOKUP.reject!{|key,_| key == 'text/iphone'} <ide> end <ide> <ide> def test_using_resource <ide> class MimeControllerLayoutsTest < ActionController::TestCase <ide> def setup <ide> super <ide> @request.host = "www.example.com" <add> Mime::Type.register_alias("text/html", :iphone) <add> end <add> <add> def teardown <add> super <add> Mime.module_eval { remove_const :IPHONE if const_defined?(:IPHONE) } <add> Mime.module_eval { remove_const :MOBILE if const_defined?(:MOBILE) } <add> Mime::LOOKUP.reject!{|key,_| key == 'text/x-mobile'} <add> Mime::LOOKUP.reject!{|key,_| key == 'text/iphone'} <ide> end <ide> <ide> def test_missing_layout_renders_properly
1
Ruby
Ruby
eliminate warnings for am on 1.8
cd9ffd11e13ef6e62eba2cbd5c3760ff04132820
<ide><path>actionmailer/lib/action_mailer/old_api.rb <ide> module OldApi #:nodoc: <ide> # replies to this message. <ide> adv_attr_accessor :reply_to <ide> <del> # Specify additional headers to be added to the message. <del> adv_attr_accessor :headers <del> <ide> # Specify the order in which parts should be sorted, based on content-type. <ide> # This defaults to the value for the +default_implicit_parts_order+. <ide> adv_attr_accessor :implicit_parts_order <ide><path>actionmailer/test/abstract_unit.rb <del>require File.expand_path('../../../load_paths', __FILE__) <add># Pathname has a warning, so require it first while silencing <add># warnings to shut it up. <add># <add># Also, in 1.9, Bundler creates warnings due to overriding <add># Rubygems methods <add>begin <add> old, $VERBOSE = $VERBOSE, nil <add> require 'pathname' <add> require File.expand_path('../../../load_paths', __FILE__) <add>ensure <add> $VERBOSE = old <add>end <add> <add> <add>require 'active_support/core_ext/kernel/reporting' <add>silence_warnings do <add> # These external dependencies have warnings :/ <add> require 'text/format' <add> require 'mail' <add>end <ide> <ide> lib = File.expand_path("#{File.dirname(__FILE__)}/../lib") <ide> $:.unshift(lib) unless $:.include?('lib') || $:.include?(lib) <ide><path>actionmailer/test/old_base/url_test.rb <ide> class <<self <ide> attr_accessor :received_body <ide> end <ide> <add> remove_method :receive <add> <ide> def receive(mail) <ide> self.class.received_body = mail.body <ide> end <ide><path>actionpack/lib/abstract_controller/layouts.rb <add>require "active_support/core_ext/module/remove_method" <add> <ide> module AbstractController <ide> # Layouts reverse the common pattern of including shared headers and footers in many templates to isolate changes in <ide> # repeated setups. The inclusion pattern has pages that look like this: <ide> def _implied_layout_name <ide> # name, return that string. Otherwise, use the superclass' <ide> # layout (which might also be implied) <ide> def _write_layout_method <add> remove_possible_method(:_layout) <add> <ide> case defined?(@_layout) ? @_layout : nil <ide> when String <ide> self.class_eval %{def _layout; #{@_layout.inspect} end} <ide><path>actionpack/lib/action_controller/metal.rb <ide> def controller_name <ide> # and response object available. You might wish to control the <ide> # environment and response manually for performance reasons. <ide> <del> attr_internal :status, :headers, :content_type, :response, :request <add> attr_internal :headers, :response, :request <ide> delegate :session, :to => "@_request" <ide> <ide> def initialize(*) <ide> def location=(url) <ide> headers["Location"] = url <ide> end <ide> <add> def status <add> @_status <add> end <add> <ide> def status=(status) <ide> @_status = Rack::Utils.status_code(status) <ide> end <ide><path>actionpack/lib/action_controller/metal/rack_delegation.rb <ide> module ActionController <ide> module RackDelegation <ide> extend ActiveSupport::Concern <ide> <del> included do <del> delegate :headers, :status=, :location=, :content_type=, <del> :status, :location, :content_type, :to => "@_response" <del> end <add> delegate :headers, :status=, :location=, :content_type=, <add> :status, :location, :content_type, :to => "@_response" <ide> <ide> def dispatch(action, request) <ide> @_response = ActionDispatch::Response.new <ide><path>actionpack/lib/action_dispatch/http/filter_parameters.rb <ide> module Http <ide> module FilterParameters <ide> extend ActiveSupport::Concern <ide> <del> mattr_reader :compiled_parameter_filter_for <ide> @@compiled_parameter_filter_for = {} <ide> <ide> # Return a hash of parameters with all sensitive data replaced. <ide><path>actionpack/lib/action_view/helpers/capture_helper.rb <ide> module CaptureHelper <ide> # <ide> def capture(*args) <ide> value = nil <del> buffer = with_output_buffer { value = yield *args } <add> buffer = with_output_buffer { value = yield(*args) } <ide> if string = buffer.presence || value and string.is_a?(String) <ide> NonConcattingString.new(string) <ide> end <ide><path>activesupport/lib/active_support/core_ext/module.rb <ide> require 'active_support/core_ext/module/attr_accessor_with_default' <ide> require 'active_support/core_ext/module/delegation' <ide> require 'active_support/core_ext/module/synchronization' <del>require 'active_support/core_ext/module/deprecation' <ide>\ No newline at end of file <add>require 'active_support/core_ext/module/deprecation' <add>require 'active_support/core_ext/module/remove_method' <ide>\ No newline at end of file <ide><path>activesupport/lib/active_support/core_ext/module/delegation.rb <ide> class Module <ide> # class Foo <ide> # CONSTANT_ARRAY = [0,1,2,3] <ide> # @@class_array = [4,5,6,7] <del> # <add> # <ide> # def initialize <ide> # @instance_array = [8,9,10,11] <ide> # end <ide> def delegate(*methods) <ide> end <ide> <ide> module_eval(<<-EOS, file, line) <add> if instance_methods(false).map(&:to_s).include?("#{prefix}#{method}") <add> remove_method("#{prefix}#{method}") <add> end <add> <ide> def #{prefix}#{method}(*args, &block) # def customer_name(*args, &block) <ide> #{to}.__send__(#{method.inspect}, *args, &block) # client.__send__(:name, *args, &block) <ide> rescue NoMethodError # rescue NoMethodError <ide><path>activesupport/lib/active_support/core_ext/module/remove_method.rb <add>class Module <add> def remove_possible_method(method) <add> remove_method(method) <add> rescue NameError <add> end <add>end <ide>\ No newline at end of file
11
Ruby
Ruby
require formula name to be in issue title
1937625d861ef1ef7bc0796477fdb81e7dbb9cf4
<ide><path>Library/Homebrew/utils/github.rb <ide> def search_code(**qualifiers) <ide> <ide> def issues_for_formula(name, options = {}) <ide> tap = options[:tap] || CoreTap.instance <del> search_issues(name, state: "open", repo: "#{tap.user}/homebrew-#{tap.repo}") <add> search_issues(name, state: "open", repo: "#{tap.user}/homebrew-#{tap.repo}", in: "title") <ide> end <ide> <ide> def print_pull_requests_matching(query)
1
Javascript
Javascript
remove meteor-package from bump_version files
d6e4005204108c6253cf525ff67ae9c328ecbe1a
<ide><path>tasks/bump_version.js <ide> module.exports = function (grunt) { <ide> } <ide> }); <ide> <del> grunt.config('string-replace.meteor-package-js', { <del> files: {'meteor/package.js': 'meteor/package.js'}, <del> options: { <del> replacements: [ <del> { <del> pattern: /version: .*/, <del> replacement: "version: '" + version + "'," <del> } <del> ] <del> } <del> }); <del> <ide> grunt.task.run([ <ide> 'string-replace:moment-js', <ide> 'string-replace:package-json', <ide> 'string-replace:bower-json', <ide> 'string-replace:component-json', <del> 'string-replace:meteor-package-js' <ide> ]); <ide> }); <ide> };
1
Javascript
Javascript
use const in toolbar.js
790b0aede6d328a6a2b8c4ea786951e0c2b96a99
<ide><path>web/toolbar.js <ide> * See the License for the specific language governing permissions and <ide> * limitations under the License. <ide> */ <add>/* eslint no-var: error, prefer-const: error */ <ide> <ide> import { <ide> animationStarted, DEFAULT_SCALE, DEFAULT_SCALE_VALUE, MAX_SCALE, <ide> class Toolbar { <ide> items.zoomOut.disabled = (pageScale <= MIN_SCALE); <ide> items.zoomIn.disabled = (pageScale >= MAX_SCALE); <ide> <del> let customScale = Math.round(pageScale * 10000) / 100; <add> const customScale = Math.round(pageScale * 10000) / 100; <ide> this.l10n.get('page_scale_percent', { scale: customScale, }, <ide> '{{scale}}%').then((msg) => { <ide> let predefinedValueFound = false; <ide> class Toolbar { <ide> } <ide> <ide> updateLoadingIndicatorState(loading = false) { <del> let pageNumberInput = this.items.pageNumber; <add> const pageNumberInput = this.items.pageNumber; <ide> <ide> pageNumberInput.classList.toggle(PAGE_NUMBER_LOADING_INDICATOR, loading); <ide> } <ide> <ide> _adjustScaleWidth() { <del> let container = this.items.scaleSelectContainer; <del> let select = this.items.scaleSelect; <add> const container = this.items.scaleSelectContainer; <add> const select = this.items.scaleSelect; <ide> <ide> animationStarted.then(function() { <ide> // Adjust the width of the zoom box to fit the content. <ide> class Toolbar { <ide> } <ide> if (container.clientWidth > 0) { <ide> select.setAttribute('style', 'min-width: inherit;'); <del> let width = select.clientWidth + SCALE_SELECT_CONTAINER_PADDING; <add> const width = select.clientWidth + SCALE_SELECT_CONTAINER_PADDING; <ide> select.setAttribute('style', 'min-width: ' + <ide> (width + SCALE_SELECT_PADDING) + 'px;'); <ide> container.setAttribute('style', 'min-width: ' + width + 'px; ' +
1
Javascript
Javascript
add hascrypto check to tls-socket-close
5a71cb6d32c2e2b12cc5db9b7533fe42aba50c46
<ide><path>test/parallel/test-tls-socket-close.js <ide> 'use strict'; <ide> const common = require('../common'); <add>if (!common.hasCrypto) { <add> common.skip('missing crypto'); <add> return; <add>} <ide> const assert = require('assert'); <ide> <ide> const tls = require('tls');
1
Javascript
Javascript
move offscreen logic from suspense fiber
9ab90de602357407fb03a27715b61761a258a8c4
<ide><path>packages/react-reconciler/src/ReactFiberCommitWork.new.js <ide> function commitMutationEffectsOnFiber(finishedWork: Fiber, root: FiberRoot) { <ide> case SuspenseComponent: { <ide> const newState: OffscreenState | null = finishedWork.memoizedState; <ide> const isHidden = newState !== null; <del> const current = finishedWork.alternate; <del> const wasHidden = current !== null && current.memoizedState !== null; <del> const offscreenBoundary: Fiber = (finishedWork.child: any); <del> <ide> if (isHidden) { <add> const current = finishedWork.alternate; <add> const wasHidden = current !== null && current.memoizedState !== null; <ide> if (!wasHidden) { <add> // TODO: Move to passive phase <ide> markCommitTimeOfFallback(); <del> if (supportsMutation) { <del> hideOrUnhideAllChildren(offscreenBoundary, true); <del> } <del> if ( <del> enableSuspenseLayoutEffectSemantics && <del> (offscreenBoundary.mode & ConcurrentMode) !== NoMode <del> ) { <del> let offscreenChild = offscreenBoundary.child; <del> while (offscreenChild !== null) { <del> nextEffect = offscreenChild; <del> disappearLayoutEffects_begin(offscreenChild); <del> offscreenChild = offscreenChild.sibling; <del> } <del> } <del> } <del> } else { <del> if (wasHidden) { <del> if (supportsMutation) { <del> hideOrUnhideAllChildren(offscreenBoundary, false); <del> } <del> // TODO: Move re-appear call here for symmetry? <ide> } <ide> } <ide> break; <ide><path>packages/react-reconciler/src/ReactFiberCommitWork.old.js <ide> function commitMutationEffectsOnFiber(finishedWork: Fiber, root: FiberRoot) { <ide> case SuspenseComponent: { <ide> const newState: OffscreenState | null = finishedWork.memoizedState; <ide> const isHidden = newState !== null; <del> const current = finishedWork.alternate; <del> const wasHidden = current !== null && current.memoizedState !== null; <del> const offscreenBoundary: Fiber = (finishedWork.child: any); <del> <ide> if (isHidden) { <add> const current = finishedWork.alternate; <add> const wasHidden = current !== null && current.memoizedState !== null; <ide> if (!wasHidden) { <add> // TODO: Move to passive phase <ide> markCommitTimeOfFallback(); <del> if (supportsMutation) { <del> hideOrUnhideAllChildren(offscreenBoundary, true); <del> } <del> if ( <del> enableSuspenseLayoutEffectSemantics && <del> (offscreenBoundary.mode & ConcurrentMode) !== NoMode <del> ) { <del> let offscreenChild = offscreenBoundary.child; <del> while (offscreenChild !== null) { <del> nextEffect = offscreenChild; <del> disappearLayoutEffects_begin(offscreenChild); <del> offscreenChild = offscreenChild.sibling; <del> } <del> } <del> } <del> } else { <del> if (wasHidden) { <del> if (supportsMutation) { <del> hideOrUnhideAllChildren(offscreenBoundary, false); <del> } <del> // TODO: Move re-appear call here for symmetry? <ide> } <ide> } <ide> break; <ide><path>packages/react-reconciler/src/ReactFiberCompleteWork.new.js <ide> if (supportsMutation) { <ide> // If we have a portal child, then we don't want to traverse <ide> // down its children. Instead, we'll get insertions from each child in <ide> // the portal directly. <del> } else if (node.tag === SuspenseComponent) { <del> if ((node.flags & Visibility) !== NoFlags) { <del> // Need to toggle the visibility of the primary children. <del> const newIsHidden = node.memoizedState !== null; <del> if (newIsHidden) { <del> const primaryChildParent = node.child; <del> if (primaryChildParent !== null) { <del> if (primaryChildParent.child !== null) { <del> primaryChildParent.child.return = primaryChildParent; <del> appendAllChildren( <del> parent, <del> primaryChildParent, <del> true, <del> newIsHidden, <del> ); <del> } <del> const fallbackChildParent = primaryChildParent.sibling; <del> if (fallbackChildParent !== null) { <del> fallbackChildParent.return = node; <del> node = fallbackChildParent; <del> continue; <del> } <del> } <del> } <del> } <del> if (node.child !== null) { <del> // Continue traversing like normal <del> node.child.return = node; <del> node = node.child; <del> continue; <add> } else if ( <add> node.tag === OffscreenComponent && <add> node.memoizedState !== null <add> ) { <add> // The children in this boundary are hidden. Toggle their visibility <add> // before appending. <add> const child = node.child; <add> if (child !== null) { <add> child.return = node; <ide> } <add> appendAllChildren(parent, node, true, true); <ide> } else if (node.child !== null) { <ide> node.child.return = node; <ide> node = node.child; <ide> if (supportsMutation) { <ide> // If we have a portal child, then we don't want to traverse <ide> // down its children. Instead, we'll get insertions from each child in <ide> // the portal directly. <del> } else if (node.tag === SuspenseComponent) { <del> if ((node.flags & Visibility) !== NoFlags) { <del> // Need to toggle the visibility of the primary children. <del> const newIsHidden = node.memoizedState !== null; <del> if (newIsHidden) { <del> const primaryChildParent = node.child; <del> if (primaryChildParent !== null) { <del> if (primaryChildParent.child !== null) { <del> primaryChildParent.child.return = primaryChildParent; <del> appendAllChildrenToContainer( <del> containerChildSet, <del> primaryChildParent, <del> true, <del> newIsHidden, <del> ); <del> } <del> const fallbackChildParent = primaryChildParent.sibling; <del> if (fallbackChildParent !== null) { <del> fallbackChildParent.return = node; <del> node = fallbackChildParent; <del> continue; <del> } <del> } <del> } <del> } <del> if (node.child !== null) { <del> // Continue traversing like normal <del> node.child.return = node; <del> node = node.child; <del> continue; <add> } else if ( <add> node.tag === OffscreenComponent && <add> node.memoizedState !== null <add> ) { <add> // The children in this boundary are hidden. Toggle their visibility <add> // before appending. <add> const child = node.child; <add> if (child !== null) { <add> child.return = node; <ide> } <add> appendAllChildrenToContainer(containerChildSet, node, true, true); <ide> } else if (node.child !== null) { <ide> node.child.return = node; <ide> node = node.child; <ide> function completeWork( <ide> prevDidTimeout = prevState !== null; <ide> } <ide> <add> // If the suspended state of the boundary changes, we need to schedule <add> // an effect to toggle the subtree's visibility. When we switch from <add> // fallback -> primary, the inner Offscreen fiber schedules this effect <add> // as part of its normal complete phase. But when we switch from <add> // primary -> fallback, the inner Offscreen fiber does not have a complete <add> // phase. So we need to schedule its effect here. <add> // <add> // We also use this flag to connect/disconnect the effects, but the same <add> // logic applies: when re-connecting, the Offscreen fiber's complete <add> // phase will handle scheduling the effect. It's only when the fallback <add> // is active that we have to do anything special. <ide> if (nextDidTimeout && !prevDidTimeout) { <add> const offscreenFiber: Fiber = (workInProgress.child: any); <add> offscreenFiber.flags |= Visibility; <add> <ide> // TODO: This will still suspend a synchronous tree if anything <ide> // in the concurrent tree already suspended during this render. <ide> // This is a known bug. <ide> function completeWork( <ide> workInProgress.flags |= Update; <ide> } <ide> <del> if (supportsMutation) { <del> if (nextDidTimeout !== prevDidTimeout) { <del> // In mutation mode, visibility is toggled by mutating the nearest <del> // host nodes whenever they switch from hidden -> visible or vice <del> // versa. We don't need to switch when the boundary updates but its <del> // visibility hasn't changed. <del> workInProgress.flags |= Visibility; <del> } <del> } <del> if (supportsPersistence) { <del> if (nextDidTimeout) { <del> // In persistent mode, visibility is toggled by cloning the nearest <del> // host nodes in the complete phase whenever the boundary is hidden. <del> // TODO: The plan is to add a transparent host wrapper (no layout) <del> // around the primary children and hide that node. Then we don't need <del> // to do the funky cloning business. <del> workInProgress.flags |= Visibility; <del> } <del> } <del> <ide> if ( <ide> enableSuspenseCallback && <ide> workInProgress.updateQueue !== null && <ide><path>packages/react-reconciler/src/ReactFiberCompleteWork.old.js <ide> if (supportsMutation) { <ide> // If we have a portal child, then we don't want to traverse <ide> // down its children. Instead, we'll get insertions from each child in <ide> // the portal directly. <del> } else if (node.tag === SuspenseComponent) { <del> if ((node.flags & Visibility) !== NoFlags) { <del> // Need to toggle the visibility of the primary children. <del> const newIsHidden = node.memoizedState !== null; <del> if (newIsHidden) { <del> const primaryChildParent = node.child; <del> if (primaryChildParent !== null) { <del> if (primaryChildParent.child !== null) { <del> primaryChildParent.child.return = primaryChildParent; <del> appendAllChildren( <del> parent, <del> primaryChildParent, <del> true, <del> newIsHidden, <del> ); <del> } <del> const fallbackChildParent = primaryChildParent.sibling; <del> if (fallbackChildParent !== null) { <del> fallbackChildParent.return = node; <del> node = fallbackChildParent; <del> continue; <del> } <del> } <del> } <del> } <del> if (node.child !== null) { <del> // Continue traversing like normal <del> node.child.return = node; <del> node = node.child; <del> continue; <add> } else if ( <add> node.tag === OffscreenComponent && <add> node.memoizedState !== null <add> ) { <add> // The children in this boundary are hidden. Toggle their visibility <add> // before appending. <add> const child = node.child; <add> if (child !== null) { <add> child.return = node; <ide> } <add> appendAllChildren(parent, node, true, true); <ide> } else if (node.child !== null) { <ide> node.child.return = node; <ide> node = node.child; <ide> if (supportsMutation) { <ide> // If we have a portal child, then we don't want to traverse <ide> // down its children. Instead, we'll get insertions from each child in <ide> // the portal directly. <del> } else if (node.tag === SuspenseComponent) { <del> if ((node.flags & Visibility) !== NoFlags) { <del> // Need to toggle the visibility of the primary children. <del> const newIsHidden = node.memoizedState !== null; <del> if (newIsHidden) { <del> const primaryChildParent = node.child; <del> if (primaryChildParent !== null) { <del> if (primaryChildParent.child !== null) { <del> primaryChildParent.child.return = primaryChildParent; <del> appendAllChildrenToContainer( <del> containerChildSet, <del> primaryChildParent, <del> true, <del> newIsHidden, <del> ); <del> } <del> const fallbackChildParent = primaryChildParent.sibling; <del> if (fallbackChildParent !== null) { <del> fallbackChildParent.return = node; <del> node = fallbackChildParent; <del> continue; <del> } <del> } <del> } <del> } <del> if (node.child !== null) { <del> // Continue traversing like normal <del> node.child.return = node; <del> node = node.child; <del> continue; <add> } else if ( <add> node.tag === OffscreenComponent && <add> node.memoizedState !== null <add> ) { <add> // The children in this boundary are hidden. Toggle their visibility <add> // before appending. <add> const child = node.child; <add> if (child !== null) { <add> child.return = node; <ide> } <add> appendAllChildrenToContainer(containerChildSet, node, true, true); <ide> } else if (node.child !== null) { <ide> node.child.return = node; <ide> node = node.child; <ide> function completeWork( <ide> prevDidTimeout = prevState !== null; <ide> } <ide> <add> // If the suspended state of the boundary changes, we need to schedule <add> // an effect to toggle the subtree's visibility. When we switch from <add> // fallback -> primary, the inner Offscreen fiber schedules this effect <add> // as part of its normal complete phase. But when we switch from <add> // primary -> fallback, the inner Offscreen fiber does not have a complete <add> // phase. So we need to schedule its effect here. <add> // <add> // We also use this flag to connect/disconnect the effects, but the same <add> // logic applies: when re-connecting, the Offscreen fiber's complete <add> // phase will handle scheduling the effect. It's only when the fallback <add> // is active that we have to do anything special. <ide> if (nextDidTimeout && !prevDidTimeout) { <add> const offscreenFiber: Fiber = (workInProgress.child: any); <add> offscreenFiber.flags |= Visibility; <add> <ide> // TODO: This will still suspend a synchronous tree if anything <ide> // in the concurrent tree already suspended during this render. <ide> // This is a known bug. <ide> function completeWork( <ide> workInProgress.flags |= Update; <ide> } <ide> <del> if (supportsMutation) { <del> if (nextDidTimeout !== prevDidTimeout) { <del> // In mutation mode, visibility is toggled by mutating the nearest <del> // host nodes whenever they switch from hidden -> visible or vice <del> // versa. We don't need to switch when the boundary updates but its <del> // visibility hasn't changed. <del> workInProgress.flags |= Visibility; <del> } <del> } <del> if (supportsPersistence) { <del> if (nextDidTimeout) { <del> // In persistent mode, visibility is toggled by cloning the nearest <del> // host nodes in the complete phase whenever the boundary is hidden. <del> // TODO: The plan is to add a transparent host wrapper (no layout) <del> // around the primary children and hide that node. Then we don't need <del> // to do the funky cloning business. <del> workInProgress.flags |= Visibility; <del> } <del> } <del> <ide> if ( <ide> enableSuspenseCallback && <ide> workInProgress.updateQueue !== null && <ide><path>packages/react-reconciler/src/__tests__/ReactOffscreen-test.js <ide> describe('ReactOffscreen', () => { <ide> }); <ide> // No layout effect. <ide> expect(Scheduler).toHaveYielded(['Child']); <del> // TODO: Offscreen does not yet hide/unhide children correctly. Until we do, <del> // it should only be used inside a host component wrapper whose visibility <del> // is toggled simultaneously. <del> expect(root).toMatchRenderedOutput(<span prop="Child" />); <add> if (gate(flags => flags.persistent)) { <add> expect(root).toMatchRenderedOutput(<span hidden={true} prop="Child" />); <add> } else { <add> // TODO: Offscreen does not yet hide/unhide children correctly in mutation <add> // mode. Until we do, it should only be used inside a host component <add> // wrapper whose visibility is toggled simultaneously. <add> expect(root).toMatchRenderedOutput(<span prop="Child" />); <add> } <ide> <ide> // Unhide the tree. The layout effect is mounted. <ide> await act(async () => { <ide> describe('ReactOffscreen', () => { <ide> ); <ide> }); <ide> expect(Scheduler).toHaveYielded(['Unmount layout', 'Child']); <del> // TODO: Offscreen does not yet hide/unhide children correctly. Until we do, <del> // it should only be used inside a host component wrapper whose visibility <del> // is toggled simultaneously. <del> expect(root).toMatchRenderedOutput(<span prop="Child" />); <add> if (gate(flags => flags.persistent)) { <add> expect(root).toMatchRenderedOutput(<span hidden={true} prop="Child" />); <add> } else { <add> // TODO: Offscreen does not yet hide/unhide children correctly in mutation <add> // mode. Until we do, it should only be used inside a host component <add> // wrapper whose visibility is toggled simultaneously. <add> expect(root).toMatchRenderedOutput(<span prop="Child" />); <add> } <ide> <ide> // Unhide the tree. The layout effect is re-mounted. <ide> await act(async () => { <ide> describe('ReactOffscreen', () => { <ide> ); <ide> }); <ide> expect(Scheduler).toHaveYielded(['Child']); <del> // TODO: Offscreen does not yet hide/unhide children correctly. Until we do, <del> // it should only be used inside a host component wrapper whose visibility <del> // is toggled simultaneously. <del> expect(root).toMatchRenderedOutput(<span prop="Child" />); <add> if (gate(flags => flags.persistent)) { <add> expect(root).toMatchRenderedOutput(<span hidden={true} prop="Child" />); <add> } else { <add> // TODO: Offscreen does not yet hide/unhide children correctly in mutation <add> // mode. Until we do, it should only be used inside a host component <add> // wrapper whose visibility is toggled simultaneously. <add> expect(root).toMatchRenderedOutput(<span prop="Child" />); <add> } <ide> <ide> // Show the tree. The layout effect is mounted. <ide> await act(async () => { <ide> describe('ReactOffscreen', () => { <ide> ); <ide> }); <ide> expect(Scheduler).toHaveYielded(['Unmount layout', 'Child']); <del> // TODO: Offscreen does not yet hide/unhide children correctly. Until we do, <del> // it should only be used inside a host component wrapper whose visibility <del> // is toggled simultaneously. <del> expect(root).toMatchRenderedOutput(<span prop="Child" />); <add> if (gate(flags => flags.persistent)) { <add> expect(root).toMatchRenderedOutput(<span hidden={true} prop="Child" />); <add> } else { <add> // TODO: Offscreen does not yet hide/unhide children correctly in mutation <add> // mode. Until we do, it should only be used inside a host component <add> // wrapper whose visibility is toggled simultaneously. <add> expect(root).toMatchRenderedOutput(<span prop="Child" />); <add> } <ide> }); <ide> });
5
Javascript
Javascript
allow non-indexed buffergeometries
8874516ec257f1782adfb7276a557973ab0d928d
<ide><path>src/renderers/WebGLRenderer.js <ide> THREE.WebGLRenderer = function ( parameters ) { <ide> <ide> if ( object instanceof THREE.Mesh ) { <ide> <del> var offsets = geometry.offsets; <add> var index = geometry.attributes["index"]; <add> if (index) { <add> // Indexed triangles <add> var offsets = geometry.offsets; <ide> <del> // if there is more than 1 chunk <del> // must set attribute pointers to use new offsets for each chunk <del> // even if geometry and materials didn't change <add> // if there is more than 1 chunk <add> // must set attribute pointers to use new offsets for each chunk <add> // even if geometry and materials didn't change <ide> <del> if ( offsets.length > 1 ) updateBuffers = true; <add> if (offsets.length > 1) updateBuffers = true; <ide> <del> for ( var i = 0, il = offsets.length; i < il; ++ i ) { <add> for (var i = 0, il = offsets.length; i < il; ++i) { <ide> <del> var startIndex = offsets[ i ].index; <add> var startIndex = offsets[i].index; <ide> <del> if ( updateBuffers ) { <add> if (updateBuffers) { <ide> <del> // vertices <add> // vertices <ide> <del> var position = geometry.attributes[ "position" ]; <del> var positionSize = position.itemSize; <add> var position = geometry.attributes["position"]; <add> var positionSize = position.itemSize; <ide> <del> _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer ); <del> enableAttribute( attributes.position ); <del> _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, startIndex * positionSize * 4 ); // 4 bytes per Float32 <add> _gl.bindBuffer(_gl.ARRAY_BUFFER, position.buffer); <add> enableAttribute(attributes.position); <add> _gl.vertexAttribPointer(attributes.position, positionSize, _gl.FLOAT, false, 0, startIndex * positionSize * 4); // 4 bytes per Float32 <ide> <del> // normals <add> // normals <ide> <del> var normal = geometry.attributes[ "normal" ]; <add> var normal = geometry.attributes["normal"]; <ide> <del> if ( attributes.normal >= 0 && normal ) { <add> if (attributes.normal >= 0 && normal) { <ide> <del> var normalSize = normal.itemSize; <add> var normalSize = normal.itemSize; <ide> <del> _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer ); <del> enableAttribute( attributes.normal ); <del> _gl.vertexAttribPointer( attributes.normal, normalSize, _gl.FLOAT, false, 0, startIndex * normalSize * 4 ); <add> _gl.bindBuffer(_gl.ARRAY_BUFFER, normal.buffer); <add> enableAttribute(attributes.normal); <add> _gl.vertexAttribPointer(attributes.normal, normalSize, _gl.FLOAT, false, 0, startIndex * normalSize * 4); <ide> <del> } <add> } <ide> <del> // uvs <add> // uvs <ide> <del> var uv = geometry.attributes[ "uv" ]; <add> var uv = geometry.attributes["uv"]; <ide> <del> if ( attributes.uv >= 0 && uv ) { <add> if (attributes.uv >= 0 && uv) { <ide> <del> var uvSize = uv.itemSize; <add> var uvSize = uv.itemSize; <ide> <del> _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer ); <del> enableAttribute( attributes.uv ); <del> _gl.vertexAttribPointer( attributes.uv, uvSize, _gl.FLOAT, false, 0, startIndex * uvSize * 4 ); <add> _gl.bindBuffer(_gl.ARRAY_BUFFER, uv.buffer); <add> enableAttribute(attributes.uv); <add> _gl.vertexAttribPointer(attributes.uv, uvSize, _gl.FLOAT, false, 0, startIndex * uvSize * 4); <ide> <del> } <add> } <ide> <del> // colors <add> // colors <ide> <del> var color = geometry.attributes[ "color" ]; <add> var color = geometry.attributes["color"]; <ide> <del> if ( attributes.color >= 0 && color ) { <add> if (attributes.color >= 0 && color) { <ide> <del> var colorSize = color.itemSize; <add> var colorSize = color.itemSize; <ide> <del> _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer ); <del> enableAttribute( attributes.color ); <del> _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, startIndex * colorSize * 4 ); <add> _gl.bindBuffer(_gl.ARRAY_BUFFER, color.buffer); <add> enableAttribute(attributes.color); <add> _gl.vertexAttribPointer(attributes.color, colorSize, _gl.FLOAT, false, 0, startIndex * colorSize * 4); <ide> <del> } <add> } <ide> <del> // tangents <add> // tangents <ide> <del> var tangent = geometry.attributes[ "tangent" ]; <add> var tangent = geometry.attributes["tangent"]; <ide> <del> if ( attributes.tangent >= 0 && tangent ) { <add> if (attributes.tangent >= 0 && tangent) { <ide> <del> var tangentSize = tangent.itemSize; <add> var tangentSize = tangent.itemSize; <ide> <del> _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer ); <del> enableAttribute( attributes.tangent ); <del> _gl.vertexAttribPointer( attributes.tangent, tangentSize, _gl.FLOAT, false, 0, startIndex * tangentSize * 4 ); <add> _gl.bindBuffer(_gl.ARRAY_BUFFER, tangent.buffer); <add> enableAttribute(attributes.tangent); <add> _gl.vertexAttribPointer(attributes.tangent, tangentSize, _gl.FLOAT, false, 0, startIndex * tangentSize * 4); <ide> <del> } <add> } <ide> <del> // indices <add> // indices <add> <add> _gl.bindBuffer(_gl.ELEMENT_ARRAY_BUFFER, index.buffer); <ide> <del> var index = geometry.attributes[ "index" ]; <add> } <ide> <del> _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer ); <add> // render indexed triangles <ide> <del> } <add> _gl.drawElements(_gl.TRIANGLES, offsets[i].count, _gl.UNSIGNED_SHORT, offsets[i].start * 2); // 2 bytes per Uint16 <ide> <del> // render indexed triangles <add> _this.info.render.calls++; <add> _this.info.render.vertices += offsets[i].count; // not really true, here vertices can be shared <add> _this.info.render.faces += offsets[i].count / 3; <ide> <del> _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16 <add> } <ide> <del> _this.info.render.calls ++; <del> _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared <del> _this.info.render.faces += offsets[ i ].count / 3; <add> } <add> else <add> { <add> // non-indexed triangles <add> if (updateBuffers) { <ide> <del> } <add> // vertices <add> var position = geometry.attributes["position"]; <add> var positionSize = position.itemSize; <add> <add> _gl.bindBuffer(_gl.ARRAY_BUFFER, position.buffer); <add> enableAttribute(attributes.position); <add> _gl.vertexAttribPointer(attributes.position, positionSize, _gl.FLOAT, false, 0, 0); <add> <add> // normals <add> <add> var normal = geometry.attributes["normal"]; <add> <add> if (attributes.normal >= 0 && normal) { <add> <add> var normalSize = normal.itemSize; <add> <add> _gl.bindBuffer(_gl.ARRAY_BUFFER, normal.buffer); <add> enableAttribute(attributes.normal); <add> _gl.vertexAttribPointer(attributes.normal, normalSize, _gl.FLOAT, false, 0, 0); <add> <add> } <add> <add> // uvs <add> <add> var uv = geometry.attributes["uv"]; <add> <add> if (attributes.uv >= 0 && uv) { <add> <add> var uvSize = uv.itemSize; <add> <add> _gl.bindBuffer(_gl.ARRAY_BUFFER, uv.buffer); <add> enableAttribute(attributes.uv); <add> _gl.vertexAttribPointer(attributes.uv, uvSize, _gl.FLOAT, false, 0, 0); <add> <add> } <add> <add> // colors <add> <add> var color = geometry.attributes["color"]; <add> <add> if (attributes.color >= 0 && color) { <add> <add> var colorSize = color.itemSize; <add> <add> _gl.bindBuffer(_gl.ARRAY_BUFFER, color.buffer); <add> enableAttribute(attributes.color); <add> _gl.vertexAttribPointer(attributes.color, colorSize, _gl.FLOAT, false, 0, 0); <add> <add> } <add> <add> // tangents <add> <add> var tangent = geometry.attributes["tangent"]; <add> <add> if (attributes.tangent >= 0 && tangent) { <add> <add> var tangentSize = tangent.itemSize; <add> <add> _gl.bindBuffer(_gl.ARRAY_BUFFER, tangent.buffer); <add> enableAttribute(attributes.tangent); <add> _gl.vertexAttribPointer(attributes.tangent, tangentSize, _gl.FLOAT, false, 0, 0); <add> <add> } <add> <add> } <add> <add> // render non-indexed triangles <add> <add> _gl.drawArrays(_gl.TRIANGLES, 0, position.numItems / 3); <add> <add> _this.info.render.calls++; <add> _this.info.render.vertices += position.numItems / 3; <add> _this.info.render.faces += position.numItems / 3 / 3; <add> <add> } <ide> <ide> // render particles <ide>
1
Go
Go
increase the coverage of pkg/plugins
8dd100a2297a34a0aef422383117fb0c3314fba1
<ide><path>pkg/plugins/client.go <ide> func NewClient(addr string, tlsConfig *tlsconfig.Options) (*Client, error) { <ide> } <ide> <ide> // NewClientWithTimeout creates a new plugin client (http). <del>func NewClientWithTimeout(addr string, tlsConfig *tlsconfig.Options, timeoutInSecs int) (*Client, error) { <add>func NewClientWithTimeout(addr string, tlsConfig *tlsconfig.Options, timeout time.Duration) (*Client, error) { <ide> clientTransport, err := newTransport(addr, tlsConfig) <ide> if err != nil { <ide> return nil, err <ide> } <del> return newClientWithTransport(clientTransport, timeoutInSecs), nil <add> return newClientWithTransport(clientTransport, timeout), nil <ide> } <ide> <ide> // newClientWithTransport creates a new plugin client with a given transport. <del>func newClientWithTransport(tr transport.Transport, timeoutInSecs int) *Client { <add>func newClientWithTransport(tr transport.Transport, timeout time.Duration) *Client { <ide> return &Client{ <ide> http: &http.Client{ <ide> Transport: tr, <del> Timeout: time.Duration(timeoutInSecs) * time.Second, <add> Timeout: timeout, <ide> }, <ide> requestFactory: tr, <ide> } <ide><path>pkg/plugins/client_test.go <ide> package plugins <ide> <ide> import ( <add> "bytes" <add> "encoding/json" <ide> "io" <ide> "net/http" <ide> "net/http/httptest" <ide> "net/url" <del> "reflect" <ide> "strings" <ide> "testing" <ide> "time" <ide> <ide> "github.com/docker/docker/pkg/plugins/transport" <ide> "github.com/docker/go-connections/tlsconfig" <add> "github.com/stretchr/testify/assert" <ide> ) <ide> <ide> var ( <ide> func TestEchoInputOutput(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> <del> if !reflect.DeepEqual(output, m) { <del> t.Fatalf("Expected %v, was %v\n", m, output) <del> } <add> assert.Equal(t, m, output) <ide> err = c.Call("Test.Echo", nil, nil) <ide> if err != nil { <ide> t.Fatal(err) <ide> func TestClientScheme(t *testing.T) { <ide> } <ide> } <ide> } <add> <add>func TestNewClientWithTimeout(t *testing.T) { <add> addr := setupRemotePluginServer() <add> defer teardownRemotePluginServer() <add> <add> m := Manifest{[]string{"VolumeDriver", "NetworkDriver"}} <add> <add> mux.HandleFunc("/Test.Echo", func(w http.ResponseWriter, r *http.Request) { <add> time.Sleep(time.Duration(600) * time.Millisecond) <add> io.Copy(w, r.Body) <add> }) <add> <add> // setting timeout of 500ms <add> timeout := time.Duration(500) * time.Millisecond <add> c, _ := NewClientWithTimeout(addr, &tlsconfig.Options{InsecureSkipVerify: true}, timeout) <add> var output Manifest <add> err := c.Call("Test.Echo", m, &output) <add> if err == nil { <add> t.Fatal("Expected timeout error") <add> } <add>} <add> <add>func TestClientStream(t *testing.T) { <add> addr := setupRemotePluginServer() <add> defer teardownRemotePluginServer() <add> <add> m := Manifest{[]string{"VolumeDriver", "NetworkDriver"}} <add> var output Manifest <add> <add> mux.HandleFunc("/Test.Echo", func(w http.ResponseWriter, r *http.Request) { <add> if r.Method != "POST" { <add> t.Fatalf("Expected POST, got %s", r.Method) <add> } <add> <add> header := w.Header() <add> header.Set("Content-Type", transport.VersionMimetype) <add> <add> io.Copy(w, r.Body) <add> }) <add> <add> c, _ := NewClient(addr, &tlsconfig.Options{InsecureSkipVerify: true}) <add> body, err := c.Stream("Test.Echo", m) <add> if err != nil { <add> t.Fatal(err) <add> } <add> defer body.Close() <add> if err := json.NewDecoder(body).Decode(&output); err != nil { <add> t.Fatalf("Test.Echo: error reading plugin resp: %v", err) <add> } <add> assert.Equal(t, m, output) <add>} <add> <add>func TestClientSendFile(t *testing.T) { <add> addr := setupRemotePluginServer() <add> defer teardownRemotePluginServer() <add> <add> m := Manifest{[]string{"VolumeDriver", "NetworkDriver"}} <add> var output Manifest <add> var buf bytes.Buffer <add> if err := json.NewEncoder(&buf).Encode(m); err != nil { <add> t.Fatal(err) <add> } <add> mux.HandleFunc("/Test.Echo", func(w http.ResponseWriter, r *http.Request) { <add> if r.Method != "POST" { <add> t.Fatalf("Expected POST, got %s\n", r.Method) <add> } <add> <add> header := w.Header() <add> header.Set("Content-Type", transport.VersionMimetype) <add> <add> io.Copy(w, r.Body) <add> }) <add> <add> c, _ := NewClient(addr, &tlsconfig.Options{InsecureSkipVerify: true}) <add> if err := c.SendFile("Test.Echo", &buf, &output); err != nil { <add> t.Fatal(err) <add> } <add> assert.Equal(t, m, output) <add>} <ide><path>pkg/plugins/discovery_unix_test.go <ide> package plugins <ide> <ide> import ( <ide> "fmt" <add> "io/ioutil" <ide> "net" <ide> "os" <ide> "path/filepath" <ide> func TestLocalSocket(t *testing.T) { <ide> l.Close() <ide> } <ide> } <add> <add>func TestScan(t *testing.T) { <add> tmpdir, unregister := Setup(t) <add> defer unregister() <add> <add> pluginNames, err := Scan() <add> if err != nil { <add> t.Fatal(err) <add> } <add> if pluginNames != nil { <add> t.Fatal("Plugin names should be empty.") <add> } <add> <add> path := filepath.Join(tmpdir, "echo.spec") <add> addr := "unix://var/lib/docker/plugins/echo.sock" <add> name := "echo" <add> <add> err = os.MkdirAll(filepath.Dir(path), 0755) <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> err = ioutil.WriteFile(path, []byte(addr), 0644) <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> r := newLocalRegistry() <add> p, err := r.Plugin(name) <add> <add> pluginNamesNotEmpty, err := Scan() <add> if err != nil { <add> t.Fatal(err) <add> } <add> if p.Name() != pluginNamesNotEmpty[0] { <add> t.Fatalf("Unable to scan plugin with name %s", p.name) <add> } <add>} <ide><path>pkg/plugins/plugin_test.go <ide> package plugins <ide> <ide> import ( <add> "bytes" <add> "encoding/json" <ide> "errors" <add> "io" <add> "io/ioutil" <add> "net/http" <ide> "path/filepath" <ide> "runtime" <ide> "sync" <ide> "testing" <ide> "time" <add> <add> "github.com/docker/docker/pkg/plugins/transport" <add> "github.com/docker/go-connections/tlsconfig" <add> "github.com/stretchr/testify/assert" <add>) <add> <add>const ( <add> fruitPlugin = "fruit" <add> fruitImplements = "apple" <ide> ) <ide> <ide> // regression test for deadlock in handlers <ide> func testActive(t *testing.T, p *Plugin) { <ide> } <ide> <ide> } <add> <add>func TestGet(t *testing.T) { <add> p := &Plugin{name: fruitPlugin, activateWait: sync.NewCond(&sync.Mutex{})} <add> p.Manifest = &Manifest{Implements: []string{fruitImplements}} <add> storage.plugins[fruitPlugin] = p <add> <add> plugin, err := Get(fruitPlugin, fruitImplements) <add> if err != nil { <add> t.Fatal(err) <add> } <add> if p.Name() != plugin.Name() { <add> t.Fatalf("No matching plugin with name %s found", plugin.Name()) <add> } <add> if plugin.Client() != nil { <add> t.Fatal("expected nil Client but found one") <add> } <add> if !plugin.IsV1() { <add> t.Fatal("Expected true for V1 plugin") <add> } <add> <add> // check negative case where plugin fruit doesn't implement banana <add> _, err = Get("fruit", "banana") <add> assert.Equal(t, err, ErrNotImplements) <add> <add> // check negative case where plugin vegetable doesn't exist <add> _, err = Get("vegetable", "potato") <add> assert.Equal(t, err, ErrNotFound) <add> <add>} <add> <add>func TestPluginWithNoManifest(t *testing.T) { <add> addr := setupRemotePluginServer() <add> defer teardownRemotePluginServer() <add> <add> m := Manifest{[]string{fruitImplements}} <add> var buf bytes.Buffer <add> if err := json.NewEncoder(&buf).Encode(m); err != nil { <add> t.Fatal(err) <add> } <add> <add> mux.HandleFunc("/Plugin.Activate", func(w http.ResponseWriter, r *http.Request) { <add> if r.Method != "POST" { <add> t.Fatalf("Expected POST, got %s\n", r.Method) <add> } <add> <add> header := w.Header() <add> header.Set("Content-Type", transport.VersionMimetype) <add> <add> io.Copy(w, &buf) <add> }) <add> <add> p := &Plugin{ <add> name: fruitPlugin, <add> activateWait: sync.NewCond(&sync.Mutex{}), <add> Addr: addr, <add> TLSConfig: &tlsconfig.Options{InsecureSkipVerify: true}, <add> } <add> storage.plugins[fruitPlugin] = p <add> <add> plugin, err := Get(fruitPlugin, fruitImplements) <add> if err != nil { <add> t.Fatal(err) <add> } <add> if p.Name() != plugin.Name() { <add> t.Fatalf("No matching plugin with name %s found", plugin.Name()) <add> } <add>} <add> <add>func TestGetAll(t *testing.T) { <add> tmpdir, unregister := Setup(t) <add> defer unregister() <add> <add> p := filepath.Join(tmpdir, "example.json") <add> spec := `{ <add> "Name": "example", <add> "Addr": "https://example.com/docker/plugin" <add>}` <add> <add> if err := ioutil.WriteFile(p, []byte(spec), 0644); err != nil { <add> t.Fatal(err) <add> } <add> <add> r := newLocalRegistry() <add> plugin, err := r.Plugin("example") <add> if err != nil { <add> t.Fatal(err) <add> } <add> plugin.Manifest = &Manifest{Implements: []string{"apple"}} <add> storage.plugins["example"] = plugin <add> <add> fetchedPlugins, err := GetAll("apple") <add> if err != nil { <add> t.Fatal(err) <add> } <add> if fetchedPlugins[0].Name() != plugin.Name() { <add> t.Fatalf("Expected to get plugin with name %s", plugin.Name()) <add> } <add>} <ide><path>pkg/plugins/transport/http_test.go <add>package transport <add> <add>import ( <add> "io" <add> "net/http" <add> "testing" <add> <add> "github.com/stretchr/testify/assert" <add>) <add> <add>func TestHTTPTransport(t *testing.T) { <add> var r io.Reader <add> roundTripper := &http.Transport{} <add> newTransport := NewHTTPTransport(roundTripper, "http", "0.0.0.0") <add> request, err := newTransport.NewRequest("", r) <add> if err != nil { <add> t.Fatal(err) <add> } <add> assert.Equal(t, "POST", request.Method) <add>} <ide><path>plugin/manager_linux.go <ide> func (pm *Manager) enable(p *v2.Plugin, c *controller, force bool) error { <ide> <ide> func (pm *Manager) pluginPostStart(p *v2.Plugin, c *controller) error { <ide> sockAddr := filepath.Join(pm.config.ExecRoot, p.GetID(), p.GetSocket()) <del> client, err := plugins.NewClientWithTimeout("unix://"+sockAddr, nil, c.timeoutInSecs) <add> client, err := plugins.NewClientWithTimeout("unix://"+sockAddr, nil, time.Duration(c.timeoutInSecs)*time.Second) <ide> if err != nil { <ide> c.restart = false <ide> shutdownPlugin(p, c, pm.containerdClient)
6
PHP
PHP
remove unused "use" statements
4d5cdc7c1ca67b47da7e92973d337b14ec123663
<ide><path>tests/TestCase/View/ViewTest.php <ide> use Cake\Event\EventInterface; <ide> use Cake\Event\EventListenerInterface; <ide> use Cake\Http\ServerRequest; <del>use Cake\Routing\Router; <ide> use Cake\TestSuite\TestCase; <ide> use Cake\View\Helper; <ide> use Cake\View\View; <ide><path>tests/test_app/TestApp/Controller/Component/OrangeComponent.php <ide> namespace TestApp\Controller\Component; <ide> <ide> use Cake\Controller\Component; <del>use Cake\Controller\Controller; <ide> use Cake\Event\EventInterface; <ide> <ide> /** <ide><path>tests/test_app/TestApp/Controller/PostsController.php <ide> <ide> use Cake\Event\EventInterface; <ide> use Cake\Http\Cookie\Cookie; <del>use Cake\Utility\Security; <ide> <ide> /** <ide> * PostsController class <ide><path>tests/test_app/TestApp/Controller/SomePagesController.php <ide> namespace TestApp\Controller; <ide> <ide> use Cake\Controller\Controller; <del>use Cake\Http\Response; <ide> <ide> /** <ide> * SomePagesController class
4
Python
Python
save pod name to xcom for kubernetespodoperator
37d549bde79cd560d24748ebe7f94730115c0e88
<ide><path>airflow/providers/cncf/kubernetes/operators/kubernetes_pod.py <ide> def execute(self, context) -> Optional[str]: <ide> <ide> label_selector = self._get_pod_identifying_label_string(labels) <ide> <del> self.namespace = self.pod.metadata.namespace <del> <ide> pod_list = client.list_namespaced_pod(self.namespace, label_selector=label_selector) <ide> <ide> if len(pod_list.items) > 1 and self.reattach_on_restart: <ide> def execute(self, context) -> Optional[str]: <ide> if final_state != State.SUCCESS: <ide> status = self.client.read_namespaced_pod(self.pod.metadata.name, self.namespace) <ide> raise AirflowException(f'Pod {self.pod.metadata.name} returned a failure: {status}') <add> context['task_instance'].xcom_push(key='pod_name', value=self.pod.metadata.name) <add> context['task_instance'].xcom_push(key='pod_namespace', value=self.namespace) <ide> return result <ide> except AirflowException as ex: <ide> raise AirflowException(f'Pod Launching failed: {ex}') <ide><path>kubernetes_tests/test_kubernetes_pod_operator.py <ide> def create_context(task): <ide> tzinfo = pendulum.timezone("Europe/Amsterdam") <ide> execution_date = timezone.datetime(2016, 1, 1, 1, 0, 0, tzinfo=tzinfo) <ide> task_instance = TaskInstance(task=task, execution_date=execution_date) <add> task_instance.xcom_push = mock.Mock() <ide> return { <ide> "dag": dag, <ide> "ts": execution_date.isoformat(), <ide> "task": task, <ide> "ti": task_instance, <add> "task_instance": task_instance, <ide> } <ide> <ide> <ide><path>kubernetes_tests/test_kubernetes_pod_operator_backcompat.py <ide> def create_context(task): <ide> tzinfo = pendulum.timezone("Europe/Amsterdam") <ide> execution_date = timezone.datetime(2016, 1, 1, 1, 0, 0, tzinfo=tzinfo) <ide> task_instance = TaskInstance(task=task, execution_date=execution_date) <add> task_instance.xcom_push = mock.Mock() <ide> return { <ide> "dag": dag, <ide> "ts": execution_date.isoformat(), <ide> "task": task, <ide> "ti": task_instance, <add> "task_instance": task_instance, <ide> } <ide> <ide> <ide> def tearDown(self): <ide> client = kube_client.get_kube_client(in_cluster=False) <ide> client.delete_collection_namespaced_pod(namespace="default") <ide> <del> def create_context(self, task): <del> dag = DAG(dag_id="dag") <del> tzinfo = pendulum.timezone("Europe/Amsterdam") <del> execution_date = timezone.datetime(2016, 1, 1, 1, 0, 0, tzinfo=tzinfo) <del> task_instance = TaskInstance(task=task, execution_date=execution_date) <del> return { <del> "dag": dag, <del> "ts": execution_date.isoformat(), <del> "task": task, <del> "ti": task_instance, <del> } <del> <ide> @mock.patch("airflow.providers.cncf.kubernetes.utils.pod_launcher.PodLauncher.start_pod") <ide> @mock.patch("airflow.providers.cncf.kubernetes.utils.pod_launcher.PodLauncher.monitor_pod") <ide> @mock.patch("airflow.kubernetes.kube_client.get_kube_client") <ide> def test_image_pull_secrets_correctly_set(self, mock_client, monitor_mock, start <ide> cluster_context='default', <ide> ) <ide> monitor_mock.return_value = (State.SUCCESS, None) <del> context = self.create_context(k) <add> context = create_context(k) <ide> k.execute(context=context) <ide> assert start_mock.call_args[0][0].spec.image_pull_secrets == [ <ide> k8s.V1LocalObjectReference(name=fake_pull_secrets) <ide> def test_pod_resources(self): <ide> do_xcom_push=False, <ide> resources=resources, <ide> ) <del> context = self.create_context(k) <add> context = create_context(k) <ide> k.execute(context) <ide> actual_pod = self.api_client.sanitize_for_serialization(k.pod) <ide> self.expected_pod['spec']['containers'][0]['resources'] = { <ide> def test_port(self): <ide> do_xcom_push=False, <ide> ports=[port], <ide> ) <del> context = self.create_context(k) <add> context = create_context(k) <ide> k.execute(context=context) <ide> actual_pod = self.api_client.sanitize_for_serialization(k.pod) <ide> self.expected_pod['spec']['containers'][0]['ports'] = [{'name': 'http', 'containerPort': 80}] <ide> def test_envs_from_configmaps(self, mock_client, mock_monitor, mock_start): <ide> ) <ide> # THEN <ide> mock_monitor.return_value = (State.SUCCESS, None) <del> context = self.create_context(k) <add> context = create_context(k) <ide> k.execute(context) <ide> assert mock_start.call_args[0][0].spec.containers[0].env_from == [ <ide> k8s.V1EnvFromSource(config_map_ref=k8s.V1ConfigMapEnvSource(name=configmap)) <ide> def test_envs_from_secrets(self, mock_client, monitor_mock, start_mock): <ide> ) <ide> # THEN <ide> monitor_mock.return_value = (State.SUCCESS, None) <del> context = self.create_context(k) <add> context = create_context(k) <ide> k.execute(context) <ide> assert start_mock.call_args[0][0].spec.containers[0].env_from == [ <ide> k8s.V1EnvFromSource(secret_ref=k8s.V1SecretEnvSource(name=secret_ref)) <ide><path>tests/providers/cncf/kubernetes/operators/test_kubernetes_pod.py <ide> from tempfile import NamedTemporaryFile <ide> from unittest import mock <ide> <del>import pendulum <ide> import pytest <ide> from kubernetes.client import ApiClient, models as k8s <ide> <ide> from airflow.utils import timezone <ide> from airflow.utils.state import State <ide> <add>DEFAULT_DATE = timezone.datetime(2016, 1, 1, 1, 0, 0) <add> <ide> <ide> class TestKubernetesPodOperator(unittest.TestCase): <ide> def setUp(self): <ide> def setUp(self): <ide> @staticmethod <ide> def create_context(task): <ide> dag = DAG(dag_id="dag") <del> tzinfo = pendulum.timezone("Europe/Amsterdam") <del> execution_date = timezone.datetime(2016, 1, 1, 1, 0, 0, tzinfo=tzinfo) <del> task_instance = TaskInstance(task=task, execution_date=execution_date) <add> task_instance = TaskInstance(task=task, execution_date=DEFAULT_DATE) <ide> return { <ide> "dag": dag, <del> "ts": execution_date.isoformat(), <add> "ts": DEFAULT_DATE.isoformat(), <ide> "task": task, <ide> "ti": task_instance, <add> "task_instance": task_instance, <ide> } <ide> <ide> def run_pod(self, operator) -> k8s.V1Pod: <ide> def test_node_selector(self): <ide> sanitized_pod = self.sanitize_for_serialization(pod) <ide> assert isinstance(pod.spec.node_selector, dict) <ide> assert sanitized_pod["spec"]["nodeSelector"] == node_selector <add> <add> def test_push_xcom_pod_info(self): <add> k = KubernetesPodOperator( <add> namespace="default", <add> image="ubuntu:16.04", <add> cmds=["bash", "-cx"], <add> name="test", <add> task_id="task", <add> in_cluster=False, <add> do_xcom_push=False, <add> ) <add> pod = self.run_pod(k) <add> ti = TaskInstance(task=k, execution_date=DEFAULT_DATE) <add> pod_name = ti.xcom_pull(task_ids=k.task_id, key='pod_name') <add> pod_namespace = ti.xcom_pull(task_ids=k.task_id, key='pod_namespace') <add> assert pod_name and pod_name == pod.metadata.name <add> assert pod_namespace and pod_namespace == pod.metadata.namespace
4
Java
Java
delete unused imports
24adc7d3c6a27102696ebacd14bbc247a6acba8b
<ide><path>spring-web/src/main/java/org/springframework/http/codec/json/Jackson2SmileDecoder.java <ide> package org.springframework.http.codec.json; <ide> <ide> import java.nio.charset.StandardCharsets; <del>import java.util.Arrays; <del>import java.util.Collections; <del>import java.util.List; <ide> <ide> import com.fasterxml.jackson.databind.ObjectMapper; <ide> import com.fasterxml.jackson.dataformat.smile.SmileFactory; <ide> <del>import org.springframework.http.MediaType; <ide> import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; <ide> import org.springframework.util.Assert; <ide> import org.springframework.util.MimeType; <ide><path>spring-web/src/main/java/org/springframework/http/codec/json/Jackson2SmileEncoder.java <ide> package org.springframework.http.codec.json; <ide> <ide> import java.nio.charset.StandardCharsets; <del>import java.util.Collections; <ide> import java.util.List; <ide> <ide> import com.fasterxml.jackson.databind.ObjectMapper; <ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/ReactorServerHttpRequest.java <ide> /* <del> * Copyright 2002-2017 the original author or authors. <add> * Copyright 2002-2018 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> import org.springframework.util.Assert; <ide> import org.springframework.util.LinkedMultiValueMap; <ide> import org.springframework.util.MultiValueMap; <del>import org.springframework.util.StringUtils; <ide> <ide> /** <ide> * Adapt {@link ServerHttpRequest} to the Reactor {@link HttpServerRequest}. <ide><path>spring-web/src/test/java/org/springframework/http/codec/json/Jackson2SmileDecoderTests.java <ide> import static org.junit.Assert.assertTrue; <ide> import static org.springframework.core.ResolvableType.forClass; <ide> import static org.springframework.http.MediaType.APPLICATION_JSON; <del>import static org.springframework.http.MediaType.APPLICATION_STREAM_JSON; <ide> <ide> /** <ide> * Unit tests for {@link Jackson2SmileDecoder}. <ide><path>spring-web/src/test/java/org/springframework/http/codec/json/Jackson2SmileEncoderTests.java <ide> import org.springframework.core.io.buffer.DataBuffer; <ide> import org.springframework.core.io.buffer.DataBufferUtils; <ide> import org.springframework.core.io.buffer.support.DataBufferTestUtils; <del>import org.springframework.http.MediaType; <ide> import org.springframework.http.codec.Pojo; <ide> import org.springframework.http.codec.ServerSentEvent; <ide> import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; <ide><path>spring-web/src/test/java/org/springframework/web/server/session/InMemoryWebSessionStoreTests.java <ide> /* <del> * Copyright 2002-2017 the original author or authors. <add> * Copyright 2002-2018 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> <ide> import org.junit.Test; <ide> <del>import org.springframework.util.Assert; <ide> import org.springframework.web.server.WebSession; <ide> <ide> import static junit.framework.TestCase.assertSame;
6
Ruby
Ruby
add didyoumean suggestions for missing templates
6fa9cd88b9f66c83ae7608e7ae166c0abf6fe76c
<ide><path>actionview/lib/action_view/template/error.rb <ide> def message <ide> end <ide> <ide> class MissingTemplate < ActionViewError #:nodoc: <del> attr_reader :path <add> attr_reader :path, :paths, :prefixes <ide> <ide> def initialize(paths, path, prefixes, partial, details, *) <add> if partial && path.present? <add> path = path.sub(%r{([^/]+)$}, "_\\1") <add> end <add> <ide> @path = path <del> prefixes = Array(prefixes) <add> @paths = paths <add> @prefixes = Array(prefixes) <ide> template_type = if partial <ide> "partial" <ide> elsif /layouts/i.match?(path) <ide> def initialize(paths, path, prefixes, partial, details, *) <ide> "template" <ide> end <ide> <del> if partial && path.present? <del> path = path.sub(%r{([^/]+)$}, "_\\1") <del> end <del> searched_paths = prefixes.map { |prefix| [prefix, path].join("/") } <add> searched_paths = @prefixes.map { |prefix| [prefix, path].join("/") } <ide> <del> out = "Missing #{template_type} #{searched_paths.join(", ")} with #{details.inspect}. Searched in:\n" <add> out = "Missing #{template_type} #{searched_paths.join(", ")} with #{details.inspect}.\n\nSearched in:\n" <ide> out += paths.compact.map { |p| " * #{p.to_s.inspect}\n" }.join <ide> super out <ide> end <add> <add> class Correction <add> Result = Struct.new(:path, :score) <add> <add> class Results <add> def initialize(size) <add> @size = size <add> @results = [] <add> end <add> <add> def to_a <add> @results.map(&:path) <add> end <add> <add> def should_record?(score) <add> if @results.size < @size <add> true <add> else <add> score < @results.last.score <add> end <add> end <add> <add> def add(path, score) <add> if should_record?(score) <add> @results << Result.new(path, score) <add> @results.sort_by!(&:score) <add> @results.pop if @results.size > @size <add> end <add> end <add> end <add> <add> def initialize(error) <add> @error = error <add> end <add> <add> # Apps may have thousands of candidate templates so we attempt to <add> # generate the suggestions as efficiently as possible. <add> # First we split templates into prefixes and basenames, so that those can <add> # be matched separately. <add> def corrections <add> path = @error.path <add> prefixes = @error.prefixes <add> candidates = @error.paths.flat_map(&:template_paths_for_suggestions).uniq <add> <add> # Group by possible prefixes <add> files_by_dir = candidates.group_by do |x| <add> File.dirname(x) <add> end.transform_values do |files| <add> files.map do |file| <add> # Remove template extensions <add> File.basename(file).split(".", 2)[0] <add> end.uniq <add> end <add> <add> # No suggestions if there's an exact match, but wrong details <add> if prefixes.any? { |prefix| files_by_dir[prefix]&.include?(path) } <add> return [] <add> end <add> <add> cached_distance = Hash.new do |h, args| <add> h[args] = -DidYouMean::Jaro.distance(*args) <add> end <add> <add> results = Results.new(6) <add> <add> files_by_dir.keys.index_with do |dirname| <add> prefixes.map do |prefix| <add> cached_distance[[prefix, dirname]] <add> end.min <add> end.sort_by(&:last).each do |dirname, dirweight| <add> # If our directory's score makes it impossible to find a better match <add> # we can prune this search branch. <add> next unless results.should_record?(dirweight - 1.0) <add> <add> files = files_by_dir[dirname] <add> <add> files.each do |file| <add> fileweight = cached_distance[[path, file]] <add> score = dirweight + fileweight <add> <add> results.add(File.join(dirname, file), score) <add> end <add> end <add> <add> results.to_a <add> end <add> end <add> <add> if defined?(DidYouMean) && DidYouMean.respond_to?(:correct_error) <add> DidYouMean.correct_error(self, Correction) <add> end <ide> end <ide> <ide> class Template <ide><path>actionview/lib/action_view/template/resolver.rb <ide> def find_all_with_query(query) # :nodoc: <ide> @cache.cache_query(query) { find_template_paths(File.join(@path, query)) } <ide> end <ide> <add> def template_paths_for_suggestions # :nodoc: <add> # Not implemented by default <add> [] <add> end <add> <ide> private <ide> def _find_all(name, prefix, partial, details, key, locals) <ide> find_templates(name, prefix, partial, details, locals) <ide> def eql?(resolver) <ide> self.class.equal?(resolver.class) && to_path == resolver.to_path <ide> end <ide> alias :== :eql? <add> <add> def template_paths_for_suggestions # :nodoc: <add> Dir.glob("**/*", base: path) <add> end <ide> end <ide> <ide> # An Optimized resolver for Rails' most common case. <ide><path>actionview/test/template/lookup_context_test.rb <ide> def setup <ide> e = assert_raise ActionView::MissingTemplate do <ide> @lookup_context.find("foo", %w(parent child)) <ide> end <del> assert_match %r{Missing template parent/foo, child/foo with .* Searched in:\n \* "/Path/to/views"\n}, e.message <add> assert_match %r{Missing template parent/foo, child/foo with .*\n\nSearched in:\n \* "/Path/to/views"\n}, e.message <ide> end <ide> <ide> test "if no partial was found we get a helpful error message including the inheritance chain" do <ide> e = assert_raise ActionView::MissingTemplate do <ide> @lookup_context.find("foo", %w(parent child), true) <ide> end <del> assert_match %r{Missing partial parent/_foo, child/_foo with .* Searched in:\n \* "/Path/to/views"\n}, e.message <add> assert_match %r{Missing partial parent/_foo, child/_foo with .*\n\nSearched in:\n \* "/Path/to/views"\n}, e.message <ide> end <ide> <ide> test "if a single prefix is passed as a string and the lookup fails, MissingTemplate accepts it" do <ide> e = assert_raise ActionView::MissingTemplate do <ide> details = { handlers: [], formats: [], variants: [], locale: [] } <ide> @lookup_context.view_paths.find("foo", "parent", true, details) <ide> end <del> assert_match %r{Missing partial parent/_foo with .* Searched in:\n \* "/Path/to/views"\n}, e.message <add> assert_match %r{Missing partial parent/_foo with .*\n\nSearched in:\n \* "/Path/to/views"\n}, e.message <ide> end <ide> end <ide><path>actionview/test/template/render_test.rb <ide> def test_render_partial_with_layout_raises_descriptive_error <ide> assert_match "Missing partial /_true with", e.message <ide> end <ide> <add> if defined?(DidYouMean) && DidYouMean.respond_to?(:correct_error) <add> def test_render_partial_provides_spellcheck <add> e = assert_raises(ActionView::MissingTemplate) { @view.render(partial: "test/partail") } <add> assert_match %r{Did you mean\? test/_partial\n *test/_partialhtml}, e.message <add> end <add> end <add> <add> def test_render_partial_wrong_details_no_spellcheck <add> e = assert_raises(ActionView::MissingTemplate) { @view.render(partial: "test/partial_with_only_html_version", formats: [:xml]) } <add> assert_no_match %r{Did you mean\?}, e.message <add> end <add> <ide> def test_render_with_nested_layout <ide> assert_equal %(<title>title</title>\n\n<div id="column">column</div>\n<div id="content">content</div>\n), <ide> @view.render(template: "test/nested_layout", layout: "layouts/yield")
4
Text
Text
add stack service and fix typos
0a56e81ca4d7af22e5c623569a89d800a6778ed1
<ide><path>docs/reference/commandline/attach.md <ide> Options: <ide> --sig-proxy Proxy all received signals to the process (default true) <ide> ``` <ide> <del>The `docker attach` command allows you to attach to a running container using <del>the container's ID or name, either to view its ongoing output or to control it <del>interactively. You can attach to the same contained process multiple times <del>simultaneously, screen sharing style, or quickly view the progress of your <del>detached process. <add>Use `docker attach` to attach to a running container using the container's ID <add>or name, either to view its ongoing output or to control it interactively. <add>You can attach to the same contained process multiple times simultaneously, <add>screen sharing style, or quickly view the progress of your detached process. <ide> <ide> To stop a container, use `CTRL-c`. This key sequence sends `SIGKILL` to the <ide> container. If `--sig-proxy` is true (the default),`CTRL-c` sends a `SIGINT` to <ide><path>docs/reference/commandline/stack_ls.md <ide> myapp 2 <ide> * [stack deploy](stack_deploy.md) <ide> * [stack rm](stack_rm.md) <ide> * [stack ps](stack_ps.md) <add>* [stack services](stack_services.md)
2
Ruby
Ruby
move number_to_human test from ap to as
38f347a825cf132b1e0da9402532b40d6ea68522
<ide><path>actionpack/test/template/number_helper_test.rb <ide> def test_number_to_human_with_custom_units <ide> assert_equal '100&lt;script&gt;&lt;/script&gt;000 Quadrillion', number_to_human(10**20, :delimiter => "<script></script>") <ide> end <ide> <del> def test_number_to_human_with_custom_units_that_are_missing_the_needed_key <del> assert_equal '123', number_to_human(123, :units => {:thousand => 'k'}) <del> assert_equal '123', number_to_human(123, :units => {}) <del> end <del> <ide> def test_number_to_human_with_custom_format <ide> assert_equal '123 times Thousand', number_to_human(123456, :format => "%n times %u") <ide> volume = {:unit => "ml", :thousand => "lt", :million => "m3"} <ide><path>activesupport/test/number_helper_test.rb <ide> def test_number_to_human_with_custom_units <ide> end <ide> end <ide> <add> def test_number_to_human_with_custom_units_that_are_missing_the_needed_key <add> [@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper| <add> assert_equal '123', number_helper.number_to_human(123, units: { thousand: 'k'}) <add> assert_equal '123', number_helper.number_to_human(123, units: {}) <add> end <add> end <add> <ide> def test_number_to_human_with_custom_format <ide> [@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper| <ide> assert_equal '123 times Thousand', number_helper.number_to_human(123456, :format => "%n times %u")
2
PHP
PHP
update docblocks in association
5a127ec5c372f3efb4d94488bc414b7790a4185d
<ide><path>Cake/ORM/Association.php <ide> abstract class Association { <ide> protected $_canBeJoined = false; <ide> <ide> /** <del> * The className of the target table object <add> * The class name of the target table object <ide> * <ide> * @var string <ide> */ <ide> abstract class Association { <ide> <ide> /** <ide> * Whether the records on the target table are dependent on the source table, <del> * often used to indicate that records should be removed is the owning record in <add> * often used to indicate that records should be removed if the owning record in <ide> * the source table is deleted. <ide> * <ide> * @var boolean <ide> public function target(Table $table = null) { <ide> <ide> /** <ide> * Sets a list of conditions to be always included when fetching records from <del> * the target association. If no parameters are passed current list is returned <add> * the target association. If no parameters are passed the current list is returned <ide> * <ide> * @param array $conditions list of conditions to be used <ide> * @see Cake\Database\Query::where() for examples on the format of the array <ide> public function conditions($conditions = null) { <ide> <ide> /** <ide> * Sets the name of the field representing the foreign key to the target table. <del> * If no parameters are passed current field is returned <add> * If no parameters are passed the current field is returned <ide> * <ide> * @param string $key the key to be used to link both tables together <ide> * @return string <ide> public function foreignKey($key = null) { <ide> /** <ide> * Sets whether the records on the target table are dependent on the source table. <ide> * <del> * This is primarily used to indicate that records should be removed is the owning record in <add> * This is primarily used to indicate that records should be removed if the owning record in <ide> * the source table is deleted. <ide> * <del> * If no parameters are passed current setting is returned. <add> * If no parameters are passed the current setting is returned. <ide> * <ide> * @param boolean $dependent <ide> * @return boolean <ide> public function canBeJoined($options = []) { <ide> <ide> /** <ide> * Sets the type of join to be used when adding the association to a query. <del> * If no arguments are passed, currently configured type is returned. <add> * If no arguments are passed, the currently configured type is returned. <ide> * <ide> * @param string $type the join type to be used (e.g. INNER) <ide> * @return string <ide> public function joinType($type = null) { <ide> /** <ide> * Sets the property name that should be filled with data from the target table <ide> * in the source table record. <del> * If no arguments are passed, currently configured type is returned. <add> * If no arguments are passed, the currently configured type is returned. <ide> * <ide> * @param string $name <ide> * @return string <ide> public function property($name = null) { <ide> * Sets the strategy name to be used to fetch associated records. Keep in mind <ide> * that some association types might not implement but a default strategy, <ide> * rendering any changes to this setting void. <del> * If no arguments are passed, currently configured strategy is returned. <add> * If no arguments are passed, the currently configured strategy is returned. <ide> * <ide> * @param string $name <ide> * @return string <ide> public function find($type = 'all', $options = []) { <ide> } <ide> <ide> /** <del> * Returns a single or multiple conditions to be appended to the generated join <add> * Returns a single or multiple condition(s) to be appended to the generated join <ide> * clause for getting the results on the target table. If false is returned then <ide> * it will not attach any new conditions to the join clause <ide> *
1
Python
Python
make sorting benchmarks all sort integers
a083ce52b673c6dcadd800d64bb098d89f1e8e12
<ide><path>benchmarks/sorting.py <ide> <ide> N = 10000 <ide> b.title = 'Sorting %d elements' % N <del>b['numarray'] = ('a=N.array(None,shape=%d);a.sort()'%N,'') <del>b['numpy'] = ('a=N.empty(shape=%d);a.sort()'%N,'') <del>b['Numeric'] = ('a=N.empty(shape=%d);N.sort(a)'%N,'') <add>b['numarray'] = ('a=N.array(None,shape=%d,typecode="i");a.sort()'%N,'') <add>b['numpy'] = ('a=N.empty(shape=%d, dtype="i");a.sort()'%N,'') <add>b['Numeric'] = ('a=N.empty(shape=%d, typecode="i");N.sort(a)'%N,'') <ide> b.run() <ide> <ide> N1,N2 = 100,100 <ide> b.title = 'Sorting (%d,%d) elements, last axis' % (N1,N2) <del>b['numarray'] = ('a=N.array(None,shape=(%d,%d));a.sort()'%(N1,N2),'') <del>b['numpy'] = ('a=N.empty(shape=(%d,%d));a.sort()'%(N1,N2),'') <del>b['Numeric'] = ('a=N.empty(shape=(%d,%d));N.sort(a)'%(N1,N2),'') <add>b['numarray'] = ('a=N.array(None,shape=(%d,%d),typecode="i");a.sort()'%(N1,N2),'') <add>b['numpy'] = ('a=N.empty(shape=(%d,%d), dtype="i");a.sort()'%(N1,N2),'') <add>b['Numeric'] = ('a=N.empty(shape=(%d,%d),typecode="i");N.sort(a)'%(N1,N2),'') <ide> b.run() <ide> <ide> N1,N2 = 100,100 <ide> b.title = 'Sorting (%d,%d) elements, first axis' % (N1,N2) <del>b['numarray'] = ('a=N.array(None,shape=(%d,%d));a.sort(0)'%(N1,N2),'') <del>b['Numeric'] = ('a=N.empty(shape=(%d,%d));N.sort(a,0)'%(N1,N2),'') <del>b['numpy'] = ('a=N.empty(shape=(%d,%d));N.sort(a,0)'%(N1,N2),'') <add>b['numarray'] = ('a=N.array(None,shape=(%d,%d), typecode="i");a.sort(0)'%(N1,N2),'') <add>b['numpy'] = ('a=N.empty(shape=(%d,%d),dtype="i");N.sort(a,0)'%(N1,N2),'') <add>b['Numeric'] = ('a=N.empty(shape=(%d,%d),typecode="i");N.sort(a,0)'%(N1,N2),'') <ide> b.run()
1
Text
Text
add line-height to unitless css props
9ed72b43e8b15877d74a170fb369b19773bb285d
<ide><path>docs/cookbook/cb-06-style-prop-value-px tip.md <ide> Sometimes you _do_ want to keep the CSS properties unitless. Here's a list of pr <ide> <ide> - fillOpacity <ide> - fontWeight <add>- lineHeight <ide> - opacity <ide> - orphans <ide> - zIndex <ide><path>docs/cookbook/cb-06-style-prop-value-px.md <ide> Sometimes you _do_ want to keep the CSS properties unitless. Here's a list of pr <ide> <ide> - fillOpacity <ide> - fontWeight <add>- lineHeight <ide> - opacity <ide> - orphans <ide> - zIndex
2
Python
Python
fix the loss calculation of prophetnet
143738214cb83e471f3a43652617c8881370342c
<ide><path>src/transformers/models/prophetnet/modeling_prophetnet.py <ide> def forward( <ide> >>> last_hidden_states = outputs.last_hidden_state # main stream hidden states <ide> >>> last_hidden_states_ngram = outputs.last_hidden_state_ngram # predict hidden states <ide> """ <del> <del> if self.training: <del> logger.warning( <del> "There is a known issue with ProphetNet training/fine-tuning that hasn't been fixed yet:" <del> "https://github.com/huggingface/transformers/issues/9804. Please try to use an off-the-shelf" <del> "checkpoint from the model hub or fine-tune another architecture instead." <del> ) <del> <ide> use_cache == use_cache if use_cache is not None else self.config.use_cache <ide> output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions <ide> output_hidden_states = ( <ide> def _compute_loss(self, logits, labels, ignore_index=-100): <ide> break <ide> expend_targets[i, :, :] = labels <ide> <add> logits = logits.transpose(0, 1).contiguous() <ide> lprobs = nn.functional.log_softmax( <ide> logits.view(-1, logits.size(-1)), <ide> dim=-1, <ide> def _compute_loss(self, logits, labels, ignore_index=-100): <ide> break <ide> expend_targets[i, :, :] = labels <ide> <add> logits = logits.transpose(0, 1).contiguous() <ide> lprobs = nn.functional.log_softmax( <ide> logits.view(-1, logits.size(-1)), <ide> dim=-1,
1
Python
Python
fix number_of_digits bug
d687030d9e582534c850493ebc8a22fb4cf1ec81
<ide><path>data_structures/binary_tree/basic_binary_tree.py <ide> class Node: <ide> """ <ide> A Node has data variable and pointers to Nodes to its left and right. <ide> """ <add> <ide> def __init__(self, data: int) -> None: <ide> self.data = data <ide> self.left: Optional[Node] = None <ide><path>maths/number_of_digits.py <ide> def num_digits(n: int) -> int: <ide> 5 <ide> >>> num_digits(123) <ide> 3 <add> >>> num_digits(0) <add> 1 <add> >>> num_digits(-1) <add> 1 <add> >>> num_digits(-123456) <add> 6 <ide> """ <ide> digits = 0 <del> while n > 0: <add> n = abs(n) <add> while True: <ide> n = n // 10 <ide> digits += 1 <add> if n == 0: <add> break <ide> return digits <ide> <ide> <ide> def num_digits_fast(n: int) -> int: <ide> 5 <ide> >>> num_digits_fast(123) <ide> 3 <add> >>> num_digits_fast(0) <add> 1 <add> >>> num_digits_fast(-1) <add> 1 <add> >>> num_digits_fast(-123456) <add> 6 <ide> """ <del> return math.floor(math.log(abs(n), 10) + 1) <add> return 1 if n == 0 else math.floor(math.log(abs(n), 10) + 1) <ide> <ide> <ide> def num_digits_faster(n: int) -> int: <ide> def num_digits_faster(n: int) -> int: <ide> 5 <ide> >>> num_digits_faster(123) <ide> 3 <add> >>> num_digits_faster(0) <add> 1 <add> >>> num_digits_faster(-1) <add> 1 <add> >>> num_digits_faster(-123456) <add> 6 <ide> """ <ide> return len(str(abs(n))) <ide> <ide> def benchmark() -> None: <ide> medium_num = 1125899906842624 <ide> large_num = 1267650600228229401496703205376 <ide> benchmark() <add> import doctest <add> <add> doctest.testmod()
2
Ruby
Ruby
restore tests for 6.0 new framework defaults
a6711d6e9d72ee72615d5c24d761dff5e94b6573
<ide><path>railties/test/application/configuration_test.rb <ide> def index <ide> assert_equal "https://example.org/", last_response.location <ide> end <ide> <del> test "ActiveSupport::MessageEncryptor.use_authenticated_message_encryption can be configured via config.active_support.use_authenticated_message_encryption" do <add> test "ActiveRecord::Base.has_many_inversing is true by default for new apps" do <add> app "development" <add> <add> assert_equal true, ActiveRecord::Base.has_many_inversing <add> end <add> <add> test "ActiveRecord::Base.has_many_inversing is false by default for upgraded apps" do <add> remove_from_config '.*config\.load_defaults.*\n' <add> <add> app "development" <add> <add> assert_equal false, ActiveRecord::Base.has_many_inversing <add> end <add> <add> test "ActiveRecord::Base.has_many_inversing can be configured via config.active_record.has_many_inversing" do <ide> remove_from_config '.*config\.load_defaults.*\n' <ide> <ide> app_file "config/initializers/new_framework_defaults_6_1.rb", <<-RUBY <ide> def index <ide> assert_equal false, ActiveSupport::MessageEncryptor.use_authenticated_message_encryption <ide> end <ide> <add> test "ActiveSupport::MessageEncryptor.use_authenticated_message_encryption can be configured via config.active_support.use_authenticated_message_encryption" do <add> remove_from_config '.*config\.load_defaults.*\n' <add> <add> app_file "config/initializers/new_framework_defaults_6_0.rb", <<-RUBY <add> Rails.application.config.active_support.use_authenticated_message_encryption = true <add> RUBY <add> <add> app "development" <add> <add> assert_equal true, ActiveSupport::MessageEncryptor.use_authenticated_message_encryption <add> end <add> <ide> test "ActiveSupport::Digest.hash_digest_class is Digest::SHA1 by default for new apps" do <ide> app "development" <ide> <ide> def index <ide> assert_equal Digest::MD5, ActiveSupport::Digest.hash_digest_class <ide> end <ide> <add> test "ActiveSupport::Digest.hash_digest_class can be configured via config.active_support.use_sha1_digests" do <add> remove_from_config '.*config\.load_defaults.*\n' <add> <add> app_file "config/initializers/new_framework_defaults_6_0.rb", <<-RUBY <add> Rails.application.config.active_support.use_sha1_digests = true <add> RUBY <add> <add> app "development" <add> <add> assert_equal Digest::SHA1, ActiveSupport::Digest.hash_digest_class <add> end <add> <ide> test "custom serializers should be able to set via config.active_job.custom_serializers in an initializer" do <ide> class ::DummySerializer < ActiveJob::Serializers::ObjectSerializer; end <ide> <ide> class ::DummySerializer < ActiveJob::Serializers::ObjectSerializer; end <ide> assert_equal true, ActionView::Helpers::FormTagHelper.default_enforce_utf8 <ide> end <ide> <add> test "ActionView::Helpers::FormTagHelper.default_enforce_utf8 can be configured via config.action_view.default_enforce_utf8" do <add> remove_from_config '.*config\.load_defaults.*\n' <add> <add> app_file "config/initializers/new_framework_defaults_6_0.rb", <<-RUBY <add> Rails.application.config.action_view.default_enforce_utf8 = true <add> RUBY <add> <add> app "development" <add> <add> assert_equal true, ActionView::Helpers::FormTagHelper.default_enforce_utf8 <add> end <add> <ide> test "ActionView::Template.finalize_compiled_template_methods is true by default" do <ide> app "test" <ide> assert_deprecated do <ide> class ::DummySerializer < ActiveJob::Serializers::ObjectSerializer; end <ide> assert_equal false, ActiveJob::Base.return_false_on_aborted_enqueue <ide> end <ide> <add> test "ActiveJob::Base.return_false_on_aborted_enqueue can be configured in the new framework defaults" do <add> remove_from_config '.*config\.load_defaults.*\n' <add> <add> app_file "config/initializers/new_framework_defaults_6_0.rb", <<-RUBY <add> Rails.application.config.active_job.return_false_on_aborted_enqueue = true <add> RUBY <add> <add> app "development" <add> <add> assert_equal true, ActiveJob::Base.return_false_on_aborted_enqueue <add> end <add> <ide> test "ActiveJob::Base.skip_after_callbacks_if_terminated is true by default" do <ide> app "development" <ide> <ide> class ::DummySerializer < ActiveJob::Serializers::ObjectSerializer; end <ide> assert_equal true, ActionDispatch::Response.return_only_media_type_on_content_type <ide> end <ide> <add> test "ActionDispatch::Response.return_only_media_type_on_content_type can be configured in the new framework defaults" do <add> remove_from_config '.*config\.load_defaults.*\n' <add> <add> app_file "config/initializers/new_framework_defaults_6_0.rb", <<-RUBY <add> Rails.application.config.action_dispatch.return_only_media_type_on_content_type = false <add> RUBY <add> <add> app "development" <add> <add> assert_equal false, ActionDispatch::Response.return_only_media_type_on_content_type <add> end <add> <ide> test "ActionMailbox.logger is Rails.logger by default" do <ide> app "development" <ide> <ide> class MyLogger < ::Logger <ide> assert_equal ActionMailer::DeliveryJob, ActionMailer::Base.delivery_job <ide> end <ide> <add> test "ActionMailer::Base.delivery_job can be configured in the new framework defaults" do <add> remove_from_config '.*config\.load_defaults.*\n' <add> <add> app_file "config/initializers/new_framework_defaults_6_0.rb", <<-RUBY <add> Rails.application.config.action_mailer.delivery_job = "ActionMailer::MailDeliveryJob" <add> RUBY <add> <add> app "development" <add> <add> assert_equal ActionMailer::MailDeliveryJob, ActionMailer::Base.delivery_job <add> end <add> <ide> test "ActiveRecord::Base.filter_attributes should equal to filter_parameters" do <ide> app_file "config/initializers/filter_parameters_logging.rb", <<-RUBY <ide> Rails.application.config.filter_parameters += [ :password, :credit_card_number ]
1
PHP
PHP
consolidate more configuration data
b4d655a3c859da494deacc7261994d7cf64d73b8
<ide><path>App/Config/app.php <ide> namespace App\Config; <ide> <ide> use Cake\Core\Configure; <add>use Cake\Core\ClassLoader; <ide> <ide> /** <ide> * CakePHP Debug Level: <ide> */ <ide> Configure::write('debug', 2); <ide> <add>/** <add> * The root namespace your application uses. This should match <add> * the top level directory. <add> */ <add> $namespace = 'App'; <add> <ide> /** <ide> * Configure basic information about the application. <ide> * <ide> * - www_root - The file path to webroot. <ide> */ <ide> Configure::write('App', array( <del> 'namespace' => 'App', <add> 'namespace' => $namespace, <ide> 'encoding' => 'UTF-8', <add> 'base' => false, <ide> 'baseUrl' => false, <ide> //'baseUrl' => env('SCRIPT_NAME'), <del> 'base' => false, <ide> 'dir' => APP_DIR, <ide> 'webroot' => WEBROOT_DIR, <ide> 'www_root' => WWW_ROOT, <ide> )); <add> <add> $loader = new ClassLoader($namespace, dirname(APP)); <add> $loader->register(); <add> unset($loader, $namespace); <ide><path>App/Config/error.php <ide> * <ide> * @see ErrorHandler for more information on error handling and configuration. <ide> */ <del> Configure::write('Error', array( <add> $error = array( <ide> 'handler' => 'Cake\Error\ErrorHandler::handleError', <ide> 'level' => E_ALL & ~E_DEPRECATED, <ide> 'trace' => true <del> )); <add> ); <ide> <ide> /** <ide> * Configure the Exception handler used for uncaught exceptions. By default, <ide> * <ide> * @see ErrorHandler for more information on exception handling and configuration. <ide> */ <del> Configure::write('Exception', array( <add> $exception = array( <ide> 'handler' => 'Cake\Error\ErrorHandler::handleException', <ide> 'renderer' => 'Cake\Error\ExceptionRenderer', <ide> 'log' => true <del> )); <add> ); <ide> <del> Configure::setErrorHandlers(); <add> Configure::setErrorHandlers( <add> $error, <add> $exception <add> ); <add> <add> unset($error, $exception); <ide><path>App/Config/paths.php <ide> /** <ide> * The name of the webroot dir. Defaults to 'webroot' <ide> */ <del>define('WEBROOT_DIR', basename(dirname(__FILE__))); <add>define('WEBROOT_DIR', 'webroot'); <ide> <ide> /** <ide> * File path to the webroot directory. <ide><path>App/Config/routes.php <ide> * its action called 'display', and we pass a param to select the view file <ide> * to use (in this case, /app/View/Pages/home.ctp)... <ide> */ <del> Router::connect('/', array('controller' => 'Pages', 'action' => 'display', 'home')); <add> Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home')); <ide> /** <ide> * ...and connect the rest of 'Pages' controller's urls. <ide> */ <del> Router::connect('/pages/*', array('controller' => 'Pages', 'action' => 'display')); <add> Router::connect('/pages/*', array('controller' => 'pages', 'action' => 'display')); <ide> <ide> /** <ide> * Load all plugin routes. See the Plugin documentation on <ide><path>lib/Cake/Core/App.php <ide> public static function location($className) { <ide> * @return void <ide> */ <ide> public static function init() { <del> $loader = new ClassLoader(Configure::read('App.namespace'), dirname(APP)); <del> $loader->register(); <del> <ide> register_shutdown_function(array(__CLASS__, 'shutdown')); <ide> } <ide> <ide><path>lib/Cake/Core/Configure.php <ide> class Configure { <ide> */ <ide> protected static $_readers = array(); <ide> <del>/** <del> * Initializes configure and runs the bootstrap process. <del> * Bootstrapping includes the following steps: <del> * <del> * - Setup App array in Configure. <del> * - Include app/Config/core.php. <del> * - Configure core cache configurations. <del> * - Load App cache files. <del> * - Include app/Config/bootstrap.php. <del> * - Setup error/exception handlers. <del> * <del> * @param boolean $boot <del> * @return void <del> */ <del> public static function bootstrap($boot = true) { <del> if ($boot) { <del> static::write('App', array( <del> 'base' => false, <del> 'baseUrl' => false, <del> 'dir' => APP_DIR, <del> 'webroot' => WEBROOT_DIR, <del> 'www_root' => WWW_ROOT <del> )); <del> <del> App::init(); <del> App::build(); <del> <del> } <del> } <del> <ide> /** <ide> * Used to store a dynamic variable in Configure. <ide> * <ide> public static function clear() { <ide> * @param array $exception The exception handling configuration. <ide> * @return void <ide> */ <del> public static function setErrorHandlers($error = null, $exception = null) { <del> if (!$error) { <del> $error = self::$_values['Error']; <del> } <del> if (!$exception) { <del> $exception = self::$_values['Exception']; <del> } <add> public static function setErrorHandlers($error, $exception) { <ide> $level = -1; <ide> if (isset($error['level'])) { <ide> error_reporting($error['level']); <ide><path>lib/Cake/Routing/Dispatcher.php <ide> * @since CakePHP(tm) v 0.2.9 <ide> * @license MIT License (http://www.opensource.org/licenses/mit-license.php) <ide> */ <del> <ide> namespace Cake\Routing; <add> <ide> use Cake\Controller\Controller; <ide> use Cake\Core\App; <ide> use Cake\Core\Configure; <ide><path>lib/Cake/bootstrap.php <ide> $loader = new \Cake\Core\ClassLoader('Cake', CORE_PATH); <ide> $loader->register(); <ide> <add> <add>use Cake\Core\App; <add>use Cake\Core\Configure; <add> <add>App::init(); <add>App::build(); <add> <ide> /** <ide> * Full url prefix <ide> */
8
Go
Go
make more package in system support darwin
c6dc4f85abd3b9722bf34265366e21cc7675623b
<ide><path>pkg/system/process_unix.go <del>// +build linux freebsd solaris <add>// +build linux freebsd solaris darwin <ide> <ide> package system <ide>
1
PHP
PHP
apply fixes from styleci
b373f74ed21bcb04cd86bd71a017e8293fb43ab8
<ide><path>src/Illuminate/Auth/RequestGuard.php <ide> public function validate(array $credentials = []) <ide> public function setRequest(Request $request) <ide> { <ide> $this->user = null; <del> <add> <ide> $this->request = $request; <ide> <ide> return $this;
1
PHP
PHP
fix cs errors
2db808bcc7a2bd725752abf123504a63eabb2b71
<ide><path>src/Shell/Task/ViewTask.php <ide> protected function _associations(Table $model) { <ide> $assocName = $assoc->name(); <ide> $alias = $target->alias(); <ide> $targetClass = get_class($target); <del> list($_, $className) = namespaceSplit($targetClass); <add> list(, $className) = namespaceSplit($targetClass); <ide> <ide> $modelClass = get_class($model); <ide> if ($modelClass !== 'Cake\ORM\Table' && $targetClass === $modelClass) { <ide><path>tests/TestCase/Shell/Task/ViewTaskTest.php <ide> public function testGetContentAssociations() { <ide> $this->assertContains("'controller' => 'ViewTaskAuthors'", $result); <ide> } <ide> <del> <ide> /** <ide> * Test getContent with no pk <ide> *
2
PHP
PHP
retrieve the real original content.
e37d48720bea14c3ca4fff7f53bd2273481258ef
<ide><path>src/Illuminate/Http/ResponseTrait.php <ide> public function content() <ide> */ <ide> public function getOriginalContent() <ide> { <del> return $this->original; <add> $original = $this->original; <add> <add> return $original instanceof self ? $original->{__FUNCTION__}() : $original; <ide> } <ide> <ide> /** <ide><path>tests/Http/HttpResponseTest.php <ide> public function testGetOriginalContent() <ide> $this->assertSame($arr, $response->getOriginalContent()); <ide> } <ide> <add> public function testGetOriginalContentRetrievesTheFirstOriginalContent() <add> { <add> $previousResponse = new \Illuminate\Http\Response(['foo' => 'bar']); <add> $response = new \Illuminate\Http\Response($previousResponse); <add> <add> $this->assertSame(['foo' => 'bar'], $response->getOriginalContent()); <add> } <add> <ide> public function testSetAndRetrieveStatusCode() <ide> { <ide> $response = new \Illuminate\Http\Response('foo');
2
Ruby
Ruby
move build methods into a class
67694b8c6064e4424a05e79a7e7907c5f9f744fb
<ide><path>Library/Homebrew/build.rb <ide> def main <ide> # can be inconvenient for the user. But we need to be safe. <ide> system "/usr/bin/sudo", "-k" <ide> <del> install(Formula.factory($0)) <add> Build.new(Formula.factory($0)).install <ide> rescue Exception => e <ide> unless error_pipe.nil? <ide> e.continuation = nil if ARGV.debug? <ide> def main <ide> end <ide> end <ide> <del>def post_superenv_hacks f <del> # Only allow Homebrew-approved directories into the PATH, unless <del> # a formula opts-in to allowing the user's path. <del> if f.env.userpaths? or f.recursive_requirements.any? { |rq| rq.env.userpaths? } <del> ENV.userpaths! <del> end <del>end <add>class Build <add> attr_reader :f <ide> <del>def pre_superenv_hacks f <del> # 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 <del> not ARGV.include? '--env=super' <del>end <add> def initialize(f) <add> @f = f <add> end <ide> <del>def expand_deps f <del> f.recursive_dependencies do |dependent, dep| <del> if dep.optional? || dep.recommended? <del> Dependency.prune unless dependent.build.with?(dep.name) <del> elsif dep.build? <del> Dependency.prune unless dependent == f <add> def post_superenv_hacks <add> # Only allow Homebrew-approved directories into the PATH, unless <add> # a formula opts-in to allowing the user's path. <add> if f.env.userpaths? or f.recursive_requirements.any? { |rq| rq.env.userpaths? } <add> ENV.userpaths! <ide> end <del> end.map(&:to_formula) <del>end <del> <del>def install f <del> deps = expand_deps(f) <del> keg_only_deps = deps.select(&:keg_only?) <add> end <ide> <del> pre_superenv_hacks(f) <del> require 'superenv' <add> def pre_superenv_hacks <add> # Allow a formula to opt-in to the std environment. <add> ARGV.unshift '--env=std' if (f.env.std? or <add> f.recursive_dependencies.detect{|d| d.name == 'scons' }) and <add> not ARGV.include? '--env=super' <add> end <ide> <del> deps.each do |dep| <del> opt = HOMEBREW_PREFIX/:opt/dep <del> fixopt(dep) unless opt.directory? or ARGV.ignore_deps? <add> def expand_deps <add> f.recursive_dependencies do |dependent, dep| <add> if dep.optional? || dep.recommended? <add> Dependency.prune unless dependent.build.with?(dep.name) <add> elsif dep.build? <add> Dependency.prune unless dependent == f <add> end <add> end.map(&:to_formula) <ide> end <ide> <del> if superenv? <del> ENV.keg_only_deps = keg_only_deps.map(&:to_s) <del> ENV.deps = deps.map(&:to_s) <del> ENV.x11 = f.recursive_requirements.detect { |rq| rq.kind_of?(X11Dependency) } <del> ENV.setup_build_environment <del> post_superenv_hacks(f) <del> f.recursive_requirements.each(&:modify_build_environment) <del> else <del> ENV.setup_build_environment <del> f.recursive_requirements.each(&:modify_build_environment) <del> <del> keg_only_deps.each do |dep| <del> opt = dep.opt_prefix <del> ENV.prepend_path 'PATH', "#{opt}/bin" <del> ENV.prepend_path 'PKG_CONFIG_PATH', "#{opt}/lib/pkgconfig" <del> ENV.prepend_path 'PKG_CONFIG_PATH', "#{opt}/share/pkgconfig" <del> ENV.prepend_path 'ACLOCAL_PATH', "#{opt}/share/aclocal" <del> ENV.prepend_path 'CMAKE_PREFIX_PATH', opt <del> ENV.prepend 'LDFLAGS', "-L#{opt}/lib" if (opt/:lib).directory? <del> ENV.prepend 'CPPFLAGS', "-I#{opt}/include" if (opt/:include).directory? <add> def install <add> deps = expand_deps <add> keg_only_deps = deps.select(&:keg_only?) <add> <add> pre_superenv_hacks <add> require 'superenv' <add> <add> deps.each do |dep| <add> opt = HOMEBREW_PREFIX/:opt/dep <add> fixopt(dep) unless opt.directory? or ARGV.ignore_deps? <ide> end <del> end <ide> <del> if f.fails_with? ENV.compiler <del> begin <del> ENV.send CompilerSelector.new(f, ENV.compiler).compiler <del> rescue CompilerSelectionError => e <del> raise e.message <add> if superenv? <add> ENV.keg_only_deps = keg_only_deps.map(&:to_s) <add> ENV.deps = deps.map(&:to_s) <add> ENV.x11 = f.recursive_requirements.detect { |rq| rq.kind_of?(X11Dependency) } <add> ENV.setup_build_environment <add> post_superenv_hacks <add> f.recursive_requirements.each(&:modify_build_environment) <add> else <add> ENV.setup_build_environment <add> f.recursive_requirements.each(&:modify_build_environment) <add> <add> keg_only_deps.each do |dep| <add> opt = dep.opt_prefix <add> ENV.prepend_path 'PATH', "#{opt}/bin" <add> ENV.prepend_path 'PKG_CONFIG_PATH', "#{opt}/lib/pkgconfig" <add> ENV.prepend_path 'PKG_CONFIG_PATH', "#{opt}/share/pkgconfig" <add> ENV.prepend_path 'ACLOCAL_PATH', "#{opt}/share/aclocal" <add> ENV.prepend_path 'CMAKE_PREFIX_PATH', opt <add> ENV.prepend 'LDFLAGS', "-L#{opt}/lib" if (opt/:lib).directory? <add> ENV.prepend 'CPPFLAGS', "-I#{opt}/include" if (opt/:include).directory? <add> end <ide> end <del> end <ide> <del> f.brew do <del> if ARGV.flag? '--git' <del> system "git init" <del> system "git add -A" <add> if f.fails_with? ENV.compiler <add> begin <add> ENV.send CompilerSelector.new(f, ENV.compiler).compiler <add> rescue CompilerSelectionError => e <add> raise e.message <add> end <ide> end <del> if ARGV.interactive? <del> ohai "Entering interactive mode" <del> puts "Type `exit' to return and finalize the installation" <del> puts "Install to this prefix: #{f.prefix}" <ide> <add> f.brew do <ide> if ARGV.flag? '--git' <del> puts "This directory is now a git repo. Make your changes and then use:" <del> puts " git diff | pbcopy" <del> puts "to copy the diff to the clipboard." <add> system "git init" <add> system "git add -A" <ide> end <add> if ARGV.interactive? <add> ohai "Entering interactive mode" <add> puts "Type `exit' to return and finalize the installation" <add> puts "Install to this prefix: #{f.prefix}" <add> <add> if ARGV.flag? '--git' <add> puts "This directory is now a git repo. Make your changes and then use:" <add> puts " git diff | pbcopy" <add> puts "to copy the diff to the clipboard." <add> end <ide> <del> interactive_shell f <del> else <del> f.prefix.mkpath <del> <del> begin <del> f.install <del> rescue Exception => e <del> if ARGV.debug? <del> debrew e, f <del> else <del> raise e <add> interactive_shell f <add> else <add> f.prefix.mkpath <add> <add> begin <add> f.install <add> rescue Exception => e <add> if ARGV.debug? <add> debrew e, f <add> else <add> raise e <add> end <ide> end <del> end <ide> <del> # Find and link metafiles <del> f.prefix.install_metafiles Pathname.pwd <add> # Find and link metafiles <add> f.prefix.install_metafiles Pathname.pwd <add> end <ide> end <ide> end <ide> end
1
Javascript
Javascript
add contentparsercallback to d3.xhr constructor
88fc68cf8bffc6dd7b245ed39bc410852694ecc9
<ide><path>src/xhr/html.js <ide> import "../core/document"; <ide> import "xhr"; <ide> <ide> d3.html = function(url, callback) { <del> return d3.xhr(url, "text/html", callback).response(d3_html); <add> return d3.xhr(url, "text/html", callback, d3_html); <ide> }; <ide> <ide> function d3_html(request) { <ide><path>src/xhr/json.js <ide> import "xhr"; <ide> <ide> d3.json = function(url, callback) { <del> return d3.xhr(url, "application/json", callback).response(d3_json); <add> return d3.xhr(url, "application/json", callback, d3_json); <ide> }; <ide> <ide> function d3_json(request) { <ide><path>src/xhr/text.js <ide> import "xhr"; <ide> <ide> d3.text = function() { <del> return d3.xhr.apply(d3, arguments).response(d3_text); <add> return d3.xhr.apply(d3, arguments, d3_text); <ide> }; <ide> <ide> function d3_text(request) { <ide><path>src/xhr/xhr.js <ide> import "../core/identity"; <ide> import "../core/rebind"; <ide> import "../event/dispatch"; <ide> <del>d3.xhr = function(url, mimeType, callback) { <add>d3.xhr = function(url, mimeType, callback, contentParserCallback) { <ide> var xhr = {}, <ide> dispatch = d3.dispatch("progress", "load", "error"), <ide> headers = {}, <ide> d3.xhr = function(url, mimeType, callback) { <ide> return xhr; <ide> }; <ide> <add> xhr.response(contentParserCallback); <ide> d3.rebind(xhr, dispatch, "on"); <ide> <ide> if (arguments.length === 2 && typeof mimeType === "function") callback = mimeType, mimeType = null; <ide><path>src/xhr/xml.js <ide> import "xhr"; <ide> <ide> d3.xml = function() { <del> return d3.xhr.apply(d3, arguments).response(d3_xml); <add> return d3.xhr.apply(d3, arguments, d3_xml); <ide> }; <ide> <ide> function d3_xml(request) {
5
PHP
PHP
remove duplicate value
f0eb51b3320fb655cea56e595b7222e2c17777a5
<ide><path>src/Console/Command/Task/ControllerTask.php <ide> public function bake($controllerName) { <ide> 'actions', <ide> 'helpers', <ide> 'components', <del> 'prefix', <ide> 'namespace' <ide> ); <ide> $data['name'] = $controllerName;
1
Java
Java
add databuffer bodyinserter/bodyextractor
735e288d465ca36ae1eeccbd8a4d044d7bd3ad50
<ide><path>spring-web/src/main/java/org/springframework/http/codec/BodyExtractors.java <ide> import reactor.core.publisher.Mono; <ide> <ide> import org.springframework.core.ResolvableType; <add>import org.springframework.core.io.buffer.DataBuffer; <ide> import org.springframework.http.HttpMessage; <ide> import org.springframework.http.MediaType; <ide> import org.springframework.http.ReactiveHttpInputMessage; <ide> public static <T> BodyExtractor<Flux<T>, ReactiveHttpInputMessage> toFlux(Class< <ide> */ <ide> public static <T> BodyExtractor<Flux<T>, ReactiveHttpInputMessage> toFlux(ResolvableType elementType) { <ide> Assert.notNull(elementType, "'elementType' must not be null"); <del> return (request, context) -> readWithMessageReaders(request, context, <add> return (inputMessage, context) -> readWithMessageReaders(inputMessage, context, <ide> elementType, <del> reader -> reader.read(elementType, request, Collections.emptyMap()), <add> reader -> reader.read(elementType, inputMessage, Collections.emptyMap()), <ide> Flux::error); <ide> } <ide> <add> /** <add> * Return a {@code BodyExtractor} that returns the body of the message as a {@link Flux} of <add> * {@link DataBuffer}s. <add> * <p><strong>Note</strong> that the returned buffers should be released after usage by calling <add> * {@link org.springframework.core.io.buffer.DataBufferUtils#release(DataBuffer)} <add> * @return a {@code BodyExtractor} that returns the body <add> * @see ReactiveHttpInputMessage#getBody() <add> */ <add> public static BodyExtractor<Flux<DataBuffer>, ReactiveHttpInputMessage> toDataBuffers() { <add> return (inputMessage, context) -> inputMessage.getBody(); <add> } <add> <ide> private static <T, S extends Publisher<T>> S readWithMessageReaders( <ide> ReactiveHttpInputMessage inputMessage, <ide> BodyExtractor.Context context, <ide><path>spring-web/src/main/java/org/springframework/http/codec/BodyInserters.java <ide> <ide> import org.springframework.core.ResolvableType; <ide> import org.springframework.core.io.Resource; <add>import org.springframework.core.io.buffer.DataBuffer; <ide> import org.springframework.http.MediaType; <ide> import org.springframework.http.ReactiveHttpOutputMessage; <ide> import org.springframework.http.server.reactive.ServerHttpResponse; <ide> public static <T, S extends Publisher<T>> BodyInserter<S, ServerHttpResponse> fr <ide> Assert.notNull(eventsPublisher, "'eventsPublisher' must not be null"); <ide> Assert.notNull(eventType, "'eventType' must not be null"); <ide> return BodyInserter.of( <del> (response, context) -> { <add> (outputMessage, context) -> { <ide> HttpMessageWriter<T> messageWriter = sseMessageWriter(context); <ide> return messageWriter.write(eventsPublisher, eventType, <del> MediaType.TEXT_EVENT_STREAM, response, Collections.emptyMap()); <add> MediaType.TEXT_EVENT_STREAM, outputMessage, Collections.emptyMap()); <ide> <ide> }, <ide> () -> eventsPublisher <ide> ); <ide> } <ide> <add> /** <add> * Return a {@code BodyInserter} that writes the given {@code Publisher<DataBuffer>} to the <add> * body. <add> * @param publisher the data buffer publisher to write <add> * @param <T> the type of the publisher <add> * @return a {@code BodyInserter} that writes directly to the body <add> * @see ReactiveHttpOutputMessage#writeWith(Publisher) <add> */ <add> public static <T extends Publisher<DataBuffer>> BodyInserter<T, ReactiveHttpOutputMessage> fromDataBuffers(T publisher) { <add> Assert.notNull(publisher, "'publisher' must not be null"); <add> <add> return BodyInserter.of( <add> (outputMessage, context) -> outputMessage.writeWith(publisher), <add> () -> publisher <add> ); <add> } <add> <ide> private static <T> HttpMessageWriter<T> sseMessageWriter(BodyInserter.Context context) { <ide> return context.messageWriters().get() <ide> .filter(messageWriter -> messageWriter <ide><path>spring-web/src/test/java/org/springframework/http/codec/BodyExtractorsTests.java <ide> import java.nio.ByteBuffer; <ide> import java.nio.charset.StandardCharsets; <ide> import java.util.ArrayList; <del>import java.util.Collections; <ide> import java.util.List; <ide> import java.util.function.Supplier; <ide> import java.util.stream.Stream; <ide> import org.springframework.http.codec.json.Jackson2JsonDecoder; <ide> import org.springframework.http.codec.xml.Jaxb2XmlDecoder; <ide> import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest; <del>import org.springframework.web.server.UnsupportedMediaTypeStatusException; <ide> <ide> /** <ide> * @author Arjen Poutsma <ide> public void toFluxUnacceptable() throws Exception { <ide> BodyExtractor.Context emptyContext = new BodyExtractor.Context() { <ide> @Override <ide> public Supplier<Stream<HttpMessageReader<?>>> messageReaders() { <del> return () -> Collections.<HttpMessageReader<?>>emptySet().stream(); <add> return Stream::empty; <ide> } <ide> }; <ide> <ide> public Supplier<Stream<HttpMessageReader<?>>> messageReaders() { <ide> .verify(); <ide> } <ide> <add> @Test <add> public void toDataBuffers() throws Exception { <add> BodyExtractor<Flux<DataBuffer>, ReactiveHttpInputMessage> extractor = BodyExtractors.toDataBuffers(); <add> <add> DefaultDataBufferFactory factory = new DefaultDataBufferFactory(); <add> DefaultDataBuffer dataBuffer = <add> factory.wrap(ByteBuffer.wrap("foo".getBytes(StandardCharsets.UTF_8))); <add> Flux<DataBuffer> body = Flux.just(dataBuffer); <add> <add> MockServerHttpRequest request = new MockServerHttpRequest(); <add> request.setBody(body); <add> <add> Flux<DataBuffer> result = extractor.extract(request, this.context); <add> <add> StepVerifier.create(result) <add> .expectNext(dataBuffer) <add> .expectComplete() <add> .verify(); <add> } <add> <ide> } <ide>\ No newline at end of file <ide><path>spring-web/src/test/java/org/springframework/http/codec/BodyInsertersTests.java <ide> package org.springframework.http.codec; <ide> <ide> import java.nio.ByteBuffer; <add>import java.nio.charset.StandardCharsets; <ide> import java.nio.file.Files; <ide> import java.util.ArrayList; <ide> import java.util.Collections; <ide> import org.springframework.core.io.ClassPathResource; <ide> import org.springframework.core.io.Resource; <ide> import org.springframework.core.io.buffer.DataBuffer; <add>import org.springframework.core.io.buffer.DefaultDataBuffer; <ide> import org.springframework.core.io.buffer.DefaultDataBufferFactory; <ide> import org.springframework.http.ReactiveHttpOutputMessage; <ide> import org.springframework.http.codec.json.Jackson2JsonEncoder; <ide> public void ofServerSentEventClass() throws Exception { <ide> StepVerifier.create(result).expectNextCount(0).expectComplete().verify(); <ide> } <ide> <add> @Test <add> public void ofDataBuffers() throws Exception { <add> DefaultDataBufferFactory factory = new DefaultDataBufferFactory(); <add> DefaultDataBuffer dataBuffer = <add> factory.wrap(ByteBuffer.wrap("foo".getBytes(StandardCharsets.UTF_8))); <add> Flux<DataBuffer> body = Flux.just(dataBuffer); <add> <add> BodyInserter<Flux<DataBuffer>, ReactiveHttpOutputMessage> inserter = BodyInserters.fromDataBuffers(body); <add> <add> assertEquals(body, inserter.t()); <add> <add> MockServerHttpResponse response = new MockServerHttpResponse(); <add> Mono<Void> result = inserter.insert(response, this.context); <add> StepVerifier.create(result).expectComplete().verify(); <add> <add> StepVerifier.create(response.getBody()) <add> .expectNext(dataBuffer) <add> .expectComplete() <add> .verify(); <add> } <add> <add> <ide> } <ide>\ No newline at end of file
4
Text
Text
add v3.14.0-beta.2 to changelog
1b9349622c4c96f909e22d07474f79ebf1848084
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <add>### v3.14.0-beta.2 (September 24, 2019) <add> <add>- [#18273](https://github.com/emberjs/ember.js/pull/18273) [BUGFIX] Fix issues with SSR rehydration of <title>. <add>- [#18415](https://github.com/emberjs/ember.js/pull/18415) [BUGFIX] Fix hbs import path in test blueprint. <add>- [#18418](https://github.com/emberjs/ember.js/pull/18418) / [#18419](https://github.com/emberjs/ember.js/pull/18419) [BUGFIX] Require Octane features when using Octane preview. <add> <ide> ### v3.14.0-beta.1 (September 19, 2019) <ide> <ide> - [#18345](https://github.com/emberjs/ember.js/pull/18345) / [#18363](https://github.com/emberjs/ember.js/pull/18363) [FEATURE] Implement the [Provide @model named argument to route templates](https://github.com/emberjs/rfcs/blob/master/text/0523-model-argument-for-route-templates.md RFC. <ide> <ide> ### v3.13.1 (September 23, 2019) <ide> <del>- [#18273](https://github.com/emberjs/ember.js/pull/18273) [BUGFIX] Fix issues with SSR rehydration of <title>. (#18273) <del>- [#18418](https://github.com/emberjs/ember.js/pull/18418) / [#18418](https://github.com/emberjs/ember.js/pull/18418) [BUGFIX] Require Octane features when using Octane preview (#18418) <add>- [#18273](https://github.com/emberjs/ember.js/pull/18273) [BUGFIX] Fix issues with SSR rehydration of <title>. <add>- [#18418](https://github.com/emberjs/ember.js/pull/18418) / [#18419](https://github.com/emberjs/ember.js/pull/18419) [BUGFIX] Require Octane features when using Octane preview. <ide> <ide> ### v3.13.0 (September 19, 2019) <ide>
1
Text
Text
remove windows xperf from tierlist
dca76e7990c0ac27029e91a6730126e2adadb614
<ide><path>doc/contributing/diagnostic-tooling-support-tiers.md <ide> The tools are currently assigned to Tiers as follows: <ide> | Tracing | trace\_events (API) | No | Yes | 1 | <ide> | Tracing | trace\_gc | No | Yes | 1 | <ide> | Tracing | Systemtap | No | Partial | ? | <del>| Profiling | Windows Xperf | No | ? | ? | <ide> | F/P/T | appmetrics | No | No | ? | <ide> | M/T | eBPF tracing tool | No | No | ? |
1
Javascript
Javascript
add inlinecurve3 check
5408bd8978e9be03ef7ca70d8f57963bdb780878
<ide><path>src/extras/core/CurvePath.js <ide> CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), { <ide> var curve = curves[ i ]; <ide> var resolution = ( curve && curve.isEllipseCurve ) ? divisions * 2 <ide> : ( curve && curve.isLineCurve ) ? 1 <del> : ( curve && curve.isSplineCurve ) ? divisions * curve.points.length <del> : divisions; <add> : ( curve && curve.isLineCurve3 ) ? 1 <add> : ( curve && curve.isSplineCurve ) ? divisions * curve.points.length <add> : divisions; <ide> <ide> var pts = curve.getPoints( resolution ); <ide>
1
Javascript
Javascript
add some hints for breaking changes
038d056aed8c195139910fa389a4309d8467e99e
<ide><path>lib/Module.js <ide> class Module extends DependenciesBlock { <ide> } <ide> } <ide> <add>Object.defineProperty(Module.prototype, "isUsed", { <add> get() { <add> throw new Error( <add> "Module.isUsed was renamed (use getUsedName, isExportUsed or isModuleUsed instead)" <add> ); <add> } <add>}); <add> <add>Object.defineProperty(Module.prototype, "used", { <add> get() { <add> throw new Error("Module.used was refactored (use getUsedExports instead)"); <add> }, <add> set(value) { <add> throw new Error("Module.used was refactored (use setUsedExports instead)"); <add> } <add>}); <add> <add>Object.defineProperty(Module.prototype, "usedExports", { <add> get() { <add> throw new Error( <add> "Module.usedExports was refactored (use getUsedExports instead)" <add> ); <add> }, <add> set(value) { <add> throw new Error( <add> "Module.usedExports was refactored (use setUsedExports instead)" <add> ); <add> } <add>}); <add> <ide> module.exports = Module;
1
Python
Python
remove the internal benchmark class
1846ac335da808cb8bf6f9b1950933348a40d200
<ide><path>benchmarks/benchmarks/bench_app.py <ide> from __future__ import absolute_import, division, print_function <ide> <del>from .common import Benchmark <del> <ide> import numpy as np <ide> <ide> from six.moves import xrange <ide> <ide> <del>class LaplaceInplace(Benchmark): <add>class LaplaceInplace(object): <ide> params = ['inplace', 'normal'] <ide> param_names = ['update'] <ide> <ide> def time_it(self, update): <ide> self.run() <ide> <ide> <del>class MaxesOfDots(Benchmark): <add>class MaxesOfDots(object): <ide> def setup(self): <ide> np.random.seed(1) <ide> nsubj = 5 <ide><path>benchmarks/benchmarks/bench_core.py <ide> from __future__ import absolute_import, division, print_function <ide> <del>from .common import Benchmark <del> <ide> import numpy as np <ide> <ide> <del>class Core(Benchmark): <add>class Core(object): <ide> def setup(self): <ide> self.l100 = range(100) <ide> self.l50 = range(50) <ide> def time_tril_l10x10(self): <ide> np.tril(self.l10x10) <ide> <ide> <del>class Temporaries(Benchmark): <add>class Temporaries(object): <ide> def setup(self): <ide> self.amid = np.ones(50000) <ide> self.bmid = np.ones(50000) <ide> def time_large2(self): <ide> (self.alarge + self.blarge) - 2 <ide> <ide> <del>class CorrConv(Benchmark): <add>class CorrConv(object): <ide> params = [[50, 1000, 1e5], <ide> [10, 100, 1000, 1e4], <ide> ['valid', 'same', 'full']] <ide> def time_convolve(self, size1, size2, mode): <ide> np.convolve(self.x1, self.x2, mode=mode) <ide> <ide> <del>class CountNonzero(Benchmark): <add>class CountNonzero(object): <ide> param_names = ['numaxes', 'size', 'dtype'] <ide> params = [ <ide> [1, 2, 3], <ide> def time_count_nonzero_multi_axis(self, numaxes, size, dtype): <ide> self.x.ndim - 1, self.x.ndim - 2)) <ide> <ide> <del>class PackBits(Benchmark): <add>class PackBits(object): <ide> param_names = ['dtype'] <ide> params = [[bool, np.uintp]] <ide> def setup(self, dtype): <ide> def time_packbits_axis1(self, dtype): <ide> np.packbits(self.d2, axis=1) <ide> <ide> <del>class UnpackBits(Benchmark): <add>class UnpackBits(object): <ide> def setup(self): <ide> self.d = np.ones(10000, dtype=np.uint8) <ide> self.d2 = np.ones((200, 1000), dtype=np.uint8) <ide> def time_unpackbits_axis1(self): <ide> np.unpackbits(self.d2, axis=1) <ide> <ide> <del>class Indices(Benchmark): <add>class Indices(object): <ide> def time_indices(self): <ide> np.indices((1000, 500)) <ide><path>benchmarks/benchmarks/bench_function_base.py <ide> from __future__ import absolute_import, division, print_function <ide> <del>from .common import Benchmark <del> <ide> import numpy as np <ide> <ide> <del>class Histogram1D(Benchmark): <add>class Histogram1D(object): <ide> def setup(self): <ide> self.d = np.linspace(0, 100, 100000) <ide> <ide> def time_fine_binning(self): <ide> np.histogram(self.d, 10000, (0, 100)) <ide> <ide> <del>class Histogram2D(Benchmark): <add>class Histogram2D(object): <ide> def setup(self): <ide> self.d = np.linspace(0, 100, 200000).reshape((-1,2)) <ide> <ide> def time_fine_binning(self): <ide> np.histogramdd(self.d, (10000, 10000), ((0, 100), (0, 100))) <ide> <ide> <del>class Bincount(Benchmark): <add>class Bincount(object): <ide> def setup(self): <ide> self.d = np.arange(80000, dtype=np.intp) <ide> self.e = self.d.astype(np.float64) <ide> def time_weights(self): <ide> np.bincount(self.d, weights=self.e) <ide> <ide> <del>class Median(Benchmark): <add>class Median(object): <ide> def setup(self): <ide> self.e = np.arange(10000, dtype=np.float32) <ide> self.o = np.arange(10001, dtype=np.float32) <ide> def time_odd_small(self): <ide> np.median(self.o[:500], overwrite_input=True) <ide> <ide> <del>class Percentile(Benchmark): <add>class Percentile(object): <ide> def setup(self): <ide> self.e = np.arange(10000, dtype=np.float32) <ide> self.o = np.arange(10001, dtype=np.float32) <ide> def time_percentile(self): <ide> np.percentile(self.e, [25, 35, 55, 65, 75]) <ide> <ide> <del>class Select(Benchmark): <add>class Select(object): <ide> def setup(self): <ide> self.d = np.arange(20000) <ide> self.e = self.d.copy() <ide> def time_select_larger(self): <ide> np.select(self.cond_large, ([self.d, self.e] * 10)) <ide> <ide> <del>class Sort(Benchmark): <add>class Sort(object): <ide> def setup(self): <ide> self.e = np.arange(10000, dtype=np.float32) <ide> self.o = np.arange(10001, dtype=np.float32) <ide> def time_argsort_random(self): <ide> self.o.argsort() <ide> <ide> <del>class Where(Benchmark): <add>class Where(object): <ide> def setup(self): <ide> self.d = np.arange(20000) <ide> self.e = self.d.copy() <ide><path>benchmarks/benchmarks/bench_indexing.py <ide> from __future__ import absolute_import, division, print_function <ide> <del>from .common import Benchmark, get_squares_, get_indexes_, get_indexes_rand_ <add>from .common import get_squares_, get_indexes_, get_indexes_rand_ <ide> <ide> from os.path import join as pjoin <ide> import shutil <ide> from tempfile import mkdtemp <ide> <ide> <del>class Indexing(Benchmark): <add>class Indexing(object): <ide> params = [["indexes_", "indexes_rand_"], <ide> ['I', ':,I', 'np.ix_(I, I)'], <ide> ['', '=1']] <ide> def time_op(self, indexes, sel, op): <ide> self.func() <ide> <ide> <del>class IndexingSeparate(Benchmark): <add>class IndexingSeparate(object): <ide> def setup(self): <ide> self.tmp_dir = mkdtemp() <ide> self.fp = memmap(pjoin(self.tmp_dir, 'tmp.dat'), <ide> def time_mmap_fancy_indexing(self): <ide> self.fp[self.indexes] <ide> <ide> <del>class IndexingStructured0D(Benchmark): <add>class IndexingStructured0D(object): <ide> def setup(self): <ide> self.dt = np.dtype([('a', 'f4', 256)]) <ide> <ide><path>benchmarks/benchmarks/bench_io.py <ide> from __future__ import absolute_import, division, print_function <ide> <del>from .common import Benchmark, get_squares <add>from .common import get_squares <ide> <ide> import numpy as np <ide> from io import StringIO <ide> <ide> <del>class Copy(Benchmark): <add>class Copy(object): <ide> params = ["int8", "int16", "float32", "float64", <ide> "complex64", "complex128"] <ide> param_names = ['type'] <ide> def time_strided_assign(self, typename): <ide> self.dflat[::2] = 2 <ide> <ide> <del>class CopyTo(Benchmark): <add>class CopyTo(object): <ide> def setup(self): <ide> self.d = np.ones(50000) <ide> self.e = self.d.copy() <ide> def time_copyto_8_dense(self): <ide> np.copyto(self.d, self.e, where=self.im8) <ide> <ide> <del>class Savez(Benchmark): <add>class Savez(object): <ide> def setup(self): <ide> self.squares = get_squares() <ide> <ide> def time_vb_savez_squares(self): <ide> np.savez('tmp.npz', self.squares) <ide> <del>class LoadtxtCSVComments(Benchmark): <add>class LoadtxtCSVComments(object): <ide> # benchmarks for np.loadtxt comment handling <ide> # when reading in CSV files <ide> <ide> def time_comment_loadtxt_csv(self, num_lines): <ide> delimiter=u',') <ide> self.data_comments.seek(0) <ide> <del>class LoadtxtCSVdtypes(Benchmark): <add>class LoadtxtCSVdtypes(object): <ide> # benchmarks for np.loadtxt operating with <ide> # different dtypes parsed / cast from CSV files <ide> <ide> def time_loadtxt_dtypes_csv(self, dtype, num_lines): <ide> dtype=dtype) <ide> self.csv_data.seek(0) <ide> <del>class LoadtxtCSVStructured(Benchmark): <add>class LoadtxtCSVStructured(object): <ide> # benchmarks for np.loadtxt operating with <ide> # a structured data type & CSV file <ide> <ide> def time_loadtxt_csv_struct_dtype(self): <ide> self.csv_data.seek(0) <ide> <ide> <del>class LoadtxtCSVSkipRows(Benchmark): <add>class LoadtxtCSVSkipRows(object): <ide> # benchmarks for loadtxt row skipping when <ide> # reading in csv file data; a similar benchmark <ide> # is present in the pandas asv suite <ide> def time_skiprows_csv(self, skiprows): <ide> delimiter=',', <ide> skiprows=skiprows) <ide> <del>class LoadtxtReadUint64Integers(Benchmark): <add>class LoadtxtReadUint64Integers(object): <ide> # pandas has a similar CSV reading benchmark <ide> # modified to suit np.loadtxt <ide> <ide> def time_read_uint64_neg_values(self, size): <ide> np.loadtxt(self.data2) <ide> self.data2.seek(0) <ide> <del>class LoadtxtUseColsCSV(Benchmark): <add>class LoadtxtUseColsCSV(object): <ide> # benchmark selective column reading from CSV files <ide> # using np.loadtxt <ide> <ide> def time_loadtxt_usecols_csv(self, usecols): <ide> usecols=usecols) <ide> self.csv_data.seek(0) <ide> <del>class LoadtxtCSVDateTime(Benchmark): <add>class LoadtxtCSVDateTime(object): <ide> # benchmarks for np.loadtxt operating with <ide> # datetime data in a CSV file <ide> <ide><path>benchmarks/benchmarks/bench_lib.py <del>"""Benchmarks for `numpy.lib`.""" <add>"""objects for `numpy.lib`.""" <ide> <ide> <ide> from __future__ import absolute_import, division, print_function <ide> <del>from .common import Benchmark <del> <ide> import numpy as np <ide> <ide> <del>class Pad(Benchmark): <del> """Benchmarks for `numpy.pad`.""" <add>class Pad(object): <add> """objects for `numpy.pad`.""" <ide> <ide> param_names = ["shape", "pad_width", "mode"] <ide> params = [ <ide><path>benchmarks/benchmarks/bench_linalg.py <ide> from __future__ import absolute_import, division, print_function <ide> <del>from .common import Benchmark, get_squares_, get_indexes_rand, TYPES1 <add>from .common import get_squares_, get_indexes_rand, TYPES1 <ide> <ide> import numpy as np <ide> <ide> <del>class Eindot(Benchmark): <add>class Eindot(object): <ide> def setup(self): <ide> self.a = np.arange(60000.0).reshape(150, 400) <ide> self.ac = self.a.copy() <ide> def time_tensordot_a_b_axes_1_0_0_1(self): <ide> np.tensordot(self.a3, self.b3, axes=([1, 0], [0, 1])) <ide> <ide> <del>class Linalg(Benchmark): <add>class Linalg(object): <ide> params = [['svd', 'pinv', 'det', 'norm'], <ide> TYPES1] <ide> param_names = ['op', 'type'] <ide> def time_op(self, op, typename): <ide> self.func(self.a) <ide> <ide> <del>class Lstsq(Benchmark): <add>class Lstsq(object): <ide> def setup(self): <ide> self.a = get_squares_()['float64'] <ide> self.b = get_indexes_rand()[:100].astype(np.float64) <ide><path>benchmarks/benchmarks/bench_ma.py <ide> from __future__ import absolute_import, division, print_function <ide> <del>from .common import Benchmark <del> <ide> import numpy as np <ide> <ide> <del>class MA(Benchmark): <add>class MA(object): <ide> def setup(self): <ide> self.l100 = range(100) <ide> self.t100 = ([True] * 100) <ide> def time_masked_array_l100_t100(self): <ide> np.ma.masked_array(self.l100, self.t100) <ide> <ide> <del>class Indexing(Benchmark): <add>class Indexing(object): <ide> param_names = ['masked', 'ndim', 'size'] <ide> params = [[True, False], <ide> [1, 2], <ide> def time_1d(self, masked, ndim, size): <ide> self.m[self.idx_1d] <ide> <ide> <del>class UFunc(Benchmark): <add>class UFunc(object): <ide> param_names = ['a_masked', 'b_masked', 'size'] <ide> params = [[True, False], <ide> [True, False], <ide> def time_2d(self, a_masked, b_masked, size): <ide> np.ma.add(self.a_2d, self.b_2d) <ide> <ide> <del>class Concatenate(Benchmark): <add>class Concatenate(object): <ide> param_names = ['mode', 'n'] <ide> params = [ <ide> ['ndarray', 'unmasked', <ide><path>benchmarks/benchmarks/bench_overrides.py <ide> from __future__ import absolute_import, division, print_function <ide> <del>from .common import Benchmark <del> <ide> from numpy.core.overrides import array_function_dispatch <ide> import numpy as np <ide> <ide> def __array_function__(self, func, types, args, kwargs): <ide> pass <ide> <ide> <del>class ArrayFunction(Benchmark): <add>class ArrayFunction(object): <ide> <ide> def setup(self): <ide> self.numpy_array = np.array(1) <ide><path>benchmarks/benchmarks/bench_random.py <ide> from __future__ import absolute_import, division, print_function <ide> <del>from .common import Benchmark <del> <ide> import numpy as np <ide> <ide> <del>class Random(Benchmark): <add>class Random(object): <ide> params = ['normal', 'uniform', 'weibull 1', 'binomial 10 0.5', <ide> 'poisson 10'] <ide> <ide> def time_rng(self, name): <ide> self.func(*self.params) <ide> <ide> <del>class Shuffle(Benchmark): <add>class Shuffle(object): <ide> def setup(self): <ide> self.a = np.arange(100000) <ide> <ide> def time_100000(self): <ide> np.random.shuffle(self.a) <ide> <ide> <del>class Randint(Benchmark): <add>class Randint(object): <ide> <ide> def time_randint_fast(self): <ide> """Compare to uint32 below""" <ide> def time_randint_slow(self): <ide> np.random.randint(0, 2**30 + 1, size=10**5) <ide> <ide> <del>class Randint_dtype(Benchmark): <add>class Randint_dtype(object): <ide> high = { <ide> 'bool': 1, <ide> 'uint8': 2**7, <ide> def time_randint_slow(self, name): <ide> np.random.randint(0, high + 1, size=10**5, dtype=name) <ide> <ide> <del>class Permutation(Benchmark): <add>class Permutation(object): <ide> def setup(self): <ide> self.n = 10000 <ide> self.a_1d = np.random.random_sample(self.n) <ide><path>benchmarks/benchmarks/bench_reduce.py <ide> from __future__ import absolute_import, division, print_function <ide> <del>from .common import Benchmark, TYPES1, get_squares <add>from .common import TYPES1, get_squares <ide> <ide> import numpy as np <ide> <ide> <del>class AddReduce(Benchmark): <add>class AddReduce(object): <ide> def setup(self): <ide> self.squares = get_squares().values() <ide> <ide> def time_axis_1(self): <ide> [np.add.reduce(a, axis=1) for a in self.squares] <ide> <ide> <del>class AddReduceSeparate(Benchmark): <add>class AddReduceSeparate(object): <ide> params = [[0, 1], TYPES1] <ide> param_names = ['axis', 'type'] <ide> <ide> def time_reduce(self, axis, typename): <ide> np.add.reduce(self.a, axis=axis) <ide> <ide> <del>class AnyAll(Benchmark): <add>class AnyAll(object): <ide> def setup(self): <ide> self.zeros = np.zeros(100000, bool) <ide> self.ones = np.ones(100000, bool) <ide> def time_any_slow(self): <ide> self.zeros.any() <ide> <ide> <del>class MinMax(Benchmark): <add>class MinMax(object): <ide> params = [np.float32, np.float64, np.intp] <ide> param_names = ['dtype'] <ide> <ide> def time_max(self, dtype): <ide> np.max(self.d) <ide> <ide> <del>class SmallReduction(Benchmark): <add>class SmallReduction(object): <ide> def setup(self): <ide> self.d = np.ones(100, dtype=np.float32) <ide> <ide><path>benchmarks/benchmarks/bench_shape_base.py <ide> from __future__ import absolute_import, division, print_function <ide> <del>from .common import Benchmark <del> <ide> import numpy as np <ide> <ide> <del>class Block(Benchmark): <add>class Block(object): <ide> params = [1, 10, 100] <ide> param_names = ['size'] <ide> <ide> def time_no_lists(self, n): <ide> np.block(np.eye(3 * n)) <ide> <ide> <del>class Block3D(Benchmark): <add>class Block3D(object): <ide> params = [1, 10, 100] <ide> param_names = ['size'] <ide> <ide><path>benchmarks/benchmarks/bench_ufunc.py <ide> from __future__ import absolute_import, division, print_function <ide> <del>from .common import Benchmark, get_squares_ <add>from .common import get_squares_ <ide> <ide> import numpy as np <ide> <ide> print("Missing ufunc %r" % (name,)) <ide> <ide> <del>class Broadcast(Benchmark): <add>class Broadcast(object): <ide> def setup(self): <ide> self.d = np.ones((50000, 100), dtype=np.float64) <ide> self.e = np.ones((100,), dtype=np.float64) <ide> def time_broadcast(self): <ide> self.d - self.e <ide> <ide> <del>class UFunc(Benchmark): <add>class UFunc(object): <ide> params = [ufuncs] <ide> param_names = ['ufunc'] <ide> timeout = 10 <ide> def time_ufunc_types(self, ufuncname): <ide> [self.f(*arg) for arg in self.args] <ide> <ide> <del>class Custom(Benchmark): <add>class Custom(object): <ide> def setup(self): <ide> self.b = np.ones(20000, dtype=bool) <ide> <ide> def time_or_bool(self): <ide> (self.b | self.b) <ide> <ide> <del>class CustomInplace(Benchmark): <add>class CustomInplace(object): <ide> def setup(self): <ide> self.c = np.ones(500000, dtype=np.int8) <ide> self.i = np.ones(150000, dtype=np.int32) <ide> def time_double_add_temp(self): <ide> 1. + self.d + 1. <ide> <ide> <del>class CustomScalar(Benchmark): <add>class CustomScalar(object): <ide> params = [np.float32, np.float64] <ide> param_names = ['dtype'] <ide> <ide> def time_less_than_scalar2(self, dtype): <ide> (self.d < 1) <ide> <ide> <del>class Scalar(Benchmark): <add>class Scalar(object): <ide> def setup(self): <ide> self.x = np.asarray(1.0) <ide> self.y = np.asarray((1.0 + 1j)) <ide> def __repr__(self): <ide> )) <ide> <ide> <del>class ArgParsing(Benchmark): <add>class ArgParsing(object): <ide> # In order to benchmark the speed of argument parsing, all but the <ide> # out arguments are chosen such that they have no effect on the <ide> # calculation. In particular, subok=True and where=True are <ide> def time_add_arg_parsing(self, arg_pack): <ide> np.add(*arg_pack.args, **arg_pack.kwargs) <ide> <ide> <del>class ArgParsingReduce(Benchmark): <add>class ArgParsingReduce(object): <ide> # In order to benchmark the speed of argument parsing, all but the <ide> # out arguments are chosen such that they have minimal effect on the <ide> # calculation. <ide><path>benchmarks/benchmarks/common.py <ide> def get_indexes_rand_(): <ide> indexes_rand = get_indexes_rand() <ide> indexes_rand_ = indexes_rand[indexes_rand < nxs] <ide> return indexes_rand_ <del> <del> <del>class Benchmark(object): <del> sample_time = 0.25
14
Ruby
Ruby
add tests for curldownloadstrategy#tarball_path
ba830df4e6759c7f3e5c5772484ed28ef6fba3f9
<ide><path>Library/Homebrew/test/cask/download_strategy_spec.rb <ide> expect(curl_args.each_cons(2)).to include(["-e", "http://somehost/also"]) <ide> end <ide> end <add> <add> context "with a file name trailing the URL path" do <add> describe "#tarball_path" do <add> subject { downloader.tarball_path } <add> its(:extname) { is_expected.to eq(".dmg") } <add> end <add> end <add> <add> context "with no discernible file name in it" do <add> let(:url) { "http://example.com/download" } <add> <add> describe "#tarball_path" do <add> subject { downloader.tarball_path } <add> its(:to_path) { is_expected.to end_with("some-cask--1.2.3.4") } <add> end <add> end <add> <add> context "with a file name trailing the first query parameter" do <add> let(:url) { "http://example.com/download?file=cask.zip&a=1" } <add> <add> describe "#tarball_path" do <add> subject { downloader.tarball_path } <add> its(:extname) { is_expected.to eq(".zip") } <add> end <add> end <add> <add> context "with a file name trailing the second query parameter" do <add> let(:url) { "http://example.com/dl?a=1&file=cask.zip&b=2" } <add> <add> describe "#tarball_path" do <add> subject { downloader.tarball_path } <add> its(:extname) { is_expected.to eq(".zip") } <add> end <add> end <add> <add> context "with an unusually long query string" do <add> let(:url) do <add> [ <add> "https://node49152.ssl.fancycdn.example.com", <add> "/fancycdn/node/49152/file/upload/download", <add> "?cask_class=zf920df", <add> "&cask_group=2348779087242312", <add> "&cask_archive_file_name=cask.zip", <add> "&signature=CGmDulxL8pmutKTlCleNTUY%2FyO9Xyl5u9yVZUE0", <add> "uWrjadjuz67Jp7zx3H7NEOhSyOhu8nzicEHRBjr3uSoOJzwkLC8L", <add> "BLKnz%2B2X%2Biq5m6IdwSVFcLp2Q1Hr2kR7ETn3rF1DIq5o0lHC", <add> "yzMmyNe5giEKJNW8WF0KXriULhzLTWLSA3ZTLCIofAdRiiGje1kN", <add> "YY3C0SBqymQB8CG3ONn5kj7CIGbxrDOq5xI2ZSJdIyPysSX7SLvE", <add> "DBw2KdR24q9t1wfjS9LUzelf5TWk6ojj8p9%2FHjl%2Fi%2FVCXN", <add> "N4o1mW%2FMayy2tTY1qcC%2FTmqI1ulZS8SNuaSgr9Iys9oDF1%2", <add> "BPK%2B4Sg==", <add> ].join("") <add> end <add> <add> describe "#tarball_path" do <add> subject { downloader.tarball_path } <add> its(:extname) { is_expected.to eq(".zip") } <add> its("to_path.length") { is_expected.to be_between(0, 255) } <add> end <add> end <ide> end <ide> <ide> describe Hbc::CurlPostDownloadStrategy do
1
Javascript
Javascript
use globalhotkeys to catch keyup events
023df092895614eacf9bc8e85acbd70ea488f98e
<ide><path>client/src/templates/Challenges/components/Hotkeys.js <ide> import React from 'react'; <ide> import PropTypes from 'prop-types'; <del>import { HotKeys } from 'react-hotkeys'; <add>import { HotKeys, GlobalHotKeys } from 'react-hotkeys'; <ide> import { navigate } from 'gatsby'; <ide> <ide> const keyMap = { <ide> function Hotkeys({ <ide> prevChallengePath <ide> }) { <ide> const handlers = { <del> EXECUTE_CHALLENGE: () => { <add> EXECUTE_CHALLENGE: e => { <add> // the 'enter' part of 'ctrl+enter' stops HotKeys from listening, so it <add> // needs to be prevented. <add> // TODO: 'enter' on its own also disables HotKeys, but default behaviour <add> // should not be prevented in that case. <add> e.preventDefault(); <ide> if (executeChallenge) executeChallenge(); <ide> }, <ide> NAVIGATE_PREV: () => navigate(prevChallengePath), <ide> NAVIGATE_NEXT: () => navigate(introPath ? introPath : nextChallengePath) <ide> }; <add> // GlobalHotKeys is always mounted and tracks all keypresses. Without it, <add> // keyup events can be missed and react-hotkeys assumes that that key is still <add> // being pressed. <ide> return ( <ide> <HotKeys handlers={handlers} innerRef={innerRef} keyMap={keyMap}> <ide> {children} <add> <GlobalHotKeys /> <ide> </HotKeys> <ide> ); <ide> }
1
Java
Java
prefer use of "java ee" over "j2ee"
14f27bda3708eee64ce21807d4284cdf6ca26566
<ide><path>spring-jms/src/main/java/org/springframework/jms/connection/TransactionAwareConnectionFactoryProxy.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2015 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> /** <ide> * Proxy for a target JMS {@link javax.jms.ConnectionFactory}, adding awareness of <ide> * Spring-managed transactions. Similar to a transactional JNDI ConnectionFactory <del> * as provided by a J2EE server. <add> * as provided by a Java EE application server. <ide> * <ide> * <p>Messaging code which should remain unaware of Spring's JMS support can work with <ide> * this proxy to seamlessly participate in Spring-managed transactions. Note that the <ide><path>spring-jms/src/main/java/org/springframework/jms/core/JmsTemplate.java <ide> * domain. <ide> * <ide> * <p>Default settings for JMS Sessions are "not transacted" and "auto-acknowledge". <del> * As defined by the J2EE specification, the transaction and acknowledgement <add> * As defined by the Java EE specification, the transaction and acknowledgement <ide> * parameters are ignored when a JMS Session is created inside an active <ide> * transaction, no matter if a JTA transaction or a Spring-managed transaction. <ide> * To configure them for native JMS usage, specify appropriate values for <ide> * {@link org.springframework.jms.connection.SingleConnectionFactory} as a <ide> * decorator for your target {@code ConnectionFactory}, reusing a single <ide> * JMS Connection in a thread-safe fashion; this is often good enough for the <del> * purpose of sending messages via this template. In a J2EE environment, <add> * purpose of sending messages via this template. In a Java EE environment, <ide> * make sure that the {@code ConnectionFactory} is obtained from the <ide> * application's environment naming context via JNDI; application servers <ide> * typically expose pooled, transaction-aware factories there. <ide><path>spring-jms/src/main/java/org/springframework/jms/listener/AbstractPollingMessageListenerContainer.java <ide> * configured through the {@link #setReceiveTimeout "receiveTimeout"} property. <ide> * <ide> * <p>The underlying mechanism is based on standard JMS MessageConsumer handling, <del> * which is perfectly compatible with both native JMS and JMS in a J2EE environment. <del> * Neither the JMS {@code MessageConsumer.setMessageListener} facility <del> * nor the JMS ServerSessionPool facility is required. A further advantage <del> * of this approach is full control over the listening process, allowing for <del> * custom scaling and throttling and of concurrent message processing <del> * (which is up to concrete subclasses). <add> * which is perfectly compatible with both native JMS and JMS in a Java EE environment. <add> * Neither the JMS {@code MessageConsumer.setMessageListener} facility nor the JMS <add> * ServerSessionPool facility is required. A further advantage of this approach is <add> * full control over the listening process, allowing for custom scaling and throttling <add> * and of concurrent message processing (which is up to concrete subclasses). <ide> * <ide> * <p>Message reception and listener execution can automatically be wrapped <ide> * in transactions through passing a Spring <ide> * {@link org.springframework.transaction.PlatformTransactionManager} into the <ide> * {@link #setTransactionManager "transactionManager"} property. This will usually <ide> * be a {@link org.springframework.transaction.jta.JtaTransactionManager} in a <del> * J2EE enviroment, in combination with a JTA-aware JMS ConnectionFactory obtained <del> * from JNDI (check your J2EE server's documentation). <add> * Java EE enviroment, in combination with a JTA-aware JMS ConnectionFactory <add> * obtained from JNDI (check your application server's documentation). <ide> * <ide> * <p>This base class does not assume any specific mechanism for asynchronous <ide> * execution of polling invokers. Check out {@link DefaultMessageListenerContainer} <ide><path>spring-jms/src/main/java/org/springframework/jms/support/JmsAccessor.java <ide> /* <del> * Copyright 2002-2014 the original author or authors. <add> * Copyright 2002-2015 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 ConnectionFactory getConnectionFactory() { <ide> * Default is "false". <ide> * <p>Note that within a JTA transaction, the parameters passed to <ide> * {@code create(Queue/Topic)Session(boolean transacted, int acknowledgeMode)} <del> * method are not taken into account. Depending on the J2EE transaction context, <add> * method are not taken into account. Depending on the Java EE transaction context, <ide> * the container makes its own decisions on these values. Analogously, these <ide> * parameters are not taken into account within a locally managed transaction <ide> * either, since the accessor operates on an existing JMS Session in this case. <ide><path>spring-tx/src/main/java/org/springframework/transaction/TransactionDefinition.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2015 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 TransactionDefinition { <ide> * <p><b>NOTE:</b> Actual transaction suspension will not work out-of-the-box <ide> * on all transaction managers. This in particular applies to <ide> * {@link org.springframework.transaction.jta.JtaTransactionManager}, <del> * which requires the {@code javax.transaction.TransactionManager} <del> * to be made available it to it (which is server-specific in standard J2EE). <add> * which requires the {@code javax.transaction.TransactionManager} to be <add> * made available it to it (which is server-specific in standard Java EE). <ide> * <p>A {@code PROPAGATION_REQUIRES_NEW} scope always defines its own <ide> * transaction synchronizations. Existing synchronizations will be suspended <ide> * and resumed appropriately. <ide> public interface TransactionDefinition { <ide> * <p><b>NOTE:</b> Actual transaction suspension will not work out-of-the-box <ide> * on all transaction managers. This in particular applies to <ide> * {@link org.springframework.transaction.jta.JtaTransactionManager}, <del> * which requires the {@code javax.transaction.TransactionManager} <del> * to be made available it to it (which is server-specific in standard J2EE). <add> * which requires the {@code javax.transaction.TransactionManager} to be <add> * made available it to it (which is server-specific in standard Java EE). <ide> * <p>Note that transaction synchronization is <i>not</i> available within a <ide> * {@code PROPAGATION_NOT_SUPPORTED} scope. Existing synchronizations <ide> * will be suspended and resumed appropriately. <ide><path>spring-tx/src/main/java/org/springframework/transaction/annotation/Propagation.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2015 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 enum Propagation { <ide> /** <ide> * Create a new transaction, and suspend the current transaction if one exists. <ide> * Analogous to the EJB transaction attribute of the same name. <del> * <p>Note: Actual transaction suspension will not work out-of-the-box on <del> * all transaction managers. This in particular applies to JtaTransactionManager, <add> * <p><b>NOTE:</b> Actual transaction suspension will not work out-of-the-box <add> * on all transaction managers. This in particular applies to <add> * {@link org.springframework.transaction.jta.JtaTransactionManager}, <ide> * which requires the {@code javax.transaction.TransactionManager} to be <del> * made available it to it (which is server-specific in standard J2EE). <add> * made available it to it (which is server-specific in standard Java EE). <ide> * @see org.springframework.transaction.jta.JtaTransactionManager#setTransactionManager <ide> */ <ide> REQUIRES_NEW(TransactionDefinition.PROPAGATION_REQUIRES_NEW), <ide> <ide> /** <ide> * Execute non-transactionally, suspend the current transaction if one exists. <ide> * Analogous to EJB transaction attribute of the same name. <del> * <p>Note: Actual transaction suspension will not work on out-of-the-box <del> * on all transaction managers. This in particular applies to JtaTransactionManager, <add> * <p><b>NOTE:</b> Actual transaction suspension will not work out-of-the-box <add> * on all transaction managers. This in particular applies to <add> * {@link org.springframework.transaction.jta.JtaTransactionManager}, <ide> * which requires the {@code javax.transaction.TransactionManager} to be <del> * made available it to it (which is server-specific in standard J2EE). <add> * made available it to it (which is server-specific in standard Java EE). <ide> * @see org.springframework.transaction.jta.JtaTransactionManager#setTransactionManager <ide> */ <ide> NOT_SUPPORTED(TransactionDefinition.PROPAGATION_NOT_SUPPORTED), <ide><path>spring-tx/src/main/java/org/springframework/transaction/jta/WebSphereUowTransactionManager.java <ide> /* <del> * Copyright 2002-2014 the original author or authors. <add> * Copyright 2002-2015 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 WebSphereUowTransactionManager(UOWManager uowManager) { <ide> <ide> /** <ide> * Set the WebSphere UOWManager to use as direct reference. <del> * <p>Typically just used for test setups; in a J2EE environment, <add> * <p>Typically just used for test setups; in a Java EE environment, <ide> * the UOWManager will always be fetched from JNDI. <ide> * @see #setUserTransactionName <ide> */
7
PHP
PHP
change some paths
46aedf54af4a5c495b7c463874e3f3eb0ecb3691
<ide><path>src/Illuminate/Foundation/Application.php <ide> public function routesAreCached() <ide> */ <ide> public function getRouteCachePath() <ide> { <del> return $this['path.storage'].'/meta/routes.php'; <add> return $this['path.storage'].'/framework/routes.php'; <ide> } <ide> <ide> /** <ide><path>src/Illuminate/Foundation/Console/ClearCompiledCommand.php <ide> class ClearCompiledCommand extends Command { <ide> */ <ide> public function fire() <ide> { <del> if (file_exists($path = $this->laravel['path.storage'].'/meta/compiled.php')) <add> if (file_exists($path = $this->laravel['path.storage'].'/framework/compiled.php')) <ide> { <ide> @unlink($path); <ide> } <ide><path>src/Illuminate/Foundation/Console/OptimizeCommand.php <ide> protected function compileClasses() <ide> { <ide> $this->registerClassPreloaderCommand(); <ide> <del> $outputPath = $this->laravel['path.storage'].'/meta/compiled.php'; <add> $outputPath = $this->laravel['path.storage'].'/framework/compiled.php'; <ide> <ide> $this->callSilent('compile', array( <ide> '--config' => implode(',', $this->getClassFiles()),
3
Python
Python
remove unused import
9e09477b2f2a115192d6481dfdf754aeeee963e1
<ide><path>spacy/tests/test_matcher.py <ide> <ide> from ..matcher import Matcher, PhraseMatcher <ide> from .util import get_doc <del>from ..util import get_lang_class <ide> <ide> import pytest <ide>
1
Javascript
Javascript
pass number format to tooltip
7966227df36fdb3a79f35ac238ea8b5c84b3f3a8
<ide><path>src/scales/scale.linearbase.js <ide> export default class LinearScaleBase extends Scale { <ide> } <ide> <ide> getLabelForValue(value) { <del> return formatNumber(value, this.chart.options.locale); <add> return formatNumber(value, this.chart.options.locale, this.options.ticks.format); <ide> } <ide> } <ide><path>src/scales/scale.logarithmic.js <ide> export default class LogarithmicScale extends Scale { <ide> * @return {string} <ide> */ <ide> getLabelForValue(value) { <del> return value === undefined ? '0' : formatNumber(value, this.chart.options.locale); <add> return value === undefined <add> ? '0' <add> : formatNumber(value, this.chart.options.locale, this.options.ticks.format); <ide> } <ide> <ide> /**
2
Mixed
Ruby
fix undefined method `to_i' introduced since 3.2.8
8d98c83bbceb905cd65c487cfa714d2fca92501c
<ide><path>activerecord/CHANGELOG.md <ide> ## Rails 4.0.0 (unreleased) ## <ide> <del>* Rename `update_attributes` to `update`, keep `update_attributes` as an alias for `update` method. <add>* Fix undefined method `to_i` when calling `new` on a scope that uses an Array. <add> Fixes #8718, #8734. <add> <add> *Jason Stirk* <add> <add>* Rename `update_attributes` to `update`, keep `update_attributes` as an alias for `update` method. <ide> This is a soft-deprecation for `update_attributes`, although it will still work without any <ide> deprecation message in 4.0 is recommended to start using `update` since `update_attributes` will be <ide> deprecated and removed in future versions of Rails. <ide><path>activerecord/lib/active_record/connection_adapters/column.rb <ide> def value_to_integer(value) <ide> when TrueClass, FalseClass <ide> value ? 1 : 0 <ide> else <del> value.to_i <add> if value.respond_to?(:to_i) <add> value.to_i <add> else <add> nil <add> end <ide> end <ide> end <ide> <ide><path>activerecord/test/cases/associations/belongs_to_associations_test.rb <ide> def test_natural_assignment <ide> assert_equal apple.id, citibank.firm_id <ide> end <ide> <add> def test_id_assignment <add> apple = Firm.create("name" => "Apple") <add> citibank = Account.create("credit_limit" => 10) <add> citibank.firm_id = apple <add> assert_nil citibank.firm_id <add> end <add> <ide> def test_natural_assignment_with_primary_key <ide> apple = Firm.create("name" => "Apple") <ide> citibank = Client.create("name" => "Primary key client") <ide> def test_attributes_are_being_set_when_initialized_from_belongs_to_association_w <ide> assert_equal new_firm.name, "Apple" <ide> end <ide> <add> def test_attributes_are_set_without_error_when_initialized_from_belongs_to_association_with_array_in_where_clause <add> new_account = Account.where(:credit_limit => [ 50, 60 ]).new <add> assert_nil new_account.credit_limit <add> end <add> <ide> def test_reassigning_the_parent_id_updates_the_object <ide> client = companies(:second_client) <ide> <ide><path>activerecord/test/cases/column_test.rb <ide> require "cases/helper" <add>require 'models/company' <ide> <ide> module ActiveRecord <ide> module ConnectionAdapters <ide> def test_type_cast_integer <ide> <ide> def test_type_cast_non_integer_to_integer <ide> column = Column.new("field", nil, "integer") <del> assert_raises(NoMethodError) do <del> column.type_cast([]) <del> end <add> assert_nil column.type_cast([1,2]) <add> assert_nil column.type_cast({1 => 2}) <add> assert_nil column.type_cast((1..2)) <add> end <ide> <del> assert_raises(NoMethodError) do <del> column.type_cast(Object.new) <del> end <add> def test_type_cast_activerecord_to_integer <add> column = Column.new("field", nil, "integer") <add> firm = Firm.create(:name => 'Apple') <add> assert_nil column.type_cast(firm) <add> end <add> <add> def test_type_cast_object_without_to_i_to_integer <add> column = Column.new("field", nil, "integer") <add> assert_nil column.type_cast(Object.new) <ide> end <ide> <ide> def test_type_cast_time
4
Javascript
Javascript
fix portuguese weekdaysmin
ed06d372009d1d149d09bcc98693e142d3282a56
<ide><path>lang/pt.js <ide> monthsShort : "Jan_Fev_Mar_Abr_Mai_Jun_Jul_Ago_Set_Out_Nov_Dez".split("_"), <ide> weekdays : "Domingo_Segunda-feira_Terça-feira_Quarta-feira_Quinta-feira_Sexta-feira_Sábado".split("_"), <ide> weekdaysShort : "Dom_Seg_Ter_Qua_Qui_Sex_Sáb".split("_"), <del> weekdaysMin : "Dom_Seg_Ter_Qua_Qui_Sex_Sáb".split("_"), <add> weekdaysMin : "Dom_2ª_3ª_4ª_5ª_6ª_Sáb".split("_"), <ide> longDateFormat : { <ide> LT : "HH:mm", <ide> L : "DD/MM/YYYY", <ide><path>min/lang-all.min.js <ide> // moment.js language configuration <ide> // language : catalan (ca) <ide> // author : Juan G. Hurtado : https://github.com/juanghurtado <del>(function(){var a={months:"Gener_Febrer_Març_Abril_Maig_Juny_Juliol_Agost_Setembre_Octubre_Novembre_Desembre".split("_"),monthsShort:"Gen._Febr._Mar._Abr._Mai._Jun._Jul._Ag._Set._Oct._Nov._Des.".split("_"),weekdays:"Diumenge_Dilluns_Dimarts_Dimecres_Dijous_Divendres_Dissabte".split("_"),weekdaysShort:"Dg._Dl._Dt._Dc._Dj._Dv._Ds.".split("_"),weekdaysMin:"Dg_Dl_Dt_Dc_Dj_Dv_Ds".split("_"),longDateFormat:{LT:"H:mm",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd D MMMM YYYY LT"},calendar:{sameDay:function(){return"[avui a "+(this.hours()!==1?"les":"la")+"] LT"},nextDay:function(){return"[demà a "+(this.hours()!==1?"les":"la")+"] LT"},nextWeek:function(){return"dddd [a "+(this.hours()!==1?"les":"la")+"] LT"},lastDay:function(){return"[ahir a "+(this.hours()!==1?"les":"la")+"] LT"},lastWeek:function(){return"[el] dddd [passat a "+(this.hours()!==1?"les":"la")+"] LT"},sameElse:"L"},relativeTime:{future:"en %s",past:"fa %s",s:"uns segons",m:"un minut",mm:"%d minuts",h:"una hora",hh:"%d hores",d:"un dia",dd:"%d dies",M:"un mes",MM:"%d mesos",y:"un any",yy:"%d anys"},ordinal:function(a){return"º"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("ca",a)})(),function(){var a={months:"кăрлач_нарăс_пуш_ака_май_çĕртме_утă_çурла_авăн_юпа_чӳк_раштав".split("_"),monthsShort:"кăр_нар_пуш_ака_май_çĕр_утă_çур_ав_юпа_чӳк_раш".split("_"),weekdays:"вырсарникун_тунтикун_ытларикун_юнкун_кĕçнерникун_эрнекун_шăматкун".split("_"),weekdaysShort:"выр_тун_ытл_юн_кĕç_эрн_шăм".split("_"),weekdaysMin:"вр_тн_ыт_юн_кç_эр_шм".split("_"),longDateFormat:{LT:"HH:mm",L:"DD-MM-YYYY",LL:"YYYY çулхи MMMM уйăхĕн D-мĕшĕ",LLL:"YYYY çулхи MMMM уйăхĕн D-мĕшĕ, LT",LLLL:"dddd, YYYY çулхи MMMM уйăхĕн D-мĕшĕ, LT"},calendar:{sameDay:"[Паян] LT [сехетре]",nextDay:"[Ыран] LT [сехетре]",lastDay:"[Ĕнер] LT [сехетре]",nextWeek:"[Çитес] dddd LT [сехетре]",lastWeek:"[Иртнĕ] dddd LT [сехетре]",sameElse:"L"},relativeTime:{future:"%sран",past:"%s каялла",s:"пĕр-ик çеккунт",m:"пĕр минут",mm:"%d минут",h:"пĕр сехет",hh:"%d сехет",d:"пĕр кун",dd:"%d кун",M:"пĕр уйăх",MM:"%d уйăх",y:"пĕр çул",yy:"%d çул"},ordinal:function(a){return"-мĕш"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("cv",a)}(),function(){var a={months:"Januar_Februar_Marts_April_Maj_Juni_Juli_August_September_Oktober_November_December".split("_"),monthsShort:"Jan_Feb_Mar_Apr_Maj_Jun_Jul_Aug_Sep_Okt_Nov_Dec".split("_"),weekdays:"Søndag_Mandag_Tirsdag_Onsdag_Torsdag_Fredag_Lørdag".split("_"),weekdaysShort:"Søn_Man_Tir_Ons_Tor_Fre_Lør".split("_"),weekdaysMin:"Sø_Ma_Ti_On_To_Fr_Lø".split("_"),longDateFormat:{LT:"h:mm A",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY h:mm A",LLLL:"dddd D. MMMM, YYYY h:mm A"},calendar:{sameDay:"[I dag kl.] LT",nextDay:"[I morgen kl.] LT",nextWeek:"dddd [kl.] LT",lastDay:"[I går kl.] LT",lastWeek:"[sidste] dddd [kl] LT",sameElse:"L"},relativeTime:{future:"om %s",past:"%s siden",s:"få sekunder",m:"minut",mm:"%d minutter",h:"time",hh:"%d timer",d:"dag",dd:"%d dage",M:"månede",MM:"%d måneder",y:"år",yy:"%d år"},ordinal:function(a){return"."}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("da",a)}(),function(){var a={months:"Januar_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember".split("_"),monthsShort:"Jan._Febr._Mrz._Apr._Mai_Jun._Jul._Aug._Sept._Okt._Nov._Dez.".split("_"),weekdays:"Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag".split("_"),weekdaysShort:"So._Mo._Di._Mi._Do._Fr._Sa.".split("_"),weekdaysMin:"So_Mo_Di_Mi_Do_Fr_Sa".split("_"),longDateFormat:{LT:"H:mm U\\hr",L:"DD.MM.YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY LT",LLLL:"dddd, D. MMMM YYYY LT"},calendar:{sameDay:"[Heute um] LT",sameElse:"L",nextDay:"[Morgen um] LT",nextWeek:"dddd [um] LT",lastDay:"[Gestern um] LT",lastWeek:"[letzten] dddd [um] LT"},relativeTime:{future:"in %s",past:"vor %s",s:"ein paar Sekunden",m:"einer Minute",mm:"%d Minuten",h:"einer Stunde",hh:"%d Stunden",d:"einem Tag",dd:"%d Tagen",M:"einem Monat",MM:"%d Monaten",y:"einem Jahr",yy:"%d Jahren"},ordinal:function(a){return"."}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("de",a)}(),function(){var a={months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),monthsShort:"Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),weekdaysShort:"Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),weekdaysMin:"Su_Mo_Tu_We_Th_Fr_Sa".split("_"),longDateFormat:{LT:"h:mm A",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd, D MMMM YYYY LT"},calendar:{sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[last] dddd [at] LT",sameElse:"L"},relativeTime:{future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},ordinal:function(a){var b=a%10;return~~(a%100/10)===1?"th":b===1?"st":b===2?"nd":b===3?"rd":"th"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("en-gb",a)}(),function(){var a={months:"Enero_Febrero_Marzo_Abril_Mayo_Junio_Julio_Agosto_Septiembre_Octubre_Noviembre_Diciembre".split("_"),monthsShort:"Ene._Feb._Mar._Abr._May._Jun._Jul._Ago._Sep._Oct._Nov._Dic.".split("_"),weekdays:"Domingo_Lunes_Martes_Miércoles_Jueves_Viernes_Sábado".split("_"),weekdaysShort:"Dom._Lun._Mar._Mié._Jue._Vie._Sáb.".split("_"),weekdaysMin:"Do_Lu_Ma_Mi_Ju_Vi_Sá".split("_"),longDateFormat:{LT:"H:mm",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd D MMMM YYYY LT"},calendar:{sameDay:function(){return"[hoy a la"+(this.hours()!==1?"s":"")+"] LT"},nextDay:function(){return"[mañana a la"+(this.hours()!==1?"s":"")+"] LT"},nextWeek:function(){return"dddd [a la"+(this.hours()!==1?"s":"")+"] LT"},lastDay:function(){return"[ayer a la"+(this.hours()!==1?"s":"")+"] LT"},lastWeek:function(){return"[el] dddd [pasado a la"+(this.hours()!==1?"s":"")+"] LT"},sameElse:"L"},relativeTime:{future:"en %s",past:"hace %s",s:"unos segundos",m:"un minuto",mm:"%d minutos",h:"una hora",hh:"%d horas",d:"un día",dd:"%d días",M:"un mes",MM:"%d meses",y:"un año",yy:"%d años"},ordinal:function(a){return"º"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("es",a)}(),function(){var a={months:"urtarrila_otsaila_martxoa_apirila_maiatza_ekaina_uztaila_abuztua_iraila_urria_azaroa_abendua".split("_"),monthsShort:"urt._ots._mar._api._mai._eka._uzt._abu._ira._urr._aza._abe.".split("_"),weekdays:"igandea_astelehena_asteartea_asteazkena_osteguna_ostirala_larunbata".split("_"),weekdaysShort:"ig._al._ar._az._og._ol._lr.".split("_"),weekdaysMin:"ig_al_ar_az_og_ol_lr".split("_"),longDateFormat:{LT:"HH:mm",L:"YYYY-MM-DD",LL:"YYYYko MMMMren D[a]",LLL:"YYYYko MMMMren D[a] LT",LLLL:"dddd, YYYYko MMMMren D[a] LT"},calendar:{sameDay:"[gaur] LT[etan]",nextDay:"[bihar] LT[etan]",nextWeek:"dddd LT[etan]",lastDay:"[atzo] LT[etan]",lastWeek:"[aurreko] dddd LT[etan]",sameElse:"L"},relativeTime:{future:"%s barru",past:"duela %s",s:"segundo batzuk",m:"minutu bat",mm:"%d minutu",h:"ordu bat",hh:"%d ordu",d:"egun bat",dd:"%d egun",M:"hilabete bat",MM:"%d hilabete",y:"urte bat",yy:"%d urte"},ordinal:function(a){return"."}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("eu",a)}(),function(){function c(a,b,c,e){var f="";switch(c){case"s":return e?"muutaman sekunnin":"muutama sekunti";case"m":return e?"minuutin":"minuutti";case"mm":f=e?"minuutin":"minuuttia";break;case"h":return e?"tunnin":"tunti";case"hh":f=e?"tunnin":"tuntia";break;case"d":return e?"päivän":"päivä";case"dd":f=e?"päivän":"päivää";break;case"M":return e?"kuukauden":"kuukausi";case"MM":f=e?"kuukauden":"kuukautta";break;case"y":return e?"vuoden":"vuosi";case"yy":f=e?"vuoden":"vuotta"}return f=d(a,e)+" "+f,f}function d(c,d){return c<10?d?b[c]:a[c]:c}var a=["nolla","yksi","kaksi","kolme","neljä","viisi","kuusi","seitsemän","kahdeksan","yhdeksän"],b=["nolla","yhden","kahden","kolmen","neljän","viiden","kuuden",a[7],a[8],a[9]],e={months:"tammikuu_helmikuu_maaliskuu_huhtikuu_toukokuu_kesäkuu_heinäkuu_elokuu_syyskuu_lokakuu_marraskuu_joulukuu".split("_"),monthsShort:"tam_hel_maa_huh_tou_kes_hei_elo_syy_lok_mar_jou".split("_"),weekdays:"sunnuntai_maanantai_tiistai_keskiviikko_torstai_perjantai_lauantai".split("_"),weekdaysShort:"su_ma_ti_ke_to_pe_la".split("_"),weekdaysMin:"su_ma_ti_ke_to_pe_la".split("_"),longDateFormat:{LT:"HH.mm",L:"DD.MM.YYYY",LL:"Do MMMMt\\a YYYY",LLL:"Do MMMMt\\a YYYY, klo LT",LLLL:"dddd, Do MMMMt\\a YYYY, klo LT"},calendar:{sameDay:"[tänään] [klo] LT",nextDay:"[huomenna] [klo] LT",nextWeek:"dddd [klo] LT",lastDay:"[eilen] [klo] LT",lastWeek:"[viime] dddd[na] [klo] LT",sameElse:"L"},relativeTime:{future:"%s päästä",past:"%s sitten",s:c,m:c,mm:c,h:c,hh:c,d:c,dd:c,M:c,MM:c,y:c,yy:c},ordinal:function(a){return"."}};typeof module!="undefined"&&(module.exports=e),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("fi",e)}(),function(){var a={months:"janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre".split("_"),monthsShort:"janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.".split("_"),weekdays:"dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi".split("_"),weekdaysShort:"dim._lun._mar._mer._jeu._ven._sam.".split("_"),weekdaysMin:"Di_Lu_Ma_Me_Je_Ve_Sa".split("_"),longDateFormat:{LT:"HH:mm",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd D MMMM YYYY LT"},calendar:{sameDay:"[Aujourd'hui à] LT",nextDay:"[Demain à] LT",nextWeek:"dddd [à] LT",lastDay:"[Hier à] LT",lastWeek:"dddd [dernier à] LT",sameElse:"L"},relativeTime:{future:"dans %s",past:"il y a %s",s:"quelques secondes",m:"une minute",mm:"%d minutes",h:"une heure",hh:"%d heures",d:"un jour",dd:"%d jours",M:"un mois",MM:"%d mois",y:"une année",yy:"%d années"},ordinal:function(a){return a===1?"er":"ème"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("fr",a)}(),function(){var a={months:"Xaneiro_Febreiro_Marzo_Abril_Maio_Xuño_Xullo_Agosto_Setembro_Octubro_Novembro_Decembro".split("_"),monthsShort:"Xan._Feb._Mar._Abr._Mai._Xuñ._Xul._Ago._Set._Out._Nov._Dec.".split("_"),weekdays:"Domingo_Luns_Martes_Mércores_Xoves_Venres_Sábado".split("_"),weekdaysShort:"Dom._Lun._Mar._Mér._Xov._Ven._Sáb.".split("_"),weekdaysMin:"Do_Lu_Ma_Mé_Xo_Ve_Sá".split("_"),longDateFormat:{LT:"H:mm",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd D MMMM YYYY LT"},calendar:{sameDay:function(){return"[hoxe "+(this.hours()!==1?"ás":"a")+"] LT"},nextDay:function(){return"[mañá "+(this.hours()!==1?"ás":"a")+"] LT"},nextWeek:function(){return"dddd ["+(this.hours()!==1?"ás":"a")+"] LT"},lastDay:function(){return"[onte "+(this.hours()!==1?"á":"a")+"] LT"},lastWeek:function(){return"[o] dddd [pasado "+(this.hours()!==1?"ás":"a")+"] LT"},sameElse:"L"},relativeTime:{future:"en %s",past:"fai %s",s:"uns segundo",m:"un minuto",mm:"%d minutos",h:"unha hora",hh:"%d horas",d:"un día",dd:"%d días",M:"un mes",MM:"%d meses",y:"un ano",yy:"%d anos"},ordinal:function(a){return"º"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("gl",a)}(),function(){var a=function(a){return a%100==11?!0:a%10==1?!1:!0},b=function(b,c,d,e){var f=b+" ";switch(d){case"s":return c||e?"nokkrar sekúndur":"nokkrum sekúndum";case"m":return c?"mínúta":"mínútu";case"mm":return a(b)?f+(c||e?"mínútur":"mínútum"):c?f+"mínúta":f+"mínútu";case"hh":return a(b)?f+(c||e?"klukkustundir":"klukkustundum"):f+"klukkustund";case"d":return c?"dagur":e?"dag":"degi";case"dd":return a(b)?c?f+"dagar":f+(e?"daga":"dögum"):c?f+"dagur":f+(e?"dag":"degi");case"M":return c?"mánuður":e?"mánuð":"mánuði";case"MM":return a(b)?c?f+"mánuðir":f+(e?"mánuði":"mánuðum"):c?f+"mánuður":f+(e?"mánuð":"mánuði");case"y":return c||e?"ár":"ári";case"yy":return a(b)?f+(c||e?"ár":"árum"):f+(c||e?"ár":"ári")}},c={months:"janúar_febrúar_mars_apríl_maí_júní_júlí_ágúst_september_október_nóvember_desember".split("_"),monthsShort:"jan_feb_mar_apr_maí_jún_júl_ágú_sep_okt_nóv_des".split("_"),weekdays:"sunnudagur_mánudagur_þriðjudagur_miðvikudagur_fimmtudagur_föstudagur_laugardagur".split("_"),weekdaysShort:"sun_mán_þri_mið_fim_fös_lau".split("_"),weekdaysMin:"Su_Má_Þr_Mi_Fi_Fö_La".split("_"),longDateFormat:{LT:"H:mm",L:"DD/MM/YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY kl. LT",LLLL:"dddd, D. MMMM YYYY kl. LT"},calendar:{sameDay:"[í dag kl.] LT",nextDay:"[á morgun kl.] LT",nextWeek:"dddd [kl.] LT",lastDay:"[í gær kl.] LT",lastWeek:"[síðasta] dddd [kl.] LT",sameElse:"L"},relativeTime:{future:"eftir %s",past:"fyrir %s síðan",s:b,m:b,mm:b,h:"klukkustund",hh:b,d:b,dd:b,M:b,MM:b,y:b,yy:b},ordinal:function(a){return"."}};typeof module!="undefined"&&(module.exports=c),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("is",c)}(),function(){var a={months:"Gennaio_Febbraio_Marzo_Aprile_Maggio_Giugno_Luglio_Agosto_Settebre_Ottobre_Novembre_Dicembre".split("_"),monthsShort:"Gen_Feb_Mar_Apr_Mag_Giu_Lug_Ago_Set_Ott_Nov_Dic".split("_"),weekdays:"Domenica_Lunedi_Martedi_Mercoledi_Giovedi_Venerdi_Sabato".split("_"),weekdaysShort:"Dom_Lun_Mar_Mer_Gio_Ven_Sab".split("_"),weekdaysMin:"D_L_Ma_Me_G_V_S".split("_"),longDateFormat:{LT:"HH:mm",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd, D MMMM YYYY LT"},calendar:{sameDay:"[Oggi alle] LT",nextDay:"[Domani alle] LT",nextWeek:"dddd [alle] LT",lastDay:"[Ieri alle] LT",lastWeek:"[lo scorso] dddd [alle] LT",sameElse:"L"},relativeTime:{future:"in %s",past:"%s fa",s:"secondi",m:"un minuto",mm:"%d minuti",h:"un ora",hh:"%d ore",d:"un giorno",dd:"%d giorni",M:"un mese",MM:"%d mesi",y:"un anno",yy:"%d anni"},ordinal:function(){return"º"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("it",a)}(),function(){var a={months:"1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"),monthsShort:"1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"),weekdays:"日曜日_月曜日_火曜日_水曜日_木曜日_金曜日_土曜日".split("_"),weekdaysShort:"日_月_火_水_木_金_土".split("_"),weekdaysMin:"日_月_火_水_木_金_土".split("_"),longDateFormat:{LT:"Ah:mm",L:"YYYY/MM/DD",LL:"YYYY年M月D日",LLL:"YYYY年M月D日 LT",LLLL:"YYYY年M月D日 dddd LT"},meridiem:function(a,b,c){return a<12?"午前":"午後"},calendar:{sameDay:"[今日] LT",nextDay:"[明日] LT",nextWeek:"[来週]dddd LT",lastDay:"[昨日] LT",lastWeek:"[前週]dddd LT",sameElse:"L"},relativeTime:{future:"%s後",past:"%s前",s:"数秒",m:"1分",mm:"%d分",h:"1時間",hh:"%d時間",d:"1日",dd:"%d日",M:"1ヶ月",MM:"%dヶ月",y:"1年",yy:"%d年"},ordinal:function(a){return""}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("jp",a)}(),function(){var a={months:"1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월".split("_"),monthsShort:"1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월".split("_"),weekdays:"일요일_월요일_화요일_수요일_목요일_금요일_토요일".split("_"),weekdaysShort:"일_월_화_수_목_금_토".split("_"),weekdaysMin:"일_월_화_수_목_금_토".split("_"),longDateFormat:{LT:"A h시 mm분",L:"YYYY.MM.DD",LL:"YYYY년 MMMM D일",LLL:"YYYY년 MMMM D일 LT",LLLL:"YYYY년 MMMM D일 dddd LT"},meridiem:function(a,b,c){return a<12?"오전":"오후"},calendar:{sameDay:"오늘 LT",nextDay:"내일 LT",nextWeek:"dddd LT",lastDay:"어제 LT",lastWeek:"지난주 dddd LT",sameElse:"L"},relativeTime:{future:"%s 후",past:"%s 전",s:"몇초",ss:"%d초",m:"일분",mm:"%d분",h:"한시간",hh:"%d시간",d:"하루",dd:"%d일",M:"한달",MM:"%d달",y:"일년",yy:"%d년"},ordinal:function(a){return"일"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("kr",a)}(),function(){var a={months:"januar_februar_mars_april_mai_juni_juli_august_september_oktober_november_desember".split("_"),monthsShort:"jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des".split("_"),weekdays:"søndag_mandag_tirsdag_onsdag_torsdag_fredag_lørdag".split("_"),weekdaysShort:"søn_man_tir_ons_tor_fre_lør".split("_"),weekdaysMin:"sø_ma_ti_on_to_fr_lø".split("_"),longDateFormat:{LT:"HH:mm",L:"YYYY-MM-DD",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd D MMMM YYYY LT"},calendar:{sameDay:"[I dag klokken] LT",nextDay:"[I morgen klokken] LT",nextWeek:"dddd [klokken] LT",lastDay:"[I går klokken] LT",lastWeek:"[Forrige] dddd [klokken] LT",sameElse:"L"},relativeTime:{future:"om %s",past:"for %s siden",s:"noen sekunder",m:"ett minutt",mm:"%d minutter",h:"en time",hh:"%d timer",d:"en dag",dd:"%d dager",M:"en måned",MM:"%d måneder",y:"ett år",yy:"%d år"},ordinal:function(a){return"."}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("nb",a)}(),function(){var a={months:"januari_februari_maart_april_mei_juni_juli_augustus_september_oktober_november_december".split("_"),monthsShort:"jan._feb._mar._apr._mei._jun._jul._aug._sep._okt._nov._dec.".split("_"),weekdays:"zondag_maandag_dinsdag_woensdag_donderdag_vrijdag_zaterdag".split("_"),weekdaysShort:"zo._ma._di._wo._do._vr._za.".split("_"),weekdaysMin:"Zo_Ma_Di_Wo_Do_Vr_Za".split("_"),longDateFormat:{LT:"HH:mm",L:"DD-MM-YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd D MMMM YYYY LT"},calendar:{sameDay:"[Vandaag om] LT",nextDay:"[Morgen om] LT",nextWeek:"dddd [om] LT",lastDay:"[Gisteren om] LT",lastWeek:"[afgelopen] dddd [om] LT",sameElse:"L"},relativeTime:{future:"over %s",past:"%s geleden",s:"een paar seconden",m:"één minuut",mm:"%d minuten",h:"één uur",hh:"%d uur",d:"één dag",dd:"%d dagen",M:"één maand",MM:"%d maanden",y:"één jaar",yy:"%d jaar"},ordinal:function(a){return a===1||a===8||a>=20?"ste":"de"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("nl",a)}(),function(){var a=function(a){return a%10<5&&a%10>1&&~~(a/10)!==1},b=function(b,c,d){var e=b+" ";switch(d){case"m":return c?"minuta":"minutę";case"mm":return e+(a(b)?"minuty":"minut");case"h":return c?"godzina":"godzinę";case"hh":return e+(a(b)?"godziny":"godzin");case"MM":return e+(a(b)?"miesiące":"miesięcy");case"yy":return e+(a(b)?"lata":"lat")}},c={months:"styczeń_luty_marzec_kwiecień_maj_czerwiec_lipiec_sierpień_wrzesień_październik_listopad_grudzień".split("_"),monthsShort:"sty_lut_mar_kwi_maj_cze_lip_sie_wrz_paź_lis_gru".split("_"),weekdays:"niedziela_poniedziałek_wtorek_środa_czwartek_piątek_sobota".split("_"),weekdaysShort:"nie_pon_wt_śr_czw_pt_sb".split("_"),weekdaysMin:"N_Pn_Wt_Śr_Cz_Pt_So".split("_"),longDateFormat:{LT:"HH:mm",L:"DD-MM-YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd, D MMMM YYYY LT"},calendar:{sameDay:"[Dziś o] LT",nextDay:"[Jutro o] LT",nextWeek:"[W] dddd [o] LT",lastDay:"[Wczoraj o] LT",lastWeek:"[W zeszły/łą] dddd [o] LT",sameElse:"L"},relativeTime:{future:"za %s",past:"%s temu",s:"kilka sekund",m:b,mm:b,h:b,hh:b,d:"1 dzień",dd:"%d dni",M:"miesiąc",MM:b,y:"rok",yy:b},ordinal:function(a){return"."}};typeof module!="undefined"&&(module.exports=c),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("pl",c)}(),function(){var a={months:"Janeiro_Fevereiro_Março_Abril_Maio_Junho_Julho_Agosto_Setembro_Outubro_Novembro_Dezembro".split("_"),monthsShort:"Jan_Fev_Mar_Abr_Mai_Jun_Jul_Ago_Set_Out_Nov_Dez".split("_"),weekdays:"Domingo_Segunda-feira_Terça-feira_Quarta-feira_Quinta-feira_Sexta-feira_Sábado".split("_"),weekdaysShort:"Dom_Seg_Ter_Qua_Qui_Sex_Sáb".split("_"),weekdaysMin:"Dom_Seg_Ter_Qua_Qui_Sex_Sáb".split("_"),longDateFormat:{LT:"HH:mm",L:"DD/MM/YYYY",LL:"D \\de MMMM \\de YYYY",LLL:"D \\de MMMM \\de YYYY LT",LLLL:"dddd, D \\de MMMM \\de YYYY LT"},calendar:{sameDay:"[Hoje às] LT",nextDay:"[Amanhã às] LT",nextWeek:"dddd [às] LT",lastDay:"[Ontem às] LT",lastWeek:function(){return this.day()===0||this.day()===6?"[Último] dddd [às] LT":"[Última] dddd [às] LT"},sameElse:"L"},relativeTime:{future:"em %s",past:"%s atrás",s:"segundos",m:"um minuto",mm:"%d minutos",h:"uma hora",hh:"%d horas",d:"um dia",dd:"%d dias",M:"um mês",MM:"%d meses",y:"um ano",yy:"%d anos"},ordinal:function(a){return"º"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("pt",a)}(),function(){var a=[function(a){return a%10===1&&a%100!==11},function(a){return a%10>=2&&a%10<=4&&a%10%1===0&&(a%100<12||a%100>14)},function(a){return a%10===0||a%10>=5&&a%10<=9&&a%10%1===0||a%100>=11&&a%100<=14&&a%100%1===0},function(a){return!0}],b=function(b,c){var d=b.split("_"),e=Math.min(a.length,d.length),f=-1;while(++f<e)if(a[f](c))return d[f];return d[e-1]},c=function(a,c,d){var e={mm:"минута_минуты_минут_минуты",hh:"час_часа_часов_часа",dd:"день_дня_дней_дня",MM:"месяц_месяца_месяцев_месяца",yy:"год_года_лет_года"};return d==="m"?c?"минута":"минуту":a+" "+b(e[d],+a)},d={months:"январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь".split("_"),monthsShort:"янв_фев_мар_апр_май_июн_июл_авг_сен_окт_ноя_дек".split("_"),weekdays:"воскресенье_понедельник_вторник_среда_четверг_пятница_суббота".split("_"),weekdaysShort:"вск_пнд_втр_срд_чтв_птн_суб".split("_"),weekdaysMin:"вс_пн_вт_ср_чт_пт_сб".split("_"),longDateFormat:{LT:"HH:mm",L:"DD-MM-YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd, D MMMM YYYY LT"},calendar:{sameDay:"[Сегодня в] LT",nextDay:"[Завтра в] LT",lastDay:"[Вчера в] LT",nextWeek:function(){return this.day()===2?"[Во] dddd [в] LT":"[В] dddd [в] LT"},lastWeek:function(){switch(this.day()){case 0:return"[В прошлое] dddd [в] LT";case 1:case 2:case 4:return"[В прошлый] dddd [в] LT";case 3:case 5:case 6:return"[В прошлую] dddd [в] LT"}},sameElse:"L"},relativeTime:{future:"через %s",past:"%s назад",s:"несколько секунд",m:c,mm:c,h:"час",hh:c,d:"день",dd:c,M:"месяц",MM:c,y:"год",yy:c},ordinal:function(a){return"."}};typeof module!="undefined"&&(module.exports=d),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("ru",d)}(),function(){var a={months:"januari_februari_mars_april_maj_juni_juli_augusti_september_oktober_november_december".split("_"),monthsShort:"jan_feb_mar_apr_maj_jun_jul_aug_sep_okt_nov_dec".split("_"),weekdays:"söndag_måndag_tisdag_onsdag_torsdag_fredag_lördag".split("_"),weekdaysShort:"sön_mån_tis_ons_tor_fre_lör".split("_"),weekdaysMin:"sö_må_ti_on_to_fr_lö".split("_"),longDateFormat:{LT:"HH:mm",L:"YYYY-MM-DD",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd D MMMM YYYY LT"},calendar:{sameDay:"[Idag klockan] LT",nextDay:"[Imorgon klockan] LT",lastDay:"[Igår klockan] LT",nextWeek:"dddd [klockan] LT",lastWeek:"[Förra] dddd[en klockan] LT",sameElse:"L"},relativeTime:{future:"om %s",past:"för %s sen",s:"några sekunder",m:"en minut",mm:"%d minuter",h:"en timme",hh:"%d timmar",d:"en dag",dd:"%d dagar",M:"en månad",MM:"%d månader",y:"ett år",yy:"%d år"},ordinal:function(a){var b=a%10;return~~(a%100/10)===1?"e":b===1?"a":b===2?"a":b===3?"e":"e"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("sv",a)}(),function(){var a={months:"Ocak_Şubat_Mart_Nisan_Mayıs_Haziran_Temmuz_Ağustos_Eylül_Ekim_Kasım_Aralık".split("_"),monthsShort:"Oca_Şub_Mar_Nis_May_Haz_Tem_Ağu_Eyl_Eki_Kas_Ara".split("_"),weekdays:"Pazar_Pazartesi_Salı_Çarşamba_Perşembe_Cuma_Cumartesi".split("_"),weekdaysShort:"Paz_Pts_Sal_Çar_Per_Cum_Cts".split("_"),weekdaysMin:"Pz_Pt_Sa_Ça_Pe_Cu_Ct".split("_"),longDateFormat:{LT:"HH:mm",L:"DD.MM.YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd, D MMMM YYYY LT"},calendar:{sameDay:"[bugün saat] LT",nextDay:"[yarın saat] LT",nextWeek:"[haftaya] dddd [saat] LT",lastDay:"[dün] LT",lastWeek:"[geçen hafta] dddd [saat] LT",sameElse:"L"},relativeTime:{future:"%s sonra",past:"%s önce",s:"birkaç saniye",m:"bir dakika",mm:"%d dakika",h:"bir saat",hh:"%d saat",d:"bir gün",dd:"%d gün",M:"bir ay",MM:"%d ay",y:"bir yıl",yy:"%d yıl"},ordinal:function(a){var b=a%10;return~~(a%100/10)===1?"th":b===1?"st":b===2?"nd":b===3?"rd":"th"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("tr",a)}(),function(){var a={months:"一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月".split("_"),monthsShort:"1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"),weekdays:"星期日_星期一_星期二_星期三_星期四_星期五_星期六".split("_"),weekdaysShort:"周日_周一_周二_周三_周四_周五_周六".split("_"),weekdaysMin:"日_一_二_三_四_五_六".split("_"),longDateFormat:{LT:"Ah点mm",L:"YYYY年MMMD日",LL:"YYYY年MMMD日",LLL:"YYYY年MMMD日LT",LLLL:"YYYY年MMMD日ddddLT"},meridiem:function(a,b,c){return a<9?"早上":a<11&&b<30?"上午":a<13&&b<30?"中午":a<18?"下午":"晚上"},calendar:{sameDay:"[今天]LT",nextDay:"[明天]LT",nextWeek:"[下]ddddLT",lastDay:"[昨天]LT",lastWeek:"[上]ddddLT",sameElse:"L"},relativeTime:{future:"%s内",past:"%s前",s:"几秒",m:"1分钟",mm:"%d分钟",h:"1小时",hh:"%d小时",d:"1天",dd:"%d天",M:"1个月",MM:"%d个月",y:"1年",yy:"%d年"},ordinal:function(a){return""}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("zh-cn",a)}(),function(){var a={months:"一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月".split("_"),monthsShort:"1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"),weekdays:"星期日_星期一_星期二_星期三_星期四_星期五_星期六".split("_"),weekdaysShort:"週日_週一_週二_週三_週四_週五_週六".split("_"),weekdaysMin:"日_一_二_三_四_五_六".split("_"),longDateFormat:{LT:"Ah點mm",L:"YYYY年MMMD日",LL:"YYYY年MMMD日",LLL:"YYYY年MMMD日LT",LLLL:"YYYY年MMMD日ddddLT"},meridiem:function(a,b,c){return a<9?"早上":a<11&&b<30?"上午":a<13&&b<30?"中午":a<18?"下午":"晚上"},calendar:{sameDay:"[今天]LT",nextDay:"[明天]LT",nextWeek:"[下]ddddLT",lastDay:"[昨天]LT",lastWeek:"[上]ddddLT",sameElse:"L"},relativeTime:{future:"%s內",past:"%s前",s:"幾秒",m:"一分鐘",mm:"%d分鐘",h:"一小時",hh:"%d小時",d:"一天",dd:"%d天",M:"一個月",MM:"%d個月",y:"一年",yy:"%d年"},ordinal:function(a){return""}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("zh-tw",a)}(); <ide>\ No newline at end of file <add>(function(){var a={months:"Gener_Febrer_Març_Abril_Maig_Juny_Juliol_Agost_Setembre_Octubre_Novembre_Desembre".split("_"),monthsShort:"Gen._Febr._Mar._Abr._Mai._Jun._Jul._Ag._Set._Oct._Nov._Des.".split("_"),weekdays:"Diumenge_Dilluns_Dimarts_Dimecres_Dijous_Divendres_Dissabte".split("_"),weekdaysShort:"Dg._Dl._Dt._Dc._Dj._Dv._Ds.".split("_"),weekdaysMin:"Dg_Dl_Dt_Dc_Dj_Dv_Ds".split("_"),longDateFormat:{LT:"H:mm",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd D MMMM YYYY LT"},calendar:{sameDay:function(){return"[avui a "+(this.hours()!==1?"les":"la")+"] LT"},nextDay:function(){return"[demà a "+(this.hours()!==1?"les":"la")+"] LT"},nextWeek:function(){return"dddd [a "+(this.hours()!==1?"les":"la")+"] LT"},lastDay:function(){return"[ahir a "+(this.hours()!==1?"les":"la")+"] LT"},lastWeek:function(){return"[el] dddd [passat a "+(this.hours()!==1?"les":"la")+"] LT"},sameElse:"L"},relativeTime:{future:"en %s",past:"fa %s",s:"uns segons",m:"un minut",mm:"%d minuts",h:"una hora",hh:"%d hores",d:"un dia",dd:"%d dies",M:"un mes",MM:"%d mesos",y:"un any",yy:"%d anys"},ordinal:function(a){return"º"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("ca",a)})(),function(){var a={months:"кăрлач_нарăс_пуш_ака_май_çĕртме_утă_çурла_авăн_юпа_чӳк_раштав".split("_"),monthsShort:"кăр_нар_пуш_ака_май_çĕр_утă_çур_ав_юпа_чӳк_раш".split("_"),weekdays:"вырсарникун_тунтикун_ытларикун_юнкун_кĕçнерникун_эрнекун_шăматкун".split("_"),weekdaysShort:"выр_тун_ытл_юн_кĕç_эрн_шăм".split("_"),weekdaysMin:"вр_тн_ыт_юн_кç_эр_шм".split("_"),longDateFormat:{LT:"HH:mm",L:"DD-MM-YYYY",LL:"YYYY çулхи MMMM уйăхĕн D-мĕшĕ",LLL:"YYYY çулхи MMMM уйăхĕн D-мĕшĕ, LT",LLLL:"dddd, YYYY çулхи MMMM уйăхĕн D-мĕшĕ, LT"},calendar:{sameDay:"[Паян] LT [сехетре]",nextDay:"[Ыран] LT [сехетре]",lastDay:"[Ĕнер] LT [сехетре]",nextWeek:"[Çитес] dddd LT [сехетре]",lastWeek:"[Иртнĕ] dddd LT [сехетре]",sameElse:"L"},relativeTime:{future:"%sран",past:"%s каялла",s:"пĕр-ик çеккунт",m:"пĕр минут",mm:"%d минут",h:"пĕр сехет",hh:"%d сехет",d:"пĕр кун",dd:"%d кун",M:"пĕр уйăх",MM:"%d уйăх",y:"пĕр çул",yy:"%d çул"},ordinal:function(a){return"-мĕш"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("cv",a)}(),function(){var a={months:"Januar_Februar_Marts_April_Maj_Juni_Juli_August_September_Oktober_November_December".split("_"),monthsShort:"Jan_Feb_Mar_Apr_Maj_Jun_Jul_Aug_Sep_Okt_Nov_Dec".split("_"),weekdays:"Søndag_Mandag_Tirsdag_Onsdag_Torsdag_Fredag_Lørdag".split("_"),weekdaysShort:"Søn_Man_Tir_Ons_Tor_Fre_Lør".split("_"),weekdaysMin:"Sø_Ma_Ti_On_To_Fr_Lø".split("_"),longDateFormat:{LT:"h:mm A",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY h:mm A",LLLL:"dddd D. MMMM, YYYY h:mm A"},calendar:{sameDay:"[I dag kl.] LT",nextDay:"[I morgen kl.] LT",nextWeek:"dddd [kl.] LT",lastDay:"[I går kl.] LT",lastWeek:"[sidste] dddd [kl] LT",sameElse:"L"},relativeTime:{future:"om %s",past:"%s siden",s:"få sekunder",m:"minut",mm:"%d minutter",h:"time",hh:"%d timer",d:"dag",dd:"%d dage",M:"månede",MM:"%d måneder",y:"år",yy:"%d år"},ordinal:function(a){return"."}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("da",a)}(),function(){var a={months:"Januar_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember".split("_"),monthsShort:"Jan._Febr._Mrz._Apr._Mai_Jun._Jul._Aug._Sept._Okt._Nov._Dez.".split("_"),weekdays:"Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag".split("_"),weekdaysShort:"So._Mo._Di._Mi._Do._Fr._Sa.".split("_"),weekdaysMin:"So_Mo_Di_Mi_Do_Fr_Sa".split("_"),longDateFormat:{LT:"H:mm U\\hr",L:"DD.MM.YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY LT",LLLL:"dddd, D. MMMM YYYY LT"},calendar:{sameDay:"[Heute um] LT",sameElse:"L",nextDay:"[Morgen um] LT",nextWeek:"dddd [um] LT",lastDay:"[Gestern um] LT",lastWeek:"[letzten] dddd [um] LT"},relativeTime:{future:"in %s",past:"vor %s",s:"ein paar Sekunden",m:"einer Minute",mm:"%d Minuten",h:"einer Stunde",hh:"%d Stunden",d:"einem Tag",dd:"%d Tagen",M:"einem Monat",MM:"%d Monaten",y:"einem Jahr",yy:"%d Jahren"},ordinal:function(a){return"."}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("de",a)}(),function(){var a={months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),monthsShort:"Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),weekdaysShort:"Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),weekdaysMin:"Su_Mo_Tu_We_Th_Fr_Sa".split("_"),longDateFormat:{LT:"h:mm A",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd, D MMMM YYYY LT"},calendar:{sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[last] dddd [at] LT",sameElse:"L"},relativeTime:{future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},ordinal:function(a){var b=a%10;return~~(a%100/10)===1?"th":b===1?"st":b===2?"nd":b===3?"rd":"th"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("en-gb",a)}(),function(){var a={months:"Enero_Febrero_Marzo_Abril_Mayo_Junio_Julio_Agosto_Septiembre_Octubre_Noviembre_Diciembre".split("_"),monthsShort:"Ene._Feb._Mar._Abr._May._Jun._Jul._Ago._Sep._Oct._Nov._Dic.".split("_"),weekdays:"Domingo_Lunes_Martes_Miércoles_Jueves_Viernes_Sábado".split("_"),weekdaysShort:"Dom._Lun._Mar._Mié._Jue._Vie._Sáb.".split("_"),weekdaysMin:"Do_Lu_Ma_Mi_Ju_Vi_Sá".split("_"),longDateFormat:{LT:"H:mm",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd D MMMM YYYY LT"},calendar:{sameDay:function(){return"[hoy a la"+(this.hours()!==1?"s":"")+"] LT"},nextDay:function(){return"[mañana a la"+(this.hours()!==1?"s":"")+"] LT"},nextWeek:function(){return"dddd [a la"+(this.hours()!==1?"s":"")+"] LT"},lastDay:function(){return"[ayer a la"+(this.hours()!==1?"s":"")+"] LT"},lastWeek:function(){return"[el] dddd [pasado a la"+(this.hours()!==1?"s":"")+"] LT"},sameElse:"L"},relativeTime:{future:"en %s",past:"hace %s",s:"unos segundos",m:"un minuto",mm:"%d minutos",h:"una hora",hh:"%d horas",d:"un día",dd:"%d días",M:"un mes",MM:"%d meses",y:"un año",yy:"%d años"},ordinal:function(a){return"º"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("es",a)}(),function(){var a={months:"urtarrila_otsaila_martxoa_apirila_maiatza_ekaina_uztaila_abuztua_iraila_urria_azaroa_abendua".split("_"),monthsShort:"urt._ots._mar._api._mai._eka._uzt._abu._ira._urr._aza._abe.".split("_"),weekdays:"igandea_astelehena_asteartea_asteazkena_osteguna_ostirala_larunbata".split("_"),weekdaysShort:"ig._al._ar._az._og._ol._lr.".split("_"),weekdaysMin:"ig_al_ar_az_og_ol_lr".split("_"),longDateFormat:{LT:"HH:mm",L:"YYYY-MM-DD",LL:"YYYYko MMMMren D[a]",LLL:"YYYYko MMMMren D[a] LT",LLLL:"dddd, YYYYko MMMMren D[a] LT"},calendar:{sameDay:"[gaur] LT[etan]",nextDay:"[bihar] LT[etan]",nextWeek:"dddd LT[etan]",lastDay:"[atzo] LT[etan]",lastWeek:"[aurreko] dddd LT[etan]",sameElse:"L"},relativeTime:{future:"%s barru",past:"duela %s",s:"segundo batzuk",m:"minutu bat",mm:"%d minutu",h:"ordu bat",hh:"%d ordu",d:"egun bat",dd:"%d egun",M:"hilabete bat",MM:"%d hilabete",y:"urte bat",yy:"%d urte"},ordinal:function(a){return"."}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("eu",a)}(),function(){function c(a,b,c,e){var f="";switch(c){case"s":return e?"muutaman sekunnin":"muutama sekunti";case"m":return e?"minuutin":"minuutti";case"mm":f=e?"minuutin":"minuuttia";break;case"h":return e?"tunnin":"tunti";case"hh":f=e?"tunnin":"tuntia";break;case"d":return e?"päivän":"päivä";case"dd":f=e?"päivän":"päivää";break;case"M":return e?"kuukauden":"kuukausi";case"MM":f=e?"kuukauden":"kuukautta";break;case"y":return e?"vuoden":"vuosi";case"yy":f=e?"vuoden":"vuotta"}return f=d(a,e)+" "+f,f}function d(c,d){return c<10?d?b[c]:a[c]:c}var a=["nolla","yksi","kaksi","kolme","neljä","viisi","kuusi","seitsemän","kahdeksan","yhdeksän"],b=["nolla","yhden","kahden","kolmen","neljän","viiden","kuuden",a[7],a[8],a[9]],e={months:"tammikuu_helmikuu_maaliskuu_huhtikuu_toukokuu_kesäkuu_heinäkuu_elokuu_syyskuu_lokakuu_marraskuu_joulukuu".split("_"),monthsShort:"tam_hel_maa_huh_tou_kes_hei_elo_syy_lok_mar_jou".split("_"),weekdays:"sunnuntai_maanantai_tiistai_keskiviikko_torstai_perjantai_lauantai".split("_"),weekdaysShort:"su_ma_ti_ke_to_pe_la".split("_"),weekdaysMin:"su_ma_ti_ke_to_pe_la".split("_"),longDateFormat:{LT:"HH.mm",L:"DD.MM.YYYY",LL:"Do MMMMt\\a YYYY",LLL:"Do MMMMt\\a YYYY, klo LT",LLLL:"dddd, Do MMMMt\\a YYYY, klo LT"},calendar:{sameDay:"[tänään] [klo] LT",nextDay:"[huomenna] [klo] LT",nextWeek:"dddd [klo] LT",lastDay:"[eilen] [klo] LT",lastWeek:"[viime] dddd[na] [klo] LT",sameElse:"L"},relativeTime:{future:"%s päästä",past:"%s sitten",s:c,m:c,mm:c,h:c,hh:c,d:c,dd:c,M:c,MM:c,y:c,yy:c},ordinal:function(a){return"."}};typeof module!="undefined"&&(module.exports=e),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("fi",e)}(),function(){var a={months:"janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre".split("_"),monthsShort:"janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.".split("_"),weekdays:"dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi".split("_"),weekdaysShort:"dim._lun._mar._mer._jeu._ven._sam.".split("_"),weekdaysMin:"Di_Lu_Ma_Me_Je_Ve_Sa".split("_"),longDateFormat:{LT:"HH:mm",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd D MMMM YYYY LT"},calendar:{sameDay:"[Aujourd'hui à] LT",nextDay:"[Demain à] LT",nextWeek:"dddd [à] LT",lastDay:"[Hier à] LT",lastWeek:"dddd [dernier à] LT",sameElse:"L"},relativeTime:{future:"dans %s",past:"il y a %s",s:"quelques secondes",m:"une minute",mm:"%d minutes",h:"une heure",hh:"%d heures",d:"un jour",dd:"%d jours",M:"un mois",MM:"%d mois",y:"une année",yy:"%d années"},ordinal:function(a){return a===1?"er":"ème"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("fr",a)}(),function(){var a={months:"Xaneiro_Febreiro_Marzo_Abril_Maio_Xuño_Xullo_Agosto_Setembro_Octubro_Novembro_Decembro".split("_"),monthsShort:"Xan._Feb._Mar._Abr._Mai._Xuñ._Xul._Ago._Set._Out._Nov._Dec.".split("_"),weekdays:"Domingo_Luns_Martes_Mércores_Xoves_Venres_Sábado".split("_"),weekdaysShort:"Dom._Lun._Mar._Mér._Xov._Ven._Sáb.".split("_"),weekdaysMin:"Do_Lu_Ma_Mé_Xo_Ve_Sá".split("_"),longDateFormat:{LT:"H:mm",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd D MMMM YYYY LT"},calendar:{sameDay:function(){return"[hoxe "+(this.hours()!==1?"ás":"a")+"] LT"},nextDay:function(){return"[mañá "+(this.hours()!==1?"ás":"a")+"] LT"},nextWeek:function(){return"dddd ["+(this.hours()!==1?"ás":"a")+"] LT"},lastDay:function(){return"[onte "+(this.hours()!==1?"á":"a")+"] LT"},lastWeek:function(){return"[o] dddd [pasado "+(this.hours()!==1?"ás":"a")+"] LT"},sameElse:"L"},relativeTime:{future:"en %s",past:"fai %s",s:"uns segundo",m:"un minuto",mm:"%d minutos",h:"unha hora",hh:"%d horas",d:"un día",dd:"%d días",M:"un mes",MM:"%d meses",y:"un ano",yy:"%d anos"},ordinal:function(a){return"º"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("gl",a)}(),function(){var a=function(a){return a%100==11?!0:a%10==1?!1:!0},b=function(b,c,d,e){var f=b+" ";switch(d){case"s":return c||e?"nokkrar sekúndur":"nokkrum sekúndum";case"m":return c?"mínúta":"mínútu";case"mm":return a(b)?f+(c||e?"mínútur":"mínútum"):c?f+"mínúta":f+"mínútu";case"hh":return a(b)?f+(c||e?"klukkustundir":"klukkustundum"):f+"klukkustund";case"d":return c?"dagur":e?"dag":"degi";case"dd":return a(b)?c?f+"dagar":f+(e?"daga":"dögum"):c?f+"dagur":f+(e?"dag":"degi");case"M":return c?"mánuður":e?"mánuð":"mánuði";case"MM":return a(b)?c?f+"mánuðir":f+(e?"mánuði":"mánuðum"):c?f+"mánuður":f+(e?"mánuð":"mánuði");case"y":return c||e?"ár":"ári";case"yy":return a(b)?f+(c||e?"ár":"árum"):f+(c||e?"ár":"ári")}},c={months:"janúar_febrúar_mars_apríl_maí_júní_júlí_ágúst_september_október_nóvember_desember".split("_"),monthsShort:"jan_feb_mar_apr_maí_jún_júl_ágú_sep_okt_nóv_des".split("_"),weekdays:"sunnudagur_mánudagur_þriðjudagur_miðvikudagur_fimmtudagur_föstudagur_laugardagur".split("_"),weekdaysShort:"sun_mán_þri_mið_fim_fös_lau".split("_"),weekdaysMin:"Su_Má_Þr_Mi_Fi_Fö_La".split("_"),longDateFormat:{LT:"H:mm",L:"DD/MM/YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY kl. LT",LLLL:"dddd, D. MMMM YYYY kl. LT"},calendar:{sameDay:"[í dag kl.] LT",nextDay:"[á morgun kl.] LT",nextWeek:"dddd [kl.] LT",lastDay:"[í gær kl.] LT",lastWeek:"[síðasta] dddd [kl.] LT",sameElse:"L"},relativeTime:{future:"eftir %s",past:"fyrir %s síðan",s:b,m:b,mm:b,h:"klukkustund",hh:b,d:b,dd:b,M:b,MM:b,y:b,yy:b},ordinal:function(a){return"."}};typeof module!="undefined"&&(module.exports=c),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("is",c)}(),function(){var a={months:"Gennaio_Febbraio_Marzo_Aprile_Maggio_Giugno_Luglio_Agosto_Settebre_Ottobre_Novembre_Dicembre".split("_"),monthsShort:"Gen_Feb_Mar_Apr_Mag_Giu_Lug_Ago_Set_Ott_Nov_Dic".split("_"),weekdays:"Domenica_Lunedi_Martedi_Mercoledi_Giovedi_Venerdi_Sabato".split("_"),weekdaysShort:"Dom_Lun_Mar_Mer_Gio_Ven_Sab".split("_"),weekdaysMin:"D_L_Ma_Me_G_V_S".split("_"),longDateFormat:{LT:"HH:mm",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd, D MMMM YYYY LT"},calendar:{sameDay:"[Oggi alle] LT",nextDay:"[Domani alle] LT",nextWeek:"dddd [alle] LT",lastDay:"[Ieri alle] LT",lastWeek:"[lo scorso] dddd [alle] LT",sameElse:"L"},relativeTime:{future:"in %s",past:"%s fa",s:"secondi",m:"un minuto",mm:"%d minuti",h:"un ora",hh:"%d ore",d:"un giorno",dd:"%d giorni",M:"un mese",MM:"%d mesi",y:"un anno",yy:"%d anni"},ordinal:function(){return"º"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("it",a)}(),function(){var a={months:"1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"),monthsShort:"1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"),weekdays:"日曜日_月曜日_火曜日_水曜日_木曜日_金曜日_土曜日".split("_"),weekdaysShort:"日_月_火_水_木_金_土".split("_"),weekdaysMin:"日_月_火_水_木_金_土".split("_"),longDateFormat:{LT:"Ah:mm",L:"YYYY/MM/DD",LL:"YYYY年M月D日",LLL:"YYYY年M月D日 LT",LLLL:"YYYY年M月D日 dddd LT"},meridiem:function(a,b,c){return a<12?"午前":"午後"},calendar:{sameDay:"[今日] LT",nextDay:"[明日] LT",nextWeek:"[来週]dddd LT",lastDay:"[昨日] LT",lastWeek:"[前週]dddd LT",sameElse:"L"},relativeTime:{future:"%s後",past:"%s前",s:"数秒",m:"1分",mm:"%d分",h:"1時間",hh:"%d時間",d:"1日",dd:"%d日",M:"1ヶ月",MM:"%dヶ月",y:"1年",yy:"%d年"},ordinal:function(a){return""}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("jp",a)}(),function(){var a={months:"1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월".split("_"),monthsShort:"1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월".split("_"),weekdays:"일요일_월요일_화요일_수요일_목요일_금요일_토요일".split("_"),weekdaysShort:"일_월_화_수_목_금_토".split("_"),weekdaysMin:"일_월_화_수_목_금_토".split("_"),longDateFormat:{LT:"A h시 mm분",L:"YYYY.MM.DD",LL:"YYYY년 MMMM D일",LLL:"YYYY년 MMMM D일 LT",LLLL:"YYYY년 MMMM D일 dddd LT"},meridiem:function(a,b,c){return a<12?"오전":"오후"},calendar:{sameDay:"오늘 LT",nextDay:"내일 LT",nextWeek:"dddd LT",lastDay:"어제 LT",lastWeek:"지난주 dddd LT",sameElse:"L"},relativeTime:{future:"%s 후",past:"%s 전",s:"몇초",ss:"%d초",m:"일분",mm:"%d분",h:"한시간",hh:"%d시간",d:"하루",dd:"%d일",M:"한달",MM:"%d달",y:"일년",yy:"%d년"},ordinal:function(a){return"일"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("kr",a)}(),function(){var a={months:"januar_februar_mars_april_mai_juni_juli_august_september_oktober_november_desember".split("_"),monthsShort:"jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des".split("_"),weekdays:"søndag_mandag_tirsdag_onsdag_torsdag_fredag_lørdag".split("_"),weekdaysShort:"søn_man_tir_ons_tor_fre_lør".split("_"),weekdaysMin:"sø_ma_ti_on_to_fr_lø".split("_"),longDateFormat:{LT:"HH:mm",L:"YYYY-MM-DD",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd D MMMM YYYY LT"},calendar:{sameDay:"[I dag klokken] LT",nextDay:"[I morgen klokken] LT",nextWeek:"dddd [klokken] LT",lastDay:"[I går klokken] LT",lastWeek:"[Forrige] dddd [klokken] LT",sameElse:"L"},relativeTime:{future:"om %s",past:"for %s siden",s:"noen sekunder",m:"ett minutt",mm:"%d minutter",h:"en time",hh:"%d timer",d:"en dag",dd:"%d dager",M:"en måned",MM:"%d måneder",y:"ett år",yy:"%d år"},ordinal:function(a){return"."}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("nb",a)}(),function(){var a={months:"januari_februari_maart_april_mei_juni_juli_augustus_september_oktober_november_december".split("_"),monthsShort:"jan._feb._mar._apr._mei._jun._jul._aug._sep._okt._nov._dec.".split("_"),weekdays:"zondag_maandag_dinsdag_woensdag_donderdag_vrijdag_zaterdag".split("_"),weekdaysShort:"zo._ma._di._wo._do._vr._za.".split("_"),weekdaysMin:"Zo_Ma_Di_Wo_Do_Vr_Za".split("_"),longDateFormat:{LT:"HH:mm",L:"DD-MM-YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd D MMMM YYYY LT"},calendar:{sameDay:"[Vandaag om] LT",nextDay:"[Morgen om] LT",nextWeek:"dddd [om] LT",lastDay:"[Gisteren om] LT",lastWeek:"[afgelopen] dddd [om] LT",sameElse:"L"},relativeTime:{future:"over %s",past:"%s geleden",s:"een paar seconden",m:"één minuut",mm:"%d minuten",h:"één uur",hh:"%d uur",d:"één dag",dd:"%d dagen",M:"één maand",MM:"%d maanden",y:"één jaar",yy:"%d jaar"},ordinal:function(a){return a===1||a===8||a>=20?"ste":"de"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("nl",a)}(),function(){var a=function(a){return a%10<5&&a%10>1&&~~(a/10)!==1},b=function(b,c,d){var e=b+" ";switch(d){case"m":return c?"minuta":"minutę";case"mm":return e+(a(b)?"minuty":"minut");case"h":return c?"godzina":"godzinę";case"hh":return e+(a(b)?"godziny":"godzin");case"MM":return e+(a(b)?"miesiące":"miesięcy");case"yy":return e+(a(b)?"lata":"lat")}},c={months:"styczeń_luty_marzec_kwiecień_maj_czerwiec_lipiec_sierpień_wrzesień_październik_listopad_grudzień".split("_"),monthsShort:"sty_lut_mar_kwi_maj_cze_lip_sie_wrz_paź_lis_gru".split("_"),weekdays:"niedziela_poniedziałek_wtorek_środa_czwartek_piątek_sobota".split("_"),weekdaysShort:"nie_pon_wt_śr_czw_pt_sb".split("_"),weekdaysMin:"N_Pn_Wt_Śr_Cz_Pt_So".split("_"),longDateFormat:{LT:"HH:mm",L:"DD-MM-YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd, D MMMM YYYY LT"},calendar:{sameDay:"[Dziś o] LT",nextDay:"[Jutro o] LT",nextWeek:"[W] dddd [o] LT",lastDay:"[Wczoraj o] LT",lastWeek:"[W zeszły/łą] dddd [o] LT",sameElse:"L"},relativeTime:{future:"za %s",past:"%s temu",s:"kilka sekund",m:b,mm:b,h:b,hh:b,d:"1 dzień",dd:"%d dni",M:"miesiąc",MM:b,y:"rok",yy:b},ordinal:function(a){return"."}};typeof module!="undefined"&&(module.exports=c),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("pl",c)}(),function(){var a={months:"Janeiro_Fevereiro_Março_Abril_Maio_Junho_Julho_Agosto_Setembro_Outubro_Novembro_Dezembro".split("_"),monthsShort:"Jan_Fev_Mar_Abr_Mai_Jun_Jul_Ago_Set_Out_Nov_Dez".split("_"),weekdays:"Domingo_Segunda-feira_Terça-feira_Quarta-feira_Quinta-feira_Sexta-feira_Sábado".split("_"),weekdaysShort:"Dom_Seg_Ter_Qua_Qui_Sex_Sáb".split("_"),weekdaysMin:"Dom_2ª_3ª_4ª_5ª_6ª_Sáb".split("_"),longDateFormat:{LT:"HH:mm",L:"DD/MM/YYYY",LL:"D \\de MMMM \\de YYYY",LLL:"D \\de MMMM \\de YYYY LT",LLLL:"dddd, D \\de MMMM \\de YYYY LT"},calendar:{sameDay:"[Hoje às] LT",nextDay:"[Amanhã às] LT",nextWeek:"dddd [às] LT",lastDay:"[Ontem às] LT",lastWeek:function(){return this.day()===0||this.day()===6?"[Último] dddd [às] LT":"[Última] dddd [às] LT"},sameElse:"L"},relativeTime:{future:"em %s",past:"%s atrás",s:"segundos",m:"um minuto",mm:"%d minutos",h:"uma hora",hh:"%d horas",d:"um dia",dd:"%d dias",M:"um mês",MM:"%d meses",y:"um ano",yy:"%d anos"},ordinal:function(a){return"º"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("pt",a)}(),function(){var a=[function(a){return a%10===1&&a%100!==11},function(a){return a%10>=2&&a%10<=4&&a%10%1===0&&(a%100<12||a%100>14)},function(a){return a%10===0||a%10>=5&&a%10<=9&&a%10%1===0||a%100>=11&&a%100<=14&&a%100%1===0},function(a){return!0}],b=function(b,c){var d=b.split("_"),e=Math.min(a.length,d.length),f=-1;while(++f<e)if(a[f](c))return d[f];return d[e-1]},c=function(a,c,d){var e={mm:"минута_минуты_минут_минуты",hh:"час_часа_часов_часа",dd:"день_дня_дней_дня",MM:"месяц_месяца_месяцев_месяца",yy:"год_года_лет_года"};return d==="m"?c?"минута":"минуту":a+" "+b(e[d],+a)},d={months:"январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь".split("_"),monthsShort:"янв_фев_мар_апр_май_июн_июл_авг_сен_окт_ноя_дек".split("_"),weekdays:"воскресенье_понедельник_вторник_среда_четверг_пятница_суббота".split("_"),weekdaysShort:"вск_пнд_втр_срд_чтв_птн_суб".split("_"),weekdaysMin:"вс_пн_вт_ср_чт_пт_сб".split("_"),longDateFormat:{LT:"HH:mm",L:"DD-MM-YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd, D MMMM YYYY LT"},calendar:{sameDay:"[Сегодня в] LT",nextDay:"[Завтра в] LT",lastDay:"[Вчера в] LT",nextWeek:function(){return this.day()===2?"[Во] dddd [в] LT":"[В] dddd [в] LT"},lastWeek:function(){switch(this.day()){case 0:return"[В прошлое] dddd [в] LT";case 1:case 2:case 4:return"[В прошлый] dddd [в] LT";case 3:case 5:case 6:return"[В прошлую] dddd [в] LT"}},sameElse:"L"},relativeTime:{future:"через %s",past:"%s назад",s:"несколько секунд",m:c,mm:c,h:"час",hh:c,d:"день",dd:c,M:"месяц",MM:c,y:"год",yy:c},ordinal:function(a){return"."}};typeof module!="undefined"&&(module.exports=d),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("ru",d)}(),function(){var a={months:"januari_februari_mars_april_maj_juni_juli_augusti_september_oktober_november_december".split("_"),monthsShort:"jan_feb_mar_apr_maj_jun_jul_aug_sep_okt_nov_dec".split("_"),weekdays:"söndag_måndag_tisdag_onsdag_torsdag_fredag_lördag".split("_"),weekdaysShort:"sön_mån_tis_ons_tor_fre_lör".split("_"),weekdaysMin:"sö_må_ti_on_to_fr_lö".split("_"),longDateFormat:{LT:"HH:mm",L:"YYYY-MM-DD",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd D MMMM YYYY LT"},calendar:{sameDay:"[Idag klockan] LT",nextDay:"[Imorgon klockan] LT",lastDay:"[Igår klockan] LT",nextWeek:"dddd [klockan] LT",lastWeek:"[Förra] dddd[en klockan] LT",sameElse:"L"},relativeTime:{future:"om %s",past:"för %s sen",s:"några sekunder",m:"en minut",mm:"%d minuter",h:"en timme",hh:"%d timmar",d:"en dag",dd:"%d dagar",M:"en månad",MM:"%d månader",y:"ett år",yy:"%d år"},ordinal:function(a){var b=a%10;return~~(a%100/10)===1?"e":b===1?"a":b===2?"a":b===3?"e":"e"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("sv",a)}(),function(){var a={months:"Ocak_Şubat_Mart_Nisan_Mayıs_Haziran_Temmuz_Ağustos_Eylül_Ekim_Kasım_Aralık".split("_"),monthsShort:"Oca_Şub_Mar_Nis_May_Haz_Tem_Ağu_Eyl_Eki_Kas_Ara".split("_"),weekdays:"Pazar_Pazartesi_Salı_Çarşamba_Perşembe_Cuma_Cumartesi".split("_"),weekdaysShort:"Paz_Pts_Sal_Çar_Per_Cum_Cts".split("_"),weekdaysMin:"Pz_Pt_Sa_Ça_Pe_Cu_Ct".split("_"),longDateFormat:{LT:"HH:mm",L:"DD.MM.YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY LT",LLLL:"dddd, D MMMM YYYY LT"},calendar:{sameDay:"[bugün saat] LT",nextDay:"[yarın saat] LT",nextWeek:"[haftaya] dddd [saat] LT",lastDay:"[dün] LT",lastWeek:"[geçen hafta] dddd [saat] LT",sameElse:"L"},relativeTime:{future:"%s sonra",past:"%s önce",s:"birkaç saniye",m:"bir dakika",mm:"%d dakika",h:"bir saat",hh:"%d saat",d:"bir gün",dd:"%d gün",M:"bir ay",MM:"%d ay",y:"bir yıl",yy:"%d yıl"},ordinal:function(a){var b=a%10;return~~(a%100/10)===1?"th":b===1?"st":b===2?"nd":b===3?"rd":"th"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("tr",a)}(),function(){var a={months:"一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月".split("_"),monthsShort:"1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"),weekdays:"星期日_星期一_星期二_星期三_星期四_星期五_星期六".split("_"),weekdaysShort:"周日_周一_周二_周三_周四_周五_周六".split("_"),weekdaysMin:"日_一_二_三_四_五_六".split("_"),longDateFormat:{LT:"Ah点mm",L:"YYYY年MMMD日",LL:"YYYY年MMMD日",LLL:"YYYY年MMMD日LT",LLLL:"YYYY年MMMD日ddddLT"},meridiem:function(a,b,c){return a<9?"早上":a<11&&b<30?"上午":a<13&&b<30?"中午":a<18?"下午":"晚上"},calendar:{sameDay:"[今天]LT",nextDay:"[明天]LT",nextWeek:"[下]ddddLT",lastDay:"[昨天]LT",lastWeek:"[上]ddddLT",sameElse:"L"},relativeTime:{future:"%s内",past:"%s前",s:"几秒",m:"1分钟",mm:"%d分钟",h:"1小时",hh:"%d小时",d:"1天",dd:"%d天",M:"1个月",MM:"%d个月",y:"1年",yy:"%d年"},ordinal:function(a){return""}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("zh-cn",a)}(),function(){var a={months:"一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月".split("_"),monthsShort:"1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"),weekdays:"星期日_星期一_星期二_星期三_星期四_星期五_星期六".split("_"),weekdaysShort:"週日_週一_週二_週三_週四_週五_週六".split("_"),weekdaysMin:"日_一_二_三_四_五_六".split("_"),longDateFormat:{LT:"Ah點mm",L:"YYYY年MMMD日",LL:"YYYY年MMMD日",LLL:"YYYY年MMMD日LT",LLLL:"YYYY年MMMD日ddddLT"},meridiem:function(a,b,c){return a<9?"早上":a<11&&b<30?"上午":a<13&&b<30?"中午":a<18?"下午":"晚上"},calendar:{sameDay:"[今天]LT",nextDay:"[明天]LT",nextWeek:"[下]ddddLT",lastDay:"[昨天]LT",lastWeek:"[上]ddddLT",sameElse:"L"},relativeTime:{future:"%s內",past:"%s前",s:"幾秒",m:"一分鐘",mm:"%d分鐘",h:"一小時",hh:"%d小時",d:"一天",dd:"%d天",M:"一個月",MM:"%d個月",y:"一年",yy:"%d年"},ordinal:function(a){return""}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("zh-tw",a)}(); <ide>\ No newline at end of file <ide><path>min/lang/pt.js <ide> // moment.js language configuration <ide> // language : portuguese (pt) <ide> // author : Jefferson : https://github.com/jalex79 <del>(function(){var a={months:"Janeiro_Fevereiro_Março_Abril_Maio_Junho_Julho_Agosto_Setembro_Outubro_Novembro_Dezembro".split("_"),monthsShort:"Jan_Fev_Mar_Abr_Mai_Jun_Jul_Ago_Set_Out_Nov_Dez".split("_"),weekdays:"Domingo_Segunda-feira_Terça-feira_Quarta-feira_Quinta-feira_Sexta-feira_Sábado".split("_"),weekdaysShort:"Dom_Seg_Ter_Qua_Qui_Sex_Sáb".split("_"),weekdaysMin:"Dom_Seg_Ter_Qua_Qui_Sex_Sáb".split("_"),longDateFormat:{LT:"HH:mm",L:"DD/MM/YYYY",LL:"D \\de MMMM \\de YYYY",LLL:"D \\de MMMM \\de YYYY LT",LLLL:"dddd, D \\de MMMM \\de YYYY LT"},calendar:{sameDay:"[Hoje às] LT",nextDay:"[Amanhã às] LT",nextWeek:"dddd [às] LT",lastDay:"[Ontem às] LT",lastWeek:function(){return this.day()===0||this.day()===6?"[Último] dddd [às] LT":"[Última] dddd [às] LT"},sameElse:"L"},relativeTime:{future:"em %s",past:"%s atrás",s:"segundos",m:"um minuto",mm:"%d minutos",h:"uma hora",hh:"%d horas",d:"um dia",dd:"%d dias",M:"um mês",MM:"%d meses",y:"um ano",yy:"%d anos"},ordinal:function(a){return"º"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("pt",a)})(); <ide>\ No newline at end of file <add>(function(){var a={months:"Janeiro_Fevereiro_Março_Abril_Maio_Junho_Julho_Agosto_Setembro_Outubro_Novembro_Dezembro".split("_"),monthsShort:"Jan_Fev_Mar_Abr_Mai_Jun_Jul_Ago_Set_Out_Nov_Dez".split("_"),weekdays:"Domingo_Segunda-feira_Terça-feira_Quarta-feira_Quinta-feira_Sexta-feira_Sábado".split("_"),weekdaysShort:"Dom_Seg_Ter_Qua_Qui_Sex_Sáb".split("_"),weekdaysMin:"Dom_2ª_3ª_4ª_5ª_6ª_Sáb".split("_"),longDateFormat:{LT:"HH:mm",L:"DD/MM/YYYY",LL:"D \\de MMMM \\de YYYY",LLL:"D \\de MMMM \\de YYYY LT",LLLL:"dddd, D \\de MMMM \\de YYYY LT"},calendar:{sameDay:"[Hoje às] LT",nextDay:"[Amanhã às] LT",nextWeek:"dddd [às] LT",lastDay:"[Ontem às] LT",lastWeek:function(){return this.day()===0||this.day()===6?"[Último] dddd [às] LT":"[Última] dddd [às] LT"},sameElse:"L"},relativeTime:{future:"em %s",past:"%s atrás",s:"segundos",m:"um minuto",mm:"%d minutos",h:"uma hora",hh:"%d horas",d:"um dia",dd:"%d dias",M:"um mês",MM:"%d meses",y:"um ano",yy:"%d anos"},ordinal:function(a){return"º"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("pt",a)})(); <ide>\ No newline at end of file <ide><path>test/lang/pt.js <ide> exports["lang:pt"] = { <ide> "format week" : function(test) { <ide> test.expect(7); <ide> moment.lang('pt'); <del> var expected = 'Domingo Dom Dom_Segunda-feira Seg Seg_Terça-feira Ter Ter_Quarta-feira Qua Qua_Quinta-feira Qui Qui_Sexta-feira Sex Sex_Sábado Sáb Sáb'.split("_"); <add> var expected = 'Domingo Dom Dom_Segunda-feira Seg 2ª_Terça-feira Ter 3ª_Quarta-feira Qua 4ª_Quinta-feira Qui 5ª_Sexta-feira Sex 6ª_Sábado Sáb Sáb'.split("_"); <ide> var i; <ide> for (i = 0; i < expected.length; i++) { <ide> test.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]);
4
Text
Text
remove inaccurate docs
a023d0d057ca2dbc948585152363515df419d73e
<ide><path>docs/Performance.md <ide> but their receipt is not necessary for the scroll to occur). <ide> <ide> When running a bundled app, these statements can cause a big bottleneck in the JavaScript thread. This includes calls from debugging libraries such as [redux-logger](https://github.com/evgenyrodionov/redux-logger), so make sure to remove them before bundling. <ide> <del>> There is a [babel plugin](https://babeljs.io/docs/plugins/transform-remove-console/) that can remove all `console.*` calls. You need to install it first using `npm install babel-plugin-transform-remove-console --save`, and then edit (or create) `.babelrc` under your project directory like the following: <del>```json <del>{ <del> "env": { <del> "production": { <del> "plugins": ["transform-remove-console"] <del> } <del> } <del>} <del>``` <del>Then it will automatically remove all `console.*` calls in a release (production) version of your project. However, the `console.*` calls will still be executed in the debug version of your project. <del> <del> <ide> #### Development mode (dev=true) <ide> <ide> JavaScript thread performance suffers greatly when running in dev mode.
1
Text
Text
fix documentation of process.argv
475dc439e21dd257e75ffe5e5ba8a954618fb403
<ide><path>doc/api/process.md <ide> console.log(`This processor architecture is ${process.arch}`); <ide> added: v0.1.27 <ide> --> <ide> <del>The `process.argv` property returns a array containing the command line <add>The `process.argv` property returns an array containing the command line <ide> arguments passed when the Node.js process was launched. The first element will <del>be 'node', the second element will be the name of the JavaScript file. The <del>remaining elements will be any additional command line arguments. <add>be [`process.execPath`]. The second element will be the path to the <add>JavaScript file being executed. The remaining elements will be any additional <add>command line arguments. <ide> <ide> For example, assuming the following script for `process-args.js`: <ide> <ide> $ node process-2.js one two=three four <ide> Would generate the output: <ide> <ide> ```text <del>0: node <add>0: /usr/local/bin/node <ide> 1: /Users/mjr/work/node/process-2.js <ide> 2: one <ide> 3: two=three <ide> cases: <ide> [`process.argv`]: #process_process_argv <ide> [`process.exit()`]: #process_process_exit_code <ide> [`process.kill()`]: #process_process_kill_pid_signal <add>[`process.execPath`]: #process_process_execPath <ide> [`promise.catch()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch <ide> [`require.main`]: modules.html#modules_accessing_the_main_module <ide> [`setTimeout(fn, 0)`]: timers.html#timers_settimeout_callback_delay_arg
1
PHP
PHP
allow empty name for selectbox widget
c86a9aef4a4abdd9d2c163e5ded3a6da648f9935
<ide><path>src/View/Widget/SelectBoxWidget.php <ide> public function render(array $data, ContextInterface $context) <ide> 'val' => null, <ide> ]; <ide> <del> if (empty($data['name'])) { <del> throw new \RuntimeException('Cannot make inputs with empty name attributes.'); <del> } <ide> $options = $this->_renderContent($data); <ide> $name = $data['name']; <ide> unset($data['name'], $data['options'], $data['empty'], $data['val'], $data['escape']);
1
PHP
PHP
fix another typo in memcached engine comments
b8789cddaa990864cbcf8549d592bf4bd84e3db8
<ide><path>src/Cache/Engine/MemcachedEngine.php <ide> * control you have over expire times far in the future. See MemcachedEngine::write() for <ide> * more information. <ide> * <del> * Memcached engine support of binary protocol and igbinary <add> * Memcached engine support binary protocol and igbinary <ide> * serialization (if memcached extension compiled with --enable-igbinary). <del> * Compressed keys can also be incremented/decremented <add> * Compressed keys can also be incremented/decremented. <ide> */ <ide> class MemcachedEngine extends CacheEngine <ide> {
1
PHP
PHP
add lastoutput property
6b185832af11badaef1c47547db435a5124e0b88
<ide><path>src/Illuminate/Console/Application.php <ide> class Application extends SymfonyApplication implements ApplicationContract { <ide> */ <ide> protected $events; <ide> <add> /** <add> * The output from the previous command. <add> * <add> * @var \Symfony\Component\Console\Output\OutputInterface <add> */ <add> protected $lastOutput; <add> <ide> /** <ide> * Create a new Artisan console application. <ide> *
1
Python
Python
add scalar squeeze tests
a3c7204a311036e891ec0c3e1e0b09cf7a614354
<ide><path>numpy/core/tests/test_regression.py <ide> def test_structarray_title(self): <ide> structure = np.array([1], dtype=[(('x', 'X'), np.object_)]) <ide> structure[0]['x'] = np.array([2]) <ide> gc.collect() <add> <add> def test_dtype_scalar_squeeze(self): <add> # gh-11384 <add> values = { <add> 'S': b"a", <add> 'M': "2018-06-20", <add> } <add> for ch in np.typecodes['All']: <add> if ch in 'O': <add> continue <add> sctype = np.dtype(ch).type <add> scvalue = sctype(values.get(ch, 3)) <add> for axis in [None, ()]: <add> squeezed = scvalue.squeeze(axis=axis) <add> assert_equal(squeezed, scvalue) <add> assert_equal(type(squeezed), type(scvalue))
1
Python
Python
fix cyclic imports
ce589d896eb02597b2b13f05024ff3e4c01dfc82
<ide><path>airflow/settings.py <ide> import logging <ide> import os <ide> import sys <del>from typing import TYPE_CHECKING, Optional <add>from typing import Optional <ide> <ide> import pendulum <ide> from sqlalchemy import create_engine, exc <ide> # pylint: disable=unused-import <ide> from airflow.configuration import AIRFLOW_HOME, WEBSERVER_CONFIG, conf # NOQA F401 <ide> from airflow.logging_config import configure_logging <del>from airflow.utils.sqlalchemy import setup_event_handlers <del> <del>if TYPE_CHECKING: <del> from airflow.models.baseoperator import BaseOperator <del> from airflow.models.taskinstance import TaskInstance <del> <add>from airflow.utils.orm_event_handlers import setup_event_handlers <ide> <ide> log = logging.getLogger(__name__) <ide> <ide> json = json # pylint: disable=self-assigning-variable <ide> <ide> <del>def policy(task: 'BaseOperator'): # pylint: disable=unused-argument <add>def policy(task): # pylint: disable=unused-argument <ide> """ <ide> This policy setting allows altering tasks after they are loaded in <ide> the DagBag. It allows administrator to rewire some task parameters. <ide> def policy(task: 'BaseOperator'): # pylint: disable=unused-argument <ide> """ <ide> <ide> <del>def task_instance_mutation_hook(task_instance: 'TaskInstance'): # pylint: disable=unused-argument <add>def task_instance_mutation_hook(task_instance): # pylint: disable=unused-argument <ide> """ <ide> This setting allows altering task instances before they are queued by <ide> the Airflow scheduler. <ide> def import_local_settings(): <ide> import airflow_local_settings <ide> <ide> if hasattr(airflow_local_settings, "__all__"): <del> for i in airflow_local_settings.__all__: <add> for i in airflow_local_settings.__all__: # pylint: disable=no-member <ide> globals()[i] = getattr(airflow_local_settings, i) <ide> else: <ide> for k, v in airflow_local_settings.__dict__.items(): <ide><path>airflow/utils/orm_event_handlers.py <add># <add># Licensed to the Apache Software Foundation (ASF) under one <add># or more contributor license agreements. See the NOTICE file <add># distributed with this work for additional information <add># regarding copyright ownership. The ASF licenses this file <add># to you under the Apache License, Version 2.0 (the <add># "License"); you may not use this file except in compliance <add># 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, <add># software distributed under the License is distributed on an <add># "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY <add># KIND, either express or implied. See the License for the <add># specific language governing permissions and limitations <add># under the License. <add> <add>import logging <add>import os <add>import time <add>import traceback <add> <add>from sqlalchemy import event, exc <add> <add>from airflow.configuration import conf <add> <add>log = logging.getLogger(__name__) <add> <add> <add>def setup_event_handlers(engine): <add> """ <add> Setups event handlers. <add> """ <add> # pylint: disable=unused-argument <add> @event.listens_for(engine, "connect") <add> def connect(dbapi_connection, connection_record): <add> connection_record.info['pid'] = os.getpid() <add> <add> if engine.dialect.name == "sqlite": <add> @event.listens_for(engine, "connect") <add> def set_sqlite_pragma(dbapi_connection, connection_record): <add> cursor = dbapi_connection.cursor() <add> cursor.execute("PRAGMA foreign_keys=ON") <add> cursor.close() <add> <add> # this ensures sanity in mysql when storing datetimes (not required for postgres) <add> if engine.dialect.name == "mysql": <add> @event.listens_for(engine, "connect") <add> def set_mysql_timezone(dbapi_connection, connection_record): <add> cursor = dbapi_connection.cursor() <add> cursor.execute("SET time_zone = '+00:00'") <add> cursor.close() <add> <add> @event.listens_for(engine, "checkout") <add> def checkout(dbapi_connection, connection_record, connection_proxy): <add> pid = os.getpid() <add> if connection_record.info['pid'] != pid: <add> connection_record.connection = connection_proxy.connection = None <add> raise exc.DisconnectionError( <add> "Connection record belongs to pid {}, " <add> "attempting to check out in pid {}".format(connection_record.info['pid'], pid) <add> ) <add> if conf.getboolean('debug', 'sqlalchemy_stats', fallback=False): <add> @event.listens_for(engine, "before_cursor_execute") <add> def before_cursor_execute(conn, cursor, statement, parameters, context, executemany): <add> conn.info.setdefault('query_start_time', []).append(time.time()) <add> <add> @event.listens_for(engine, "after_cursor_execute") <add> def after_cursor_execute(conn, cursor, statement, parameters, context, executemany): <add> total = time.time() - conn.info['query_start_time'].pop() <add> file_name = [ <add> f"'{f.name}':{f.filename}:{f.lineno}" for f <add> in traceback.extract_stack() if 'sqlalchemy' not in f.filename][-1] <add> stack = [f for f in traceback.extract_stack() if 'sqlalchemy' not in f.filename] <add> stack_info = ">".join([f"{f.filename.rpartition('/')[-1]}:{f.name}" for f in stack][-3:]) <add> conn.info.setdefault('query_start_time', []).append(time.monotonic()) <add> log.info("@SQLALCHEMY %s |$ %s |$ %s |$ %s ", <add> total, file_name, stack_info, statement.replace("\n", " ") <add> ) <ide><path>airflow/utils/sqlalchemy.py <ide> import datetime <ide> import json <ide> import logging <del>import os <del>import time <del>import traceback <ide> <ide> import pendulum <ide> from dateutil import relativedelta <del>from sqlalchemy import event, exc <ide> from sqlalchemy.types import DateTime, Text, TypeDecorator <ide> <ide> from airflow.configuration import conf <ide> using_mysql = conf.get('core', 'sql_alchemy_conn').lower().startswith('mysql') <ide> <ide> <del>def setup_event_handlers(engine): <del> """ <del> Setups event handlers. <del> """ <del> # pylint: disable=unused-argument <del> @event.listens_for(engine, "connect") <del> def connect(dbapi_connection, connection_record): <del> connection_record.info['pid'] = os.getpid() <del> <del> if engine.dialect.name == "sqlite": <del> @event.listens_for(engine, "connect") <del> def set_sqlite_pragma(dbapi_connection, connection_record): <del> cursor = dbapi_connection.cursor() <del> cursor.execute("PRAGMA foreign_keys=ON") <del> cursor.close() <del> <del> # this ensures sanity in mysql when storing datetimes (not required for postgres) <del> if engine.dialect.name == "mysql": <del> @event.listens_for(engine, "connect") <del> def set_mysql_timezone(dbapi_connection, connection_record): <del> cursor = dbapi_connection.cursor() <del> cursor.execute("SET time_zone = '+00:00'") <del> cursor.close() <del> <del> @event.listens_for(engine, "checkout") <del> def checkout(dbapi_connection, connection_record, connection_proxy): <del> pid = os.getpid() <del> if connection_record.info['pid'] != pid: <del> connection_record.connection = connection_proxy.connection = None <del> raise exc.DisconnectionError( <del> "Connection record belongs to pid {}, " <del> "attempting to check out in pid {}".format(connection_record.info['pid'], pid) <del> ) <del> if conf.getboolean('debug', 'sqlalchemy_stats', fallback=False): <del> @event.listens_for(engine, "before_cursor_execute") <del> def before_cursor_execute(conn, cursor, statement, parameters, context, executemany): <del> conn.info.setdefault('query_start_time', []).append(time.time()) <del> <del> @event.listens_for(engine, "after_cursor_execute") <del> def after_cursor_execute(conn, cursor, statement, parameters, context, executemany): <del> total = time.time() - conn.info['query_start_time'].pop() <del> file_name = [ <del> f"'{f.name}':{f.filename}:{f.lineno}" for f <del> in traceback.extract_stack() if 'sqlalchemy' not in f.filename][-1] <del> stack = [f for f in traceback.extract_stack() if 'sqlalchemy' not in f.filename] <del> stack_info = ">".join([f"{f.filename.rpartition('/')[-1]}:{f.name}" for f in stack][-3:]) <del> conn.info.setdefault('query_start_time', []).append(time.monotonic()) <del> log.info("@SQLALCHEMY %s |$ %s |$ %s |$ %s ", <del> total, file_name, stack_info, statement.replace("\n", " ") <del> ) <del> <ide> # pylint: enable=unused-argument <del> <del> <ide> class UtcDateTime(TypeDecorator): <ide> """ <ide> Almost equivalent to :class:`~sqlalchemy.types.DateTime` with
3
Python
Python
add cli registry
b470062153e52983b1aca661cd2c96c6f38e88d4
<ide><path>spacy/cli/_util.py <ide> from configparser import InterpolationError <ide> <ide> from ..schemas import ProjectConfigSchema, validate <del>from ..util import import_file, run_command, make_tempdir <add>from ..util import import_file, run_command, make_tempdir, registry <ide> <ide> if TYPE_CHECKING: <ide> from pathy import Pathy # noqa: F401 <ide> <ide> <ide> def setup_cli() -> None: <add> # Make sure the entry-point for CLI runs, so that they get imported. <add> registry.cli.get_all() <ide> # Ensure that the help messages always display the correct prompt <ide> command = get_command(app) <ide> command(prog_name=COMMAND) <ide><path>spacy/util.py <ide> class registry(thinc.registry): <ide> # environment. spaCy models packaged with `spacy package` will "advertise" <ide> # themselves via entry points. <ide> models = catalogue.create("spacy", "models", entry_points=True) <add> cli = catalogue.create("spacy", "cli", entry_points=True) <ide> <ide> <ide> class SimpleFrozenDict(dict):
2
Java
Java
add callback for connection/disconnection to metro
3d5dc872a4eefa1557554b3b338227959d166370
<ide><path>ReactAndroid/src/main/java/com/facebook/react/devsupport/DevServerHelper.java <ide> import com.facebook.react.packagerconnection.FileIoHandler; <ide> import com.facebook.react.packagerconnection.JSPackagerClient; <ide> import com.facebook.react.packagerconnection.NotificationOnlyHandler; <add>import com.facebook.react.packagerconnection.ReconnectingWebSocket.ConnectionCallback; <ide> import com.facebook.react.packagerconnection.RequestHandler; <ide> import com.facebook.react.packagerconnection.RequestOnlyHandler; <ide> import com.facebook.react.packagerconnection.Responder; <ide> public interface OnServerContentChangeListener { <ide> } <ide> <ide> public interface PackagerCommandListener { <add> void onPackagerConnected(); <add> void onPackagerDisconnected(); <ide> void onPackagerReloadCommand(); <ide> void onPackagerDevMenuCommand(); <ide> void onCaptureHeapCommand(final Responder responder); <ide> public void onRequest(@Nullable Object params, Responder responder) { <ide> }); <ide> handlers.putAll(new FileIoHandler().handlers()); <ide> <add> ConnectionCallback onPackagerConnectedCallback = <add> new ConnectionCallback() { <add> @Override <add> public void onConnected() { <add> commandListener.onPackagerConnected(); <add> } <add> <add> @Override <add> public void onDisconnected() { <add> commandListener.onPackagerDisconnected(); <add> } <add> }; <add> <ide> mPackagerClient = new JSPackagerClient( <ide> clientId, <ide> mSettings.getPackagerConnectionSettings(), <del> handlers); <add> handlers, <add> onPackagerConnectedCallback); <ide> mPackagerClient.init(); <ide> <ide> return null; <ide><path>ReactAndroid/src/main/java/com/facebook/react/devsupport/DevSupportManagerImpl.java <ide> public void isPackagerRunning(PackagerStatusCallback callback) { <ide> return mLastErrorStack; <ide> } <ide> <add> @Override <add> public void onPackagerConnected() { <add> // No-op <add> } <add> <add> @Override <add> public void onPackagerDisconnected() { <add> // No-op <add> } <add> <ide> @Override <ide> public void onPackagerReloadCommand() { <ide> // Disable debugger to resume the JsVM & avoid thread locks while reloading <ide><path>ReactAndroid/src/main/java/com/facebook/react/packagerconnection/JSPackagerClient.java <ide> package com.facebook.react.packagerconnection; <ide> <ide> import java.util.Map; <add>import javax.annotation.Nullable; <ide> <ide> import android.net.Uri; <ide> <ide> public void error(Object error) { <ide> private Map<String, RequestHandler> mRequestHandlers; <ide> <ide> public JSPackagerClient(String clientId, PackagerConnectionSettings settings, Map<String, RequestHandler> requestHandlers) { <add> this(clientId, settings, requestHandlers, null); <add> } <add> <add> public JSPackagerClient( <add> String clientId, PackagerConnectionSettings settings, <add> Map<String, RequestHandler> requestHandlers, <add> @Nullable ReconnectingWebSocket.ConnectionCallback connectionCallback) { <ide> super(); <ide> <ide> Uri.Builder builder = new Uri.Builder(); <ide> public JSPackagerClient(String clientId, PackagerConnectionSettings settings, Ma <ide> .appendQueryParameter("clientid", clientId); <ide> String url = builder.build().toString(); <ide> <del> mWebSocket = new ReconnectingWebSocket(url, this, null); <add> mWebSocket = new ReconnectingWebSocket(url, this, connectionCallback); <ide> mRequestHandlers = requestHandlers; <ide> } <ide> <ide><path>ReactAndroid/src/test/java/com/facebook/react/packagerconnection/JSPackagerClientTest.java <ide> <ide> package com.facebook.react.packagerconnection; <ide> <add>import com.facebook.react.packagerconnection.ReconnectingWebSocket.ConnectionCallback; <add> <ide> import org.junit.Before; <ide> import org.junit.Test; <ide> import org.junit.runner.RunWith; <ide> public void test_onMessage_WrongVersion_ShouldNotTriggerCallback() throws IOExce <ide> verify(handler, never()).onNotification(any()); <ide> verify(handler, never()).onRequest(any(), any(Responder.class)); <ide> } <add> <add> @Test <add> public void test_onDisconnection_ShouldTriggerDisconnectionCallback() throws IOException { <add> ConnectionCallback connectionHandler = mock(ConnectionCallback.class); <add> RequestHandler handler = mock(RequestHandler.class); <add> final JSPackagerClient client = <add> new JSPackagerClient("test_client", mSettings, new HashMap<String,RequestHandler>(), connectionHandler); <add> <add> client.close(); <add> <add> verify(connectionHandler, never()).onConnected(); <add> verify(connectionHandler, times(1)).onDisconnected(); <add> <add> verify(handler, never()).onNotification(any()); <add> verify(handler, never()).onRequest(any(), any(Responder.class)); <add> } <ide> }
4
Go
Go
fix the create api when fromsrc has a bad url
e050f1760dd8a3d48d95bb3d2de503fc4177ff5f
<ide><path>daemon/import.go <ide> import ( <ide> "net/http" <ide> "net/url" <ide> "runtime" <add> "strings" <ide> "time" <ide> <ide> "github.com/docker/distribution/reference" <ide> func (daemon *Daemon) ImportImage(src string, repository, tag string, msg string <ide> rc = inConfig <ide> } else { <ide> inConfig.Close() <add> if len(strings.Split(src, "://")) == 1 { <add> src = "http://" + src <add> } <ide> u, err := url.Parse(src) <ide> if err != nil { <ide> return err <ide> } <del> if u.Scheme == "" { <del> u.Scheme = "http" <del> u.Host = src <del> u.Path = "" <del> } <del> outStream.Write(sf.FormatStatus("", "Downloading from %s", u)) <add> <ide> resp, err = httputils.Download(u.String()) <ide> if err != nil { <ide> return err <ide> } <add> outStream.Write(sf.FormatStatus("", "Downloading from %s", u)) <ide> progressOutput := sf.NewProgressOutput(outStream, true) <ide> rc = progress.NewProgressReader(resp.Body, progressOutput, resp.ContentLength, "", "Importing") <ide> } <ide><path>integration-cli/docker_api_images_test.go <ide> func (s *DockerSuite) TestAPIImagesHistory(c *check.C) { <ide> c.Assert(historydata[0].Tags[0], checker.Equals, "test-api-images-history:latest") <ide> } <ide> <add>func (s *DockerSuite) TestAPIImagesImportBadSrc(c *check.C) { <add> testRequires(c, Network) <add> <add> tt := []struct { <add> statusExp int <add> fromSrc string <add> }{ <add> {http.StatusNotFound, "http://example.com/nofile.tar"}, <add> {http.StatusNotFound, "example.com/nofile.tar"}, <add> {http.StatusNotFound, "example.com%2Fdata%2Ffile.tar"}, <add> {http.StatusInternalServerError, "%2Fdata%2Ffile.tar"}, <add> } <add> <add> for _, te := range tt { <add> res, b, err := request.SockRequestRaw("POST", strings.Join([]string{"/images/create?fromSrc=", te.fromSrc}, ""), nil, "application/json", daemonHost()) <add> c.Assert(err, check.IsNil) <add> b.Close() <add> c.Assert(res.StatusCode, checker.Equals, te.statusExp) <add> c.Assert(res.Header.Get("Content-Type"), checker.Equals, "application/json") <add> } <add> <add>} <add> <ide> // #14846 <ide> func (s *DockerSuite) TestAPIImagesSearchJSONContentType(c *check.C) { <ide> testRequires(c, Network)
2
Text
Text
optimize description for feature highlights
dde0f86a88989c02256a8b301ff8388752d88eed
<ide><path>docs/swarm/index.md <ide> a swarm. <ide> * **Decentralized design:** Instead of handling differentiation between node <ide> roles at deployment time, the Docker Engine handles any specialization at <ide> runtime. You can deploy both kinds of nodes, managers and workers, using the <del>Docker Engine. This means you can build an entire Swarm from a single disk <add>Docker Engine. This means you can build an entire swarm from a single disk <ide> image. <ide> <ide> * **Declarative service model:** Docker Engine uses a declarative approach to <ide> adding or removing tasks to maintain the desired state. <ide> the cluster state and reconciles any differences between the actual state your <ide> expressed desired state. For example, if you set up a service to run 10 <ide> replicas of a container, and a worker machine hosting two of those replicas <del>crashes, the manager will create two new replicas to replace the ones that <add>crashes, the manager will create two new replicas to replace the replicas that <ide> crashed. The swarm manager assigns the new replicas to workers that are <ide> running and available. <ide>
1
PHP
PHP
add phar to list
2d1f76ab752ced011da05cf139799eab2a36ef90
<ide><path>src/Illuminate/Validation/Concerns/ValidatesAttributes.php <ide> protected function shouldBlockPhpUpload($value, $parameters) <ide> } <ide> <ide> $phpExtensions = [ <del> 'php', 'php3', 'php4', 'php5', 'phtml', <add> 'php', 'php3', 'php4', 'php5', 'phtml', 'phar' <ide> ]; <ide> <ide> return ($value instanceof UploadedFile)
1
Text
Text
add iansu to collaborators
9237280559b3296e6ae8baef8eaa0dc16aafc3c3
<ide><path>README.md <ide> For information about the governance of the Node.js project, see <ide> **Zeyu Yang** &lt;himself65@outlook.com&gt; (he/him) <ide> * [hiroppy](https://github.com/hiroppy) - <ide> **Yuta Hiroto** &lt;hello@hiroppy.me&gt; (he/him) <add>* [iansu](https://github.com/iansu) - <add>**Ian Sutherland** &lt;ian@iansutherland.ca&gt; <ide> * [indutny](https://github.com/indutny) - <ide> **Fedor Indutny** &lt;fedor.indutny@gmail.com&gt; <ide> * [JacksonTian](https://github.com/JacksonTian) -
1
PHP
PHP
add reference links to docblock
31c7b01c3a7b5af29cbffe3e587c7a91b5217bab
<ide><path>lib/Cake/I18n/I18n.php <ide> public static function domains() { <ide> * @param string $header Type <ide> * @param int $n Number <ide> * @return int plural match <del> * @see <add> * @link http://localization-guide.readthedocs.org/en/latest/l10n/pluralforms.html <add> * @link https://developer.mozilla.org/en-US/docs/Mozilla/Localization/Localization_and_Plurals#List_of_Plural_Rules <ide> */ <ide> protected function _pluralGuess($header, $n) { <ide> if (!is_string($header) || $header === "nplurals=1;plural=0;" || !isset($header[0])) {
1
Mixed
Javascript
fix non selectable text in flatlist
c360b1d92b69e1d298b390ec88c4d29c1023945a
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextView.java <ide> public class ReactTextView extends AppCompatTextView implements ReactCompoundVie <ide> private boolean mAdjustsFontSizeToFit = false; <ide> private int mLinkifyMaskType = 0; <ide> private boolean mNotifyOnInlineViewLayout; <add> private boolean mTextIsSelectable = false; <ide> <ide> private ReactViewBackgroundManager mReactBackgroundManager; <ide> private Spannable mSpanned; <ide> public void onStartTemporaryDetach() { <ide> } <ide> } <ide> <add> @Override <add> public void setTextIsSelectable(boolean selectable) { <add> mTextIsSelectable = selectable; <add> super.setTextIsSelectable(selectable); <add> } <add> <ide> @Override <ide> public void onAttachedToWindow() { <ide> super.onAttachedToWindow(); <add> setTextIsSelectable(mTextIsSelectable); <ide> if (mContainsImages && getText() instanceof Spanned) { <ide> Spanned text = (Spanned) getText(); <ide> TextInlineImageSpan[] spans = text.getSpans(0, text.length(), TextInlineImageSpan.class); <ide><path>packages/rn-tester/js/components/ListExampleShared.js <ide> class ItemComponent extends React.PureComponent<{ <ide> onPress: (key: string) => void, <ide> onShowUnderlay?: () => void, <ide> onHideUnderlay?: () => void, <add> textSelectable?: ?boolean, <ide> ... <ide> }> { <ide> _onPress = () => { <ide> this.props.onPress(this.props.item.key); <ide> }; <ide> render(): React.Node { <del> const {fixedHeight, horizontal, item} = this.props; <add> const {fixedHeight, horizontal, item, textSelectable} = this.props; <ide> const itemHash = Math.abs(hashCode(item.title)); <ide> const imgSource = THUMB_URLS[itemHash % THUMB_URLS.length]; <ide> return ( <ide> class ItemComponent extends React.PureComponent<{ <ide> {!item.noImage && <Image style={styles.thumb} source={imgSource} />} <ide> <Text <ide> style={styles.text} <add> selectable={textSelectable} <ide> numberOfLines={horizontal || fixedHeight ? 3 : undefined}> <ide> {item.title} - {item.text} <ide> </Text> <ide><path>packages/rn-tester/js/examples/FlatList/FlatListExample.js <ide> type State = {| <ide> empty: boolean, <ide> useFlatListItemComponent: boolean, <ide> fadingEdgeLength: number, <add> onPressDisabled: boolean, <add> textSelectable: boolean, <ide> |}; <ide> <ide> class FlatListExample extends React.PureComponent<Props, State> { <ide> class FlatListExample extends React.PureComponent<Props, State> { <ide> empty: false, <ide> useFlatListItemComponent: false, <ide> fadingEdgeLength: 0, <add> onPressDisabled: false, <add> textSelectable: true, <ide> }; <ide> <ide> _onChangeFilterText = filterText => { <ide> class FlatListExample extends React.PureComponent<Props, State> { <ide> this.state.debug, <ide> this._setBooleanValue('debug'), <ide> )} <add> {renderSmallSwitchOption( <add> 'onPress Disabled', <add> this.state.onPressDisabled, <add> this._setBooleanValue('onPressDisabled'), <add> )} <add> {renderSmallSwitchOption( <add> 'Text Selectable', <add> this.state.textSelectable, <add> this._setBooleanValue('textSelectable'), <add> )} <ide> {renderSmallSwitchOption( <ide> 'Use FlatListItemComponent', <ide> this.state.useFlatListItemComponent, <ide> class FlatListExample extends React.PureComponent<Props, State> { <ide> data: state.data.concat(genItemData(100, state.data.length)), <ide> })); <ide> }; <add> _onPressCallback = () => { <add> const {onPressDisabled} = this.state; <add> const warning = () => console.log('onPress disabled'); <add> const onPressAction = onPressDisabled ? warning : this._pressItem; <add> return onPressAction; <add> }; <ide> _onRefresh = () => Alert.alert('onRefresh: nothing to refresh :P'); <ide> _renderItemComponent = () => { <ide> const flatListPropKey = this.state.useFlatListItemComponent <ide> class FlatListExample extends React.PureComponent<Props, State> { <ide> item={item} <ide> horizontal={this.state.horizontal} <ide> fixedHeight={this.state.fixedHeight} <del> onPress={this._pressItem} <add> onPress={this._onPressCallback()} <ide> onShowUnderlay={separators.highlight} <ide> onHideUnderlay={separators.unhighlight} <add> textSelectable={this.state.textSelectable} <ide> /> <ide> ); <ide> },
3
Text
Text
fix code block fences and typo
08fe24c2d5ef415d2b94f8e3f28d0299db2d7b6a
<ide><path>docs/extend/index.md <ide> Hub or on a private registry. <ide> <ide> You install the plugin using a single command: `docker plugin install <PLUGIN>`. <ide> The `plugin install` command pulls the plugin from the Docker Hub or private <del>registry. If necessary the CLI prompts you to accept any privilige requriements. <add>registry. If necessary the CLI prompts you to accept any privilege requriements. <ide> For example the plugin may require access to a device on the host system. <ide> Finally it enables the plugin. <ide> <ide> to create a volume. <ide> The plugin requests 2 privileges, the `CAP_SYS_ADMIN` capability to be able <ide> to do mount inside the plugin and `host networking`. <ide> <del>2. Check for a value of `true` the `ENABLED` column to verify the plugin <add>2. Check for a value of `true` the `ENABLED` column to verify the plugin <ide> started without error. <ide> <ide> ```bash <ide> started without error. <ide> vieux/sshfs latest true <ide> ``` <ide> <del>3. Create a volume using the plugin. <add>3. Create a volume using the plugin. <ide> <ide> ```bash <ide> $ docker volume create \ <ide> started without error. <ide> <content of /remote on machine 1.2.3.4> <ide> ``` <ide> <del>5. Verify the plugin successfully created the volume. <add>5. Verify the plugin successfully created the volume. <ide> <ide> ```bash <ide> $ docker volume ls <ide><path>docs/extend/plugin_api.md <ide> ExecStart=/usr/lib/docker/your-plugin <ide> WantedBy=multi-user.target <ide> ``` <ide> The `socket` file (for example `/lib/systemd/system/your-plugin.socket`): <add> <ide> ``` <ide> [Unit] <ide> Description=Your plugin
2
Text
Text
add shallow nesting to the routing guide
2610797d08c2d356e5a2e33f0d3bf6864adeddfc
<ide><path>guides/source/routing.md <ide> The corresponding route helper would be `publisher_magazine_photo_url`, requirin <ide> <ide> TIP: _Resources should never be nested more than 1 level deep._ <ide> <add>#### Shallow Nesting <add> <add>One way to avoid deep nesting (as recommended above) is to generate the collection actions scoped under the parent, so as to get a sense of the hierarchy, but to not nest the member actions. In other words, to only build routes with the minimal amount of information to uniquely identify the resource, like this: <add> <add>```ruby <add>resources :posts do <add> resources :comments, only: [:index, :new, :create] <add>end <add>resources :comments, only: [:show, :edit, :update, :destroy] <add>``` <add> <add>This idea strikes a balance between descriptive routes and deep nesting. There exists shorthand syntax to achieve just that, via the `:shallow` option: <add> <add>```ruby <add>resources :posts do <add> resources :comments, shallow: true <add>end <add>``` <add> <add>This will generate the exact same routes as the first example. You can also specify the `:shallow` option in the parent resource, in which case all of the nested resources will be shallow: <add> <add>```ruby <add>resources :posts, shallow: true do <add> resources :comments <add> resources :quotes <add> resources :drafts <add>end <add>``` <add> <add>The `shallow` method of the DSL creates a scope inside of which every nesting is shallow. This generates the same routes as the previous example: <add> <add>```ruby <add>shallow do <add> resources :posts do <add> resources :comments <add> resources :quotes <add> resources :drafts <add> end <add>end <add>``` <add> <add>There exists two options for `scope` to customize shallow routes. `:shallow_path` prefixes member paths with the specified parameter: <add> <add>```ruby <add>scope shallow_path: "sekret" do <add> resources :posts do <add> resources :comments, shallow: true <add> end <add>end <add>``` <add> <add>The comments resource here will have the following routes generated for it: <add> <add>| HTTP Verb | Path | Named Helper | <add>| --------- | -------------------------------------- | ------------------- | <add>| GET | /posts/:post_id/comments(.:format) | post_comments | <add>| POST | /posts/:post_id/comments(.:format) | post_comments | <add>| GET | /posts/:post_id/comments/new(.:format) | new_post_comment | <add>| GET | /sekret/comments/:id/edit(.:format) | edit_comment | <add>| GET | /sekret/comments/:id(.:format) | comment | <add>| PATCH/PUT | /sekret/comments/:id(.:format) | comment | <add>| DELETE | /sekret/comments/:id(.:format) | comment | <add> <add>The `:shallow_prefix` option adds the specified parameter to the named helpers: <add> <add>```ruby <add>scope shallow_prefix: "sekret" do <add> resources :posts do <add> resources :comments, shallow: true <add> end <add>end <add>``` <add> <add>The comments resource here will have the following routes generated for it: <add> <add>| HTTP Verb | Path | Named Helper | <add>| --------- | -------------------------------------- | ------------------- | <add>| GET | /posts/:post_id/comments(.:format) | post_comments | <add>| POST | /posts/:post_id/comments(.:format) | post_comments | <add>| GET | /posts/:post_id/comments/new(.:format) | new_post_comment | <add>| GET | /comments/:id/edit(.:format) | edit_sekret_comment | <add>| GET | /comments/:id(.:format) | sekret_comment | <add>| PATCH/PUT | /comments/:id(.:format) | sekret_comment | <add>| DELETE | /comments/:id(.:format) | sekret_comment | <add> <ide> ### Routing concerns <ide> <ide> Routing Concerns allows you to declare common routes that can be reused inside others resources and routes.
1
Python
Python
add test for cudnn rnns + bidirectional
a8a59c71eccb0bea3ef17feeed6970112ab4aa8e
<ide><path>tests/keras/layers/cudnn_recurrent_test.py <ide> def test_load_weights_into_noncudnn_lstm(): <ide> assert_allclose(out, cudnn_out, atol=1e-4) <ide> <ide> <add>@keras_test <add>@pytest.mark.skipif((keras.backend.backend() != 'tensorflow'), <add> reason='Requires TensorFlow backend') <add>@pytest.mark.skipif(not keras.backend.tensorflow_backend._get_available_gpus(), <add> reason='Requires GPU') <add>def test_cudnnrnn_bidirectional(): <add> rnn = keras.layers.CuDNNGRU <add> samples = 2 <add> dim = 2 <add> timesteps = 2 <add> output_dim = 2 <add> dropout_rate = 0.2 <add> mode = 'concat' <add> <add> x = np.random.random((samples, timesteps, dim)) <add> target_dim = 2 * output_dim if mode == 'concat' else output_dim <add> y = np.random.random((samples, target_dim)) <add> <add> # test with Sequential model <add> model = Sequential() <add> model.add(wrappers.Bidirectional(rnn(output_dim, dropout=dropout_rate, <add> recurrent_dropout=dropout_rate), <add> merge_mode=mode, <add> input_shape=(None, dim))) <add> model.compile(loss='mse', optimizer='sgd') <add> model.fit(x, y, epochs=1, batch_size=1) <add> <add> # test config <add> model.get_config() <add> model = model_from_json(model.to_json()) <add> model.summary() <add> <add> # test stacked bidirectional layers <add> model = Sequential() <add> model.add(wrappers.Bidirectional(rnn(output_dim, <add> return_sequences=True), <add> merge_mode=mode, <add> input_shape=(None, dim))) <add> model.add(wrappers.Bidirectional(rnn(output_dim), merge_mode=mode)) <add> model.compile(loss='mse', optimizer='sgd') <add> model.fit(x, y, epochs=1, batch_size=1) <add> <add> # test with functional API <add> inputs = Input((timesteps, dim)) <add> outputs = wrappers.Bidirectional(rnn(output_dim, dropout=dropout_rate, <add> recurrent_dropout=dropout_rate), <add> merge_mode=mode)(inputs) <add> model = Model(inputs, outputs) <add> model.compile(loss='mse', optimizer='sgd') <add> model.fit(x, y, epochs=1, batch_size=1) <add> <add> # Bidirectional and stateful <add> inputs = Input(batch_shape=(1, timesteps, dim)) <add> outputs = wrappers.Bidirectional(rnn(output_dim, stateful=True), <add> merge_mode=mode)(inputs) <add> model = Model(inputs, outputs) <add> model.compile(loss='mse', optimizer='sgd') <add> model.fit(x, y, epochs=1, batch_size=1) <add> <add> <ide> if __name__ == '__main__': <ide> pytest.main([__file__]) <ide><path>tests/keras/layers/wrappers_test.py <ide> from numpy.testing import assert_allclose <ide> from keras.utils.test_utils import keras_test <ide> from keras.layers import wrappers, Input <del>from keras.layers import core, convolutional, recurrent, embeddings, normalization <add>from keras import layers <ide> from keras.models import Sequential, Model, model_from_json <ide> from keras import backend as K <ide> from keras.engine.topology import _object_list_uid <ide> def test_TimeDistributed(): <ide> # first, test with Dense layer <ide> model = Sequential() <del> model.add(wrappers.TimeDistributed(core.Dense(2), input_shape=(3, 4))) <del> model.add(core.Activation('relu')) <add> model.add(wrappers.TimeDistributed(layers.Dense(2), input_shape=(3, 4))) <add> model.add(layers.Activation('relu')) <ide> model.compile(optimizer='rmsprop', loss='mse') <del> model.fit(np.random.random((10, 3, 4)), np.random.random((10, 3, 2)), epochs=1, batch_size=10) <add> model.fit(np.random.random((10, 3, 4)), np.random.random((10, 3, 2)), <add> epochs=1, <add> batch_size=10) <ide> <ide> # test config <ide> model.get_config() <ide> def test_TimeDistributed(): <ide> weights = model.layers[0].get_weights() <ide> <ide> reference = Sequential() <del> reference.add(wrappers.TimeDistributed(core.Dense(2), batch_input_shape=(1, 3, 4))) <del> reference.add(core.Activation('relu')) <add> reference.add(wrappers.TimeDistributed(layers.Dense(2), <add> batch_input_shape=(1, 3, 4))) <add> reference.add(layers.Activation('relu')) <ide> reference.compile(optimizer='rmsprop', loss='mse') <ide> reference.layers[0].set_weights(weights) <ide> <ide> def test_TimeDistributed(): <ide> <ide> # test with Embedding <ide> model = Sequential() <del> model.add(wrappers.TimeDistributed(embeddings.Embedding(5, 6), batch_input_shape=(10, 3, 4), dtype='int32')) <add> model.add(wrappers.TimeDistributed(layers.Embedding(5, 6), <add> batch_input_shape=(10, 3, 4), <add> dtype='int32')) <ide> model.compile(optimizer='rmsprop', loss='mse') <del> model.fit(np.random.randint(5, size=(10, 3, 4), dtype='int32'), np.random.random((10, 3, 4, 6)), epochs=1, batch_size=10) <add> model.fit(np.random.randint(5, size=(10, 3, 4), dtype='int32'), <add> np.random.random((10, 3, 4, 6)), epochs=1, batch_size=10) <ide> <ide> # compare to not using batch_input_shape <ide> test_input = np.random.randint(5, size=(10, 3, 4), dtype='int32') <ide> test_output = model.predict(test_input) <ide> weights = model.layers[0].get_weights() <ide> <ide> reference = Sequential() <del> reference.add(wrappers.TimeDistributed(embeddings.Embedding(5, 6), input_shape=(3, 4), dtype='int32')) <add> reference.add(wrappers.TimeDistributed(layers.Embedding(5, 6), <add> input_shape=(3, 4), dtype='int32')) <ide> reference.compile(optimizer='rmsprop', loss='mse') <ide> reference.layers[0].set_weights(weights) <ide> <ide> def test_TimeDistributed(): <ide> <ide> # test with Conv2D <ide> model = Sequential() <del> model.add(wrappers.TimeDistributed(convolutional.Conv2D(5, (2, 2), padding='same'), input_shape=(2, 4, 4, 3))) <del> model.add(core.Activation('relu')) <add> model.add(wrappers.TimeDistributed(layers.Conv2D(5, (2, 2), <add> padding='same'), <add> input_shape=(2, 4, 4, 3))) <add> model.add(layers.Activation('relu')) <ide> model.compile(optimizer='rmsprop', loss='mse') <del> model.train_on_batch(np.random.random((1, 2, 4, 4, 3)), np.random.random((1, 2, 4, 4, 5))) <add> model.train_on_batch(np.random.random((1, 2, 4, 4, 3)), <add> np.random.random((1, 2, 4, 4, 5))) <ide> <ide> model = model_from_json(model.to_json()) <ide> model.summary() <ide> <ide> # test stacked layers <ide> model = Sequential() <del> model.add(wrappers.TimeDistributed(core.Dense(2), input_shape=(3, 4))) <del> model.add(wrappers.TimeDistributed(core.Dense(3))) <del> model.add(core.Activation('relu')) <add> model.add(wrappers.TimeDistributed(layers.Dense(2), input_shape=(3, 4))) <add> model.add(wrappers.TimeDistributed(layers.Dense(3))) <add> model.add(layers.Activation('relu')) <ide> model.compile(optimizer='rmsprop', loss='mse') <ide> <del> model.fit(np.random.random((10, 3, 4)), np.random.random((10, 3, 3)), epochs=1, batch_size=10) <add> model.fit(np.random.random((10, 3, 4)), np.random.random((10, 3, 3)), <add> epochs=1, batch_size=10) <ide> <ide> # test wrapping Sequential model <ide> model = Sequential() <del> model.add(core.Dense(3, input_dim=2)) <add> model.add(layers.Dense(3, input_dim=2)) <ide> outer_model = Sequential() <ide> outer_model.add(wrappers.TimeDistributed(model, input_shape=(3, 2))) <ide> outer_model.compile(optimizer='rmsprop', loss='mse') <del> outer_model.fit(np.random.random((10, 3, 2)), np.random.random((10, 3, 3)), epochs=1, batch_size=10) <add> outer_model.fit(np.random.random((10, 3, 2)), np.random.random((10, 3, 3)), <add> epochs=1, batch_size=10) <ide> <ide> # test with functional API <ide> x = Input(shape=(3, 2)) <ide> y = wrappers.TimeDistributed(model)(x) <ide> outer_model = Model(x, y) <ide> outer_model.compile(optimizer='rmsprop', loss='mse') <del> outer_model.fit(np.random.random((10, 3, 2)), np.random.random((10, 3, 3)), epochs=1, batch_size=10) <add> outer_model.fit(np.random.random((10, 3, 2)), np.random.random((10, 3, 3)), <add> epochs=1, batch_size=10) <ide> <ide> # test with BatchNormalization <ide> model = Sequential() <del> model.add(wrappers.TimeDistributed(normalization.BatchNormalization(center=True, scale=True), <del> name='bn', input_shape=(10, 2))) <add> model.add(wrappers.TimeDistributed( <add> layers.BatchNormalization(center=True, scale=True), <add> name='bn', input_shape=(10, 2))) <ide> model.compile(optimizer='rmsprop', loss='mse') <ide> # Assert that mean and variance are 0 and 1. <ide> td = model.layers[0] <ide> def test_TimeDistributed_learning_phase(): <ide> # test layers that need learning_phase to be set <ide> np.random.seed(1234) <ide> x = Input(shape=(3, 2)) <del> y = wrappers.TimeDistributed(core.Dropout(.999))(x, training=True) <add> y = wrappers.TimeDistributed(layers.Dropout(.999))(x, training=True) <ide> model = Model(x, y) <ide> y = model.predict(np.random.random((10, 3, 2))) <ide> assert_allclose(np.mean(y), 0., atol=1e-1, rtol=1e-1) <ide> def test_TimeDistributed_learning_phase(): <ide> def test_regularizers(): <ide> model = Sequential() <ide> model.add(wrappers.TimeDistributed( <del> core.Dense(2, kernel_regularizer='l1'), input_shape=(3, 4))) <del> model.add(core.Activation('relu')) <add> layers.Dense(2, kernel_regularizer='l1'), input_shape=(3, 4))) <add> model.add(layers.Activation('relu')) <ide> model.compile(optimizer='rmsprop', loss='mse') <ide> assert len(model.layers[0].layer.losses) == 1 <ide> assert len(model.layers[0].losses) == 1 <ide> def test_regularizers(): <ide> <ide> model = Sequential() <ide> model.add(wrappers.TimeDistributed( <del> core.Dense(2, activity_regularizer='l1'), input_shape=(3, 4))) <del> model.add(core.Activation('relu')) <add> layers.Dense(2, activity_regularizer='l1'), input_shape=(3, 4))) <add> model.add(layers.Activation('relu')) <ide> model.compile(optimizer='rmsprop', loss='mse') <ide> assert len(model.losses) == 1 <ide> <ide> <ide> @keras_test <ide> def test_Bidirectional(): <del> rnn = recurrent.SimpleRNN <add> rnn = layers.SimpleRNN <ide> samples = 2 <ide> dim = 2 <ide> timesteps = 2 <ide> def test_Bidirectional(): <ide> model = Sequential() <ide> model.add(wrappers.Bidirectional(rnn(output_dim, dropout=dropout_rate, <ide> recurrent_dropout=dropout_rate), <del> merge_mode=mode, input_shape=(timesteps, dim))) <add> merge_mode=mode, <add> input_shape=(timesteps, dim))) <ide> model.compile(loss='mse', optimizer='sgd') <ide> model.fit(x, y, epochs=1, batch_size=1) <ide> <ide> def test_Bidirectional(): <ide> <ide> # test stacked bidirectional layers <ide> model = Sequential() <del> model.add(wrappers.Bidirectional(rnn(output_dim, return_sequences=True), <del> merge_mode=mode, input_shape=(timesteps, dim))) <add> model.add(wrappers.Bidirectional(rnn(output_dim, <add> return_sequences=True), <add> merge_mode=mode, <add> input_shape=(timesteps, dim))) <ide> model.add(wrappers.Bidirectional(rnn(output_dim), merge_mode=mode)) <ide> model.compile(loss='mse', optimizer='sgd') <ide> model.fit(x, y, epochs=1, batch_size=1) <ide> def test_Bidirectional(): <ide> <ide> # Bidirectional and stateful <ide> inputs = Input(batch_shape=(1, timesteps, dim)) <del> outputs = wrappers.Bidirectional(rnn(output_dim, stateful=True), merge_mode=mode)(inputs) <add> outputs = wrappers.Bidirectional(rnn(output_dim, stateful=True), <add> merge_mode=mode)(inputs) <ide> model = Model(inputs, outputs) <ide> model.compile(loss='mse', optimizer='sgd') <ide> model.fit(x, y, epochs=1, batch_size=1)
2
Javascript
Javascript
expand quickstart widget with cuda 11.1 and 11.2
fd6eebbfdca942d207ffa43900868b4c6d0d943a
<ide><path>website/src/widgets/quickstart-install.js <ide> const CUDA = { <ide> '10.1': 'cuda101', <ide> '10.2': 'cuda102', <ide> '11.0': 'cuda110', <add> '11.1': 'cuda111', <add> '11.2': 'cuda112', <ide> } <ide> const LANG_EXTRAS = ['ja'] // only for languages with models <ide>
1
Text
Text
remove spaces inside code span elements
63f5a76c1dd9e9c3d4851d41eb1593d9838bad71
<ide><path>doc/api/buffer.md <ide> changes: <ide> * `value` {string|Buffer|Uint8Array|integer} What to search for. <ide> * `byteOffset` {integer} Where to begin searching in `buf`. If negative, then <ide> offset is calculated from the end of `buf`. **Default:** <del> [`buf.length`][] `- 1`. <add> `buf.length - 1`. <ide> * `encoding` {string} If `value` is a string, this is the encoding used to <ide> determine the binary representation of the string that will be searched for in <ide> `buf`. **Default:** `'utf8'`. <ide><path>test/README.md <ide> For the tests to run on Windows, be sure to clone Node.js source code with the <ide> <ide> | Directory | Runs on CI | Purpose | <ide> | ------------------- | --------------- | --------------- | <del>| `abort` | Yes | Tests for when the ``` --abort-on-uncaught-exception ``` flag is used. | <add>| `abort` | Yes | Tests for when the `--abort-on-uncaught-exception` flag is used. | <ide> | `addons` | Yes | Tests for [addon](https://nodejs.org/api/addons.html) functionality along with some tests that require an addon. | <ide> | `async-hooks` | Yes | Tests for [async_hooks](https://nodejs.org/api/async_hooks.html) functionality. | <ide> | `benchmark` | No | Test minimal functionality of benchmarks. | <ide> For the tests to run on Windows, be sure to clone Node.js source code with the <ide> | `internet` | No | Tests that make real outbound network connections. Tests for networking related modules may also be present in other directories, but those tests do not make outbound connections. | <ide> | `js-native-api` | Yes | Tests for Node.js-agnostic [n-api](https://nodejs.org/api/n-api.html) functionality. | <ide> | `known_issues` | Yes | Tests reproducing known issues within the system. All tests inside of this directory are expected to fail. If a test doesn't fail on certain platforms, those should be skipped via `known_issues.status`. | <del>| `message` | Yes | Tests for messages that are output for various conditions (```console.log```, error messages etc.) | <add>| `message` | Yes | Tests for messages that are output for various conditions (`console.log`, error messages etc.) | <ide> | `node-api` | Yes | Tests for Node.js-specific [n-api](https://nodejs.org/api/n-api.html) functionality. | <ide> | `parallel` | Yes | Various tests that are able to be run in parallel. | <ide> | `pseudo-tty` | Yes | Tests that require stdin/stdout/stderr to be a TTY. | <ide> | `pummel` | No | Various tests for various modules / system functionality operating under load. | <ide> | `sequential` | Yes | Various tests that must not run in parallel. | <ide> | `testpy` | | Test configuration utility used by various test suites. | <del>| `tick-processor` | No | Tests for the V8 tick processor integration. The tests are for the logic in ```lib/internal/v8_prof_processor.js``` and ```lib/internal/v8_prof_polyfill.js```. The tests confirm that the profile processor packages the correct set of scripts from V8 and introduces the correct platform specific logic. | <add>| `tick-processor` | No | Tests for the V8 tick processor integration. The tests are for the logic in `lib/internal/v8_prof_processor.js` and `lib/internal/v8_prof_polyfill.js`. The tests confirm that the profile processor packages the correct set of scripts from V8 and introduces the correct platform specific logic. | <ide> | `v8-updates` | No | Tests for V8 performance integration. |
2
Go
Go
use waitandassert to test node state changes
f02ec39e99bfd36f34a965f78d853e19234e513b
<ide><path>integration-cli/daemon_swarm.go <ide> func (d *SwarmDaemon) updateSwarm(c *check.C, f ...specConstructor) { <ide> c.Assert(err, checker.IsNil) <ide> c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out))) <ide> } <add> <add>func (d *SwarmDaemon) checkLocalNodeState(c *check.C) (interface{}, check.CommentInterface) { <add> info, err := d.info() <add> c.Assert(err, checker.IsNil) <add> return info.LocalNodeState, nil <add>} <add> <add>func (d *SwarmDaemon) checkControlAvailable(c *check.C) (interface{}, check.CommentInterface) { <add> info, err := d.info() <add> c.Assert(err, checker.IsNil) <add> c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateActive) <add> return info.ControlAvailable, nil <add>} <ide><path>integration-cli/docker_api_swarm_test.go <ide> func (s *DockerSwarmSuite) TestApiSwarmInit(c *check.C) { <ide> d1 := s.AddDaemon(c, true, true) <ide> info, err := d1.info() <ide> c.Assert(err, checker.IsNil) <del> c.Assert(info.ControlAvailable, checker.Equals, true) <add> c.Assert(info.ControlAvailable, checker.True) <ide> c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateActive) <ide> <ide> d2 := s.AddDaemon(c, true, false) <ide> info, err = d2.info() <ide> c.Assert(err, checker.IsNil) <del> c.Assert(info.ControlAvailable, checker.Equals, false) <add> c.Assert(info.ControlAvailable, checker.False) <ide> c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateActive) <ide> <ide> // Leaving cluster <ide> c.Assert(d2.Leave(false), checker.IsNil) <ide> <ide> info, err = d2.info() <ide> c.Assert(err, checker.IsNil) <del> c.Assert(info.ControlAvailable, checker.Equals, false) <add> c.Assert(info.ControlAvailable, checker.False) <ide> c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateInactive) <ide> <ide> c.Assert(d2.Join(swarm.JoinRequest{RemoteAddrs: []string{d1.listenAddr}}), checker.IsNil) <ide> <ide> info, err = d2.info() <ide> c.Assert(err, checker.IsNil) <del> c.Assert(info.ControlAvailable, checker.Equals, false) <add> c.Assert(info.ControlAvailable, checker.False) <ide> c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateActive) <ide> <ide> // Current state restoring after restarts <ide> func (s *DockerSwarmSuite) TestApiSwarmInit(c *check.C) { <ide> <ide> info, err = d1.info() <ide> c.Assert(err, checker.IsNil) <del> c.Assert(info.ControlAvailable, checker.Equals, true) <add> c.Assert(info.ControlAvailable, checker.True) <ide> c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateActive) <ide> <ide> info, err = d2.info() <ide> c.Assert(err, checker.IsNil) <del> c.Assert(info.ControlAvailable, checker.Equals, false) <add> c.Assert(info.ControlAvailable, checker.False) <ide> c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateActive) <ide> } <ide> <ide> func (s *DockerSwarmSuite) testAPISwarmManualAcceptance(c *check.C, secret strin <ide> d1.updateNode(c, info.NodeID, func(n *swarm.Node) { <ide> n.Spec.Membership = swarm.NodeMembershipAccepted <ide> }) <del> for i := 0; ; i++ { <del> info, err := d3.info() <del> c.Assert(err, checker.IsNil) <del> if info.LocalNodeState == swarm.LocalNodeStateActive { <del> break <del> } <del> if i > 100 { <del> c.Fatalf("node did not become active") <del> } <del> time.Sleep(200 * time.Millisecond) <del> } <add> waitAndAssert(c, defaultReconciliationTimeout, d3.checkLocalNodeState, checker.Equals, swarm.LocalNodeStateActive) <ide> } <ide> <ide> func (s *DockerSwarmSuite) TestApiSwarmSecretAcceptance(c *check.C) { <ide> func (s *DockerSwarmSuite) TestApiSwarmPromoteDemote(c *check.C) { <ide> <ide> info, err := d2.info() <ide> c.Assert(err, checker.IsNil) <del> c.Assert(info.ControlAvailable, checker.Equals, false) <add> c.Assert(info.ControlAvailable, checker.False) <ide> c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateActive) <ide> <ide> d1.updateNode(c, d2.NodeID, func(n *swarm.Node) { <ide> n.Spec.Role = swarm.NodeRoleManager <ide> }) <ide> <del> for i := 0; ; i++ { <del> info, err := d2.info() <del> c.Assert(err, checker.IsNil) <del> c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateActive) <del> if info.ControlAvailable { <del> break <del> } <del> if i > 100 { <del> c.Errorf("node did not turn into manager") <del> } <del> time.Sleep(100 * time.Millisecond) <del> } <add> waitAndAssert(c, defaultReconciliationTimeout, d2.checkControlAvailable, checker.True) <ide> <ide> d1.updateNode(c, d2.NodeID, func(n *swarm.Node) { <ide> n.Spec.Role = swarm.NodeRoleWorker <ide> }) <ide> <del> for i := 0; ; i++ { <del> info, err := d2.info() <del> c.Assert(err, checker.IsNil) <del> c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateActive) <del> if !info.ControlAvailable { <del> break <del> } <del> if i > 100 { <del> c.Errorf("node did not turn into worker") <del> } <del> time.Sleep(100 * time.Millisecond) <del> } <add> waitAndAssert(c, defaultReconciliationTimeout, d2.checkControlAvailable, checker.False) <ide> <ide> // Demoting last node should fail <ide> node := d1.getNode(c, d1.NodeID) <ide> func (s *DockerSwarmSuite) TestApiSwarmPromoteDemote(c *check.C) { <ide> info, err = d1.info() <ide> c.Assert(err, checker.IsNil) <ide> c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateActive) <del> c.Assert(info.ControlAvailable, checker.Equals, true) <add> c.Assert(info.ControlAvailable, checker.True) <ide> <ide> // Promote already demoted node <ide> d1.updateNode(c, d2.NodeID, func(n *swarm.Node) { <ide> n.Spec.Role = swarm.NodeRoleManager <ide> }) <ide> <del> for i := 0; ; i++ { <del> info, err := d2.info() <del> c.Assert(err, checker.IsNil) <del> c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateActive) <del> if info.ControlAvailable { <del> break <del> } <del> if i > 100 { <del> c.Errorf("node did not turn into manager") <del> } <del> time.Sleep(100 * time.Millisecond) <del> } <add> waitAndAssert(c, defaultReconciliationTimeout, d2.checkControlAvailable, checker.True) <ide> } <ide> <ide> func (s *DockerSwarmSuite) TestApiSwarmServicesCreate(c *check.C) { <ide> func (s *DockerSwarmSuite) TestApiSwarmLeaveOnPendingJoin(c *check.C) { <ide> RemoteAddrs: []string{"nosuchhost:1234"}, <ide> }) // will block on pending state <ide> <del> for i := 0; ; i++ { <del> info, err := d2.info() <del> c.Assert(err, checker.IsNil) <del> if info.LocalNodeState == swarm.LocalNodeStatePending { <del> break <del> } <del> if i > 100 { <del> c.Fatalf("node did not go to pending state: %v", info.LocalNodeState) <del> } <del> time.Sleep(100 * time.Millisecond) <del> } <add> waitAndAssert(c, defaultReconciliationTimeout, d2.checkLocalNodeState, checker.Equals, swarm.LocalNodeStatePending) <ide> <ide> c.Assert(d2.Leave(true), checker.IsNil) <ide> <ide> func (s *DockerSwarmSuite) TestApiSwarmRestoreOnPendingJoin(c *check.C) { <ide> RemoteAddrs: []string{"nosuchhost:1234"}, <ide> }) // will block on pending state <ide> <del> for i := 0; ; i++ { <del> info, err := d.info() <del> c.Assert(err, checker.IsNil) <del> if info.LocalNodeState == swarm.LocalNodeStatePending { <del> break <del> } <del> if i > 100 { <del> c.Fatalf("node did not go to pending state: %v", info.LocalNodeState) <del> } <del> time.Sleep(100 * time.Millisecond) <del> } <add> waitAndAssert(c, defaultReconciliationTimeout, d.checkLocalNodeState, checker.Equals, swarm.LocalNodeStatePending) <ide> <ide> c.Assert(d.Stop(), checker.IsNil) <ide> c.Assert(d.Start(), checker.IsNil) <ide> func (s *DockerSwarmSuite) TestApiSwarmForceNewCluster(c *check.C) { <ide> d3 := s.AddDaemon(c, true, true) <ide> info, err := d3.info() <ide> c.Assert(err, checker.IsNil) <del> c.Assert(info.ControlAvailable, checker.Equals, true) <add> c.Assert(info.ControlAvailable, checker.True) <ide> c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateActive) <ide> <ide> instances = 4
2
Go
Go
fix error reporting on executor wait
c895a76f1076c782011e9decf58ab6548cf0fb35
<ide><path>daemon/cluster/executor/container/controller.go <ide> func (r *controller) Wait(pctx context.Context) error { <ide> defer cancel() <ide> <ide> err := r.adapter.wait(ctx) <del> if err != nil { <del> return err <del> } <ide> if ctx.Err() != nil { <ide> return ctx.Err() <ide> } <ide> func (r *controller) Wait(pctx context.Context) error { <ide> if ec, ok := err.(exec.ExitCoder); ok { <ide> ee.code = ec.ExitCode() <ide> } <add> return ee <ide> } <ide> return nil <ide> }
1
Python
Python
add 3.10 classifier
79a8e16ed2de533dc91e474c912cfaef8e1a1e92
<ide><path>setup.py <ide> Programming Language :: Python :: 3.6 <ide> Programming Language :: Python :: 3.7 <ide> Programming Language :: Python :: 3.8 <add>Programming Language :: Python :: 3.9 <ide> Programming Language :: Python :: 3 :: Only <ide> Programming Language :: Python :: Implementation :: CPython <ide> Topic :: Software Development
1
PHP
PHP
add docblock methods in schema facade
0b54f945bafc0185a7959901772cae6c9b36646f
<ide><path>src/Illuminate/Support/Facades/Schema.php <ide> namespace Illuminate\Support\Facades; <ide> <ide> /** <add> * @method static \Illuminate\Database\Schema\Builder create(string $table, \Closure $callback) <add> * @method static \Illuminate\Database\Schema\Builder drop(string $table) <add> * @method static \Illuminate\Database\Schema\Builder dropIfExists(string $table) <add> * @method static \Illuminate\Database\Schema\Builder table(string $table, \Closure $callback) <add> * <ide> * @see \Illuminate\Database\Schema\Builder <ide> */ <ide> class Schema extends Facade
1
Go
Go
create rw and rootfs directory if they don't exist
9e8278134d73ffa0a4e72c2202aa1e5c2bcffc98
<ide><path>graph/image.go <ide> func (image *Image) Mount(root, rw string) error { <ide> if err != nil { <ide> return err <ide> } <add> // Create the target directories if they don't exist <add> if err := os.Mkdir(root, 0755); err != nil && !os.IsExist(err) { <add> return err <add> } <add> if err := os.Mkdir(rw, 0755); err != nil && !os.IsExist(err) { <add> return err <add> } <ide> // FIXME: @creack shouldn't we do this after going over changes? <ide> if err := MountAUFS(layers, rw, root); err != nil { <ide> return err
1
Python
Python
remove unused imports
ab2f63b0892637c5c7c29562944ce0a53fc32d84
<ide><path>libcloud/drivers/ecp.py <ide> import base64 <ide> import httplib <ide> import socket <del>import struct <ide> import os <ide> <ide> # JSON is included in the standard library starting with Python 2.6. For 2.5 <ide><path>libcloud/drivers/slicehost.py <ide> from libcloud.base import NodeSize, NodeImage, NodeLocation <ide> from libcloud.base import is_private_subnet <ide> import base64 <del>import struct <ide> import socket <ide> from xml.etree import ElementTree as ET <ide> from xml.parsers.expat import ExpatError
2
Javascript
Javascript
remove unneeded comma from boxhelper test
bdfdbd3dc9bf3f83f7e6c485d63efc9e71acc6b5
<ide><path>test/unit/extras/helpers/BoxHelper.tests.js <ide> 'use strict'; <ide> <ide> var parameters = { <del> diameter: 10, <add> diameter: 10 <ide> }; <ide> <ide> var geometries;
1
PHP
PHP
fix allowempty calculation
a29aec16339118e44104631d9c2e782d17f78508
<ide><path>src/Console/Command/Task/ModelTask.php <ide> public function fieldValidation($fieldName, $metaData, $primaryKey) { <ide> } <ide> <ide> $allowEmpty = false; <del> if ($rule !== 'notEmpty' && $metaData['null'] === false) { <add> if ($rule !== 'notEmpty' && $metaData['null'] === true) { <ide> $allowEmpty = true; <ide> } <ide> <ide><path>tests/TestCase/Console/Command/Task/ModelTaskTest.php <ide> public function testGetValidation() { <ide> $model = TableRegistry::get('BakeArticles'); <ide> $result = $this->Task->getValidation($model); <ide> $expected = [ <del> 'id' => ['rule' => 'numeric', 'allowEmpty' => true], <del> 'bake_user_id' => ['rule' => 'numeric', 'allowEmpty' => true], <add> 'id' => ['rule' => 'numeric', 'allowEmpty' => false], <add> 'bake_user_id' => ['rule' => 'numeric', 'allowEmpty' => false], <ide> 'title' => ['rule' => 'notEmpty', 'allowEmpty' => false], <ide> 'body' => ['rule' => 'notEmpty', 'allowEmpty' => false], <del> 'published' => ['rule' => 'boolean', 'allowEmpty' => false], <add> 'published' => ['rule' => 'boolean', 'allowEmpty' => true], <ide> ]; <ide> $this->assertEquals($expected, $result); <ide> }
2
Text
Text
update missed yarn -> pnpm in contributing
1420dd9a098d29a49376cfa1d0ed493b7462413b
<ide><path>contributing.md <ide> There are two options to develop with your local version of the codebase: <ide> 3. In your app's root directory, run: <ide> <ide> ```sh <del> yarn <add> pnpm i <ide> ``` <ide> <ide> to re-install all of the dependencies.
1
Text
Text
fix example output
55f8d5478ecb5fd913a3a5fe7c469e8bc8a4f038
<ide><path>website/docs/api/cli.md <ide> training -> dropout field required <ide> training -> optimizer field required <ide> training -> optimize extra fields not permitted <ide> <del>{'vectors': 'en_vectors_web_lg', 'seed': 0, 'accumulate_gradient': 1, 'init_tok2vec': None, 'raw_text': None, 'patience': 1600, 'max_epochs': 0, 'max_steps': 20000, 'eval_frequency': 200, 'frozen_components': [], 'optimize': None, 'batcher': {'@batchers': 'spacy.batch_by_words.v1', 'discard_oversize': False, 'tolerance': 0.2, 'get_length': None, 'size': {'@schedules': 'compounding.v1', 'start': 100, 'stop': 1000, 'compound': 1.001, 't': 0.0}}, 'dev_corpus': {'@readers': 'spacy.Corpus.v1', 'path': '', 'max_length': 0, 'gold_preproc': False, 'limit': 0}, 'score_weights': {'tag_acc': 0.5, 'dep_uas': 0.25, 'dep_las': 0.25, 'sents_f': 0.0}, 'train_corpus': {'@readers': 'spacy.Corpus.v1', 'path': '', 'max_length': 0, 'gold_preproc': False, 'limit': 0}} <add>{'vectors': 'en_vectors_web_lg', 'seed': 0, 'accumulate_gradient': 1, 'init_tok2vec': None, 'raw_text': None, 'patience': 1600, 'max_epochs': 0, 'max_steps': 20000, 'eval_frequency': 200, 'frozen_components': [], 'optimize': None, 'batcher': {'@batchers': 'spacy.batch_by_words.v1', 'discard_oversize': False, 'tolerance': 0.2, 'get_length': None, 'size': {'@schedules': 'compounding.v1', 'start': 100, 'stop': 1000, 'compound': 1.001, 't': 0.0}}, 'corpus': {'train': {'@readers': 'spacy.Corpus.v1', 'path': '', 'max_length': 0, 'gold_preproc': False, 'limit': 0}, 'dev': {'@readers': 'spacy.Corpus.v1', 'path': '', 'max_length': 0, 'gold_preproc': False, 'limit': 0}} 'score_weights': {'tag_acc': 0.5, 'dep_uas': 0.25, 'dep_las': 0.25, 'sents_f': 0.0}} <ide> <ide> If your config contains missing values, you can run the 'init fill-config' <ide> command to fill in all the defaults, if possible: <ide> Registry @schedules <ide> Name compounding.v1 <ide> Module thinc.schedules <ide> File /path/to/thinc/thinc/schedules.py (line 43) <del>ℹ [training.dev_corpus] <add>ℹ [training.corpus.dev] <add>Registry @readers <add>Name spacy.Corpus.v1 <add>Module spacy.training.corpus <add>File /path/to/spacy/training/corpus.py (line 18) <add>ℹ [training.corpus.train] <ide> Registry @readers <ide> Name spacy.Corpus.v1 <ide> Module spacy.training.corpus <ide> Registry @schedules <ide> Name warmup_linear.v1 <ide> Module thinc.schedules <ide> File /path/to/thinc/thinc/schedules.py (line 91) <del>ℹ [training.train_corpus] <del>Registry @readers <del>Name spacy.Corpus.v1 <del>Module spacy.training.corpus <del>File /path/to/spacy/training/corpus.py (line 18) <ide> ``` <ide> <ide> </Accordion>
1
Python
Python
fix bugs in test_hql
7ee537b7f8ec339807b58ed0da21b637f5bb8443
<ide><path>airflow/hooks/hive_hooks.py <ide> def test_hql(self, hql): <ide> """ <ide> create, insert, other = [], [], [] <ide> for query in hql.split(';'): # naive <add> query_original = query <ide> query = query.lower().strip() <add> <ide> if query.startswith('create table'): <del> create.append(query) <del> elif query.startswith(('set ', 'add jar ', 'temporary ')): <del> other.append(query) <add> create.append(query_original) <add> elif query.startswith(('set ', <add> 'add jar ', <add> 'create temporary function')): <add> other.append(query_original) <ide> elif query.startswith('insert'): <del> insert.append(query) <add> insert.append(query_original) <ide> other = ';'.join(other) <ide> for query_set in [create, insert]: <ide> for query in query_set: <add> <ide> query_preview = ' '.join(query.split())[:50] <ide> logging.info("Testing HQL [{0} (...)]".format(query_preview)) <ide> if query_set == insert: <ide> def test_hql(self, hql): <ide> try: <ide> self.run_cli(query, verbose=False) <ide> except AirflowException as e: <del> failure_message = e.args[0].split('\n')[-2] <del> logging.info(failure_message) <del> line_number = re.search('(\d+):(\d+)', failure_message).group(1) <del> if line_number.isdigit(): <del> l = int(line_number) <add> message = e.args[0].split('\n')[-2] <add> logging.info(message) <add> error_loc = re.search('(\d+):(\d+)', message) <add> if error_loc and error_loc.group(1).isdigit(): <add> l = int(error_loc.group(1)) <ide> begin = max(l-2, 0) <ide> end = min(l+3, len(query.split('\n'))) <ide> context = '\n'.join(query.split('\n')[begin:end])
1