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
allow empty values in checkboxes
605351d0c9706e33bde9b0354a5cf494d65d333b
<ide><path>lib/Cake/Test/Case/View/Helper/FormHelperTest.php <ide> public function testCheckboxHiddenField() { <ide> $this->assertTags($result, $expected); <ide> } <ide> <add>/** <add> * Test that a checkbox can have 0 for the value and 1 for the hidden input. <add> * <add> * @return void <add> */ <add> public function testCheckboxZeroValue() { <add> $result = $this->Form->input('User.get_spam', array( <add> 'type' => 'checkbox', <add> 'value' => '0', <add> 'hiddenField' => '1', <add> )); <add> $expected = array( <add> 'div' => array('class' => 'input checkbox'), <add> array('input' => array( <add> 'type' => 'hidden', 'name' => 'data[User][get_spam]', <add> 'value' => '1', 'id' => 'UserGetSpam_' <add> )), <add> array('input' => array( <add> 'type' => 'checkbox', 'name' => 'data[User][get_spam]', <add> 'value' => '0', 'id' => 'UserGetSpam' <add> )), <add> 'label' => array('for' => 'UserGetSpam'), <add> 'Get Spam', <add> '/label', <add> '/div' <add> ); <add> $this->assertTags($result, $expected); <add> } <add> <ide> /** <ide> * testDateTime method <ide> * <ide><path>lib/Cake/View/Helper/FormHelper.php <ide> public function checkbox($fieldName, $options = array()) { <ide> unset($options['default']); <ide> } <ide> <del> $options += array('required' => false); <add> $options += array('value' => 1, 'required' => false); <ide> $options = $this->_initInputField($fieldName, $options) + array('hiddenField' => true); <ide> $value = current($this->value($valueOptions)); <ide> $output = ''; <ide> <del> if (empty($options['value'])) { <del> $options['value'] = 1; <del> } <ide> if ( <ide> (!isset($options['checked']) && !empty($value) && $value == $options['value']) || <ide> !empty($options['checked'])
2
Text
Text
add doc page about writing custom layers
36a829c20d5dcd4d8ba120781235c278588b6bb7
<ide><path>docs/templates/layers/writing-your-own-keras-layers.md <add># Writing your own Keras layers <add> <add>For simple, stateless custom operations, you are probably better off using `layers.core.Lambda` layers. But for any custom operation that has trainable weights, you should implement your own layer. <add> <add>Here is the skeleton of a Keras layer. There are only three methods you need to implement: <add> <add>- `build(input_shape)`: this is where you will define your weights. Trainable weights should be added to the list `self.trainable_weights`. Other attributes of note are: `self.non_trainable_weights` (list) and `self.updates` (list of update tuples (tensor, new_tensor)). For an example of how to use `non_trainable_weights` and `updates`, see the code for the `BatchNormalization` layer. <add>- `call(x)`: this is where the layer's logic lives. Unless you want you want your layer to support masking, you only have to care about the first argument passed to `call`: the input tensor. <add>- `get_output_shape_for(input_shape)`: in case your layer modifies the shape of its input, you should specify here the shape transformation logic. This allows Keras to do automatic shape inference. <add> <add>```python <add>from keras import backend as K <add>from keras.engine.topology import Layer <add> <add>class MyLayer(Layer): <add> def __init__(self, output_dim, **kwargs): <add> self.output_dim = output_dim <add> super(MyLayer, self).__init__(**kwargs) <add> <add> def build(self, input_shape): <add> input_dim = input_shape[1] <add> initial_weight_value = np.random.random((input_dim, output_dim)) <add> self.W = K.variable(initial_weight_value) <add> self.trainable_weights = [self.W] <add> <add> def call(self, x, mask=None): <add> return K.dot(x, self.W) <add> <add> def get_output_shape_for(self, input_shape): <add> return (input_shape[0] + self.output_dim) <add>``` <add> <add>The existing Keras layers provide ample examples of how to implement almost anything. Never hesitate to read the source code! <ide>\ No newline at end of file
1
Python
Python
set version to v3.0.0a7
a95a36ce2ad6ce4394c686c85aa3188d15c188ec
<ide><path>spacy/about.py <ide> # fmt: off <ide> __title__ = "spacy-nightly" <del>__version__ = "3.0.0a6" <add>__version__ = "3.0.0a7" <ide> __release__ = True <ide> __download_url__ = "https://github.com/explosion/spacy-models/releases/download" <ide> __compatibility__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json"
1
Javascript
Javascript
add eslint rule for documented errors
76b8803630f9a324810f38d00610792033e862c7
<ide><path>lib/internal/errors.js <add>/* eslint documented-errors: "error" */ <ide> /* eslint alphabetize-errors: "error" */ <ide> <ide> 'use strict'; <ide><path>test/parallel/test-eslint-documented-errors.js <add>'use strict'; <add> <add>require('../common'); <add> <add>const RuleTester = require('../../tools/eslint').RuleTester; <add>const rule = require('../../tools/eslint-rules/documented-errors'); <add> <add>const invalidCode = 'UNDOCUMENTED ERROR CODE'; <add> <add>new RuleTester().run('documented-errors', rule, { <add> valid: [ <add> ` <add> E('ERR_ASSERTION', 'foo'); <add> ` <add> ], <add> invalid: [ <add> { <add> code: ` <add> E('${invalidCode}', 'bar'); <add> `, <add> errors: [ <add> { <add> message: `"${invalidCode}" is not documented in doc/api/errors.md`, <add> line: 2 <add> }, <add> { <add> message: <add> `doc/api/errors.md does not have an anchor for "${invalidCode}"`, <add> line: 2 <add> } <add> ] <add> } <add> ] <add>}); <ide><path>tools/eslint-rules/documented-errors.js <add>'use strict'; <add> <add>const fs = require('fs'); <add>const path = require('path'); <add> <add>const doc = fs.readFileSync(path.resolve(__dirname, '../../doc/api/errors.md'), <add> 'utf8'); <add> <add>function isInDoc(code) { <add> return doc.match(`### ${code}`) != null; <add>} <add> <add>function includesAnchor(code) { <add> return doc.match(`<a id="${code}"></a>`) != null; <add>} <add> <add>function errorForNode(node) { <add> return node.expression.arguments[0].value; <add>} <add> <add>function isDefiningError(node) { <add> return node.expression && <add> node.expression.type === 'CallExpression' && <add> node.expression.callee && <add> node.expression.callee.name === 'E'; <add>} <add> <add>module.exports = { <add> create: function(context) { <add> return { <add> ExpressionStatement: function(node) { <add> if (!isDefiningError(node)) return; <add> const code = errorForNode(node); <add> if (!isInDoc(code)) { <add> const message = `"${code}" is not documented in doc/api/errors.md`; <add> context.report({ node, message }); <add> } <add> if (!includesAnchor(code)) { <add> const message = <add> `doc/api/errors.md does not have an anchor for "${code}"`; <add> context.report({ node, message }); <add> } <add> } <add> }; <add> } <add>};
3
Ruby
Ruby
fix memcachestoretest stubbing
10e361179d80a7449d892c4118ee27635ab85df6
<ide><path>activesupport/test/cache/stores/mem_cache_store_test.rb <ide> def after_teardown <ide> def test_clear_also_clears_local_cache <ide> key = SecureRandom.uuid <ide> cache = lookup_store(raw: true) <del> client.stub(:flush_all, -> { client.delete(key) }) do <add> stub_called = false <add> <add> client(cache).stub(:flush_all, -> { stub_called = true; client.delete("#{@namespace}:#{key}") }) do <ide> cache.with_local_cache do <ide> cache.write(key, SecureRandom.alphanumeric) <ide> cache.clear <ide> assert_nil cache.read(key) <ide> end <ide> assert_nil cache.read(key) <ide> end <add> assert stub_called <ide> end <ide> <ide> def test_raw_values
1
Mixed
PHP
set default encryption mode to "cbc"
fc9760ad63e2421e484410394fd97e393fb21962
<ide><path>readme.md <ide> - Added `Html::mailto` and `Html::email` from Laravel 3. <ide> - Added `Mail::queue`, `Mail::later`, `Mail::queueOn`, and `Mail::laterOn`. Screencast forthcoming. <ide> - Added `URL::full` method as alias into `Request::fullUrl`. <add>- Set default encryption mode to `cbc`. `Crypt::setMode` is available if you wish to use previous mode of `ctr`. <ide> <ide> ## Beta 4 <ide> <ide><path>src/Illuminate/Encryption/Encrypter.php <ide> class Encrypter { <ide> * <ide> * @var string <ide> */ <del> protected $mode = 'ctr'; <add> protected $mode = 'cbc'; <ide> <ide> /** <ide> * The block size of the cipher.
2
Python
Python
update ndarray.round docs to match travis' mods
0982d6e124e0728e227bda735a19c359900fcc4a
<ide><path>numpy/add_newdocs.py <ide> Round to the specified number of decimals. When 'decimals' is negative it <ide> specifies the number of positions to the left of the decimal point. The real <ide> and imaginary parts of complex numbers are rounded separately. Nothing is <del> done if the array is not of float type. <add> done if the array is not of float type and 'decimals' is >= 0. <ide> <ide> The keyword 'out' may be used to specify a different array to hold the <ide> result rather than the default 'a'. If the type of the array specified by
1
PHP
PHP
remove redundant tests around debug()
bbb1567955ac91878be677bb4dfaa0b7e3799948
<ide><path>src/Error/Debug/ConsoleFormatter.php <ide> public static function environmentMatches(): bool <ide> } <ide> <ide> /** <del> * {@inheritDoc} <add> * @inheritDoc <ide> */ <del> public function formatWrapper(string $contents, array $location) <add> public function formatWrapper(string $contents, array $location): string <ide> { <ide> $lineInfo = ''; <ide> if (isset($location['file'], $location['file'])) { <ide><path>src/Error/Debug/FormatterInterface.php <ide> public function dump(NodeInterface $node): string; <ide> * @param array $location The file and line the contents came from. <ide> * @return string <ide> */ <del> public function formatWrapper(string $contents, array $location); <add> public function formatWrapper(string $contents, array $location): string; <ide> } <ide><path>src/Error/Debug/HtmlFormatter.php <ide> public static function environmentMatches(): bool <ide> } <ide> <ide> /** <del> * {@inheritDoc} <add> * @inheritDoc <ide> */ <del> public function formatWrapper(string $contents, array $location) <add> public function formatWrapper(string $contents, array $location): string <ide> { <ide> $lineInfo = ''; <ide> if (isset($location['file'], $location['file'])) { <ide><path>src/Error/Debug/TextFormatter.php <ide> class TextFormatter implements FormatterInterface <ide> { <ide> /** <del> * {@inheritDoc} <add> * @inheritDoc <ide> */ <del> public function formatWrapper(string $contents, array $location) <add> public function formatWrapper(string $contents, array $location): string <ide> { <ide> $template = <<<TEXT <ide> %s <ide><path>src/Error/Debugger.php <ide> public static function getType($var): string <ide> * @param array $location If contains keys "file" and "line" their values will <ide> * be used to show location info. <ide> * @param bool|null $showHtml If set to true, the method prints the debug <del> * data in a browser-friendly way. <add> * data encoded as HTML. If false, plain text formatting will be used. <add> * If null, the format will be chosen based on the configured exportFormatter, or <add> * environment conditions. <ide> * @return void <ide> */ <ide> public static function printVar($var, array $location = [], ?bool $showHtml = null): void <ide><path>tests/TestCase/BasicsTest.php <ide> namespace Cake\Test\TestCase; <ide> <ide> use Cake\Collection\Collection; <add>use Cake\Error\Debugger; <ide> use Cake\Event\EventManager; <ide> use Cake\Http\Response; <ide> use Cake\TestSuite\TestCase; <ide> public function testDebug() <ide> ########################### <ide> <ide> EXPECTED; <del> $expected = sprintf($expectedText, str_replace(CAKE_CORE_INCLUDE_PATH, '', __FILE__), __LINE__ - 9); <add> $expected = sprintf($expectedText, Debugger::trimPath(__FILE__), __LINE__ - 9); <ide> <ide> $this->assertSame($expected, $result); <ide> <ide> ob_start(); <ide> $value = '<div>this-is-a-test</div>'; <ide> $this->assertSame($value, debug($value, true)); <ide> $result = ob_get_clean(); <del> $expectedHtml = <<<EXPECTED <del><div class="cake-debug-output" style="direction:ltr"> <del><span><strong>%s</strong> (line <strong>%d</strong>)</span> <del><pre class="cake-debug"> <del>&#039;&lt;div&gt;this-is-a-test&lt;/div&gt;&#039; <del></pre> <del></div> <del>EXPECTED; <del> $expected = sprintf($expectedHtml, str_replace(CAKE_CORE_INCLUDE_PATH, '', __FILE__), __LINE__ - 10); <del> $this->assertSame($expected, $result); <add> $this->assertStringContainsString('<div class="cake-debug-output', $result); <add> $this->assertStringContainsString('this-is-a-test', $result); <ide> <ide> ob_start(); <ide> debug('<div>this-is-a-test</div>', true, true); <ide> $result = ob_get_clean(); <ide> $expected = <<<EXPECTED <del><div class="cake-debug-output" style="direction:ltr"> <add><div class="cake-debug-output cake-debug" style="direction:ltr"> <ide> <span><strong>%s</strong> (line <strong>%d</strong>)</span> <del><pre class="cake-debug"> <del>&#039;&lt;div&gt;this-is-a-test&lt;/div&gt;&#039; <del></pre> <del></div> <ide> EXPECTED; <del> $expected = sprintf($expected, str_replace(CAKE_CORE_INCLUDE_PATH, '', __FILE__), __LINE__ - 10); <del> $this->assertSame($expected, $result); <add> $expected = sprintf($expected, Debugger::trimPath(__FILE__), __LINE__ - 6); <add> $this->assertStringContainsString($expected, $result); <ide> <ide> ob_start(); <ide> debug('<div>this-is-a-test</div>', true, false); <ide> $result = ob_get_clean(); <del> $expected = <<<EXPECTED <del><div class="cake-debug-output" style="direction:ltr"> <del> <del><pre class="cake-debug"> <del>&#039;&lt;div&gt;this-is-a-test&lt;/div&gt;&#039; <del></pre> <del></div> <del>EXPECTED; <del> $expected = sprintf($expected, str_replace(CAKE_CORE_INCLUDE_PATH, '', __FILE__), __LINE__ - 10); <del> $this->assertSame($expected, $result); <del> <del> ob_start(); <del> debug('<div>this-is-a-test</div>', null); <del> $result = ob_get_clean(); <del> $expectedHtml = <<<EXPECTED <del><div class="cake-debug-output" style="direction:ltr"> <del><span><strong>%s</strong> (line <strong>%d</strong>)</span> <del><pre class="cake-debug"> <del>&#039;&lt;div&gt;this-is-a-test&lt;/div&gt;&#039; <del></pre> <del></div> <del>EXPECTED; <del> $expectedText = <<<EXPECTED <del>%s (line %d) <del>########## DEBUG ########## <del>'<div>this-is-a-test</div>' <del>########################### <del> <del>EXPECTED; <del> if ((PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg')) { <del> $expected = sprintf($expectedText, str_replace(CAKE_CORE_INCLUDE_PATH, '', __FILE__), __LINE__ - 18); <del> } else { <del> $expected = sprintf($expectedHtml, str_replace(CAKE_CORE_INCLUDE_PATH, '', __FILE__), __LINE__ - 19); <del> } <del> $this->assertSame($expected, $result); <del> <del> ob_start(); <del> debug('<div>this-is-a-test</div>', null, false); <del> $result = ob_get_clean(); <del> $expectedHtml = <<<EXPECTED <del><div class="cake-debug-output" style="direction:ltr"> <del> <del><pre class="cake-debug"> <del>&#039;&lt;div&gt;this-is-a-test&lt;/div&gt;&#039; <del></pre> <del></div> <del>EXPECTED; <del> $expectedText = <<<EXPECTED <del> <del>########## DEBUG ########## <del>'<div>this-is-a-test</div>' <del>########################### <del> <del>EXPECTED; <del> if ((PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg')) { <del> $expected = sprintf($expectedText, str_replace(CAKE_CORE_INCLUDE_PATH, '', __FILE__), __LINE__ - 18); <del> } else { <del> $expected = sprintf($expectedHtml, str_replace(CAKE_CORE_INCLUDE_PATH, '', __FILE__), __LINE__ - 19); <del> } <del> $this->assertSame($expected, $result); <del> <del> ob_start(); <del> debug('<div>this-is-a-test</div>', false); <del> $result = ob_get_clean(); <del> $expected = <<<EXPECTED <del>%s (line %d) <del>########## DEBUG ########## <del>'<div>this-is-a-test</div>' <del>########################### <del> <del>EXPECTED; <del> $expected = sprintf($expected, str_replace(CAKE_CORE_INCLUDE_PATH, '', __FILE__), __LINE__ - 9); <del> $this->assertSame($expected, $result); <del> <del> ob_start(); <del> debug('<div>this-is-a-test</div>', false, true); <del> $result = ob_get_clean(); <del> $expected = <<<EXPECTED <del>%s (line %d) <del>########## DEBUG ########## <del>'<div>this-is-a-test</div>' <del>########################### <del> <del>EXPECTED; <del> $expected = sprintf($expected, str_replace(CAKE_CORE_INCLUDE_PATH, '', __FILE__), __LINE__ - 9); <del> $this->assertSame($expected, $result); <del> <del> ob_start(); <del> debug('<div>this-is-a-test</div>', false, false); <del> $result = ob_get_clean(); <del> $expected = <<<EXPECTED <del> <del>########## DEBUG ########## <del>'<div>this-is-a-test</div>' <del>########################### <del> <del>EXPECTED; <del> $expected = sprintf($expected, str_replace(CAKE_CORE_INCLUDE_PATH, '', __FILE__), __LINE__ - 9); <del> $this->assertSame($expected, $result); <del> <del> ob_start(); <del> $this->assertFalse(debug(false, false, false)); <del> $result = ob_get_clean(); <del> $expected = <<<EXPECTED <del> <del>########## DEBUG ########## <del>false <del>########################### <del> <del>EXPECTED; <del> $expected = sprintf($expected, str_replace(CAKE_CORE_INCLUDE_PATH, '', __FILE__), __LINE__ - 9); <del> $this->assertSame($expected, $result); <add> $this->assertStringNotContainsString('(line', $result); <ide> } <ide> <ide> /**
6
Ruby
Ruby
create generic codesign_patched_binary
39fc3862538fa5226f4d17e94f1e1c74b7eadeb2
<ide><path>Library/Homebrew/keg_relocate.rb <ide> def each_unique_binary_file(&block) <ide> end <ide> end <ide> <add> def codesign_patched_binary(_binary_file); end <add> <ide> def lib <ide> path/"lib" <ide> end
1
Ruby
Ruby
permit loads while queries are running
007e50d8e5a900547471b6c4ec79d9d217682c5d
<ide><path>activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb <ide> def explain(arel, binds = []) <ide> <ide> # Executes the SQL statement in the context of this connection. <ide> def execute(sql, name = nil) <del> log(sql, name) { @connection.query(sql) } <add> log(sql, name) do <add> ActiveSupport::Dependencies.interlock.permit_concurrent_loads do <add> @connection.query(sql) <add> end <add> end <ide> end <ide> <ide> # Mysql2Adapter doesn't have to free a result after using it, but we use this method <ide><path>activerecord/lib/active_record/connection_adapters/mysql/database_statements.rb <ide> def exec_stmt_and_free(sql, name, binds, cache_stmt: false) <ide> end <ide> <ide> begin <del> result = stmt.execute(*type_casted_binds) <add> ActiveSupport::Dependencies.interlock.permit_concurrent_loads do <add> result = stmt.execute(*type_casted_binds) <add> end <ide> rescue Mysql2::Error => e <ide> if cache_stmt <ide> @statements.delete(sql) <ide><path>activerecord/lib/active_record/connection_adapters/postgresql/database_statements.rb <ide> def result_as_array(res) #:nodoc: <ide> # Queries the database and returns the results in an Array-like object <ide> def query(sql, name = nil) #:nodoc: <ide> log(sql, name) do <del> result_as_array @connection.async_exec(sql) <add> ActiveSupport::Dependencies.interlock.permit_concurrent_loads do <add> result_as_array @connection.async_exec(sql) <add> end <ide> end <ide> end <ide> <ide> def query(sql, name = nil) #:nodoc: <ide> # need it specifically, you may want consider the <tt>exec_query</tt> wrapper. <ide> def execute(sql, name = nil) <ide> log(sql, name) do <del> @connection.async_exec(sql) <add> ActiveSupport::Dependencies.interlock.permit_concurrent_loads do <add> @connection.async_exec(sql) <add> end <ide> end <ide> end <ide> <ide><path>activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb <ide> def execute_and_clear(sql, name, binds, prepare: false) <ide> <ide> def exec_no_cache(sql, name, binds) <ide> type_casted_binds = type_casted_binds(binds) <del> log(sql, name, binds, type_casted_binds) { @connection.async_exec(sql, type_casted_binds) } <add> log(sql, name, binds, type_casted_binds) do <add> ActiveSupport::Dependencies.interlock.permit_concurrent_loads do <add> @connection.async_exec(sql, type_casted_binds) <add> end <add> end <ide> end <ide> <ide> def exec_cache(sql, name, binds) <ide> stmt_key = prepare_statement(sql) <ide> type_casted_binds = type_casted_binds(binds) <ide> <ide> log(sql, name, binds, type_casted_binds, stmt_key) do <del> @connection.exec_prepared(stmt_key, type_casted_binds) <add> ActiveSupport::Dependencies.interlock.permit_concurrent_loads do <add> @connection.exec_prepared(stmt_key, type_casted_binds) <add> end <ide> end <ide> rescue ActiveRecord::StatementInvalid => e <ide> raise unless is_cached_plan_failure?(e) <ide><path>activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb <ide> def exec_query(sql, name = nil, binds = [], prepare: false) <ide> type_casted_binds = type_casted_binds(binds) <ide> <ide> log(sql, name, binds, type_casted_binds) do <del> # Don't cache statements if they are not prepared <del> unless prepare <del> stmt = @connection.prepare(sql) <del> begin <del> cols = stmt.columns <del> unless without_prepared_statement?(binds) <del> stmt.bind_params(type_casted_binds) <add> ActiveSupport::Dependencies.interlock.permit_concurrent_loads do <add> # Don't cache statements if they are not prepared <add> unless prepare <add> stmt = @connection.prepare(sql) <add> begin <add> cols = stmt.columns <add> unless without_prepared_statement?(binds) <add> stmt.bind_params(type_casted_binds) <add> end <add> records = stmt.to_a <add> ensure <add> stmt.close <ide> end <add> else <add> cache = @statements[sql] ||= { <add> stmt: @connection.prepare(sql) <add> } <add> stmt = cache[:stmt] <add> cols = cache[:cols] ||= stmt.columns <add> stmt.reset! <add> stmt.bind_params(type_casted_binds) <ide> records = stmt.to_a <del> ensure <del> stmt.close <ide> end <del> else <del> cache = @statements[sql] ||= { <del> stmt: @connection.prepare(sql) <del> } <del> stmt = cache[:stmt] <del> cols = cache[:cols] ||= stmt.columns <del> stmt.reset! <del> stmt.bind_params(type_casted_binds) <del> records = stmt.to_a <ide> end <ide> <ide> ActiveRecord::Result.new(cols, records) <ide> def last_inserted_id(result) <ide> end <ide> <ide> def execute(sql, name = nil) #:nodoc: <del> log(sql, name) { @connection.execute(sql) } <add> log(sql, name) do <add> ActiveSupport::Dependencies.interlock.permit_concurrent_loads do <add> @connection.execute(sql) <add> end <add> end <ide> end <ide> <ide> def begin_db_transaction #:nodoc:
5
Ruby
Ruby
adjust initializer signature
497123f7ecc6b82225b0c0afc81b2411679d64cc
<ide><path>Library/Homebrew/requirements/ld64_dependency.rb <ide> # formula is used as gcc's ld in place of the old version <ide> # that comes with the OS. <ide> class LD64Dependency < Dependency <del> def initialize(name='ld64', tags=[:build]) <add> def initialize(name='ld64', tags=[:build], env_proc=nil) <ide> @env_proc = proc { ENV.ld64 } <ide> super <ide> end
1
Javascript
Javascript
expose getresolvermainfields() config param
39d9d71adbb77eff543fe442bd3061edc9858dd6
<ide><path>local-cli/bundle/buildBundle.js <ide> async function buildBundle( <ide> extraNodeModules: config.extraNodeModules, <ide> getModulesRunBeforeMainModule: config.getModulesRunBeforeMainModule, <ide> getPolyfills: config.getPolyfills, <add> getResolverMainFields: config.getResolverMainFields, <ide> getRunModuleStatement: config.getRunModuleStatement, <ide> getTransformOptions: config.getTransformOptions, <ide> hasteImplModulePath: config.hasteImplModulePath, <ide><path>local-cli/server/runServer.js <ide> function getPackagerServer(args, config, reporter) { <ide> dynamicDepsInPackages: config.dynamicDepsInPackages, <ide> getModulesRunBeforeMainModule: config.getModulesRunBeforeMainModule, <ide> getPolyfills: config.getPolyfills, <add> getResolverMainFields: config.getResolverMainFields, <ide> getRunModuleStatement: config.getRunModuleStatement, <ide> getTransformOptions: config.getTransformOptions, <ide> hasteImplModulePath: config.hasteImplModulePath, <ide><path>local-cli/util/Config.js <ide> const Config = { <ide> DEFAULT: ({ <ide> ...MetroConfig.DEFAULT, <ide> getBlacklistRE, <del> getProjectRoots, <del> getPolyfills, <ide> getModulesRunBeforeMainModule: () => [ <ide> require.resolve('../../Libraries/Core/InitializeCore'), <ide> ], <add> getProjectRoots, <add> getPolyfills, <add> getResolverMainFields: () => ['react-native', 'browser', 'main'], <ide> getTransformModulePath: () => <ide> require.resolve('metro/src/reactNativeTransformer'), <ide> }: ConfigT),
3
Python
Python
add fp16 support for sagemaker model parallel
1690094bdb8f606685e46f26c17ddadb925d0a20
<ide><path>src/transformers/trainer.py <ide> def __init__( <ide> self.use_cuda_amp = False <ide> self.use_cpu_amp = False <ide> <add> # Mixed precision setup for SageMaker Model Parallel <add> if is_sagemaker_mp_enabled(): <add> # BF16 + model parallelism in SageMaker: currently not supported, raise an error <add> if args.bf16: <add> raise ValueError("SageMaker Model Parallelism does not support BF16 yet. Please use FP16 instead ") <add> # When there's mismatch between SMP config and trainer argument, use SMP config as truth <add> if args.fp16 != smp.state.cfg.fp16: <add> logger.warning( <add> f"FP16 provided in SM_HP_MP_PARAMETERS is {smp.state.cfg.fp16}," <add> f"but FP16 provided in trainer argument is {args.fp16}," <add> f"setting to {smp.state.cfg.fp16}" <add> ) <add> args.fp16 = smp.state.cfg.fp16 <add> <ide> if args.fp16 or args.bf16: <ide> if self.fsdp is not None: <ide> raise ValueError( <ide> def __init__( <ide> logger.info(f"Using {args.half_precision_backend} half precision backend") <ide> <ide> self.do_grad_scaling = False <del> if (args.fp16 or args.bf16) and not args.deepspeed: # deepspeed manages its own half precision <add> if (args.fp16 or args.bf16) and not (args.deepspeed or is_sagemaker_mp_enabled()): <add> # deepspeed and SageMaker Model Parallel manage their own half precision <ide> if args.half_precision_backend == "cuda_amp": <ide> self.use_cuda_amp = True <ide> self.amp_dtype = torch.float16 if args.fp16 else torch.bfloat16 <ide> self.do_grad_scaling = True <del> if is_sagemaker_mp_enabled(): <del> self.scaler = smp.amp.GradScaler() <del> elif self.sharded_ddp is not None: <add> if self.sharded_ddp is not None: <ide> self.scaler = ShardedGradScaler() <ide> elif is_torch_tpu_available(): <ide> from torch_xla.amp import GradScaler <ide> def __init__( <ide> ) <ide> self.use_apex = True <ide> <del> # FP16 + model parallelism in SageMaker: gradient clipping does not work for now so we raise a helpful error. <del> if ( <del> is_sagemaker_mp_enabled() <del> and self.use_cuda_amp <del> and args.max_grad_norm is not None <del> and args.max_grad_norm > 0 <del> ): <del> raise ValueError( <del> "SageMaker Model Parallelism in mixed precision mode does not support gradient clipping yet. Pass " <del> "along 'max_grad_norm': 0 in your hyperparameters." <del> ) <del> <ide> # Label smoothing <ide> if self.args.label_smoothing_factor != 0: <ide> self.label_smoother = LabelSmoother(epsilon=self.args.label_smoothing_factor) <ide> def create_optimizer_and_scheduler(self, num_training_steps: int): <ide> `create_scheduler`) in a subclass. <ide> """ <ide> self.create_optimizer() <del> self.create_scheduler(num_training_steps=num_training_steps, optimizer=self.optimizer) <add> self.create_scheduler( <add> num_training_steps=num_training_steps, <add> optimizer=self.optimizer.optimizer if is_sagemaker_mp_enabled() and smp.state.cfg.fp16 else self.optimizer, <add> ) <ide> <ide> def create_optimizer(self): <ide> """ <ide> def _inner_training_loop( <ide> # AMP: gradients need unscaling <ide> self.scaler.unscale_(self.optimizer) <ide> <del> if hasattr(self.optimizer, "clip_grad_norm"): <add> if is_sagemaker_mp_enabled() and args.fp16: <add> self.optimizer.clip_master_grads(args.max_grad_norm) <add> elif hasattr(self.optimizer, "clip_grad_norm"): <ide> # Some optimizers (like the sharded optimizer) have a specific way to do gradient clipping <ide> self.optimizer.clip_grad_norm(args.max_grad_norm) <ide> elif hasattr(model, "clip_grad_norm_"): <ide> def _load_optimizer_and_scheduler(self, checkpoint): <ide> if is_sagemaker_mp_enabled(): <ide> <ide> def opt_load_hook(mod, opt): <del> opt.load_state_dict(smp.load(os.path.join(checkpoint, OPTIMIZER_NAME), partial=True)) <add> opt.load_state_dict( <add> smp.load(os.path.join(checkpoint, OPTIMIZER_NAME), partial=True), gather_if_shard=False <add> ) <ide> <ide> self.model_wrapped.register_post_step_hook(opt_load_hook) <ide> else: <ide> def training_step(self, model: nn.Module, inputs: Dict[str, Union[torch.Tensor, <ide> inputs = self._prepare_inputs(inputs) <ide> <ide> if is_sagemaker_mp_enabled(): <del> scaler = self.scaler if self.do_grad_scaling else None <del> loss_mb = smp_forward_backward(model, inputs, self.args.gradient_accumulation_steps, scaler=scaler) <add> loss_mb = smp_forward_backward(model, inputs, self.args.gradient_accumulation_steps) <ide> return loss_mb.reduce_mean().detach().to(self.args.device) <ide> <ide> with self.compute_loss_context_manager(): <ide><path>src/transformers/trainer_pt_utils.py <ide> def get_parameter_names(model, forbidden_layer_types): <ide> import smdistributed.modelparallel.torch as smp <ide> <ide> @smp.step() <del> def smp_forward_backward(model, inputs, gradient_accumulation_steps=1, scaler=None): <del> with torch.cuda.amp.autocast(enabled=(scaler is not None)): <del> outputs = model(**inputs) <del> <add> def smp_forward_backward(model, inputs, gradient_accumulation_steps=1): <add> outputs = model(**inputs) <ide> loss = outputs["loss"] if isinstance(outputs, dict) else outputs[0] <ide> loss /= gradient_accumulation_steps <del> if scaler is not None: <del> loss = scaler.scale(loss).squeeze() <del> <ide> model.backward(loss) <ide> return loss <ide>
2
PHP
PHP
add coverage for deprecated method
b6d499b998997e1c0cb3ce977852da5e24f9c87f
<ide><path>tests/TestCase/Routing/Route/RouteTest.php <ide> public function testNoMatchParseExtension($url, array $ext) <ide> $this->assertNull($outExt); <ide> } <ide> <add> /** <add> * Expects extensions to be set <add> * <add> * @group deprecated <add> * @return void <add> */ <add> public function testExtensions() <add> { <add> $this->deprecated(function () { <add> $route = new RouteProtected('/:controller/:action/*', []); <add> $this->assertEquals([], $route->extensions()); <add> $route->extensions(['xml']); <add> <add> $this->assertEquals(['xml'], $route->extensions()); <add> }); <add> } <add> <ide> /** <ide> * Expects extensions to be set <ide> *
1
Text
Text
fix grammatical issues in readme.md
87eccd46be416ae97c23b1e72c898cf7d3b2beef
<ide><path>README.md <ide> The first section will teach you the basics of how webpages work and also introd <ide> <ide> Skills you'll practice include `HTML, CSS, JavaScript, jQuery` and `Bootstrap`. <ide> <del>To earn this certification you'll build **10 front-end projects** and implement many **JavaScript algorithms** <add>To earn this certification, you'll build **10 front-end projects** and implement many **JavaScript algorithms**. <ide> <ide> ##### 2. Data Visualization Certification <del>The second section builds upon the first and introduce you to more advanced topics such as `Sass, React` and `D3`. <add>The second section builds upon the first and introduces you to more advanced topics such as `Sass, React` and `D3`. <ide> <del>To earn this certification you'll build **5 React-apps** and **5 Data visualization apps** using `D3.js`. <add>To earn this certification, you'll build **5 React-apps** and **5 Data visualization apps** using `D3.js`. <ide> <ide> ##### 3. Back End Certification <del>The third section introduces you to back end development using `Node.js, Express, MongoDB` but also teach you about the important concept of source control using `Git`. <add>The third section introduces you to back end development using `Node.js, Express,` and `MongoDB`. It also teaches you about the important concept of source control using `Git`. <ide> <del>To earn this certification you'll build **5 API:s** and **5 full stack JavaScript apps**. <add>To earn this certification, you'll build **5 APIs** and **5 full stack JavaScript apps**. <ide> <ide> ##### 4. Full Stack Certification <del>The fourth section is where you'll get **real world experience** by working on projects for **Non-profits**. <del>We'll pair you with another camper, an agile project manager, and a stakeholder from a nonprofit organization. Together, you'll plan, build and maintain apps that helps that nonprofit carry out its mission more effectively. <add>The fourth section is where you'll get **real-world experience** by working on projects for **nonprofits**. <add>We'll pair you with another camper, an agile project manager, and a stakeholder from a nonprofit organization. Together, you'll plan, build and maintain apps that help that nonprofit carry out its mission more effectively. <ide> <del>For this certification you'll work on **two projects from scratch** and then **maintain/upgrade two existing projects**. <add>For this certification, you'll work on **two projects from scratch** and then **maintain/upgrade two existing projects**. <ide> <ide> --- <ide> <ide> Found a bug? <ide> Do not file an issue until you have followed these steps: <ide> <ide> 1. Read [Help I've Found a Bug](https://github.com/FreeCodeCamp/FreeCodeCamp/wiki/Help-I've-Found-a-Bug) wiki page and follow the instructions there. <del>2. Asked for confirmation in the appropriate [Help Room](https://github.com/FreeCodeCamp/FreeCodeCamp/wiki/Help-Rooms) <add>2. Ask for confirmation in the appropriate [Help Room](https://github.com/FreeCodeCamp/FreeCodeCamp/wiki/Help-Rooms). <ide> 3. Please *do not* open an issue without a 3rd party confirmation of your problem. <ide> <ide> Contributing <ide> ------------ <ide> <del>We welcome pull requests from Free Code Camp campers (our students) and seasoned JavaScript developers alike! Please, follow [these steps](CONTRIBUTING.md) to contribute. <add>We welcome pull requests from Free Code Camp campers (our students) and seasoned JavaScript developers alike! Please follow [these steps](CONTRIBUTING.md) to contribute. <ide> <ide> License <ide> -------
1
Ruby
Ruby
fix errorduringexecution status
d345864d7e6f98488ed6fc454c0338bb20b751b2
<ide><path>Library/Homebrew/exceptions.rb <ide> def initialize(cmd, status:, output: nil, secrets: []) <ide> when Integer <ide> status <ide> else <del> status.exitstatus <add> status&.exitstatus <ide> end <ide> <ide> redacted_cmd = redact_secrets(cmd.shelljoin.gsub('\=', "="), secrets) <ide> def initialize(cmd, status:, output: nil, secrets: []) <ide> elsif (uncaught_signal = status.termsig) <ide> "was terminated by uncaught signal #{Signal.signame(uncaught_signal)}" <ide> else <del> raise ArgumentError, "Status does neither have `exitstatus` nor `termsig`." <add> raise ArgumentError, "Status neither has `exitstatus` nor `termsig`." <ide> end <ide> <ide> s = +"Failure while executing; `#{redacted_cmd}` #{reason}."
1
Python
Python
simplify documentation of clip()
40c7e51f61b014f84debf6ad870a8078b6df1be0
<ide><path>numpy/core/fromnumeric.py <ide> def clip(a, a_min, a_max, out=None, **kwargs): <ide> ---------- <ide> a : array_like <ide> Array containing elements to clip. <del> a_min : array_like or None <del> Minimum value. If None, clipping is not performed on lower <del> interval edge. Not more than one of `a_min` and `a_max` may be <del> None. <del> a_max : array_like or None <del> Maximum value. If None, clipping is not performed on upper <del> interval edge. Not more than one of `a_min` and `a_max` may be <del> None. `a_min` and `a_max` are broadcast against `a`. <add> a_min, a_max : array_like or None <add> Minimum and maximum value. If ``None``, clipping is not performed on <add> the corresponding edge. Only one of `a_min` and `a_max` may be <add> ``None``. Both are broadcast against `a`. <ide> out : ndarray, optional <ide> The results will be placed in this array. It may be the input <ide> array for in-place clipping. `out` must be of the right shape
1
Go
Go
fix testrunnonrootuserresolvname flackiness
30d4c70d282248ac218c6c505d5a316e5cc9ac01
<ide><path>integration-cli/docker_cli_run_test.go <ide> func (s *DockerSuite) TestRunDnsOptionsBasedOnHostResolvConf(c *check.C) { <ide> // Test to see if a non-root user can resolve a DNS name and reach out to it. Also <ide> // check if the container resolv.conf file has atleast 0644 perm. <ide> func (s *DockerSuite) TestRunNonRootUserResolvName(c *check.C) { <del> testRequires(c, SameHostDaemon, NativeExecDriver) <del> testRequires(c, Network) <add> testRequires(c, SameHostDaemon, Network) <ide> <del> dockerCmd(c, "run", "--name=testperm", "--user=default", "busybox", "ping", "-c", "1", "www.docker.io") <add> dockerCmd(c, "run", "--name=testperm", "--user=default", "busybox", "ping", "-c", "1", "apt.dockerproject.org") <ide> <ide> cID, err := getIDByName("testperm") <ide> if err != nil {
1
Javascript
Javascript
remove second param to `chunktemplate` constructor
678984b9e435414ec64584679ef752ff537ab6b0
<ide><path>lib/Compilation.js <ide> function Compilation(compiler) { <ide> this.performance = options && options.performance; <ide> <ide> this.mainTemplate = new MainTemplate(this.outputOptions); <del> this.chunkTemplate = new ChunkTemplate(this.outputOptions, this.mainTemplate); <add> this.chunkTemplate = new ChunkTemplate(this.outputOptions); <ide> this.hotUpdateChunkTemplate = new HotUpdateChunkTemplate(this.outputOptions); <ide> this.moduleTemplate = new ModuleTemplate(this.outputOptions); <ide>
1
Javascript
Javascript
add link to built-in filters page
31f20b6db103a2d3dd095c5cd8fa668938adf7bb
<ide><path>src/ng/filter.js <ide> * @name $filter <ide> * @kind function <ide> * @description <del> * Filters are used for formatting data displayed to the user. <add> * Filters are used for formatting data displayed to the user. They can be used in view <add> * templates, controllers or services. Angular comes with a collection of <add> * [built-in filters](api/ng/filter), but it is easy to define your own as well. <ide> * <ide> * The general syntax in templates is as follows: <ide> *
1
Text
Text
update openssl 1.1.0 upgrade docs
160ac0f32513337214dc5a4cdb1fa8de3c2ed14c
<ide><path>deps/openssl/config/README.md <ide> Currently, one floating patch is needed to build S390 asm files. <ide> <ide> Cherry pick it from the previous commit. <ide> ```sh <del>$ git cherry-pick 094465362758ebf967b33c84d5c96230b46a34b3 <add>$ git cherry-pick 45b9f5df6ff1548f01ed646ebee75e3f0873cefd <ide> ``` <ide> ### 3. Execute `make` in `deps/openssl/config` directory <ide> <ide> Just type `make` then it generates all platform dependent files into <ide> $ cd deps/openssl/config; make <ide> ``` <ide> <del>The commit message can be <del>``` <del> commit 8cb1de45c60f2d520551166610115531db673518 <del> Author: Shigeki Ohtsu <ohtsu@ohtsu.org> <del> Date: Thu Mar 29 16:46:11 2018 +0900 <del> <del> deps: update archs files for OpenSSL-1.1.0 <del> <del> `cd deps/openssl/config; make` updates all archs dependant files. <del>``` <ide> ### 4. Check diffs <ide> <ide> Check diffs if updates are right. Even if no updates in openssl <ide> used for `nmake` command. The `make` command in the step 2 above uses <ide> created. When source files or build options are updated in Windows, <ide> it needs to change these two Makefiles by hand. If you are not sure, <ide> please ask @shigeki for details. <add> <ide> ### 5. Commit and make test <ide> <ide> Update all architecture dependent files. Do not forget to git add or remove <del>files if they are changed before commit. <add>files if they are changed before commit: <ide> ```sh <del>$ cd deps/openssl/openssl/config <del>$ git add archs <del>$ git commit archs <add>$ git add deps/openssl/config/archs <add>$ git add deps/openssl/openssl/crypto/include/internal/bn_conf.h <add>$ git add deps/openssl/openssl/crypto/include/internal/dso_conf.h <add>$ git add deps/openssl/openssl/include/openssl/opensslconf.h <add>$ git add deps/openssl/openssl/.gitignore <add>$ git commit <ide> ``` <ide> <ide> The commit message can be <ide> The commit message can be <ide> Date: Thu Mar 29 16:46:11 2018 +0900 <ide> <ide> deps: update archs files for OpenSSL-1.1.0 <add> <add> `cd deps/openssl/config; make` updates all archs dependant files. <ide> ``` <ide> <ide> Finally, build Node and run tests.
1
Javascript
Javascript
remove selected attribute from unselected options
b4769c371ecb79ebcd02183373c214c20aa31e41
<ide><path>src/ng/directive/ngOptions.js <ide> var ngOptionsDirective = ['$compile', '$document', '$parse', function($compile, <ide> var removeEmptyOption = function() { <ide> if (!providedEmptyOption) { <ide> emptyOption.remove(); <add> } else { <add> emptyOption.removeAttr('selected'); <ide> } <ide> }; <ide> <del> <ide> var renderUnknownOption = function() { <ide> selectElement.prepend(unknownOption); <ide> selectElement.val('?'); <ide> var ngOptionsDirective = ['$compile', '$document', '$parse', function($compile, <ide> if (!multiple) { <ide> <ide> selectCtrl.writeValue = function writeNgOptionsValue(value) { <add> var selectedOption = options.selectValueMap[selectElement.val()]; <ide> var option = options.getOptionFromViewValue(value); <ide> <add> // Make sure to remove the selected attribute from the previously selected option <add> // Otherwise, screen readers might get confused <add> if (selectedOption) selectedOption.element.removeAttribute('selected'); <add> <ide> if (option) { <ide> // Don't update the option when it is already selected. <ide> // For example, the browser will select the first option by default. In that case, <ide> var ngOptionsDirective = ['$compile', '$document', '$parse', function($compile, <ide> <ide> // If we are using `track by` then we must watch the tracked value on the model <ide> // since ngModel only watches for object identity change <add> // FIXME: When a user selects an option, this watch will fire needlessly <ide> if (ngOptions.trackBy) { <ide> scope.$watch( <ide> function() { return ngOptions.getTrackByValue(ngModelCtrl.$viewValue); }, <ide><path>test/ng/directive/ngOptionsSpec.js <ide> describe('ngOptions', function() { <ide> return { pass: errors.length === 0, message: message }; <ide> } <ide> }; <add> }, <add> toBeMarkedAsSelected: function() { <add> // Selected is special because the element property and attribute reflect each other's state. <add> // IE9 will wrongly report hasAttribute('selected') === true when the property is <add> // undefined or null, and the dev tools show that no attribute is set <add> return { <add> compare: function(actual) { <add> var errors = []; <add> if (actual.selected === null || typeof actual.selected === 'undefined' || actual.selected === false) { <add> errors.push('Expected option property "selected" to be truthy'); <add> } <add> <add> if (msie !== 9 && actual.hasAttribute('selected') === false) { <add> errors.push('Expected option to have attribute "selected"'); <add> } <add> <add> var result = { <add> pass: errors.length === 0, <add> message: errors.join('\n') <add> }; <add> <add> return result; <add> }, <add> negativeCompare: function(actual) { <add> var errors = []; <add> if (actual.selected) { <add> errors.push('Expected option property "selected" to be falsy'); <add> } <add> <add> if (msie !== 9 && actual.hasAttribute('selected')) { <add> errors.push('Expected option not to have attribute "selected"'); <add> } <add> <add> var result = { <add> pass: errors.length === 0, <add> message: errors.join('\n') <add> }; <add> <add> return result; <add> } <add> }; <ide> } <ide> }); <ide> }); <ide> describe('ngOptions', function() { <ide> }); <ide> <ide> <add> it('should remove the "selected" attribute from the previous option when the model changes', function() { <add> scope.values = [{id: 10, label: 'ten'}, {id:20, label: 'twenty'}]; <add> <add> createSelect({ <add> 'ng-model': 'selected', <add> 'ng-options': 'item.label for item in values' <add> }, true); <add> <add> var options = element.find('option'); <add> expect(options[0]).toBeMarkedAsSelected(); <add> expect(options[1]).not.toBeMarkedAsSelected(); <add> expect(options[2]).not.toBeMarkedAsSelected(); <add> <add> scope.selected = scope.values[0]; <add> scope.$digest(); <add> <add> expect(options[0]).not.toBeMarkedAsSelected(); <add> expect(options[1]).toBeMarkedAsSelected(); <add> expect(options[2]).not.toBeMarkedAsSelected(); <add> <add> scope.selected = scope.values[1]; <add> scope.$digest(); <add> <add> expect(options[0]).not.toBeMarkedAsSelected(); <add> expect(options[1]).not.toBeMarkedAsSelected(); <add> expect(options[2]).toBeMarkedAsSelected(); <add> <add> scope.selected = 'no match'; <add> scope.$digest(); <add> <add> expect(options[0]).toBeMarkedAsSelected(); <add> expect(options[1]).not.toBeMarkedAsSelected(); <add> expect(options[2]).not.toBeMarkedAsSelected(); <add> }); <add> <ide> describe('disableWhen expression', function() { <ide> <ide> describe('on single select', function() { <ide> describe('ngOptions', function() { <ide> }); <ide> }).not.toThrow(); <ide> }); <add> <add> it('should remove the "selected" attribute when the model changes', function() { <add> createSelect({ <add> 'ng-model': 'selected', <add> 'ng-options': 'item.label for item in arr track by item.id' <add> }); <add> <add> var options = element.find('option'); <add> browserTrigger(options[2], 'click'); <add> <add> expect(scope.selected).toEqual(scope.arr[1]); <add> <add> scope.selected = {}; <add> scope.$digest(); <add> <add> expect(options[0]).toBeMarkedAsSelected(); <add> expect(options[2]).not.toBeMarkedAsSelected(); <add> expect(options[2]).not.toBeMarkedAsSelected(); <add> }); <add> <ide> }); <ide> <ide>
2
Javascript
Javascript
remove default export from controllers/index
37633c221ac41b4a4cbcc5093b2049c83bee19b8
<ide><path>src/controllers/index.js <del>import bar from './controller.bar'; <del>import bubble from './controller.bubble'; <del>import doughnut from './controller.doughnut'; <del>import horizontalBar from './controller.horizontalBar'; <del>import line from './controller.line'; <del>import polarArea from './controller.polarArea'; <del>import pie from './controller.pie'; <del>import radar from './controller.radar'; <del>import scatter from './controller.scatter'; <del> <del>// NOTE export a map in which the key represents the controller type, not <del>// the class, and so must be CamelCase in order to be correctly retrieved <del>// by the controller in core.controller.js (`controllers[meta.type]`). <del> <del>export default { <del> bar, <del> bubble, <del> doughnut, <del> horizontalBar, <del> line, <del> polarArea, <del> pie, <del> radar, <del> scatter <del>}; <add>export {default as bar} from './controller.bar'; <add>export {default as bubble} from './controller.bubble'; <add>export {default as doughnut} from './controller.doughnut'; <add>export {default as horizontalBar} from './controller.horizontalBar'; <add>export {default as line} from './controller.line'; <add>export {default as polarArea} from './controller.polarArea'; <add>export {default as pie} from './controller.pie'; <add>export {default as radar} from './controller.radar'; <add>export {default as scatter} from './controller.scatter'; <ide><path>src/core/core.controller.js <del>import Animator from './core.animator'; <del>import controllers from '../controllers/index'; <add>/* eslint-disable import/no-namespace, import/namespace */ <add>import {default as Animator} from './core.animator'; <add>import * as controllers from '../controllers'; <ide> import defaults from './core.defaults'; <ide> import Interaction from './core.interaction'; <ide> import layouts from './core.layouts'; <ide><path>src/index.js <ide> import Chart from './core/core.controller'; <ide> import helpers from './helpers/index'; <ide> import _adapters from './core/core.adapters'; <ide> import Animation from './core/core.animation'; <del>import Animator from './core/core.animator'; <add>import {default as Animator} from './core/core.animator'; <ide> import animationService from './core/core.animations'; <del>import controllers from './controllers/index'; <add>import * as controllers from './controllers'; <ide> import DatasetController from './core/core.datasetController'; <ide> import defaults from './core/core.defaults'; <ide> import Element from './core/core.element';
3
PHP
PHP
fix wrong component generation
73060db7c5541fadf5e4f2874a89d18621d705a3
<ide><path>src/Illuminate/Foundation/Console/ComponentMakeCommand.php <ide> protected function buildClass($name) <ide> */ <ide> protected function getView() <ide> { <del> return collect(explode('/', $this->argument('name'))) <add> $name = str_replace('\\', '/', $this->argument('name')); <add> <add> return collect(explode('/', $name)) <ide> ->map(function ($part) { <ide> return Str::kebab($part); <ide> })
1
Ruby
Ruby
improve name detection of anonymous subclasses
f12442cce676bf88fca8dc56c2bd430171c346c6
<ide><path>Library/Homebrew/requirement.rb <ide> def mktemp(&block) <ide> private <ide> <ide> def infer_name <del> klass = self.class.name || self.class.to_s <del> klass = klass.sub(/(Dependency|Requirement)$/, "") <del> .sub(/^(\w+::)*/, "") <add> klass = self.class.name <add> klass = klass&.sub(/(Dependency|Requirement)$/, "") <add> &.sub(/^(\w+::)*/, "") <ide> return klass.downcase if klass.present? <ide> <ide> return @cask if @cask.present?
1
PHP
PHP
shorten constant names
0863a51455ff12ccc16a1aa15903f5152a446fcb
<ide><path>src/Validation/Validation.php <ide> class Validation <ide> * <ide> * @var string <ide> */ <del> const COMPARE_GREATER_THAN_OR_EQUAL_TO = '>='; <add> const COMPARE_GREATER_OR_EQUAL = '>='; <ide> <ide> /** <ide> * Less than comparison operator. <ide> class Validation <ide> * <ide> * @var string <ide> */ <del> const COMPARE_LESS_THAN_OR_EQUAL_TO = '<='; <add> const COMPARE_LESS_OR_EQUAL = '<='; <ide> <ide> /** <ide> * Some complex patterns needed in multiple places <ide> public static function comparison($check1, $operator, $check2) <ide> } <ide> break; <ide> case 'greaterorequal': <del> case static::COMPARE_GREATER_THAN_OR_EQUAL_TO: <add> case static::COMPARE_GREATER_OR_EQUAL: <ide> if ($check1 >= $check2) { <ide> return true; <ide> } <ide> break; <ide> case 'lessorequal': <del> case static::COMPARE_LESS_THAN_OR_EQUAL_TO: <add> case static::COMPARE_LESS_OR_EQUAL: <ide> if ($check1 <= $check2) { <ide> return true; <ide> } <ide> public static function uploadedFile($file, array $options = []) <ide> if ($options['optional'] && $error === UPLOAD_ERR_NO_FILE) { <ide> return true; <ide> } <del> if (isset($options['minSize']) && !static::fileSize($file, static::COMPARE_GREATER_THAN_OR_EQUAL_TO, $options['minSize'])) { <add> if (isset($options['minSize']) && !static::fileSize($file, static::COMPARE_GREATER_OR_EQUAL, $options['minSize'])) { <ide> return false; <ide> } <del> if (isset($options['maxSize']) && !static::fileSize($file, static::COMPARE_LESS_THAN_OR_EQUAL_TO, $options['maxSize'])) { <add> if (isset($options['maxSize']) && !static::fileSize($file, static::COMPARE_LESS_OR_EQUAL, $options['maxSize'])) { <ide> return false; <ide> } <ide> if (isset($options['types']) && !static::mimeType($file, $options['types'])) { <ide><path>src/Validation/Validator.php <ide> public function greaterThanOrEqual($field, $value, $message = null, $when = null <ide> $extra = array_filter(['on' => $when, 'message' => $message]); <ide> <ide> return $this->add($field, 'greaterThanOrEqual', $extra + [ <del> 'rule' => ['comparison', Validation::COMPARE_GREATER_THAN_OR_EQUAL_TO, $value] <add> 'rule' => ['comparison', Validation::COMPARE_GREATER_OR_EQUAL, $value] <ide> ]); <ide> } <ide> <ide> public function lessThanOrEqual($field, $value, $message = null, $when = null) <ide> $extra = array_filter(['on' => $when, 'message' => $message]); <ide> <ide> return $this->add($field, 'lessThanOrEqual', $extra + [ <del> 'rule' => ['comparison', Validation::COMPARE_LESS_THAN_OR_EQUAL_TO, $value] <add> 'rule' => ['comparison', Validation::COMPARE_LESS_OR_EQUAL, $value] <ide> ]); <ide> } <ide> <ide> public function greaterThanOrEqualToField($field, $secondField, $message = null, <ide> $extra = array_filter(['on' => $when, 'message' => $message]); <ide> <ide> return $this->add($field, 'greaterThanOrEqualToField', $extra + [ <del> 'rule' => ['compareFields', $secondField, Validation::COMPARE_GREATER_THAN_OR_EQUAL_TO] <add> 'rule' => ['compareFields', $secondField, Validation::COMPARE_GREATER_OR_EQUAL] <ide> ]); <ide> } <ide> <ide> public function lessThanOrEqualToField($field, $secondField, $message = null, $w <ide> $extra = array_filter(['on' => $when, 'message' => $message]); <ide> <ide> return $this->add($field, 'lessThanOrEqualToField', $extra + [ <del> 'rule' => ['compareFields', $secondField, Validation::COMPARE_LESS_THAN_OR_EQUAL_TO] <add> 'rule' => ['compareFields', $secondField, Validation::COMPARE_LESS_OR_EQUAL] <ide> ]); <ide> } <ide> <ide> public function hasAtLeast($field, $count, $message = null, $when = null) <ide> $value = $value['_ids']; <ide> } <ide> <del> return Validation::numElements($value, Validation::COMPARE_GREATER_THAN_OR_EQUAL_TO, $count); <add> return Validation::numElements($value, Validation::COMPARE_GREATER_OR_EQUAL, $count); <ide> } <ide> ]); <ide> } <ide> public function hasAtMost($field, $count, $message = null, $when = null) <ide> $value = $value['_ids']; <ide> } <ide> <del> return Validation::numElements($value, Validation::COMPARE_LESS_THAN_OR_EQUAL_TO, $count); <add> return Validation::numElements($value, Validation::COMPARE_LESS_OR_EQUAL, $count); <ide> } <ide> ]); <ide> }
2
Javascript
Javascript
destroy child scope when destroying dom
9483373c331343648e079420b3eb1f564d410ff2
<ide><path>src/ng/directive/ngIf.js <ide> var ngIfDirective = ['$animate', function($animate) { <ide> $$tlb: true, <ide> compile: function (element, attr, transclude) { <ide> return function ($scope, $element, $attr) { <del> var block = {}, childScope; <add> var block, childScope; <ide> $scope.$watch($attr.ngIf, function ngIfWatchAction(value) { <del> if (block.startNode) { <del> $animate.leave(getBlockElements(block)); <del> block = {}; <del> } <del> if (block.startNode) { <del> getBlockElements(block).$destroy(); <del> block = {}; <del> } <add> <ide> if (toBoolean(value)) { <add> <ide> childScope = $scope.$new(); <ide> transclude(childScope, function (clone) { <del> block.startNode = clone[0]; <del> block.endNode = clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' '); <add> block = { <add> startNode: clone[0], <add> endNode: clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' ') <add> }; <ide> $animate.enter(clone, $element.parent(), $element); <ide> }); <add> <add> } else { <add> <add> if (childScope) { <add> childScope.$destroy(); <add> childScope = null; <add> } <add> <add> if (block) { <add> $animate.leave(getBlockElements(block)); <add> block = null; <add> } <ide> } <ide> }); <ide> }; <ide><path>test/ng/directive/ngIfSpec.js <ide> describe('ngIf', function () { <ide> expect(element.children().length).toBe(0); <ide> }); <ide> <del> it('should create a new scope', function () { <add> it('should create a new scope every time the expression evaluates to true', function () { <ide> $scope.$apply('value = true'); <ide> element.append($compile( <ide> '<div ng-if="value"><span ng-init="value=false"></span></div>' <ide> describe('ngIf', function () { <ide> expect(element.children('div').length).toBe(1); <ide> }); <ide> <add> it('should destroy the child scope every time the expression evaluates to false', function() { <add> $scope.value = true; <add> element.append($compile( <add> '<div ng-if="value"></div>' <add> )($scope)); <add> $scope.$apply(); <add> <add> var childScope = element.children().scope(); <add> var destroyed = false; <add> <add> childScope.$on('$destroy', function() { <add> destroyed = true; <add> }); <add> <add> $scope.value = false; <add> $scope.$apply(); <add> <add> expect(destroyed).toBe(true); <add> }); <add> <ide> it('should play nice with other elements beside it', function () { <ide> $scope.values = [1, 2, 3, 4]; <ide> element.append($compile(
2
Java
Java
fix spel compilation of constructor invocation
aae221cb159b9b0de4d4bc7cc0174d12a015b510
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/CodeFlow.java <ide> package org.springframework.expression.spel; <ide> <ide> import java.lang.reflect.Constructor; <add>import java.lang.reflect.Member; <ide> import java.lang.reflect.Method; <ide> import java.util.ArrayList; <ide> import java.util.List; <ide> public static void insertNewArrayCode(MethodVisitor mv, int size, String arrayty <ide> * packaged into an array. <ide> * @param mv the method visitor where code should be generated <ide> * @param cf the current codeflow <del> * @param method the method for which arguments are being setup <add> * @param member the method or constructor for which arguments are being setup <ide> * @param arguments the expression nodes for the expression supplied argument values <ide> */ <del> public static void generateCodeForArguments(MethodVisitor mv, CodeFlow cf, Method method, SpelNodeImpl[] arguments) { <del> String[] paramDescriptors = CodeFlow.toParamDescriptors(method); <del> if (method.isVarArgs()) { <add> public static void generateCodeForArguments(MethodVisitor mv, CodeFlow cf, Member member, SpelNodeImpl[] arguments) { <add> String[] paramDescriptors = null; <add> boolean isVarargs = false; <add> if (member instanceof Constructor) { <add> Constructor<?> ctor = (Constructor<?>)member; <add> paramDescriptors = toDescriptors(ctor.getParameterTypes()); <add> isVarargs = ctor.isVarArgs(); <add> } <add> else { // Method <add> Method method = (Method)member; <add> paramDescriptors = toDescriptors(method.getParameterTypes()); <add> isVarargs = method.isVarArgs(); <add> } <add> if (isVarargs) { <ide> // The final parameter may or may not need packaging into an array, or nothing may <ide> // have been passed to satisfy the varargs and so something needs to be built. <ide> int p = 0; // Current supplied argument being processed <ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/ConstructorReference.java <ide> public boolean isCompilable() { <ide> <ide> ReflectiveConstructorExecutor executor = (ReflectiveConstructorExecutor) this.cachedExecutor; <ide> Constructor<?> constructor = executor.getConstructor(); <del> return (!constructor.isVarArgs() && Modifier.isPublic(constructor.getModifiers()) && <add> return (Modifier.isPublic(constructor.getModifiers()) && <ide> Modifier.isPublic(constructor.getDeclaringClass().getModifiers())); <ide> } <ide> <ide> @Override <ide> public void generateCode(MethodVisitor mv, CodeFlow cf) { <ide> ReflectiveConstructorExecutor executor = ((ReflectiveConstructorExecutor) this.cachedExecutor); <del> Constructor<?> constructor = executor.getConstructor(); <del> <add> Constructor<?> constructor = executor.getConstructor(); <ide> String classSlashedDescriptor = constructor.getDeclaringClass().getName().replace('.', '/'); <del> String[] paramDescriptors = CodeFlow.toParamDescriptors(constructor); <ide> mv.visitTypeInsn(NEW, classSlashedDescriptor); <ide> mv.visitInsn(DUP); <del> for (int c = 1; c < this.children.length; c++) { // children[0] is the type of the constructor <del> SpelNodeImpl child = this.children[c]; <del> cf.enterCompilationScope(); <del> child.generateCode(mv, cf); <del> // Check if need to box it for the method reference? <del> if (CodeFlow.isPrimitive(cf.lastDescriptor()) && paramDescriptors[c-1].charAt(0) == 'L') { <del> CodeFlow.insertBoxIfNecessary(mv, cf.lastDescriptor().charAt(0)); <del> } <del> cf.exitCompilationScope(); <del> } <add> // children[0] is the type of the constructor, don't want to include that in argument processing <add> SpelNodeImpl[] arguments = new SpelNodeImpl[children.length-1]; <add> System.arraycopy(children, 1, arguments, 0, children.length-1); <add> CodeFlow.generateCodeForArguments(mv, cf, constructor, arguments); <ide> mv.visitMethodInsn(INVOKESPECIAL, classSlashedDescriptor, "<init>", <ide> CodeFlow.createSignatureDescriptor(constructor), false); <ide> cf.pushDescriptor(this.exitTypeDescriptor); <ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/MethodReference.java <ide> public void generateCode(MethodVisitor mv, CodeFlow cf) { <ide> if (descriptor == null && !isStaticMethod) { <ide> cf.loadTarget(mv); <ide> } <add> <add> if (CodeFlow.isPrimitive(descriptor)) { <add> CodeFlow.insertBoxIfNecessary(mv, descriptor.charAt(0)); <add> } <ide> <ide> boolean itf = method.getDeclaringClass().isInterface(); <ide> String methodDeclaringClassSlashedDescriptor = null; <ide><path>spring-expression/src/main/java/org/springframework/expression/spel/standard/SpelExpression.java <ide> public Object getValue(EvaluationContext context) throws EvaluationException { <ide> Assert.notNull(context, "The EvaluationContext is required"); <ide> if (compiledAst!= null) { <ide> try { <del> Object result = this.compiledAst.getValue(null,context); <add> TypedValue contextRoot = context == null ? null : context.getRootObject(); <add> Object result = this.compiledAst.getValue(contextRoot==null?null:contextRoot.getValue(),context); <ide> return result; <ide> } <ide> catch (Throwable ex) { <ide> public Object getValue(EvaluationContext context, Object rootObject) throws Eval <ide> public <T> T getValue(EvaluationContext context, Class<T> expectedResultType) throws EvaluationException { <ide> if (this.compiledAst != null) { <ide> try { <del> Object result = this.compiledAst.getValue(null,context); <add> TypedValue contextRoot = context == null ? null : context.getRootObject(); <add> Object result = this.compiledAst.getValue(contextRoot==null?null:contextRoot.getValue(),context); <ide> if (expectedResultType != null) { <ide> return ExpressionUtils.convertTypedValue(context, new TypedValue(result), expectedResultType); <ide> } <ide><path>spring-expression/src/test/java/org/springframework/expression/spel/SpelCompilationCoverageTests.java <ide> import org.springframework.expression.spel.standard.SpelExpression; <ide> import org.springframework.expression.spel.standard.SpelExpressionParser; <ide> import org.springframework.expression.spel.support.StandardEvaluationContext; <add>import org.springframework.expression.spel.testdata.PersonInOtherPackage; <ide> <ide> import static org.junit.Assert.*; <ide> <ide> public void opModulus_12041() throws Exception { <ide> assertEquals(1.0f,expression.getValue()); <ide> } <ide> <add> @Test <add> public void constructorReference_SPR12326() { <add> String type = this.getClass().getName(); <add> String prefix = "new "+type+".Obj"; <add> <add> expression = parser.parseExpression(prefix+"([0])"); <add> assertEquals("test", ((Obj) expression.getValue(new Object[] { "test" })).param1); <add> assertCanCompile(expression); <add> assertEquals("test", ((Obj) expression.getValue(new Object[] { "test" })).param1); <add> <add> expression = parser.parseExpression(prefix+"2('foo','bar').output"); <add> assertEquals("foobar", expression.getValue(String.class)); <add> assertCanCompile(expression); <add> assertEquals("foobar", expression.getValue(String.class)); <add> <add> expression = parser.parseExpression(prefix+"2('foo').output"); <add> assertEquals("foo", expression.getValue(String.class)); <add> assertCanCompile(expression); <add> assertEquals("foo", expression.getValue(String.class)); <add> <add> expression = parser.parseExpression(prefix+"2().output"); <add> assertEquals("", expression.getValue(String.class)); <add> assertCanCompile(expression); <add> assertEquals("", expression.getValue(String.class)); <add> <add> expression = parser.parseExpression(prefix+"3(1,2,3).output"); <add> assertEquals("123", expression.getValue(String.class)); <add> assertCanCompile(expression); <add> assertEquals("123", expression.getValue(String.class)); <add> <add> expression = parser.parseExpression(prefix+"3(1).output"); <add> assertEquals("1", expression.getValue(String.class)); <add> assertCanCompile(expression); <add> assertEquals("1", expression.getValue(String.class)); <add> <add> expression = parser.parseExpression(prefix+"3().output"); <add> assertEquals("", expression.getValue(String.class)); <add> assertCanCompile(expression); <add> assertEquals("", expression.getValue(String.class)); <add> <add> expression = parser.parseExpression(prefix+"3('abc',5.0f,1,2,3).output"); <add> assertEquals("abc:5.0:123", expression.getValue(String.class)); <add> assertCanCompile(expression); <add> assertEquals("abc:5.0:123", expression.getValue(String.class)); <add> <add> expression = parser.parseExpression(prefix+"3('abc',5.0f,1).output"); <add> assertEquals("abc:5.0:1", expression.getValue(String.class)); <add> assertCanCompile(expression); <add> assertEquals("abc:5.0:1", expression.getValue(String.class)); <add> <add> expression = parser.parseExpression(prefix+"3('abc',5.0f).output"); <add> assertEquals("abc:5.0:", expression.getValue(String.class)); <add> assertCanCompile(expression); <add> assertEquals("abc:5.0:", expression.getValue(String.class)); <add> <add> expression = parser.parseExpression(prefix+"4(#root).output"); <add> assertEquals("123", expression.getValue(new int[]{1,2,3},String.class)); <add> assertCanCompile(expression); <add> assertEquals("123", expression.getValue(new int[]{1,2,3},String.class)); <add> } <add> <add> @Test <add> public void methodReferenceMissingCastAndRootObjectAccessing_SPR12326() { <add> // Need boxing code on the 1 so that toString() can be called <add> expression = parser.parseExpression("1.toString()"); <add> assertEquals("1", expression.getValue()); <add> assertCanCompile(expression); <add> assertEquals("1", expression.getValue()); <add> <add> expression = parser.parseExpression("#it?.age.equals([0])"); <add> Person person = new Person(1); <add> StandardEvaluationContext context = <add> new StandardEvaluationContext(new Object[] { person.getAge() }); <add> context.setVariable("it", person); <add> assertTrue(expression.getValue(context, Boolean.class)); <add> assertCanCompile(expression); <add> assertTrue(expression.getValue(context, Boolean.class)); <add> <add> // Variant of above more like what was in the bug report: <add> SpelExpressionParser parser = new SpelExpressionParser( <add> new SpelParserConfiguration(SpelCompilerMode.IMMEDIATE, <add> this.getClass().getClassLoader())); <add> <add> SpelExpression ex = parser.parseRaw("#it?.age.equals([0])"); <add> context = new StandardEvaluationContext(new Object[] { person.getAge() }); <add> context.setVariable("it", person); <add> assertTrue(ex.getValue(context, Boolean.class)); <add> assertTrue(ex.getValue(context, Boolean.class)); <add> <add> PersonInOtherPackage person2 = new PersonInOtherPackage(1); <add> ex = parser.parseRaw("#it?.age.equals([0])"); <add> context = <add> new StandardEvaluationContext(new Object[] { person2.getAge() }); <add> context.setVariable("it", person2); <add> assertTrue(ex.getValue(context, Boolean.class)); <add> assertTrue(ex.getValue(context, Boolean.class)); <add> <add> ex = parser.parseRaw("#it?.age.equals([0])"); <add> context = <add> new StandardEvaluationContext(new Object[] { person2.getAge() }); <add> context.setVariable("it", person2); <add> assertTrue((Boolean)ex.getValue(context)); <add> assertTrue((Boolean)ex.getValue(context)); <add> } <add> <add> public class Person { <add> <add> private int age; <add> <add> public Person(int age) { <add> this.age = age; <add> } <add> <add> public int getAge() { <add> return age; <add> } <add> <add> public void setAge(int age) { <add> this.age = age; <add> } <add> } <add> <ide> @Test <ide> public void constructorReference() throws Exception { <ide> // simple ctor <ide> private TestClass8(String a, String b) { <ide> this.s = a+b; <ide> } <ide> } <add> <add> public static class Obj { <add> <add> private final String param1; <add> <add> public Obj(String param1){ <add> this.param1 = param1; <add> } <add> } <add> <add> public static class Obj2 { <add> <add> public final String output; <add> <add> public Obj2(String... params){ <add> StringBuilder b = new StringBuilder(); <add> for (String param: params) { <add> b.append(param); <add> } <add> output = b.toString(); <add> } <add> } <add> <add> public static class Obj3 { <add> <add> public final String output; <add> <add> public Obj3(int... params) { <add> StringBuilder b = new StringBuilder(); <add> for (int param: params) { <add> b.append(Integer.toString(param)); <add> } <add> output = b.toString(); <add> } <add> <add> public Obj3(String s, Float f, int... ints) { <add> StringBuilder b = new StringBuilder(); <add> b.append(s); <add> b.append(":"); <add> b.append(Float.toString(f)); <add> b.append(":"); <add> for (int param: ints) { <add> b.append(Integer.toString(param)); <add> } <add> output = b.toString(); <add> } <add> } <add> <add> public static class Obj4 { <add> <add> public final String output; <add> <add> public Obj4(int[] params) { <add> StringBuilder b = new StringBuilder(); <add> for (int param: params) { <add> b.append(Integer.toString(param)); <add> } <add> output = b.toString(); <add> } <add> } <ide> <ide> @SuppressWarnings("unused") <ide> private static class TestClass9 { <ide><path>spring-expression/src/test/java/org/springframework/expression/spel/SpelCompilationPerformanceTests.java <ide> public void stringConcatenation() throws Exception { <ide> Object o = expression.getValue(g); <ide> assertEquals("helloworld spring", o); <ide> <del> System.out.println("Performance check for SpEL expression: '{'abcde','ijklm'}[0].substring({1,3,4}[0],{1,3,4}[1])'"); <add> System.out.println("Performance check for SpEL expression: 'hello' + getWorld() + ' spring'"); <ide> long stime = System.currentTimeMillis(); <ide> for (int i=0;i<1000000;i++) { <ide> o = expression.getValue(g); <ide><path>spring-expression/src/test/java/org/springframework/expression/spel/testdata/PersonInOtherPackage.java <add>/* <add> * Copyright 2014 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add>package org.springframework.expression.spel.testdata; <add> <add>/** <add> * <add> * @author Andy Clement <add> * @since 4.1.2 <add> */ <add>public class PersonInOtherPackage { <add> <add> private int age; <add> <add> public PersonInOtherPackage(int age) { <add> this.age = age; <add> } <add> <add> public int getAge() { <add> return age; <add> } <add> <add> public void setAge(int age) { <add> this.age = age; <add> } <add>} <ide>\ No newline at end of file
7
Ruby
Ruby
remove redundant comments
b3ed5a367df7e551f5e3b30cb140486fa56ff3c7
<ide><path>Library/Homebrew/formula.rb <ide> def to_hash <ide> <ide> end <ide> <del> # For brew-fetch and others. <ide> def fetch <ide> active_spec.fetch <ide> end <ide> <del> # For FormulaInstaller. <ide> def verify_download_integrity fn <ide> active_spec.verify_download_integrity(fn) <ide> end <ide><path>Library/Homebrew/resource.rb <ide> def files(*files) <ide> Partial.new(self, files) <ide> end <ide> <del> # For brew-fetch and others. <ide> def fetch <ide> # Ensure the cache exists <ide> HOMEBREW_CACHE.mkpath
2
Python
Python
add separate noise vs orth level to train cli
f3906950d3f17681bff3b1bede1b81d8ebfb1bec
<ide><path>spacy/cli/train.py <ide> str, <ide> ), <ide> noise_level=("Amount of corruption for data augmentation", "option", "nl", float), <add> orth_variant_level=("Amount of orthography variation for data augmentation", "option", "ovl", float), <ide> eval_beam_widths=("Beam widths to evaluate, e.g. 4,8", "option", "bw", str), <ide> gold_preproc=("Use gold preprocessing", "flag", "G", bool), <ide> learn_tokens=("Make parser learn gold-standard tokenization", "flag", "T", bool), <ide> def train( <ide> parser_multitasks="", <ide> entity_multitasks="", <ide> noise_level=0.0, <add> orth_variant_level=0.0, <ide> eval_beam_widths="", <ide> gold_preproc=False, <ide> learn_tokens=False, <ide> def train( <ide> best_score = 0.0 <ide> for i in range(n_iter): <ide> train_docs = corpus.train_docs( <del> nlp, orth_variant_level=noise_level, gold_preproc=gold_preproc, max_length=0 <add> nlp, noise_level=noise_level, orth_variant_level=orth_variant_level, gold_preproc=gold_preproc, max_length=0 <ide> ) <ide> if raw_text: <ide> random.shuffle(raw_text)
1
Python
Python
update addition example
361a7cfe41f7663fd9f0c12345e4ca52b0a8a2a5
<ide><path>examples/addition_rnn.py <ide> Output: "596" <ide> Padding is handled by using a repeated sentinel character (space) <ide> <del>By default, the JZS1 recurrent neural network is used <del>JZS1 was an "evolved" recurrent neural network performing well on arithmetic benchmark in: <del>"An Empirical Exploration of Recurrent Network Architectures" <del>http://jmlr.org/proceedings/papers/v37/jozefowicz15.pdf <del> <ide> Input may optionally be inverted, shown to increase performance in many tasks in: <ide> "Learning to Execute" <ide> http://arxiv.org/abs/1410.4615 <ide> Theoretically it introduces shorter term dependencies between source and target. <ide> <ide> Two digits inverted: <del>+ One layer JZS1 (128 HN), 5k training examples = 99% train/test accuracy in 55 epochs <add>+ One layer LSTM (128 HN), 5k training examples = 99% train/test accuracy in 55 epochs <ide> <ide> Three digits inverted: <del>+ One layer JZS1 (128 HN), 50k training examples = 99% train/test accuracy in 100 epochs <add>+ One layer LSTM (128 HN), 50k training examples = 99% train/test accuracy in 100 epochs <ide> <ide> Four digits inverted: <del>+ One layer JZS1 (128 HN), 400k training examples = 99% train/test accuracy in 20 epochs <add>+ One layer LSTM (128 HN), 400k training examples = 99% train/test accuracy in 20 epochs <ide> <ide> Five digits inverted: <del>+ One layer JZS1 (128 HN), 550k training examples = 99% train/test accuracy in 30 epochs <add>+ One layer LSTM (128 HN), 550k training examples = 99% train/test accuracy in 30 epochs <ide> <ide> """ <ide> <ide> class colors: <ide> TRAINING_SIZE = 50000 <ide> DIGITS = 3 <ide> INVERT = True <del># Try replacing JZS1 with LSTM, GRU, or SimpleRNN <del>RNN = recurrent.JZS1 <add># Try replacing GRU, or SimpleRNN <add>RNN = recurrent.LSTM <ide> HIDDEN_SIZE = 128 <ide> BATCH_SIZE = 128 <ide> LAYERS = 1 <ide> class colors: <ide> np.random.shuffle(indices) <ide> X = X[indices] <ide> y = y[indices] <add> <ide> # Explicitly set apart 10% for validation data that we never train over <ide> split_at = len(X) - len(X) / 10 <ide> (X_train, X_val) = (slice_X(X, 0, split_at), slice_X(X, split_at)) <ide> class colors: <ide> # "Encode" the input sequence using an RNN, producing an output of HIDDEN_SIZE <ide> # note: in a situation where your input sequences have a variable length, <ide> # use input_shape=(None, nb_feature). <del>model.add(RNN(HIDDEN_SIZE, input_shape=(None, len(chars)))) <add>model.add(RNN(HIDDEN_SIZE, input_shape=(MAXLEN, len(chars)))) <ide> # For the decoder's input, we repeat the encoded input for each time step <ide> model.add(RepeatVector(DIGITS + 1)) <ide> # The decoder RNN could be multiple layers stacked or a single layer
1
Go
Go
move "copy" to daemon/copy.go
06229a4b76aa221d08cfb1888b919da31c49194f
<ide><path>daemon/copy.go <add>package daemon <add> <add>import ( <add> "io" <add> <add> "github.com/docker/docker/engine" <add>) <add> <add>func (daemon *Daemon) ContainerCopy(job *engine.Job) engine.Status { <add> if len(job.Args) != 2 { <add> return job.Errorf("Usage: %s CONTAINER RESOURCE\n", job.Name) <add> } <add> <add> var ( <add> name = job.Args[0] <add> resource = job.Args[1] <add> ) <add> <add> if container := daemon.Get(name); container != nil { <add> <add> data, err := container.Copy(resource) <add> if err != nil { <add> return job.Error(err) <add> } <add> defer data.Close() <add> <add> if _, err := io.Copy(job.Stdout, data); err != nil { <add> return job.Error(err) <add> } <add> return engine.StatusOK <add> } <add> return job.Errorf("No such container: %s", name) <add>} <ide><path>daemon/daemon.go <ide> func (daemon *Daemon) Install(eng *engine.Engine) error { <ide> if err := eng.Register("delete", daemon.ContainerDestroy); err != nil { <ide> return err <ide> } <add> if err := eng.Register("container_copy", daemon.ContainerCopy); err != nil { <add> return err <add> } <ide> return nil <ide> } <ide> <ide><path>server/container.go <ide> package server <ide> import ( <ide> "errors" <ide> "fmt" <del> "io" <ide> "os/exec" <ide> "strconv" <ide> "strings" <ide> func (srv *Server) Containers(job *engine.Job) engine.Status { <ide> } <ide> return engine.StatusOK <ide> } <del> <del>func (srv *Server) ContainerCopy(job *engine.Job) engine.Status { <del> if len(job.Args) != 2 { <del> return job.Errorf("Usage: %s CONTAINER RESOURCE\n", job.Name) <del> } <del> <del> var ( <del> name = job.Args[0] <del> resource = job.Args[1] <del> ) <del> <del> if container := srv.daemon.Get(name); container != nil { <del> <del> data, err := container.Copy(resource) <del> if err != nil { <del> return job.Error(err) <del> } <del> defer data.Close() <del> <del> if _, err := io.Copy(job.Stdout, data); err != nil { <del> return job.Error(err) <del> } <del> return engine.StatusOK <del> } <del> return job.Errorf("No such container: %s", name) <del>} <ide><path>server/init.go <ide> func InitServer(job *engine.Job) engine.Status { <ide> job.Eng.Hack_SetGlobalVar("httpapi.daemon", srv.daemon) <ide> <ide> for name, handler := range map[string]engine.Handler{ <del> "tag": srv.ImageTag, // FIXME merge with "image_tag" <del> "info": srv.DockerInfo, <del> "image_export": srv.ImageExport, <del> "images": srv.Images, <del> "history": srv.ImageHistory, <del> "viz": srv.ImagesViz, <del> "container_copy": srv.ContainerCopy, <del> "log": srv.Log, <del> "changes": srv.ContainerChanges, <del> "top": srv.ContainerTop, <del> "load": srv.ImageLoad, <del> "build": srv.Build, <del> "pull": srv.ImagePull, <del> "import": srv.ImageImport, <del> "image_delete": srv.ImageDelete, <del> "events": srv.Events, <del> "push": srv.ImagePush, <del> "containers": srv.Containers, <add> "tag": srv.ImageTag, // FIXME merge with "image_tag" <add> "info": srv.DockerInfo, <add> "image_export": srv.ImageExport, <add> "images": srv.Images, <add> "history": srv.ImageHistory, <add> "viz": srv.ImagesViz, <add> "log": srv.Log, <add> "changes": srv.ContainerChanges, <add> "top": srv.ContainerTop, <add> "load": srv.ImageLoad, <add> "build": srv.Build, <add> "pull": srv.ImagePull, <add> "import": srv.ImageImport, <add> "image_delete": srv.ImageDelete, <add> "events": srv.Events, <add> "push": srv.ImagePush, <add> "containers": srv.Containers, <ide> } { <ide> if err := job.Eng.Register(name, srv.handlerWrap(handler)); err != nil { <ide> return job.Error(err)
4
Text
Text
update the readme file
b3b561e095081aeac7b1b6e293e45f7764fb9ff0
<ide><path>readme.md <ide> - Added `URL::previous` method for getting previous URL from `referer` $_SERVER variable. <ide> - Renamed `path` helper to `url` for consistency. <ide> - Added `App::shutdown` method for registering callbacks to be fired at very end of both web and Artisan life-cycle. <add>- Added `saveMany` and `createMany` to 1:1, 1:*, and *:* relations. <ide> <ide> ## Beta 3 <ide>
1
PHP
PHP
add failed job handling for syncqueue
8b7c5a42895f41028899f9dfeb0059bcdb250183
<ide><path>src/Illuminate/Queue/SyncQueue.php <ide> <?php namespace Illuminate\Queue; <ide> <add>use Exception; <ide> use Illuminate\Queue\Jobs\SyncJob; <add>use Illuminate\Contracts\Queue\Job; <ide> use Illuminate\Contracts\Queue\Queue as QueueContract; <ide> <ide> class SyncQueue extends Queue implements QueueContract { <ide> class SyncQueue extends Queue implements QueueContract { <ide> * @param mixed $data <ide> * @param string $queue <ide> * @return mixed <add> * @throws \Exception <ide> */ <ide> public function push($job, $data = '', $queue = null) <ide> { <del> $this->resolveJob($this->createPayload($job, $data, $queue))->fire(); <add> $queueJob = $this->resolveJob($this->createPayload($job, $data, $queue)); <add> <add> try <add> { <add> $queueJob->fire(); <add> } <add> catch(Exception $e) <add> { <add> $this->handleFailedJob($queueJob); <add> <add> throw $e; <add> } <ide> <ide> return 0; <ide> } <ide> protected function resolveJob($payload) <ide> return new SyncJob($this->container, $payload); <ide> } <ide> <add> /** <add> * Handle the failed job <add> * <add> * @param \Illuminate\Contracts\Queue\Job $job <add> * @return array <add> */ <add> protected function handleFailedJob(Job $job) <add> { <add> $job->failed(); <add> <add> $this->raiseFailedJobEvent($job); <add> } <add> <add> /** <add> * Raise the failed queue job event. <add> * <add> * @param \Illuminate\Contracts\Queue\Job $job <add> * @return void <add> */ <add> protected function raiseFailedJobEvent(Job $job) <add> { <add> $data = json_decode($job->getRawBody(), true); <add> <add> if($this->container->bound('events')) <add> { <add> $this->container['events']->fire('illuminate.queue.failed', array('sync', $job, $data)); <add> } <add> } <add> <ide> } <ide><path>tests/Queue/QueueSyncQueueTest.php <ide> <?php <ide> <add>use Exception; <ide> use Mockery as m; <ide> <ide> class QueueSyncQueueTest extends PHPUnit_Framework_TestCase { <ide> public function testQueueableEntitiesAreSerializedAndResolvedWhenPassedAsSingleE <ide> $this->assertInstanceOf('SyncQueueTestEntity', $_SERVER['__sync.test'][1]); <ide> } <ide> <add> <add> public function testFailedJobGetsHandledWhenAnExceptionIsThrown() <add> { <add> unset($_SERVER['__sync.failed']); <add> <add> $sync = new Illuminate\Queue\SyncQueue; <add> $container = new Illuminate\Container\Container; <add> $encrypter = new Illuminate\Encryption\Encrypter(str_random(32)); <add> $container->instance('Illuminate\Contracts\Encryption\Encrypter', $encrypter); <add> $events = m::mock('Illuminate\Contracts\Events\Dispatcher'); <add> $events->shouldReceive('fire')->once(); <add> $container->instance('events', $events); <add> $sync->setContainer($container); <add> $sync->setEncrypter($encrypter); <add> <add> try { <add> $sync->push('FailingSyncQueueTestHandler', ['foo' => 'bar']); <add> } <add> catch(Exception $e) <add> { <add> $this->assertTrue($_SERVER['__sync.failed']); <add> } <add> } <add> <ide> } <ide> <ide> class SyncQueueTestEntity implements Illuminate\Contracts\Queue\QueueableEntity { <ide> public function fire($job, $data) { <ide> $_SERVER['__sync.test'] = func_get_args(); <ide> } <ide> } <add> <add>class FailingSyncQueueTestHandler { <add> public function fire($job, $data) { <add> throw new Exception(); <add> } <add> public function failed(){ <add> $_SERVER['__sync.failed'] = true; <add> } <add>} <ide>\ No newline at end of file
2
Java
Java
check template availability in scripttemplateview
9e5435e6f2b9110969af9d581d1a05c6106b8dd7
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/view/script/ScriptTemplateView.java <ide> <ide> package org.springframework.web.servlet.view.script; <ide> <add>import java.io.FileNotFoundException; <ide> import java.io.IOException; <ide> import java.io.InputStreamReader; <ide> import java.nio.charset.Charset; <ide> import java.nio.charset.StandardCharsets; <ide> import java.util.Arrays; <ide> import java.util.HashMap; <add>import java.util.Locale; <ide> import java.util.Map; <ide> import javax.script.Invocable; <ide> import javax.script.ScriptEngine; <ide> public void setResourceLoaderPath(String resourceLoaderPath) { <ide> } <ide> } <ide> <add> @Override <add> public boolean checkResource(Locale locale) throws Exception { <add> try { <add> getTemplate(getUrl()); <add> return true; <add> } <add> catch (IllegalStateException exc) { <add> if (logger.isDebugEnabled()) { <add> logger.debug("No ScriptTemplate view found for URL: " + getUrl()); <add> } <add> return false; <add> } <add> } <ide> <ide> @Override <ide> protected void initApplicationContext(ApplicationContext context) { <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/view/script/ScriptTemplateViewTests.java <ide> import java.util.ArrayList; <ide> import java.util.HashMap; <ide> import java.util.List; <add>import java.util.Locale; <ide> import java.util.Map; <ide> import java.util.concurrent.ExecutorService; <ide> import java.util.concurrent.Executors; <ide> import javax.script.ScriptEngine; <ide> <ide> import org.junit.Before; <add>import org.junit.Rule; <ide> import org.junit.Test; <add>import org.junit.rules.ExpectedException; <ide> <ide> import org.springframework.beans.DirectFieldAccessor; <ide> import org.springframework.context.ApplicationContextException; <ide> public class ScriptTemplateViewTests { <ide> <ide> private StaticWebApplicationContext wac; <ide> <add> @Rule <add> public ExpectedException expectedException = ExpectedException.none(); <ide> <ide> @Before <ide> public void setup() { <ide> public void setup() { <ide> } <ide> <ide> <add> @Test <add> public void missingTemplate() throws Exception { <add> MockServletContext servletContext = new MockServletContext(); <add> this.wac.setServletContext(servletContext); <add> this.wac.refresh(); <add> this.view.setResourceLoaderPath("classpath:org/springframework/web/servlet/view/script/"); <add> this.view.setUrl("missing.txt"); <add> this.view.setEngine(mock(InvocableScriptEngine.class)); <add> this.configurer.setRenderFunction("render"); <add> this.view.setApplicationContext(this.wac); <add> assertFalse(this.view.checkResource(Locale.ENGLISH)); <add> } <add> <ide> @Test <ide> public void missingScriptTemplateConfig() throws Exception { <del> try { <del> this.view.setApplicationContext(new StaticApplicationContext()); <del> fail("Should have thrown ApplicationContextException"); <del> } <del> catch (ApplicationContextException ex) { <del> assertTrue(ex.getMessage().contains("ScriptTemplateConfig")); <del> } <add> this.expectedException.expect(ApplicationContextException.class); <add> this.view.setApplicationContext(new StaticApplicationContext()); <add> this.expectedException.expectMessage(contains("ScriptTemplateConfig")); <ide> } <ide> <ide> @Test <ide> public void nonSharedEngine() throws Exception { <ide> <ide> @Test <ide> public void nonInvocableScriptEngine() throws Exception { <del> try { <del> this.view.setEngine(mock(ScriptEngine.class)); <del> fail("Should have thrown IllegalArgumentException"); <del> } <del> catch (IllegalArgumentException ex) { <del> assertThat(ex.getMessage(), containsString("instance")); <del> } <add> this.expectedException.expect(IllegalArgumentException.class); <add> this.view.setEngine(mock(ScriptEngine.class)); <add> this.expectedException.expectMessage(contains("instance")); <ide> } <ide> <ide> @Test <ide> public void noRenderFunctionDefined() { <ide> this.view.setEngine(mock(InvocableScriptEngine.class)); <del> try { <del> this.view.setApplicationContext(this.wac); <del> fail("Should have thrown IllegalArgumentException"); <del> } <del> catch (IllegalArgumentException ex) { <del> assertThat(ex.getMessage(), containsString("renderFunction")); <del> } <add> this.expectedException.expect(IllegalArgumentException.class); <add> this.view.setApplicationContext(this.wac); <add> this.expectedException.expectMessage(contains("renderFunction")); <ide> } <ide> <ide> @Test <ide> public void engineAndEngineNameBothDefined() { <ide> this.view.setEngine(mock(InvocableScriptEngine.class)); <ide> this.view.setEngineName("test"); <ide> this.view.setRenderFunction("render"); <del> try { <del> this.view.setApplicationContext(this.wac); <del> fail("Should have thrown IllegalArgumentException"); <del> } <del> catch (IllegalArgumentException ex) { <del> assertThat(ex.getMessage(), containsString("'engine' or 'engineName'")); <del> } <add> this.expectedException.expect(IllegalArgumentException.class); <add> this.view.setApplicationContext(this.wac); <add> this.expectedException.expectMessage(contains("'engine' or 'engineName'")); <ide> } <ide> <ide> @Test <ide> public void engineSetterAndNonSharedEngine() { <ide> this.view.setEngine(mock(InvocableScriptEngine.class)); <ide> this.view.setRenderFunction("render"); <ide> this.view.setSharedEngine(false); <del> try { <del> this.view.setApplicationContext(this.wac); <del> fail("Should have thrown IllegalArgumentException"); <del> } <del> catch (IllegalArgumentException ex) { <del> assertThat(ex.getMessage(), containsString("sharedEngine")); <del> } <add> this.expectedException.expect(IllegalArgumentException.class); <add> this.view.setApplicationContext(this.wac); <add> this.expectedException.expectMessage(contains("sharedEngine")); <ide> } <ide> <ide> @Test // SPR-14210
2
Javascript
Javascript
remove unneeded tests
732620cfe91154d1b821cb1c04ebbfd4c7c44d04
<ide><path>test/parallel/test-async-wrap-check-providers.js <del>'use strict'; <del> <del>const common = require('../common'); <del>if (!common.hasCrypto) { <del> common.skip('missing crypto'); <del> return; <del>} <del> <del>const assert = require('assert'); <del>const crypto = require('crypto'); <del>const dgram = require('dgram'); <del>const dns = require('dns'); <del>const fs = require('fs'); <del>const net = require('net'); <del>const tls = require('tls'); <del>const zlib = require('zlib'); <del>const ChildProcess = require('child_process').ChildProcess; <del>const StreamWrap = require('_stream_wrap').StreamWrap; <del>const HTTPParser = process.binding('http_parser').HTTPParser; <del>const async_wrap = process.binding('async_wrap'); <del>const pkeys = Object.keys(async_wrap.Providers); <del> <del>let keyList = pkeys.slice(); <del>// Drop NONE <del>keyList.splice(0, 1); <del> <del>// fs-watch currently needs special configuration on AIX and we <del>// want to improve under https://github.com/nodejs/node/issues/5085. <del>// strip out fs watch related parts for now <del>if (common.isAix) { <del> for (let i = 0; i < keyList.length; i++) { <del> if ((keyList[i] === 'FSEVENTWRAP') || (keyList[i] === 'STATWATCHER')) { <del> keyList.splice(i, 1); <del> } <del> } <del>} <del> <del>function init(id, provider) { <del> keyList = keyList.filter((e) => e !== pkeys[provider]); <del>} <del> <del>async_wrap.setupHooks({ init }); <del> <del>async_wrap.enable(); <del> <del> <del>setTimeout(common.noop, 1); <del> <del>fs.stat(__filename, common.noop); <del> <del>if (!common.isAix) { <del> // fs-watch currently needs special configuration on AIX and we <del> // want to improve under https://github.com/nodejs/node/issues/5085. <del> // strip out fs watch related parts for now <del> fs.watchFile(__filename, common.noop); <del> fs.unwatchFile(__filename); <del> fs.watch(__filename).close(); <del>} <del> <del>dns.lookup('localhost', common.noop); <del>dns.lookupService('::', 0, common.noop); <del>dns.resolve('localhost', common.noop); <del> <del>new StreamWrap(new net.Socket()); <del> <del>new (process.binding('tty_wrap').TTY)(); <del> <del>crypto.randomBytes(1, common.noop); <del> <del>common.refreshTmpDir(); <del> <del>net.createServer(function(c) { <del> c.end(); <del> this.close(); <del>}).listen(common.PIPE, function() { <del> net.connect(common.PIPE, common.noop); <del>}); <del> <del>net.createServer(function(c) { <del> c.end(); <del> this.close(checkTLS); <del>}).listen(0, function() { <del> net.connect(this.address().port, common.noop); <del>}); <del> <del>dgram.createSocket('udp4').bind(0, function() { <del> this.send(Buffer.allocUnsafe(2), 0, 2, this.address().port, '::', () => { <del> this.close(); <del> }); <del>}); <del> <del>process.on('SIGINT', () => process.exit()); <del> <del>// Run from closed net server above. <del>function checkTLS() { <del> const options = { <del> key: fs.readFileSync(`${common.fixturesDir}/keys/ec-key.pem`), <del> cert: fs.readFileSync(`${common.fixturesDir}/keys/ec-cert.pem`) <del> }; <del> const server = tls.createServer(options, common.noop) <del> .listen(0, function() { <del> const connectOpts = { rejectUnauthorized: false }; <del> tls.connect(this.address().port, connectOpts, function() { <del> this.destroy(); <del> server.close(); <del> }); <del> }); <del>} <del> <del>zlib.createGzip(); <del> <del>new ChildProcess(); <del> <del>new HTTPParser(HTTPParser.REQUEST); <del> <del>process.on('exit', function() { <del> if (keyList.length !== 0) { <del> process._rawDebug('Not all keys have been used:'); <del> process._rawDebug(keyList); <del> assert.strictEqual(keyList.length, 0); <del> } <del>}); <ide><path>test/parallel/test-async-wrap-disabled-propagate-parent.js <del>'use strict'; <del> <del>const common = require('../common'); <del>const assert = require('assert'); <del>const net = require('net'); <del>const async_wrap = process.binding('async_wrap'); <del>const providers = Object.keys(async_wrap.Providers); <del> <del>const uidSymbol = Symbol('uid'); <del> <del>let cntr = 0; <del>let client; <del> <del>function init(uid, type, parentUid, parentHandle) { <del> this[uidSymbol] = uid; <del> <del> if (parentHandle) { <del> cntr++; <del> // Cannot assert in init callback or will abort. <del> process.nextTick(() => { <del> assert.strictEqual(providers[type], 'TCPWRAP'); <del> assert.strictEqual(parentUid, server._handle[uidSymbol], <del> 'server uid doesn\'t match parent uid'); <del> assert.strictEqual(parentHandle, server._handle, <del> 'server handle doesn\'t match parent handle'); <del> assert.strictEqual(this, client._handle, 'client doesn\'t match context'); <del> }); <del> } <del>} <del> <del>async_wrap.setupHooks({ init }); <del>async_wrap.enable(); <del> <del>const server = net.createServer(function(c) { <del> client = c; <del> // Allow init callback to run before closing. <del> setImmediate(() => { <del> c.end(); <del> this.close(); <del> }); <del>}).listen(0, function() { <del> net.connect(this.address().port, common.noop); <del>}); <del> <del>async_wrap.disable(); <del> <del>process.on('exit', function() { <del> // init should have only been called once with a parent. <del> assert.strictEqual(cntr, 1); <del>}); <ide><path>test/parallel/test-async-wrap-post-did-throw.js <del>'use strict'; <del> <del>const common = require('../common'); <del>if (!common.hasCrypto) { <del> common.skip('missing crypto'); <del> return; <del>} <del> <del>const assert = require('assert'); <del>const async_wrap = process.binding('async_wrap'); <del>let asyncThrows = 0; <del>let uncaughtExceptionCount = 0; <del> <del>process.on('uncaughtException', (e) => { <del> assert.strictEqual(e.message, 'oh noes!', 'error messages do not match'); <del>}); <del> <del>process.on('exit', () => { <del> process.removeAllListeners('uncaughtException'); <del> assert.strictEqual(uncaughtExceptionCount, 1); <del> assert.strictEqual(uncaughtExceptionCount, asyncThrows); <del>}); <del> <del>function init() { } <del>function post(id, threw) { <del> if (threw) <del> uncaughtExceptionCount++; <del>} <del> <del>async_wrap.setupHooks({ init, post }); <del>async_wrap.enable(); <del> <del>// Timers still aren't supported, so use crypto API. <del>// It's also important that the callback not happen in a nextTick, like many <del>// error events in core. <del>require('crypto').randomBytes(0, () => { <del> asyncThrows++; <del> throw new Error('oh noes!'); <del>}); <ide><path>test/parallel/test-async-wrap-propagate-parent.js <del>'use strict'; <del> <del>const common = require('../common'); <del>const assert = require('assert'); <del>const net = require('net'); <del>const async_wrap = process.binding('async_wrap'); <del>const providers = Object.keys(async_wrap.Providers); <del> <del>const uidSymbol = Symbol('uid'); <del> <del>let cntr = 0; <del>let client; <del> <del>function init(uid, type, parentUid, parentHandle) { <del> this[uidSymbol] = uid; <del> <del> if (parentHandle) { <del> cntr++; <del> // Cannot assert in init callback or will abort. <del> process.nextTick(() => { <del> assert.strictEqual(providers[type], 'TCPWRAP'); <del> assert.strictEqual(parentUid, server._handle[uidSymbol], <del> 'server uid doesn\'t match parent uid'); <del> assert.strictEqual(parentHandle, server._handle, <del> 'server handle doesn\'t match parent handle'); <del> assert.strictEqual(this, client._handle, 'client doesn\'t match context'); <del> }); <del> } <del>} <del> <del>async_wrap.setupHooks({ init }); <del>async_wrap.enable(); <del> <del>const server = net.createServer(function(c) { <del> client = c; <del> // Allow init callback to run before closing. <del> setImmediate(() => { <del> c.end(); <del> this.close(); <del> }); <del>}).listen(0, function() { <del> net.connect(this.address().port, common.noop); <del>}); <del> <del> <del>process.on('exit', function() { <del> // init should have only been called once with a parent. <del> assert.strictEqual(cntr, 1); <del>}); <ide><path>test/parallel/test-async-wrap-throw-no-init.js <del>'use strict'; <del> <del>const common = require('../common'); <del>const assert = require('assert'); <del>const async_wrap = process.binding('async_wrap'); <del> <del>assert.throws(function() { <del> async_wrap.setupHooks(null); <del>}, /first argument must be an object/); <del> <del>assert.throws(function() { <del> async_wrap.setupHooks({}); <del>}, /init callback must be a function/); <del> <del>assert.throws(function() { <del> async_wrap.enable(); <del>}, /init callback is not assigned to a function/); <del> <del>// Should not throw <del>async_wrap.setupHooks({ init: common.noop }); <del>async_wrap.enable(); <del> <del>assert.throws(function() { <del> async_wrap.setupHooks(common.noop); <del>}, /hooks should not be set while also enabled/); <ide><path>test/parallel/test-async-wrap-uid.js <del>'use strict'; <del> <del>const common = require('../common'); <del>const fs = require('fs'); <del>const assert = require('assert'); <del>const async_wrap = process.binding('async_wrap'); <del> <del>// Give the event loop time to clear out the final uv_close(). <del>let si_cntr = 3; <del>process.on('beforeExit', () => { <del> if (--si_cntr > 0) setImmediate(common.noop); <del>}); <del> <del>const storage = new Map(); <del>async_wrap.setupHooks({ init, pre, post, destroy }); <del>async_wrap.enable(); <del> <del>function init(uid) { <del> storage.set(uid, { <del> init: true, <del> pre: false, <del> post: false, <del> destroy: false, <del> }); <del>} <del> <del>function pre(uid) { <del> storage.get(uid).pre = true; <del>} <del> <del>function post(uid) { <del> storage.get(uid).post = true; <del>} <del> <del>function destroy(uid) { <del> storage.get(uid).destroy = true; <del>} <del> <del>fs.access(__filename, function(err) { <del> assert.ifError(err); <del>}); <del> <del>fs.access(__filename, function(err) { <del> assert.ifError(err); <del>}); <del> <del>async_wrap.disable(); <del> <del>process.once('exit', function() { <del> assert.strictEqual(storage.size, 2); <del> <del> for (const item of storage) { <del> const uid = item[0]; <del> const value = item[1]; <del> assert.strictEqual(typeof uid, 'number'); <del> assert.deepStrictEqual(value, { <del> init: true, <del> pre: true, <del> post: true, <del> destroy: true, <del> }); <del> } <del>}); <ide><path>test/parallel/test-stream-base-no-abort.js <del>'use strict'; <del> <del>const common = require('../common'); <del>if (!common.hasCrypto) { <del> common.skip('missing crypto'); <del> return; <del>} <del> <del>const async_wrap = process.binding('async_wrap'); <del>const uv = process.binding('uv'); <del>const assert = require('assert'); <del>const dgram = require('dgram'); <del>const fs = require('fs'); <del>const net = require('net'); <del>const tls = require('tls'); <del>const providers = Object.keys(async_wrap.Providers); <del>let flags = 0; <del> <del>// Make sure all asserts have run at least once. <del>process.on('exit', () => assert.strictEqual(flags, 0b111)); <del> <del>function init(id, provider) { <del> this._external; // Test will abort if nullptr isn't properly checked. <del> switch (providers[provider]) { <del> case 'TCPWRAP': <del> assert.strictEqual(this.fd, uv.UV_EINVAL); <del> flags |= 0b1; <del> break; <del> case 'TLSWRAP': <del> assert.strictEqual(this.fd, uv.UV_EINVAL); <del> flags |= 0b10; <del> break; <del> case 'UDPWRAP': <del> assert.strictEqual(this.fd, uv.UV_EBADF); <del> flags |= 0b100; <del> break; <del> } <del>} <del> <del>async_wrap.setupHooks({ init }); <del>async_wrap.enable(); <del> <del>const checkTLS = common.mustCall(function checkTLS() { <del> const options = { <del> key: fs.readFileSync(`${common.fixturesDir}/keys/ec-key.pem`), <del> cert: fs.readFileSync(`${common.fixturesDir}/keys/ec-cert.pem`) <del> }; <del> const server = tls.createServer(options, common.noop) <del> .listen(0, function() { <del> const connectOpts = { rejectUnauthorized: false }; <del> tls.connect(this.address().port, connectOpts, function() { <del> this.destroy(); <del> server.close(); <del> }); <del> }); <del>}); <del> <del>const checkTCP = common.mustCall(function checkTCP() { <del> net.createServer(common.noop).listen(0, function() { <del> this.close(checkTLS); <del> }); <del>}); <del> <del>dgram.createSocket('udp4').close(checkTCP);
7
Javascript
Javascript
skip flaky dynamic import tests
489ca73e436c54408b8769437d5fd51bb336d6f4
<ide><path>test/integration/react-streaming-and-server-components/test/index.test.js <ide> describe('concurrentFeatures - dev', () => { <ide> await killApp(context.server) <ide> }) <ide> <del> it('should support React.lazy and dynamic imports', async () => { <add> // TODO: re-enabled test when update webpack with chunkLoading support <add> it.skip('should support React.lazy and dynamic imports', async () => { <ide> const html = await renderViaHTTP(context.appPort, '/dynamic-imports') <ide> expect(html).toContain('loading...') <ide>
1
Javascript
Javascript
fix typo in computed_macros.js
28a16f2b56584c7a786b85e393606aeb23d58802
<ide><path>packages/ember-metal/lib/computed_macros.js <ide> registerComputed('equal', function(dependentKey, value) { <ide> }); <ide> <ide> /** <del> A computed property that returns true if the provied dependent property <add> A computed property that returns true if the provided dependent property <ide> is greater than the provided value. <ide> <ide> Example
1
Javascript
Javascript
clarify test types during scaffolding
5c8e787803af7337f8b7665bceb8b90be78dff5a
<ide><path>plopfile.js <ide> module.exports = function (plop) { <ide> type: 'list', <ide> name: 'type', <ide> message: 'Test type', <del> choices: ['e2e', 'unit', 'production', 'development'], <add> choices: [ <add> { <add> name: 'e2e - Test "next dev" and "next build && next start"', <add> value: 'e2e', <add> }, <add> { <add> name: 'production - Test "next build && next start"', <add> value: 'production', <add> }, <add> { name: 'development - Test "next dev"', value: 'development' }, <add> { name: 'unit - Test individual files', value: 'unit' }, <add> ], <ide> }, <ide> ], <ide> actions: function (data) {
1
Java
Java
fix simple typo in comment
5c12a84c7790cdeeba9f0ad0a68c061240dddb32
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/JSTouchDispatcher.java <ide> public void handleTouchEvent(MotionEvent ev, EventDispatcher eventDispatcher) { <ide> mTargetCoordinates[1], <ide> mTouchEventCoalescingKeyHelper)); <ide> } else if (action == MotionEvent.ACTION_POINTER_UP) { <del> // Exactly onw of the pointers goes up <add> // Exactly one of the pointers goes up <ide> eventDispatcher.dispatchEvent( <ide> TouchEvent.obtain( <ide> getSurfaceId(),
1
Text
Text
correct typos in incidence matrix instruction
890ce894ccaf044643d083cc367cc8a3c4fc27b5
<ide><path>curriculum/challenges/english/08-coding-interview-prep/data-structures/incidence-matrix.english.md <ide> Graphs can also have <dfn>weights</dfn> on their edges. So far, we have <dfn>unw <ide> ## Instructions <ide> <section id='instructions'> <ide> Create an incidence matrix of an undirected graph with five nodes and four edges. This matrix should be in a multi-dimensional array. <del>These five nodes have relationships following relationships. The first edge is between the first and second node. The second edge is between the second and third node. The third edge is between the third and fifth node. And four edge is between the fourth and second node. All edge weights are one and the edge order matters. <add>These five nodes have the following relationships. The first edge is between the first and second node. The second edge is between the second and third node. The third edge is between the third and fifth node. The fourth edge is between the fourth and second node. All edge weights are one and the edge order matters. <ide> </section> <ide> <ide> ## Tests
1
Python
Python
raise assertionerror instead of assert
05921b06c3ef486ff173645b915cd93e5f8cddd6
<ide><path>numpy/ma/testutils.py <ide> def assert_equal(actual,desired,err_msg=''): <ide> """ <ide> # Case #1: dictionary ..... <ide> if isinstance(desired, dict): <del> assert isinstance(actual, dict), repr(type(actual)) <add> if not isinstance(actual, dict): <add> raise AssertionError(repr(type(actual))) <ide> assert_equal(len(actual),len(desired),err_msg) <ide> for k,i in desired.items(): <del> assert k in actual, repr(k) <add> if not k in actual: <add> raise AssertionError("%s not in %s" % (k,actual)) <ide> assert_equal(actual[k], desired[k], 'key=%r\n%s' % (k,err_msg)) <ide> return <ide> # Case #2: lists ..... <ide> if isinstance(desired, (list,tuple)) and isinstance(actual, (list,tuple)): <ide> return _assert_equal_on_sequences(actual, desired, err_msg='') <ide> if not (isinstance(actual, ndarray) or isinstance(desired, ndarray)): <ide> msg = build_err_msg([actual, desired], err_msg,) <del> assert desired == actual, msg <add> if not desired == actual: <add> raise AssertionError(msg) <ide> return <ide> # Case #4. arrays or equivalent <ide> if ((actual is masked) and not (desired is masked)) or \ <ide> def fail_if_equal(actual,desired,err_msg='',): <ide> """Raises an assertion error if two items are equal. <ide> """ <ide> if isinstance(desired, dict): <del> assert isinstance(actual, dict), repr(type(actual)) <add> if not isinstance(actual, dict): <add> raise AssertionError(repr(type(actual))) <ide> fail_if_equal(len(actual),len(desired),err_msg) <ide> for k,i in desired.items(): <del> assert k in actual, repr(k) <add> if not k in actual: <add> raise AssertionError(repr(k)) <ide> fail_if_equal(actual[k], desired[k], 'key=%r\n%s' % (k,err_msg)) <ide> return <ide> if isinstance(desired, (list,tuple)) and isinstance(actual, (list,tuple)): <ide> def fail_if_equal(actual,desired,err_msg='',): <ide> if isinstance(actual, np.ndarray) or isinstance(desired, np.ndarray): <ide> return fail_if_array_equal(actual, desired, err_msg) <ide> msg = build_err_msg([actual, desired], err_msg) <del> assert desired != actual, msg <add> if not desired != actual: <add> raise AssertionError(msg) <ide> assert_not_equal = fail_if_equal <ide> <ide> <ide> def assert_almost_equal(actual, desired, decimal=7, err_msg='', verbose=True): <ide> err_msg=err_msg, verbose=verbose) <ide> msg = build_err_msg([actual, desired], <ide> err_msg=err_msg, verbose=verbose) <del> assert round(abs(desired - actual),decimal) == 0, msg <add> if not round(abs(desired - actual),decimal) == 0: <add> raise AssertionError(msg) <ide> <ide> <ide> assert_close = assert_almost_equal
1
Ruby
Ruby
change one more place for json string to hash
ac49fb1aa92ac9f65e009eec2bb22f730f8c37f5
<ide><path>activemodel/lib/active_model/serializers/json.rb <ide> module JSON <ide> # The remainder of the examples in this section assume include_root_in_json is set to <ide> # <tt>false</tt>. <ide> # <del> # Without any +options+, the returned JSON string will include all the model's <add> # Without any +options+, the returned Hash will include all the model's <ide> # attributes. For example: <ide> # <ide> # user = User.find(1)
1
Java
Java
fix javadoc for httpheaders#setcontentlanguage
4523d01a5001835891b2f4160698521eef1256fe
<ide><path>spring-web/src/main/java/org/springframework/http/HttpHeaders.java <ide> public ContentDisposition getContentDisposition() { <ide> /** <ide> * Set the {@link Locale} of the content language, <ide> * as specified by the {@literal Content-Language} header. <del> * <p>Use {@code set(CONTENT_LANGUAGE, list)} if you need <add> * <p>Use {@code put(CONTENT_LANGUAGE, list)} if you need <ide> * to set multiple content languages.</p> <ide> * @since 5.0 <ide> */
1
Text
Text
resolve more crowdin issues
709018571bc1d6e686f67cb6883b3df30952e748
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-by-building-a-cat-photo-app/5f05a1d8e233dff4a68508d8.md <ide> Your new radio button should have an `id` attribute. Check that there is a space <ide> assert($('input')[1].hasAttribute('id')); <ide> ``` <ide> <del>Your new radio element should have an `id` attribute with the value `outdoor`. You have either omitted the value or have a typo. Remember that attribute values should be surrounded with quotation marks. <add>Your new radio button should have an `id` attribute with the value `outdoor`. You have either omitted the value or have a typo. Remember that attribute values should be surrounded with quotation marks. <ide> <ide> ```js <ide> assert($('input')[1].id.match(/^outdoor$/)); <ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-intermediate-css-by-building-a-picasso-painting/60b69a66b6ddb80858c5159c.md <ide> Your `#black-character` selector should have a `height` property set to `500px`. <ide> assert(new __helpers.CSSHelp(document).getStyle('#black-character')?.height === '500px'); <ide> ``` <ide> <del>Your `#black-character` selector should have a `background-color` property to `rgb(45, 31, 19)`. <add>Your `#black-character` selector should have a `background-color` property set to `rgb(45, 31, 19)`. <ide> <ide> ```js <ide> assert(new __helpers.CSSHelp(document).getStyle('#black-character')?.backgroundColor === 'rgb(45, 31, 19)');
2
Javascript
Javascript
add tests for .concat alongside template literals
08179b3860e0ac235cf766498d6fd36964136c10
<ide><path>test/cases/parsing/complex-require/amd.js <ide> it("should parse template strings in amd requires", function(done) { <ide> } <ide> } <ide> }) <add> <add>it("should parse .concat strings in amd requires", function(done) { <add> var name = "abc"; <add> var suffix = "Test"; <add> <add> var pending = [ <add> require(["./abc/abcTest"], test), <add> require(["./abc/".concat(name, "Test")], test), <add> require(["./".concat(name, "/").concat(name, "Test")], test), <add> require(["./abc/".concat(name).concat(suffix)], test) <add> ].length; <add> <add> function test (result) { <add> result.default.should.eql("ok") <add> if (--pending <= 0) { <add> done() <add> } <add> } <add>}) <ide><path>test/cases/parsing/complex-require/cjs.js <ide> it("should parse template strings in require.ensure requires", function(done) { <ide> <ide> require.ensure([], function(require) { <ide> var imports = [ <del> require(`./abc/${name}Test`), <ide> require(`./abc/${name}Test`), <ide> require(`./${name}/${name}Test`), <ide> require(`./abc/${name}${suffix}`), <ide> it("should parse template strings in require.resolve", function() { <ide> // can't use typeof as that depends on webpack config. <ide> require.resolve(`./sync/${name}Test`).should.not.be.undefined(); <ide> }) <add> <add>it("should parse .concat strings in require.ensure requires", function(done) { <add> var name = "abc"; <add> var suffix = "Test"; <add> <add> require.ensure([], function(require) { <add> var imports = [ <add> require("./abc/".concat(name, "Test")), <add> require("./".concat(name, "/").concat(name, "Test")), <add> require("./abc/".concat(name).concat(suffix)) <add> ]; <add> <add> for (var i = 0; i < imports.length; i++) { <add> imports[i].default.should.eql("ok"); <add> } <add> done() <add> }) <add>}) <add> <add>it("should parse .concat strings in sync requires", function() { <add> var name = "sync"; <add> var suffix = "Test"; <add> <add> var imports = [ <add> require("./sync/".concat(name, "Test")), <add> require("./sync/".concat(name).concat(suffix)), <add> require("./sync/sync".concat("Test")) <add> ]; <add> <add> for (var i = 0; i < imports.length; i++) { <add> imports[i].default.should.eql("sync"); <add> } <add>}) <add> <add>it("should parse .concat strings in require.resolve", function() { <add> var name = "sync"; <add> <add> // Arbitrary assertion; can't use .ok() as it could be 0, <add> // can't use typeof as that depends on webpack config. <add> require.resolve("./sync/".concat(name, "Test")).should.not.be.undefined(); <add>}) <ide><path>test/cases/parsing/complex-require/index.js <ide> it("should parse template strings in import", function(done) { <ide> .then(function () { done(); }, done) <ide> }); <ide> <add>it("should parse .concat strings in import", function(done) { <add> var name = "abc".split(""); <add> var suffix = "Test"; <add> import("./abc/".concat(name[0]).concat(name[1]).concat(name[2], "Test")) <add> .then(function (imported) { <add> imported.default.should.eql("ok"); <add> }) <add> .then(function () { done(); }, done) <add>}); <add> <ide> require("./cjs") <ide> require("./amd")
3
PHP
PHP
add html escaping
b5b151e114702b420a9f3fe0c8d008bd8544fa7f
<ide><path>Cake/View/Input/SelectBox.php <ide> public function __construct($templates) { <ide> } <ide> <ide> public function render($data) { <add> $data += [ <add> 'name' => '', <add> 'empty' => false, <add> 'escape' => true, <add> 'options' => [], <add> 'disabled' => null, <add> 'value' => null, <add> ]; <add> <ide> if (empty($data['name'])) { <ide> throw new \RuntimeException('Cannot make inputs with empty name attributes.'); <ide> } <ide> $options = $this->_renderContent($data); <ide> $name = $data['name']; <del> unset($data['name'], $data['options'], $data['empty'], $data['value']); <add> unset($data['name'], $data['options'], $data['empty'], $data['value'], $data['escape']); <ide> if (isset($data['disabled']) && is_array($data['disabled'])) { <ide> unset($data['disabled']); <ide> } <ide> public function render($data) { <ide> <ide> protected function _renderContent($data) { <ide> $out = []; <del> if (!isset($data['options'])) { <del> $data['options'] = []; <del> } <ide> $options = $data['options']; <ide> <ide> if (!empty($data['empty'])) { <ide> protected function _renderContent($data) { <ide> if (isset($data['disabled']) && is_array($data['disabled'])) { <ide> $disabled = $data['disabled']; <ide> } <del> return $this->_renderOptions($options, $disabled, $selected); <add> return $this->_renderOptions($options, $disabled, $selected, $data['escape']); <ide> } <ide> <del> protected function _renderOptions($options, $disabled, $selected) { <add> protected function _renderOptions($options, $disabled, $selected, $escape) { <ide> foreach ($options as $key => $val) { <ide> if (is_array($val)) { <del> $groupOptions = $this->_renderOptions($val, $disabled, $selected); <add> $groupOptions = $this->_renderOptions($val, $disabled, $selected, $escape); <ide> $out[] = $this->_templates->format('optgroup', [ <del> 'label' => $key, <add> 'label' => $escape ? h($key) : $key, <ide> 'content' => implode('', $groupOptions) <ide> ]); <ide> } else { <ide> protected function _renderOptions($options, $disabled, $selected) { <ide> } <ide> <ide> $out[] = $this->_templates->format($template, [ <del> 'name' => $key, <del> 'value' => $val <add> 'name' => $escape ? h($key) : $key, <add> 'value' => $escape ? h($val) : $val, <ide> ]); <ide> } <ide> } <ide><path>Test/TestCase/View/Input/SelectBoxTest.php <ide> public function testRenderEmptyOption() { <ide> * @return void <ide> */ <ide> public function testRenderEscapingOption() { <del> $this->markTestIncomplete('Not done'); <add> $select = new SelectBox($this->templates); <add> $data = [ <add> 'name' => 'Birds[name]', <add> 'options' => [ <add> 'a' => '>Albatross', <add> 'b' => '>Budgie', <add> 'c' => '>Canary', <add> ] <add> ]; <add> $result = $select->render($data); <add> $expected = [ <add> 'select' => [ <add> 'name' => 'Birds[name]', <add> ], <add> ['option' => ['value' => 'a']], <add> '&gt;Albatross', <add> '/option', <add> ['option' => ['value' => 'b']], <add> '&gt;Budgie', <add> '/option', <add> ['option' => ['value' => 'c']], <add> '&gt;Canary', <add> '/option', <add> '/select' <add> ]; <add> $this->assertTags($result, $expected); <add> <add> $data = [ <add> 'escape' => false, <add> 'name' => 'Birds[name]', <add> 'options' => [ <add> '>a' => '>Albatross', <add> ] <add> ]; <add> $result = $select->render($data); <add> $expected = [ <add> 'select' => [ <add> 'name' => 'Birds[name]', <add> ], <add> ['option' => ['value' => '>a']], <add> '>Albatross', <add> '/option', <add> '/select' <add> ]; <add> $this->assertTags($result, $expected); <ide> } <ide> <ide> }
2
Javascript
Javascript
move initial addclass to the compile phase
b1ee5386d584f208bce6d3b613afdb3bae9df76a
<ide><path>src/ng/directive/form.js <ide> function FormController(element, attrs, $scope, $animate, $interpolate) { <ide> <ide> parentForm.$addControl(form); <ide> <del> // Setup initial state of the control <del> element.addClass(PRISTINE_CLASS); <del> <ide> /** <ide> * @ngdoc method <ide> * @name form.FormController#$rollbackViewValue <ide> var formDirectiveFactory = function(isNgForm) { <ide> name: 'form', <ide> restrict: isNgForm ? 'EAC' : 'E', <ide> controller: FormController, <del> compile: function() { <add> compile: function ngFormCompile(formElement) { <add> // Setup initial state of the control <add> formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS); <add> <ide> return { <del> pre: function(scope, formElement, attr, controller) { <add> pre: function ngFormPreLink(scope, formElement, attr, controller) { <ide> if (!attr.action) { <ide> // we can't use jq events because if a form is destroyed during submission the default <ide> // action is not prevented. see #1238 <ide><path>src/ng/directive/input.js <ide> var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$ <ide> var parentForm = $element.inheritedData('$formController') || nullFormCtrl, <ide> currentValidationRunId = 0; <ide> <del> // Setup initial state of the control <del> $element <del> .addClass(PRISTINE_CLASS) <del> .addClass(UNTOUCHED_CLASS); <del> <ide> /** <ide> * @ngdoc method <ide> * @name ngModel.NgModelController#$setValidity <ide> var ngModelDirective = function() { <ide> restrict: 'A', <ide> require: ['ngModel', '^?form', '^?ngModelOptions'], <ide> controller: NgModelController, <del> link: { <del> pre: function(scope, element, attr, ctrls) { <del> var modelCtrl = ctrls[0], <del> formCtrl = ctrls[1] || nullFormCtrl; <add> compile: function ngModelCompile(element) { <add> // Setup initial state of the control <add> element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS); <ide> <del> modelCtrl.$$setOptions(ctrls[2] && ctrls[2].$options); <add> return { <add> pre: function ngModelPreLink(scope, element, attr, ctrls) { <add> var modelCtrl = ctrls[0], <add> formCtrl = ctrls[1] || nullFormCtrl; <ide> <del> // notify others, especially parent forms <del> formCtrl.$addControl(modelCtrl); <add> modelCtrl.$$setOptions(ctrls[2] && ctrls[2].$options); <ide> <del> attr.$observe('name', function(newValue) { <del> if (modelCtrl.$name !== newValue) { <del> formCtrl.$$renameControl(modelCtrl, newValue); <del> } <del> }); <add> // notify others, especially parent forms <add> formCtrl.$addControl(modelCtrl); <ide> <del> scope.$on('$destroy', function() { <del> formCtrl.$removeControl(modelCtrl); <del> }); <del> }, <del> post: function(scope, element, attr, ctrls) { <del> var modelCtrl = ctrls[0]; <del> if (modelCtrl.$options && modelCtrl.$options.updateOn) { <del> element.on(modelCtrl.$options.updateOn, function(ev) { <del> modelCtrl.$$debounceViewValueCommit(ev && ev.type); <add> attr.$observe('name', function(newValue) { <add> if (modelCtrl.$name !== newValue) { <add> formCtrl.$$renameControl(modelCtrl, newValue); <add> } <ide> }); <del> } <ide> <del> element.on('blur', function(ev) { <del> if (modelCtrl.$touched) return; <add> scope.$on('$destroy', function() { <add> formCtrl.$removeControl(modelCtrl); <add> }); <add> }, <add> post: function ngModelPostLink(scope, element, attr, ctrls) { <add> var modelCtrl = ctrls[0]; <add> if (modelCtrl.$options && modelCtrl.$options.updateOn) { <add> element.on(modelCtrl.$options.updateOn, function(ev) { <add> modelCtrl.$$debounceViewValueCommit(ev && ev.type); <add> }); <add> } <add> <add> element.on('blur', function(ev) { <add> if (modelCtrl.$touched) return; <ide> <del> scope.$apply(function() { <del> modelCtrl.$setTouched(); <add> scope.$apply(function() { <add> modelCtrl.$setTouched(); <add> }); <ide> }); <del> }); <del> } <add> } <add> }; <ide> } <ide> }; <ide> }; <ide> function addSetValidityMethod(context) { <ide> parentForm = context.parentForm, <ide> $animate = context.$animate; <ide> <add> classCache[INVALID_CLASS] = !(classCache[VALID_CLASS] = $element.hasClass(VALID_CLASS)); <add> <ide> ctrl.$setValidity = setValidity; <del> toggleValidationCss('', true); <ide> <ide> function setValidity(validationErrorKey, state, options) { <ide> if (state === undefined) {
2
Java
Java
fix failing headerassertiontests
7f845f7b5e6031aee2f1dc37f0965a5be4442a34
<ide><path>spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resultmatchers/HeaderAssertionTests.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> public void longValueWithCorrectResponseHeaderValue() throws Exception { <ide> public void stringWithMissingResponseHeader() throws Exception { <ide> this.mockMvc.perform(get("/persons/1").header(IF_MODIFIED_SINCE, currentTime))// <ide> .andExpect(status().isNotModified())// <del> .andExpect(header().string(LAST_MODIFIED, (String) null)); <add> .andExpect(header().string("X-Custom-Header", (String) null)); <ide> } <ide> <ide> @Test <ide> public void stringWithMatcherAndMissingResponseHeader() throws Exception { <ide> this.mockMvc.perform(get("/persons/1").header(IF_MODIFIED_SINCE, currentTime))// <ide> .andExpect(status().isNotModified())// <del> .andExpect(header().string(LAST_MODIFIED, nullValue())); <add> .andExpect(header().string("X-Custom-Header", nullValue())); <ide> } <ide> <ide> @Test <ide> public void longValueWithMissingResponseHeader() throws Exception { <ide> try { <ide> this.mockMvc.perform(get("/persons/1").header(IF_MODIFIED_SINCE, currentTime))// <ide> .andExpect(status().isNotModified())// <del> .andExpect(header().longValue(LAST_MODIFIED, 99L)); <add> .andExpect(header().longValue("X-Custom-Header", 99L)); <ide> <ide> fail(EXPECTED_ASSERTION_ERROR_MSG); <ide> } <ide> catch (AssertionError e) { <ide> if (EXPECTED_ASSERTION_ERROR_MSG.equals(e.getMessage())) { <ide> throw e; <ide> } <del> assertEquals("Response does not contain header " + LAST_MODIFIED, e.getMessage()); <add> assertEquals("Response does not contain header " + "X-Custom-Header", e.getMessage()); <ide> } <ide> } <ide>
1
Text
Text
add link to logging drivers reference
7ca02f86de2ceef980cad98faefc15cbc628c91a
<ide><path>docs/reference/commandline/logs.md <ide> Options: <ide> -t, --timestamps Show timestamps <ide> ``` <ide> <del>> **Note**: this command is available only for containers with `json-file` and <del>> `journald` logging drivers. <del> <ide> The `docker logs` command batch-retrieves logs present at the time of execution. <ide> <add>> **Note**: this command is only functional for containers that are started with <add>> the `json-file` or `journald` logging driver. <add> <add>For more information about selecting and configuring login-drivers, refer to <add>[Configure logging drivers](../../admin/logging/overview.md). <add> <ide> The `docker logs --follow` command will continue streaming the new output from <ide> the container's `STDOUT` and `STDERR`. <ide>
1
PHP
PHP
add knowledge, love and rain to uncountable array
964f69f66e2c9b4e3e0557ee26417dfe2936cf3d
<ide><path>src/Illuminate/Support/Pluralizer.php <ide> class Pluralizer <ide> 'fish', <ide> 'gold', <ide> 'information', <add> 'knowledge', <add> 'love', <add> 'rain', <ide> 'money', <ide> 'moose', <ide> 'offspring',
1
PHP
PHP
fix null value injected from container in routes
60027c4a1a0fd42fe00f38993167fc6e26fde694
<ide><path>src/Illuminate/Routing/RouteDependencyResolverTrait.php <ide> public function resolveMethodDependencies(array $parameters, ReflectionFunctionA <ide> <ide> $values = array_values($parameters); <ide> <add> $shouldSkipValue = new \StdClass; <add> <ide> foreach ($reflector->getParameters() as $key => $parameter) { <del> $instance = $this->transformDependency( <del> $parameter, $parameters <del> ); <add> $instance = $this->transformDependency($parameter, $parameters, $shouldSkipValue); <ide> <del> if (! is_null($instance)) { <add> if ($instance !== $shouldSkipValue) { <ide> $instanceCount++; <ide> <ide> $this->spliceIntoParameters($parameters, $key, $instance); <ide> public function resolveMethodDependencies(array $parameters, ReflectionFunctionA <ide> * <ide> * @param \ReflectionParameter $parameter <ide> * @param array $parameters <add> * @param object $shouldSkipValue <ide> * @return mixed <ide> */ <del> protected function transformDependency(ReflectionParameter $parameter, $parameters) <add> protected function transformDependency(ReflectionParameter $parameter, $parameters, $shouldSkipValue) <ide> { <ide> $class = $parameter->getClass(); <ide> <ide> // If the parameter has a type-hinted class, we will check to see if it is already in <ide> // the list of parameters. If it is we will just skip it as it is probably a model <ide> // binding and we do not want to mess with those; otherwise, we resolve it here. <ide> if ($class && ! $this->alreadyInParameters($class->name, $parameters)) { <del> return $parameter->isDefaultValueAvailable() <del> ? $parameter->getDefaultValue() <del> : $this->container->make($class->name); <add> // If it has a default value and is not already resolved, it's <add> // probably an optional model binding not present in the url. <add> return $parameter->isDefaultValueAvailable() ? null : $this->container->make($class->name); <ide> } <add> <add> return $shouldSkipValue; <ide> } <ide> <ide> /** <ide><path>tests/Routing/RoutingRouteTest.php <ide> public function testClassesCanBeInjectedIntoRoutes() <ide> unset($_SERVER['__test.route_inject']); <ide> } <ide> <add> public function testNullValuesCanBeInjectedIntoRoutes() <add> { <add> $container = new Container; <add> $router = new Router(new Dispatcher, $container); <add> $container->singleton(Registrar::class, function () use ($router) { <add> return $router; <add> }); <add> <add> $container->bind(RoutingTestUserModel::class, function() { <add> return null; <add> }); <add> <add> $router->get('foo/{team}/{post}', [ <add> 'middleware' => SubstituteBindings::class, <add> 'uses' => function (?RoutingTestUserModel $userFromContainer, RoutingTestTeamModel $team, $postId) { <add> $this->assertSame(null, $userFromContainer); <add> $this->assertInstanceOf(RoutingTestTeamModel::class, $team); <add> $this->assertSame('bar', $team->value); <add> $this->assertSame('baz', $postId); <add> }, <add> ]); <add> $router->dispatch(Request::create('foo/bar/baz', 'GET'))->getContent(); <add> } <add> <ide> public function testOptionsResponsesAreGeneratedByDefault() <ide> { <ide> $router = $this->getRouter();
2
PHP
PHP
fix typo in description
602e0f923c94ff44cf0916c4a49ee8495c0ce3d9
<ide><path>src/Shell/CacheShell.php <ide> public function getOptionParser() <ide> 'description' => [ <ide> 'Clear the cache for a particular prefix.', <ide> 'For example, `cake cache clear _cake_model_` will clear the model cache', <del> 'Use `cake cache clear list_prefixes` to list available prefixes' <add> 'Use `cake cache list_prefixes` to list available prefixes' <ide> ], <ide> 'arguments' => [ <ide> 'prefix' => [
1
PHP
PHP
add status code `429 too many requests`
4c3eeb1857f52a2027840bf15f48a01f4a5d2aa8
<ide><path>src/Network/Response.php <ide> class Response <ide> 415 => 'Unsupported Media Type', <ide> 416 => 'Requested range not satisfiable', <ide> 417 => 'Expectation Failed', <add> 429 => 'Too Many Requests', <ide> 500 => 'Internal Server Error', <ide> 501 => 'Not Implemented', <ide> 502 => 'Bad Gateway',
1
PHP
PHP
remove invalid docblock
597f5ab16d0d2df67e50fedfd2fa66789b29998c
<ide><path>src/Illuminate/Database/Eloquent/SoftDeletes.php <ide> * @method static static|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Builder withTrashed(bool $withTrashed = true) <ide> * @method static static|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Builder onlyTrashed() <ide> * @method static static|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Builder withoutTrashed() <del> * @method static static|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Builder restore() <ide> */ <ide> trait SoftDeletes <ide> {
1
Javascript
Javascript
ignore more parent properties
6661f147e764f5275e4301ca5f4dadea1893a283
<ide><path>packages/ember-metal/lib/mixin.js <ide> function findNamespaces() { <ide> // globalStorage is a storage obsoleted by the WhatWG storage specification. See https://developer.mozilla.org/en/DOM/Storage#globalStorage <ide> if (prop === "globalStorage" && window.StorageList && window.globalStorage instanceof window.StorageList) { continue; } <ide> // Don't access properties on parent window, which will throw "Access/Permission Denied" in IE/Firefox for windows on different domains <del> if (prop === "parent") { continue; } <add> if (prop === "parent" || prop === "top" || prop === "frameElement" || prop === "content") { continue; } <ide> // Unfortunately, some versions of IE don't support window.hasOwnProperty <ide> if (window.hasOwnProperty && !window.hasOwnProperty(prop)) { continue; } <ide>
1
PHP
PHP
remove unneeded instanceof check
b200465653f1633a0fa644369fb6012976707f24
<ide><path>src/View/Form/ContextFactory.php <ide> public function addProvider(string $type, callable $check) <ide> * @param \Cake\Http\ServerRequest $request Request instance. <ide> * @param array $data The data to get a context provider for. <ide> * @return \Cake\View\Form\ContextInterface Context provider. <del> * @throws \RuntimeException When a context instace cannot be generated for <del> * given entity or context class does not implement the ContextInterface. <add> * @throws \RuntimeException When a context instace cannot be generated for given entity. <ide> */ <ide> public function get(ServerRequest $request, array $data = []): ContextInterface <ide> { <ide> public function get(ServerRequest $request, array $data = []): ContextInterface <ide> break; <ide> } <ide> } <add> <ide> if (!isset($context)) { <ide> throw new RuntimeException(sprintf( <ide> 'No context provider found for entity of type `%s`.', <ide> getTypeName($data['entity']) <ide> )); <ide> } <del> if (!($context instanceof ContextInterface)) { <del> throw new RuntimeException(sprintf( <del> 'Context providers must return object implementing %s. Got "%s" instead.', <del> ContextInterface::class, <del> getTypeName($context) <del> )); <del> } <ide> <ide> return $context; <ide> } <ide><path>tests/TestCase/View/Helper/FormHelperTest.php <ide> public function testAddContextProviderAdd() <ide> */ <ide> public function testAddContextProviderInvalid() <ide> { <del> $this->expectException(\RuntimeException::class); <del> $this->expectExceptionMessage('Context providers must return object implementing Cake\View\Form\ContextInterface. Got "stdClass" instead.'); <add> $this->expectException(\TypeError::class); <add> $this->expectExceptionMessage('Return value of Cake\View\Form\ContextFactory::get() must implement interface Cake\View\Form\ContextInterface, instance of stdClass returned'); <ide> $context = 'My data'; <ide> $this->Form->addContextProvider('test', function ($request, $data) use ($context) { <ide> return new \StdClass();
2
Javascript
Javascript
fix spelling of 'existence'
c0de6b51ff17ea94bfc57e66b801d54d1587adb3
<ide><path>src/browser/ui/ReactDOMComponent.js <ide> ReactDOMComponent.Mixin = { <ide> // we can do a cheap identity compare here to determine if this is a <ide> // superfluous reconcile. It's possible for state to be mutable but such <ide> // change should trigger an update of the owner which would recreate <del> // the descriptor. We explicitly check for the existance of an owner since <add> // the descriptor. We explicitly check for the existence of an owner since <ide> // it's possible for a descriptor created outside a composite to be <ide> // deeply mutated and reused. <ide> return; <ide><path>src/core/ReactCompositeComponent.js <ide> var ReactCompositeComponentMixin = { <ide> // we can do a cheap identity compare here to determine if this is a <ide> // superfluous reconcile. It's possible for state to be mutable but such <ide> // change should trigger an update of the owner which would recreate <del> // the descriptor. We explicitly check for the existance of an owner since <add> // the descriptor. We explicitly check for the existence of an owner since <ide> // it's possible for a descriptor created outside a composite to be <ide> // deeply mutated and reused. <ide> return;
2
Ruby
Ruby
use presence method instead of checking for blank
6927fadbe7c3768f94d91dcd9197dc6c68cff6d7
<ide><path>actionpack/lib/action_view/lookup_context.rb <ide> def detail_args_for(options) <ide> # as well as incorrectly putting part of the path in the template <ide> # name instead of the prefix. <ide> def normalize_name(name, prefixes) #:nodoc: <del> prefixes = nil if prefixes.blank? <add> prefixes = prefixes.presence <ide> parts = name.to_s.split('/') <ide> parts.shift if parts.first.empty? <ide> name = parts.pop
1
Text
Text
remove extraneous full stop after exclamation mark
4f898f687d534cf08386dfc1874eb5027319d621
<ide><path>docs/tutorials/fundamentals/part-3-state-actions-reducers.md <ide> const todoAppState = { <ide> } <ide> ``` <ide> <del>It's important to note that **it's okay to have other state values outside of Redux!**. This example is small enough so far that we actually do have all our state in the Redux store, but as we'll see later, some data really doesn't need to be kept in Redux (like "is this dropdown open?" or "current value of a form input"). <add>It's important to note that **it's okay to have other state values outside of Redux!** This example is small enough so far that we actually do have all our state in the Redux store, but as we'll see later, some data really doesn't need to be kept in Redux (like "is this dropdown open?" or "current value of a form input"). <ide> <ide> ### Designing Actions <ide>
1
Python
Python
add type check to axis
96148d86f3b2fe52ac99c898d2adcb5cca7ddde5
<ide><path>keras/losses.py <ide> def categorical_crossentropy(y_true, <ide> Categorical crossentropy loss value. <ide> """ <ide> #axis assert <del> check_ops.assert_integer_v2(axis, message=('`axis` must be of type `int`.')) <add> check_ops.assert_integer_v2(int(axis), message=('`axis` must be of type `int`.')) <ide> y_pred = tf.convert_to_tensor(y_pred) <ide> y_true = tf.cast(y_true, y_pred.dtype) <ide> label_smoothing = tf.convert_to_tensor(label_smoothing, dtype=y_pred.dtype)
1
Ruby
Ruby
allow deprecated hash syntax in cask headers
5b593ebb8958cc57cfbbd7013ca3d275466d66bf
<ide><path>Library/Homebrew/cask/lib/hbc/source/path_base.rb <ide> def test_cask(header_token, &block) <ide> end <ide> <ide> def build_cask(cask_class, header_token, &block) <add> if header_token.is_a?(Hash) <add> # Cask file is using old `cask :v1 => 'token'` syntax <add> header_token = header_token.values.first <add> end <ide> raise Hbc::CaskTokenDoesNotMatchError.new(cask_token, header_token) unless cask_token == header_token <ide> cask_class.new(cask_token, sourcefile_path: path, &block) <ide> end <ide><path>Library/Homebrew/cask/test/cask/dsl_test.rb <ide> <ide> it "does not require a DSL version in the header" do <ide> test_cask = Hbc.load("no-dsl-version") <add> test_cask.token.must_equal "no-dsl-version" <add> test_cask.url.to_s.must_equal "http://example.com/TestCask.dmg" <add> test_cask.homepage.must_equal "http://example.com/" <add> test_cask.version.to_s.must_equal "1.2.3" <add> end <add> <add> it "may use deprecated DSL version hash syntax" do <add> test_cask = Hbc.load("with-dsl-version") <add> test_cask.token.must_equal "with-dsl-version" <ide> test_cask.url.to_s.must_equal "http://example.com/TestCask.dmg" <ide> test_cask.homepage.must_equal "http://example.com/" <ide> test_cask.version.to_s.must_equal "1.2.3" <ide><path>Library/Homebrew/cask/test/support/Casks/with-dsl-version.rb <add>test_cask :v1 => 'with-dsl-version' do <add> version '1.2.3' <add> sha256 '8c62a2b791cf5f0da6066a0a4b6e85f62949cd60975da062df44adf887f4370b' <add> <add> url 'http://example.com/TestCask.dmg' <add> homepage 'http://example.com/' <add> <add> app 'TestCask.app' <add>end
3
Text
Text
add experimental note to docs for has
1cf7360788a35485c45d69b5f24427c3fe6fb6cc
<ide><path>docs/api-reference/next.config.js/headers.md <ide> module.exports = { <ide> <ide> ## Header, Cookie, and Query Matching <ide> <add>Note: this feature is still experimental and not covered by semver and is to be used at your own risk until it is made stable. <add> <ide> To only apply a header when either header, cookie, or query values also match the `has` field can be used. Both the `source` and all `has` items must match for the header to be applied. <ide> <ide> `has` items have the following fields: <ide><path>docs/api-reference/next.config.js/redirects.md <ide> module.exports = { <ide> <ide> ## Header, Cookie, and Query Matching <ide> <add>Note: this feature is still experimental and not covered by semver and is to be used at your own risk until it is made stable. <add> <ide> To only match a redirect when header, cookie, or query values also match the `has` field can be used. Both the `source` and all `has` items must match for the redirect to be applied. <ide> <ide> `has` items have the following fields: <ide><path>docs/api-reference/next.config.js/rewrites.md <ide> module.exports = { <ide> <ide> ## Header, Cookie, and Query Matching <ide> <add>Note: this feature is still experimental and not covered by semver and is to be used at your own risk until it is made stable. <add> <ide> To only match a rewrite when header, cookie, or query values also match the `has` field can be used. Both the `source` and all `has` items must match for the rewrite to be applied. <ide> <ide> `has` items have the following fields:
3
Javascript
Javascript
transform html scripts
4bf89a873eed4802ff08362e7ade08f0b332c360
<ide><path>client/src/templates/Challenges/rechallenge/builders.js <ide> A required file can not have both a src and a link: src = ${src}, link = ${link} <ide> <ide> const body = Promise.all(files).then(files => <ide> files <del> .reduce( <del> (body, file) => [...body, file.contents + file.tail + htmlCatch], <del> [] <del> ) <add> .reduce((body, file) => [...body, file.contents + htmlCatch], []) <ide> .map(source => createBody({ source })) <ide> ); <ide> <ide><path>client/src/templates/Challenges/rechallenge/transformers.js <ide> export const babelTransformer = cond([ <ide> ]); <ide> <ide> const sassWorker = new WorkerExecutor('sass-compile'); <add>async function transformSASS(element) { <add> const styleTags = element.querySelectorAll('style[type="text/sass"]'); <add> await Promise.all( <add> [].map.call(styleTags, async style => { <add> style.type = 'text/css'; <add> style.innerHTML = await sassWorker.execute(style.innerHTML, 2000); <add> }) <add> ); <add>} <add> <add>function transformScript(element) { <add> const scriptTags = element.querySelectorAll('script'); <add> scriptTags.forEach(script => { <add> script.innerHTML = tryTransform(babelTransformCode(babelOptionsJSX))( <add> script.innerHTML <add> ); <add> }); <add>} <ide> <del>const htmlSassTransformCode = file => { <add>const transformHtml = async function(file) { <ide> const div = document.createElement('div'); <ide> div.innerHTML = file.contents; <del> const styleTags = div.querySelectorAll('style[type="text/sass"]'); <del> if (styleTags.length > 0) { <del> return Promise.all( <del> [].map.call(styleTags, async style => { <del> style.type = 'text/css'; <del> style.innerHTML = await sassWorker.execute(style.innerHTML, 2000); <del> }) <del> ).then(() => vinyl.transformContents(() => div.innerHTML, file)); <del> } <add> await Promise.all([transformSASS(div), transformScript(div)]); <ide> return vinyl.transformContents(() => div.innerHTML, file); <ide> }; <ide> <del>export const htmlSassTransformer = cond([ <del> [testHTML, htmlSassTransformCode], <add>export const composeHTML = cond([ <add> [ <add> testHTML, <add> flow( <add> partial( <add> vinyl.transformHeadTailAndContents, <add> source => { <add> const div = document.createElement('div'); <add> div.innerHTML = source; <add> return div.innerHTML; <add> } <add> ), <add> partial(vinyl.compileHeadTail, '') <add> ) <add> ], <add> [stubTrue, identity] <add>]); <add> <add>export const htmlTransformer = cond([ <add> [testHTML, transformHtml], <ide> [stubTrue, identity] <ide> ]); <ide> <ide> export const transformers = [ <ide> replaceNBSP, <ide> babelTransformer, <del> htmlSassTransformer <add> composeHTML, <add> htmlTransformer <ide> ];
2
Go
Go
fix wrapf args
2e30e9e6db42043cb2bd67d25a7152488c834f9f
<ide><path>daemon/graphdriver/aufs/aufs.go <ide> func atomicRemove(source string) error { <ide> case os.IsExist(err): <ide> // Got error saying the target dir already exists, maybe the source doesn't exist due to a previous (failed) remove <ide> if _, e := os.Stat(source); !os.IsNotExist(e) { <del> return errors.Wrapf(err, "target rename dir '%s' exists but should not, this needs to be manually cleaned up") <add> return errors.Wrapf(err, "target rename dir %q exists but should not, this needs to be manually cleaned up", target) <ide> } <ide> default: <ide> return errors.Wrapf(err, "error preparing atomic delete")
1
Javascript
Javascript
add spec for heapcapture
94029eee546cc8f95cedbb1dd4be73a6a62e53a9
<ide><path>Libraries/Core/setUpBatchedBridge.js <ide> BatchedBridge.registerLazyCallableModule('JSTimers', () => <ide> require('./Timers/JSTimers'), <ide> ); <ide> BatchedBridge.registerLazyCallableModule('HeapCapture', () => <del> require('../Utilities/HeapCapture'), <add> require('../HeapCapture/HeapCapture'), <ide> ); <ide> BatchedBridge.registerLazyCallableModule('SamplingProfiler', () => <ide> require('../Performance/SamplingProfiler'), <add><path>Libraries/HeapCapture/HeapCapture.js <del><path>Libraries/Utilities/HeapCapture.js <ide> <ide> 'use strict'; <ide> <add>import NativeHeapCapture from './NativeHeapCapture'; <add> <ide> const HeapCapture = { <ide> captureHeap: function(path: string) { <ide> let error = null; <ide> const HeapCapture = { <ide> console.log('HeapCapture.captureHeap error: ' + e.toString()); <ide> error = e.toString(); <ide> } <del> require('../BatchedBridge/NativeModules').JSCHeapCapture.captureComplete( <del> path, <del> error, <del> ); <add> if (NativeHeapCapture) { <add> NativeHeapCapture.captureComplete(path, error); <add> } <ide> }, <ide> }; <ide> <ide><path>Libraries/HeapCapture/NativeHeapCapture.js <add>/** <add> * Copyright (c) Facebook, Inc. and its affiliates. <add> * <add> * This source code is licensed under the MIT license found in the <add> * LICENSE file in the root directory of this source tree. <add> * <add> * @flow <add> * @format <add> */ <add> <add>'use strict'; <add> <add>import type {TurboModule} from 'RCTExport'; <add>import * as TurboModuleRegistry from 'TurboModuleRegistry'; <add> <add>export interface Spec extends TurboModule { <add> // Common interface <add> +captureHeap: (path: string) => void; <add> <add> // Android only <add> +captureComplete: (path: string, error: ?string) => void; <add>} <add> <add>export default TurboModuleRegistry.get<Spec>('HeapCapture');
3
Python
Python
fix remaining misuses of bool(dt.names)
483f565d85dadc899f94710531fba8355d554d59
<ide><path>numpy/lib/recfunctions.py <ide> def recursive_fill_fields(input, output): <ide> current = input[field] <ide> except ValueError: <ide> continue <del> if current.dtype.names: <add> if current.dtype.names is not None: <ide> recursive_fill_fields(current, output[field]) <ide> else: <ide> output[field][:len(current)] = current <ide> def merge_arrays(seqarrays, fill_value=-1, flatten=False, <ide> if isinstance(seqarrays, (ndarray, np.void)): <ide> seqdtype = seqarrays.dtype <ide> # Make sure we have named fields <del> if not seqdtype.names: <add> if seqdtype.names is None: <ide> seqdtype = np.dtype([('', seqdtype)]) <ide> if not flatten or zip_dtype((seqarrays,), flatten=True) == seqdtype: <ide> # Minimal processing needed: just make sure everythng's a-ok <ide> def _recursive_rename_fields(ndtype, namemapper): <ide> for name in ndtype.names: <ide> newname = namemapper.get(name, name) <ide> current = ndtype[name] <del> if current.names: <add> if current.names is not None: <ide> newdtype.append( <ide> (newname, _recursive_rename_fields(current, namemapper)) <ide> )
1
Python
Python
fix backfill occassional deadlocking
6931fbf8f7c0e3dfe96ce51ef03f2b1502baef07
<ide><path>airflow/jobs/backfill_job.py <ide> def _get_dag_run(self, dagrun_info: DagRunInfo, dag: DAG, session: Session = Non <ide> return run <ide> <ide> @provide_session <del> def _task_instances_for_dag_run(self, dag_run, session=None): <add> def _task_instances_for_dag_run(self, dag, dag_run, session=None): <ide> """ <ide> Returns a map of task instance key to task instance object for the tasks to <ide> run in the given dag run. <ide> def _task_instances_for_dag_run(self, dag_run, session=None): <ide> dag_run.refresh_from_db() <ide> make_transient(dag_run) <ide> <add> dag_run.dag = dag <add> info = dag_run.task_instance_scheduling_decisions(session=session) <add> schedulable_tis = info.schedulable_tis <ide> try: <del> for ti in dag_run.get_task_instances(): <del> # all tasks part of the backfill are scheduled to run <del> if ti.state == State.NONE: <del> ti.set_state(TaskInstanceState.SCHEDULED, session=session) <add> for ti in dag_run.get_task_instances(session=session): <add> if ti in schedulable_tis: <add> ti.set_state(TaskInstanceState.SCHEDULED) <ide> if ti.state != TaskInstanceState.REMOVED: <ide> tasks_to_run[ti.key] = ti <ide> session.commit() <ide> except Exception: <ide> session.rollback() <ide> raise <del> <ide> return tasks_to_run <ide> <ide> def _log_progress(self, ti_status): <ide> def _per_task_process(key, ti: TaskInstance, session=None): <ide> ti_status.running.pop(key) <ide> return <ide> <del> # guard against externally modified tasks instances or <del> # in case max concurrency has been reached at task runtime <del> elif ti.state == State.NONE: <del> self.log.warning( <del> "FIXME: Task instance %s state was set to None externally. This should not happen", ti <del> ) <del> ti.set_state(TaskInstanceState.SCHEDULED, session=session) <ide> if self.rerun_failed_tasks: <ide> # Rerun failed tasks or upstreamed failed tasks <ide> if ti.state in (TaskInstanceState.FAILED, TaskInstanceState.UPSTREAM_FAILED): <ide> def _execute_dagruns(self, dagrun_infos, ti_status, executor, pickle_id, start_d <ide> for dagrun_info in dagrun_infos: <ide> for dag in self._get_dag_with_subdags(): <ide> dag_run = self._get_dag_run(dagrun_info, dag, session=session) <del> tis_map = self._task_instances_for_dag_run(dag_run, session=session) <add> tis_map = self._task_instances_for_dag_run(dag, dag_run, session=session) <ide> if dag_run is None: <ide> continue <ide> <ide><path>tests/jobs/test_backfill_job.py <ide> def test_backfill_override_conf(self, dag_maker): <ide> wraps=job._task_instances_for_dag_run, <ide> ) as wrapped_task_instances_for_dag_run: <ide> job.run() <del> dr = wrapped_task_instances_for_dag_run.call_args_list[0][0][0] <add> dr = wrapped_task_instances_for_dag_run.call_args_list[0][0][1] <ide> assert dr.conf == {"a": 1} <ide> <ide> def test_backfill_skip_active_scheduled_dagrun(self, dag_maker, caplog): <ide> def test_start_date_set_for_resetted_dagruns(self, dag_maker, session, caplog): <ide> (dr,) = DagRun.find(dag_id=dag.dag_id, execution_date=DEFAULT_DATE, session=session) <ide> assert dr.start_date <ide> assert f'Failed to record duration of {dr}' not in caplog.text <add> <add> def test_task_instances_are_not_set_to_scheduled_when_dagrun_reset(self, dag_maker, session): <add> """Test that when dagrun is reset, task instances are not set to scheduled""" <add> <add> with dag_maker() as dag: <add> task1 = EmptyOperator(task_id='task1') <add> task2 = EmptyOperator(task_id='task2') <add> task3 = EmptyOperator(task_id='task3') <add> task1 >> task2 >> task3 <add> <add> for i in range(1, 4): <add> dag_maker.create_dagrun( <add> run_id=f'test_dagrun_{i}', execution_date=DEFAULT_DATE + datetime.timedelta(days=i) <add> ) <add> <add> dag.clear() <add> <add> job = BackfillJob( <add> dag=dag, <add> start_date=DEFAULT_DATE + datetime.timedelta(days=1), <add> end_date=DEFAULT_DATE + datetime.timedelta(days=4), <add> executor=MockExecutor(), <add> donot_pickle=True, <add> ) <add> for dr in DagRun.find(dag_id=dag.dag_id, session=session): <add> tasks_to_run = job._task_instances_for_dag_run(dag, dr, session=session) <add> states = [ti.state for _, ti in tasks_to_run.items()] <add> assert TaskInstanceState.SCHEDULED in states <add> assert State.NONE in states
2
Python
Python
add __repr__ and __str__ methods
91f8df844a1dc0d288b969d89465b707a541efd6
<ide><path>libcloud/compute/ssh.py <ide> def __init__(self, cmd, timeout): <ide> message = 'Command didn\'t finish in %s seconds' % (timeout) <ide> super(SSHCommandTimeoutError, self).__init__(message) <ide> <add> def __repr__(self): <add> return ('<SSHCommandTimeoutError: cmd="%s",timeout=%s)>' % <add> (self.cmd, self.timeout)) <add> <add> def __str__(self): <add> return self.message <add> <ide> <ide> class BaseSSHClient(object): <ide> """
1
Javascript
Javascript
fix missing methods in keyboard module
5105c09f56035df595104666e370a9fc57ca4dcd
<ide><path>Libraries/Components/Keyboard/Keyboard.js <ide> */ <ide> 'use strict'; <ide> <add>const invariant = require('fbjs/lib/invariant'); <ide> const NativeEventEmitter = require('NativeEventEmitter'); <ide> const KeyboardObserver = require('NativeModules').KeyboardObserver; <ide> const dismissKeyboard = require('dismissKeyboard'); <ide> const KeyboardEventEmitter = new NativeEventEmitter(KeyboardObserver); <ide> <add>type KeyboardEventName = <add> | 'keyboardWillShow' <add> | 'keyboardDidShow' <add> | 'keyboardWillHide' <add> | 'keyboardDidHide' <add> | 'keyboardWillChangeFrame' <add> | 'keyboardDidChangeFrame'; <add> <add>type KeyboardEventData = { <add> endCoordinates: { <add> width: number, <add> height: number, <add> screenX: number, <add> screenY: number, <add> }, <add>}; <add> <add>type KeyboardEventListener = (e: KeyboardEventData) => void; <add> <ide> // The following object exists for documentation purposes <ide> // Actual work happens in <ide> // https://github.com/facebook/react-native/blob/master/Libraries/EventEmitter/NativeEventEmitter.js <add> <ide> /** <del> * `Keyboard` component to control keyboard events. <add> * `Keyboard` module to control keyboard events. <ide> * <ide> * ### Usage <ide> * <del> * The Keyboard component allows you to listen for native events and react to them, as <add> * The Keyboard module allows you to listen for native events and react to them, as <ide> * well as make changes to the keyboard, like dismissing it. <ide> * <ide> *``` <ide> const KeyboardEventEmitter = new NativeEventEmitter(KeyboardObserver); <ide> * } <ide> *``` <ide> */ <del>module.exports = { <ide> <add>let Keyboard = { <ide> /** <ide> * The `addListener` function connects a JavaScript function to an identified native <ide> * keyboard notification event. <ide> * <ide> * This function then returns the reference to the listener. <ide> * <del> * @param {string} nativeEvent The `nativeEvent` is the string that identifies the event you're listening for. This <add> * @param {string} eventName The `nativeEvent` is the string that identifies the event you're listening for. This <ide> *can be any of the following: <add> * <ide> * - `keyboardWillShow` <ide> * - `keyboardDidShow` <ide> * - `keyboardWillHide` <ide> * - `keyboardDidHide` <ide> * - `keyboardWillChangeFrame` <ide> * - `keyboardDidChangeFrame` <ide> * <del> * @param {function} jsFunction function to be called when the event fires. <add> * @param {function} callback function to be called when the event fires. <ide> */ <del> addListener (nativeEvent: string, jsFunction: Function) { <del> return KeyboardEventEmitter.addListener(nativeEvent, jsFunction); <add> addListener(eventName: KeyboardEventName, callback: KeyboardEventListener) { <add> invariant(false, 'Dummy method used for documentation'); <ide> }, <ide> <ide> /** <del> * Removes all listeners for a specific event type. <add> * Removes a specific listener. <ide> * <del> * @param {string} eventType The native event string listeners are watching which will be removed. <add> * @param {string} eventName The `nativeEvent` is the string that identifies the event you're listening for. <add> * @param {function} callback function to be called when the event fires. <ide> */ <del> removeAllListeners (eventType: string) { <del> KeyboardEventEmitter.removeAllListeners(eventType); <add> removeListener(eventName: KeyboardEventName, callback: Function) { <add> invariant(false, 'Dummy method used for documentation'); <ide> }, <ide> <ide> /** <del> * Removes a specific subscription. <add> * Removes all listeners for a specific event type. <ide> * <del> * @param {EmitterSubscription} subscription The subscription emitter to be removed. <add> * @param {string} eventType The native event string listeners are watching which will be removed. <ide> */ <del> removeSubscription (subscription: Object) { <del> KeyboardEventEmitter.removeSubscription(subscription); <add> removeAllListeners(eventName: KeyboardEventName) { <add> invariant(false, 'Dummy method used for documentation'); <ide> }, <ide> <ide> /** <ide> * Dismisses the active keyboard and removes focus. <ide> */ <del> dismiss () { <del> dismissKeyboard(); <add> dismiss() { <add> invariant(false, 'Dummy method used for documentation'); <ide> } <del> <ide> }; <add> <add>// Throw away the dummy object and reassign it to original module <add>Keyboard = KeyboardEventEmitter; <add>Keyboard.dismiss = dismissKeyboard; <add> <add>module.exports = Keyboard; <add>
1
Text
Text
add require(atom) for home directory example
94d4ad618caa00a0b8b228a40cd46e4d3192fba5
<ide><path>CONTRIBUTING.md <ide> * Class methods (methods starting with a `@`) <ide> * Instance methods <ide> * Beware of platform differences <del> * Use `fs.getHomeDirectory()` to get home directory. <add> * Use `require('atom').fs.getHomeDirectory()` to get the home directory. <ide> * Use `path.join()` to concatenate filenames. <ide> * Temporary directory is not `/tmp` on Windows, use `os.tmpdir()` when <ide> possible
1
Javascript
Javascript
use switch in matchheader
54caeae38a66841b7f7119649dc78ce55c8a7c52
<ide><path>lib/_http_outgoing.js <ide> const { utcDate } = internalHttp; <ide> <ide> const kIsCorked = Symbol('isCorked'); <ide> <del>var RE_FIELDS = <del> /^(?:Connection|Transfer-Encoding|Content-Length|Date|Expect|Trailer|Upgrade)$/i; <ide> var RE_CONN_VALUES = /(?:^|\W)close|upgrade(?:$|\W)/ig; <ide> var RE_TE_CHUNKED = common.chunkExpression; <ide> <ide> function matchConnValue(self, state, value) { <ide> } <ide> <ide> function matchHeader(self, state, field, value) { <del> var m = RE_FIELDS.exec(field); <del> if (!m) <add> if (field.length < 4 || field.length > 17) <ide> return; <del> var len = m[0].length; <del> if (len === 10) { <del> state.connection = true; <del> matchConnValue(self, state, value); <del> } else if (len === 17) { <del> state.te = true; <del> if (RE_TE_CHUNKED.test(value)) self.chunkedEncoding = true; <del> } else if (len === 14) { <del> state.contLen = true; <del> } else if (len === 4) { <del> state.date = true; <del> } else if (len === 6) { <del> state.expect = true; <del> } else if (len === 7) { <del> var ch = m[0].charCodeAt(0); <del> if (ch === 85 || ch === 117) <del> state.upgrade = true; <del> else <del> state.trailer = true; <add> field = field.toLowerCase(); <add> switch (field) { <add> case 'connection': <add> state.connection = true; <add> matchConnValue(self, state, value); <add> break; <add> case 'transfer-encoding': <add> state.te = true; <add> if (RE_TE_CHUNKED.test(value)) self.chunkedEncoding = true; <add> break; <add> case 'content-length': <add> state.contLen = true; <add> break; <add> case 'date': <add> case 'expect': <add> case 'trailer': <add> case 'upgrade': <add> state[field] = true; <add> break; <ide> } <ide> } <ide>
1
Ruby
Ruby
remove unused sheep fixture from av
7375c17114cd3782aae0bfa08d36a8ed816c2ff5
<ide><path>actionview/test/lib/controller/fake_models.rb <ide> def value <ide> end <ide> end <ide> <del>class Sheep <del> extend ActiveModel::Naming <del> include ActiveModel::Conversion <del> <del> attr_reader :id <del> def to_key; id ? [id] : nil end <del> def save; @id = 1 end <del> def new_record?; @id.nil? end <del> def name <del> @id.nil? ? 'new sheep' : "sheep ##{@id}" <del> end <del>end <del> <ide> class TagRelevance <ide> extend ActiveModel::Naming <ide> include ActiveModel::Conversion <ide><path>actionview/test/template/record_identifier_test.rb <ide> def setup <ide> @record = @klass.new <ide> @singular = 'comment' <ide> @plural = 'comments' <del> @uncountable = Sheep <ide> end <ide> <ide> def test_dom_id_with_new_record
2
Python
Python
add test for
ac9e3a4a8beec9bfa849aa2c0d64788e58e9999f
<ide><path>spacy/tests/regression/test_issue1773.py <add>from __future__ import unicode_literals <add> <add> <add>def test_issue1773(en_tokenizer): <add> """Test that spaces don't receive a POS but no TAG. This is the root cause <add> of the serialization issue reported in #1773.""" <add> doc = en_tokenizer('\n') <add> if doc[0].pos_ == 'SPACE': <add> assert doc[0].tag_ != ""
1
Javascript
Javascript
fix uastc to bc7 target format selection
2a6c961acef8052ca2cd28ed601e672596aeecbd
<ide><path>examples/jsm/loaders/KTX2Loader.js <ide> class KTX2Container { <ide> <ide> } else if ( config.bptcSupported && texFormat === TextureFormat.UASTC4x4 ) { <ide> <del> targetFormat = hasAlpha ? TranscodeTarget.BC7_M5_RGBA : BC7_M6_RGB; <add> targetFormat = TranscodeTarget.BC7_M5_RGBA; <ide> this.transcodedFormat = RGBA_BPTC_Format; <ide> <ide> } else if ( config.dxtSupported ) {
1
Go
Go
fix typo in variable
aac6008800ab06047ff000d6af487f3b52ba3019
<ide><path>integration-cli/docker_cli_run_test.go <ide> func (s *DockerSuite) TestRunDnsOptionsBasedOnHostResolvConf(c *check.C) { <ide> c.Fatalf("/etc/resolv.conf does not exist") <ide> } <ide> <del> hostNamservers := resolvconf.GetNameservers(origResolvConf, types.IP) <add> hostNameservers := resolvconf.GetNameservers(origResolvConf, types.IP) <ide> hostSearch := resolvconf.GetSearchDomains(origResolvConf) <ide> <ide> var out string <ide> func (s *DockerSuite) TestRunDnsOptionsBasedOnHostResolvConf(c *check.C) { <ide> out, _ = dockerCmd(c, "run", "--dns-search=mydomain", "busybox", "cat", "/etc/resolv.conf") <ide> <ide> actualNameservers := resolvconf.GetNameservers([]byte(out), types.IP) <del> if len(actualNameservers) != len(hostNamservers) { <del> c.Fatalf("expected %q nameserver(s), but it has: %q", len(hostNamservers), len(actualNameservers)) <add> if len(actualNameservers) != len(hostNameservers) { <add> c.Fatalf("expected %q nameserver(s), but it has: %q", len(hostNameservers), len(actualNameservers)) <ide> } <ide> for i := range actualNameservers { <del> if actualNameservers[i] != hostNamservers[i] { <del> c.Fatalf("expected %q nameserver, but says: %q", actualNameservers[i], hostNamservers[i]) <add> if actualNameservers[i] != hostNameservers[i] { <add> c.Fatalf("expected %q nameserver, but says: %q", actualNameservers[i], hostNameservers[i]) <ide> } <ide> } <ide> <ide> func (s *DockerSuite) TestRunDnsOptionsBasedOnHostResolvConf(c *check.C) { <ide> c.Fatalf("/etc/resolv.conf does not exist") <ide> } <ide> <del> hostNamservers = resolvconf.GetNameservers(resolvConf, types.IP) <add> hostNameservers = resolvconf.GetNameservers(resolvConf, types.IP) <ide> hostSearch = resolvconf.GetSearchDomains(resolvConf) <ide> <ide> out, _ = dockerCmd(c, "run", "busybox", "cat", "/etc/resolv.conf")
1
Text
Text
add lts info to collaborator_guide.md
d394e9e6bb75dc6a15befb89f7cd0b30df51596f
<ide><path>COLLABORATOR_GUIDE.md <ide> * [Landing Pull Requests](#landing-pull-requests) <ide> - [Technical HOWTO](#technical-howto) <ide> - [I Just Made a Mistake](#i-just-made-a-mistake) <add> - [Long Term Support](#long-term-support) <ide> <ide> This document contains information for Collaborators of the Node.js <ide> project regarding maintaining the code, documentation and issues. <ide> messages. However, you are only allowed to force push to any Node.js <ide> branch within 10 minutes from your original push. If someone else <ide> pushes to the branch or the 10 minute period passes, consider the <ide> commit final. <add> <add>### Long Term Support <add> <add>#### What is LTS? <add> <add>Long Term Support (often referred to as *LTS*) guarantees application developers <add>a 30 month support cycle with specific versions of Node.js. <add> <add>You can find more information [in the full LTS plan](https://github.com/nodejs/lts#lts-plan). <add> <add>#### How does LTS work? <add> <add>Once a stable branch enters LTS, no new features may be added to that release. Changes are <add>limited to bug fixes, security updates, possible npm updates, documentation updates, and certain <add>performance improvements that can be demonstrated to not break existing applications. <add>Semver-minor changes are only permitted if required for bug fixes. Semver-major changes are only <add>permitted if required for critical security and bug fixes. <add> <add>Once a stable branch moves into Maintenance mode, only **critical** bugs, **critical** security fixes, <add>and documentation updates will be permitted. <add> <add>#### How can I help? <add> <add>When you send your pull request, consider including information about <add>whether your change is breaking. If you think your patch can be backported, <add>please feel free to include that information in the PR thread. <add> <add>#### Who is doing the backporting? <add> <add>The current plan is for commits to cherry pick into a staging branch (e.g. v4.x-staging), <add>which can be done by anyone. The preference would be for the individual landing the commit <add>on master to backport to staging branches if it is appropriate. <add> <add>#### How is an LTS release cut? <add> <add>When the LTS working group determines that a new LTS release is required, selected commits <add>will be picked from the staging branch to be included in the release. This process of making <add>a release will be a collaboration between the LTS working group and the Release team.
1
Ruby
Ruby
fix typo in test error message
a71bbed76aab9e8a9a6b2da18bcacd8ee32a0dd0
<ide><path>railties/test/generators/app_generator_test.rb <ide> def test_active_storage_install <ide> case command <ide> when "active_storage:install" <ide> @binstub_called += 1 <del> assert_equal 1, @binstub_called, "active_storage:install expected to be called once, but was called #{@install_called} times." <add> assert_equal 1, @binstub_called, "active_storage:install expected to be called once, but was called #{@binstub_called} times" <ide> end <ide> end <ide>
1
Go
Go
forbid attach to ghost
b76d63cb0c97aacec6d81c07108d2a573fb8af05
<ide><path>commands.go <ide> func (srv *Server) CmdAttach(stdin io.ReadCloser, stdout rcli.DockerConn, args . <ide> return fmt.Errorf("No such container: %s", name) <ide> } <ide> <add> if container.State.Ghost { <add> return fmt.Errorf("Impossible to attach to a ghost container") <add> } <add> <ide> if container.Config.Tty { <ide> stdout.SetOptionRawTerminal() <ide> }
1
Javascript
Javascript
report bad dead code elimination to react devtools
aebd7f545442360388f61e0e7f5bbb9e8fbc30c9
<ide><path>packages/react-dom/index.js <ide> 'use strict'; <ide> <add>function checkDCE() { <add> /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */ <add> if ( <add> typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined' || <add> typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE !== 'function' <add> ) { <add> return; <add> } <add> if (process.env.NODE_ENV !== 'production') { <add> // This branch is unreachable because this function is only called <add> // in production, but the condition is true only in development. <add> // Therefore if the branch is still here, dead code elimination wasn't <add> // properly applied. <add> // Don't change the message. React DevTools relies on it. Also make sure <add> // this message doesn't occur elsewhere in this function, or it will cause <add> // a false positive. <add> throw new Error('^_^'); <add> } <add> try { <add> // Verify that the code above has been dead code eliminated (DCE'd). <add> __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE); <add> } catch (err) { <add> // DevTools shouldn't crash React, no matter what. <add> // We should still report in case we break this code. <add> console.error(err); <add> } <add>} <add> <ide> if (process.env.NODE_ENV === 'production') { <add> // DCE check should happen before ReactDOM bundle executes so that <add> // DevTools can report bad minification during injection. <add> checkDCE(); <ide> module.exports = require('./cjs/react-dom.production.min.js'); <ide> } else { <ide> module.exports = require('./cjs/react-dom.development.js');
1
Ruby
Ruby
fix const reference for sessionrestoreerror
89082004b0381ec67b4a2782ef4d4f63853e586f
<ide><path>actionpack/lib/action_dispatch/middleware/session/abstract_store.rb <ide> def stale_session_check! <ide> # Note that the regexp does not allow $1 to end with a ':' <ide> $1.constantize <ide> rescue LoadError, NameError => const_error <del> raise ActionDispatch::SessionRestoreError, "Session contains objects whose class definition isn't available.\nRemember to require the classes for all objects kept in the session.\n(Original exception: #{const_error.message} [#{const_error.class}])\n" <add> raise ActionDispatch::Session::SessionRestoreError, "Session contains objects whose class definition isn't available.\nRemember to require the classes for all objects kept in the session.\n(Original exception: #{const_error.message} [#{const_error.class}])\n" <ide> end <ide> <ide> retry
1
Javascript
Javascript
fix regression which affected old jquery releases
ef64169db32ffdf5e0e3ae2154ac434c6a55378b
<ide><path>src/ng/compile.js <ide> function $CompileProvider($provide, $$sanitizeUriProvider) { <ide> if (jqLiteIsTextNode(directiveValue)) { <ide> $template = []; <ide> } else { <del> $template = jqLite(directiveValue); <add> $template = jqLite(trim(directiveValue)); <ide> } <ide> compileNode = $template[0]; <ide> <ide> function $CompileProvider($provide, $$sanitizeUriProvider) { <ide> if (jqLiteIsTextNode(content)) { <ide> $template = []; <ide> } else { <del> $template = jqLite(content); <add> $template = jqLite(trim(content)); <ide> } <ide> compileNode = $template[0]; <ide>
1
Mixed
Javascript
add sync enterwith to als
d368dcc63af2eb75d5dbef5c6669e5e8ab3be5d2
<ide><path>doc/api/async_hooks.md <ide> If this method is called outside of an asynchronous context initialized by <ide> calling `asyncLocalStorage.run` or `asyncLocalStorage.runAndReturn`, it will <ide> return `undefined`. <ide> <add>### `asyncLocalStorage.enterWith(store)` <add><!-- YAML <add>added: REPLACEME <add>--> <add> <add>* `store` {any} <add> <add>Calling `asyncLocalStorage.enterWith(store)` will transition into the context <add>for the remainder of the current synchronous execution and will persist <add>through any following asynchronous calls. <add> <add>Example: <add> <add>```js <add>const store = { id: 1 }; <add>asyncLocalStorage.enterWith(store); <add>asyncLocalStorage.getStore(); // Returns the store object <add>someAsyncOperation(() => { <add> asyncLocalStorage.getStore(); // Returns the same object <add>}); <add>``` <add> <add>This transition will continue for the _entire_ synchronous execution. <add>This means that if, for example, the context is entered within an event <add>handler subsequent event handlers will also run within that context unless <add>specifically bound to another context with an `AsyncResource`. <add> <add>```js <add>const store = { id: 1 }; <add> <add>emitter.on('my-event', () => { <add> asyncLocalStorage.enterWith(store); <add>}); <add>emitter.on('my-event', () => { <add> asyncLocalStorage.getStore(); // Returns the same object <add>}); <add> <add>asyncLocalStorage.getStore(); // Returns undefined <add>emitter.emit('my-event'); <add>asyncLocalStorage.getStore(); // Returns the same object <add>``` <add> <ide> ### `asyncLocalStorage.run(store, callback[, ...args])` <ide> <!-- YAML <ide> added: v13.10.0 <ide><path>lib/async_hooks.js <ide> class AsyncLocalStorage { <ide> } <ide> } <ide> <del> _enter(store) { <add> enterWith(store) { <ide> if (!this.enabled) { <ide> this.enabled = true; <ide> storageList.push(this); <ide> class AsyncLocalStorage { <ide> runSyncAndReturn(store, callback, ...args) { <ide> const resource = executionAsyncResource(); <ide> const outerStore = resource[this.kResourceStore]; <del> this._enter(store); <add> this.enterWith(store); <ide> try { <ide> return callback(...args); <ide> } finally { <ide> class AsyncLocalStorage { <ide> run(store, callback, ...args) { <ide> const resource = executionAsyncResource(); <ide> const outerStore = resource[this.kResourceStore]; <del> this._enter(store); <add> this.enterWith(store); <ide> process.nextTick(callback, ...args); <ide> resource[this.kResourceStore] = outerStore; <ide> } <ide><path>test/async-hooks/test-async-local-storage-enter-with.js <add>'use strict'; <add>require('../common'); <add>const assert = require('assert'); <add>const { AsyncLocalStorage } = require('async_hooks'); <add> <add>const asyncLocalStorage = new AsyncLocalStorage(); <add> <add>setImmediate(() => { <add> const store = { foo: 'bar' }; <add> asyncLocalStorage.enterWith(store); <add> <add> assert.strictEqual(asyncLocalStorage.getStore(), store); <add> setTimeout(() => { <add> assert.strictEqual(asyncLocalStorage.getStore(), store); <add> }, 10); <add>}); <add> <add>setTimeout(() => { <add> assert.strictEqual(asyncLocalStorage.getStore(), undefined); <add>}, 10);
3
PHP
PHP
put a guard on getinvalidfield() call
5d91bee023f3e03fddfb6f871948f24b2d87df1f
<ide><path>src/View/Form/EntityContext.php <ide> use ArrayAccess; <ide> use Cake\Collection\Collection; <ide> use Cake\Datasource\EntityInterface; <add>use Cake\Datasource\InvalidPropertyInterface; <ide> use Cake\ORM\Entity; <ide> use Cake\ORM\Locator\LocatorAwareTrait; <ide> use Cake\ORM\Table; <ide> public function val(string $field, array $options = []) <ide> if ($entity instanceof EntityInterface) { <ide> $part = end($parts); <ide> <del> $val = $entity->getInvalidField($part); <del> if ($val !== null) { <del> return $val; <add> if ($entity instanceof InvalidPropertyInterface) { <add> $val = $entity->getInvalidField($part); <add> if ($val !== null) { <add> return $val; <add> } <ide> } <ide> <ide> $val = $entity->get($part);
1
Python
Python
use keyword args to make it more explicit
59ce9031b854bc29926596f627bd0a6e271a1dd5
<ide><path>libcloud/compute/drivers/cloudstack.py <ide> def ex_get_node(self, node_id, project=None): <ide> <ide> node = self._to_node(data=vm, public_ips=list(public_ips.keys())) <ide> <del> addresses = [CloudStackAddress(address_id, address, node.driver) <del> for address, address_id in public_ips.items()] <add> addresses = [CloudStackAddress(id=address_id, address=address, <add> driver=node.driver) for <add> address, address_id in public_ips.items()] <ide> node.extra['ip_addresses'] = addresses <ide> <ide> rules = []
1
Javascript
Javascript
use dynamic port in 3 test-cluster-worker tests
2519757b800a21c6b93490372841bc58307c46b7
<ide><path>test/parallel/test-cluster-worker-disconnect.js <ide> if (cluster.isWorker) { <ide> const http = require('http'); <ide> http.Server(() => { <ide> <del> }).listen(common.PORT, '127.0.0.1'); <add> }).listen(0, '127.0.0.1'); <ide> const worker = cluster.worker; <ide> assert.strictEqual(worker.exitedAfterDisconnect, worker.suicide); <ide> <ide><path>test/parallel/test-cluster-worker-exit.js <ide> if (cluster.isWorker) { <ide> server.once('listening', common.mustCall(() => { <ide> process.exit(EXIT_CODE); <ide> })); <del> server.listen(common.PORT, '127.0.0.1'); <add> server.listen(0, '127.0.0.1'); <ide> <ide> } else if (cluster.isMaster) { <ide> <ide><path>test/parallel/test-cluster-worker-kill.js <ide> if (cluster.isWorker) { <ide> const server = http.Server(() => { }); <ide> <ide> server.once('listening', common.mustCall(() => { })); <del> server.listen(common.PORT, '127.0.0.1'); <add> server.listen(0, '127.0.0.1'); <ide> <ide> } else if (cluster.isMaster) { <ide>
3
Java
Java
remove unused variable in reacttextinputmanager
2afc4e24824a2f949fed54ce879c9f46d3b4ebdb
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputManager.java <ide> import android.view.KeyEvent; <ide> import android.view.View; <ide> import android.view.inputmethod.EditorInfo; <del>import android.widget.EditText; <ide> import android.widget.TextView; <ide> import androidx.annotation.Nullable; <ide> import androidx.core.content.ContextCompat; <ide> public class ReactTextInputManager extends BaseViewManager<ReactEditText, Layout <ide> private static final InputFilter[] EMPTY_FILTERS = new InputFilter[0]; <ide> private static final int UNSET = -1; <ide> <del> @Nullable private static EditText mDummyEditText = null; <del> <ide> @Override <ide> public String getName() { <ide> return REACT_CLASS;
1
PHP
PHP
convert language php 5.4 arrays
01e97e13e25a45d26df39042d1bdaba62d9b39ad
<ide><path>resources/lang/en/validation.php <ide> <?php <ide> <del>return array( <add>return [ <ide> <ide> /* <ide> |-------------------------------------------------------------------------- <ide> "alpha_num" => "The :attribute may only contain letters and numbers.", <ide> "array" => "The :attribute must be an array.", <ide> "before" => "The :attribute must be a date before :date.", <del> "between" => array( <add> "between" => [ <ide> "numeric" => "The :attribute must be between :min and :max.", <ide> "file" => "The :attribute must be between :min and :max kilobytes.", <ide> "string" => "The :attribute must be between :min and :max characters.", <ide> "array" => "The :attribute must have between :min and :max items.", <del> ), <add> ], <ide> "boolean" => "The :attribute field must be true or false", <ide> "confirmed" => "The :attribute confirmation does not match.", <ide> "date" => "The :attribute is not a valid date.", <ide> "in" => "The selected :attribute is invalid.", <ide> "integer" => "The :attribute must be an integer.", <ide> "ip" => "The :attribute must be a valid IP address.", <del> "max" => array( <add> "max" => [ <ide> "numeric" => "The :attribute may not be greater than :max.", <ide> "file" => "The :attribute may not be greater than :max kilobytes.", <ide> "string" => "The :attribute may not be greater than :max characters.", <ide> "array" => "The :attribute may not have more than :max items.", <del> ), <add> ], <ide> "mimes" => "The :attribute must be a file of type: :values.", <del> "min" => array( <add> "min" => [ <ide> "numeric" => "The :attribute must be at least :min.", <ide> "file" => "The :attribute must be at least :min kilobytes.", <ide> "string" => "The :attribute must be at least :min characters.", <ide> "array" => "The :attribute must have at least :min items.", <del> ), <add> ], <ide> "not_in" => "The selected :attribute is invalid.", <ide> "numeric" => "The :attribute must be a number.", <ide> "regex" => "The :attribute format is invalid.", <ide> "required_without" => "The :attribute field is required when :values is not present.", <ide> "required_without_all" => "The :attribute field is required when none of :values are present.", <ide> "same" => "The :attribute and :other must match.", <del> "size" => array( <add> "size" => [ <ide> "numeric" => "The :attribute must be :size.", <ide> "file" => "The :attribute must be :size kilobytes.", <ide> "string" => "The :attribute must be :size characters.", <ide> "array" => "The :attribute must contain :size items.", <del> ), <add> ], <ide> "unique" => "The :attribute has already been taken.", <ide> "url" => "The :attribute format is invalid.", <ide> "timezone" => "The :attribute must be a valid zone.", <ide> | <ide> */ <ide> <del> 'custom' => array( <del> 'attribute-name' => array( <add> 'custom' => [ <add> 'attribute-name' => [ <ide> 'rule-name' => 'custom-message', <del> ), <del> ), <add> ], <add> ], <ide> <ide> /* <ide> |-------------------------------------------------------------------------- <ide> | <ide> */ <ide> <del> 'attributes' => array(), <add> 'attributes' => [], <ide> <del>); <add>];
1
Javascript
Javascript
add details in assertions in test-vm-context
51637574daa06f5f378d72c83336008f5ec0050d
<ide><path>test/parallel/test-vm-context.js <ide> try { <ide> } catch (e) { <ide> gh1140Exception = e; <ide> assert.ok(/expected-filename/.test(e.stack), <del> 'expected appearance of filename in Error stack'); <add> `expected appearance of filename in Error stack: ${e.stack}`); <ide> } <del>assert.ok(gh1140Exception, <del> 'expected exception from runInContext signature test'); <add>// This is outside of catch block to confirm catch block ran. <add>assert.strictEqual(gh1140Exception.toString(), 'Error'); <ide> <ide> // GH-558, non-context argument segfaults / raises assertion <ide> const nonContextualSandboxErrorMsg = <ide> Object.defineProperty(ctx, 'b', { configurable: false }); <ide> ctx = vm.createContext(ctx); <ide> assert.strictEqual(script.runInContext(ctx), false); <ide> <del>// Error on the first line of a module should <del>// have the correct line and column number <del>assert.throws(() => { <del> vm.runInContext(' throw new Error()', context, { <del> filename: 'expected-filename.js', <del> lineOffset: 32, <del> columnOffset: 123 <del> }); <del>}, (err) => { <del> return /^ \^/m.test(err.stack) && <del> /expected-filename\.js:33:131/.test(err.stack); <del>}, 'Expected appearance of proper offset in Error stack'); <add>// Error on the first line of a module should have the correct line and column <add>// number. <add>{ <add> let stack = null; <add> assert.throws(() => { <add> vm.runInContext(' throw new Error()', context, { <add> filename: 'expected-filename.js', <add> lineOffset: 32, <add> columnOffset: 123 <add> }); <add> }, (err) => { <add> stack = err.stack; <add> return /^ \^/m.test(stack) && <add> /expected-filename\.js:33:131/.test(stack); <add> }, `stack not formatted as expected: ${stack}`); <add>} <ide> <ide> // https://github.com/nodejs/node/issues/6158 <ide> ctx = new Proxy({}, {});
1
Javascript
Javascript
fix common chunk chunkhash validation
e1590e005ee36885e58f673a87d8ea3048898639
<ide><path>lib/Module.js <ide> class Module extends DependenciesBlock { <ide> super.sortItems(); <ide> this.chunks.sort(byId); <ide> this.reasons.sort((a, b) => byId(a.module, b.module)); <add> if(Array.isArray(this.usedExports)) { <add> this.usedExports.sort(); <add> } <ide> } <ide> <ide> unbuild() {
1
Ruby
Ruby
add support for mysql2 adapter to dbconsole
bf2ee896594f389b378fb1f1351f6f315b1a4498
<ide><path>railties/lib/rails/commands/dbconsole.rb <ide> def find_cmd(*commands) <ide> end <ide> <ide> case config["adapter"] <del> when "mysql" <add> when /^mysql/ <ide> args = { <ide> 'host' => '--host', <ide> 'port' => '--port', <ide> def find_cmd(*commands) <ide> # Has to set the RAILS_ENV before config/application is required <ide> if ARGV.first && !ARGV.first.index("-") && env = ARGV.first <ide> ENV['RAILS_ENV'] = %w(production development test).find { |e| e.index(env) } || env <del>end <ide>\ No newline at end of file <add>end
1
Javascript
Javascript
fix incorrect link
e26bc2370b8a1d1b1190899f4b948172e4c8316f
<ide><path>src/ng/directive/ngInclude.js <ide> * **Note:** When using onload on SVG elements in IE11, the browser will try to call <ide> * a function with the name on the window element, which will usually throw a <ide> * "function is undefined" error. To fix this, you can instead use `data-onload` or a <del> * different form that {@link guide/directives#normalization matches} `onload`. <add> * different form that {@link guide/directive#normalization matches} `onload`. <ide> * </div> <ide> * <ide> * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
1
Javascript
Javascript
add binding unittest
4f88d97af577e4b4f51e1943782e0380637e5233
<ide><path>test/unit/src/math/Euler.tests.js <ide> export default QUnit.module( 'Maths', () => { <ide> <ide> QUnit.test( "_onChangeCallback", ( assert ) => { <ide> <add> var b = false; <add> var a = new Euler( 11, 12, 13, "XYZ" ); <ide> var f = function () { <ide> <del> var b = true; <add> b = true; <add> assert.ok( a === this, "Passed!" ); <ide> <ide> }; <ide> <del> var a = new Euler( 11, 12, 13, "XYZ" ); <ide> a._onChangeCallback = f; <ide> assert.ok( a._onChangeCallback === f, "Passed!" ); <ide> <ide> <add> a._onChangeCallback(); <add> assert.ok( b, "Passed!" ); <add> <ide> } ); <ide> <ide> // OTHERS <ide><path>test/unit/src/math/Quaternion.tests.js <ide> export default QUnit.module( 'Maths', () => { <ide> QUnit.test( "_onChangeCallback", ( assert ) => { <ide> <ide> var b = false; <add> var a = new Quaternion( 11, 12, 13, 1 ); <ide> var f = function () { <ide> <ide> b = true; <add> assert.ok( a === this, "Passed!" ); <ide> <ide> }; <ide> <del> var a = new Quaternion( 11, 12, 13, 1 ); <ide> a._onChangeCallback = f; <ide> assert.ok( a._onChangeCallback === f, "Passed!" ); <ide>
2
Python
Python
improve support in tflite model conversion
083ee92fd6fd0eab20f8f91826a61ebe969b474f
<ide><path>official/vision/serving/export_tflite.py <ide> <ide> FLAGS = flags.FLAGS <ide> <del>flags.DEFINE_string( <add>_EXPERIMENT = flags.DEFINE_string( <ide> 'experiment', <ide> None, <ide> 'experiment type, e.g. retinanet_resnetfpn_coco', <ide> required=True) <del>flags.DEFINE_multi_string( <add>_CONFIG_FILE = flags.DEFINE_multi_string( <ide> 'config_file', <ide> default='', <ide> help='YAML/JSON files which specifies overrides. The override order ' <ide> 'specified in Python. If the same parameter is specified in both ' <ide> '`--config_file` and `--params_override`, `config_file` will be used ' <ide> 'first, followed by params_override.') <del>flags.DEFINE_string( <add>_PARAMS_OVERRIDE = flags.DEFINE_string( <ide> 'params_override', '', <ide> 'The JSON/YAML file or string which specifies the parameter to be overriden' <ide> ' on top of `config_file` template.') <del>flags.DEFINE_string( <add>_SAVED_MODEL_DIR = flags.DEFINE_string( <ide> 'saved_model_dir', None, 'The directory to the saved model.', required=True) <del>flags.DEFINE_string( <add>_TFLITE_PATH = flags.DEFINE_string( <ide> 'tflite_path', None, 'The path to the output tflite model.', required=True) <del>flags.DEFINE_string( <add>_QUANT_TYPE = flags.DEFINE_string( <ide> 'quant_type', <ide> default=None, <ide> help='Post training quantization type. Support `int8_fallback`, ' <ide> '`int8_full_fp32_io`, `int8_full`, `fp16`, `qat`, `qat_fp32_io`, ' <ide> '`int8_full_int8_io` and `default`. See ' <ide> 'https://www.tensorflow.org/lite/performance/post_training_quantization ' <ide> 'for more details.') <del>flags.DEFINE_integer('calibration_steps', 500, <del> 'The number of calibration steps for integer model.') <add>_CALIBRATION_STEPS = flags.DEFINE_integer( <add> 'calibration_steps', 500, <add> 'The number of calibration steps for integer model.') <add>_DENYLISTED_OPS = flags.DEFINE_string( <add> 'denylisted_ops', '', 'The comma-separated string of ops ' <add> 'that are excluded from integer quantization. The name of ' <add> 'ops should be all capital letters, such as CAST or GREATER.' <add> 'This is useful to exclude certains ops that affects quality or latency. ' <add> 'Valid ops that should not be included are quantization friendly ops, such ' <add> 'as CONV_2D, DEPTHWISE_CONV_2D, FULLY_CONNECTED, etc.') <ide> <ide> <ide> def main(_) -> None: <del> params = exp_factory.get_exp_config(FLAGS.experiment) <del> if FLAGS.config_file is not None: <del> for config_file in FLAGS.config_file: <add> params = exp_factory.get_exp_config(_EXPERIMENT.value) <add> if _CONFIG_FILE.value is not None: <add> for config_file in _CONFIG_FILE.value: <ide> params = hyperparams.override_params_dict( <ide> params, config_file, is_strict=True) <del> if FLAGS.params_override: <add> if _PARAMS_OVERRIDE.value: <ide> params = hyperparams.override_params_dict( <del> params, FLAGS.params_override, is_strict=True) <add> params, _PARAMS_OVERRIDE.value, is_strict=True) <ide> <ide> params.validate() <ide> params.lock() <ide> <ide> logging.info('Converting SavedModel from %s to TFLite model...', <del> FLAGS.saved_model_dir) <add> _SAVED_MODEL_DIR.value) <add> <add> if _DENYLISTED_OPS.value: <add> denylisted_ops = list(_DENYLISTED_OPS.value.split(',')) <ide> tflite_model = export_tflite_lib.convert_tflite_model( <del> saved_model_dir=FLAGS.saved_model_dir, <del> quant_type=FLAGS.quant_type, <add> saved_model_dir=_SAVED_MODEL_DIR.value, <add> quant_type=_QUANT_TYPE.value, <ide> params=params, <del> calibration_steps=FLAGS.calibration_steps) <add> calibration_steps=_CALIBRATION_STEPS.value, <add> denylisted_ops=denylisted_ops) <ide> <del> with tf.io.gfile.GFile(FLAGS.tflite_path, 'wb') as fw: <add> with tf.io.gfile.GFile(_TFLITE_PATH.value, 'wb') as fw: <ide> fw.write(tflite_model) <ide> <del> logging.info('TFLite model converted and saved to %s.', FLAGS.tflite_path) <add> logging.info('TFLite model converted and saved to %s.', _TFLITE_PATH.value) <ide> <ide> <ide> if __name__ == '__main__': <ide><path>official/vision/serving/export_tflite_lib.py <ide> from absl import logging <ide> import tensorflow as tf <ide> <add>from official.core import base_task <ide> from official.core import config_definitions as cfg <ide> from official.vision import configs <ide> from official.vision import tasks <ide> <ide> <ide> def create_representative_dataset( <del> params: cfg.ExperimentConfig) -> tf.data.Dataset: <add> params: cfg.ExperimentConfig, <add> task: Optional[base_task.Task] = None) -> tf.data.Dataset: <ide> """Creates a tf.data.Dataset to load images for representative dataset. <ide> <ide> Args: <ide> params: An ExperimentConfig. <add> task: An optional task instance. If it is None, task will be built according <add> to the task type in params. <ide> <ide> Returns: <ide> A tf.data.Dataset instance. <ide> <ide> Raises: <ide> ValueError: If task is not supported. <ide> """ <del> if isinstance(params.task, <del> configs.image_classification.ImageClassificationTask): <del> <del> task = tasks.image_classification.ImageClassificationTask(params.task) <del> elif isinstance(params.task, configs.retinanet.RetinaNetTask): <del> task = tasks.retinanet.RetinaNetTask(params.task) <del> elif isinstance(params.task, configs.maskrcnn.MaskRCNNTask): <del> task = tasks.maskrcnn.MaskRCNNTask(params.task) <del> elif isinstance(params.task, <del> configs.semantic_segmentation.SemanticSegmentationTask): <del> task = tasks.semantic_segmentation.SemanticSegmentationTask(params.task) <del> else: <del> raise ValueError('Task {} not supported.'.format(type(params.task))) <add> if task is None: <add> if isinstance(params.task, <add> configs.image_classification.ImageClassificationTask): <add> <add> task = tasks.image_classification.ImageClassificationTask(params.task) <add> elif isinstance(params.task, configs.retinanet.RetinaNetTask): <add> task = tasks.retinanet.RetinaNetTask(params.task) <add> elif isinstance(params.task, configs.maskrcnn.MaskRCNNTask): <add> task = tasks.maskrcnn.MaskRCNNTask(params.task) <add> elif isinstance(params.task, <add> configs.semantic_segmentation.SemanticSegmentationTask): <add> task = tasks.semantic_segmentation.SemanticSegmentationTask(params.task) <add> else: <add> raise ValueError('Task {} not supported.'.format(type(params.task))) <ide> # Ensure batch size is 1 for TFLite model. <ide> params.task.train_data.global_batch_size = 1 <ide> params.task.train_data.dtype = 'float32' <ide> def create_representative_dataset( <ide> <ide> def representative_dataset( <ide> params: cfg.ExperimentConfig, <add> task: Optional[base_task.Task] = None, <ide> calibration_steps: int = 2000) -> Iterator[List[tf.Tensor]]: <ide> """"Creates representative dataset for input calibration. <ide> <ide> Args: <ide> params: An ExperimentConfig. <add> task: An optional task instance. If it is None, task will be built according <add> to the task type in params. <ide> calibration_steps: The steps to do calibration. <ide> <ide> Yields: <ide> An input image tensor. <ide> """ <del> dataset = create_representative_dataset(params=params) <add> dataset = create_representative_dataset(params=params, task=task) <ide> for image, _ in dataset.take(calibration_steps): <ide> # Skip images that do not have 3 channels. <ide> if image.shape[-1] != 3: <ide> def representative_dataset( <ide> def convert_tflite_model(saved_model_dir: str, <ide> quant_type: Optional[str] = None, <ide> params: Optional[cfg.ExperimentConfig] = None, <del> calibration_steps: Optional[int] = 2000) -> bytes: <add> task: Optional[base_task.Task] = None, <add> calibration_steps: Optional[int] = 2000, <add> denylisted_ops: Optional[list[str]] = None) -> bytes: <ide> """Converts and returns a TFLite model. <ide> <ide> Args: <ide> def convert_tflite_model(saved_model_dir: str, <ide> fallback), `int8_full` (integer only) and None (no quantization). <ide> params: An optional ExperimentConfig to load and preprocess input images to <ide> do calibration for integer quantization. <add> task: An optional task instance. If it is None, task will be built according <add> to the task type in params. <ide> calibration_steps: The steps to do calibration. <add> denylisted_ops: A list of strings containing ops that are excluded from <add> integer quantization. <ide> <ide> Returns: <ide> A converted TFLite model with optional PTQ. <ide> def convert_tflite_model(saved_model_dir: str, <ide> converter.representative_dataset = functools.partial( <ide> representative_dataset, <ide> params=params, <add> task=task, <ide> calibration_steps=calibration_steps) <ide> if quant_type.startswith('int8_full'): <ide> converter.target_spec.supported_ops = [ <ide> def convert_tflite_model(saved_model_dir: str, <ide> if quant_type == 'int8_full_int8_io': <ide> converter.inference_input_type = tf.int8 <ide> converter.inference_output_type = tf.int8 <add> <add> if denylisted_ops: <add> debug_options = tf.lite.experimental.QuantizationDebugOptions( <add> denylisted_ops=denylisted_ops) <add> debugger = tf.lite.experimental.QuantizationDebugger( <add> converter=converter, <add> debug_dataset=functools.partial( <add> representative_dataset, <add> params=params, <add> calibration_steps=calibration_steps), <add> debug_options=debug_options) <add> debugger.run() <add> return debugger.get_nondebug_quantized_model() <add> <ide> elif quant_type == 'fp16': <ide> converter.optimizations = [tf.lite.Optimize.DEFAULT] <ide> converter.target_spec.supported_types = [tf.float16]
2
Ruby
Ruby
fix the test based on the changes on
7101489293ece071013417aeed2da3aa1b0927c9
<ide><path>activerecord/test/cases/associations/inverse_associations_test.rb <ide> def test_trying_to_use_inverses_that_dont_exist_should_raise_an_error <ide> if defined?(DidYouMean) && DidYouMean.respond_to?(:correct_error) <ide> def test_trying_to_use_inverses_that_dont_exist_should_have_suggestions_for_fix <ide> error = assert_raise(ActiveRecord::InverseOfAssociationNotFoundError) { <del> Human.first.dirty_face <add> Human.first.confused_face <ide> } <ide> <ide> assert_match "Did you mean?", error.message <del> assert_equal "horrible_human", error.corrections.first <add> assert_equal "super_human", error.corrections.first <ide> end <ide> end <ide> end <ide> def test_trying_to_use_inverses_that_dont_exist_should_raise_an_error <ide> if defined?(DidYouMean) && DidYouMean.respond_to?(:correct_error) <ide> def test_trying_to_use_inverses_that_dont_exist_should_have_suggestions_for_fix <ide> error = assert_raise(ActiveRecord::InverseOfAssociationNotFoundError) { <del> Face.first.horrible_human <add> Face.first.puzzled_human <ide> } <ide> <ide> assert_match "Did you mean?", error.message <del> assert_equal "polymorphic_face", error.corrections.first <add> assert_equal "confused_face", error.corrections.first <ide> end <ide> end <ide>
1
Javascript
Javascript
add unit test for getscript(object)
7be448d41fa124474aeee8423d57df11073791fd
<ide><path>test/unit/ajax.js <ide> if ( typeof window.ArrayBuffer === "undefined" || typeof new XMLHttpRequest().re <ide> } ); <ide> } ); <ide> <add> QUnit.test( "jQuery.getScript( Object ) - with callback", 2, function( assert ) { <add> var done = assert.async(); <add> <add> Globals.register( "testBar" ); <add> jQuery.getScript( { <add> url: url( "mock.php?action=testbar" ), <add> success: function() { <add> assert.strictEqual( window[ "testBar" ], "bar", "Check if script was evaluated" ); <add> done(); <add> } <add> } ); <add> } ); <add> <add> QUnit.test( "jQuery.getScript( Object ) - no callback", 1, function( assert ) { <add> Globals.register( "testBar" ); <add> jQuery.getScript( { url: url( "mock.php?action=testbar" ) } ).done( assert.async() ); <add> } ); <add> <ide> // //----------- jQuery.fn.load() <ide> <ide> // check if load can be called with only url
1
Ruby
Ruby
remove code duplication
f170453493dd7c2d62f7b866867f7a3c8ec623d7
<ide><path>actionpack/lib/action_view/helpers/number_helper.rb <ide> def number_to_percentage(number, options = {}) <ide> def number_with_delimiter(number, options = {}) <ide> options.symbolize_keys! <ide> <del> begin <del> Float(number) <del> rescue ArgumentError, TypeError <del> if options[:raise] <del> raise InvalidNumberError, number <del> else <del> return number <del> end <add> parse_float_number(number, options[:raise]) do <add> return number <ide> end <ide> <ide> defaults = I18n.translate(:'number.format', :locale => options[:locale], :default => {}) <ide> def number_with_delimiter(number, options = {}) <ide> parts = number.to_s.to_str.split('.') <ide> parts[0].gsub!(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1#{options[:delimiter]}") <ide> parts.join(options[:separator]).html_safe <del> <ide> end <ide> <ide> # Formats a +number+ with the specified level of <tt>:precision</tt> (e.g., 112.32 has a precision <ide> def number_with_delimiter(number, options = {}) <ide> def number_with_precision(number, options = {}) <ide> options.symbolize_keys! <ide> <del> number = begin <del> Float(number) <del> rescue ArgumentError, TypeError <del> if options[:raise] <del> raise InvalidNumberError, number <del> else <del> return number <del> end <add> number = parse_float_number(number, options[:raise]) do <add> return number <ide> end <ide> <ide> defaults = I18n.translate(:'number.format', :locale => options[:locale], :default => {}) <ide> def number_with_precision(number, options = {}) <ide> else <ide> formatted_number <ide> end <del> <ide> end <ide> <ide> STORAGE_UNITS = [:byte, :kb, :mb, :gb, :tb].freeze <ide> def number_with_precision(number, options = {}) <ide> def number_to_human_size(number, options = {}) <ide> options.symbolize_keys! <ide> <del> number = begin <del> Float(number) <del> rescue ArgumentError, TypeError <del> if options[:raise] <del> raise InvalidNumberError, number <del> else <del> return number <del> end <add> number = parse_float_number(number, options[:raise]) do <add> return number <ide> end <ide> <ide> defaults = I18n.translate(:'number.format', :locale => options[:locale], :default => {}) <ide> def number_to_human_size(number, options = {}) <ide> def number_to_human(number, options = {}) <ide> options.symbolize_keys! <ide> <del> number = begin <del> Float(number) <del> rescue ArgumentError, TypeError <del> if options[:raise] <del> raise InvalidNumberError, number <del> else <del> return number <del> end <add> number = parse_float_number(number, options[:raise]) do <add> return number <ide> end <ide> <ide> defaults = I18n.translate(:'number.format', :locale => options[:locale], :default => {}) <ide> def number_to_human(number, options = {}) <ide> decimal_format.gsub(/%n/, formatted_number).gsub(/%u/, unit).strip.html_safe <ide> end <ide> <add> private <add> <add> def parse_float_number(number, raise_error) <add> Float(number) <add> rescue ArgumentError, TypeError <add> if raise_error <add> raise InvalidNumberError, number <add> else <add> yield <add> end <add> end <ide> end <ide> end <ide> end
1
PHP
PHP
remove registry clear calls
9829646ea2e56a005796714e52ded5b8ef48b09c
<ide><path>src/Console/Command/Task/ModelTask.php <ide> public function bakeTable($model, array $data = []) { <ide> $filename = $path . 'Table' . DS . $name . 'Table.php'; <ide> $this->out("\n" . __d('cake_console', 'Baking table class for %s...', $name), 1, Shell::QUIET); <ide> $this->createFile($filename, $out); <del> TableRegistry::clear(); <ide> return $out; <ide> } <ide> <ide><path>src/Console/Command/Task/TestTask.php <ide> public function typeCanDetectFixtures($type) { <ide> * @return object And instance of the class that is going to be tested. <ide> */ <ide> public function buildTestSubject($type, $class) { <del> TableRegistry::clear(); <ide> if (strtolower($type) === 'table') { <ide> list($namespace, $name) = namespaceSplit($class); <ide> $name = str_replace('Table', '', $name); <ide><path>tests/TestCase/Console/Command/Task/TestTaskTest.php <ide> public function testFixtureArrayGenerationFromController() { <ide> $this->assertEquals($expected, $result); <ide> } <ide> <del>/** <del> * creating test subjects should clear the registry so the registry is always fresh <del> * <del> * @return void <del> */ <del> public function testRegistryClearWhenBuildingTestObjects() { <del> $articles = TableRegistry::get('Articles'); <del> $this->Task->buildTestSubject('Table', 'Posts'); <del> <del> $this->assertFalse(TableRegistry::exists('Articles')); <del> } <del> <ide> /** <ide> * Dataprovider for class name generation. <ide> *
3
PHP
PHP
move some things into the dispatcher
3800ecb1f28a40964df80d51b4230288d49ecc7a
<ide><path>src/Illuminate/Bus/Dispatcher.php <ide> public function __construct(Container $container, Closure $queueResolver = null) <ide> $this->queueResolver = $queueResolver; <ide> } <ide> <add> /** <add> * Marshal a command and dispatch it to its appropriate handler. <add> * <add> * @param mixed $command <add> * @param array $array <add> * @return mixed <add> */ <add> public function dispatchFromArray($command, array $array) <add> { <add> return $this->dispatch($this->marshalFromArray($command, $array)); <add> } <add> <add> /** <add> * Marshal a command and dispatch it to its appropriate handler. <add> * <add> * @param mixed $command <add> * @param array $array <add> * @return mixed <add> */ <add> public function dispatchFrom($command, ArrayAccess $source, $extras = []) <add> { <add> return $this->dispatch($this->marshal($command, $source, $extras)); <add> } <add> <add> /** <add> * Marshal a command from the given array. <add> * <add> * @param string $command <add> * @param array $array <add> * @return mixed <add> */ <add> protected function marshalFromArray($command, array $array) <add> { <add> return $this->marshal($command, new Collection, $array); <add> } <add> <add> /** <add> * Marshal a command from the given array accessible object. <add> * <add> * @param string $command <add> * @param \ArrayAccess $source <add> * @param array $extras <add> * @return mixed <add> */ <add> protected function marshal($command, ArrayAccess $source, $extras = []) <add> { <add> $injected = []; <add> <add> $reflection = new ReflectionClass($command); <add> <add> if ($constructor = $reflection->getConstructor()) <add> { <add> $injected = array_map(function($parameter) use ($command, $source, $extras) <add> { <add> return $this->getParameterValueForCommand($command, $source, $parameter, $extras); <add> <add> }, $constructor->getParameters()); <add> } <add> <add> return $reflection->newInstanceArgs($injected); <add> } <add> <add> /** <add> * Get a parameter value for a marshalled command. <add> * <add> * @param string $command <add> * @param \ArrayAccess $source <add> * @param \ReflectionParameter $parameter <add> * @param array $extras <add> * @return mixed <add> */ <add> protected function getParameterValueForCommand($command, ArrayAccess $source, <add> ReflectionParameter $parameter, array $extras = array()) <add> { <add> $value = $this->extractValueFromExtras($parameter, $extras) <add> ?: $this->extractValueFromSource($source, $parameter); <add> <add> if (is_null($value) && $parameter->isDefaultValueAvailable()) <add> { <add> $value = $parameter->getDefaultValue(); <add> } <add> elseif (is_null($value)) <add> { <add> MarshalException::whileMapping($command, $parameter); <add> } <add> <add> return $value; <add> } <add> <add> /** <add> * Attempt to extract the given parameter out of the given array. <add> * <add> * @param \ReflectionParameter $parameter <add> * @param array $extras <add> * @return mixed <add> */ <add> protected function extractValueFromExtras(ReflectionParameter $parameter, array $extras) <add> { <add> return array_get($extras, $parameter->name); <add> } <add> <add> /** <add> * Attempt to extract the given parameter out of the source. <add> * <add> * @param \ArrayAccess $source <add> * @param \ReflectionParameter $parameter <add> * @return mixed <add> */ <add> protected function extractValueFromSource(ArrayAccess $source, ReflectionParameter $parameter) <add> { <add> return array_get($source, $parameter->name); <add> } <add> <ide> /** <ide> * Dispatch a command to its appropriate handler. <ide> * <ide><path>src/Illuminate/Contracts/Bus/Dispatcher.php <ide> <?php namespace Illuminate\Contracts\Bus; <ide> <ide> use Closure; <add>use ArrayAccess; <ide> <ide> interface Dispatcher { <ide> <add> /** <add> * Marshal a command and dispatch it to its appropriate handler. <add> * <add> * @param mixed $command <add> * @param array $array <add> * @return mixed <add> */ <add> public function dispatchFromArray($command, array $array); <add> <add> /** <add> * Marshal a command and dispatch it to its appropriate handler. <add> * <add> * @param mixed $command <add> * @param array $array <add> * @return mixed <add> */ <add> public function dispatchFrom($command, ArrayAccess $source, $extras = []); <add> <ide> /** <ide> * Dispatch a command to its appropriate handler. <ide> * <ide><path>src/Illuminate/Foundation/Bus/DispatchesCommands.php <ide> protected function dispatch($command) <ide> */ <ide> protected function dispatchFromArray($command, array $array) <ide> { <del> return $this->dispatch($this->marshalFromArray($command, $array)); <add> return app('Illuminate\Contracts\Bus\Dispatcher')->dispatchFromArray($command, $array); <ide> } <ide> <ide> /** <ide> protected function dispatchFromArray($command, array $array) <ide> */ <ide> protected function dispatchFrom($command, ArrayAccess $source, $extras = []) <ide> { <del> return $this->dispatch($this->marshal($command, $source, $extras)); <del> } <del> <del> /** <del> * Marshal a command from the given array. <del> * <del> * @param string $command <del> * @param array $array <del> * @return mixed <del> */ <del> public function marshalFromArray($command, array $array) <del> { <del> return $this->marshal($command, new Collection, $array); <del> } <del> <del> /** <del> * Marshal a command from the given array accessible object. <del> * <del> * @param string $command <del> * @param \ArrayAccess $source <del> * @param array $extras <del> * @return mixed <del> */ <del> public function marshal($command, ArrayAccess $source, $extras = []) <del> { <del> $injected = []; <del> <del> $reflection = new ReflectionClass($command); <del> <del> if ($constructor = $reflection->getConstructor()) <del> { <del> $injected = array_map(function($parameter) use ($command, $source, $extras) <del> { <del> return $this->getParameterValueForCommand($command, $source, $parameter, $extras); <del> <del> }, $constructor->getParameters()); <del> } <del> <del> return $reflection->newInstanceArgs($injected); <del> } <del> <del> /** <del> * Get a parameter value for a marshalled command. <del> * <del> * @param string $command <del> * @param \ArrayAccess $source <del> * @param \ReflectionParameter $parameter <del> * @param array $extras <del> * @return mixed <del> */ <del> protected function getParameterValueForCommand($command, ArrayAccess $source, <del> ReflectionParameter $parameter, array $extras = array()) <del> { <del> $value = $this->extractValueFromExtras($parameter, $extras) <del> ?: $this->extractValueFromSource($source, $parameter); <del> <del> if (is_null($value) && $parameter->isDefaultValueAvailable()) <del> { <del> $value = $parameter->getDefaultValue(); <del> } <del> elseif (is_null($value)) <del> { <del> MarshalException::whileMapping($command, $parameter); <del> } <del> <del> return $value; <del> } <del> <del> /** <del> * Attempt to extract the given parameter out of the given array. <del> * <del> * @param \ReflectionParameter $parameter <del> * @param array $extras <del> * @return mixed <del> */ <del> protected function extractValueFromExtras(ReflectionParameter $parameter, array $extras) <del> { <del> return array_get($extras, $parameter->name); <del> } <del> <del> /** <del> * Attempt to extract the given parameter out of the source. <del> * <del> * @param \ArrayAccess $source <del> * @param \ReflectionParameter $parameter <del> * @return mixed <del> */ <del> protected function extractValueFromSource(ArrayAccess $source, ReflectionParameter $parameter) <del> { <del> return array_get($source, $parameter->name); <add> return app('Illuminate\Contracts\Bus\Dispatcher')->dispatchFrom($command, $source, $extras); <ide> } <ide> <ide> }
3
Python
Python
add mapping of roberta for qa
d440e21f5bdf2de787b616c2ab16bd3ca362ddc1
<ide><path>src/transformers/modeling_auto.py <ide> RobertaForSequenceClassification, <ide> RobertaForTokenClassification, <ide> RobertaModel, <add> RobertaForQuestionAnswering <ide> ) <ide> from .modeling_t5 import T5_PRETRAINED_MODEL_ARCHIVE_MAP, T5Model, T5WithLMHeadModel <ide> from .modeling_transfo_xl import TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_MAP, TransfoXLLMHeadModel, TransfoXLModel <ide> [ <ide> (DistilBertConfig, DistilBertForQuestionAnswering), <ide> (AlbertConfig, AlbertForQuestionAnswering), <add> (RobertaConfig, RobertaForQuestionAnswering), <ide> (BertConfig, BertForQuestionAnswering), <ide> (XLNetConfig, XLNetForQuestionAnswering), <ide> (XLMConfig, XLMForQuestionAnswering),
1