content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Text
Text
update pull request template
4120a69ac7f9e82a38b59e25e31a79bbb4299c3f
<ide><path>.github/PULL_REQUEST_TEMPLATE.md <ide> <ide> #### Checklist: <ide> <!-- Go over all points below, and after creating the PR, tick the checkboxes that apply. --> <del><!-- If you're unsure about any of these, don't hesitate to ask in the Help Contributors room linked above. We're here to help! --> <add><!-- If you're unsure about any of these, don't hesitate to ask in the Contributors room linked above. We're here to help! --> <ide> - [ ] Tested changes locally. <del>- [ ] Closes currently open issue (replace XXXX with an issue no): Closes #XXXX <add>- [ ] Addressed currently open issue (replace XXXXX with an issue no in next line) <add> <add>Closes #XXXXX <ide> <ide> #### Description <ide> <!-- Describe your changes in detail -->
1
Ruby
Ruby
remove testing code
532864b0ef0109a9efa8bca15c50c99f531b65b1
<ide><path>Library/Homebrew/dev-cmd/dispatch-build-bottle.rb <ide> def dispatch_build_bottle <ide> else <ide> macos.to_s <ide> end <del> p macos_label <del> odie "no" <ide> <ide> tap = Tap.fetch(args.tap || CoreTap.instance.name) <ide> user, repo = tap.full_name.split("/")
1
Python
Python
fold long lines
37740a0f7868515885060f921c2fe077125e746a
<ide><path>numpy/lib/format.py <ide> def read_array(fp, pickle_kwargs=None): <ide> and time. <ide> pickle_kwargs : dict <ide> Additional keyword arguments to pass to pickle.load. These are only <del> useful when loading object arrays saved on Python 2 when using Python 3. <add> useful when loading object arrays saved on Python 2 when using <add> Python 3. <ide> <ide> Returns <ide> ------- <ide> def read_array(fp, pickle_kwargs=None): <ide> if sys.version_info[0] >= 3: <ide> # Friendlier error message <ide> raise UnicodeError("Unpickling a python object failed: %r\n" <del> "You may need to pass the encoding= option to numpy.load" % (err,)) <add> "You may need to pass the encoding= option " <add> "to numpy.load" % (err,)) <ide> raise <ide> else: <ide> if isfileobj(fp): <ide><path>numpy/lib/npyio.py <ide> def __getitem__(self, key): <ide> bytes.close() <ide> if magic == format.MAGIC_PREFIX: <ide> bytes = self.zip.open(key) <del> return format.read_array(bytes, pickle_kwargs=self.pickle_kwargs) <add> return format.read_array(bytes, <add> pickle_kwargs=self.pickle_kwargs) <ide> else: <ide> return self.zip.read(key) <ide> else: <ide> def save(file, arr, fix_imports=True): <ide> extension will be appended to the file name if it does not already <ide> have one. <ide> fix_imports : bool, optional <del> Only useful in forcing objects in object arrays on Python 3 to be pickled <del> in a Python 2 compatible way. If `fix_imports` is True, pickle will try to <del> map the new Python 3 names to the old module names used in Python 2, so that <del> the pickle data stream is readable with Python 2. <add> Only useful in forcing objects in object arrays on Python 3 to be <add> pickled in a Python 2 compatible way. If `fix_imports` is True, pickle <add> will try to map the new Python 3 names to the old module names used in <add> Python 2, so that the pickle data stream is readable with Python 2. <ide> arr : array_like <ide> Array data to be saved. <ide> <ide> def _savez(file, args, kwds, compress, pickle_kwargs=None): <ide> fname = key + '.npy' <ide> fid = open(tmpfile, 'wb') <ide> try: <del> format.write_array(fid, np.asanyarray(val), pickle_kwargs=pickle_kwargs) <add> format.write_array(fid, np.asanyarray(val), <add> pickle_kwargs=pickle_kwargs) <ide> fid.close() <ide> fid = None <ide> zipf.write(tmpfile, arcname=fname) <ide><path>numpy/lib/tests/test_format.py <ide> def test_pickle_python2_python3(): <ide> data.close() <ide> else: <ide> assert_raises(UnicodeError, np.load, path) <del> assert_raises(ImportError, np.load, path, encoding='latin1', <del> fix_imports=False) <add> assert_raises(ImportError, np.load, path, <add> encoding='latin1', fix_imports=False) <ide> <ide> <ide> def test_version_2_0():
3
Javascript
Javascript
warn it only in dev
cbef3fd41228040eb580bb1298f91cd9fbce24f9
<ide><path>src/renderers/shared/server/ReactServerRenderer.js <ide> function flattenOptionChildren(children) { <ide> } <ide> if (typeof child === 'string' || typeof child === 'number') { <ide> content += child; <del> } else if (!didWarnInvalidOptionChildren) { <del> didWarnInvalidOptionChildren = true; <del> warning( <del> false, <del> 'Only strings and numbers are supported as <option> children.', <del> ); <add> } else { <add> if (__DEV__) { <add> if (!didWarnInvalidOptionChildren) { <add> didWarnInvalidOptionChildren = true; <add> warning( <add> false, <add> 'Only strings and numbers are supported as <option> children.', <add> ); <add> } <add> } <ide> } <ide> }); <ide> return content; <ide> class ReactDOMServerRenderer { <ide> ); <ide> } <ide> } <del> } <ide> <del> if ( <del> props.value !== undefined && <del> props.defaultValue !== undefined && <del> !didWarnDefaultSelectValue <del> ) { <del> warning( <del> false, <del> 'Select elements must be either controlled or uncontrolled ' + <del> '(specify either the value prop, or the defaultValue prop, but not ' + <del> 'both). Decide between using a controlled or uncontrolled select ' + <del> 'element and remove one of these props. More info: ' + <del> 'https://fb.me/react-controlled-components', <del> ); <del> didWarnDefaultSelectValue = true; <add> if ( <add> props.value !== undefined && <add> props.defaultValue !== undefined && <add> !didWarnDefaultSelectValue <add> ) { <add> warning( <add> false, <add> 'Select elements must be either controlled or uncontrolled ' + <add> '(specify either the value prop, or the defaultValue prop, but not ' + <add> 'both). Decide between using a controlled or uncontrolled select ' + <add> 'element and remove one of these props. More info: ' + <add> 'https://fb.me/react-controlled-components', <add> ); <add> didWarnDefaultSelectValue = true; <add> } <ide> } <del> <ide> this.currentSelectValue = props.value != null <ide> ? props.value <ide> : props.defaultValue;
1
Python
Python
fix visualbert embeddings
c4e1586db8ef6b4102016fc5cb038940fde45325
<ide><path>src/transformers/models/visual_bert/modeling_visual_bert.py <ide> def forward( <ide> inputs_embeds = self.word_embeddings(input_ids) <ide> <ide> if token_type_ids is None: <del> token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.input_embeds.device) <add> token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device) <ide> <ide> token_type_embeddings = self.token_type_embeddings(token_type_ids) <ide>
1
Text
Text
update array description
e6e58b8aa023ca9df19e3b36ddd62e2404ea999c
<ide><path>guide/english/php/arrays/index.md <ide> title: Arrays <ide> --- <ide> ## Arrays <ide> <add>Arrays are like regular variables, but hold multiple values in an ordered list. This can be useful if you have multiple values that are all related to each other, like a list of student names or a list of capital cities. <add> <ide> ### Types Of Arrays <del>In PHP there are three types of arrays: Indexed Arrays, Associative arrays, and Multidimensional arrays. <add>In PHP, there are two types of arrays: Indexed arrays and Associative arrays. Each has their own use and we'll look at how to create these arrays. <ide> <ide> ### Indexed Array Example <del>An indexed array accesses objects by index number. <add>An indexed array is a list of ordered values. Each of these values in the array is assigned an index number. Indexes for arrays always start at `0` for the first value and then increase by one from there. <add> <ide> ```PHP <ide> <?php <del>$freecodecamp = array("free", "code", "camp"); <add>$shopping_list = array("eggs", "milk", "cheese"); <ide> ``` <del>`$freecodecamp[0]` would return `"free"`, `$freecodecamp[1]` would return `"code"`, and `$freecodecamp[2]` would return `"camp"`. <add>`$shopping_list[0]` would return `"eggs"`, `$shopping_list[1]` would return `"milk"`, and `$shopping_list[2]` would return `"cheese"`. <ide> <ide> ### Associative Array Example <del>An associative array accesses objects by key name. <add>An associative array is a list of values that are accessed via a key instead of index numbers. The key can be any value but it must be unique to the array. <add> <ide> ```PHP <ide> <?php <del>$freecodecamp = array("free"=>"0","code"=>"1","camp"=>"2"); <add>$student_scores = array("Joe" => 83, "Frank" => "93", "Benji" => "90"); <ide> ``` <del>`$freecodecamp['free']` would return "0", `$freecodecamp['code']` would return "1", `$freecodecamp['camp']` would return "2", <add>`$student_scores['Joe']` would return `83`, `$student_scores['Frank']` would return `93`, `$student_scores['Benji']` would return `90`. <ide> <ide> ### Multidimensional Array Example <del>A multidimensional array is an array that contains other arrays. <add>A multidimensional array is an array that contains other arrays. This lets you create complex data structures that can model a very complex group of data. <ide> ```PHP <ide> <?php <del>$freecodecamp = array(array("free"=>"0","code"=>"1","camp"=>"2"),array("free"=>"0","code"=>"1","camp"=>"2"),array("free"=>"0","code"=>"1","camp"=>"2")); <add>$students = <add> array( <add> array("first_name" => "Joe", "score" => 83, "last_name" => "Smith"), <add> array("first_name" => "Frank", "score" => 92, "last_name" => "Barbson"), <add> array("first_name" => "Benji", "score" => 90, "last_name" => "Warner") <add> ); <ide> ``` <ide> <add>Now you can get the first student's `first_name` with: <add>```PHP <add>$students[0]['first_name'] <add>``` <ide> #### More Information: <ide> * <a href="https://secure.php.net/manual/en/language.types.array.php" rel="nofollow">php.net arrays manual</a>
1
Ruby
Ruby
fix aggregate attribute on enum types
ea4a5a94060be0b0e793302c9188388749ad06d1
<ide><path>activerecord/lib/active_record/relation/calculations.rb <ide> def execute_simple_calculation(operation, column_name, distinct) #:nodoc: <ide> if operation != "count" <ide> type = column.try(:type_caster) || <ide> lookup_cast_type_from_join_dependencies(column_name.to_s) || Type.default_value <add> type = type.subtype if Enum::EnumType === type <ide> end <ide> <ide> type_cast_calculated_value(result.cast_values.first, operation, type) <ide> def execute_grouped_calculation(operation, column_name, distinct) #:nodoc: <ide> if operation != "count" <ide> type = column.try(:type_caster) || <ide> lookup_cast_type_from_join_dependencies(column_name.to_s) || Type.default_value <add> type = type.subtype if Enum::EnumType === type <ide> end <ide> <ide> hash_rows.each_with_object({}) do |row, result| <ide><path>activerecord/test/cases/calculations_test.rb <ide> def test_group_by_attribute_with_custom_type <ide> assert_equal({ "proposed" => 2, "published" => 2 }, Book.group(:status).count) <ide> end <ide> <del> def test_aggregate_attribute_on_custom_type <del> assert_nil Book.sum(:status) <del> assert_equal "medium", Book.sum(:difficulty) <del> assert_equal "easy", Book.minimum(:difficulty) <del> assert_equal "medium", Book.maximum(:difficulty) <del> assert_equal({ "proposed" => "proposed", "published" => nil }, Book.group(:status).sum(:status)) <del> assert_equal({ "proposed" => "easy", "published" => "medium" }, Book.group(:status).sum(:difficulty)) <del> assert_equal({ "proposed" => "easy", "published" => "easy" }, Book.group(:status).minimum(:difficulty)) <del> assert_equal({ "proposed" => "easy", "published" => "medium" }, Book.group(:status).maximum(:difficulty)) <add> def test_aggregate_attribute_on_enum_type <add> assert_equal 4, Book.sum(:status) <add> assert_equal 1, Book.sum(:difficulty) <add> assert_equal 0, Book.minimum(:difficulty) <add> assert_equal 1, Book.maximum(:difficulty) <add> assert_equal({ "proposed" => 0, "published" => 4 }, Book.group(:status).sum(:status)) <add> assert_equal({ "proposed" => 0, "published" => 1 }, Book.group(:status).sum(:difficulty)) <add> assert_equal({ "proposed" => 0, "published" => 0 }, Book.group(:status).minimum(:difficulty)) <add> assert_equal({ "proposed" => 0, "published" => 1 }, Book.group(:status).maximum(:difficulty)) <ide> end <ide> <ide> def test_minimum_and_maximum_on_non_numeric_type
2
Ruby
Ruby
add test case for `unscope` with `merge`
257564d65a87bd2cccfd4ef78ae4b9a49c476f5d
<ide><path>activerecord/test/cases/relations_test.rb <ide> def test_unscope_with_subquery <ide> assert_equal p2.first.comments, comments <ide> end <ide> <add> def test_unscope_with_merge <add> p0 = Post.where(author_id: 0) <add> p1 = Post.where(author_id: 1, comments_count: 1) <add> <add> assert_equal [posts(:authorless)], p0 <add> assert_equal [posts(:thinking)], p1 <add> <add> comments = Comment.merge(p0).unscope(where: :author_id).where(post: p1) <add> <add> assert_not_equal p0.first.comments, comments <add> assert_equal p1.first.comments, comments <add> end <add> <ide> def test_unscope_with_unknown_column <ide> comment = comments(:greetings) <ide> comment.update!(comments: 1)
1
Javascript
Javascript
fix failing test in ie
000f47f75c14aed055f5c2e1b5ccecfa37d43755
<ide><path>packages/ember-testing/tests/helpers_test.js <ide> test("`click` triggers appropriate events in order", function() { <ide> ['mousedown', 'focusin', 'mouseup', 'click'], <ide> 'fires focus events on textareas'); <ide> }).then(function() { <add> // In IE (< 8), the change event only fires when the value changes before element focused. <add> Ember.$('.index-view input[type=checkbox]').focus(); <ide> events = []; <ide> return click('.index-view input[type=checkbox]'); <ide> }).then(function() {
1
Python
Python
remove abbreviation for positional plac argument
5a9d377580e573457665d9859d2d43286197565e
<ide><path>spacy/cli/init_model.py <ide> @plac.annotations( <ide> lang=("model language", "positional", None, str), <ide> output_dir=("model output directory", "positional", None, Path), <del> freqs_loc=("location of words frequencies file", "positional", <del> "f", Path), <add> freqs_loc=("location of words frequencies file", "positional", None, Path), <ide> clusters_loc=("optional: location of brown clusters data", <ide> "option", "c", str), <ide> vectors_loc=("optional: location of vectors file in GenSim text format",
1
PHP
PHP
convert files processing to use recursion
b54c3b030878e95fd706bcc0b19ddde0f238ff88
<ide><path>lib/Cake/Network/CakeRequest.php <ide> protected function _processFiles() { <ide> <ide> if (isset($_FILES['data'])) { <ide> foreach ($_FILES['data'] as $key => $data) { <del> foreach ($data as $model => $fields) { <del> if (is_array($fields)) { <del> foreach ($fields as $field => $value) { <del> if (is_array($value)) { <del> foreach ($value as $k => $v) { <del> $this->data[$model][$field][$k][$key] = $v; <del> } <del> } else { <del> $this->data[$model][$field][$key] = $value; <del> } <del> } <del> } else { <del> $this->data[$model][$key] = $fields; <del> } <del> } <add> $this->_processFileData('', $data, $key); <add> } <add> } <add> } <add> <add>/** <add> * Recursively walks the FILES array restructuring the data <add> * into something sane and useable. <add> * <add> * @param string $path The dot separated path to insert $data into. <add> * @param array $data The data to traverse/insert. <add> * @param string $field The terminal field name, which is the top level key in $_FILES. <add> * @return void <add> */ <add> protected function _processFileData($path, $data, $field) { <add> foreach ($data as $key => $fields) { <add> $newPath = $key; <add> if (!empty($path)) { <add> $newPath = $path . '.' . $key; <add> } <add> if (is_array($fields)) { <add> $this->_processFileData($newPath, $fields, $field); <add> } else { <add> $newPath .= '.' . $field; <add> $this->data = Set::insert($this->data, $newPath, $fields); <ide> } <ide> } <ide> }
1
PHP
PHP
fix issues in orm\query
e37b5786bbe7b0eccd194c7d6c360da1acc3107a
<ide><path>Cake/Database/Query.php <ide> public function connection($connection = null) { <ide> * Resulting statement is traversable, so it can be used in any loop as you would <ide> * with an array. <ide> * <add> * This method can be overridden in query subclasses to decorate behavior <add> * around query execution. <add> * <ide> * @return Cake\Database\StatementInterface <ide> */ <ide> public function execute() { <add> return $this->_executeStatement(); <add> } <add> <add>/** <add> * Internal implementation of statement execution. <add> * <add> * @return Cake\Database\StatementInterface <add> */ <add> protected function _executeStatement() { <ide> $query = $this->_transformQuery(); <ide> $statement = $this->_connection->prepare($query->sql()); <ide> $query->_bindStatement($statement); <ide> protected function _buildFromPart($parts, $generator) { <ide> * {{{ <ide> * $query->join([ <ide> * 'a' => [ <del> * 'table' => 'authors', 'type' => 'LEFT', 'conditions' => 'a.id = b.author_id' <add> * 'table' => 'authors', <add> * 'type' => 'LEFT', <add> * 'conditions' => 'a.id = b.author_id' <ide> * ] <ide> * ]); <ide> * // Produces LEFT JOIN authors a ON (a.id = b.author_id) <ide> protected function _buildFromPart($parts, $generator) { <ide> * {{{ <ide> * $query->join([ <ide> * 'a' => [ <del> * 'table' => 'authors', 'type' => 'LEFT', 'conditions' => 'a.id = b.author_id' <add> * 'table' => 'authors', <add> * 'type' => 'LEFT', <add> * 'conditions' => 'a.id = b.author_id' <ide> * ], <ide> * 'p' => [ <del> * 'table' => 'products', 'type' => 'INNER', 'conditions' => 'a.owner_id = p.id <add> * 'table' => 'products', <add> * 'type' => 'INNER', <add> * 'conditions' => 'a.owner_id = p.id <ide> * ] <ide> * ]); <ide> * // LEFT JOIN authors a ON (a.id = b.author_id) <ide><path>Cake/ORM/Query.php <ide> public function setResult($results) { <ide> * Compiles the SQL representation of this query and executes it using the <ide> * provided connection object. Returns a ResultSet iterator object. <ide> * <add> * This method fires the `Model.beforeFind` event and processes the <add> * callback results. <add> * <ide> * If a result set was set using setResult() that ResultSet will be returned. <ide> * <ide> * Resulting object is traversable, so it can be used in any loop as you would <ide> * with an array. <ide> * <del> * @return Cake\ORM\ResultCollectionTrait <add> * @return Cake\ORM\ResultCollectionTrait|Cake\Database\StatementInterface <add> * A result set will be returned for select queries. For insert, delete and update <add> * queries a statement will be returned. <ide> */ <ide> public function execute() { <del> $table = $this->repository(); <del> $event = new Event('Model.beforeFind', $table, [$this, $this->_options]); <del> $table->getEventManager()->dispatch($event); <add> if ($this->_type === 'select' || $this->_type === null) { <add> $table = $this->repository(); <add> $event = new Event('Model.beforeFind', $table, [$this, $this->_options]); <add> $table->getEventManager()->dispatch($event); <add> return $this->getResults(); <add> } <add> return $this->_executeStatement(); <add> } <add> <add>/** <add> * Get the result set for this query. <add> * <add> * Will return either the results set through setResult(), or execute the underlying statement <add> * and return the ResultSet object ready for streaming of results. <add> * <add> * @return Cake\ORM\ResultCollectionTrait <add> */ <add> public function getResults() { <ide> if (isset($this->_results)) { <ide> return $this->_results; <ide> } <ide> if ($this->_useBufferedResults) { <ide> return $this->_results = $this->_decorateResults( <del> new BufferedResultSet($this, $this->executeStatement()) <add> new BufferedResultSet($this, $this->_executeStatement()) <ide> ); <ide> } <del> return $this->_decorateResults(new ResultSet($this, $this->executeStatement())); <del> } <del> <del>/** <del> * Compiles the SQL representation of this query and executes it using <del> * the provided connection object. <del> * <del> * @return Cake\Database\StatementInterface <del> */ <del> public function executeStatement() { <del> return parent::execute(); <add> return $this->_decorateResults(new ResultSet($this, $this->_executeStatement())); <ide> } <ide> <ide> /** <ide><path>Cake/ORM/Table.php <ide> public function updateAll($fields, $conditions) { <ide> $query->update($this->table()) <ide> ->set($fields) <ide> ->where($conditions); <del> $statement = $query->executeStatement(); <add> $statement = $query->execute(); <ide> $success = $statement->rowCount() > 0; <ide> $statement->closeCursor(); <ide> return $success; <ide> public function deleteAll($conditions) { <ide> $query = $this->query(); <ide> $query->delete($this->table()) <ide> ->where($conditions); <del> $statement = $query->executeStatement(); <add> $statement = $query->execute(); <ide> $success = $statement->rowCount() > 0; <ide> $statement->closeCursor(); <ide> return $success; <ide> protected function _insert($entity, $data) { <ide> <ide> $statement = $query->insert($this->table(), array_keys($data)) <ide> ->values($data) <del> ->executeStatement(); <add> ->execute(); <ide> <ide> $success = false; <ide> if ($statement->rowCount() > 0) { <ide> protected function _update($entity, $data) { <ide> $statement = $query->update($this->table()) <ide> ->set($data) <ide> ->where($primaryKey) <del> ->executeStatement(); <add> ->execute(); <ide> <ide> $success = false; <ide> if ($statement->rowCount() > 0) { <ide> protected function _processDelete($entity, $options) { <ide> $query = $this->query(); <ide> $statement = $query->delete($this->table()) <ide> ->where($conditions) <del> ->executeStatement(); <add> ->execute(); <ide> <ide> $success = $statement->rowCount() > 0; <ide> if (!$success) { <ide><path>Cake/Test/TestCase/ORM/QueryTest.php <ide> public function testFilteringByBelongsToManyNoHydration() { <ide> */ <ide> public function testSetResult() { <ide> $query = new Query($this->connection, $this->table); <add> <ide> $stmt = $this->getMock('Cake\Database\StatementInterface'); <ide> $results = new ResultSet($query, $stmt); <ide> $query->setResult($results); <ide> public function testOverwriteMapReduce() { <ide> */ <ide> public function testResultsAreWrappedInMapReduce() { <ide> $params = [$this->connection, $this->table]; <del> $query = $this->getMock('\Cake\ORM\Query', ['executeStatement'], $params); <add> $query = $this->getMock('\Cake\ORM\Query', ['_executeStatement'], $params); <ide> <ide> $statement = $this->getMock('\Database\StatementInterface', ['fetch', 'closeCursor']); <ide> $statement->expects($this->exactly(3)) <ide> ->method('fetch') <ide> ->will($this->onConsecutiveCalls(['a' => 1], ['a' => 2], false)); <ide> <ide> $query->expects($this->once()) <del> ->method('executeStatement') <add> ->method('_executeStatement') <ide> ->will($this->returnValue($statement)); <ide> <ide> $query->mapReduce(function($k, $v, $mr) { <ide> public function testCount() { <ide> <ide> /** <ide> * Test that count() returns correct results with group by. <add> * <add> * @return void <ide> */ <ide> public function testCountWithGroup() { <ide> $table = TableRegistry::get('articles'); <ide> public function testCountWithGroup() { <ide> $this->assertEquals(1, $result); <ide> } <ide> <add>/** <add> * Test that there is no beforeFind event with update queries. <add> * <add> * @return void <add> */ <add> public function testUpdateNoBeforeFind() { <add> $table = TableRegistry::get('articles'); <add> $table->getEventManager()->attach(function() { <add> $this->fail('No callback should be fired'); <add> }, 'Model.beforeFind'); <add> <add> $query = $table->query() <add> ->update($table->table()) <add> ->set(['title' => 'First']); <add> <add> $result = $query->execute(); <add> $this->assertInstanceOf('Cake\Database\StatementInterface', $result); <add> $this->assertTrue($result->rowCount() > 0); <add> } <add> <add>/** <add> * Test that there is no beforeFind event with delete queries. <add> * <add> * @return void <add> */ <add> public function testDeleteNoBeforeFind() { <add> $table = TableRegistry::get('articles'); <add> $table->getEventManager()->attach(function() { <add> $this->fail('No callback should be fired'); <add> }, 'Model.beforeFind'); <add> <add> $query = $table->query() <add> ->delete($table->table()); <add> <add> $result = $query->execute(); <add> $this->assertInstanceOf('Cake\Database\StatementInterface', $result); <add> $this->assertTrue($result->rowCount() > 0); <add> } <add> <ide> } <ide><path>Cake/Test/TestCase/ORM/TableTest.php <ide> public function testUpdateAllFailure() { <ide> ['query'], <ide> [['table' => 'users']] <ide> ); <del> $query = $this->getMock('Cake\ORM\Query', ['executeStatement'], [$this->connection, null]); <add> $query = $this->getMock('Cake\ORM\Query', ['_executeStatement'], [$this->connection, null]); <ide> $table->expects($this->once()) <ide> ->method('query') <ide> ->will($this->returnValue($query)); <ide> $query->expects($this->once()) <del> ->method('executeStatement') <add> ->method('_executeStatement') <ide> ->will($this->throwException(new \Cake\Database\Exception('Not good'))); <ide> $table->updateAll(['username' => 'mark'], []); <ide> } <ide> public function testDeleteAllFailure() { <ide> ['query'], <ide> [['table' => 'users', 'connection' => $this->connection]] <ide> ); <del> $query = $this->getMock('Cake\ORM\Query', ['executeStatement'], [$this->connection, null]); <add> $query = $this->getMock('Cake\ORM\Query', ['_executeStatement'], [$this->connection, null]); <ide> $table->expects($this->once()) <ide> ->method('query') <ide> ->will($this->returnValue($query)); <ide> $query->expects($this->once()) <del> ->method('executeStatement') <add> ->method('_executeStatement') <ide> ->will($this->throwException(new \Cake\Database\Exception('Not good'))); <ide> $table->deleteAll(['id >' => 4]); <ide> } <ide> public function testAfterSaveNotCalled() { <ide> ); <ide> $query = $this->getMock( <ide> '\Cake\ORM\Query', <del> ['executeStatement', 'addDefaultTypes'], <add> ['_executeStatement', 'addDefaultTypes'], <ide> [null, $table] <ide> ); <ide> $statement = $this->getMock('\Cake\Database\Statement\StatementDecorator'); <ide> public function testAfterSaveNotCalled() { <ide> $table->expects($this->once())->method('query') <ide> ->will($this->returnValue($query)); <ide> <del> $query->expects($this->once())->method('executeStatement') <add> $query->expects($this->once())->method('_executeStatement') <ide> ->will($this->returnValue($statement)); <ide> <ide> $statement->expects($this->once())->method('rowCount') <ide> public function testAtomicSaveRollback() { <ide> ); <ide> $query = $this->getMock( <ide> '\Cake\ORM\Query', <del> ['executeStatement', 'addDefaultTypes'], <add> ['_executeStatement', 'addDefaultTypes'], <ide> [null, $table] <ide> ); <ide> <ide> public function testAtomicSaveRollback() { <ide> <ide> $connection->expects($this->once())->method('begin'); <ide> $connection->expects($this->once())->method('rollback'); <del> $query->expects($this->once())->method('executeStatement') <add> $query->expects($this->once())->method('_executeStatement') <ide> ->will($this->throwException(new \PDOException)); <ide> <ide> $data = new \Cake\ORM\Entity([ <ide> public function testAtomicSaveRollbackOnFailure() { <ide> ); <ide> $query = $this->getMock( <ide> '\Cake\ORM\Query', <del> ['executeStatement', 'addDefaultTypes'], <add> ['_executeStatement', 'addDefaultTypes'], <ide> [null, $table] <ide> ); <ide> <ide> public function testAtomicSaveRollbackOnFailure() { <ide> ->will($this->returnValue(0)); <ide> $connection->expects($this->once())->method('begin'); <ide> $connection->expects($this->once())->method('rollback'); <del> $query->expects($this->once())->method('executeStatement') <add> $query->expects($this->once())->method('_executeStatement') <ide> ->will($this->returnValue($statement)); <ide> <ide> $data = new \Cake\ORM\Entity([ <ide> public function testSaveUpdatePrimaryKeyNotModified() { <ide> <ide> $query = $this->getMock( <ide> '\Cake\ORM\Query', <del> ['executeStatement', 'addDefaultTypes', 'set'], <add> ['_executeStatement', 'addDefaultTypes', 'set'], <ide> [null, $table] <ide> ); <ide> <ide> public function testSaveUpdatePrimaryKeyNotModified() { <ide> $statement->expects($this->once())->method('rowCount') <ide> ->will($this->returnValue(1)); <ide> <del> $query->expects($this->once())->method('executeStatement') <add> $query->expects($this->once())->method('_executeStatement') <ide> ->will($this->returnValue($statement)); <ide> <ide> $query->expects($this->once())->method('set')
5
Mixed
PHP
fix handling of hash urls
6a9cc4816408b55df0c606af9ee97228c16f1aea
<ide><path>changes.md <ide> - Added "$hidden" static variable to the base Eloquent model. <ide> - Added "sync" method to has_many_and_belongs_to Eloquent relationship. <ide> - Improved View performance by only loading contents from file once. <add>- Fix handling of URLs beginning with has in URL::to. <ide> <ide> <a name="upgrade-3.2"></a> <ide> ## Upgrading From 3.1 <ide><path>laravel/url.php <ide> protected static function guess() <ide> */ <ide> public static function to($url = '', $https = false) <ide> { <del> if (filter_var($url, FILTER_VALIDATE_URL) !== false) return $url; <add> // If the given URL is already valid or begins with a hash, we'll just return <add> // the URL unchanged since it is already well formed. Otherwise we will add <add> // the base URL of the application and return the full URL. <add> if (static::valid($url) or starts_with($url, '#')) <add> { <add> return $url; <add> } <ide> <ide> $root = static::base().'/'.Config::get('application.index'); <ide> <ide> public static function transpose($uri, $parameters) <ide> return trim($uri, '/'); <ide> } <ide> <add> /** <add> * Determine if the given URL is valid. <add> * <add> * @param string $url <add> * @return bool <add> */ <add> public static function valid($url) <add> { <add> return filter_var($url, FILTER_VALIDATE_URL) !== false; <add> } <add> <ide> } <ide>\ No newline at end of file
2
Javascript
Javascript
increase timeout in readable stream test
0f10dd4cb2334474d3cab52df8507ddd8781b7f7
<ide><path>test/simple/test-stream2-readable-empty-buffer-no-eof.js <ide> function test1() { <ide> case 1: <ide> return r.push(buf); <ide> case 2: <del> setTimeout(r.read.bind(r, 0), 10); <add> setTimeout(r.read.bind(r, 0), 50); <ide> return r.push(new Buffer(0)); // Not-EOF! <ide> case 3: <del> setTimeout(r.read.bind(r, 0), 10); <add> setTimeout(r.read.bind(r, 0), 50); <ide> return process.nextTick(function() { <ide> return r.push(new Buffer(0)); <ide> }); <ide> case 4: <del> setTimeout(r.read.bind(r, 0), 10); <add> setTimeout(r.read.bind(r, 0), 50); <ide> return setTimeout(function() { <ide> return r.push(new Buffer(0)); <ide> });
1
Text
Text
fix 404 links
f81bef53984eedbf583900c3e92348b8775fca18
<ide><path>doc/changelogs/CHANGELOG_V010.md <ide> This is a security release. All Node.js users should consult the security releas <ide> This is a security release. All Node.js users should consult the security release summary at https://nodejs.org/en/blog/vulnerability/june-2016-security-releases/ for details on patched vulnerabilities. <ide> <ide> * libuv: (CVE-2014-9748) Fixes a bug in the read/write locks implementation for Windows XP and Windows 2003 that can lead to undefined and potentially unsafe behaviour. More information can be found at https://github.com/libuv/libuv/issues/515 or at https://nodejs.org/en/blog/vulnerability/june-2016-security-releases/. <del>* V8: (CVE-2016-1669) Fixes a potential Buffer overflow vulnerability discovered in V8, more details can be found in the CVE at https://www.cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2016-1669 or at https://nodejs.org/en/blog/vulnerability/june-2016-security-releases/. <add>* V8: (CVE-2016-1669) Fixes a potential Buffer overflow vulnerability discovered in V8, more details can be found in the CVE at https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2016-1669 or at https://nodejs.org/en/blog/vulnerability/june-2016-security-releases/. <ide> <ide> ### Commits: <ide> <ide><path>doc/changelogs/CHANGELOG_V012.md <ide> This is a security release. All Node.js users should consult the security releas <ide> This is a security release. All Node.js users should consult the security release summary at https://nodejs.org/en/blog/vulnerability/june-2016-security-releases/ for details on patched vulnerabilities. <ide> <ide> * libuv: (CVE-2014-9748) Fixes a bug in the read/write locks implementation for Windows XP and Windows 2003 that can lead to undefined and potentially unsafe behaviour. More information can be found at https://github.com/libuv/libuv/issues/515 or at https://nodejs.org/en/blog/vulnerability/june-2016-security-releases/. <del>* V8: (CVE-2016-1669) Fixes a potential Buffer overflow vulnerability discovered in V8, more details can be found in the CVE at https://www.cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2016-1669 or at https://nodejs.org/en/blog/vulnerability/june-2016-security-releases/. <add>* V8: (CVE-2016-1669) Fixes a potential Buffer overflow vulnerability discovered in V8, more details can be found in the CVE at https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2016-1669 or at https://nodejs.org/en/blog/vulnerability/june-2016-security-releases/. <ide> <ide> ### Commits: <ide> <ide><path>doc/changelogs/CHANGELOG_V12.md <ide> Vulnerabilities fixed: <ide> * [[`8e28259bf8`](https://github.com/nodejs/node/commit/8e28259bf8)] - **test**: change formatting of fixtures/keys/Makefile (Alex Aubuchon) [#27962](https://github.com/nodejs/node/pull/27962) <ide> * [[`d258504a31`](https://github.com/nodejs/node/commit/d258504a31)] - **test**: change fixtures.readSync to fixtures.readKey (Alex Aubuchon) [#27962](https://github.com/nodejs/node/pull/27962) <ide> * [[`328b2d0c88`](https://github.com/nodejs/node/commit/328b2d0c88)] - **test**: remove uneeded agent keypair in fixtures/ (Alex Aubuchon) [#27962](https://github.com/nodejs/node/pull/27962) <del>* [[`a0d2862b1e`](https://github.om/nodejs/node/commit/a0d2862b1e)] - **test**: move foafssl certs to fixtures/keys/ (Alex Aubuchon) [#27962](https://github.com/nodejs/node/pull/27962) <add>* [[`a0d2862b1e`](https://github.com/nodejs/node/commit/a0d2862b1e)] - **test**: move foafssl certs to fixtures/keys/ (Alex Aubuchon) [#27962](https://github.com/nodejs/node/pull/27962) <ide> * [[`af9eb9648e`](https://github.com/nodejs/node/commit/af9eb9648e)] - **test**: remove uneeded alice certs in fixtures/ (Alex Aubuchon) [#27962](https://github.com/nodejs/node/pull/27962) <ide> * [[`ee62fa172c`](https://github.com/nodejs/node/commit/ee62fa172c)] - **test**: remove uneeded certs in fixtures/ (Alex Aubuchon) [#27962](https://github.com/nodejs/node/pull/27962) <ide> * [[`f41dfd71a0`](https://github.com/nodejs/node/commit/f41dfd71a0)] - **test**: move dherror.pem to fixtures/keys/ (Alex Aubuchon) [#27962](https://github.com/nodejs/node/pull/27962) <ide><path>doc/changelogs/CHANGELOG_V4.md <ide> This LTS release comes with 89 commits. This includes 46 commits that are docs r <ide> <ide> This is an important security release. All Node.js users should consult the security release summary at nodejs.org for details on patched vulnerabilities. <ide> <del>This release is specifically related to a Buffer overflow vulnerability discovered in v8, more details can be found [in the CVE](https://www.cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2016-1669) <add>This release is specifically related to a Buffer overflow vulnerability discovered in v8, more details can be found [in the CVE](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2016-1669) <ide> <ide> ### Commits <ide>
4
Go
Go
add container package for container apis
fa8d96ebe21f5bb83e4d2da8e59234e701a8ee70
<ide><path>api/server/router/container/backend_unix.go <add>// +build !windows <add> <add>package container <add> <add>import ( <add> "io" <add> "time" <add> <add> "github.com/docker/docker/api/types" <add> "github.com/docker/docker/api/types/versions/v1p19" <add> "github.com/docker/docker/api/types/versions/v1p20" <add> "github.com/docker/docker/daemon" <add> "github.com/docker/docker/pkg/archive" <add> "github.com/docker/docker/runconfig" <add>) <add> <add>// Backend is all the methods that need to be implemented to provide <add>// container specific functionality <add>type Backend interface { <add> ContainerArchivePath(name string, path string) (content io.ReadCloser, stat *types.ContainerPathStat, err error) <add> ContainerAttachWithLogs(prefixOrName string, c *daemon.ContainerAttachWithLogsConfig) error <add> ContainerChanges(name string) ([]archive.Change, error) <add> ContainerCopy(name string, res string) (io.ReadCloser, error) <add> ContainerCreate(params *daemon.ContainerCreateConfig) (types.ContainerCreateResponse, error) <add> ContainerExecCreate(config *runconfig.ExecConfig) (string, error) <add> ContainerExecInspect(id string) (*daemon.ExecConfig, error) <add> ContainerExecResize(name string, height, width int) error <add> ContainerExecStart(name string, stdin io.ReadCloser, stdout io.Writer, stderr io.Writer) error <add> ContainerExport(name string, out io.Writer) error <add> ContainerExtractToDir(name, path string, noOverwriteDirNonDir bool, content io.Reader) error <add> ContainerInspect(name string, size bool) (*types.ContainerJSON, error) <add> ContainerInspect120(name string) (*v1p20.ContainerJSON, error) <add> // unix version <add> ContainerInspectPre120(name string) (*v1p19.ContainerJSON, error) <add> // windows version <add> //ContainerInspectPre120(name string) (*types.ContainerJSON, error) <add> ContainerKill(name string, sig uint64) error <add> ContainerLogs(containerName string, config *daemon.ContainerLogsConfig) error <add> ContainerPause(name string) error <add> ContainerRename(oldName, newName string) error <add> ContainerResize(name string, height, width int) error <add> ContainerRestart(name string, seconds int) error <add> ContainerRm(name string, config *daemon.ContainerRmConfig) error <add> Containers(config *daemon.ContainersConfig) ([]*types.Container, error) <add> ContainerStart(name string, hostConfig *runconfig.HostConfig) error <add> ContainerStatPath(name string, path string) (stat *types.ContainerPathStat, err error) <add> ContainerStats(prefixOrName string, config *daemon.ContainerStatsConfig) error <add> ContainerStop(name string, seconds int) error <add> ContainerTop(name string, psArgs string) (*types.ContainerProcessList, error) <add> ContainerUnpause(name string) error <add> ContainerWait(name string, timeout time.Duration) (int, error) <add> ContainerWsAttachWithLogs(prefixOrName string, c *daemon.ContainerWsAttachWithLogsConfig) error <add> ExecExists(name string) (bool, error) <add> Exists(id string) bool <add> IsPaused(id string) bool <add>} <ide><path>api/server/router/container/backend_windows.go <add>// +build windows <add> <add>package container <add> <add>import ( <add> "io" <add> "time" <add> <add> "github.com/docker/docker/api/types" <add> "github.com/docker/docker/api/types/versions/v1p20" <add> "github.com/docker/docker/daemon" <add> "github.com/docker/docker/pkg/archive" <add> "github.com/docker/docker/runconfig" <add>) <add> <add>// Backend is all the methods that need to be implemented to provide <add>// container specific functionality <add>type Backend interface { <add> ContainerArchivePath(name string, path string) (content io.ReadCloser, stat *types.ContainerPathStat, err error) <add> ContainerAttachWithLogs(prefixOrName string, c *daemon.ContainerAttachWithLogsConfig) error <add> ContainerChanges(name string) ([]archive.Change, error) <add> ContainerCopy(name string, res string) (io.ReadCloser, error) <add> ContainerCreate(params *daemon.ContainerCreateConfig) (types.ContainerCreateResponse, error) <add> ContainerExecCreate(config *runconfig.ExecConfig) (string, error) <add> ContainerExecInspect(id string) (*daemon.ExecConfig, error) <add> ContainerExecResize(name string, height, width int) error <add> ContainerExecStart(name string, stdin io.ReadCloser, stdout io.Writer, stderr io.Writer) error <add> ContainerExport(name string, out io.Writer) error <add> ContainerExtractToDir(name, path string, noOverwriteDirNonDir bool, content io.Reader) error <add> ContainerInspect(name string, size bool) (*types.ContainerJSON, error) <add> ContainerInspect120(name string) (*v1p20.ContainerJSON, error) <add> // unix version <add> //ContainerInspectPre120(name string) (*v1p19.ContainerJSON, error) <add> // windows version <add> ContainerInspectPre120(name string) (*types.ContainerJSON, error) <add> ContainerKill(name string, sig uint64) error <add> ContainerLogs(containerName string, config *daemon.ContainerLogsConfig) error <add> ContainerPause(name string) error <add> ContainerRename(oldName, newName string) error <add> ContainerResize(name string, height, width int) error <add> ContainerRestart(name string, seconds int) error <add> ContainerRm(name string, config *daemon.ContainerRmConfig) error <add> Containers(config *daemon.ContainersConfig) ([]*types.Container, error) <add> ContainerStart(name string, hostConfig *runconfig.HostConfig) error <add> ContainerStatPath(name string, path string) (stat *types.ContainerPathStat, err error) <add> ContainerStats(prefixOrName string, config *daemon.ContainerStatsConfig) error <add> ContainerStop(name string, seconds int) error <add> ContainerTop(name string, psArgs string) (*types.ContainerProcessList, error) <add> ContainerUnpause(name string) error <add> ContainerWait(name string, timeout time.Duration) (int, error) <add> ContainerWsAttachWithLogs(prefixOrName string, c *daemon.ContainerWsAttachWithLogsConfig) error <add> ExecExists(name string) (bool, error) <add> Exists(id string) bool <add> IsPaused(id string) bool <add>} <ide><path>api/server/router/container/container.go <add>package container <add> <add>import ( <add> "github.com/docker/docker/api/server/router" <add> "github.com/docker/docker/api/server/router/local" <add>) <add> <add>// containerRouter is a router to talk with the container controller <add>type containerRouter struct { <add> backend Backend <add> routes []router.Route <add>} <add> <add>// NewRouter initializes a new container router <add>func NewRouter(b Backend) router.Router { <add> r := &containerRouter{ <add> backend: b, <add> } <add> r.initRoutes() <add> return r <add>} <add> <add>// Routes returns the available routers to the container controller <add>func (r *containerRouter) Routes() []router.Route { <add> return r.routes <add>} <add> <add>// initRoutes initializes the routes in container router <add>func (r *containerRouter) initRoutes() { <add> r.routes = []router.Route{ <add> // HEAD <add> local.NewHeadRoute("/containers/{name:.*}/archive", r.headContainersArchive), <add> // GET <add> local.NewGetRoute("/containers/json", r.getContainersJSON), <add> local.NewGetRoute("/containers/{name:.*}/export", r.getContainersExport), <add> local.NewGetRoute("/containers/{name:.*}/changes", r.getContainersChanges), <add> local.NewGetRoute("/containers/{name:.*}/json", r.getContainersByName), <add> local.NewGetRoute("/containers/{name:.*}/top", r.getContainersTop), <add> local.NewGetRoute("/containers/{name:.*}/logs", r.getContainersLogs), <add> local.NewGetRoute("/containers/{name:.*}/stats", r.getContainersStats), <add> local.NewGetRoute("/containers/{name:.*}/attach/ws", r.wsContainersAttach), <add> local.NewGetRoute("/exec/{id:.*}/json", r.getExecByID), <add> local.NewGetRoute("/containers/{name:.*}/archive", r.getContainersArchive), <add> // POST <add> local.NewPostRoute("/containers/create", r.postContainersCreate), <add> local.NewPostRoute("/containers/{name:.*}/kill", r.postContainersKill), <add> local.NewPostRoute("/containers/{name:.*}/pause", r.postContainersPause), <add> local.NewPostRoute("/containers/{name:.*}/unpause", r.postContainersUnpause), <add> local.NewPostRoute("/containers/{name:.*}/restart", r.postContainersRestart), <add> local.NewPostRoute("/containers/{name:.*}/start", r.postContainersStart), <add> local.NewPostRoute("/containers/{name:.*}/stop", r.postContainersStop), <add> local.NewPostRoute("/containers/{name:.*}/wait", r.postContainersWait), <add> local.NewPostRoute("/containers/{name:.*}/resize", r.postContainersResize), <add> local.NewPostRoute("/containers/{name:.*}/attach", r.postContainersAttach), <add> local.NewPostRoute("/containers/{name:.*}/copy", r.postContainersCopy), <add> local.NewPostRoute("/containers/{name:.*}/exec", r.postContainerExecCreate), <add> local.NewPostRoute("/exec/{name:.*}/start", r.postContainerExecStart), <add> local.NewPostRoute("/exec/{name:.*}/resize", r.postContainerExecResize), <add> local.NewPostRoute("/containers/{name:.*}/rename", r.postContainerRename), <add> // PUT <add> local.NewPutRoute("/containers/{name:.*}/archive", r.putContainersArchive), <add> // DELETE <add> local.NewDeleteRoute("/containers/{name:.*}", r.deleteContainers), <add> } <add>} <ide><path>api/server/router/container/container_routes.go <del>package local <add>package container <ide> <ide> import ( <ide> "fmt" <ide> import ( <ide> "golang.org/x/net/websocket" <ide> ) <ide> <del>func (s *router) getContainersJSON(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <add>func (s *containerRouter) getContainersJSON(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <ide> if err := httputils.ParseForm(r); err != nil { <ide> return err <ide> } <ide> func (s *router) getContainersJSON(ctx context.Context, w http.ResponseWriter, r <ide> config.Limit = limit <ide> } <ide> <del> containers, err := s.daemon.Containers(config) <add> containers, err := s.backend.Containers(config) <ide> if err != nil { <ide> return err <ide> } <ide> <ide> return httputils.WriteJSON(w, http.StatusOK, containers) <ide> } <ide> <del>func (s *router) getContainersStats(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <add>func (s *containerRouter) getContainersStats(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <ide> if err := httputils.ParseForm(r); err != nil { <ide> return err <ide> } <ide> func (s *router) getContainersStats(ctx context.Context, w http.ResponseWriter, <ide> Version: httputils.VersionFromContext(ctx), <ide> } <ide> <del> return s.daemon.ContainerStats(vars["name"], config) <add> return s.backend.ContainerStats(vars["name"], config) <ide> } <ide> <del>func (s *router) getContainersLogs(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <add>func (s *containerRouter) getContainersLogs(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <ide> if err := httputils.ParseForm(r); err != nil { <ide> return err <ide> } <ide> func (s *router) getContainersLogs(ctx context.Context, w http.ResponseWriter, r <ide> <ide> containerName := vars["name"] <ide> <del> if !s.daemon.Exists(containerName) { <add> if !s.backend.Exists(containerName) { <ide> return derr.ErrorCodeNoSuchContainer.WithArgs(containerName) <ide> } <ide> <ide> func (s *router) getContainersLogs(ctx context.Context, w http.ResponseWriter, r <ide> Stop: closeNotifier, <ide> } <ide> <del> if err := s.daemon.ContainerLogs(containerName, logsConfig); err != nil { <add> if err := s.backend.ContainerLogs(containerName, logsConfig); err != nil { <ide> // The client may be expecting all of the data we're sending to <ide> // be multiplexed, so send it through OutStream, which will <ide> // have been set up to handle that if needed. <ide> func (s *router) getContainersLogs(ctx context.Context, w http.ResponseWriter, r <ide> return nil <ide> } <ide> <del>func (s *router) getContainersExport(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <del> return s.daemon.ContainerExport(vars["name"], w) <add>func (s *containerRouter) getContainersExport(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <add> return s.backend.ContainerExport(vars["name"], w) <ide> } <ide> <del>func (s *router) postContainersStart(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <add>func (s *containerRouter) postContainersStart(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <ide> // If contentLength is -1, we can assumed chunked encoding <ide> // or more technically that the length is unknown <ide> // https://golang.org/src/pkg/net/http/request.go#L139 <ide> func (s *router) postContainersStart(ctx context.Context, w http.ResponseWriter, <ide> hostConfig = c <ide> } <ide> <del> if err := s.daemon.ContainerStart(vars["name"], hostConfig); err != nil { <add> if err := s.backend.ContainerStart(vars["name"], hostConfig); err != nil { <ide> return err <ide> } <ide> w.WriteHeader(http.StatusNoContent) <ide> return nil <ide> } <ide> <del>func (s *router) postContainersStop(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <add>func (s *containerRouter) postContainersStop(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <ide> if err := httputils.ParseForm(r); err != nil { <ide> return err <ide> } <ide> <ide> seconds, _ := strconv.Atoi(r.Form.Get("t")) <ide> <del> if err := s.daemon.ContainerStop(vars["name"], seconds); err != nil { <add> if err := s.backend.ContainerStop(vars["name"], seconds); err != nil { <ide> return err <ide> } <ide> w.WriteHeader(http.StatusNoContent) <ide> <ide> return nil <ide> } <ide> <del>func (s *router) postContainersKill(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <add>func (s *containerRouter) postContainersKill(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <ide> if err := httputils.ParseForm(r); err != nil { <ide> return err <ide> } <ide> func (s *router) postContainersKill(ctx context.Context, w http.ResponseWriter, <ide> } <ide> } <ide> <del> if err := s.daemon.ContainerKill(name, uint64(sig)); err != nil { <add> if err := s.backend.ContainerKill(name, uint64(sig)); err != nil { <ide> theErr, isDerr := err.(errcode.ErrorCoder) <ide> isStopped := isDerr && theErr.ErrorCode() == derr.ErrorCodeNotRunning <ide> <ide> func (s *router) postContainersKill(ctx context.Context, w http.ResponseWriter, <ide> return nil <ide> } <ide> <del>func (s *router) postContainersRestart(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <add>func (s *containerRouter) postContainersRestart(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <ide> if err := httputils.ParseForm(r); err != nil { <ide> return err <ide> } <ide> <ide> timeout, _ := strconv.Atoi(r.Form.Get("t")) <ide> <del> if err := s.daemon.ContainerRestart(vars["name"], timeout); err != nil { <add> if err := s.backend.ContainerRestart(vars["name"], timeout); err != nil { <ide> return err <ide> } <ide> <ide> func (s *router) postContainersRestart(ctx context.Context, w http.ResponseWrite <ide> return nil <ide> } <ide> <del>func (s *router) postContainersPause(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <add>func (s *containerRouter) postContainersPause(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <ide> if err := httputils.ParseForm(r); err != nil { <ide> return err <ide> } <ide> <del> if err := s.daemon.ContainerPause(vars["name"]); err != nil { <add> if err := s.backend.ContainerPause(vars["name"]); err != nil { <ide> return err <ide> } <ide> <ide> func (s *router) postContainersPause(ctx context.Context, w http.ResponseWriter, <ide> return nil <ide> } <ide> <del>func (s *router) postContainersUnpause(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <add>func (s *containerRouter) postContainersUnpause(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <ide> if err := httputils.ParseForm(r); err != nil { <ide> return err <ide> } <ide> <del> if err := s.daemon.ContainerUnpause(vars["name"]); err != nil { <add> if err := s.backend.ContainerUnpause(vars["name"]); err != nil { <ide> return err <ide> } <ide> <ide> func (s *router) postContainersUnpause(ctx context.Context, w http.ResponseWrite <ide> return nil <ide> } <ide> <del>func (s *router) postContainersWait(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <del> status, err := s.daemon.ContainerWait(vars["name"], -1*time.Second) <add>func (s *containerRouter) postContainersWait(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <add> status, err := s.backend.ContainerWait(vars["name"], -1*time.Second) <ide> if err != nil { <ide> return err <ide> } <ide> func (s *router) postContainersWait(ctx context.Context, w http.ResponseWriter, <ide> }) <ide> } <ide> <del>func (s *router) getContainersChanges(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <del> changes, err := s.daemon.ContainerChanges(vars["name"]) <add>func (s *containerRouter) getContainersChanges(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <add> changes, err := s.backend.ContainerChanges(vars["name"]) <ide> if err != nil { <ide> return err <ide> } <ide> <ide> return httputils.WriteJSON(w, http.StatusOK, changes) <ide> } <ide> <del>func (s *router) getContainersTop(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <add>func (s *containerRouter) getContainersTop(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <ide> if err := httputils.ParseForm(r); err != nil { <ide> return err <ide> } <ide> <del> procList, err := s.daemon.ContainerTop(vars["name"], r.Form.Get("ps_args")) <add> procList, err := s.backend.ContainerTop(vars["name"], r.Form.Get("ps_args")) <ide> if err != nil { <ide> return err <ide> } <ide> <ide> return httputils.WriteJSON(w, http.StatusOK, procList) <ide> } <ide> <del>func (s *router) postContainerRename(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <add>func (s *containerRouter) postContainerRename(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <ide> if err := httputils.ParseForm(r); err != nil { <ide> return err <ide> } <ide> <ide> name := vars["name"] <ide> newName := r.Form.Get("name") <del> if err := s.daemon.ContainerRename(name, newName); err != nil { <add> if err := s.backend.ContainerRename(name, newName); err != nil { <ide> return err <ide> } <ide> w.WriteHeader(http.StatusNoContent) <ide> return nil <ide> } <ide> <del>func (s *router) postContainersCreate(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <add>func (s *containerRouter) postContainersCreate(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <ide> if err := httputils.ParseForm(r); err != nil { <ide> return err <ide> } <ide> func (s *router) postContainersCreate(ctx context.Context, w http.ResponseWriter <ide> version := httputils.VersionFromContext(ctx) <ide> adjustCPUShares := version.LessThan("1.19") <ide> <del> ccr, err := s.daemon.ContainerCreate(&daemon.ContainerCreateConfig{ <add> ccr, err := s.backend.ContainerCreate(&daemon.ContainerCreateConfig{ <ide> Name: name, <ide> Config: config, <ide> HostConfig: hostConfig, <ide> func (s *router) postContainersCreate(ctx context.Context, w http.ResponseWriter <ide> return httputils.WriteJSON(w, http.StatusCreated, ccr) <ide> } <ide> <del>func (s *router) deleteContainers(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <add>func (s *containerRouter) deleteContainers(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <ide> if err := httputils.ParseForm(r); err != nil { <ide> return err <ide> } <ide> func (s *router) deleteContainers(ctx context.Context, w http.ResponseWriter, r <ide> RemoveLink: httputils.BoolValue(r, "link"), <ide> } <ide> <del> if err := s.daemon.ContainerRm(name, config); err != nil { <add> if err := s.backend.ContainerRm(name, config); err != nil { <ide> // Force a 404 for the empty string <ide> if strings.Contains(strings.ToLower(err.Error()), "prefix can't be empty") { <ide> return fmt.Errorf("no such id: \"\"") <ide> func (s *router) deleteContainers(ctx context.Context, w http.ResponseWriter, r <ide> return nil <ide> } <ide> <del>func (s *router) postContainersResize(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <add>func (s *containerRouter) postContainersResize(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <ide> if err := httputils.ParseForm(r); err != nil { <ide> return err <ide> } <ide> func (s *router) postContainersResize(ctx context.Context, w http.ResponseWriter <ide> return err <ide> } <ide> <del> return s.daemon.ContainerResize(vars["name"], height, width) <add> return s.backend.ContainerResize(vars["name"], height, width) <ide> } <ide> <del>func (s *router) postContainersAttach(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <add>func (s *containerRouter) postContainersAttach(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <ide> if err := httputils.ParseForm(r); err != nil { <ide> return err <ide> } <ide> containerName := vars["name"] <ide> <del> if !s.daemon.Exists(containerName) { <add> if !s.backend.Exists(containerName) { <ide> return derr.ErrorCodeNoSuchContainer.WithArgs(containerName) <ide> } <ide> <del> if s.daemon.IsPaused(containerName) { <add> if s.backend.IsPaused(containerName) { <ide> return derr.ErrorCodePausedContainer.WithArgs(containerName) <ide> } <ide> <ide> func (s *router) postContainersAttach(ctx context.Context, w http.ResponseWriter <ide> Stream: httputils.BoolValue(r, "stream"), <ide> } <ide> <del> if err := s.daemon.ContainerAttachWithLogs(containerName, attachWithLogsConfig); err != nil { <add> if err := s.backend.ContainerAttachWithLogs(containerName, attachWithLogsConfig); err != nil { <ide> fmt.Fprintf(outStream, "Error attaching: %s\n", err) <ide> } <ide> <ide> return nil <ide> } <ide> <del>func (s *router) wsContainersAttach(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <add>func (s *containerRouter) wsContainersAttach(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <ide> if err := httputils.ParseForm(r); err != nil { <ide> return err <ide> } <ide> containerName := vars["name"] <ide> <del> if !s.daemon.Exists(containerName) { <add> if !s.backend.Exists(containerName) { <ide> return derr.ErrorCodeNoSuchContainer.WithArgs(containerName) <ide> } <ide> <ide> func (s *router) wsContainersAttach(ctx context.Context, w http.ResponseWriter, <ide> Stream: httputils.BoolValue(r, "stream"), <ide> } <ide> <del> if err := s.daemon.ContainerWsAttachWithLogs(containerName, wsAttachWithLogsConfig); err != nil { <add> if err := s.backend.ContainerWsAttachWithLogs(containerName, wsAttachWithLogsConfig); err != nil { <ide> logrus.Errorf("Error attaching websocket: %s", err) <ide> } <ide> }) <ide><path>api/server/router/container/copy.go <del>package local <add>package container <ide> <ide> import ( <ide> "encoding/base64" <ide> import ( <ide> ) <ide> <ide> // postContainersCopy is deprecated in favor of getContainersArchive. <del>func (s *router) postContainersCopy(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <add>func (s *containerRouter) postContainersCopy(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <ide> if err := httputils.CheckForJSON(r); err != nil { <ide> return err <ide> } <ide> func (s *router) postContainersCopy(ctx context.Context, w http.ResponseWriter, <ide> return fmt.Errorf("Path cannot be empty") <ide> } <ide> <del> data, err := s.daemon.ContainerCopy(vars["name"], cfg.Resource) <add> data, err := s.backend.ContainerCopy(vars["name"], cfg.Resource) <ide> if err != nil { <ide> if strings.Contains(strings.ToLower(err.Error()), "no such id") { <ide> w.WriteHeader(http.StatusNotFound) <ide> func setContainerPathStatHeader(stat *types.ContainerPathStat, header http.Heade <ide> return nil <ide> } <ide> <del>func (s *router) headContainersArchive(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <add>func (s *containerRouter) headContainersArchive(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <ide> v, err := httputils.ArchiveFormValues(r, vars) <ide> if err != nil { <ide> return err <ide> } <ide> <del> stat, err := s.daemon.ContainerStatPath(v.Name, v.Path) <add> stat, err := s.backend.ContainerStatPath(v.Name, v.Path) <ide> if err != nil { <ide> return err <ide> } <ide> <ide> return setContainerPathStatHeader(stat, w.Header()) <ide> } <ide> <del>func (s *router) getContainersArchive(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <add>func (s *containerRouter) getContainersArchive(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <ide> v, err := httputils.ArchiveFormValues(r, vars) <ide> if err != nil { <ide> return err <ide> } <ide> <del> tarArchive, stat, err := s.daemon.ContainerArchivePath(v.Name, v.Path) <add> tarArchive, stat, err := s.backend.ContainerArchivePath(v.Name, v.Path) <ide> if err != nil { <ide> return err <ide> } <ide> func (s *router) getContainersArchive(ctx context.Context, w http.ResponseWriter <ide> return err <ide> } <ide> <del>func (s *router) putContainersArchive(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <add>func (s *containerRouter) putContainersArchive(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <ide> v, err := httputils.ArchiveFormValues(r, vars) <ide> if err != nil { <ide> return err <ide> } <ide> <ide> noOverwriteDirNonDir := httputils.BoolValue(r, "noOverwriteDirNonDir") <del> return s.daemon.ContainerExtractToDir(v.Name, v.Path, noOverwriteDirNonDir, r.Body) <add> return s.backend.ContainerExtractToDir(v.Name, v.Path, noOverwriteDirNonDir, r.Body) <ide> } <ide><path>api/server/router/container/exec.go <del>package local <add>package container <ide> <ide> import ( <ide> "encoding/json" <ide> import ( <ide> "golang.org/x/net/context" <ide> ) <ide> <del>func (s *router) getExecByID(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <del> eConfig, err := s.daemon.ContainerExecInspect(vars["id"]) <add>func (s *containerRouter) getExecByID(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <add> eConfig, err := s.backend.ContainerExecInspect(vars["id"]) <ide> if err != nil { <ide> return err <ide> } <ide> <ide> return httputils.WriteJSON(w, http.StatusOK, eConfig) <ide> } <ide> <del>func (s *router) postContainerExecCreate(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <add>func (s *containerRouter) postContainerExecCreate(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <ide> if err := httputils.ParseForm(r); err != nil { <ide> return err <ide> } <ide> func (s *router) postContainerExecCreate(ctx context.Context, w http.ResponseWri <ide> } <ide> <ide> // Register an instance of Exec in container. <del> id, err := s.daemon.ContainerExecCreate(execConfig) <add> id, err := s.backend.ContainerExecCreate(execConfig) <ide> if err != nil { <ide> logrus.Errorf("Error setting up exec command in container %s: %s", name, err) <ide> return err <ide> func (s *router) postContainerExecCreate(ctx context.Context, w http.ResponseWri <ide> } <ide> <ide> // TODO(vishh): Refactor the code to avoid having to specify stream config as part of both create and start. <del>func (s *router) postContainerExecStart(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <add>func (s *containerRouter) postContainerExecStart(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <ide> if err := httputils.ParseForm(r); err != nil { <ide> return err <ide> } <ide> func (s *router) postContainerExecStart(ctx context.Context, w http.ResponseWrit <ide> return err <ide> } <ide> <del> if exists, err := s.daemon.ExecExists(execName); !exists { <add> if exists, err := s.backend.ExecExists(execName); !exists { <ide> return err <ide> } <ide> <ide> func (s *router) postContainerExecStart(ctx context.Context, w http.ResponseWrit <ide> } <ide> <ide> // Now run the user process in container. <del> if err := s.daemon.ContainerExecStart(execName, stdin, stdout, stderr); err != nil { <add> if err := s.backend.ContainerExecStart(execName, stdin, stdout, stderr); err != nil { <ide> if execStartCheck.Detach { <ide> return err <ide> } <ide> func (s *router) postContainerExecStart(ctx context.Context, w http.ResponseWrit <ide> return nil <ide> } <ide> <del>func (s *router) postContainerExecResize(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <add>func (s *containerRouter) postContainerExecResize(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <ide> if err := httputils.ParseForm(r); err != nil { <ide> return err <ide> } <ide> func (s *router) postContainerExecResize(ctx context.Context, w http.ResponseWri <ide> return err <ide> } <ide> <del> return s.daemon.ContainerExecResize(vars["name"], height, width) <add> return s.backend.ContainerExecResize(vars["name"], height, width) <ide> } <ide><path>api/server/router/container/inspect.go <del>package local <add>package container <ide> <ide> import ( <ide> "net/http" <ide> import ( <ide> ) <ide> <ide> // getContainersByName inspects containers configuration and serializes it as json. <del>func (s *router) getContainersByName(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <add>func (s *containerRouter) getContainersByName(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <ide> displaySize := httputils.BoolValue(r, "size") <ide> <ide> var json interface{} <ide> func (s *router) getContainersByName(ctx context.Context, w http.ResponseWriter, <ide> <ide> switch { <ide> case version.LessThan("1.20"): <del> json, err = s.daemon.ContainerInspectPre120(vars["name"]) <add> json, err = s.backend.ContainerInspectPre120(vars["name"]) <ide> case version.Equal("1.20"): <del> json, err = s.daemon.ContainerInspect120(vars["name"]) <add> json, err = s.backend.ContainerInspect120(vars["name"]) <ide> default: <del> json, err = s.daemon.ContainerInspect(vars["name"], displaySize) <add> json, err = s.backend.ContainerInspect(vars["name"], displaySize) <ide> } <ide> <ide> if err != nil { <ide><path>api/server/router/local/local.go <ide> func (r *router) Routes() []dkrouter.Route { <ide> // initRoutes initializes the routes in this router <ide> func (r *router) initRoutes() { <ide> r.routes = []dkrouter.Route{ <del> // HEAD <del> NewHeadRoute("/containers/{name:.*}/archive", r.headContainersArchive), <ide> // OPTIONS <ide> NewOptionsRoute("/", optionsHandler), <ide> // GET <ide> func (r *router) initRoutes() { <ide> NewGetRoute("/images/{name:.*}/get", r.getImagesGet), <ide> NewGetRoute("/images/{name:.*}/history", r.getImagesHistory), <ide> NewGetRoute("/images/{name:.*}/json", r.getImagesByName), <del> NewGetRoute("/containers/json", r.getContainersJSON), <del> NewGetRoute("/containers/{name:.*}/export", r.getContainersExport), <del> NewGetRoute("/containers/{name:.*}/changes", r.getContainersChanges), <del> NewGetRoute("/containers/{name:.*}/json", r.getContainersByName), <del> NewGetRoute("/containers/{name:.*}/top", r.getContainersTop), <del> NewGetRoute("/containers/{name:.*}/logs", r.getContainersLogs), <del> NewGetRoute("/containers/{name:.*}/stats", r.getContainersStats), <del> NewGetRoute("/containers/{name:.*}/attach/ws", r.wsContainersAttach), <del> NewGetRoute("/exec/{id:.*}/json", r.getExecByID), <del> NewGetRoute("/containers/{name:.*}/archive", r.getContainersArchive), <ide> // POST <ide> NewPostRoute("/auth", r.postAuth), <ide> NewPostRoute("/commit", r.postCommit), <ide> func (r *router) initRoutes() { <ide> NewPostRoute("/images/load", r.postImagesLoad), <ide> NewPostRoute("/images/{name:.*}/push", r.postImagesPush), <ide> NewPostRoute("/images/{name:.*}/tag", r.postImagesTag), <del> NewPostRoute("/containers/create", r.postContainersCreate), <del> NewPostRoute("/containers/{name:.*}/kill", r.postContainersKill), <del> NewPostRoute("/containers/{name:.*}/pause", r.postContainersPause), <del> NewPostRoute("/containers/{name:.*}/unpause", r.postContainersUnpause), <del> NewPostRoute("/containers/{name:.*}/restart", r.postContainersRestart), <del> NewPostRoute("/containers/{name:.*}/start", r.postContainersStart), <del> NewPostRoute("/containers/{name:.*}/stop", r.postContainersStop), <del> NewPostRoute("/containers/{name:.*}/wait", r.postContainersWait), <del> NewPostRoute("/containers/{name:.*}/resize", r.postContainersResize), <del> NewPostRoute("/containers/{name:.*}/attach", r.postContainersAttach), <del> NewPostRoute("/containers/{name:.*}/copy", r.postContainersCopy), <del> NewPostRoute("/containers/{name:.*}/exec", r.postContainerExecCreate), <del> NewPostRoute("/exec/{name:.*}/start", r.postContainerExecStart), <del> NewPostRoute("/exec/{name:.*}/resize", r.postContainerExecResize), <del> NewPostRoute("/containers/{name:.*}/rename", r.postContainerRename), <del> // PUT <del> NewPutRoute("/containers/{name:.*}/archive", r.putContainersArchive), <ide> // DELETE <del> NewDeleteRoute("/containers/{name:.*}", r.deleteContainers), <ide> NewDeleteRoute("/images/{name:.*}", r.deleteImages), <ide> } <ide> } <ide><path>api/server/server.go <ide> import ( <ide> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/api/server/httputils" <ide> "github.com/docker/docker/api/server/router" <add> "github.com/docker/docker/api/server/router/container" <ide> "github.com/docker/docker/api/server/router/local" <ide> "github.com/docker/docker/api/server/router/network" <ide> "github.com/docker/docker/api/server/router/volume" <ide> func (s *Server) InitRouters(d *daemon.Daemon) { <ide> s.addRouter(local.NewRouter(d)) <ide> s.addRouter(network.NewRouter(d)) <ide> s.addRouter(volume.NewRouter(d)) <add> s.addRouter(container.NewRouter(d)) <ide> <ide> for _, srv := range s.servers { <ide> srv.srv.Handler = s.CreateMux()
9
Javascript
Javascript
remove unused imports
dc60f97e9dab2479ff78d696ca6a0b4acf486d01
<ide><path>packages/ember-routing/lib/services/router.js <ide> import { <ide> Service, <ide> readOnly <ide> } from 'ember-runtime'; <del>import { assign } from 'ember-utils'; <ide> import { shallowEqual } from '../utils'; <del>import RouterDSL from '../system/dsl'; <ide> <ide> /** <ide> The Router service is the public API that provides component/view layer
1
Java
Java
fix typo in javadoc
60123b6ca34480482478ca8e70dddd7f4efbed5c
<ide><path>spring-aspects/src/main/java/org/springframework/context/annotation/aspectj/SpringConfiguredConfiguration.java <ide> * Configurable}. <ide> * <ide> * <p>This configuration class is automatically imported when using the <del> * @{@link EnableSpringConfigured} annotation. See {@code @EnableSpringConfigured}'s <add> * {@link EnableSpringConfigured @EnableSpringConfigured} annotation. See {@code @EnableSpringConfigured}'s <ide> * javadoc for complete usage details. <ide> * <ide> * @author Chris Beams
1
Ruby
Ruby
use identity mapper only if enabled
09f12a12706593884961a682660f34282e937e46
<ide><path>activerecord/lib/active_record/persistence.rb <ide> def save!(*) <ide> def delete <ide> if persisted? <ide> self.class.delete(id) <del> IdentityMap.remove(self) <add> IdentityMap.remove(self) if IdentityMap.enabled? <ide> end <ide> @destroyed = true <ide> freeze <ide> def delete <ide> # that no changes should be made (since they can't be persisted). <ide> def destroy <ide> if persisted? <del> IdentityMap.remove(self) <add> IdentityMap.remove(self) if IdentityMap.enabled? <ide> self.class.unscoped.where(self.class.arel_table[self.class.primary_key].eq(id)).delete_all <ide> end <ide> <ide> def create <ide> <ide> self.id ||= new_id <ide> <del> IdentityMap.add(self) <add> IdentityMap.add(self) if IdentityMap.enabled? <ide> @persisted = true <ide> id <ide> end
1
Text
Text
make semi-colon optional
07b38d02b3b1068c17ffc362874b87198d737d73
<ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/basic-javascript/passing-values-to-functions-with-arguments.english.md <ide> tests: <ide> - text: <code>functionWithArgs(7,9)</code> should output <code>16</code> <ide> testString: if(typeof functionWithArgs === "function") { capture(); functionWithArgs(7,9); uncapture(); } assert(logOutput == 16); <ide> - text: Call <code>functionWithArgs</code> with two numbers after you define it. <del> testString: assert(/^\s*functionWithArgs\s*\(\s*\d+\s*,\s*\d+\s*\)\s*;/m.test(code)); <add> testString: assert(/^\s*functionWithArgs\s*\(\s*\d+\s*,\s*\d+\s*\)\s*/m.test(code)); <ide> <ide> ``` <ide>
1
Javascript
Javascript
add createelement alias for createdescriptor
036d751397140e1eae01ea6ce6ebe86f0482f485
<ide><path>src/browser/ui/React.js <ide> var React = { <ide> EventPluginUtils.useTouchEvents = shouldUseTouch; <ide> }, <ide> createClass: ReactCompositeComponent.createClass, <del> createDescriptor: createDescriptor, <add> createDescriptor: createDescriptor, // deprecated, will be removed next week <add> createElement: createDescriptor, <ide> createFactory: createFactory, <ide> constructAndRenderComponent: ReactMount.constructAndRenderComponent, <ide> constructAndRenderComponentByID: ReactMount.constructAndRenderComponentByID,
1
PHP
PHP
remove deprecated code in http/client
41016a41bdb5cabf923a86e8f6a54ae9fde77117
<ide><path>src/Http/Client/CookieCollection.php <del><?php <del>/** <del> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <del> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <del> * <del> * Licensed under The MIT License <del> * Redistributions of files must retain the above copyright notice. <del> * <del> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <del> * @link https://cakephp.org CakePHP(tm) Project <del> * @since 3.0.0 <del> * @license https://opensource.org/licenses/mit-license.php MIT License <del> */ <del>namespace Cake\Http\Client; <del> <del>use Cake\Http\Cookie\CookieCollection as BaseCollection; <del>use Cake\Http\Cookie\CookieInterface; <del> <del>/** <del> * Container class for cookies used in Http\Client. <del> * <del> * Provides cookie jar like features for storing cookies between <del> * requests, as well as appending cookies to new requests. <del> * <del> * @deprecated 3.5.0 Use Cake\Http\Cookie\CookieCollection instead. <del> */ <del>class CookieCollection extends BaseCollection <del>{ <del> <del> /** <del> * {@inheritDoc} <del> */ <del> public function __construct(array $cookies = []) <del> { <del> parent::__construct($cookies); <del> <del> deprecationWarning('Use Cake\Http\Cookie\CookieCollection instead.'); <del> } <del> <del> /** <del> * Store the cookies from a response. <del> * <del> * Store the cookies that haven't expired. If a cookie has been expired <del> * and is currently stored, it will be removed. <del> * <del> * @param Response $response The response to read cookies from <del> * @param string $url The request URL used for default host/path values. <del> * @return void <del> */ <del> public function store(Response $response, $url) <del> { <del> $host = parse_url($url, PHP_URL_HOST); <del> $path = parse_url($url, PHP_URL_PATH); <del> $path = $path ?: '/'; <del> <del> $header = $response->getHeader('Set-Cookie'); <del> $cookies = $this->parseSetCookieHeader($header); <del> $cookies = $this->setRequestDefaults($cookies, $host, $path); <del> foreach ($cookies as $cookie) { <del> $this->cookies[$cookie->getId()] = $cookie; <del> } <del> $this->removeExpiredCookies($host, $path); <del> } <del> <del> /** <del> * Get stored cookies for a URL. <del> * <del> * Finds matching stored cookies and returns a simple array <del> * of name => value <del> * <del> * @param string $url The URL to find cookies for. <del> * @return array <del> */ <del> public function get($url) <del> { <del> $path = parse_url($url, PHP_URL_PATH) ?: '/'; <del> $host = parse_url($url, PHP_URL_HOST); <del> $scheme = parse_url($url, PHP_URL_SCHEME); <del> <del> return $this->findMatchingCookies($scheme, $host, $path); <del> } <del> <del> /** <del> * Get all the stored cookies as arrays. <del> * <del> * @return array <del> */ <del> public function getAll() <del> { <del> $out = []; <del> foreach ($this->cookies as $cookie) { <del> $out[] = $this->convertCookieToArray($cookie); <del> } <del> <del> return $out; <del> } <del> <del> /** <del> * Convert the cookie into an array of its properties. <del> * <del> * Primarily useful where backwards compatibility is needed. <del> * <del> * @param \Cake\Http\Cookie\CookieInterface $cookie Cookie object. <del> * @return array <del> */ <del> protected function convertCookieToArray(CookieInterface $cookie) <del> { <del> return [ <del> 'name' => $cookie->getName(), <del> 'value' => $cookie->getValue(), <del> 'path' => $cookie->getPath(), <del> 'domain' => $cookie->getDomain(), <del> 'secure' => $cookie->isSecure(), <del> 'httponly' => $cookie->isHttpOnly(), <del> 'expires' => $cookie->getExpiresTimestamp() <del> ]; <del> } <del>} <ide><path>src/Http/Client/Message.php <ide> class Message <ide> */ <ide> protected $_body; <ide> <del> /** <del> * Get all headers <del> * <del> * @return array <del> * @deprecated 3.3.0 Use getHeaders() instead. <del> */ <del> public function headers() <del> { <del> deprecationWarning( <del> 'Message::headers() is deprecated. ' . <del> 'Use getHeaders() instead.' <del> ); <del> <del> return $this->headers; <del> } <del> <ide> /** <ide> * Get all cookies <ide> * <ide><path>src/Http/Client/Request.php <ide> public function __construct($url = '', $method = self::METHOD_GET, array $header <ide> $this->body($data); <ide> } <ide> <del> /** <del> * Get/Set the HTTP method. <del> * <del> * *Warning* This method mutates the request in-place for backwards <del> * compatibility reasons, and is not part of the PSR7 interface. <del> * <del> * @param string|null $method The method for the request. <del> * @return $this|string Either this or the current method. <del> * @throws \Cake\Core\Exception\Exception On invalid methods. <del> * @deprecated 3.3.0 Use getMethod() and withMethod() instead. <del> */ <del> public function method($method = null) <del> { <del> deprecationWarning( <del> 'Request::method() is deprecated. ' . <del> 'Use getMethod() and withMethod() instead.' <del> ); <del> <del> if ($method === null) { <del> return $this->method; <del> } <del> $name = get_called_class() . '::METHOD_' . strtoupper($method); <del> if (!defined($name)) { <del> throw new Exception('Invalid method type'); <del> } <del> $this->method = $method; <del> <del> return $this; <del> } <del> <del> /** <del> * Get/Set the url for the request. <del> * <del> * *Warning* This method mutates the request in-place for backwards <del> * compatibility reasons, and is not part of the PSR7 interface. <del> * <del> * @param string|null $url The url for the request. Leave null for get <del> * @return $this|string Either $this or the url value. <del> * @deprecated 3.3.0 Use getUri() and withUri() instead. <del> */ <del> public function url($url = null) <del> { <del> deprecationWarning( <del> 'Request::url() is deprecated. ' . <del> 'Use getUri() and withUri() instead.' <del> ); <del> <del> if ($url === null) { <del> return '' . $this->getUri(); <del> } <del> $this->uri = $this->createUri($url); <del> <del> return $this; <del> } <del> <del> /** <del> * Get/Set headers into the request. <del> * <del> * You can get the value of a header, or set one/many headers. <del> * Headers are set / fetched in a case insensitive way. <del> * <del> * ### Getting headers <del> * <del> * ``` <del> * $request->header('Content-Type'); <del> * ``` <del> * <del> * ### Setting one header <del> * <del> * ``` <del> * $request->header('Content-Type', 'application/json'); <del> * ``` <del> * <del> * ### Setting multiple headers <del> * <del> * ``` <del> * $request->header(['Connection' => 'close', 'User-Agent' => 'CakePHP']); <del> * ``` <del> * <del> * *Warning* This method mutates the request in-place for backwards <del> * compatibility reasons, and is not part of the PSR7 interface. <del> * <del> * @param string|array|null $name The name to get, or array of multiple values to set. <del> * @param string|null $value The value to set for the header. <del> * @return mixed Either $this when setting or header value when getting. <del> * @deprecated 3.3.0 Use withHeader() and getHeaderLine() instead. <del> */ <del> public function header($name = null, $value = null) <del> { <del> deprecationWarning( <del> 'Request::header() is deprecated. ' . <del> 'Use withHeader() and getHeaderLine() instead.' <del> ); <del> <del> if ($value === null && is_string($name)) { <del> $val = $this->getHeaderLine($name); <del> if ($val === '') { <del> return null; <del> } <del> <del> return $val; <del> } <del> <del> if ($value !== null && !is_array($name)) { <del> $name = [$name => $value]; <del> } <del> $this->addHeaders($name); <del> <del> return $this; <del> } <del> <ide> /** <ide> * Add an array of headers to the request. <ide> * <ide> protected function addHeaders(array $headers) <ide> } <ide> } <ide> <del> /** <del> * Get/Set cookie values. <del> * <del> * ### Getting a cookie <del> * <del> * ``` <del> * $request->cookie('session'); <del> * ``` <del> * <del> * ### Setting one cookie <del> * <del> * ``` <del> * $request->cookie('session', '123456'); <del> * ``` <del> * <del> * ### Setting multiple headers <del> * <del> * ``` <del> * $request->cookie(['test' => 'value', 'split' => 'banana']); <del> * ``` <del> * <del> * @param string $name The name of the cookie to get/set <del> * @param string|null $value Either the value or null when getting values. <del> * @return mixed Either $this or the cookie value. <del> * @deprecated 3.5.0 No longer used. CookieCollections now add `Cookie` header to the request <del> * before sending. Use Cake\Http\Cookie\CookieCollection::addToRequest() to make adding cookies <del> * to a request easier. <del> */ <del> public function cookie($name, $value = null) <del> { <del> deprecationWarning( <del> 'Request::cookie() is deprecated. ' . <del> 'The Client internals now add the required `Cookie` header to the ' . <del> 'request before sending. Use Cake\Http\Cookie\CookieCollection::addToRequest() ' . <del> 'to make adding cookies to a request easier.' <del> ); <del> <del> if ($value === null && is_string($name)) { <del> return isset($this->_cookies[$name]) ? $this->_cookies[$name] : null; <del> } <del> if (is_string($name) && is_string($value)) { <del> $name = [$name => $value]; <del> } <del> foreach ($name as $key => $val) { <del> $this->_cookies[$key] = $val; <del> } <del> <del> return $this; <del> } <del> <del> /** <del> * Get/Set HTTP version. <del> * <del> * *Warning* This method mutates the request in-place for backwards <del> * compatibility reasons, and is not part of the PSR7 interface. <del> * <del> * @param string|null $version The HTTP version. <del> * @return $this|string Either $this or the HTTP version. <del> * @deprecated 3.3.0 Use getProtocolVersion() and withProtocolVersion() instead. <del> */ <del> public function version($version = null) <del> { <del> deprecationWarning( <del> 'Request::version() is deprecated. ' . <del> 'Use getProtocolVersion() and withProtocolVersion() instead.' <del> ); <del> <del> if ($version === null) { <del> return $this->protocol; <del> } <del> <del> $this->protocol = $version; <del> <del> return $this; <del> } <del> <ide> /** <ide> * Get/set the body/payload for the message. <ide> * <ide><path>src/Http/Client/Response.php <ide> */ <ide> namespace Cake\Http\Client; <ide> <del>// This alias is necessary to avoid class name conflicts <del>// with the deprecated class in this namespace. <del>use Cake\Http\Cookie\CookieCollection as CookiesCollection; <add>use Cake\Http\Cookie\CookieCollection; <ide> use Cake\Http\Cookie\CookieInterface; <ide> use Psr\Http\Message\ResponseInterface; <ide> use RuntimeException; <ide> public function isRedirect() <ide> ); <ide> } <ide> <del> /** <del> * Get the status code from the response <del> * <del> * @return int <del> * @deprecated 3.3.0 Use getStatusCode() instead. <del> */ <del> public function statusCode() <del> { <del> deprecationWarning( <del> 'Response::statusCode() is deprecated. ' . <del> 'Use Response::getStatusCode() instead.' <del> ); <del> <del> return $this->code; <del> } <del> <ide> /** <ide> * {@inheritdoc} <ide> * <ide> public function getReasonPhrase() <ide> return $this->reasonPhrase; <ide> } <ide> <del> /** <del> * Get the encoding if it was set. <del> * <del> * @return string|null <del> * @deprecated 3.3.0 Use getEncoding() instead. <del> */ <del> public function encoding() <del> { <del> deprecationWarning( <del> 'Response::encoding() is deprecated. ' . <del> 'Use Response::getEncoding() instead.' <del> ); <del> <del> return $this->getEncoding(); <del> } <del> <ide> /** <ide> * Get the encoding if it was set. <ide> * <ide> public function getEncoding() <ide> return $matches[1]; <ide> } <ide> <del> /** <del> * Read single/multiple header value(s) out. <del> * <del> * @param string|null $name The name of the header you want. Leave <del> * null to get all headers. <del> * @return mixed Null when the header doesn't exist. An array <del> * will be returned when getting all headers or when getting <del> * a header that had multiple values set. Otherwise a string <del> * will be returned. <del> * @deprecated 3.3.0 Use getHeader() and getHeaderLine() instead. <del> */ <del> public function header($name = null) <del> { <del> deprecationWarning( <del> 'Response::header() is deprecated. ' . <del> 'Use Response::getHeader() and getHeaderLine() instead.' <del> ); <del> <del> if ($name === null) { <del> return $this->_getHeaders(); <del> } <del> $header = $this->getHeader($name); <del> if (count($header) === 1) { <del> return $header[0]; <del> } <del> <del> return $header; <del> } <del> <del> /** <del> * Read single/multiple cookie values out. <del> * <del> * *Note* This method will only provide access to cookies that <del> * were added as part of the constructor. If cookies are added post <del> * construction they will not be accessible via this method. <del> * <del> * @param string|null $name The name of the cookie you want. Leave <del> * null to get all cookies. <del> * @param bool $all Get all parts of the cookie. When false only <del> * the value will be returned. <del> * @return mixed <del> * @deprecated 3.3.0 Use getCookie(), getCookieData() or getCookies() instead. <del> */ <del> public function cookie($name = null, $all = false) <del> { <del> deprecationWarning( <del> 'Response::cookie() is deprecated. ' . <del> 'Use Response::getCookie(), getCookieData() or getCookies() instead.' <del> ); <del> <del> if ($name === null) { <del> return $this->getCookies(); <del> } <del> if ($all) { <del> return $this->getCookieData($name); <del> } <del> <del> return $this->getCookie($name); <del> } <del> <ide> /** <ide> * Get the all cookie data. <ide> * <ide> protected function buildCookieCollection() <ide> if ($this->cookies) { <ide> return; <ide> } <del> $this->cookies = CookiesCollection::createFromHeader($this->getHeader('Set-Cookie')); <add> $this->cookies = CookieCollection::createFromHeader($this->getHeader('Set-Cookie')); <ide> } <ide> <ide> /** <ide> protected function _getCookies() <ide> return $cookies; <ide> } <ide> <del> /** <del> * Get the HTTP version used. <del> * <del> * @return string <del> * @deprecated 3.3.0 Use getProtocolVersion() <del> */ <del> public function version() <del> { <del> deprecationWarning( <del> 'Response::version() is deprecated. ' . <del> 'Use Response::getProtocolVersion() instead.' <del> ); <del> <del> return $this->protocol; <del> } <del> <ide> /** <ide> * Get the response body. <ide> * <ide><path>tests/TestCase/Http/Client/CookieCollectionTest.php <del><?php <del>/** <del> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <del> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <del> * <del> * Licensed under The MIT License <del> * Redistributions of files must retain the above copyright notice. <del> * <del> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <del> * @link https://cakephp.org CakePHP(tm) Project <del> * @since 3.0.0 <del> * @license https://opensource.org/licenses/mit-license.php MIT License <del> */ <del>namespace Cake\Test\TestCase\Http\Client; <del> <del>use Cake\Http\Client\CookieCollection; <del>use Cake\Http\Client\Response; <del>use Cake\TestSuite\TestCase; <del> <del>/** <del> * HTTP cookies test. <del> * <del> * @group deprecated <del> */ <del>class CookieCollectionTest extends TestCase <del>{ <del> <del> /** <del> * setup <del> * <del> * @return void <del> */ <del> public function setUp() <del> { <del> parent::setUp(); <del> $this->deprecated(function () { <del> $this->cookies = new CookieCollection(); <del> }); <del> } <del> <del> /** <del> * test store <del> * <del> * @return void <del> */ <del> public function testStore() <del> { <del> $headers = [ <del> 'HTTP/1.0 200 Ok', <del> 'Set-Cookie: first=1', <del> 'Set-Cookie: second=2; Path=/; Domain=.foo.example.com', <del> 'Set-Cookie: expiring=now; Expires=Wed, 09-Jun-1999 10:18:14 GMT', <del> ]; <del> $response = new Response($headers, ''); <del> $result = $this->cookies->store($response, 'http://example.com/some/path'); <del> $this->assertNull($result); <del> <del> $result = $this->cookies->getAll(); <del> $this->assertCount(2, $result); <del> $expected = [ <del> [ <del> 'name' => 'first', <del> 'value' => '1', <del> 'path' => '/some/path', <del> 'domain' => 'example.com', <del> 'secure' => false, <del> 'httponly' => false, <del> 'expires' => 0, <del> ], <del> [ <del> 'name' => 'second', <del> 'value' => '2', <del> 'path' => '/', <del> 'domain' => '.foo.example.com', <del> 'secure' => false, <del> 'httponly' => false, <del> 'expires' => 0, <del> ], <del> ]; <del> $this->assertEquals($expected, $result); <del> } <del> <del> /** <del> * test store secure. <del> * <del> * @return void <del> */ <del> public function testStoreSecure() <del> { <del> $headers = [ <del> 'HTTP/1.0 200 Ok', <del> 'Set-Cookie: first=1', <del> 'Set-Cookie: second=2; Secure; HttpOnly', <del> ]; <del> $response = new Response($headers, ''); <del> $result = $this->cookies->store($response, 'http://example.com/some/path'); <del> $this->assertNull($result); <del> <del> $result = $this->cookies->getAll(); <del> $this->assertCount(2, $result); <del> $expected = [ <del> [ <del> 'name' => 'first', <del> 'value' => '1', <del> 'path' => '/some/path', <del> 'domain' => 'example.com', <del> 'secure' => false, <del> 'httponly' => false, <del> 'expires' => 0, <del> ], <del> [ <del> 'name' => 'second', <del> 'value' => '2', <del> 'path' => '/some/path', <del> 'domain' => 'example.com', <del> 'secure' => true, <del> 'httponly' => true, <del> 'expires' => 0, <del> ], <del> ]; <del> $this->assertEquals($expected, $result); <del> } <del> <del> /** <del> * test storing an expired cookie clears existing ones too. <del> * <del> * @return void <del> */ <del> public function testStoreExpiring() <del> { <del> $headers = [ <del> 'HTTP/1.0 200 Ok', <del> 'Set-Cookie: first=1', <del> 'Set-Cookie: second=2; Path=/', <del> ]; <del> $response = new Response($headers, ''); <del> $this->cookies->store($response, 'http://example.com/some/path'); <del> <del> $result = $this->cookies->getAll(); <del> $this->assertCount(2, $result); <del> <del> $headers = [ <del> 'HTTP/1.0 200 Ok', <del> 'Set-Cookie: first=1; Expires=Wed, 09-Jun-1999 10:18:14 GMT', <del> ]; <del> $response = new Response($headers, ''); <del> $this->cookies->store($response, 'http://example.com/'); <del> $result = $this->cookies->getAll(); <del> $this->assertCount(2, $result, 'Path does not match, no expiration'); <del> <del> // Use a more common date format that doesn't match <del> $headers = [ <del> 'HTTP/1.0 200 Ok', <del> 'Set-Cookie: first=1; Domain=.foo.example.com; Expires=Wed, 09-Jun-1999 10:18:14 GMT', <del> ]; <del> $response = new Response($headers, ''); <del> $this->cookies->store($response, 'http://example.com/some/path'); <del> $result = $this->cookies->getAll(); <del> $this->assertCount(2, $result, 'Domain does not match, no expiration'); <del> <del> // Use an RFC1123 date <del> $headers = [ <del> 'HTTP/1.0 200 Ok', <del> 'Set-Cookie: first=1; Expires=Wed, 09 Jun 1999 10:18:14 GMT', <del> ]; <del> $response = new Response($headers, ''); <del> $this->cookies->store($response, 'http://example.com/some/path'); <del> $result = $this->cookies->getAll(); <del> $this->assertCount(1, $result, 'Domain does not match, no expiration'); <del> <del> $expected = [ <del> [ <del> 'name' => 'second', <del> 'value' => '2', <del> 'path' => '/', <del> 'domain' => 'example.com', <del> 'expires' => 0, <del> 'secure' => false, <del> 'httponly' => false, <del> ], <del> ]; <del> $this->assertEquals($expected, $result); <del> } <del> <del> /** <del> * test getting cookies with secure flags <del> * <del> * @return void <del> */ <del> public function testGetMatchingSecure() <del> { <del> $headers = [ <del> 'HTTP/1.0 200 Ok', <del> 'Set-Cookie: first=1', <del> 'Set-Cookie: second=2; Secure; HttpOnly', <del> ]; <del> $response = new Response($headers, ''); <del> $this->cookies->store($response, 'https://example.com/'); <del> <del> $result = $this->cookies->get('https://example.com/test'); <del> $expected = ['first' => '1', 'second' => '2']; <del> $this->assertEquals($expected, $result); <del> <del> $result = $this->cookies->get('http://example.com/test'); <del> $expected = ['first' => '1']; <del> $this->assertEquals($expected, $result); <del> } <del> <del> /** <del> * test getting cookies with secure flags <del> * <del> * @return void <del> */ <del> public function testGetMatchingPath() <del> { <del> $headers = [ <del> 'HTTP/1.0 200 Ok', <del> 'Set-Cookie: first=1; Path=/foo', <del> 'Set-Cookie: second=2; Path=/', <del> ]; <del> $response = new Response($headers, ''); <del> $this->cookies->store($response, 'http://example.com/foo'); <del> <del> $result = $this->cookies->get('http://example.com/foo'); <del> $expected = ['first' => '1', 'second' => 2]; <del> $this->assertEquals($expected, $result); <del> <del> $result = $this->cookies->get('http://example.com/'); <del> $expected = ['second' => 2]; <del> $this->assertEquals($expected, $result); <del> <del> $result = $this->cookies->get('http://example.com/test'); <del> $expected = ['second' => 2]; <del> $this->assertEquals($expected, $result); <del> } <del> <del> /** <del> * Test getting cookies matching on paths exactly <del> * <del> * @return void <del> */ <del> public function testGetMatchingDomain() <del> { <del> $headers = [ <del> 'HTTP/1.0 200 Ok', <del> 'Set-Cookie: first=1; Domain=example.com', <del> 'Set-Cookie: second=2;', <del> ]; <del> $response = new Response($headers, ''); <del> $this->cookies->store($response, 'http://foo.example.com/'); <del> <del> $result = $this->cookies->get('http://example.com'); <del> $expected = ['first' => 1]; <del> $this->assertEquals($expected, $result); <del> <del> $result = $this->cookies->get('http://foo.example.com'); <del> $expected = ['first' => 1, 'second' => '2']; <del> $this->assertEquals($expected, $result); <del> <del> $result = $this->cookies->get('http://bar.foo.example.com'); <del> $expected = ['first' => 1, 'second' => '2']; <del> $this->assertEquals($expected, $result); <del> <del> $result = $this->cookies->get('http://api.example.com'); <del> $expected = ['first' => 1]; <del> $this->assertEquals($expected, $result); <del> <del> $result = $this->cookies->get('http://google.com'); <del> $expected = []; <del> $this->assertEquals($expected, $result); <del> } <del> <del> /** <del> * Test getting cookies matching on paths exactly <del> * <del> * @return void <del> */ <del> public function testGetMatchingDomainWithDot() <del> { <del> $headers = [ <del> 'HTTP/1.0 200 Ok', <del> 'Set-Cookie: first=1; Domain=.example.com', <del> 'Set-Cookie: second=2;', <del> ]; <del> $response = new Response($headers, ''); <del> $this->cookies->store($response, 'http://foo.example.com/'); <del> <del> $result = $this->cookies->get('http://example.com'); <del> $expected = ['first' => 1]; <del> $this->assertEquals($expected, $result); <del> <del> $result = $this->cookies->get('http://foo.example.com'); <del> $expected = ['first' => 1, 'second' => '2']; <del> $this->assertEquals($expected, $result); <del> <del> $result = $this->cookies->get('http://bar.foo.example.com'); <del> $expected = ['first' => 1, 'second' => '2']; <del> $this->assertEquals($expected, $result); <del> <del> $result = $this->cookies->get('http://api.example.com'); <del> $expected = ['first' => 1]; <del> $this->assertEquals($expected, $result); <del> <del> $result = $this->cookies->get('http://google.com'); <del> $expected = []; <del> $this->assertEquals($expected, $result); <del> } <del>} <ide><path>tests/TestCase/Http/Client/RequestTest.php <ide> public function testConstructorArrayNestedData() <ide> $this->assertEquals('a=b&c%5B0%5D=foo&c%5B1%5D=bar', $request->body()); <ide> } <ide> <del> /** <del> * test url method <del> * <del> * @group deprecated <del> * @return void <del> */ <del> public function testUrl() <del> { <del> $this->deprecated(function () { <del> $request = new Request(); <del> $this->assertSame($request, $request->url('http://example.com')); <del> <del> $this->assertEquals('http://example.com', $request->url()); <del> }); <del> } <del> <del> /** <del> * Test that url() modifies the PSR7 stream <del> * <del> * @group deprecated <del> * @return void <del> */ <del> public function testUrlInteroperability() <del> { <del> $this->deprecated(function () { <del> $request = new Request(); <del> $request->url('http://example.com'); <del> $this->assertSame('http://example.com', $request->url()); <del> $this->assertSame('http://example.com', $request->getUri()->__toString()); <del> <del> $uri = 'http://example.com/test'; <del> $request = new Request(); <del> $request = $request->withUri(new Uri($uri)); <del> $this->assertSame($uri, $request->url()); <del> $this->assertSame($uri, $request->getUri()->__toString()); <del> }); <del> } <del> <del> /** <del> * test method method. <del> * <del> * @group deprecated <del> * @return void <del> */ <del> public function testMethod() <del> { <del> $this->deprecated(function () { <del> $request = new Request(); <del> $this->assertSame($request, $request->method(Request::METHOD_GET)); <del> <del> $this->assertEquals(Request::METHOD_GET, $request->method()); <del> }); <del> } <del> <del> /** <del> * test method interoperability. <del> * <del> * @group deprecated <del> * @return void <del> */ <del> public function testMethodInteroperability() <del> { <del> $this->deprecated(function () { <del> $request = new Request(); <del> $this->assertSame($request, $request->method(Request::METHOD_GET)); <del> <del> $this->assertEquals(Request::METHOD_GET, $request->method()); <del> $this->assertEquals(Request::METHOD_GET, $request->getMethod()); <del> <del> $request = $request->withMethod(Request::METHOD_GET); <del> $this->assertEquals(Request::METHOD_GET, $request->method()); <del> $this->assertEquals(Request::METHOD_GET, $request->getMethod()); <del> }); <del> } <del> <del> /** <del> * test invalid method. <del> * <del> * @group deprecated <del> * @return void <del> */ <del> public function testMethodInvalid() <del> { <del> $this->expectException(\Cake\Core\Exception\Exception::class); <del> $this->deprecated(function () { <del> $request = new Request(); <del> $request->method('set on fire'); <del> }); <del> } <del> <ide> /** <ide> * test body method. <ide> * <ide> public function testBody() <ide> /** <ide> * test body method with array payload <ide> * <del> * @group deprecated <ide> * @return void <ide> */ <ide> public function testBodyArray() <ide> public function testBodyInteroperability() <ide> $this->assertSame($data, '' . $request->getBody()); <ide> } <ide> <del> /** <del> * test header method. <del> * <del> * @group deprecated <del> * @return void <del> */ <del> public function testHeader() <del> { <del> $this->deprecated(function () { <del> $request = new Request(); <del> $type = 'application/json'; <del> $result = $request->header('Content-Type', $type); <del> $this->assertSame($result, $request, 'Should return self'); <del> <del> $result = $request->header('content-type'); <del> $this->assertEquals($type, $result, 'lowercase does not work'); <del> <del> $result = $request->header('ConTent-typE'); <del> $this->assertEquals($type, $result, 'Funny casing does not work'); <del> <del> $result = $request->header([ <del> 'Connection' => 'close', <del> 'user-agent' => 'CakePHP' <del> ]); <del> $this->assertSame($result, $request, 'Should return self'); <del> <del> $this->assertEquals('close', $request->header('connection')); <del> $this->assertEquals('CakePHP', $request->header('USER-AGENT')); <del> $this->assertNull($request->header('not set')); <del> }); <del> } <del> <ide> /** <ide> * Test the default headers <ide> * <ide> public function testDefaultHeaders() <ide> $this->assertEquals('CakePHP', $request->getHeaderLine('User-Agent')); <ide> $this->assertEquals('close', $request->getHeaderLine('Connection')); <ide> } <del> <del> /** <del> * Test that header() and PSR7 methods play nice. <del> * <del> * @group deprecated <del> * @return void <del> */ <del> public function testHeaderMethodInteroperability() <del> { <del> $this->deprecated(function () { <del> $request = new Request(); <del> $request->header('Content-Type', 'application/json'); <del> $this->assertEquals('application/json', $request->header('Content-Type'), 'Old getter should work'); <del> <del> $this->assertEquals('application/json', $request->getHeaderLine('Content-Type'), 'getHeaderLine works'); <del> $this->assertEquals('application/json', $request->getHeaderLine('content-type'), 'getHeaderLine works'); <del> $this->assertEquals(['application/json'], $request->getHeader('Content-Type'), 'getHeader works'); <del> $this->assertEquals(['application/json'], $request->getHeader('content-type'), 'getHeader works'); <del> }); <del> } <del> <del> /** <del> * test cookie method. <del> * <del> * @group deprecated <del> * @return void <del> */ <del> public function testCookie() <del> { <del> $this->deprecated(function () { <del> $request = new Request(); <del> $result = $request->cookie('session', '123456'); <del> $this->assertSame($result, $request, 'Should return self'); <del> <del> $this->assertNull($request->cookie('not set')); <del> <del> $result = $request->cookie('session'); <del> $this->assertEquals('123456', $result); <del> }); <del> } <del> <del> /** <del> * test version method. <del> * <del> * @group deprecated <del> * @return void <del> */ <del> public function testVersion() <del> { <del> $this->deprecated(function () { <del> $request = new Request(); <del> $result = $request->version('1.0'); <del> $this->assertSame($request, $result, 'Should return self'); <del> <del> $this->assertSame('1.0', $request->version()); <del> }); <del> } <del> <del> /** <del> * test version Interoperable. <del> * <del> * @group deprecated <del> * @return void <del> */ <del> public function testVersionInteroperability() <del> { <del> $this->deprecated(function () { <del> $request = new Request(); <del> $this->assertEquals('1.1', $request->version()); <del> $this->assertEquals('1.1', $request->getProtocolVersion()); <del> <del> $request = $request->withProtocolVersion('1.0'); <del> $this->assertEquals('1.0', $request->version()); <del> $this->assertEquals('1.0', $request->getProtocolVersion()); <del> }); <del> } <ide> } <ide><path>tests/TestCase/Http/Client/ResponseTest.php <ide> public function testIsRedirect() <ide> $this->assertFalse($response->isRedirect()); <ide> } <ide> <del> /** <del> * Test parsing / getting cookies. <del> * <del> * @group deprecated <del> * @return void <del> */ <del> public function testCookie() <del> { <del> $this->deprecated(function () { <del> $headers = [ <del> 'HTTP/1.0 200 Ok', <del> 'Set-Cookie: test=value', <del> 'Set-Cookie: session=123abc', <del> 'Set-Cookie: expiring=soon; Expires=Wed, 09-Jun-2021 10:18:14 GMT; Path=/; HttpOnly; Secure;', <del> ]; <del> $response = new Response($headers, ''); <del> $this->assertEquals('value', $response->cookie('test')); <del> $this->assertEquals('123abc', $response->cookie('session')); <del> $this->assertEquals('soon', $response->cookie('expiring')); <del> <del> $result = $response->cookie('expiring', true); <del> $this->assertTrue($result['httponly']); <del> $this->assertTrue($result['secure']); <del> $this->assertEquals( <del> 'Wed, 09-Jun-2021 10:18:14 GMT', <del> $result['expires'] <del> ); <del> $this->assertEquals('/', $result['path']); <del> <del> $result = $response->header('set-cookie'); <del> $this->assertCount(3, $result, 'Should be an array.'); <del> <del> $this->assertTrue(isset($response->cookies)); <del> $this->assertEquals( <del> 'soon', <del> $response->cookies['expiring']['value'] <del> ); <del> }); <del> } <del> <ide> /** <ide> * Test accessing cookies through the PSR7-like methods <ide> * <ide> public function testGetStatusCode() <ide> $this->assertTrue(isset($response->code)); <ide> } <ide> <del> /** <del> * Test statusCode() <del> * <del> * @group deprecated <del> * @return void <del> */ <del> public function testStatusCode() <del> { <del> $this->deprecated(function () { <del> $headers = [ <del> 'HTTP/1.0 404 Not Found', <del> 'Content-Type: text/html' <del> ]; <del> $response = new Response($headers, ''); <del> $this->assertSame(404, $response->statusCode()); <del> $this->assertSame(404, $response->code); <del> $this->assertTrue(isset($response->code)); <del> }); <del> } <del> <ide> /** <ide> * Test reading the encoding out. <ide> * <ide> public function testGetEncoding() <ide> $this->assertEquals('ISO-8859-1', $response->getEncoding()); <ide> } <ide> <del> /** <del> * Test reading the encoding out. <del> * <del> * @group deprecated <del> * @return void <del> */ <del> public function testEncoding() <del> { <del> $this->deprecated(function () { <del> $headers = [ <del> 'HTTP/1.0 200 Ok', <del> ]; <del> $response = new Response($headers, ''); <del> $this->assertNull($response->encoding()); <del> <del> $headers = [ <del> 'HTTP/1.0 200 Ok', <del> 'Content-Type: text/html' <del> ]; <del> $response = new Response($headers, ''); <del> $this->assertNull($response->encoding()); <del> <del> $headers = [ <del> 'HTTP/1.0 200 Ok', <del> 'Content-Type: text/html; charset="UTF-8"' <del> ]; <del> $response = new Response($headers, ''); <del> $this->assertEquals('UTF-8', $response->encoding()); <del> <del> $headers = [ <del> 'HTTP/1.0 200 Ok', <del> "Content-Type: text/html; charset='ISO-8859-1'" <del> ]; <del> $response = new Response($headers, ''); <del> $this->assertEquals('ISO-8859-1', $response->encoding()); <del> }); <del> } <del> <ide> /** <ide> * Test that gzip responses are automatically decompressed. <ide> *
7
Javascript
Javascript
escape backslashes for windows pipe name
a6a3bf6d470dbc2cd167c9d7788181793d0dc8a0
<ide><path>test/common.js <ide> exports.tmpDir = path.join(exports.testDir, 'tmp'); <ide> exports.PORT = 12346; <ide> <ide> if (process.platform == 'win32') { <del> exports.PIPE = '\\.\pipe\libuv-test'; <add> exports.PIPE = '\\\\.\\pipe\\libuv-test'; <ide> } else { <ide> exports.PIPE = exports.tmpDir + '/test.sock'; <ide> }
1
Javascript
Javascript
replace linebreakmode with ellipsizemode
e5e35910095a4933a59554e0f2ecde979b8f8fd5
<ide><path>RNTester/js/TextExample.ios.js <ide> var AdjustingFontSize = React.createClass({ <ide> } <ide> return ( <ide> <View> <del> <Text lineBreakMode="tail" numberOfLines={1} style={{fontSize: 36, marginVertical:6}}> <add> <Text ellipsizeMode="tail" numberOfLines={1} style={{fontSize: 36, marginVertical: 6}}> <ide> Truncated text is baaaaad. <ide> </Text> <ide> <Text numberOfLines={1} adjustsFontSizeToFit={true} style={{fontSize: 40, marginVertical:6}}>
1
Go
Go
add default timeout to pkg/plugins/client
0699b00d26a60f4a8447572b34c4aad1ce73d2e1
<ide><path>pkg/plugins/client.go <ide> import ( <ide> ) <ide> <ide> const ( <del> defaultTimeOut = 30 <add> defaultTimeOut = 30 <add> defaultHTTPTimeOut = 32 * time.Second <ide> ) <ide> <ide> // NewClient creates a new plugin client (http). <ide> func NewClient(addr string, tlsConfig *tlsconfig.Options) (*Client, error) { <ide> func NewClientWithTransport(tr transport.Transport) *Client { <ide> return &Client{ <ide> http: &http.Client{ <add> Timeout: defaultHTTPTimeOut, <ide> Transport: tr, <ide> }, <ide> requestFactory: tr, <ide><path>pkg/plugins/client_test.go <ide> import ( <ide> "net/http/httptest" <ide> "net/url" <ide> "reflect" <add> "strings" <ide> "testing" <ide> "time" <ide> <ide> func teardownRemotePluginServer() { <ide> } <ide> } <ide> <add>func TestHttpTimeout(t *testing.T) { <add> addr := setupRemotePluginServer() <add> defer teardownRemotePluginServer() <add> stop := false // we need this variable to stop the http server <add> mux.HandleFunc("/hang", func(w http.ResponseWriter, r *http.Request) { <add> for { <add> if stop { <add> break <add> } <add> time.Sleep(5 * time.Second) <add> } <add> }) <add> c, _ := NewClient(addr, &tlsconfig.Options{InsecureSkipVerify: true}) <add> _, err := c.callWithRetry("hang", nil, false) <add> stop = true <add> if err == nil || !strings.Contains(err.Error(), "request canceled") { <add> t.Fatalf("The request should be canceled %v", err) <add> } <add>} <add> <ide> func TestFailedConnection(t *testing.T) { <ide> c, _ := NewClient("tcp://127.0.0.1:1", &tlsconfig.Options{InsecureSkipVerify: true}) <ide> _, err := c.callWithRetry("Service.Method", nil, false)
2
PHP
PHP
exclude nulls clauses in schema reflection
2005e1d213eb8d439c670a8858bce17f2448543f
<ide><path>src/Database/Schema/PostgresSchema.php <ide> public function convertIndexDescription(Table $table, $row) <ide> if ($row['indisunique'] && $type === Table::INDEX_INDEX) { <ide> $type = Table::CONSTRAINT_UNIQUE; <ide> } <del> preg_match('/\(([^\)]+)\)/', $row['statement'], $matches); <add> preg_match('/\(([^\)]+?)\s*(?:ASC|DESC)?(?:NULLS FIRST|LAST)?\)/', $row['statement'], $matches); <ide> $columns = $this->_convertColumnList($matches[1]); <ide> if ($type === Table::CONSTRAINT_PRIMARY || $type === Table::CONSTRAINT_UNIQUE) { <ide> $table->addConstraint($name, [ <ide><path>tests/TestCase/Database/Schema/PostgresSchemaTest.php <ide> public function testDescribeTableIndexes() <ide> $this->assertEquals($expected, $result->index('author_idx')); <ide> } <ide> <add> /** <add> * Test describing a table with indexes with nulls first <add> * <add> * @return void <add> */ <add> public function testDescribeTableIndexesNullsFirst() <add> { <add> $this->_needsConnection(); <add> $connection = ConnectionManager::get('test'); <add> $connection->execute('DROP TABLE IF EXISTS schema_index'); <add> <add> $table = <<<SQL <add>CREATE TABLE schema_index ( <add> id serial NOT NULL, <add> user_id integer NOT NULL, <add> group_id integer NOT NULL, <add> grade double precision <add>) <add>WITH ( <add> OIDS=FALSE <add>) <add>SQL; <add> $connection->execute($table); <add> <add> $index = <<<SQL <add>CREATE INDEX schema_index_nulls <add> ON schema_index <add> USING btree <add> (group_id, grade DESC NULLS FIRST); <add>SQL; <add> $connection->execute($index); <add> $schema = new SchemaCollection($connection); <add> <add> $result = $schema->describe('schema_index'); <add> $this->assertCount(1, $result->indexes()); <add> $expected = [ <add> 'type' => 'index', <add> 'columns' => ['group_id', 'grade'], <add> 'length' => [] <add> ]; <add> $this->assertEquals($expected, $result->index('schema_index_nulls')); <add> $connection->execute('DROP TABLE schema_index'); <add> } <add> <ide> /** <ide> * Column provider for creating column sql <ide> *
2
Go
Go
remove workaround for nano server tp5
250193387c98a4ad69a6591d5fe5a39c1409ffba
<ide><path>cmd/dockerd/docker_windows.go <ide> package main <ide> <ide> import ( <del> "sync/atomic" <del> <ide> _ "github.com/docker/docker/autogen/winresources/dockerd" <ide> ) <del> <del>//go:cgo_import_dynamic main.dummy CommandLineToArgvW%2 "shell32.dll" <del> <del>var dummy uintptr <del> <del>func init() { <del> // Ensure that this import is not removed by the linker. This is used to <del> // ensure that shell32.dll is loaded by the system loader, preventing <del> // go#15286 from triggering on Nano Server TP5. <del> atomic.LoadUintptr(&dummy) <del>}
1
Python
Python
fix lines too long
e1c3c19a68f08d78cfe79eba6dfde1352d2ff29b
<ide><path>celery/fields.py <ide> class PickledObjectField(models.Field): <ide> <ide> def to_python(self, value): <ide> if isinstance(value, PickledObject): <del> # If the value is a definite pickle; and an error is raised in de-pickling <del> # it should be allowed to propogate. <add> # If the value is a definite pickle; and an error is <add> # raised in de-pickling it should be allowed to propogate. <ide> return pickle.loads(str(value)) <ide> else: <ide> try: <ide> def get_internal_type(self): <ide> def get_db_prep_lookup(self, lookup_type, value): <ide> if lookup_type == 'exact': <ide> value = self.get_db_prep_save(value) <del> return super(PickledObjectField, self).get_db_prep_lookup(lookup_type, value) <add> return super(PickledObjectField, self).get_db_prep_lookup( <add> lookup_type, value) <ide> elif lookup_type == 'in': <ide> value = [self.get_db_prep_save(v) for v in value] <del> return super(PickledObjectField, self).get_db_prep_lookup(lookup_type, value) <add> return super(PickledObjectField, self).get_db_prep_lookup( <add> lookup_type, value) <ide> else: <ide> raise TypeError('Lookup type %s is not supported.' % lookup_type)
1
Javascript
Javascript
use indexof instead of startswith
9fb8b93ed919fa8631a4a7f38dfda5a308f54d91
<ide><path>lib/head.js <ide> function unique () { <ide> const metaCategories = {} <ide> <ide> return (h) => { <del> if (h.key && h.key.startsWith('.$')) { <add> if (h.key && h.key.indexOf('.$') === 0) { <ide> if (keys.has(h.key)) return false <ide> keys.add(h.key) <ide> }
1
Python
Python
move collection trainable variables outside loop
a009f4fb9d2fc4949e32192a944688925ef78659
<ide><path>official/bert/common_flags.py <ide> def define_common_bert_flags(): <ide> flags.DEFINE_boolean( <ide> 'run_eagerly', False, <ide> 'Run the model op by op without building a model function.') <add> flags.DEFINE_boolean( <add> 'scale_loss', False, <add> 'Whether to divide the loss by number of replica inside the per-replica ' <add> 'loss function.') <ide> <ide> # Adds flags for mixed precision training. <ide> flags_core.define_performance( <ide><path>official/bert/model_training_utils.py <ide> def run_customized_training_loop( <ide> else: <ide> train_summary_writer = None <ide> <add> # De-dupes variables due to keras tracking issues. <add> training_vars = list({id(v): v for v in model.trainable_variables <add> }.values()) <add> <ide> def _replicated_step(inputs): <ide> """Replicated training step.""" <ide> <ide> def _replicated_step(inputs): <ide> if use_float16: <ide> scaled_loss = optimizer.get_scaled_loss(loss) <ide> <del> # De-dupes variables due to keras tracking issues. <del> tvars = list({id(v): v for v in model.trainable_variables}.values()) <ide> if use_float16: <del> scaled_grads = tape.gradient(scaled_loss, tvars) <add> scaled_grads = tape.gradient(scaled_loss, training_vars) <ide> grads = optimizer.get_unscaled_gradients(scaled_grads) <ide> else: <del> grads = tape.gradient(loss, tvars) <del> optimizer.apply_gradients(zip(grads, tvars)) <add> grads = tape.gradient(loss, training_vars) <add> optimizer.apply_gradients(zip(grads, training_vars)) <ide> # For reporting, the metric takes the mean of losses. <ide> train_loss_metric.update_state(loss) <ide> for metric in train_metrics: <ide><path>official/bert/run_classifier.py <ide> FLAGS = flags.FLAGS <ide> <ide> <del>def get_loss_fn(num_classes, loss_scale=1.0): <add>def get_loss_fn(num_classes, loss_factor=1.0): <ide> """Gets the classification loss function.""" <ide> <ide> def classification_loss_fn(labels, logits): <ide> def classification_loss_fn(labels, logits): <ide> per_example_loss = -tf.reduce_sum( <ide> tf.cast(one_hot_labels, dtype=tf.float32) * log_probs, axis=-1) <ide> loss = tf.reduce_mean(per_example_loss) <del> loss *= loss_scale <add> loss *= loss_factor <ide> return loss <ide> <ide> return classification_loss_fn <ide> def _get_classifier_model(): <ide> initial_lr, steps_per_epoch * epochs, warmup_steps) <ide> return classifier_model, core_model <ide> <del> loss_fn = get_loss_fn(num_classes, loss_scale=1.0) <add> loss_fn = get_loss_fn( <add> num_classes, <add> loss_factor=1.0 / <add> strategy.num_replicas_in_sync if FLAGS.scale_loss else 1.0) <ide> <ide> # Defines evaluation metrics function, which will create metrics in the <ide> # correct device and strategy scope. <ide><path>official/bert/run_pretraining.py <ide> def _dataset_fn(ctx=None): <ide> return _dataset_fn if use_dataset_fn else _dataset_fn() <ide> <ide> <del>def get_loss_fn(loss_scale=1.0): <add>def get_loss_fn(loss_factor=1.0): <ide> """Returns loss function for BERT pretraining.""" <ide> <ide> def _bert_pretrain_loss_fn(unused_labels, losses, **unused_args): <del> return tf.keras.backend.mean(losses) * loss_scale <add> return tf.keras.backend.mean(losses) * loss_factor <ide> <ide> return _bert_pretrain_loss_fn <ide> <ide> def _get_pretrain_model(): <ide> trained_model = model_training_utils.run_customized_training_loop( <ide> strategy=strategy, <ide> model_fn=_get_pretrain_model, <del> loss_fn=get_loss_fn(), <add> loss_fn=get_loss_fn( <add> loss_factor=1.0 / <add> strategy.num_replicas_in_sync if FLAGS.scale_loss else 1.0), <ide> model_dir=model_dir, <ide> train_input_fn=train_input_fn, <ide> steps_per_epoch=steps_per_epoch, <ide><path>official/bert/run_squad.py <ide> def _get_squad_model(): <ide> # 1/num_replicas_in_sync. It could be an accident. So, in order to use <ide> # the same hyper parameter, we do the same thing here by keeping each <ide> # replica loss as it is. <del> loss_fn = get_loss_fn(loss_factor=1.0) <add> loss_fn = get_loss_fn( <add> loss_factor=1.0 / <add> strategy.num_replicas_in_sync if FLAGS.scale_loss else 1.0) <ide> use_remote_tpu = (FLAGS.strategy_type == 'tpu' and FLAGS.tpu) <ide> <ide> model_training_utils.run_customized_training_loop(
5
Javascript
Javascript
fix missing types in xhrexample
95050e46580ff0519adcc3d1e5805405bbd750a2
<ide><path>Examples/UIExplorer/XHRExample.js <ide> var PAGE_SIZE = 20; <ide> <ide> class FormUploader extends React.Component { <ide> <add> _isMounted: boolean; <add> _fetchRandomPhoto: () => void; <add> _addTextParam: () => void; <add> _upload: () => void; <add> <ide> constructor(props) { <ide> super(props); <ide> this.state = {
1
PHP
PHP
add support for setting attachment’s footer icon
2f7cec4653ba2345561916e3d289543630e551bc
<ide><path>src/Illuminate/Notifications/Channels/SlackWebhookChannel.php <ide> protected function attachments(SlackMessage $message) <ide> 'fields' => $this->fields($attachment), <ide> 'mrkdwn_in' => $attachment->markdown, <ide> 'footer' => $attachment->footer, <add> 'footer_icon' => $attachment->footerIcon, <ide> 'ts' => $attachment->timestamp <ide> ]); <ide> })->all(); <ide><path>src/Illuminate/Notifications/Messages/SlackAttachment.php <ide> class SlackAttachment <ide> */ <ide> public $footer; <ide> <add> /** <add> * The attachment's footer icon. <add> * <add> * @var string <add> */ <add> public $footerIcon; <add> <ide> /** <ide> * The attachment's timestamp. <ide> * <ide> public function footer($footer) <ide> return $this; <ide> } <ide> <add> /** <add> * Set the footer icon. <add> * <add> * @param string $icon <add> * @return $this <add> */ <add> public function footerIcon($icon) <add> { <add> $this->footerIcon = $icon; <add> return $this; <add> } <add> <ide> /** <ide> * Set the timestamp. <ide> *
2
PHP
PHP
update typehints for testsuite/
96d7367210c08132b96891139f89aecf751f1864
<ide><path>src/TestSuite/ConsoleIntegrationTestTrait.php <ide> public function exec(string $command, array $input = []): void <ide> * @after <ide> * @return void <ide> */ <del> public function cleanupConsoleTrait() <add> public function cleanupConsoleTrait(): void <ide> { <ide> $this->_exitCode = null; <ide> $this->_out = null; <ide><path>src/TestSuite/Constraint/Response/BodyContains.php <ide> */ <ide> namespace Cake\TestSuite\Constraint\Response; <ide> <del>use Cake\Http\Response; <add>use Psr\Http\Message\ResponseInterface; <ide> <ide> /** <ide> * BodyContains <ide> class BodyContains extends ResponseBase <ide> /** <ide> * Constructor. <ide> * <del> * @param \Cake\Http\Response $response A response instance. <add> * @param \Psr\Http\Message\ResponseInterface $response A response instance. <ide> * @param bool $ignoreCase Ignore case <ide> */ <del> public function __construct(Response $response, bool $ignoreCase = false) <add> public function __construct(ResponseInterface $response, bool $ignoreCase = false) <ide> { <ide> parent::__construct($response); <ide> <ide><path>src/TestSuite/Constraint/Response/ContentType.php <ide> */ <ide> class ContentType extends ResponseBase <ide> { <add> /** <add> * @var \Cake\Http\Response <add> */ <add> protected $response; <add> <ide> /** <ide> * Checks assertion <ide> * <ide><path>src/TestSuite/Constraint/Response/CookieEncryptedEquals.php <ide> class CookieEncryptedEquals extends CookieEquals <ide> { <ide> use CookieCryptTrait; <ide> <add> /** <add> * @var \Cake\Http\Response <add> */ <add> protected $response; <add> <ide> /** <ide> * @var string <ide> */ <ide> class CookieEncryptedEquals extends CookieEquals <ide> /** <ide> * Constructor. <ide> * <del> * @param \Cake\Http\Response $response A response instance. <add> * @param \Cake\Http\Response|null $response A response instance. <ide> * @param string $cookieName Cookie name <ide> * @param string $mode Mode <ide> * @param string $key Key <ide> */ <del> public function __construct(Response $response, string $cookieName, string $mode, string $key) <add> public function __construct(?Response $response, string $cookieName, string $mode, string $key) <ide> { <ide> parent::__construct($response, $cookieName); <ide> <ide><path>src/TestSuite/Constraint/Response/CookieEquals.php <ide> */ <ide> class CookieEquals extends ResponseBase <ide> { <add> /** <add> * @var \Cake\Http\Response <add> */ <add> protected $response; <add> <ide> /** <ide> * @var string <ide> */ <ide> class CookieEquals extends ResponseBase <ide> /** <ide> * Constructor. <ide> * <del> * @param \Cake\Http\Response $response A response instance. <add> * @param \Cake\Http\Response|null $response A response instance. <ide> * @param string $cookieName Cookie name <ide> */ <del> public function __construct(Response $response, string $cookieName) <add> public function __construct(?Response $response, string $cookieName) <ide> { <ide> parent::__construct($response); <ide> <ide><path>src/TestSuite/Constraint/Response/CookieSet.php <ide> */ <ide> class CookieSet extends ResponseBase <ide> { <add> /** <add> * @var \Cake\Http\Response <add> */ <add> protected $response; <add> <ide> /** <ide> * Checks assertion <ide> * <ide><path>src/TestSuite/Constraint/Response/FileSent.php <ide> */ <ide> class FileSent extends ResponseBase <ide> { <add> /** <add> * @var \Cake\Http\Response <add> */ <add> protected $response; <add> <ide> /** <ide> * Checks assertion <ide> * <ide><path>src/TestSuite/Constraint/Response/FileSentAs.php <ide> */ <ide> class FileSentAs extends ResponseBase <ide> { <add> /** <add> * @var \Cake\Http\Response <add> */ <add> protected $response; <add> <ide> /** <ide> * Checks assertion <ide> * <ide><path>src/TestSuite/Constraint/Response/HeaderEquals.php <ide> */ <ide> namespace Cake\TestSuite\Constraint\Response; <ide> <add>use Psr\Http\Message\ResponseInterface; <add> <ide> /** <ide> * HeaderEquals <ide> * <ide> class HeaderEquals extends ResponseBase <ide> /** <ide> * Constructor. <ide> * <del> * @param \Cake\Http\Response $response A response instance. <add> * @param \Psr\Http\Message\ResponseInterface $response A response instance. <ide> * @param string $headerName Header name <ide> */ <del> public function __construct($response, $headerName) <add> public function __construct(ResponseInterface $response, string $headerName) <ide> { <ide> parent::__construct($response); <ide> <ide><path>src/TestSuite/Constraint/Response/HeaderSet.php <ide> */ <ide> namespace Cake\TestSuite\Constraint\Response; <ide> <add>use Psr\Http\Message\ResponseInterface; <add> <ide> /** <ide> * HeaderSet <ide> * <ide> class HeaderSet extends ResponseBase <ide> /** <ide> * Constructor. <ide> * <del> * @param \Cake\Http\Response $response A response instance. <add> * @param \Psr\Http\Message\ResponseInterface|null $response A response instance. <ide> * @param string $headerName Header name <ide> */ <del> public function __construct($response, $headerName) <add> public function __construct(?ResponseInterface $response, string $headerName) <ide> { <ide> parent::__construct($response); <ide> <ide><path>src/TestSuite/Constraint/Response/ResponseBase.php <ide> */ <ide> namespace Cake\TestSuite\Constraint\Response; <ide> <del>use Cake\Http\Response; <ide> use PHPUnit\Framework\AssertionFailedError; <ide> use PHPUnit\Framework\Constraint\Constraint; <add>use Psr\Http\Message\ResponseInterface; <ide> <ide> /** <ide> * Base constraint for response constraints <ide> abstract class ResponseBase extends Constraint <ide> { <ide> /** <del> * @var \Cake\Http\Response <add> * @var \Psr\Http\Message\ResponseInterface <ide> */ <ide> protected $response; <ide> <ide> /** <ide> * Constructor <ide> * <del> * @param \Cake\Http\Response|null $response Response <add> * @param \Psr\Http\Message\ResponseInterface|null $response Response <ide> */ <del> public function __construct(?Response $response) <add> public function __construct(?ResponseInterface $response) <ide> { <ide> if (!$response) { <ide> throw new AssertionFailedError('No response set, cannot assert content.'); <ide><path>src/TestSuite/EmailTrait.php <ide> trait EmailTrait <ide> * @before <ide> * @return void <ide> */ <del> public function setupTransports() <add> public function setupTransports(): void <ide> { <ide> TestEmailTransport::replaceAllTransports(); <ide> } <ide> public function setupTransports() <ide> * @after <ide> * @return void <ide> */ <del> public function cleanupEmailTrait() <add> public function cleanupEmailTrait(): void <ide> { <ide> TestEmailTransport::clearMessages(); <ide> } <ide><path>src/TestSuite/IntegrationTestCase.php <ide> abstract class IntegrationTestCase extends TestCase <ide> * @param bool $enable Unused. <ide> * @return void <ide> */ <del> public function useHttpServer($enable) <add> public function useHttpServer(bool $enable): void <ide> { <ide> } <ide> } <ide><path>src/TestSuite/IntegrationTestTrait.php <ide> trait IntegrationTestTrait <ide> * @before <ide> * @return void <ide> */ <del> public function setupServer() <add> public function setupServer(): void <ide> { <ide> $namespace = Configure::read('App.namespace'); <ide> } <ide> public function setupServer() <ide> * @after <ide> * @return void <ide> */ <del> public function cleanup() <add> public function cleanup(): void <ide> { <ide> $this->_request = []; <ide> $this->_session = []; <ide> public function assertRedirectContains(string $url, string $message = ''): void <ide> * @param string $message The failure message that will be appended to the generated message. <ide> * @return void <ide> */ <del> public function assertRedirectNotContains($url, $message = '') <add> public function assertRedirectNotContains(string $url, string $message = ''): void <ide> { <ide> $verboseMessage = $this->extractVerboseMessage($message); <ide> $this->assertThat(null, new HeaderSet($this->_response, 'Location'), $verboseMessage); <ide> public function assertHeaderContains(string $header, string $content, string $me <ide> * @param string $message The failure message that will be appended to the generated message. <ide> * @return void <ide> */ <del> public function assertHeaderNotContains($header, $content, $message = '') <add> public function assertHeaderNotContains(string $header, string $content, string $message = ''): void <ide> { <ide> $verboseMessage = $this->extractVerboseMessage($message); <ide> $this->assertThat(null, new HeaderSet($this->_response, $header), $verboseMessage); <ide> protected function extractVerboseMessage(string $message): string <ide> * @param \Exception $exception Exception to extract <ide> * @return string <ide> */ <del> protected function extractExceptionMessage(Exception $exception) <add> protected function extractExceptionMessage(Exception $exception): string <ide> { <ide> return PHP_EOL . <ide> sprintf('Possibly related to %s: "%s" ', get_class($exception), $exception->getMessage()) .
14
Text
Text
add hasintl to test/common/readme.md
282b1edbe753eaa3219e934dcc5a473a2e53e25f
<ide><path>test/common/README.md <ide> Checks for 'openssl'. <ide> <ide> Checks `hasCrypto` and `crypto` with fips. <ide> <add>### hasIntl <add>* return [&lt;Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) <add> <add>Checks if [internationalization] is supported. <add> <ide> ### hasIPv6 <ide> * return [&lt;Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) <ide> <ide> implementation with tests from <ide> [W3C Web Platform Tests](https://github.com/w3c/web-platform-tests). <ide> <ide> [MDN-Function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Normal_objects_and_functions <add>[internationalization]: https://github.com/nodejs/node/wiki/Intl
1
PHP
PHP
show error if specified plugin is not loaded
7a973ce5d2873b4a7c9b54777126b709d2e0440b
<ide><path>src/Shell/PluginAssetsShell.php <ide> protected function _list($name = null) { <ide> if ($name === null) { <ide> $pluginsList = Plugin::loaded(); <ide> } else { <add> if (!Plugin::loaded($name)) { <add> $this->err(sprintf('Plugin %s is not loaded.', $name)); <add> return []; <add> } <ide> $pluginsList = [$name]; <ide> } <ide>
1
Mixed
Ruby
fix dirty tracking after rollback
63ff495bdf90e0ab20114a49db5cffe3cb9ef2fd
<ide><path>activerecord/CHANGELOG.md <add>* Fix dirty tracking after rollback. <add> <add> Fixes #15018, #30167, #33868. <add> <add> *Ryuta Kamizono* <add> <ide> * Fix dirty tracking for `touch` to track saved changes. <ide> <ide> Fixes #33429. <ide><path>activerecord/lib/active_record/attribute_methods/before_type_cast.rb <ide> module BeforeTypeCast <ide> # task.read_attribute_before_type_cast('completed_on') # => "2012-10-21" <ide> # task.read_attribute_before_type_cast(:completed_on) # => "2012-10-21" <ide> def read_attribute_before_type_cast(attr_name) <add> sync_with_transaction_state <ide> @attributes[attr_name.to_s].value_before_type_cast <ide> end <ide> <ide> def read_attribute_before_type_cast(attr_name) <ide> # task.attributes_before_type_cast <ide> # # => {"id"=>nil, "title"=>nil, "is_done"=>true, "completed_on"=>"2012-10-21", "created_at"=>nil, "updated_at"=>nil} <ide> def attributes_before_type_cast <add> sync_with_transaction_state <ide> @attributes.values_before_type_cast <ide> end <ide> <ide> def attribute_before_type_cast(attribute_name) <ide> end <ide> <ide> def attribute_came_from_user?(attribute_name) <add> sync_with_transaction_state <ide> @attributes[attribute_name].came_from_user? <ide> end <ide> end <ide><path>activerecord/lib/active_record/attribute_methods/dirty.rb <ide> def attributes_in_database <ide> end <ide> <ide> private <add> def mutations_from_database <add> sync_with_transaction_state <add> super <add> end <add> <add> def mutations_before_last_save <add> sync_with_transaction_state <add> super <add> end <add> <ide> def write_attribute_without_type_cast(attr_name, value) <ide> name = attr_name.to_s <ide> if self.class.attribute_alias?(name) <ide><path>activerecord/lib/active_record/attribute_methods/primary_key.rb <ide> def to_key <ide> <ide> # Returns the primary key column's value. <ide> def id <del> sync_with_transaction_state <ide> primary_key = self.class.primary_key <ide> _read_attribute(primary_key) if primary_key <ide> end <ide> <ide> # Sets the primary key column's value. <ide> def id=(value) <del> sync_with_transaction_state <ide> primary_key = self.class.primary_key <ide> _write_attribute(primary_key, value) if primary_key <ide> end <ide> <ide> # Queries the primary key column's value. <ide> def id? <del> sync_with_transaction_state <ide> query_attribute(self.class.primary_key) <ide> end <ide> <ide> # Returns the primary key column's value before type cast. <ide> def id_before_type_cast <del> sync_with_transaction_state <ide> read_attribute_before_type_cast(self.class.primary_key) <ide> end <ide> <ide> # Returns the primary key column's previous value. <ide> def id_was <del> sync_with_transaction_state <ide> attribute_was(self.class.primary_key) <ide> end <ide> <ide> # Returns the primary key column's value from the database. <ide> def id_in_database <del> sync_with_transaction_state <ide> attribute_in_database(self.class.primary_key) <ide> end <ide> <ide><path>activerecord/lib/active_record/attribute_methods/read.rb <ide> module ClassMethods # :nodoc: <ide> private <ide> <ide> def define_method_attribute(name) <del> sync_with_transaction_state = "sync_with_transaction_state" if name == primary_key <del> <ide> ActiveModel::AttributeMethods::AttrNames.define_attribute_accessor_method( <ide> generated_attribute_methods, name <ide> ) do |temp_method_name, attr_name_expr| <ide> generated_attribute_methods.module_eval <<-RUBY, __FILE__, __LINE__ + 1 <ide> def #{temp_method_name} <del> #{sync_with_transaction_state} <ide> name = #{attr_name_expr} <ide> _read_attribute(name) { |n| missing_attribute(n, caller) } <ide> end <ide> def read_attribute(attr_name, &block) <ide> <ide> primary_key = self.class.primary_key <ide> name = primary_key if name == "id" && primary_key <del> sync_with_transaction_state if name == primary_key <ide> _read_attribute(name, &block) <ide> end <ide> <ide> # This method exists to avoid the expensive primary_key check internally, without <ide> # breaking compatibility with the read_attribute API <ide> def _read_attribute(attr_name, &block) # :nodoc <add> sync_with_transaction_state <ide> @attributes.fetch_value(attr_name.to_s, &block) <ide> end <ide> <ide><path>activerecord/lib/active_record/attribute_methods/write.rb <ide> module ClassMethods # :nodoc: <ide> private <ide> <ide> def define_method_attribute=(name) <del> sync_with_transaction_state = "sync_with_transaction_state" if name == primary_key <del> <ide> ActiveModel::AttributeMethods::AttrNames.define_attribute_accessor_method( <ide> generated_attribute_methods, name, writer: true, <ide> ) do |temp_method_name, attr_name_expr| <ide> generated_attribute_methods.module_eval <<-RUBY, __FILE__, __LINE__ + 1 <ide> def #{temp_method_name}(value) <ide> name = #{attr_name_expr} <del> #{sync_with_transaction_state} <ide> _write_attribute(name, value) <ide> end <ide> RUBY <ide> def write_attribute(attr_name, value) <ide> <ide> primary_key = self.class.primary_key <ide> name = primary_key if name == "id" && primary_key <del> sync_with_transaction_state if name == primary_key <ide> _write_attribute(name, value) <ide> end <ide> <ide> # This method exists to avoid the expensive primary_key check internally, without <ide> # breaking compatibility with the write_attribute API <ide> def _write_attribute(attr_name, value) # :nodoc: <add> sync_with_transaction_state <ide> @attributes.write_from_user(attr_name.to_s, value) <ide> value <ide> end <ide> <ide> private <ide> def write_attribute_without_type_cast(attr_name, value) <del> name = attr_name.to_s <del> @attributes.write_cast_value(name, value) <add> sync_with_transaction_state <add> @attributes.write_cast_value(attr_name.to_s, value) <ide> value <ide> end <ide> <ide><path>activerecord/lib/active_record/core.rb <ide> def init_internals <ide> def initialize_internals_callback <ide> end <ide> <del> def thaw <del> if @attributes.frozen? <del> @attributes = @attributes.dup <del> end <del> end <del> <ide> def custom_inspect_method_defined? <ide> self.class.instance_method(:inspect).owner != ActiveRecord::Base.instance_method(:inspect).owner <ide> end <ide><path>activerecord/lib/active_record/transactions.rb <ide> def remember_transaction_record_state <ide> id: id, <ide> new_record: @new_record, <ide> destroyed: @destroyed, <add> attributes: @attributes, <ide> frozen?: frozen?, <ide> ) <ide> @_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) + 1 <ide> def restore_transaction_record_state(force_restore_state = false) <ide> transaction_level = (@_start_transaction_state[:level] || 0) - 1 <ide> if transaction_level < 1 || force_restore_state <ide> restore_state = @_start_transaction_state <del> thaw <ide> @new_record = restore_state[:new_record] <ide> @destroyed = restore_state[:destroyed] <add> @attributes = restore_state[:attributes].map do |attr| <add> value = @attributes.fetch_value(attr.name) <add> attr = attr.with_value_from_user(value) if attr.value != value <add> attr <add> end <add> @mutations_from_database = nil <add> @mutations_before_last_save = nil <ide> pk = self.class.primary_key <del> if pk && _read_attribute(pk) != restore_state[:id] <del> _write_attribute(pk, restore_state[:id]) <add> if pk && @attributes.fetch_value(pk) != restore_state[:id] <add> @attributes.write_from_user(pk, restore_state[:id]) <ide> end <ide> freeze if restore_state[:frozen?] <ide> end <ide><path>activerecord/test/cases/transactions_test.rb <ide> def setup <ide> @first, @second = Topic.find(1, 2).sort_by(&:id) <ide> end <ide> <add> def test_rollback_dirty_changes <add> topic = topics(:fifth) <add> <add> ActiveRecord::Base.transaction do <add> topic.update(title: "Ruby on Rails") <add> raise ActiveRecord::Rollback <add> end <add> <add> title_change = ["The Fifth Topic of the day", "Ruby on Rails"] <add> assert_equal title_change, topic.changes["title"] <add> end <add> <add> def test_rollback_dirty_changes_multiple_saves <add> topic = topics(:fifth) <add> <add> ActiveRecord::Base.transaction do <add> topic.update(title: "Ruby on Rails") <add> topic.update(title: "Another Title") <add> raise ActiveRecord::Rollback <add> end <add> <add> title_change = ["The Fifth Topic of the day", "Another Title"] <add> assert_equal title_change, topic.changes["title"] <add> end <add> <add> def test_rollback_dirty_changes_then_retry_save <add> topic = topics(:fifth) <add> <add> ActiveRecord::Base.transaction do <add> topic.update(title: "Ruby on Rails") <add> raise ActiveRecord::Rollback <add> end <add> <add> title_change = ["The Fifth Topic of the day", "Ruby on Rails"] <add> assert_equal title_change, topic.changes["title"] <add> <add> assert topic.save <add> <add> assert_equal title_change, topic.saved_changes["title"] <add> assert_equal topic.title, topic.reload.title <add> end <add> <add> def test_rollback_dirty_changes_then_retry_save_on_new_record <add> topic = Topic.new(title: "Ruby on Rails") <add> <add> ActiveRecord::Base.transaction do <add> topic.save <add> raise ActiveRecord::Rollback <add> end <add> <add> title_change = [nil, "Ruby on Rails"] <add> assert_equal title_change, topic.changes["title"] <add> <add> assert topic.save <add> <add> assert_equal title_change, topic.saved_changes["title"] <add> assert_equal topic.title, topic.reload.title <add> end <add> <ide> def test_persisted_in_a_model_with_custom_primary_key_after_failed_save <ide> movie = Movie.create <ide> assert_not_predicate movie, :persisted?
9
Javascript
Javascript
remove keymirror in reactproptypelocations
84084153edbeab515f9955b4c5b955ef95167787
<ide><path>src/addons/link/__tests__/ReactLinkPropTypes-test.js <ide> var emptyFunction = require('emptyFunction'); <ide> var LinkPropTypes = require('ReactLink').PropTypes; <ide> var React = require('React'); <del>var ReactPropTypeLocations = require('ReactPropTypeLocations'); <ide> var ReactPropTypesSecret = require('ReactPropTypesSecret'); <ide> <ide> var invalidMessage = 'Invalid prop `testProp` supplied to `testComponent`.'; <ide> function typeCheckFail(declaration, value, message) { <ide> props, <ide> 'testProp', <ide> 'testComponent', <del> ReactPropTypeLocations.prop, <add> 'prop', <ide> null, <ide> ReactPropTypesSecret <ide> ); <ide> function typeCheckPass(declaration, value) { <ide> props, <ide> 'testProp', <ide> 'testComponent', <del> ReactPropTypeLocations.prop, <add> 'prop', <ide> null, <ide> ReactPropTypesSecret <ide> ); <ide><path>src/isomorphic/classic/class/ReactClass.js <ide> <ide> var ReactComponent = require('ReactComponent'); <ide> var ReactElement = require('ReactElement'); <del>var ReactPropTypeLocations = require('ReactPropTypeLocations'); <ide> var ReactPropTypeLocationNames = require('ReactPropTypeLocationNames'); <ide> var ReactNoopUpdateQueue = require('ReactNoopUpdateQueue'); <ide> <ide> var keyMirror = require('keyMirror'); <ide> var keyOf = require('keyOf'); <ide> var warning = require('warning'); <ide> <add>import type { ReactPropTypeLocations } from 'ReactPropTypeLocations'; <add> <ide> var MIXINS_KEY = keyOf({mixins: null}); <ide> <ide> /** <ide> var RESERVED_SPEC_KEYS = { <ide> validateTypeDef( <ide> Constructor, <ide> childContextTypes, <del> ReactPropTypeLocations.childContext <add> 'childContext' <ide> ); <ide> } <ide> Constructor.childContextTypes = Object.assign( <ide> var RESERVED_SPEC_KEYS = { <ide> validateTypeDef( <ide> Constructor, <ide> contextTypes, <del> ReactPropTypeLocations.context <add> 'context' <ide> ); <ide> } <ide> Constructor.contextTypes = Object.assign( <ide> var RESERVED_SPEC_KEYS = { <ide> validateTypeDef( <ide> Constructor, <ide> propTypes, <del> ReactPropTypeLocations.prop <add> 'prop' <ide> ); <ide> } <ide> Constructor.propTypes = Object.assign( <ide> var RESERVED_SPEC_KEYS = { <ide> autobind: function() {}, // noop <ide> }; <ide> <del>function validateTypeDef(Constructor, typeDef, location) { <add>function validateTypeDef( <add> Constructor, <add> typeDef, <add> location: ReactPropTypeLocations, <add>) { <ide> for (var propName in typeDef) { <ide> if (typeDef.hasOwnProperty(propName)) { <ide> // use a warning instead of an invariant so components <ide><path>src/isomorphic/classic/element/ReactElementValidator.js <ide> var ReactCurrentOwner = require('ReactCurrentOwner'); <ide> var ReactComponentTreeHook = require('ReactComponentTreeHook'); <ide> var ReactElement = require('ReactElement'); <del>var ReactPropTypeLocations = require('ReactPropTypeLocations'); <ide> <ide> var checkReactTypeSpec = require('checkReactTypeSpec'); <ide> <ide> function validatePropTypes(element) { <ide> checkReactTypeSpec( <ide> componentClass.propTypes, <ide> element.props, <del> ReactPropTypeLocations.prop, <add> 'prop', <ide> name, <ide> element, <ide> null <ide><path>src/isomorphic/classic/types/__tests__/ReactPropTypes-test.js <ide> var PropTypes; <ide> var React; <ide> var ReactFragment; <del>var ReactPropTypeLocations; <ide> var ReactTestUtils; <ide> var ReactPropTypesSecret; <ide> <ide> function typeCheckFail(declaration, value, message) { <ide> props, <ide> 'testProp', <ide> 'testComponent', <del> ReactPropTypeLocations.prop, <add> 'prop', <ide> null, <ide> ReactPropTypesSecret <ide> ); <ide> function typeCheckFailRequiredValues(declaration) { <ide> props1, <ide> 'testProp', <ide> 'testComponent', <del> ReactPropTypeLocations.prop, <add> 'prop', <ide> null, <ide> ReactPropTypesSecret <ide> ); <ide> function typeCheckFailRequiredValues(declaration) { <ide> props2, <ide> 'testProp', <ide> 'testComponent', <del> ReactPropTypeLocations.prop, <add> 'prop', <ide> null, <ide> ReactPropTypesSecret <ide> ); <ide> function typeCheckFailRequiredValues(declaration) { <ide> props3, <ide> 'testProp', <ide> 'testComponent', <del> ReactPropTypeLocations.prop, <add> 'prop', <ide> null, <ide> ReactPropTypesSecret <ide> ); <ide> function typeCheckPass(declaration, value) { <ide> props, <ide> 'testProp', <ide> 'testComponent', <del> ReactPropTypeLocations.prop, <add> 'prop', <ide> null, <ide> ReactPropTypesSecret <ide> ); <ide> describe('ReactPropTypes', function() { <ide> PropTypes = require('ReactPropTypes'); <ide> React = require('React'); <ide> ReactFragment = require('ReactFragment'); <del> ReactPropTypeLocations = require('ReactPropTypeLocations'); <ide> ReactTestUtils = require('ReactTestUtils'); <ide> ReactPropTypesSecret = require('ReactPropTypesSecret'); <ide> }); <ide><path>src/renderers/dom/client/wrappers/LinkedValueUtils.js <ide> 'use strict'; <ide> <ide> var React = require('React'); <del>var ReactPropTypeLocations = require('ReactPropTypeLocations'); <ide> var ReactPropTypesSecret = require('ReactPropTypesSecret'); <ide> <ide> var invariant = require('invariant'); <ide> var LinkedValueUtils = { <ide> props, <ide> propName, <ide> tagName, <del> ReactPropTypeLocations.prop, <add> 'prop', <ide> null, <ide> ReactPropTypesSecret <ide> ); <ide><path>src/renderers/shared/stack/reconciler/ReactCompositeComponent.js <ide> var ReactNodeTypes = require('ReactNodeTypes'); <ide> var ReactReconciler = require('ReactReconciler'); <ide> <ide> if (__DEV__) { <del> var ReactPropTypeLocations = require('ReactPropTypeLocations'); <ide> var checkReactTypeSpec = require('checkReactTypeSpec'); <ide> } <ide> <ide> var shallowEqual = require('shallowEqual'); <ide> var shouldUpdateReactComponent = require('shouldUpdateReactComponent'); <ide> var warning = require('warning'); <ide> <add>import type { ReactPropTypeLocations } from 'ReactPropTypeLocations'; <add> <ide> var CompositeTypes = { <ide> ImpureClass: 0, <ide> PureClass: 1, <ide> var ReactCompositeComponentMixin = { <ide> this._checkContextTypes( <ide> Component.contextTypes, <ide> maskedContext, <del> ReactPropTypeLocations.context <add> 'context' <ide> ); <ide> } <ide> } <ide> var ReactCompositeComponentMixin = { <ide> this._checkContextTypes( <ide> Component.childContextTypes, <ide> childContext, <del> ReactPropTypeLocations.childContext <add> 'childContext' <ide> ); <ide> } <ide> for (var name in childContext) { <ide> var ReactCompositeComponentMixin = { <ide> * @param {string} location e.g. "prop", "context", "child context" <ide> * @private <ide> */ <del> _checkContextTypes: function(typeSpecs, values, location) { <add> _checkContextTypes: function( <add> typeSpecs, <add> values, <add> location: ReactPropTypeLocations, <add> ) { <ide> if (__DEV__) { <ide> checkReactTypeSpec( <ide> typeSpecs, <ide><path>src/shared/types/ReactPropTypeLocationNames.js <ide> <ide> 'use strict'; <ide> <add>import type { ReactPropTypeLocations } from 'ReactPropTypeLocations'; <add> <add>type NamesType = {[key: ReactPropTypeLocations]: string}; <add> <ide> var ReactPropTypeLocationNames = {}; <ide> <ide> if (__DEV__) { <del> ReactPropTypeLocationNames = { <add> ReactPropTypeLocationNames = ({ <ide> prop: 'prop', <ide> context: 'context', <ide> childContext: 'child context', <del> }; <add> }: NamesType); <ide> } <ide> <ide> module.exports = ReactPropTypeLocationNames; <ide><path>src/shared/types/ReactPropTypeLocations.js <ide> <ide> 'use strict'; <ide> <del>var keyMirror = require('keyMirror'); <del> <del>var ReactPropTypeLocations = keyMirror({ <del> prop: null, <del> context: null, <del> childContext: null, <del>}); <del> <del>module.exports = ReactPropTypeLocations; <add>export type ReactPropTypeLocations = <add> 'prop' | <add> 'context' | <add> 'childContext'; <ide><path>src/shared/types/checkReactTypeSpec.js <ide> var ReactPropTypesSecret = require('ReactPropTypesSecret'); <ide> var invariant = require('invariant'); <ide> var warning = require('warning'); <ide> <add>import type { ReactPropTypeLocations } from 'ReactPropTypeLocations'; <add> <ide> var ReactComponentTreeHook; <ide> <ide> if ( <ide> var loggedTypeFailures = {}; <ide> * @param {?number} debugID The React component instance that is being type-checked <ide> * @private <ide> */ <del>function checkReactTypeSpec(typeSpecs, values, location, componentName, element, debugID) { <add>function checkReactTypeSpec( <add> typeSpecs, <add> values, <add> location: ReactPropTypeLocations, <add> componentName, <add> element, <add> debugID, <add>) { <ide> for (var typeSpecName in typeSpecs) { <ide> if (typeSpecs.hasOwnProperty(typeSpecName)) { <ide> var error;
9
Text
Text
fix cson syntax for keybinding example
63aedb65d95f8950add16a8c06da3cc7e939a33a
<ide><path>docs/customizing-atom.md <ide> built-in keymaps: <ide> '.editor': <ide> 'enter': 'editor:newline' <ide> <del>'body': <del> 'ctrl-b': 'core:move-left' <del> 'ctrl-f': 'core:move-right' <add>'.mini.editor input': <add> 'enter': 'core:confirm' <ide> ``` <ide> <ide> This keymap defines the meaning of `enter` in two different contexts. In a
1
Javascript
Javascript
change forum link in help modal
25cabc0a184dc0f28ef574b454643f944c74a327
<ide><path>client/src/templates/Challenges/components/HelpModal.js <ide> const propTypes = { <ide> isOpen: PropTypes.bool <ide> }; <ide> <del>const RSA = <del> 'https://www.freecodecamp.org/forum/t/how-to-get-help-when-you-are-stuck-coding/19514'; <add>const RSA = 'https://forum.freecodecamp.org/t/19514'; <ide> <ide> export class HelpModal extends Component { <ide> render() {
1
Ruby
Ruby
update the statementcache documentation
8fc7eb5f21e42f1bc484c496a6431c284b9ee805
<ide><path>activerecord/lib/active_record/statement_cache.rb <ide> module ActiveRecord <ide> <ide> # Statement cache is used to cache a single statement in order to avoid creating the AST again. <del> # Initializing the cache is done by passing the statement in the initialization block: <add> # Initializing the cache is done by passing the statement in the create block: <ide> # <del> # cache = ActiveRecord::StatementCache.new do <del> # Book.where(name: "my book").limit(100) <add> # cache = StatementCache.create(Book.connection) do |params| <add> # Book.where(name: "my book").where("author_id > 3") <ide> # end <ide> # <ide> # The cached statement is executed by using the +execute+ method: <ide> # <del> # cache.execute <add> # cache.execute([], Book, Book.connection) <ide> # <ide> # The relation returned by the block is cached, and for each +execute+ call the cached relation gets duped. <ide> # Database is queried when +to_a+ is called on the relation. <add> # <add> # If you want to cache the statement without the values you can use the +bind+ method of the <add> # block parameter. <add> # <add> # cache = StatementCache.create(Book.connection) do |params| <add> # Book.where(name: params.bind) <add> # end <add> # <add> # And pass the bind values as the first argument of +execute+ call. <add> # <add> # cache.execute(["my book"], Book, Book.connection) <ide> class StatementCache # :nodoc: <ide> class Substitute; end # :nodoc: <ide>
1
Ruby
Ruby
fix unintentional method redefinitions
57d926a78a6968b9268f4ec1acde608132a1c920
<ide><path>activestorage/app/models/active_storage/variant.rb <ide> class ActiveStorage::Variant <ide> attr_reader :blob, :variation <ide> delegate :service, to: :blob <del> delegate :content_type, :filename, to: :specification <add> delegate :filename, :content_type, to: :specification <ide> <ide> def initialize(blob, variation_or_variation_key) <ide> @blob, @variation = blob, ActiveStorage::Variation.wrap(variation_or_variation_key) <ide> def specification <ide> end <ide> end <ide> <del> delegate :filename, :content_type, :format, to: :specification <add> delegate :format, to: :specification <ide> <ide> class Specification < OpenStruct; end <ide> end
1
Javascript
Javascript
expand blocked usernames list
f7943d0ad54e28f53e5ac43aa1665d5b3b23898a
<ide><path>api-server/server/utils/constants.js <ide> let blocklist = [ <ide> 'username', <ide> 'wiki', <ide> <add> // reserved paths for localizations <add> 'afrikaans', <add> 'arabic', <add> 'bengali', <add> 'catalan', <add> 'chinese', <add> 'czech', <add> 'danish', <add> 'dutch', <add> 'espanol', <add> 'finnish', <add> 'french', <add> 'german', <add> 'greek', <add> 'hebrew', <add> 'hindi', <add> 'hungarian', <add> 'italian', <add> 'japanese', <add> 'korean', <add> 'norwegian', <add> 'polish', <add> 'portuguese', <add> 'romanian', <add> 'russian', <add> 'serbian', <add> 'spanish', <add> 'swahili', <add> 'swedish', <add> 'turkish', <add> 'ukrainian', <add> 'vietnamese', <add> <ide> // some more names from https://github.com/marteinn/The-Big-Username-Blacklist-JS/blob/master/src/list.js <ide> '.htaccess', <ide> '.htpasswd',
1
Javascript
Javascript
fix incorrect code sample
321685209eb34d3e79a6b3e789b14718beab646d
<ide><path>website/src/react-native/index.js <ide> var React = require('react-native'); <ide> var { NativeModules, Text } = React; <ide> <ide> var Message = React.createClass({ <add> getInitialState() { <add> return { text: 'Goodbye World.' }; <add> }, <add> componentDidMount() { <add> NativeModules.MyCustomModule.processString(this.state.text, (text) => { <add> this.setState({text}); <add> }); <add> }, <ide> render: function() { <del> getInitialState() { <del> return { text: 'Goodbye World.' }; <del> }, <del> componentDidMount() { <del> NativeModules.MyCustomModule.processString(this.state.text, (text) => { <del> this.setState({text}); <del> }); <del> }, <ide> return ( <ide> <Text>{this.state.text}</Text> <ide> ); <del> }, <add> } <ide> });`} <ide> </Prism> <ide> <p>
1
Ruby
Ruby
reset schemamigration after updating
e56c80a172dbb5e1627e1122b6f4b87f5e880dd1
<ide><path>activerecord/test/cases/ar_schema_test.rb <ide> def setup <ide> <ide> def teardown <ide> @connection.drop_table :fruits rescue nil <add> ActiveRecord::SchemaMigration.delete_all rescue nil <ide> end <ide> <ide> def test_schema_define
1
PHP
PHP
use mocks to fix test failures
7818cde98ee6a93f4906f06fbb1ca0ad5239cfcf
<ide><path>lib/Cake/Test/TestCase/Database/ConnectionTest.php <ide> <ide> use Cake\Core\Configure; <ide> use Cake\Database\Connection; <add>use Cake\Model\ConnectionManager; <ide> use Cake\TestSuite\TestCase; <ide> <ide> /** <ide> * Tests Connection class <del> * <del> **/ <add> */ <ide> class ConnectionTest extends TestCase { <ide> <ide> public function setUp() { <ide> parent::setUp(); <del> $this->connection = new Connection(Configure::read('Datasource.test')); <add> $this->connection = ConnectionManager::getDataSource('test'); <ide> } <ide> <ide> public function tearDown() { <ide> public function testLogFunction() { <ide> * @return void <ide> */ <ide> public function testLogBeginRollbackTransaction() { <add> $connection = $this->getMock( <add> '\Cake\Database\Connection', <add> ['connect'], <add> [Configure::read('Datasource.test')] <add> ); <ide> $logger = $this->getMock('\Cake\Database\Log\QueryLogger'); <del> $this->connection->logger($logger); <add> $connection->logger($logger); <ide> $logger->expects($this->at(0))->method('log') <ide> ->with($this->logicalAnd( <ide> $this->isInstanceOf('\Cake\Database\Log\LoggedQuery'), <ide> public function testLogBeginRollbackTransaction() { <ide> $this->isInstanceOf('\Cake\Database\Log\LoggedQuery'), <ide> $this->attributeEqualTo('query', 'ROLLBACK') <ide> )); <del> $this->connection->logQueries(true); <del> $this->connection->begin(); <del> $this->connection->begin(); //This one will not be logged <del> $this->connection->rollback(); <add> $connection->logQueries(true); <add> $connection->begin(); <add> $connection->begin(); //This one will not be logged <add> $connection->rollback(); <ide> } <ide> <ide> /** <ide> public function testLogBeginRollbackTransaction() { <ide> */ <ide> public function testLogCommitTransaction() { <ide> $logger = $this->getMock('\Cake\Database\Log\QueryLogger'); <del> $this->connection->logger($logger); <add> $connection = $this->getMock( <add> '\Cake\Database\Connection', <add> ['connect'], <add> [Configure::read('Datasource.test')] <add> ); <add> $connection->logger($logger); <ide> $logger->expects($this->at(1))->method('log') <ide> ->with($this->logicalAnd( <ide> $this->isInstanceOf('\Cake\Database\Log\LoggedQuery'), <ide> $this->attributeEqualTo('query', 'COMMIT') <ide> )); <del> $this->connection->logQueries(true); <del> $this->connection->begin(); <del> $this->connection->commit(); <add> $connection->logQueries(true); <add> $connection->begin(); <add> $connection->commit(); <ide> } <ide> <ide> } <ide><path>lib/Cake/Test/TestCase/Database/Driver/PostgresTest.php <ide> <ide> /** <ide> * Tests Postgres driver <del> * <ide> */ <ide> class PostgresTest extends \Cake\TestSuite\TestCase { <ide>
2
Python
Python
add support for negative numbers
a6831c898a12e568c2e611d457dd71bd89488ce2
<ide><path>maths/greatest_common_divisor.py <ide> Greatest Common Divisor. <ide> <ide> Wikipedia reference: https://en.wikipedia.org/wiki/Greatest_common_divisor <add> <add>gcd(a, b) = gcd(a, -b) = gcd(-a, b) = gcd(-a, -b) by definition of divisibility <ide> """ <ide> <ide> <del>def greatest_common_divisor(a, b): <add>def greatest_common_divisor(a: int, b: int) -> int: <ide> """ <ide> Calculate Greatest Common Divisor (GCD). <ide> >>> greatest_common_divisor(24, 40) <ide> def greatest_common_divisor(a, b): <ide> 1 <ide> >>> greatest_common_divisor(16, 4) <ide> 4 <add> >>> greatest_common_divisor(-3, 9) <add> 3 <add> >>> greatest_common_divisor(9, -3) <add> 3 <add> >>> greatest_common_divisor(3, -9) <add> 3 <add> >>> greatest_common_divisor(-3, -9) <add> 3 <ide> """ <del> return b if a == 0 else greatest_common_divisor(b % a, a) <del> <del> <del>""" <del>Below method is more memory efficient because it does not use the stack (chunk of <del>memory). While above method is good, uses more memory for huge numbers because of the <del>recursive calls required to calculate the greatest common divisor. <del>""" <add> return abs(b) if a == 0 else greatest_common_divisor(b % a, a) <ide> <ide> <del>def gcd_by_iterative(x, y): <add>def gcd_by_iterative(x: int, y: int) -> int: <ide> """ <add> Below method is more memory efficient because it does not create additional <add> stack frames for recursive functions calls (as done in the above method). <ide> >>> gcd_by_iterative(24, 40) <ide> 8 <ide> >>> greatest_common_divisor(24, 40) == gcd_by_iterative(24, 40) <ide> True <add> >>> gcd_by_iterative(-3, -9) <add> 3 <add> >>> gcd_by_iterative(3, -9) <add> 3 <add> >>> gcd_by_iterative(1, -800) <add> 1 <add> >>> gcd_by_iterative(11, 37) <add> 1 <ide> """ <ide> while y: # --> when y=0 then loop will terminate and return x as final GCD. <ide> x, y = y, x % y <del> return x <add> return abs(x) <ide> <ide> <ide> def main(): <del> """Call Greatest Common Divisor function.""" <add> """ <add> Call Greatest Common Divisor function. <add> """ <ide> try: <ide> nums = input("Enter two integers separated by comma (,): ").split(",") <ide> num_1 = int(nums[0])
1
Javascript
Javascript
remove dead code
d8c0f2d780eab25eeee36249a2d657aa67868605
<ide><path>lib/internal/process.js <ide> function setupChannel() { <ide> // Make sure it's not accidentally inherited by child processes. <ide> delete process.env.NODE_CHANNEL_FD; <ide> <del> const cp = require('child_process'); <del> <del> // Load tcp_wrap to avoid situation where we might immediately receive <del> // a message. <del> // FIXME is this really necessary? <del> process.binding('tcp_wrap'); <del> <del> cp._forkChild(fd); <add> require('child_process')._forkChild(fd); <ide> assert(process.send); <ide> } <ide> }
1
Javascript
Javascript
add helpful error messages for removed plugins
94db1bd21c182dac45b226c304639a70f3e9f3fc
<ide><path>lib/webpack.js <ide> exportPlugins(exports.node = {}, { <ide> exportPlugins(exports.debug = {}, { <ide> "ProfilingPlugin": () => require("./debug/ProfilingPlugin"), <ide> }); <add> <add>const defineMissingPluginError = (pluginName, errorMessage) => { <add> Reflect.defineProperty(exports.optimize, pluginName, { <add> configurable: false, <add> enumerable: true, <add> get() { <add> throw new Error(errorMessage); <add> } <add> }); <add>} <add> <add>defineMissingPluginError( <add> "UglifyJsPlugin", <add> "webpack.optimize.UglifyJsPlugin has been removed, please use config.optimization.minimize instead." <add>) <add> <add>defineMissingPluginError( <add> "CommonsChunkPlugin", <add> "webpack.optimize.CommonsChunkPlugin has been removed, please use config.optimization.splitChunks instead." <add>)
1
Javascript
Javascript
remove route event in componentwillunmount
0e13d8c952bb960837ce5e6553b25331e272370b
<ide><path>test/integration/with-router/components/header-nav.js <ide> class HeaderNav extends React.Component { <ide> <ide> componentWillUnmount () { <ide> Router.onRouteChangeComplete = null <del> Router.events.on('routeChangeComplete', this.handleRouteChangeTopLevelRouter) <add> Router.events.off('routeChangeComplete', this.handleRouteChangeTopLevelRouter) <ide> this.props.router.events.off('routeChangeComplete', this.handleRouteChange) <ide> } <ide>
1
Javascript
Javascript
fix deprecation link for ember.string.fmt
254fdf1514020b19ece60d96305e87f2e00ee4f2
<ide><path>packages/ember-runtime/lib/system/string.js <ide> function fmt(str, formats) { <ide> deprecate( <ide> 'Ember.String.fmt is deprecated, use ES6 template strings instead.', <ide> false, <del> { id: 'ember-string-utils.fmt', until: '3.0.0', url: 'https://babeljs.io/docs/learn-es6/#template-strings' } <add> { id: 'ember-string-utils.fmt', until: '3.0.0', url: 'http://babeljs.io/docs/learn-es2015/#template-strings' } <ide> ); <ide> return _fmt(...arguments); <ide> } <ide> export default { <ide> @param {Array} formats An array of parameters to interpolate into string. <ide> @return {String} formatted string <ide> @public <del> @deprecated Use ES6 template strings instead: https://babeljs.io/docs/learn-es6/#template-strings'); <add> @deprecated Use ES6 template strings instead: http://babeljs.io/docs/learn-es2015/#template-strings <ide> */ <ide> fmt, <ide>
1
Ruby
Ruby
add versioned formulae method
840c97c1cce29cdb7c5e453deb17b2023b35ea42
<ide><path>Library/Homebrew/dev-cmd/audit.rb <ide> def audit_file <ide> problem "#{formula} is versioned but no #{unversioned_name} formula exists" <ide> end <ide> elsif ARGV.build_stable? && formula.stable? && <del> !(versioned_formulae = Dir[formula.path.to_s.gsub(/\.rb$/, "@*.rb")]).empty? <add> !(versioned_formulae = formula.versioned_formulae).empty? <ide> versioned_aliases = formula.aliases.grep(/.@\d/) <del> _, last_alias_version = <del> File.basename(versioned_formulae.sort.reverse.first) <del> .gsub(/\.rb$/, "").split("@") <add> _, last_alias_version = versioned_formulae.map(&:name).last.split("@") <ide> major, minor, = formula.version.to_s.split(".") <ide> alias_name_major = "#{formula.name}@#{major}" <ide> alias_name_major_minor = "#{alias_name_major}.#{minor}" <ide><path>Library/Homebrew/formula.rb <ide> def versioned_formula? <ide> name.include?("@") <ide> end <ide> <add> # Returns any `@`-versioned formulae for an non-`@`-versioned formula. <add> def versioned_formulae <add> return [] if versioned_formula? <add> <add> Pathname.glob(path.to_s.gsub(/\.rb$/, "@*.rb")).map do |path| <add> Formula[path.basename(".rb").to_s] <add> end.sort <add> end <add> <ide> # A named Resource for the currently active {SoftwareSpec}. <ide> # Additional downloads can be defined as {#resource}s. <ide> # {Resource#stage} will create a temporary directory and yield to a block. <ide><path>Library/Homebrew/test/formula_spec.rb <ide> end <ide> end <ide> <add> describe "#versioned_formula?" do <add> let(:f) do <add> formula "foo" do <add> url "foo-1.0" <add> end <add> end <add> <add> let(:f2) do <add> formula "foo@2.0" do <add> url "foo-2.0" <add> end <add> end <add> <add> it "returns true for @-versioned formulae" do <add> expect(f2.versioned_formula?).to be true <add> end <add> <add> it "returns false for non-@-versioned formulae" do <add> expect(f.versioned_formula?).to be false <add> end <add> end <add> <add> describe "#versioned_formulae" do <add> let(:f) do <add> formula "foo" do <add> url "foo-1.0" <add> end <add> end <add> <add> let(:f2) do <add> formula "foo@2.0" do <add> url "foo-2.0" <add> end <add> end <add> <add> it "returns true by default" do <add> FileUtils.touch f.path <add> FileUtils.touch f2.path <add> allow(Formulary).to receive(:load_formula_from_path).with(f2.name, f2.path).and_return(f2) <add> allow(Formulary).to receive(:factory).with(f2.name).and_return(f2) <add> expect(f.versioned_formulae).to eq [f2] <add> end <add> <add> it "returns empty array for non-@-versioned formulae" do <add> FileUtils.touch f.path <add> FileUtils.touch f2.path <add> expect(f2.versioned_formulae).to be_empty <add> end <add> end <add> <ide> example "installed alias with core" do <ide> f = formula do <ide> url "foo-1.0" <ide> def test <ide> expect(f3.runtime_dependencies.map(&:name)).to eq(["foo/bar/f1", "baz/qux/f2"]) <ide> end <ide> <del> it "includes non-declared direct dependencies", :focus do <add> it "includes non-declared direct dependencies" do <ide> formula = Class.new(Testball).new <ide> dependency = formula("dependency") { url "f-1.0" } <ide>
3
Text
Text
add changelog entry for [ci skip]
a1564d470d688eecd5fd01ee771521764cba4b7b
<ide><path>activesupport/CHANGELOG.md <add>* Maintain proleptic gregorian in Time#advance <add> <add> `Time#advance` uses `Time#to_date` and `Date#advance` to calculate a new date. <add> The `Date` object returned by `Time#to_date` is constructed with the assumption <add> that the `Time` object represents a proleptic gregorian date, but it is <add> configured to observe the default julian calendar reform date (2299161j) <add> for purposes of calculating month, date and year: <add> <add> Time.new(1582, 10, 4).to_date.to_s # => "1582-09-24" <add> Time.new(1582, 10, 4).to_date.gregorian.to_s # => "1582-10-04" <add> <add> This patch ensures that when the intermediate `Date` object is advanced <add> to yield a new `Date` object, that the `Time` object for return is contructed <add> with a proleptic gregorian month, date and year. <add> <add> *Riley Lynch* <add> <ide> * MemCacheStore should only accept a Dalli::Client, or create one. <ide> <ide> *arthurnn*
1
Python
Python
remove merge artefact
698fc0d016c3fde05234ef7125ac56343bd343c9
<ide><path>spacy/cli/train.py <ide> def train(cmd, lang, output_dir, train_data, dev_data, n_iter=20, n_sents=0, <ide> <ide> with meta_loc.open('w') as file_: <ide> file_.write(json_dumps(meta)) <del>>>>>>>> origin/develop <ide> util.set_env_log(True) <ide> print_progress(i, losses, scorer.scores) <ide> finally:
1
Ruby
Ruby
remove unused accessor
dd331245ab334b2e3fde162b51c3b8b63f065548
<ide><path>Library/Homebrew/build_options.rb <ide> class BuildOptions <ide> <ide> attr_accessor :args <ide> attr_accessor :universal <del> attr_accessor :cxx11 <ide> attr_reader :options <ide> protected :options <ide> <ide> def universal? <ide> <ide> # True if the user requested to enable C++11 mode. <ide> def cxx11? <del> cxx11 || args.include?('--c++11') && has_option?('c++11') <add> args.include?('--c++11') && has_option?('c++11') <ide> end <ide> <ide> # Request a 32-bit only build.
1
PHP
PHP
remove unused namespaces
4d6a540a2bb2331a2bdb8bdc5ab90122eacd0af9
<ide><path>src/I18n/Formatter/IcuFormatter.php <ide> use Aura\Intl\Exception\CannotFormat; <ide> use Aura\Intl\Exception\CannotInstantiateFormatter; <ide> use Aura\Intl\FormatterInterface; <del>use Cake\I18n\PluralRules; <ide> use MessageFormatter; <ide> <ide> /** <ide><path>src/I18n/Formatter/SprintfFormatter.php <ide> namespace Cake\I18n\Formatter; <ide> <ide> use Aura\Intl\FormatterInterface; <del>use Cake\I18n\PluralRules; <ide> <ide> /** <ide> * A formatter that will interpolate variables using sprintf and <ide><path>src/I18n/Translator.php <ide> use Aura\Intl\FormatterInterface; <ide> use Aura\Intl\Package; <ide> use Aura\Intl\TranslatorInterface; <del>use Cake\I18n\PluralRules; <ide> <ide> /** <ide> * Provides missing message behavior for CakePHP internal message formats. <ide><path>tests/TestCase/Http/ControllerFactoryTest.php <ide> namespace Cake\Test\TestCase\Http; <ide> <ide> use Cake\Http\ControllerFactory; <del>use Cake\Http\Response; <ide> use Cake\Http\ServerRequest; <ide> use Cake\TestSuite\TestCase; <ide> <ide><path>tests/test_app/Plugin/TestPlugin/src/Log/Engine/TestPluginLog.php <ide> */ <ide> namespace TestPlugin\Log\Engine; <ide> <del>use Cake\Log\LogInterface; <ide> use Psr\Log\AbstractLogger; <ide> <ide> /** <ide><path>tests/test_app/TestApp/Controller/CakesController.php <ide> namespace TestApp\Controller; <ide> <ide> use Cake\Controller\Controller; <del>use Cake\Network\Exception\NotFoundException; <ide> <ide> /** <ide> * CakesController class <ide><path>tests/test_app/TestApp/Controller/PostsController.php <ide> namespace TestApp\Controller; <ide> <ide> use Cake\Event\Event; <del>use TestApp\Controller\AppController; <ide> <ide> /** <ide> * PostsController class <ide><path>tests/test_app/TestApp/Model/Behavior/SluggableBehavior.php <ide> use Cake\Event\Event; <ide> use Cake\ORM\Behavior; <ide> use Cake\ORM\Query; <del>use Cake\ORM\Table; <ide> use Cake\Utility\Inflector; <ide> <ide> class SluggableBehavior extends Behavior <ide><path>tests/test_app/TestApp/Model/Table/PaginatorPostsTable.php <ide> <ide> use Cake\ORM\Query; <ide> use Cake\ORM\Table; <del>use Cake\Utility\Hash; <ide> <ide> /** <ide> * PaginatorPostsTable class
9
Javascript
Javascript
enable eager listeners in open source
b754caaaf23a070de281dcd0a9d32846470e1907
<ide><path>packages/react-dom/src/__tests__/ReactDOMFiber-test.js <ide> describe('ReactDOMFiber', () => { <ide> }); <ide> <ide> it('should not update event handlers until commit', () => { <add> spyOnDev(console, 'error'); <add> <ide> let ops = []; <ide> const handlerA = () => ops.push('A'); <ide> const handlerB = () => ops.push('B'); <ide> describe('ReactDOMFiber', () => { <ide> class Click extends React.Component { <ide> constructor() { <ide> super(); <del> expect(() => { <del> node.click(); <del> }).toErrorDev( <del> 'Warning: unstable_flushDiscreteUpdates: Cannot flush updates when React is already rendering.', <del> ); <add> node.click(); <ide> } <ide> render() { <ide> return null; <ide> describe('ReactDOMFiber', () => { <ide> // Any click that happens after commit, should invoke A. <ide> click(); <ide> expect(ops).toEqual(['A']); <add> <add> if (__DEV__) { <add> // TODO: this warning shouldn't be firing in the first place if user didn't call it. <add> const errorCalls = console.error.calls.count(); <add> for (let i = 0; i < errorCalls; i++) { <add> expect(console.error.calls.argsFor(i)[0]).toMatch( <add> 'unstable_flushDiscreteUpdates: Cannot flush updates when React is already rendering.', <add> ); <add> } <add> } <ide> }); <ide> <ide> it('should not crash encountering low-priority tree', () => { <ide><path>packages/shared/ReactFeatureFlags.js <ide> export const enableDiscreteEventFlushingChange = false; <ide> export const enablePassiveEventIntervention = true; <ide> export const disableOnScrollBubbling = true; <ide> <del>export const enableEagerRootListeners = false; <add>export const enableEagerRootListeners = true; <ide><path>packages/shared/forks/ReactFeatureFlags.native-fb.js <ide> export const deferRenderPhaseUpdateToNextBatch = true; <ide> export const decoupleUpdatePriorityFromScheduler = false; <ide> export const enableDiscreteEventFlushingChange = false; <ide> export const enablePassiveEventIntervention = true; <del>export const enableEagerRootListeners = false; <add>export const enableEagerRootListeners = true; <ide> <ide> // Flow magic to verify the exports of this file match the original version. <ide> // eslint-disable-next-line no-unused-vars <ide><path>packages/shared/forks/ReactFeatureFlags.native-oss.js <ide> export const deferRenderPhaseUpdateToNextBatch = true; <ide> export const decoupleUpdatePriorityFromScheduler = false; <ide> export const enableDiscreteEventFlushingChange = false; <ide> export const enablePassiveEventIntervention = true; <del>export const enableEagerRootListeners = false; <add>export const enableEagerRootListeners = true; <ide> <ide> // Flow magic to verify the exports of this file match the original version. <ide> // eslint-disable-next-line no-unused-vars <ide><path>packages/shared/forks/ReactFeatureFlags.test-renderer.js <ide> export const deferRenderPhaseUpdateToNextBatch = true; <ide> export const decoupleUpdatePriorityFromScheduler = false; <ide> export const enableDiscreteEventFlushingChange = false; <ide> export const enablePassiveEventIntervention = true; <del>export const enableEagerRootListeners = false; <add>export const enableEagerRootListeners = true; <ide> <ide> // Flow magic to verify the exports of this file match the original version. <ide> // eslint-disable-next-line no-unused-vars <ide><path>packages/shared/forks/ReactFeatureFlags.test-renderer.native.js <ide> export const deferRenderPhaseUpdateToNextBatch = true; <ide> export const decoupleUpdatePriorityFromScheduler = false; <ide> export const enableDiscreteEventFlushingChange = false; <ide> export const enablePassiveEventIntervention = true; <del>export const enableEagerRootListeners = false; <add>export const enableEagerRootListeners = true; <ide> <ide> // Flow magic to verify the exports of this file match the original version. <ide> // eslint-disable-next-line no-unused-vars <ide><path>packages/shared/forks/ReactFeatureFlags.test-renderer.www.js <ide> export const deferRenderPhaseUpdateToNextBatch = true; <ide> export const decoupleUpdatePriorityFromScheduler = false; <ide> export const enableDiscreteEventFlushingChange = false; <ide> export const enablePassiveEventIntervention = true; <del>export const enableEagerRootListeners = false; <add>export const enableEagerRootListeners = true; <ide> <ide> // Flow magic to verify the exports of this file match the original version. <ide> // eslint-disable-next-line no-unused-vars <ide><path>packages/shared/forks/ReactFeatureFlags.testing.js <ide> export const deferRenderPhaseUpdateToNextBatch = true; <ide> export const decoupleUpdatePriorityFromScheduler = false; <ide> export const enableDiscreteEventFlushingChange = false; <ide> export const enablePassiveEventIntervention = true; <del>export const enableEagerRootListeners = false; <add>export const enableEagerRootListeners = true; <ide> <ide> // Flow magic to verify the exports of this file match the original version. <ide> // eslint-disable-next-line no-unused-vars <ide><path>packages/shared/forks/ReactFeatureFlags.testing.www.js <ide> export const deferRenderPhaseUpdateToNextBatch = true; <ide> export const decoupleUpdatePriorityFromScheduler = false; <ide> export const enableDiscreteEventFlushingChange = true; <ide> export const enablePassiveEventIntervention = true; <del>export const enableEagerRootListeners = false; <add>export const enableEagerRootListeners = true; <ide> <ide> // Flow magic to verify the exports of this file match the original version. <ide> // eslint-disable-next-line no-unused-vars <ide><path>packages/shared/forks/ReactFeatureFlags.www-dynamic.js <ide> export const decoupleUpdatePriorityFromScheduler = __VARIANT__; <ide> export const skipUnmountedBoundaries = __VARIANT__; <ide> export const enablePassiveEventIntervention = __VARIANT__; <ide> export const disableOnScrollBubbling = __VARIANT__; <del>export const enableEagerRootListeners = __VARIANT__; <add>export const enableEagerRootListeners = !__VARIANT__; <ide> <ide> // Enable this flag to help with concurrent mode debugging. <ide> // It logs information to the console about React scheduling, rendering, and commit phases.
10
Go
Go
fix xtables_lock message probe
e2f00704928fd474cf2074a2931069d90d021087
<ide><path>libnetwork/iptables/iptables.go <ide> var ( <ide> iptablesPath string <ide> supportsXlock = false <ide> supportsCOpt = false <add> xLockWaitMsg = "Another app is currently holding the xtables lock; waiting" <ide> // used to lock iptables commands if xtables lock is not supported <ide> bestEffortLock sync.Mutex <ide> // ErrIptablesNotFound is returned when the rule is not found. <ide> func raw(args ...string) ([]byte, error) { <ide> } <ide> <ide> // ignore iptables' message about xtables lock <del> if strings.Contains(string(output), "waiting for it to exit") { <add> if strings.Contains(string(output), xLockWaitMsg) { <ide> output = []byte("") <ide> } <ide>
1
Python
Python
correct an issue on idle display
4b1983174198c393a9adb12dbb0d158d2507e49d
<ide><path>glances/plugins/glances_cpu.py <ide> def msg_curse(self, args=None, max_width=None): <ide> ret.append(self.curse_add_line( <ide> msg, self.get_views(key='total', option='decoration'))) <ide> # Idle CPU <del> if not idle_tag: <del> ret.extend(self.curse_add_stat('idle', width=15, header=' ')) <add> if 'idle' in self.stats and not idle_tag: <add> msg = ' {:8}'.format('idle:') <add> ret.append(self.curse_add_line(msg, optional=self.get_views(key='idle', <add> option='optional'))) <add> msg = '{:5.1f}%'.format(self.stats['idle']) <add> ret.append(self.curse_add_line(msg, optional=self.get_views(key='idle', <add> option='optional'))) <ide> # ctx_switches <ide> ret.extend(self.curse_add_stat('ctx_switches', width=15, header=' ')) <ide>
1
Javascript
Javascript
add unit tests for raycaster
7961f3a999a330276ff55e4183765cd31c07f345
<ide><path>test/unit/core/Raycaster.js <add>/** <add> * @author simonThiele / https://github.com/simonThiele <add> */ <add> <add>module( "Raycaster" ); <add> <add>test( "intersectObjects", function() { <add> var raycaster = getRaycaster(); <add> var objectsToCheck = getObjectsToCheck(); <add> <add> ok ( raycaster.intersectObjects(objectsToCheck).length === 1, <add> "no recursive search should lead to one hit" ); <add> <add> ok ( raycaster.intersectObjects(objectsToCheck, true).length === 3, <add> "recursive search should lead to two hits" ); <add> <add> var intersections = raycaster.intersectObjects(objectsToCheck, true); <add> for (var i = 0; i < intersections.length - 1; i++) { <add> ok( intersections[i].distance <= intersections[i + 1].distance, "intersections are sorted" ); <add> } <add>}); <add> <add>test( "intersectObject", function() { <add> var raycaster = getRaycaster(); <add> var objectsToCheck = getObjectsToCheck(); <add> <add> ok ( raycaster.intersectObject(objectsToCheck[0]).length === 1, <add> "no recursive search should lead to one hit" ); <add> <add> ok ( raycaster.intersectObject(objectsToCheck[0], true).length === 3, <add> "recursive search should lead to two hits" ); <add> <add> var intersections = raycaster.intersectObject(objectsToCheck[0], true); <add> for (var i = 0; i < intersections.length - 1; i++) { <add> ok( intersections[i].distance <= intersections[i + 1].distance, "intersections are sorted" ); <add> } <add>}); <add> <add>test( "setFromCamera", function() { <add> var raycaster = new THREE.Raycaster(); <add> var rayDirection = raycaster.ray.direction; <add> var camera = new THREE.PerspectiveCamera( 90, 1, 1, 1000 ); <add> <add> raycaster.setFromCamera( { x : 0, y: 0 }, camera ); <add> ok( rayDirection.x === 0, rayDirection.y === 0, rayDirection.z === -1, <add> "camera is looking straight to -z and so does the ray in the middle of the screen" ); <add> <add> var step = 0.1; <add> for (var x = -1; x <= 1; x+=step) { <add> for (var y = -1; y <= 1; y+=step) { <add> raycaster.setFromCamera( { x, y }, camera ); <add> var refVector = new THREE.Vector3(x, y, -1).normalize(); <add> checkRayDirectionAgainstReferenceVector(rayDirection, refVector); <add> } <add> } <add>}); <add> <add>function checkRayDirectionAgainstReferenceVector(rayDirection, refVector) { <add> ok( refVector.x - rayDirection.x <= Number.EPSILON && <add> refVector.y - rayDirection.y <= Number.EPSILON && <add> refVector.z - rayDirection.z <= Number.EPSILON, <add> "camera is pointing to the same direction as expected" ); <add>} <add> <add>function getRaycaster() { <add> return raycaster = new THREE.Raycaster( <add> new THREE.Vector3( 0, 0, 0 ), <add> new THREE.Vector3( 0, 0, -1 ), <add> 1, <add> 100 <add> ); <add>} <add> <add>function getObjectsToCheck() { <add> var objects = []; <add> <add> var sphere1 = getSphere(); <add> sphere1.position.set(0, 0, -10); <add> sphere1.name = 1; <add> objects.push(sphere1); <add> <add> var sphere11 = getSphere(); <add> sphere11.position.set(0, 0, 1); <add> sphere11.name = 11; <add> sphere1.add(sphere11); <add> <add> var sphere12 = getSphere(); <add> sphere12.position.set(0, 0, -1); <add> sphere12.name = 12; <add> sphere1.add(sphere12); <add> <add> var sphere2 = getSphere(); <add> sphere2.position.set(-5, 0, -5); <add> sphere2.name = 2; <add> objects.push(sphere2); <add> <add> for (var i = 0; i < objects.length; i++) { <add> objects[i].updateMatrixWorld(); <add> } <add> return objects; <add>} <add> <add>function getSphere() { <add> return new THREE.Mesh(new THREE.SphereGeometry(1, 100, 100)); <add>}
1
Ruby
Ruby
add -sources to the version recognizer
da565308add13f866590b43dd860fd250d00fedc
<ide><path>Library/Homebrew/pathname+yeast.rb <ide> def version <ide> return $1 if $1 <ide> <ide> # eg foobar-4.5.0-bin <del> /-((\d+\.)+\d+[abc]?)-(bin|src)$/.match stem <add> /-((\d+\.)+\d+[abc]?)-(bin|src|sources)$/.match stem <ide> return $1 if $1 <ide> <ide> # eg. otp_src_R13B (this is erlang's style)
1
Javascript
Javascript
avoid touching length in vector constructor
795f69793a2e5c96fb6dd2ced2167553339f0770
<ide><path>dist/immutable.js <ide> var $Vector = Vector; <ide> return EMPTY_VECT || (EMPTY_VECT = makeVector(0, 0, SHIFT)); <ide> }, <ide> from: function(sequence) { <del> if (!sequence || sequence.length === 0 || sequence.size === 0) { <add> if (!sequence) { <ide> return $Vector.empty(); <ide> } <ide> if (sequence.constructor === $Vector) { <ide> return sequence; <ide> } <ide> var isArray = Array.isArray(sequence); <del> if (sequence.size > 0 && sequence.size < SIZE) { <del> return makeVector(0, sequence.size, SHIFT, null, new VNode(isArray ? arrCopy(sequence) : Sequence(sequence).toArray())); <add> var size = isArray ? sequence.length : sequence.size; <add> if (size === 0) { <add> return $Vector.empty(); <add> } <add> if (size > 0 && size < SIZE) { <add> return makeVector(0, size, SHIFT, null, new VNode(isArray ? arrCopy(sequence) : (sequence.toArray ? sequence : Sequence(sequence)).toArray())); <ide> } <ide> if (!isArray) { <ide> sequence = Sequence(sequence).valueSeq(); <ide><path>dist/immutable.min.js <ide> return i},__iterator:function(t,e){var r=this._array,n=r.length-1,i=0;return new <ide> },get:function(t,e){return this._root?this._root.get(0,h(t),t,e):e},set:function(t,e){return Z(this,t,e)},setIn:function(t,e){return o(t.length>0,"Requires non-empty key path."),this.updateIn(t,function(){return e})},remove:function(t){return Z(this,t,Be)},removeIn:function(t){return o(t.length>0,"Requires non-empty key path."),this.updateIn(t,function(){return Be})},update:function(t,e,r){return 1===arguments.length?t(this):this.updateIn([t],e,r)},updateIn:function(t,e,r){return r||(r=e,e=void 0),0===t.length?r(this):ae(this,t,e,r,0)},clear:function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._root=null,this.__hash=void 0,this.__altered=!0,this):Ir.empty()},merge:function(){return ie(this,null,arguments)},mergeWith:function(t){for(var e=[],r=1;arguments.length>r;r++)e[r-1]=arguments[r];return ie(this,t,e)},mergeDeep:function(){return ie(this,ue(null),arguments)},mergeDeepWith:function(t){for(var e=[],r=1;arguments.length>r;r++)e[r-1]=arguments[r];return ie(this,ue(t),e)},cursor:function(t,e){var r=0===arguments.length||"function"==typeof t&&(e=t)?[]:Array.isArray(t)?t:[t];return Oe(this,r,e)},withMutations:function(t){var e=this.asMutable();return t(e),e.wasAltered()?e.__ensureOwner(this.__ownerID):this},asMutable:function(){return this.__ownerID?this:this.__ensureOwner(new s)},asImmutable:function(){return this.__ensureOwner()},wasAltered:function(){return this.__altered},__iterator:function(t,e){return new jr(this,t,e)},__iterate:function(t,e){var r=this,n=0;return this._root&&this._root.iterate(function(e){return n++,t(e[1],e[0],r)},e),n},__ensureOwner:function(t){return t===this.__ownerID?this:t?Y(this.size,this._root,t,this.__hash):(this.__ownerID=t,this.__altered=!1,this)}},{empty:function(){return Rr||(Rr=Y(0))}},hr);var br=qr.prototype;br[Ue]=br.remove,qr.from=qr;var kr=function(t,e,r){this.ownerID=t,this.bitmap=e,this.nodes=r},xr=kr;Re.createClass(kr,{get:function(t,e,r,n){var i=1<<((0===t?e:e>>>t)&We),u=this.bitmap;return 0===(u&i)?n:this.nodes[oe(u&i-1)].get(t+Ke,e,r,n)},update:function(t,e,r,n,i,u,s){var a=(0===e?r:r>>>e)&We,o=1<<a,h=this.bitmap,c=0!==(h&o); <ide> if(!c&&i===Be)return this;var f=oe(h&o-1),_=this.nodes,l=c?_[f]:null,v=$(l,t,e+Ke,r,n,i,u,s);if(v===l)return this;if(!c&&v&&_.length>=Ur)return ne(t,_,h,a,v);if(c&&!v&&2===_.length&&te(_[1^f]))return _[1^f];if(c&&v&&1===_.length&&te(v))return v;var p=t&&t===this.ownerID,m=c?v?h:h^o:h|o,y=c?v?he(_,f,v,p):fe(_,f,p):ce(_,f,v,p);return p?(this.bitmap=m,this.nodes=y,this):new xr(t,m,y)},iterate:function(t,e){for(var r=this.nodes,n=0,i=r.length-1;i>=n;n++)if(r[e?i-n:n].iterate(t,e)===!1)return!1}},{});var Mr=function(t,e,r){this.ownerID=t,this.count=e,this.nodes=r},Dr=Mr;Re.createClass(Mr,{get:function(t,e,r,n){var i=(0===t?e:e>>>t)&We,u=this.nodes[i];return u?u.get(t+Ke,e,r,n):n},update:function(t,e,r,n,i,u,s){var a=(0===e?r:r>>>e)&We,o=i===Be,h=this.nodes,c=h[a];if(o&&!c)return this;var f=$(c,t,e+Ke,r,n,i,u,s);if(f===c)return this;var _=this.count;if(c){if(!f&&(_--,Kr>_))return re(t,h,_,a)}else _++;var l=t&&t===this.ownerID,v=he(h,a,f,l);return l?(this.count=_,this.nodes=v,this):new Dr(t,_,v)},iterate:function(t,e){for(var r=this.nodes,n=0,i=r.length-1;i>=n;n++){var u=r[e?i-n:n];if(u&&u.iterate(t,e)===!1)return!1}}},{});var Or=function(t,e,r){this.ownerID=t,this.hash=e,this.entries=r},Cr=Or;Re.createClass(Or,{get:function(t,e,r,i){for(var u=this.entries,s=0,a=u.length;a>s;s++)if(n(r,u[s][0]))return u[s][1];return i},update:function(t,e,r,i,s,o,h){var c=s===Be;if(r!==this.hash)return c?this:(u(h),u(o),ee(this,t,e,r,[i,s]));for(var f=this.entries,_=0,l=f.length;l>_&&!n(i,f[_][0]);_++);var v=l>_;if(c&&!v)return this;if(u(h),(c||!v)&&u(o),c&&2===l)return new Ar(t,this.hash,f[1^_]);var p=t&&t===this.ownerID,m=p?f:a(f);return v?c?_===l-1?m.pop():m[_]=m.pop():m[_]=[i,s]:m.push([i,s]),p?(this.entries=m,this):new Cr(t,this.hash,m)},iterate:function(t,e){for(var r=this.entries,n=0,i=r.length-1;i>=n;n++)if(t(r[e?i-n:n])===!1)return!1}},{});var Ar=function(t,e,r){this.ownerID=t,this.hash=e,this.entry=r},Er=Ar;Re.createClass(Ar,{get:function(t,e,r,i){return n(r,this.entry[0])?this.entry[1]:i},update:function(t,e,r,i,s,a,o){var h=s===Be,c=n(i,this.entry[0]); <ide> return(c?s===this.entry[1]:h)?this:(u(o),h?(u(a),null):c?t&&t===this.ownerID?(this.entry[1]=s,this):new Er(t,r,[i,s]):(u(a),ee(this,t,e,r,[i,s])))},iterate:function(t){return t(this.entry)}},{});var jr=function(t,e,r){this._type=e,this._reverse=r,this._stack=t._root&&X(t._root)};Re.createClass(jr,{next:function(){for(var t=this._type,e=this._stack;e;){var r,n=e.node,i=e.index++;if(n.entry){if(0===i)return Q(t,n.entry)}else if(n.entries){if(r=n.entries.length-1,r>=i)return Q(t,n.entries[this._reverse?r-i:i])}else if(r=n.nodes.length-1,r>=i){var u=n.nodes[this._reverse?r-i:i];if(u){if(u.entry)return Q(t,u.entry);e=this._stack=X(u,e)}continue}e=this._stack=this._stack.__prev}return p()}},{},ir);var Rr,Ur=Pe/2,Kr=Pe/4,Pr=function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];return Wr.from(t)},Wr=Pr;Re.createClass(Pr,{toString:function(){return this.__toString("Vector [","]")},get:function(t,e){if(t=C(this,t),0>t||t>=this.size)return e;t+=this._origin;var r=ge(this,t);return r&&r.array[t&We]},set:function(t,e){return pe(this,t,e)},remove:function(t){return pe(this,t,Be)},clear:function(){return 0===this.size?this:this.__ownerID?(this.size=this._origin=this._capacity=0,this._level=Ke,this._root=this._tail=null,this.__hash=void 0,this.__altered=!0,this):Wr.empty()},push:function(){var t=arguments,e=this.size;return this.withMutations(function(r){de(r,0,e+t.length);for(var n=0;t.length>n;n++)r.set(e+n,t[n])})},pop:function(){return de(this,0,-1)},unshift:function(){var t=arguments;return this.withMutations(function(e){de(e,-t.length);for(var r=0;t.length>r;r++)e.set(r,t[r])})},shift:function(){return de(this,1)},merge:function(){return we(this,null,arguments)},mergeWith:function(t){for(var e=[],r=1;arguments.length>r;r++)e[r-1]=arguments[r];return we(this,t,e)},mergeDeep:function(){return we(this,ue(null),arguments)},mergeDeepWith:function(t){for(var e=[],r=1;arguments.length>r;r++)e[r-1]=arguments[r];return we(this,ue(t),e)},setSize:function(t){return de(this,0,t)},slice:function(t,e){var r=Re.superCall(this,Wr.prototype,"slice",[t,e]); <del>if(r!==this){var n=this,i=n.size;r.toVector=function(){return de(n,0>t?Math.max(0,i+t):i?Math.min(i,t):t,null==e?i:0>e?Math.max(0,i+e):i?Math.min(i,e):e)}}return r},__iterator:function(t,e){return new Lr(this,t,e)},__iterate:function(t,e){var r=this,n=0,i=function(e){return t(e,n++,r)},u=ze(this._capacity);return e?_e(this._tail,0,u-this._origin,this._capacity-this._origin,i,e)&&_e(this._root,this._level,-this._origin,u-this._origin,i,e):_e(this._root,this._level,-this._origin,u-this._origin,i,e)&&_e(this._tail,0,u-this._origin,this._capacity-this._origin,i,e),n},__ensureOwner:function(t){return t===this.__ownerID?this:t?ve(this._origin,this._capacity,this._level,this._root,this._tail,t,this.__hash):(this.__ownerID=t,this)}},{empty:function(){return Tr||(Tr=ve(0,0,Ke))},from:function(t){if(!t||0===t.length||0===t.size)return Wr.empty();if(t.constructor===Wr)return t;var e=Array.isArray(t);return t.size>0&&Pe>t.size?ve(0,t.size,Ke,null,new Jr(e?a(t):sr(t).toArray())):(e||(t=sr(t).valueSeq()),Wr.empty().merge(t))}},_r);var Br=Pr.prototype;Br[Ue]=Br.remove,Br.setIn=br.setIn,Br.removeIn=br.removeIn,Br.update=br.update,Br.updateIn=br.updateIn,Br.cursor=br.cursor,Br.withMutations=br.withMutations,Br.asMutable=br.asMutable,Br.asImmutable=br.asImmutable,Br.wasAltered=br.wasAltered;var Jr=function(t,e){this.array=t,this.ownerID=e},Vr=Jr;Re.createClass(Jr,{removeBefore:function(t,e,r){if(r===e?1<<e:0||0===this.array.length)return this;var n=r>>>e&We;if(n>=this.array.length)return new Vr([],t);var i,u=0===n;if(e>0){var s=this.array[n];if(i=s&&s.removeBefore(t,e-Ke,r),i===s&&u)return this}if(u&&!i)return this;var a=ye(this,t);if(!u)for(var o=0;n>o;o++)a.array[o]=void 0;return i&&(a.array[n]=i),a},removeAfter:function(t,e,r){if(r===e?1<<e:0||0===this.array.length)return this;var n=r-1>>>e&We;if(n>=this.array.length)return this;var i,u=n===this.array.length-1;if(e>0){var s=this.array[n];if(i=s&&s.removeAfter(t,e-Ke,r),i===s&&u)return this}if(u&&!i)return this;var a=ye(this,t);return u||a.array.pop(),i&&(a.array[n]=i),a}},{});var Lr=function(t,e,r){this._type=e,this._reverse=!!r,this._maxIndex=t.size-1; <del>var n=ze(t._capacity),i=le(t._root&&t._root.array,t._level,-t._origin,n-t._origin-1),u=le(t._tail&&t._tail.array,0,n-t._origin,t._capacity-t._origin-1);this._stack=r?u:i,this._stack.__prev=r?i:u};Re.createClass(Lr,{next:function(){for(var t=this._stack;t;){var e=t.array,r=t.index++;if(this._reverse&&(r=We-r,r>t.rawMax&&(r=t.rawMax,t.index=Pe-r)),r>=0&&Pe>r&&t.rawMax>=r){var n=e&&e[r];if(0===t.level){var i,u=this._type;return 1!==u&&(i=t.offset+(r<<t.level),this._reverse&&(i=this._maxIndex-i)),v(u,i,n)}this._stack=t=le(n&&n.array,t.level-Ke,t.offset+(r<<t.level),t.max,t)}else t=this._stack=this._stack.__prev}return p()}},{},ir);var Tr,Nr=function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];return Fr.from(t)},Fr=Nr;Re.createClass(Nr,{toString:function(){return this.__toString("Stack [","]")},get:function(t,e){for(var r=this._head;r&&t--;)r=r.next;return r?r.value:e},peek:function(){return this._head&&this._head.value},push:function(){if(0===arguments.length)return this;for(var t=this.size+arguments.length,e=this._head,r=arguments.length-1;r>=0;r--)e={value:arguments[r],next:e};return this.__ownerID?(this.size=t,this._head=e,this.__hash=void 0,this.__altered=!0,this):Se(t,e)},pushAll:function(t){if(t=sr(t),0===t.size)return this;var e=this.size,r=this._head;return t.reverse().forEach(function(t){e++,r={value:t,next:r}}),this.__ownerID?(this.size=e,this._head=r,this.__hash=void 0,this.__altered=!0,this):Se(e,r)},pop:function(){return this.slice(1)},unshift:function(){return this.push.apply(this,arguments)},unshiftAll:function(t){return this.pushAll(t)},shift:function(){return this.pop.apply(this,arguments)},clear:function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._head=void 0,this.__hash=void 0,this.__altered=!0,this):Fr.empty()},slice:function(t,e){if(z(t,e,this.size))return this;var r=S(t,this.size),n=q(e,this.size);if(n!==this.size)return Re.superCall(this,Fr.prototype,"slice",[t,e]);for(var i=this.size-r,u=this._head;r--;)u=u.next;return this.__ownerID?(this.size=i,this._head=u,this.__hash=void 0,this.__altered=!0,this):Se(i,u) <del>},__ensureOwner:function(t){return t===this.__ownerID?this:t?Se(this.size,this._head,t,this.__hash):(this.__ownerID=t,this.__altered=!1,this)},__iterateUncached:function(t,e){if(e)return this.cacheResult().__iterate(t,e);for(var r=0,n=this._head;n&&t(n.value,r++,this)!==!1;)n=n.next;return r},__iteratorUncached:function(t,e){if(e)return this.cacheResult().__iterator(t,e);var r=0,n=this._head;return new ir(function(){if(n){var e=n.value;return n=n.next,v(t,r++,e)}return p()})}},{empty:function(){return Hr||(Hr=Se(0))},from:function(t){var e=Fr.empty();return t?t.constructor===Fr?t:e.unshiftAll(t):e}},_r);var Gr=Nr.prototype;Gr.withMutations=br.withMutations,Gr.asMutable=br.asMutable,Gr.asImmutable=br.asImmutable,Gr.wasAltered=br.wasAltered;var Hr,Qr=function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];return Xr.from(t)},Xr=Qr;Re.createClass(Qr,{get:function(t,e){return this._map.has(t)?t:e},contains:function(t){return this._map.has(t)},add:function(t){var e=this._map.set(t,null);return this.__ownerID?(this.size=e.size,this._map=e,this):e===this._map?this:qe(e)},remove:function(t){var e=this._map.remove(t);return this.__ownerID?(this.size=e.size,this._map=e,this):e===this._map?this:0===e.size?Xr.empty():qe(e)},clear:function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._map.clear(),this):Xr.empty()},union:function(){var t=arguments;return 0===t.length?this:this.withMutations(function(e){for(var r=0;t.length>r;r++)sr(t[r]).forEach(function(t){return e.add(t)})})},intersect:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];if(0===t.length)return this;t=t.map(function(t){return sr(t)});var r=this;return this.withMutations(function(e){r.forEach(function(r){t.every(function(t){return t.contains(r)})||e.remove(r)})})},subtract:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];if(0===t.length)return this;t=t.map(function(t){return sr(t)});var r=this;return this.withMutations(function(e){r.forEach(function(r){t.some(function(t){return t.contains(r)})&&e.remove(r) <del>})})},isSubset:function(t){return t=sr(t),this.every(function(e){return t.contains(e)})},isSuperset:function(t){var e=this;return t=sr(t),t.every(function(t){return e.contains(t)})},merge:function(){return this.union.apply(this,arguments)},mergeWith:function(){for(var t=[],e=1;arguments.length>e;e++)t[e-1]=arguments[e];return this.union.apply(this,t)},wasAltered:function(){return this._map.wasAltered()},__iterate:function(t,e){var r=this;return this._map.__iterate(function(e,n){return t(n,n,r)},e)},__iterator:function(t,e){return this._map.map(function(t,e){return e}).__iterator(t,e)},__ensureOwner:function(t){if(t===this.__ownerID)return this;var e=this._map.__ensureOwner(t);return t?qe(e,t):(this.__ownerID=t,this._map=e,this)}},{empty:function(){return Zr||(Zr=qe(qr.empty()))},from:function(t){var e=Xr.empty();return t?t.constructor===Xr?t:e.union(t):e},fromKeys:function(t){return Xr.from(sr(t).flip())}},sr);var Yr=Qr.prototype;Yr[Ue]=Yr.remove,Yr.mergeDeep=Yr.merge,Yr.mergeDeepWith=Yr.mergeWith,Yr.withMutations=br.withMutations,Yr.asMutable=br.asMutable,Yr.asImmutable=br.asImmutable;var Zr,$r=function(t){var e=tn.empty();return t?t.constructor===tn?t:e.merge(t):e},tn=$r;Re.createClass($r,{toString:function(){return this.__toString("OrderedMap {","}")},get:function(t,e){var r=this._map.get(t);return null!=r?this._vector.get(r)[1]:e},clear:function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._map.clear(),this._vector.clear(),this):tn.empty()},set:function(t,e){return be(this,t,e)},remove:function(t){return be(this,t,Be)},wasAltered:function(){return this._map.wasAltered()||this._vector.wasAltered()},__iterate:function(t,e){var r=this;return this._vector.__iterate(function(e){return e&&t(e[1],e[0],r)},e)},__iterator:function(t,e){return this._vector.fromEntrySeq().__iterator(t,e)},__ensureOwner:function(t){if(t===this.__ownerID)return this;var e=this._map.__ensureOwner(t),r=this._vector.__ensureOwner(t);return t?Ie(e,r,t,this.__hash):(this.__ownerID=t,this._map=e,this._vector=r,this)}},{empty:function(){return en||(en=Ie(qr.empty(),Pr.empty())) <del>}},qr),$r.from=$r,$r.prototype[Ue]=$r.prototype.remove;var en,rn=function(t,e){var r=function(t){return this instanceof r?void(this._map=qr(t)):new r(t)},n=Object.keys(t),i=r.prototype=Object.create(nn);i.constructor=r,e&&(i._name=e),i._defaultValues=t,i._keys=n,i.size=n.length;try{sr(t).forEach(function(t,e){Object.defineProperty(r.prototype,e,{get:function(){return this.get(e)},set:function(t){o(this.__ownerID,"Cannot set on an immutable record."),this.set(e,t)}})})}catch(u){}return r};Re.createClass(rn,{toString:function(){return this.__toString(this._name+" {","}")},has:function(t){return this._defaultValues.hasOwnProperty(t)},get:function(t,e){return void 0===e||this.has(t)?this._map.get(t,this._defaultValues[t]):e},clear:function(){if(this.__ownerID)return this._map.clear(),this;var t=Object.getPrototypeOf(this).constructor;return t._empty||(t._empty=ke(this,qr.empty()))},set:function(t,e){if(!this.has(t))throw Error('Cannot set unknown key "'+t+'" on '+this._name);var r=this._map.set(t,e);return this.__ownerID||r===this._map?this:ke(this,r)},remove:function(t){if(null==t||!this.has(t))return this;var e=this._map.remove(t);return this.__ownerID||e===this._map?this:ke(this,e)},keys:function(){return this._map.keys()},values:function(){return this._map.values()},entries:function(){return this._map.entries()},wasAltered:function(){return this._map.wasAltered()},__iterator:function(t,e){return this._map.__iterator(t,e)},__iterate:function(t,e){var r=this;return sr(this._defaultValues).map(function(t,e){return r.get(e)}).__iterate(t,e)},__ensureOwner:function(t){if(t===this.__ownerID)return this;var e=this._map&&this._map.__ensureOwner(t);return t?ke(this,e,t):(this.__ownerID=t,this._map=e,this)}},{},hr);var nn=rn.prototype;nn._name="Record",nn[Ue]=nn.remove,nn.merge=br.merge,nn.mergeWith=br.mergeWith,nn.mergeDeep=br.mergeDeep,nn.mergeDeepWith=br.mergeDeepWith,nn.update=br.update,nn.updateIn=br.updateIn,nn.cursor=br.cursor,nn.withMutations=br.withMutations,nn.asMutable=br.asMutable,nn.asImmutable=br.asImmutable;var un=function(t,e,r){return this instanceof sn?(o(0!==r,"Cannot step a Range by 0"),t=t||0,null==e&&(e=1/0),t===e&&on?on:(r=null==r?1:Math.abs(r),t>e&&(r=-r),this._start=t,this._end=e,this._step=r,void(this.size=Math.max(0,Math.ceil((e-t)/r-1)+1)))):new sn(t,e,r) <del>},sn=un;Re.createClass(un,{toString:function(){return 0===this.size?"Range []":"Range [ "+this._start+"..."+this._end+(this._step>1?" by "+this._step:"")+" ]"},get:function(t,e){return this.has(t)?this._start+C(this,t)*this._step:e},contains:function(t){var e=(t-this._start)/this._step;return e>=0&&this.size>e&&e===Math.floor(e)},slice:function(t,e){return z(t,e,this.size)?this:(t=S(t,this.size),e=q(e,this.size),t>=e?on:new sn(this.get(t,this._end),this.get(e,this._end),this._step))},indexOf:function(t){var e=t-this._start;if(e%this._step===0){var r=e/this._step;if(r>=0&&this.size>r)return r}return-1},lastIndexOf:function(t){return this.indexOf(t)},take:function(t){return this.slice(0,Math.max(0,t))},skip:function(t){return this.slice(Math.max(0,t))},__iterate:function(t,e){for(var r=this.size-1,n=this._step,i=e?this._start+r*n:this._start,u=0;r>=u;u++){if(t(i,u,this)===!1)return u+1;i+=e?-n:n}return u},__iterator:function(t,e){var r=this.size-1,n=this._step,i=e?this._start+r*n:this._start,u=0;return new ir(function(){var s=i;return i+=e?-n:n,u>r?p():v(t,u++,s)})},__deepEquals:function(t){return t instanceof sn?this._start===t._start&&this._end===t._end&&this._step===t._step:Re.superCall(this,sn.prototype,"__deepEquals",[t])}},{},_r);var an=un.prototype;an.__toJS=an.toArray,an.first=Br.first,an.last=Br.last;var on=un(0,0),hn=function(t,e){return 0===e&&_n?_n:this instanceof cn?(this._value=t,void(this.size=null==e?1/0:Math.max(0,e))):new cn(t,e)},cn=hn;Re.createClass(hn,{toString:function(){return 0===this.size?"Repeat []":"Repeat [ "+this._value+" "+this.size+" times ]"},get:function(t,e){return this.has(t)?this._value:e},contains:function(t){return n(this._value,t)},slice:function(t,e){var r=this.size;return t=0>t?Math.max(0,r+t):Math.min(r,t),e=null==e?r:e>0?Math.min(r,e):Math.max(0,r+e),e>t?new cn(this._value,e-t):_n},reverse:function(){return this},indexOf:function(t){return n(this._value,t)?0:-1},lastIndexOf:function(t){return n(this._value,t)?this.size:-1},__iterate:function(t){for(var e=0;this.size>e;e++)if(t(this._value,e,this)===!1)return e+1; <del>return e},__iterator:function(t){var e=this,r=0;return new ir(function(){return e.size>r?v(t,r++,e._value):p()})},__deepEquals:function(t){return t instanceof cn?n(this._value,t._value):Re.superCall(this,cn.prototype,"__deepEquals",[t])}},{},_r);var fn=hn.prototype;fn.last=fn.first,fn.has=an.has,fn.take=an.take,fn.skip=an.skip,fn.__toJS=an.__toJS;var _n=new hn(void 0,0),ln=function(t,e,r,n){this.size=n,this._rootData=t,this._keyPath=e,this._onChange=r};Re.createClass(ln,{equals:function(t){return n(this.deref(),t&&("function"==typeof t.deref?t.deref():t))},deref:function(t){return this._rootData.getIn(this._keyPath,t)},get:function(t,e){if(Array.isArray(t)&&0===t.length)return this;var r=this._rootData.getIn(this._keyPath.concat(t),Be);return r===Be?e:Ce(this,t,r)},set:function(t,e){return Ee(this,function(r){return r.set(t,e)},t)},remove:function(t){return Ee(this,function(e){return e.remove(t)},t)},clear:function(){return Ee(this,function(t){return t.clear()})},update:function(t,e,r){return 1===arguments.length?Ee(this,t):Ee(this,function(n){return n.update(t,e,r)},t)},withMutations:function(t){return Ee(this,function(e){return(e||qr.empty()).withMutations(t)})},cursor:function(t){return Array.isArray(t)&&0===t.length?this:Ae(this,t)},__iterate:function(t,e){var r=this,n=this.deref();return n&&n.__iterate?n.__iterate(function(e,n){return t(Ce(r,n,e),n,r)},e):0},__iterator:function(t,e){var r=this,n=this.deref(),i=n&&n.__iterator&&n.__iterator(tr,e);return new ir(function(){if(!i)return p();var e=i.next();if(e.done)return e;var n=e.value,u=n[0],s=n[1];return v(t,u,Ce(r,u,s),e)})}},{},hr);var vn=ln.prototype;vn[Ue]=vn.remove,vn.getIn=vn.get;var pn=function(t,e,r,n){this.size=n,this._rootData=t,this._keyPath=e,this._onChange=r};Re.createClass(pn,{},{},_r);var mn=pn.prototype;mn.equals=vn.equals,mn.deref=vn.deref,mn.get=vn.get,mn.getIn=vn.getIn,mn.set=vn.set,mn[Ue]=mn.remove=vn.remove,mn.clear=vn.clear,mn.update=vn.update,mn.withMutations=vn.withMutations,mn.cursor=vn.cursor,mn.__iterate=vn.__iterate,mn.__iterator=vn.__iterator; <add>if(r!==this){var n=this,i=n.size;r.toVector=function(){return de(n,0>t?Math.max(0,i+t):i?Math.min(i,t):t,null==e?i:0>e?Math.max(0,i+e):i?Math.min(i,e):e)}}return r},__iterator:function(t,e){return new Lr(this,t,e)},__iterate:function(t,e){var r=this,n=0,i=function(e){return t(e,n++,r)},u=ze(this._capacity);return e?_e(this._tail,0,u-this._origin,this._capacity-this._origin,i,e)&&_e(this._root,this._level,-this._origin,u-this._origin,i,e):_e(this._root,this._level,-this._origin,u-this._origin,i,e)&&_e(this._tail,0,u-this._origin,this._capacity-this._origin,i,e),n},__ensureOwner:function(t){return t===this.__ownerID?this:t?ve(this._origin,this._capacity,this._level,this._root,this._tail,t,this.__hash):(this.__ownerID=t,this)}},{empty:function(){return Tr||(Tr=ve(0,0,Ke))},from:function(t){if(!t)return Wr.empty();if(t.constructor===Wr)return t;var e=Array.isArray(t),r=e?t.length:t.size;return 0===r?Wr.empty():r>0&&Pe>r?ve(0,r,Ke,null,new Jr(e?a(t):(t.toArray?t:sr(t)).toArray())):(e||(t=sr(t).valueSeq()),Wr.empty().merge(t))}},_r);var Br=Pr.prototype;Br[Ue]=Br.remove,Br.setIn=br.setIn,Br.removeIn=br.removeIn,Br.update=br.update,Br.updateIn=br.updateIn,Br.cursor=br.cursor,Br.withMutations=br.withMutations,Br.asMutable=br.asMutable,Br.asImmutable=br.asImmutable,Br.wasAltered=br.wasAltered;var Jr=function(t,e){this.array=t,this.ownerID=e},Vr=Jr;Re.createClass(Jr,{removeBefore:function(t,e,r){if(r===e?1<<e:0||0===this.array.length)return this;var n=r>>>e&We;if(n>=this.array.length)return new Vr([],t);var i,u=0===n;if(e>0){var s=this.array[n];if(i=s&&s.removeBefore(t,e-Ke,r),i===s&&u)return this}if(u&&!i)return this;var a=ye(this,t);if(!u)for(var o=0;n>o;o++)a.array[o]=void 0;return i&&(a.array[n]=i),a},removeAfter:function(t,e,r){if(r===e?1<<e:0||0===this.array.length)return this;var n=r-1>>>e&We;if(n>=this.array.length)return this;var i,u=n===this.array.length-1;if(e>0){var s=this.array[n];if(i=s&&s.removeAfter(t,e-Ke,r),i===s&&u)return this}if(u&&!i)return this;var a=ye(this,t);return u||a.array.pop(),i&&(a.array[n]=i),a <add>}},{});var Lr=function(t,e,r){this._type=e,this._reverse=!!r,this._maxIndex=t.size-1;var n=ze(t._capacity),i=le(t._root&&t._root.array,t._level,-t._origin,n-t._origin-1),u=le(t._tail&&t._tail.array,0,n-t._origin,t._capacity-t._origin-1);this._stack=r?u:i,this._stack.__prev=r?i:u};Re.createClass(Lr,{next:function(){for(var t=this._stack;t;){var e=t.array,r=t.index++;if(this._reverse&&(r=We-r,r>t.rawMax&&(r=t.rawMax,t.index=Pe-r)),r>=0&&Pe>r&&t.rawMax>=r){var n=e&&e[r];if(0===t.level){var i,u=this._type;return 1!==u&&(i=t.offset+(r<<t.level),this._reverse&&(i=this._maxIndex-i)),v(u,i,n)}this._stack=t=le(n&&n.array,t.level-Ke,t.offset+(r<<t.level),t.max,t)}else t=this._stack=this._stack.__prev}return p()}},{},ir);var Tr,Nr=function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];return Fr.from(t)},Fr=Nr;Re.createClass(Nr,{toString:function(){return this.__toString("Stack [","]")},get:function(t,e){for(var r=this._head;r&&t--;)r=r.next;return r?r.value:e},peek:function(){return this._head&&this._head.value},push:function(){if(0===arguments.length)return this;for(var t=this.size+arguments.length,e=this._head,r=arguments.length-1;r>=0;r--)e={value:arguments[r],next:e};return this.__ownerID?(this.size=t,this._head=e,this.__hash=void 0,this.__altered=!0,this):Se(t,e)},pushAll:function(t){if(t=sr(t),0===t.size)return this;var e=this.size,r=this._head;return t.reverse().forEach(function(t){e++,r={value:t,next:r}}),this.__ownerID?(this.size=e,this._head=r,this.__hash=void 0,this.__altered=!0,this):Se(e,r)},pop:function(){return this.slice(1)},unshift:function(){return this.push.apply(this,arguments)},unshiftAll:function(t){return this.pushAll(t)},shift:function(){return this.pop.apply(this,arguments)},clear:function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._head=void 0,this.__hash=void 0,this.__altered=!0,this):Fr.empty()},slice:function(t,e){if(z(t,e,this.size))return this;var r=S(t,this.size),n=q(e,this.size);if(n!==this.size)return Re.superCall(this,Fr.prototype,"slice",[t,e]);for(var i=this.size-r,u=this._head;r--;)u=u.next; <add>return this.__ownerID?(this.size=i,this._head=u,this.__hash=void 0,this.__altered=!0,this):Se(i,u)},__ensureOwner:function(t){return t===this.__ownerID?this:t?Se(this.size,this._head,t,this.__hash):(this.__ownerID=t,this.__altered=!1,this)},__iterateUncached:function(t,e){if(e)return this.cacheResult().__iterate(t,e);for(var r=0,n=this._head;n&&t(n.value,r++,this)!==!1;)n=n.next;return r},__iteratorUncached:function(t,e){if(e)return this.cacheResult().__iterator(t,e);var r=0,n=this._head;return new ir(function(){if(n){var e=n.value;return n=n.next,v(t,r++,e)}return p()})}},{empty:function(){return Hr||(Hr=Se(0))},from:function(t){var e=Fr.empty();return t?t.constructor===Fr?t:e.unshiftAll(t):e}},_r);var Gr=Nr.prototype;Gr.withMutations=br.withMutations,Gr.asMutable=br.asMutable,Gr.asImmutable=br.asImmutable,Gr.wasAltered=br.wasAltered;var Hr,Qr=function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];return Xr.from(t)},Xr=Qr;Re.createClass(Qr,{get:function(t,e){return this._map.has(t)?t:e},contains:function(t){return this._map.has(t)},add:function(t){var e=this._map.set(t,null);return this.__ownerID?(this.size=e.size,this._map=e,this):e===this._map?this:qe(e)},remove:function(t){var e=this._map.remove(t);return this.__ownerID?(this.size=e.size,this._map=e,this):e===this._map?this:0===e.size?Xr.empty():qe(e)},clear:function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._map.clear(),this):Xr.empty()},union:function(){var t=arguments;return 0===t.length?this:this.withMutations(function(e){for(var r=0;t.length>r;r++)sr(t[r]).forEach(function(t){return e.add(t)})})},intersect:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];if(0===t.length)return this;t=t.map(function(t){return sr(t)});var r=this;return this.withMutations(function(e){r.forEach(function(r){t.every(function(t){return t.contains(r)})||e.remove(r)})})},subtract:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];if(0===t.length)return this;t=t.map(function(t){return sr(t)});var r=this;return this.withMutations(function(e){r.forEach(function(r){t.some(function(t){return t.contains(r) <add>})&&e.remove(r)})})},isSubset:function(t){return t=sr(t),this.every(function(e){return t.contains(e)})},isSuperset:function(t){var e=this;return t=sr(t),t.every(function(t){return e.contains(t)})},merge:function(){return this.union.apply(this,arguments)},mergeWith:function(){for(var t=[],e=1;arguments.length>e;e++)t[e-1]=arguments[e];return this.union.apply(this,t)},wasAltered:function(){return this._map.wasAltered()},__iterate:function(t,e){var r=this;return this._map.__iterate(function(e,n){return t(n,n,r)},e)},__iterator:function(t,e){return this._map.map(function(t,e){return e}).__iterator(t,e)},__ensureOwner:function(t){if(t===this.__ownerID)return this;var e=this._map.__ensureOwner(t);return t?qe(e,t):(this.__ownerID=t,this._map=e,this)}},{empty:function(){return Zr||(Zr=qe(qr.empty()))},from:function(t){var e=Xr.empty();return t?t.constructor===Xr?t:e.union(t):e},fromKeys:function(t){return Xr.from(sr(t).flip())}},sr);var Yr=Qr.prototype;Yr[Ue]=Yr.remove,Yr.mergeDeep=Yr.merge,Yr.mergeDeepWith=Yr.mergeWith,Yr.withMutations=br.withMutations,Yr.asMutable=br.asMutable,Yr.asImmutable=br.asImmutable;var Zr,$r=function(t){var e=tn.empty();return t?t.constructor===tn?t:e.merge(t):e},tn=$r;Re.createClass($r,{toString:function(){return this.__toString("OrderedMap {","}")},get:function(t,e){var r=this._map.get(t);return null!=r?this._vector.get(r)[1]:e},clear:function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._map.clear(),this._vector.clear(),this):tn.empty()},set:function(t,e){return be(this,t,e)},remove:function(t){return be(this,t,Be)},wasAltered:function(){return this._map.wasAltered()||this._vector.wasAltered()},__iterate:function(t,e){var r=this;return this._vector.__iterate(function(e){return e&&t(e[1],e[0],r)},e)},__iterator:function(t,e){return this._vector.fromEntrySeq().__iterator(t,e)},__ensureOwner:function(t){if(t===this.__ownerID)return this;var e=this._map.__ensureOwner(t),r=this._vector.__ensureOwner(t);return t?Ie(e,r,t,this.__hash):(this.__ownerID=t,this._map=e,this._vector=r,this) <add>}},{empty:function(){return en||(en=Ie(qr.empty(),Pr.empty()))}},qr),$r.from=$r,$r.prototype[Ue]=$r.prototype.remove;var en,rn=function(t,e){var r=function(t){return this instanceof r?void(this._map=qr(t)):new r(t)},n=Object.keys(t),i=r.prototype=Object.create(nn);i.constructor=r,e&&(i._name=e),i._defaultValues=t,i._keys=n,i.size=n.length;try{sr(t).forEach(function(t,e){Object.defineProperty(r.prototype,e,{get:function(){return this.get(e)},set:function(t){o(this.__ownerID,"Cannot set on an immutable record."),this.set(e,t)}})})}catch(u){}return r};Re.createClass(rn,{toString:function(){return this.__toString(this._name+" {","}")},has:function(t){return this._defaultValues.hasOwnProperty(t)},get:function(t,e){return void 0===e||this.has(t)?this._map.get(t,this._defaultValues[t]):e},clear:function(){if(this.__ownerID)return this._map.clear(),this;var t=Object.getPrototypeOf(this).constructor;return t._empty||(t._empty=ke(this,qr.empty()))},set:function(t,e){if(!this.has(t))throw Error('Cannot set unknown key "'+t+'" on '+this._name);var r=this._map.set(t,e);return this.__ownerID||r===this._map?this:ke(this,r)},remove:function(t){if(null==t||!this.has(t))return this;var e=this._map.remove(t);return this.__ownerID||e===this._map?this:ke(this,e)},keys:function(){return this._map.keys()},values:function(){return this._map.values()},entries:function(){return this._map.entries()},wasAltered:function(){return this._map.wasAltered()},__iterator:function(t,e){return this._map.__iterator(t,e)},__iterate:function(t,e){var r=this;return sr(this._defaultValues).map(function(t,e){return r.get(e)}).__iterate(t,e)},__ensureOwner:function(t){if(t===this.__ownerID)return this;var e=this._map&&this._map.__ensureOwner(t);return t?ke(this,e,t):(this.__ownerID=t,this._map=e,this)}},{},hr);var nn=rn.prototype;nn._name="Record",nn[Ue]=nn.remove,nn.merge=br.merge,nn.mergeWith=br.mergeWith,nn.mergeDeep=br.mergeDeep,nn.mergeDeepWith=br.mergeDeepWith,nn.update=br.update,nn.updateIn=br.updateIn,nn.cursor=br.cursor,nn.withMutations=br.withMutations,nn.asMutable=br.asMutable,nn.asImmutable=br.asImmutable; <add>var un=function(t,e,r){return this instanceof sn?(o(0!==r,"Cannot step a Range by 0"),t=t||0,null==e&&(e=1/0),t===e&&on?on:(r=null==r?1:Math.abs(r),t>e&&(r=-r),this._start=t,this._end=e,this._step=r,void(this.size=Math.max(0,Math.ceil((e-t)/r-1)+1)))):new sn(t,e,r)},sn=un;Re.createClass(un,{toString:function(){return 0===this.size?"Range []":"Range [ "+this._start+"..."+this._end+(this._step>1?" by "+this._step:"")+" ]"},get:function(t,e){return this.has(t)?this._start+C(this,t)*this._step:e},contains:function(t){var e=(t-this._start)/this._step;return e>=0&&this.size>e&&e===Math.floor(e)},slice:function(t,e){return z(t,e,this.size)?this:(t=S(t,this.size),e=q(e,this.size),t>=e?on:new sn(this.get(t,this._end),this.get(e,this._end),this._step))},indexOf:function(t){var e=t-this._start;if(e%this._step===0){var r=e/this._step;if(r>=0&&this.size>r)return r}return-1},lastIndexOf:function(t){return this.indexOf(t)},take:function(t){return this.slice(0,Math.max(0,t))},skip:function(t){return this.slice(Math.max(0,t))},__iterate:function(t,e){for(var r=this.size-1,n=this._step,i=e?this._start+r*n:this._start,u=0;r>=u;u++){if(t(i,u,this)===!1)return u+1;i+=e?-n:n}return u},__iterator:function(t,e){var r=this.size-1,n=this._step,i=e?this._start+r*n:this._start,u=0;return new ir(function(){var s=i;return i+=e?-n:n,u>r?p():v(t,u++,s)})},__deepEquals:function(t){return t instanceof sn?this._start===t._start&&this._end===t._end&&this._step===t._step:Re.superCall(this,sn.prototype,"__deepEquals",[t])}},{},_r);var an=un.prototype;an.__toJS=an.toArray,an.first=Br.first,an.last=Br.last;var on=un(0,0),hn=function(t,e){return 0===e&&_n?_n:this instanceof cn?(this._value=t,void(this.size=null==e?1/0:Math.max(0,e))):new cn(t,e)},cn=hn;Re.createClass(hn,{toString:function(){return 0===this.size?"Repeat []":"Repeat [ "+this._value+" "+this.size+" times ]"},get:function(t,e){return this.has(t)?this._value:e},contains:function(t){return n(this._value,t)},slice:function(t,e){var r=this.size;return t=0>t?Math.max(0,r+t):Math.min(r,t),e=null==e?r:e>0?Math.min(r,e):Math.max(0,r+e),e>t?new cn(this._value,e-t):_n <add>},reverse:function(){return this},indexOf:function(t){return n(this._value,t)?0:-1},lastIndexOf:function(t){return n(this._value,t)?this.size:-1},__iterate:function(t){for(var e=0;this.size>e;e++)if(t(this._value,e,this)===!1)return e+1;return e},__iterator:function(t){var e=this,r=0;return new ir(function(){return e.size>r?v(t,r++,e._value):p()})},__deepEquals:function(t){return t instanceof cn?n(this._value,t._value):Re.superCall(this,cn.prototype,"__deepEquals",[t])}},{},_r);var fn=hn.prototype;fn.last=fn.first,fn.has=an.has,fn.take=an.take,fn.skip=an.skip,fn.__toJS=an.__toJS;var _n=new hn(void 0,0),ln=function(t,e,r,n){this.size=n,this._rootData=t,this._keyPath=e,this._onChange=r};Re.createClass(ln,{equals:function(t){return n(this.deref(),t&&("function"==typeof t.deref?t.deref():t))},deref:function(t){return this._rootData.getIn(this._keyPath,t)},get:function(t,e){if(Array.isArray(t)&&0===t.length)return this;var r=this._rootData.getIn(this._keyPath.concat(t),Be);return r===Be?e:Ce(this,t,r)},set:function(t,e){return Ee(this,function(r){return r.set(t,e)},t)},remove:function(t){return Ee(this,function(e){return e.remove(t)},t)},clear:function(){return Ee(this,function(t){return t.clear()})},update:function(t,e,r){return 1===arguments.length?Ee(this,t):Ee(this,function(n){return n.update(t,e,r)},t)},withMutations:function(t){return Ee(this,function(e){return(e||qr.empty()).withMutations(t)})},cursor:function(t){return Array.isArray(t)&&0===t.length?this:Ae(this,t)},__iterate:function(t,e){var r=this,n=this.deref();return n&&n.__iterate?n.__iterate(function(e,n){return t(Ce(r,n,e),n,r)},e):0},__iterator:function(t,e){var r=this,n=this.deref(),i=n&&n.__iterator&&n.__iterator(tr,e);return new ir(function(){if(!i)return p();var e=i.next();if(e.done)return e;var n=e.value,u=n[0],s=n[1];return v(t,u,Ce(r,u,s),e)})}},{},hr);var vn=ln.prototype;vn[Ue]=vn.remove,vn.getIn=vn.get;var pn=function(t,e,r,n){this.size=n,this._rootData=t,this._keyPath=e,this._onChange=r};Re.createClass(pn,{},{},_r);var mn=pn.prototype;mn.equals=vn.equals,mn.deref=vn.deref,mn.get=vn.get,mn.getIn=vn.getIn,mn.set=vn.set,mn[Ue]=mn.remove=vn.remove,mn.clear=vn.clear,mn.update=vn.update,mn.withMutations=vn.withMutations,mn.cursor=vn.cursor,mn.__iterate=vn.__iterate,mn.__iterator=vn.__iterator; <ide> var yn={Sequence:sr,Map:qr,Vector:Pr,Stack:Nr,Set:Qr,OrderedMap:$r,Record:rn,Range:un,Repeat:hn,is:n,fromJS:xe};return yn}"object"==typeof exports?module.exports=t():"function"==typeof define&&define.amd?define(t):Immutable=t(); <ide>\ No newline at end of file <ide><path>src/Vector.js <ide> class Vector extends IndexedSequence { <ide> } <ide> <ide> static from(sequence) { <del> if (!sequence || sequence.length === 0 || sequence.size === 0) { <add> if (!sequence) { <ide> return Vector.empty(); <ide> } <ide> if (sequence.constructor === Vector) { <ide> return sequence; <ide> } <ide> var isArray = Array.isArray(sequence); <del> if (sequence.size > 0 && sequence.size < SIZE) { <del> return makeVector(0, sequence.size, SHIFT, null, new VNode( <del> isArray ? arrCopy(sequence) : Sequence(sequence).toArray() <add> var size = isArray ? sequence.length : sequence.size; <add> if (size === 0) { <add> return Vector.empty(); <add> } <add> if (size > 0 && size < SIZE) { <add> return makeVector(0, size, SHIFT, null, new VNode( <add> isArray ? <add> arrCopy(sequence) : <add> (sequence.toArray ? sequence : Sequence(sequence)).toArray() <ide> )); <ide> } <ide> if (!isArray) {
3
Text
Text
improve datetime format docs
306726d9e8645aeb9528a3f6c6674d0fe5471374
<ide><path>docs/api-guide/fields.md <ide> A date and time representation. <ide> <ide> Corresponds to `django.db.models.fields.DateTimeField`. <ide> <del>**Signature:** `DateTimeField(format=None, input_formats=None)` <add>**Signature:** `DateTimeField(format=api_settings.DATETIME_FORMAT, input_formats=None)` <ide> <del>* `format` - A string representing the output format. If not specified, this defaults to the same value as the `DATETIME_FORMAT` settings key, which will be `'iso-8601'` unless set. Setting to a format string indicates that `to_representation` return values should be coerced to string output. Format strings are described below. Setting this value to `None` indicates that Python `datetime` objects should be returned by `to_representation`. In this case the datetime encoding will be determined by the renderer. <add>* `format` - A string representing the output format. If not specified, this defaults to the same value as the `DATETIME_FORMAT` settings key, which will be `'iso-8601'` unless set. Setting to a format string indicates that `to_representation` return values should be coerced to string output. Format strings are described below. Setting this value to `None` indicates that Python `datetime` objects should be returned by `to_representation`. In this case the datetime encoding will be determined by the renderer. <ide> * `input_formats` - A list of strings representing the input formats which may be used to parse the date. If not specified, the `DATETIME_INPUT_FORMATS` setting will be used, which defaults to `['iso-8601']`. <ide> <ide> #### `DateTimeField` format strings. <ide> A date representation. <ide> <ide> Corresponds to `django.db.models.fields.DateField` <ide> <del>**Signature:** `DateField(format=None, input_formats=None)` <add>**Signature:** `DateField(format=api_settings.DATE_FORMAT, input_formats=None)` <ide> <ide> * `format` - A string representing the output format. If not specified, this defaults to the same value as the `DATE_FORMAT` settings key, which will be `'iso-8601'` unless set. Setting to a format string indicates that `to_representation` return values should be coerced to string output. Format strings are described below. Setting this value to `None` indicates that Python `date` objects should be returned by `to_representation`. In this case the date encoding will be determined by the renderer. <ide> * `input_formats` - A list of strings representing the input formats which may be used to parse the date. If not specified, the `DATE_INPUT_FORMATS` setting will be used, which defaults to `['iso-8601']`. <ide> A time representation. <ide> <ide> Corresponds to `django.db.models.fields.TimeField` <ide> <del>**Signature:** `TimeField(format=None, input_formats=None)` <add>**Signature:** `TimeField(format=api_settings.TIME_FORMAT, input_formats=None)` <ide> <ide> * `format` - A string representing the output format. If not specified, this defaults to the same value as the `TIME_FORMAT` settings key, which will be `'iso-8601'` unless set. Setting to a format string indicates that `to_representation` return values should be coerced to string output. Format strings are described below. Setting this value to `None` indicates that Python `time` objects should be returned by `to_representation`. In this case the time encoding will be determined by the renderer. <ide> * `input_formats` - A list of strings representing the input formats which may be used to parse the date. If not specified, the `TIME_INPUT_FORMATS` setting will be used, which defaults to `['iso-8601']`.
1
Go
Go
simplify logical expression
90e2459ecb82c9cd0f231a04776272c6ffe435e4
<ide><path>registry/registry.go <ide> func ContinueOnError(err error) bool { <ide> case *client.UnexpectedHTTPResponseError: <ide> return true <ide> case error: <del> if val := strings.Contains(err.Error(), strings.ToLower(syscall.ENOSPC.Error())); val { <del> return false <del> } <add> return !strings.Contains(err.Error(), strings.ToLower(syscall.ENOSPC.Error())) <ide> } <ide> // let's be nice and fallback if the error is a completely <ide> // unexpected one.
1
Text
Text
add details for catalan and danish
35425d7e261763ea4bd2546c42fda692cf81ca91
<ide><path>website/docs/usage/v3-1.md <ide> See the [models directory](/models) for an overview of all available trained <ide> pipelines and the [training guide](/usage/training) for details on how to train <ide> your own. <ide> <del><!-- TODO: thank contributors and update with final numbers --> <del> <del>| Package | Language | Tagger | Parser |  NER | <del>| ------------------------------------------------- | -------- | -----: | -----: | ---: | <del>| [`ca_core_news_sm`](/models/ca#ca_core_news_sm) | Catalan | | | | <del>| [`ca_core_news_md`](/models/ca#ca_core_news_md) | Catalan | | | | <del>| [`ca_core_news_lg`](/models/ca#ca_core_news_lg) | Catalan | | | | <del>| [`ca_core_news_trf`](/models/ca#ca_core_news_trf) | Catalan | | | | <del>| [`da_core_news_trf`](/models/da#da_core_news_trf) | Danish | | | | <add>Thanks to Carlos Rodríguez Penagos and the <add>[Barcelona Supercomputing Center](https://temu.bsc.es/) for their contributions <add>for Catalan and to Kenneth Enevoldsen for Danish. For additional Danish <add>pipelines, check out [DaCy](https://github.com/KennethEnevoldsen/DaCy). <add> <add>| Package | Language | UPOS | Parser LAS |  NER F | <add>| ------------------------------------------------- | -------- | ---: | ---------: | -----: | <add>| [`ca_core_news_sm`](/models/ca#ca_core_news_sm) | Catalan | 98.2 | 87.4 | 79.8 | <add>| [`ca_core_news_md`](/models/ca#ca_core_news_md) | Catalan | 98.3 | 88.2 | 84.0 | <add>| [`ca_core_news_lg`](/models/ca#ca_core_news_lg) | Catalan | 98.5 | 88.4 | 84.2 | <add>| [`ca_core_news_trf`](/models/ca#ca_core_news_trf) | Catalan | 98.9 | 93.0 | 91.2 | <add>| [`da_core_news_trf`](/models/da#da_core_news_trf) | Danish | 98.0 | 85.0 | 82.9 | <ide> <ide> ### Resizable text classification architectures {#resizable-textcat} <ide>
1
Javascript
Javascript
remove trailing space
4ec384f36981a9e5e4b4104f5e3e729be9123a60
<ide><path>src/renderers/webgl/WebGLExtensions.js <ide> function WebGLExtensions( gl ) { <ide> <ide> default: <ide> <del> if ( isWebGL2 && <add> if ( isWebGL2 && <ide> [ 'ANGLE_instanced_arrays', <ide> 'OES_texture_float', <ide> 'OES_texture_half_float',
1
Python
Python
add test for issue
52ef51f36e005a5d7033c21d08cfae17a561ebca
<ide><path>spacy/tests/regression/test_issue1889.py <add># coding: utf-8 <add>from __future__ import unicode_literals <add>from ...lang.lex_attrs import is_stop <add>from ...lang.en.stop_words import STOP_WORDS <add> <add>import pytest <add> <add> <add>@pytest.mark.parametrize('word', ['the']) <add>def test_lex_attrs_stop_words_case_sensitivity(word): <add> assert is_stop(word, STOP_WORDS) == is_stop(word.upper(), STOP_WORDS)
1
Javascript
Javascript
convert premature close to aborterror
3f0b62375b3a4edc8365b803749e8dd5abc706b0
<ide><path>lib/internal/webstreams/adapters.js <ide> const { <ide> ERR_INVALID_STATE, <ide> ERR_STREAM_PREMATURE_CLOSE, <ide> }, <add> AbortError, <ide> } = require('internal/errors'); <ide> <ide> const { <ide> function newWritableStreamFromStreamWritable(streamWritable) { <ide> } <ide> <ide> const cleanup = finished(streamWritable, (error) => { <add> if (error?.code === 'ERR_STREAM_PREMATURE_CLOSE') { <add> const err = new AbortError(); <add> err.cause = error; <add> error = err; <add> } <add> <ide> cleanup(); <ide> // This is a protection against non-standard, legacy streams <ide> // that happen to emit an error event again after finished is called. <ide> function newWritableStreamFromStreamWritable(streamWritable) { <ide> closed = undefined; <ide> return; <ide> } <del> controller.error(new ERR_STREAM_PREMATURE_CLOSE()); <add> controller.error(new AbortError()); <ide> controller = undefined; <ide> }); <ide> <ide> function newReadableStreamFromStreamReadable(streamReadable) { <ide> streamReadable.pause(); <ide> <ide> const cleanup = finished(streamReadable, (error) => { <add> if (error?.code === 'ERR_STREAM_PREMATURE_CLOSE') { <add> const err = new AbortError(); <add> err.cause = error; <add> error = err; <add> } <add> <ide> cleanup(); <ide> // This is a protection against non-standard, legacy streams <ide> // that happen to emit an error event again after finished is called. <ide><path>test/parallel/test-whatwg-webstreams-adapters-to-readablestream.js <ide> const { <ide> const reader = readableStream.getReader(); <ide> <ide> assert.rejects(reader.closed, { <del> code: 'ERR_STREAM_PREMATURE_CLOSE', <add> code: 'ABORT_ERR', <ide> }); <ide> <ide> readable.on('end', common.mustNotCall()); <ide><path>test/parallel/test-whatwg-webstreams-adapters-to-readablewritablepair.js <ide> const { <ide> const writer = writable.getWriter(); <ide> <ide> assert.rejects(reader.closed, { <del> code: 'ERR_STREAM_PREMATURE_CLOSE', <add> code: 'ABORT_ERR', <ide> }); <ide> <ide> assert.rejects(writer.closed, { <del> code: 'ERR_STREAM_PREMATURE_CLOSE', <add> code: 'ABORT_ERR', <ide> }); <ide> <ide> duplex.destroy(); <ide> const { <ide> <ide> reader.closed.then(common.mustCall()); <ide> assert.rejects(writer.closed, { <del> code: 'ERR_STREAM_PREMATURE_CLOSE', <add> code: 'ABORT_ERR', <ide> }); <ide> <ide> duplex.end(); <ide><path>test/parallel/test-whatwg-webstreams-adapters-to-writablestream.js <ide> class TestWritable extends Writable { <ide> const writableStream = newWritableStreamFromStreamWritable(writable); <ide> <ide> assert.rejects(writableStream.close(), { <del> code: 'ERR_STREAM_PREMATURE_CLOSE' <add> code: 'ABORT_ERR' <ide> }); <ide> <ide> writable.end();
4
Go
Go
fix data race in libcontainerd
8e9fbc8f5fc5759eb7f26ec998f227994ff6c642
<ide><path>libcontainerd/remote_linux.go <ide> func (r *remote) handleConnectionChange() { <ide> transientFailureCount = 0 <ide> if utils.IsProcessAlive(r.daemonPid) { <ide> utils.KillProcess(r.daemonPid) <del> <-r.daemonWaitCh <ide> } <add> <-r.daemonWaitCh <ide> if err := r.runContainerdDaemon(); err != nil { //FIXME: Handle error <ide> logrus.Errorf("error restarting containerd: %v", err) <ide> }
1
Javascript
Javascript
add redirection and inline documentation
3fbf4b8d29a19d6f9891b48662726b1209a061d3
<ide><path>packages/ember-routing/lib/system/route.js <ide> var get = Ember.get, set = Ember.set, <ide> <ide> <ide> Ember.Route = Ember.Object.extend({ <add> /** <add> Transition into another route. Optionally supply a model for the <add> route in question. The model will be serialized into the URL <add> using the `serialize` hook. <add> <add> @param {String} name the name of the route <add> @param {...Object} models the <add> */ <add> transitionTo: function() { <add> this.transitioned = true; <add> return this.router.transitionTo.apply(this.router, arguments); <add> }, <add> <ide> /** <ide> @private <ide> <ide> Ember.Route = Ember.Object.extend({ <ide> setup: function(context) { <ide> var container = this.container; <ide> <add> this.transitioned = false; <add> this.redirect(context); <add> <add> if (this.transitioned) { return; } <add> <ide> var templateName = this.templateName, <ide> controller = container.lookup('controller:' + templateName); <ide> <ide> Ember.Route = Ember.Object.extend({ <ide> this.renderTemplates(context); <ide> }, <ide> <add> /** <add> A hook you can implement to optionally redirect to another route. <add> <add> If you call `this.transitionTo` from inside of this hook, this route <add> will not be entered in favor of the other hook. <add> <add> @param {Object} model the model for this route <add> */ <add> redirect: Ember.K, <add> <add> /** <add> @private <add> <add> The hook called by `router.js` to convert parameters into the context <add> for this handler. The public Ember hook is `model`. <add> */ <ide> deserialize: function(params) { <ide> var model = this.model(params); <ide> return this.currentModel = model; <ide> }, <ide> <del> serialize: function(model, params) { <del> if (params.length !== 1) { return; } <add> /** <add> A hook you can implement to convert the URL into the model for <add> this route. <ide> <del> var name = params[0], object = {}; <del> object[name] = get(model, 'id'); <add> ```js <add> App.Route.map(function(match) { <add> match("/posts/:post_id").to("post"); <add> }); <add> ``` <ide> <del> return object; <del> }, <add> The model for the `post` route is `App.Post.find(params.post_id)`. <add> <add> By default, if your route has a dynamic segment ending in `_id`: <ide> <add> * The model class is determined from the segment (`post_id`'s <add> class is `App.Post`) <add> * The find method is called on the model class with the value of <add> the dynamic segment. <add> <add> @param {Object} params the parameters extracted from the URL <add> */ <ide> model: function(params) { <ide> var match, name, value; <ide> <ide> Ember.Route = Ember.Object.extend({ <ide> return modelClass.find(value); <ide> }, <ide> <del> setupControllers: function(controller, context) { <add> /** <add> A hook you can implement to convert the route's model into parameters <add> for the URL. <add> <add> ```js <add> App.Route.map(function(match) { <add> match("/posts/:post_id").to("post"); <add> }); <add> <add> App.PostRoute = Ember.Route.extend({ <add> model: function(params) { <add> // the server returns `{ id: 12 }` <add> return jQuery.getJSON("/posts/" + params.post_id); <add> }, <add> <add> serialize: function(model) { <add> // this will make the URL `/posts/12` <add> return { post_id: model.id }; <add> } <add> }); <add> ``` <add> <add> The default `serialize` method inserts the model's `id` into the <add> route's dynamic segment (in this case, `:post_id`). <add> <add> This method is called when `transitionTo` is called with a context <add> in order to populate the URL. <add> <add> @param {Object} model the route's model <add> @param {Array} params an Array of parameter names for the current <add> route (in the example, `['post_id']`. <add> @return {Object} the serialized parameters <add> */ <add> serialize: function(model, params) { <add> if (params.length !== 1) { return; } <add> <add> var name = params[0], object = {}; <add> object[name] = get(model, 'id'); <add> <add> return object; <add> }, <add> <add> /** <add> A hook you can use to setup the necessary controllers for the current <add> route. <add> <add> This method is called with the controller for the current route and the <add> model supplied by the `model` hook. <add> <add> ```js <add> App.Route.map(function(match) { <add> match("/posts/:post_id").to("post"); <add> }); <add> ``` <add> <add> For the `post` route, the controller is `App.PostController`. <add> <add> By default, the `setupController` hook sets the `content` property of <add> the controller to the `model`. <add> <add> If no explicit controller is defined, the route will automatically create <add> an appropriate controller for the model: <add> <add> * if the model is an `Ember.Array` (including record arrays from Ember <add> Data), the controller is an `Ember.ArrayController`. <add> * otherwise, the controller is an `Ember.ObjectController`. <add> <add> This means that your template will get a proxy for the model as its <add> context, and you can act as though the model itself was the context. <add> */ <add> setupControllers: function(controller, model) { <ide> if (controller) { <del> controller.set('content', context); <add> controller.set('content', model); <ide> } <ide> }, <ide> <add> /** <add> Returns the controller for a particular route. <add> <add> ```js <add> App.PostRoute = Ember.Route.extend({ <add> setupControllers: function(controller, post) { <add> this._super(controller, post); <add> this.controllerFor('posts').set('currentPost', post); <add> } <add> }); <add> ``` <add> <add> By default, the controller for `post` is the shared instance of <add> `App.PostController`. <add> <add> @param {String} name the name of the route <add> @return {Ember.Controller} <add> */ <ide> controllerFor: function(name) { <ide> return this.container.lookup('controller:' + name); <ide> }, <ide> <add> /** <add> Returns the current model for a given route. <add> <add> This is the object returned by the `model` hook of the route <add> in question. <add> <add> @param {String} name the name of the route <add> @return {Object} the model object <add> */ <ide> modelFor: function(name) { <ide> return this.container.lookup('route:' + name).currentModel; <ide> }, <ide><path>packages/ember-routing/tests/integration/basic_test.js <ide> test("It is possible to get the model from a parent route", function() { <ide> }); <ide> }); <ide> <add>test("A redirection hook is provided", function() { <add> Router.map(function(match) { <add> match("/").to("choose"); <add> match("/home").to("home"); <add> }); <add> <add> var chooseFollowed = 0, destination; <add> <add> App.ChooseRoute = Ember.Route.extend({ <add> redirect: function() { <add> if (destination) { <add> this.transitionTo(destination); <add> } <add> }, <add> <add> setupControllers: function() { <add> chooseFollowed++; <add> } <add> }); <add> <add> destination = 'home'; <add> <add> bootApplication(); <add> <add> equal(chooseFollowed, 0, "The choose route wasn't entered since a transition occurred"); <add> equal(Ember.$("h3:contains(Hours)", "#qunit-fixture").length, 1, "The home template was rendered"); <add>}); <add> <ide> // TODO: Parent context change
2
Ruby
Ruby
add audit for formula.factory
50b94ada1b0dd0462ab3bf252243b6f1892f3dd4
<ide><path>Library/Homebrew/cmd/audit.rb <ide> def audit_deps <ide> def audit_conflicts <ide> f.conflicts.each do |c| <ide> begin <del> Formula.factory(c.name) <add> Formulary.factory(c.name) <ide> rescue FormulaUnavailableError <ide> problem "Can't find conflicting formula #{c.name.inspect}." <ide> end <ide> def audit_text <ide> if text =~ /system\s+['"]xcodebuild/ && text !~ /SYMROOT=/ <ide> problem "xcodebuild should be passed an explicit \"SYMROOT\"" <ide> end <add> <add> if text =~ /Formula\.factory\(/ <add> problem "\"Formula.factory(name)\" is deprecated in favor of \"Formula[name]\"" <add> end <ide> end <ide> <ide> def audit_line(line)
1
Text
Text
remove unnecessary backquote
11be70cf5ed62c0f15a7e6a9693fc5e0b5878593
<ide><path>libnetwork/docs/remote.md <ide> When the proxy is asked to create a network, the remote process shall receive a <ide> <ide> The response indicating success is empty: <ide> <del> `{}` <add> {} <ide> <ide> ### Delete network <ide> <ide> When the proxy receives a DiscoverNew notification, the remote process shall rec <ide> <ide> The response indicating success is empty: <ide> <del> `{}` <add> {} <ide> <ide> * Node Discovery <ide> <ide> When the proxy receives a DiscoverDelete notification, the remote process shall <ide> <ide> The response indicating success is empty: <ide> <del> `{}` <add> {} <ide> <ide> * Node Discovery <ide>
1
Python
Python
fix savedir for by epoch
3486a92a5725c6b35798b64d8ce973aa28d78252
<ide><path>examples/pytorch/translation/run_translation_no_trainer.py <ide> def postprocess_text(preds, labels): <ide> ) <ide> <ide> if args.checkpointing_steps == "epoch": <del> output_dir = f"step_{completed_steps}" <add> output_dir = f"epoch_{epoch}" <ide> if args.output_dir is not None: <ide> output_dir = os.path.join(args.output_dir, output_dir) <ide> accelerator.save_state(output_dir)
1
Go
Go
fix unhandled errors in tests (ineffassign)
85ed9b8746551b10e8d0b6d7f454b684ba9be6b2
<ide><path>libnetwork/libnetwork_test.go <ide> func TestEndpointMultipleJoins(t *testing.T) { <ide> sbx1, err := controller.NewSandbox(containerID, <ide> libnetwork.OptionHostname("test"), <ide> libnetwork.OptionDomainname("docker.io"), <del> libnetwork.OptionExtraHost("web", "192.168.0.1")) <add> libnetwork.OptionExtraHost("web", "192.168.0.1"), <add> ) <add> if err != nil { <add> t.Fatal(err) <add> } <ide> defer func() { <ide> if err := sbx1.Delete(); err != nil { <ide> t.Fatal(err) <ide> } <ide> }() <ide> <ide> sbx2, err := controller.NewSandbox("c2") <add> if err != nil { <add> t.Fatal(err) <add> } <ide> defer func() { <ide> if err := sbx2.Delete(); err != nil { <ide> t.Fatal(err)
1
Python
Python
add test for no resultset rtn type
4dc1778a64f1adac212e97919248d020ed8447de
<ide><path>tests/providers/exasol/hooks/test_exasol.py <ide> def test_run_no_queries(self): <ide> self.db_hook.run(sql=[]) <ide> assert err.value.args[0] == "List of SQL statements is empty" <ide> <add> def test_no_result_set(self): <add> """Queries like DROP and SELECT are of type rowCount (not resultSet), <add> which raises an error in pyexasol if trying to iterate over them""" <add> self.cur.result_type = mock.Mock() <add> self.cur.result_type.return_value = 'rowCount' <add> <add> sql = 'SQL' <add> self.db_hook.run(sql) <add> <ide> def test_bulk_load(self): <ide> with pytest.raises(NotImplementedError): <ide> self.db_hook.bulk_load('table', '/tmp/file')
1
Text
Text
fix grammatical issues in readme
7e56f8653c95a3d89efee8d276f41b982dab28bf
<ide><path>COLLABORATOR_GUIDE.md <ide> As a collaborator, you will be involved with axios with some administrative resp <ide> <ide> 1. __Adhere to and help enforce the Code of Conduct.__ It is expected that you have read the [code of conduct](https://github.com/axios/axios/blob/master/CODE_OF_CONDUCT.md) and that you agree to live by it. This community should be friendly and welcoming. <ide> <del>1. __Triage issues.__ As a collaborator, you may help sort through the issues that are reported. Issues vary from bugs, regressions, feature requests, questions, etc. Apply the appropriate label(s) and respond as needed. If it is a legitimate request, please address it, otherwise feel free to close the issue and include a comment with a suggestion on where to find support. If an issue has been inactive for more than a week (i.e., the owner of the issue hasn’t responded to you), close the issue with a note indicating stales issues are closed; it can always be reopened if needed. In the case of issues that require a code change, encourage the owner to submit a PR. For less complex code changes, add a very simple and detailed checklist, apply the “first-timers-only” label, and encourage a newcomer to open source to get involved. <add>1. __Triage issues.__ As a collaborator, you may help sort through the issues that are reported. Issues vary from bugs, regressions, feature requests, questions, etc. Apply the appropriate label(s) and respond as needed. If it is a legitimate request, please address it, otherwise feel free to close the issue and include a comment with a suggestion on where to find support. If an issue has been inactive for more than a week (i.e., the owner of the issue hasn’t responded to you), close the issue with a note indicating stale issues are closed; it can always be reopened if needed. In the case of issues that require a code change, encourage the owner to submit a PR. For less complex code changes, add a very simple and detailed checklist, apply the “first-timers-only” label, and encourage a newcomer to open source to get involved. <ide> <ide> 1. __Answer questions.__ It is not expected that you provide answers to questions that aren’t relevant, nor do you need to mentor people on how to use JavaScript, etc. If the question is not directly about the module, please close the issue. If the question stems from poor documentation, please update the docs and consider adding a code example. In any event try to be helpful and remember that there’s no such thing as a stupid question. <ide> <ide><path>README.md <ide> The response for a request contains the following information. <ide> statusText: 'OK', <ide> <ide> // `headers` the HTTP headers that the server responded with <del> // All header names are lower cased and can be accessed using the bracket notation. <add> // All header names are lowercase and can be accessed using the bracket notation. <ide> // Example: `response.headers['content-type']` <ide> headers: {}, <ide> <ide> cancel(); <ide> ``` <ide> <ide> > Note: you can cancel several requests with the same cancel token/abort controller. <del>> If a cancellation token is already cancelled at the moment of starting an Axios request, then the request is cancelled immediately, without any attempts to make real request. <add>> If a cancellation token is already cancelled at the moment of starting an Axios request, then the request is cancelled immediately, without any attempts to make a real request. <ide> <ide> > During the transition period, you can use both cancellation APIs, even for the same request: <ide> <ide> try { <ide> <ide> ## Online one-click setup <ide> <del>You can use Gitpod an online IDE(which is free for Open Source) for contributing or running the examples online. <add>You can use Gitpod, an online IDE(which is free for Open Source) for contributing or running the examples online. <ide> <ide> [![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/axios/axios/blob/master/examples/server.js) <ide>
2
PHP
PHP
use new table stuff in routes command
32d39a0d7deb70c0dccd076f23f774b1a16976e1
<ide><path>src/Illuminate/Foundation/Console/RoutesCommand.php <ide> class RoutesCommand extends Command { <ide> */ <ide> protected $routes; <ide> <del> /** <del> * The table helper set. <del> * <del> * @var \Symfony\Component\Console\Helper\TableHelper <del> */ <del> protected $table; <del> <ide> /** <ide> * The table headers for the command. <ide> * <ide> public function __construct(Router $router) <ide> */ <ide> public function fire() <ide> { <del> $this->table = $this->getHelperSet()->get('table'); <del> <ide> if (count($this->routes) == 0) <ide> { <ide> return $this->error("Your application doesn't have any routes."); <ide> protected function getRouteInformation(Route $route) <ide> */ <ide> protected function displayRoutes(array $routes) <ide> { <del> $this->table->setHeaders($this->headers)->setRows($routes); <del> <del> $this->table->render($this->getOutput()); <add> $this->table($this->headers, $routes); <ide> } <ide> <ide> /**
1
Javascript
Javascript
flow strict scrollresponder
fb4825a2c65fba3aa905f7defb7d0c125fff644d
<ide><path>Libraries/Components/ScrollResponder.js <ide> const warning = require('fbjs/lib/warning'); <ide> <ide> const {ScrollViewManager} = require('NativeModules'); <ide> <add>import type {PressEvent, ScrollEvent} from 'CoreEventTypes'; <add>import type {KeyboardEvent} from 'Keyboard'; <ide> import type EmitterSubscription from 'EmitterSubscription'; <ide> <ide> /** <ide> type State = { <ide> observedScrollSinceBecomingResponder: boolean, <ide> becameResponderWhileAnimating: boolean, <ide> }; <del>type Event = Object; <ide> <ide> const ScrollResponderMixin = { <ide> _subscriptionKeyboardWillShow: (null: ?EmitterSubscription), <ide> const ScrollResponderMixin = { <ide> * true. <ide> * <ide> */ <del> scrollResponderHandleStartShouldSetResponder: function(e: Event): boolean { <add> scrollResponderHandleStartShouldSetResponder: function( <add> e: PressEvent, <add> ): boolean { <ide> const currentlyFocusedTextInput = TextInputState.currentlyFocusedField(); <ide> <ide> if ( <ide> const ScrollResponderMixin = { <ide> * Invoke this from an `onStartShouldSetResponderCapture` event. <ide> */ <ide> scrollResponderHandleStartShouldSetResponderCapture: function( <del> e: Event, <add> e: PressEvent, <ide> ): boolean { <ide> // The scroll view should receive taps instead of its descendants if: <ide> // * it is already animating/decelerating <ide> const ScrollResponderMixin = { <ide> if ( <ide> keyboardNeverPersistTaps && <ide> currentlyFocusedTextInput != null && <add> e.target && <ide> !TextInputState.isTextInput(e.target) <ide> ) { <ide> return true; <ide> const ScrollResponderMixin = { <ide> /** <ide> * Invoke this from an `onTouchEnd` event. <ide> * <del> * @param {SyntheticEvent} e Event. <add> * @param {PressEvent} e Event. <ide> */ <del> scrollResponderHandleTouchEnd: function(e: Event) { <add> scrollResponderHandleTouchEnd: function(e: PressEvent) { <ide> const nativeEvent = e.nativeEvent; <ide> this.state.isTouching = nativeEvent.touches.length !== 0; <ide> this.props.onTouchEnd && this.props.onTouchEnd(e); <ide> const ScrollResponderMixin = { <ide> /** <ide> * Invoke this from an `onTouchCancel` event. <ide> * <del> * @param {SyntheticEvent} e Event. <add> * @param {PressEvent} e Event. <ide> */ <del> scrollResponderHandleTouchCancel: function(e: Event) { <add> scrollResponderHandleTouchCancel: function(e: PressEvent) { <ide> this.state.isTouching = false; <ide> this.props.onTouchCancel && this.props.onTouchCancel(e); <ide> }, <ide> <ide> /** <ide> * Invoke this from an `onResponderRelease` event. <ide> */ <del> scrollResponderHandleResponderRelease: function(e: Event) { <add> scrollResponderHandleResponderRelease: function(e: PressEvent) { <ide> this.props.onResponderRelease && this.props.onResponderRelease(e); <ide> <ide> // By default scroll views will unfocus a textField <ide> const ScrollResponderMixin = { <ide> } <ide> }, <ide> <del> scrollResponderHandleScroll: function(e: Event) { <add> scrollResponderHandleScroll: function(e: ScrollEvent) { <ide> this.state.observedScrollSinceBecomingResponder = true; <ide> this.props.onScroll && this.props.onScroll(e); <ide> }, <ide> <ide> /** <ide> * Invoke this from an `onResponderGrant` event. <ide> */ <del> scrollResponderHandleResponderGrant: function(e: Event) { <add> scrollResponderHandleResponderGrant: function(e: ScrollEvent) { <ide> this.state.observedScrollSinceBecomingResponder = false; <ide> this.props.onResponderGrant && this.props.onResponderGrant(e); <ide> this.state.becameResponderWhileAnimating = this.scrollResponderIsAnimating(); <ide> const ScrollResponderMixin = { <ide> * <ide> * Invoke this from an `onScrollBeginDrag` event. <ide> */ <del> scrollResponderHandleScrollBeginDrag: function(e: Event) { <add> scrollResponderHandleScrollBeginDrag: function(e: ScrollEvent) { <ide> FrameRateLogger.beginScroll(); // TODO: track all scrolls after implementing onScrollEndAnimation <ide> this.props.onScrollBeginDrag && this.props.onScrollBeginDrag(e); <ide> }, <ide> <ide> /** <ide> * Invoke this from an `onScrollEndDrag` event. <ide> */ <del> scrollResponderHandleScrollEndDrag: function(e: Event) { <add> scrollResponderHandleScrollEndDrag: function(e: ScrollEvent) { <ide> const {velocity} = e.nativeEvent; <ide> // - If we are animating, then this is a "drag" that is stopping the scrollview and momentum end <ide> // will fire. <ide> const ScrollResponderMixin = { <ide> /** <ide> * Invoke this from an `onMomentumScrollBegin` event. <ide> */ <del> scrollResponderHandleMomentumScrollBegin: function(e: Event) { <add> scrollResponderHandleMomentumScrollBegin: function(e: ScrollEvent) { <ide> this.state.lastMomentumScrollBeginTime = performanceNow(); <ide> this.props.onMomentumScrollBegin && this.props.onMomentumScrollBegin(e); <ide> }, <ide> <ide> /** <ide> * Invoke this from an `onMomentumScrollEnd` event. <ide> */ <del> scrollResponderHandleMomentumScrollEnd: function(e: Event) { <add> scrollResponderHandleMomentumScrollEnd: function(e: ScrollEvent) { <ide> FrameRateLogger.endScroll(); <ide> this.state.lastMomentumScrollEndTime = performanceNow(); <ide> this.props.onMomentumScrollEnd && this.props.onMomentumScrollEnd(e); <ide> const ScrollResponderMixin = { <ide> * responder). The `onResponderReject` won't fire in that case - it only <ide> * fires when a *current* responder rejects our request. <ide> * <del> * @param {SyntheticEvent} e Touch Start event. <add> * @param {PressEvent} e Touch Start event. <ide> */ <del> scrollResponderHandleTouchStart: function(e: Event) { <add> scrollResponderHandleTouchStart: function(e: PressEvent) { <ide> this.state.isTouching = true; <ide> this.props.onTouchStart && this.props.onTouchStart(e); <ide> }, <ide> const ScrollResponderMixin = { <ide> * responder). The `onResponderReject` won't fire in that case - it only <ide> * fires when a *current* responder rejects our request. <ide> * <del> * @param {SyntheticEvent} e Touch Start event. <add> * @param {PressEvent} e Touch Start event. <ide> */ <del> scrollResponderHandleTouchMove: function(e: Event) { <add> scrollResponderHandleTouchMove: function(e: PressEvent) { <ide> this.props.onTouchMove && this.props.onTouchMove(e); <ide> }, <ide> <ide> const ScrollResponderMixin = { <ide> * Components can pass what node to use by defining a `getScrollableNode` <ide> * function otherwise `this` is used. <ide> */ <del> scrollResponderGetScrollableNode: function(): any { <add> scrollResponderGetScrollableNode: function(): ?number { <ide> return this.getScrollableNode <ide> ? this.getScrollableNode() <ide> : ReactNative.findNodeHandle(this); <ide> const ScrollResponderMixin = { <ide> * This method should be used as the callback to onFocus in a TextInputs' <ide> * parent view. Note that any module using this mixin needs to return <ide> * the parent view's ref in getScrollViewRef() in order to use this method. <del> * @param {any} nodeHandle The TextInput node handle <add> * @param {number} nodeHandle The TextInput node handle <ide> * @param {number} additionalOffset The scroll view's bottom "contentInset". <ide> * Default is 0. <ide> * @param {bool} preventNegativeScrolling Whether to allow pulling the content <ide> * down to make it meet the keyboard's top. Default is false. <ide> */ <ide> scrollResponderScrollNativeHandleToKeyboard: function( <del> nodeHandle: any, <add> nodeHandle: number, <ide> additionalOffset?: number, <ide> preventNegativeScrollOffset?: boolean, <ide> ) { <ide> const ScrollResponderMixin = { <ide> this.preventNegativeScrollOffset = false; <ide> }, <ide> <del> scrollResponderTextInputFocusError: function(e: Event) { <del> console.error('Error measuring text field: ', e); <add> scrollResponderTextInputFocusError: function(msg: string) { <add> console.error('Error measuring text field: ', msg); <ide> }, <ide> <ide> /** <ide> const ScrollResponderMixin = { <ide> * relevant to you. (For example, only if you receive these callbacks after <ide> * you had explicitly focused a node etc). <ide> */ <del> scrollResponderKeyboardWillShow: function(e: Event) { <add> scrollResponderKeyboardWillShow: function(e: KeyboardEvent) { <ide> this.keyboardWillOpenTo = e; <ide> this.props.onKeyboardWillShow && this.props.onKeyboardWillShow(e); <ide> }, <ide> <del> scrollResponderKeyboardWillHide: function(e: Event) { <add> scrollResponderKeyboardWillHide: function(e: KeyboardEvent) { <ide> this.keyboardWillOpenTo = null; <ide> this.props.onKeyboardWillHide && this.props.onKeyboardWillHide(e); <ide> }, <ide> <del> scrollResponderKeyboardDidShow: function(e: Event) { <add> scrollResponderKeyboardDidShow: function(e: KeyboardEvent) { <ide> // TODO(7693961): The event for DidShow is not available on iOS yet. <ide> // Use the one from WillShow and do not assign. <ide> if (e) { <ide> const ScrollResponderMixin = { <ide> this.props.onKeyboardDidShow && this.props.onKeyboardDidShow(e); <ide> }, <ide> <del> scrollResponderKeyboardDidHide: function(e: Event) { <add> scrollResponderKeyboardDidHide: function(e: KeyboardEvent) { <ide> this.keyboardWillOpenTo = null; <ide> this.props.onKeyboardDidHide && this.props.onKeyboardDidHide(e); <ide> },
1
Java
Java
reuse empty class array constant in classutils
2209e7cb9201d2fa3fe265d98b4dd5dd2db462fc
<ide><path>spring-core/src/main/java/org/springframework/util/ClassUtils.java <ide> public abstract class ClassUtils { <ide> /** Prefix for internal non-primitive array class names: {@code "[L"}. */ <ide> private static final String NON_PRIMITIVE_ARRAY_PREFIX = "[L"; <ide> <add> /** A reusable empty class array constant. */ <add> private static final Class<?>[] EMPTY_CLASS_ARRAY = {}; <add> <ide> /** The package separator character: {@code '.'}. */ <ide> private static final char PACKAGE_SEPARATOR = '.'; <ide> <ide> public static boolean isAssignable(Class<?> lhsType, Class<?> rhsType) { <ide> } <ide> if (lhsType.isPrimitive()) { <ide> Class<?> resolvedPrimitive = primitiveWrapperTypeMap.get(rhsType); <del> if (lhsType == resolvedPrimitive) { <del> return true; <del> } <add> return (lhsType == resolvedPrimitive); <ide> } <ide> else { <ide> Class<?> resolvedWrapper = primitiveTypeToWrapperMap.get(rhsType); <del> if (resolvedWrapper != null && lhsType.isAssignableFrom(resolvedWrapper)) { <del> return true; <del> } <add> return (resolvedWrapper != null && lhsType.isAssignableFrom(resolvedWrapper)); <ide> } <del> return false; <ide> } <ide> <ide> /** <ide> public static String classNamesToString(@Nullable Collection<Class<?>> classes) <ide> * @since 3.1 <ide> * @see StringUtils#toStringArray <ide> */ <del> public static Class<?>[] toClassArray(Collection<Class<?>> collection) { <del> return collection.toArray(new Class<?>[0]); <add> public static Class<?>[] toClassArray(@Nullable Collection<Class<?>> collection) { <add> return (!CollectionUtils.isEmpty(collection) ? collection.toArray(EMPTY_CLASS_ARRAY) : EMPTY_CLASS_ARRAY); <ide> } <ide> <ide> /** <ide> public static String getQualifiedMethodName(Method method, @Nullable Class<?> cl <ide> * @param clazz the clazz to analyze <ide> * @param paramTypes the parameter types of the method <ide> * @return whether the class has a corresponding constructor <del> * @see Class#getMethod <add> * @see Class#getConstructor <ide> */ <ide> public static boolean hasConstructor(Class<?> clazz, Class<?>... paramTypes) { <ide> return (getConstructorIfAvailable(clazz, paramTypes) != null); <ide><path>spring-orm/src/main/java/org/springframework/orm/jpa/ExtendedEntityManagerCreator.java <ide> /* <del> * Copyright 2002-2019 the original author or authors. <add> * Copyright 2002-2020 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> private static EntityManager createProxy( <ide> <ide> if (emIfc != null) { <ide> interfaces = cachedEntityManagerInterfaces.computeIfAbsent(emIfc, key -> { <del> Set<Class<?>> ifcs = new LinkedHashSet<>(); <add> Set<Class<?>> ifcs = new LinkedHashSet<>(4); <ide> ifcs.add(key); <ide> ifcs.add(EntityManagerProxy.class); <ide> return ClassUtils.toClassArray(ifcs); <ide> }); <ide> } <ide> else { <ide> interfaces = cachedEntityManagerInterfaces.computeIfAbsent(rawEm.getClass(), key -> { <del> Set<Class<?>> ifcs = new LinkedHashSet<>(ClassUtils <del> .getAllInterfacesForClassAsSet(key, cl)); <add> Set<Class<?>> ifcs = new LinkedHashSet<>(ClassUtils.getAllInterfacesForClassAsSet(key, cl)); <ide> ifcs.add(EntityManagerProxy.class); <ide> return ClassUtils.toClassArray(ifcs); <ide> });
2
Mixed
Python
add line by line option to mlm/plm scripts
e1b1b614b132b64e2bd7c3aaf7909d38956c8dc2
<ide><path>examples/language-modeling/README.md <ide> python run_clm.py \ <ide> --output_dir /tmp/test-clm <ide> ``` <ide> <add>If your dataset is organized with one sample per line, you can use the `--line_by_line` flag (otherwise the script <add>concatenates all texts and then splits them in blocks of the same length). <add> <add>**Note:** On TPU, you should use the flag `--pad_to_max_length` in conjunction with the `--line_by_line` flag to make <add>sure all your batches have the same length. <add> <ide> ### Whole word masking <ide> <ide> The BERT authors released a new version of BERT using Whole Word Masking in May 2019. Instead of masking randomly <del>selected tokens (which may be aprt of words), they mask randomly selected words (masking all the tokens corresponding <add>selected tokens (which may be part of words), they mask randomly selected words (masking all the tokens corresponding <ide> to that word). This technique has been refined for Chinese in [this paper](https://arxiv.org/abs/1906.08101). <ide> <ide> To fine-tune a model using whole word masking, use the following script: <ide> It works well on so many Chines Task like CLUE (Chinese GLUE). They use LTP, so <ide> we need LTP. <ide> <ide> Now LTP only only works well on `transformers==3.2.0`. So we don't add it to requirements.txt. <del>You need to create a separate enviromnent with this version of Transformers to run the `run_chinese_ref.py` script that <del>will create the reference files. The script is in `examples/contrib`. Once in the proper enviromnent, run the <add>You need to create a separate environment with this version of Transformers to run the `run_chinese_ref.py` script that <add>will create the reference files. The script is in `examples/contrib`. Once in the proper environment, run the <ide> following: <ide> <ide> <ide> python run_mlm_wwm.py \ <ide> --output_dir /tmp/test-mlm-wwm <ide> ``` <ide> <add>**Note:** On TPU, you should the flag `--pad_to_max_length` to make sure all your batches have the same length. <add> <ide> ### XLNet and permutation language modeling <ide> <ide> XLNet uses a different training objective, which is permutation language modeling. It is an autoregressive method <ide> python run_plm.py \ <ide> --do_eval \ <ide> --output_dir /tmp/test-plm <ide> ``` <add> <add>If your dataset is organized with one sample per line, you can use the `--line_by_line` flag (otherwise the script <add>concatenates all texts and then splits them in blocks of the same length). <add> <add>**Note:** On TPU, you should use the flag `--pad_to_max_length` in conjunction with the `--line_by_line` flag to make <add>sure all your batches have the same length. <ide><path>examples/language-modeling/run_mlm.py <ide> class DataTrainingArguments: <ide> mlm_probability: float = field( <ide> default=0.15, metadata={"help": "Ratio of tokens to mask for masked language modeling loss"} <ide> ) <add> line_by_line: bool = field( <add> default=False, <add> metadata={"help": "Whether distinct lines of text in the dataset are to be handled as distinct sequences."}, <add> ) <add> pad_to_max_length: bool = field( <add> default=False, <add> metadata={ <add> "help": "Whether to pad all samples to `max_seq_length`. " <add> "If False, will pad the samples dynamically when batching to the maximum length in the batch." <add> }, <add> ) <ide> <ide> def __post_init__(self): <ide> if self.dataset_name is None and self.train_file is None and self.validation_file is None: <ide> def main(): <ide> column_names = datasets["validation"].column_names <ide> text_column_name = "text" if "text" in column_names else column_names[0] <ide> <del> def tokenize_function(examples): <del> # Remove empty lines <del> examples["text"] = [line for line in examples["text"] if len(line) > 0 and not line.isspace()] <del> return tokenizer(examples["text"], truncation=True, max_length=data_args.max_seq_length) <del> <del> tokenized_datasets = datasets.map( <del> tokenize_function, <del> batched=True, <del> num_proc=data_args.preprocessing_num_workers, <del> remove_columns=[text_column_name], <del> load_from_cache_file=not data_args.overwrite_cache, <del> ) <add> if data_args.line_by_line: <add> # When using line_by_line, we just tokenize each nonempty line. <add> padding = "max_length" if data_args.pad_to_max_length else False <add> <add> def tokenize_function(examples): <add> # Remove empty lines <add> examples["text"] = [line for line in examples["text"] if len(line) > 0 and not line.isspace()] <add> return tokenizer(examples["text"], padding=padding, truncation=True, max_length=data_args.max_seq_length) <add> <add> tokenized_datasets = datasets.map( <add> tokenize_function, <add> batched=True, <add> num_proc=data_args.preprocessing_num_workers, <add> remove_columns=[text_column_name], <add> load_from_cache_file=not data_args.overwrite_cache, <add> ) <add> else: <add> # Otherwise, we tokenize every text, then concatenate them together before splitting them in smaller parts. <add> def tokenize_function(examples): <add> return tokenizer(examples[text_column_name]) <add> <add> tokenized_datasets = datasets.map( <add> tokenize_function, <add> batched=True, <add> num_proc=data_args.preprocessing_num_workers, <add> remove_columns=[text_column_name], <add> load_from_cache_file=not data_args.overwrite_cache, <add> ) <add> <add> if data_args.max_seq_length is None: <add> max_seq_length = tokenizer.model_max_length <add> else: <add> if data_args.max_seq_length > tokenizer.model_max_length: <add> logger.warn( <add> f"The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the" <add> f"model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}." <add> ) <add> max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length) <add> <add> # Main data processing function that will concatenate all texts from our dataset and generate chunks of <add> # max_seq_length. <add> def group_texts(examples): <add> # Concatenate all texts. <add> concatenated_examples = {k: sum(examples[k], []) for k in examples.keys()} <add> total_length = len(concatenated_examples[list(examples.keys())[0]]) <add> # We drop the small remainder, we could add padding if the model supported it instead of this drop, you can <add> # customize this part to your needs. <add> total_length = (total_length // max_seq_length) * max_seq_length <add> # Split by chunks of max_len. <add> result = { <add> k: [t[i : i + max_seq_length] for i in range(0, total_length, max_seq_length)] <add> for k, t in concatenated_examples.items() <add> } <add> return result <add> <add> # Note that with `batched=True`, this map processes 1,000 texts together, so group_texts throws away a <add> # remainder for each of those groups of 1,000 texts. You can adjust that batch_size here but a higher value <add> # might be slower to preprocess. <add> # <add> # To speed up this part, we use multiprocessing. See the documentation of the map method for more information: <add> # https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.map <add> tokenized_datasets = tokenized_datasets.map( <add> group_texts, <add> batched=True, <add> num_proc=data_args.preprocessing_num_workers, <add> load_from_cache_file=not data_args.overwrite_cache, <add> ) <ide> <ide> # Data collator <ide> # This one will take care of randomly masking the tokens. <ide><path>examples/language-modeling/run_mlm_wwm.py <ide> class DataTrainingArguments: <ide> mlm_probability: float = field( <ide> default=0.15, metadata={"help": "Ratio of tokens to mask for masked language modeling loss"} <ide> ) <add> pad_to_max_length: bool = field( <add> default=False, <add> metadata={ <add> "help": "Whether to pad all samples to `max_seq_length`. " <add> "If False, will pad the samples dynamically when batching to the maximum length in the batch." <add> }, <add> ) <ide> <ide> def __post_init__(self): <ide> if self.train_file is not None: <ide> def main(): <ide> column_names = datasets["validation"].column_names <ide> text_column_name = "text" if "text" in column_names else column_names[0] <ide> <add> padding = "max_length" if data_args.pad_to_max_length else False <add> <ide> def tokenize_function(examples): <ide> # Remove empty lines <ide> examples["text"] = [line for line in examples["text"] if len(line) > 0 and not line.isspace()] <del> return tokenizer(examples["text"], truncation=True, max_length=data_args.max_seq_length) <add> return tokenizer(examples["text"], padding=padding, truncation=True, max_length=data_args.max_seq_length) <ide> <ide> tokenized_datasets = datasets.map( <ide> tokenize_function, <ide><path>examples/language-modeling/run_plm.py <ide> class DataTrainingArguments: <ide> max_span_length: int = field( <ide> default=5, metadata={"help": "Maximum length of a span of masked tokens for permutation language modeling."} <ide> ) <add> line_by_line: bool = field( <add> default=False, <add> metadata={"help": "Whether distinct lines of text in the dataset are to be handled as distinct sequences."}, <add> ) <add> pad_to_max_length: bool = field( <add> default=False, <add> metadata={ <add> "help": "Whether to pad all samples to `max_seq_length`. " <add> "If False, will pad the samples dynamically when batching to the maximum length in the batch." <add> }, <add> ) <ide> <ide> def __post_init__(self): <ide> if self.dataset_name is None and self.train_file is None and self.validation_file is None: <ide> def main(): <ide> column_names = datasets["validation"].column_names <ide> text_column_name = "text" if "text" in column_names else column_names[0] <ide> <del> def tokenize_function(examples): <del> # Remove empty lines <del> examples["text"] = [line for line in examples["text"] if len(line) > 0 and not line.isspace()] <del> return tokenizer(examples["text"], truncation=True, max_length=data_args.max_seq_length) <del> <del> tokenized_datasets = datasets.map( <del> tokenize_function, <del> batched=True, <del> num_proc=data_args.preprocessing_num_workers, <del> remove_columns=[text_column_name], <del> load_from_cache_file=not data_args.overwrite_cache, <del> ) <add> if data_args.line_by_line: <add> # When using line_by_line, we just tokenize each nonempty line. <add> padding = "max_length" if data_args.pad_to_max_length else False <add> <add> def tokenize_function(examples): <add> # Remove empty lines <add> examples["text"] = [line for line in examples["text"] if len(line) > 0 and not line.isspace()] <add> return tokenizer(examples["text"], padding=padding, truncation=True, max_length=data_args.max_seq_length) <add> <add> tokenized_datasets = datasets.map( <add> tokenize_function, <add> batched=True, <add> num_proc=data_args.preprocessing_num_workers, <add> remove_columns=[text_column_name], <add> load_from_cache_file=not data_args.overwrite_cache, <add> ) <add> else: <add> # Otherwise, we tokenize every text, then concatenate them together before splitting them in smaller parts. <add> def tokenize_function(examples): <add> return tokenizer(examples[text_column_name]) <add> <add> tokenized_datasets = datasets.map( <add> tokenize_function, <add> batched=True, <add> num_proc=data_args.preprocessing_num_workers, <add> remove_columns=[text_column_name], <add> load_from_cache_file=not data_args.overwrite_cache, <add> ) <add> <add> if data_args.max_seq_length is None: <add> max_seq_length = tokenizer.model_max_length <add> else: <add> if data_args.max_seq_length > tokenizer.model_max_length: <add> logger.warn( <add> f"The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the" <add> f"model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}." <add> ) <add> max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length) <add> <add> # Main data processing function that will concatenate all texts from our dataset and generate chunks of <add> # max_seq_length. <add> def group_texts(examples): <add> # Concatenate all texts. <add> concatenated_examples = {k: sum(examples[k], []) for k in examples.keys()} <add> total_length = len(concatenated_examples[list(examples.keys())[0]]) <add> # We drop the small remainder, we could add padding if the model supported it instead of this drop, you can <add> # customize this part to your needs. <add> total_length = (total_length // max_seq_length) * max_seq_length <add> # Split by chunks of max_len. <add> result = { <add> k: [t[i : i + max_seq_length] for i in range(0, total_length, max_seq_length)] <add> for k, t in concatenated_examples.items() <add> } <add> return result <add> <add> # Note that with `batched=True`, this map processes 1,000 texts together, so group_texts throws away a <add> # remainder for each of those groups of 1,000 texts. You can adjust that batch_size here but a higher value <add> # might be slower to preprocess. <add> # <add> # To speed up this part, we use multiprocessing. See the documentation of the map method for more information: <add> # https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.map <add> tokenized_datasets = tokenized_datasets.map( <add> group_texts, <add> batched=True, <add> num_proc=data_args.preprocessing_num_workers, <add> load_from_cache_file=not data_args.overwrite_cache, <add> ) <ide> <ide> # Data collator <ide> data_collator = DataCollatorForPermutationLanguageModeling(
4
Python
Python
fix samplewise normalization in imagedatagenerator
d2d33d7f900d9ad4a0208e1a48635fbb7bd0c13c
<ide><path>keras/preprocessing/image.py <ide> def standardize(self, x): <ide> x = self.preprocessing_function(x) <ide> if self.rescale: <ide> x *= self.rescale <del> # x is a single image, so it doesn't have image number at index 0 <del> img_channel_axis = self.channel_axis - 1 <ide> if self.samplewise_center: <del> x -= np.mean(x, axis=img_channel_axis, keepdims=True) <add> x -= np.mean(x, keepdims=True) <ide> if self.samplewise_std_normalization: <del> x /= (np.std(x, axis=img_channel_axis, keepdims=True) + 1e-7) <add> x /= np.std(x, keepdims=True) + 1e-7 <ide> <ide> if self.featurewise_center: <ide> if self.mean is not None:
1
Javascript
Javascript
add sneat app
9856a9726781939bb2b36bbe2e9c89861542da4f
<ide><path>website/src/react-native/showcase.js <ide> var apps = [ <ide> link: 'https://itunes.apple.com/kr/app/sweeohauseu-sesang-ui-modeun/id1060914858?mt=8', <ide> author: 'Dobbit Co., Ltd.' <ide> }, <add> { <add> name: 'sneat: réservez les meilleurs restaurants de Paris', <add> icon: 'http://a3.mzstatic.com/eu/r30/Purple49/v4/71/71/df/7171df47-6e03-8619-19a8-07f52186b0ed/icon175x175.jpeg', <add> link: 'https://itunes.apple.com/fr/app/sneat-reservez-les-meilleurs/id1062510079?l=en&mt=8', <add> author: 'sneat' <add> }, <ide> { <ide> name: 'Spero for Cancer', <ide> icon: 'https://s3-us-west-1.amazonaws.com/cancerspot/site_images/Spero1024.png',
1
PHP
PHP
fix dirty tracking for array associations
49799d893e119a93de767df7ff3bf656c8f598c9
<ide><path>src/ORM/Marshaller.php <ide> public function merge(EntityInterface $entity, array $data, array $options = []) <ide> if (isset($propertyMap[$key])) { <ide> $value = $propertyMap[$key]($value, $entity); <ide> <del> // Don't dirty complex objects that were objects before. <del> $isObject = is_object($value); <del> if ((!$isObject && $original === $value) || <del> ($isObject && $original == $value) <add> // Arrays will be marked as dirty always because <add> // the original/updated could contain references to the <add> // same objects, even those those objects may have changed. <add> if ( <add> (is_scalar($value) && $original === $value) || <add> (is_object($value) && $original == $value) <ide> ) { <ide> continue; <ide> } <ide> } <ide> $properties[$key] = $value; <ide> } <ide> <add> $entity->errors($errors); <ide> if (!isset($options['fieldList'])) { <ide> $entity->set($properties); <del> $entity->errors($errors); <ide> <ide> foreach ($properties as $field => $value) { <ide> if ($value instanceof EntityInterface) { <ide> public function merge(EntityInterface $entity, array $data, array $options = []) <ide> } <ide> } <ide> <del> $entity->errors($errors); <del> <ide> return $entity; <ide> } <ide> <ide><path>tests/TestCase/ORM/MarshallerTest.php <ide> public function testOneAssociationsSingle() <ide> <ide> $this->assertInternalType('array', $result->comments); <ide> $this->assertEquals($data['comments'], $result->comments); <add> $this->assertTrue($result->dirty('comments')); <ide> <ide> $this->assertInstanceOf('Cake\ORM\Entity', $result->user); <add> $this->assertTrue($result->dirty('user')); <ide> $this->assertEquals($data['user']['username'], $result->user->username); <ide> $this->assertEquals($data['user']['password'], $result->user->password); <ide> } <ide> public function testOneBelongsToManyWithNestedAssociations() <ide> <ide> $this->assertNotEmpty($tag->articles); <ide> $this->assertCount(1, $tag->articles); <add> $this->assertTrue($tag->dirty('articles'), 'Updated prop should be dirty'); <ide> $this->assertInstanceOf('Cake\ORM\Entity', $tag->articles[0]); <ide> $this->assertSame('New tagged article', $tag->articles[0]->title); <ide> $this->assertFalse($tag->articles[0]->isNew()); <ide> <ide> $this->assertNotEmpty($tag->articles[0]->user); <ide> $this->assertInstanceOf('Cake\ORM\Entity', $tag->articles[0]->user); <add> $this->assertTrue($tag->articles[0]->dirty('user'), 'Updated prop should be dirty'); <ide> $this->assertSame('newuser', $tag->articles[0]->user->username); <ide> $this->assertTrue($tag->articles[0]->user->isNew()); <ide> <ide> $this->assertNotEmpty($tag->articles[0]->comments); <ide> $this->assertCount(2, $tag->articles[0]->comments); <add> $this->assertTrue($tag->articles[0]->dirty('comments'), 'Updated prop should be dirty'); <ide> $this->assertInstanceOf('Cake\ORM\Entity', $tag->articles[0]->comments[0]); <ide> $this->assertTrue($tag->articles[0]->comments[0]->isNew()); <ide> $this->assertTrue($tag->articles[0]->comments[1]->isNew()); <ide> public function testBelongsToManyAddingNewExisting() <ide> $this->assertEquals($data['tags'][1]['id'], $result->tags[1]->id); <ide> $this->assertNotEmpty($result->tags[0]->_joinData); <ide> $this->assertNotEmpty($result->tags[1]->_joinData); <add> $this->assertTrue($result->dirty('tags'), 'Modified prop should be dirty'); <ide> $this->assertEquals(0, $result->tags[0]->_joinData->active); <ide> $this->assertEquals(1, $result->tags[1]->_joinData->active); <ide> } <ide> public function testMergeWithSingleAssociationAndFieldLists() <ide> 'associated' => ['Users' => []] <ide> ]); <ide> $this->assertSame($user, $article->user); <add> $this->assertTrue($article->dirty('user')); <ide> } <ide> <ide> /** <ide> public function testMergeMultipleAssociations() <ide> $result = $marshall->merge($entity, $data, ['associated' => ['Users', 'Comments']]); <ide> $this->assertSame($entity, $result); <ide> $this->assertSame($user, $result->user); <add> $this->assertTrue($result->dirty('user')); <ide> $this->assertEquals('not so secret', $entity->user->password); <add> <add> $this->assertTrue($result->dirty('comments')); <ide> $this->assertSame($comment1, $entity->comments[0]); <ide> $this->assertSame($comment2, $entity->comments[1]); <ide> $this->assertEquals('Altered comment 1', $entity->comments[0]->comment); <ide> public function testMergeBelongsToManyEntitiesFromIds() <ide> $result = $marshall->merge($entity, $data, ['associated' => ['Tags']]); <ide> <ide> $this->assertCount(3, $result->tags); <add> $this->assertTrue($result->dirty('tags'), 'Updated prop should be dirty'); <ide> $this->assertInstanceOf('Cake\ORM\Entity', $result->tags[0]); <ide> $this->assertInstanceOf('Cake\ORM\Entity', $result->tags[1]); <ide> $this->assertInstanceOf('Cake\ORM\Entity', $result->tags[2]); <ide> public function testMergeFromIdsWithAutoAssociation() <ide> $result = $marshall->merge($entity, $data, ['associated' => ['Tags']]); <ide> <ide> $this->assertCount(3, $result->tags); <add> $this->assertTrue($result->dirty('tags')); <ide> } <ide> <ide> /** <ide> public function testMergeBelongsToManyFromIdsWithConditions() <ide> $result = $marshall->merge($entity, $data, ['associated' => ['Tags']]); <ide> <ide> $this->assertCount(3, $result->tags); <add> $this->assertTrue($result->dirty('tags')); <ide> $this->assertInstanceOf('Cake\ORM\Entity', $result->tags[0]); <ide> $this->assertInstanceOf('Cake\ORM\Entity', $result->tags[1]); <ide> $this->assertInstanceOf('Cake\ORM\Entity', $result->tags[2]); <ide> public function testMergeBelongsToManyEntitiesFromIdsEmptyValue() <ide> ]; <ide> $result = $marshall->merge($entity, $data, ['associated' => ['Tags']]); <ide> $this->assertCount(0, $result->tags); <add> $this->assertTrue($result->dirty('tags')); <ide> } <ide> <ide> /** <ide> public function testMergeBelongsToManyOnlyIdsRejectArray() <ide> 'associated' => ['Tags' => ['onlyIds' => true]] <ide> ]); <ide> $this->assertCount(0, $result->tags); <add> $this->assertTrue($result->dirty('tags')); <ide> } <ide> <ide> /** <ide> public function testMergeBelongsToManyOnlyIdsWithIds() <ide> ]); <ide> $this->assertCount(1, $result->tags); <ide> $this->assertEquals('tag3', $result->tags[0]->name); <add> $this->assertTrue($result->dirty('tags')); <ide> } <ide> <ide> /** <ide> public function testMergeBelongsToManyJoinDataNotAccessible() <ide> ]); <ide> <ide> $entity = $articles->get(1, ['contain' => 'Tags']); <add> // Make only specific fields accessible, but not _joinData. <add> $entity->tags[0]->accessible('*', false); <add> $entity->tags[0]->accessible(['article_id', 'tag_id'], true); <add> <ide> $data = [ <ide> 'title' => 'Haz data', <ide> 'tags' => [ <ide> ['id' => 3, 'tag' => 'Cake', '_joinData' => ['highlighted' => '1', 'author_id' => '99']], <ide> ] <ide> ]; <del> // Make only specific fields accessible, but not _joinData. <del> $entity->tags[0]->accessible('*', false); <del> $entity->tags[0]->accessible(['article_id', 'tag_id'], true); <del> <ide> $marshall = new Marshaller($articles); <ide> $result = $marshall->merge($entity, $data, ['associated' => 'Tags._joinData']); <ide> <add> $this->assertTrue($entity->dirty('tags'), 'Association data changed'); <ide> $this->assertTrue($entity->tags[0]->dirty('_joinData')); <ide> $this->assertTrue($result->tags[0]->_joinData->dirty('author_id'), 'Field not modified'); <ide> $this->assertTrue($result->tags[0]->_joinData->dirty('highlighted'), 'Field not modified'); <ide> public function testMergeBelongsToManyHandleJoinDataConsistently() <ide> ]; <ide> $marshall = new Marshaller($articles); <ide> $result = $marshall->merge($entity, $data, ['associated' => 'Tags']); <add> <add> $this->assertTrue($entity->dirty('tags')); <ide> $this->assertInstanceOf('Cake\ORM\Entity', $result->tags[0]->_joinData); <ide> $this->assertTrue($result->tags[0]->_joinData->highlighted); <ide> <ide> public function testMergeBelongsToManyHandleJoinDataConsistently() <ide> ]; <ide> $marshall = new Marshaller($articles); <ide> $result = $marshall->merge($entity, $data, ['associated' => 'Tags']); <add> <add> $this->assertTrue($entity->dirty('tags'), 'association data changed'); <ide> $this->assertInstanceOf('Cake\ORM\Entity', $result->tags[0]->_joinData); <ide> $this->assertTrue($result->tags[0]->_joinData->highlighted); <ide> } <ide> public function testMergeBelongsToManyJoinDataAssociatedWithIds() <ide> $article = $this->articles->get(1, ['associated' => 'Tags']); <ide> $result = $marshall->merge($article, $data, ['associated' => ['Tags._joinData.Users']]); <ide> <add> $this->assertTrue($result->dirty('tags')); <ide> $this->assertInstanceOf('Cake\ORM\Entity', $result->tags[0]); <ide> $this->assertInstanceOf('Cake\ORM\Entity', $result->tags[1]); <ide> $this->assertInstanceOf('Cake\ORM\Entity', $result->tags[0]->_joinData->user); <ide> public function testMergeBelongsToManyJoinData() <ide> ['tag' => 'new tag', '_joinData' => ['active' => 1, 'foo' => 'baz']] <ide> ] <ide> ]; <del> <ide> $tag1 = $entity->tags[0]; <ide> $result = $marshall->merge($entity, $data, $options); <add> <ide> $this->assertEquals($data['title'], $result->title); <ide> $this->assertEquals('My content', $result->body); <add> $this->assertTrue($result->dirty('tags')); <ide> $this->assertSame($tag1, $entity->tags[0]); <ide> $this->assertSame($tag1->_joinData, $entity->tags[0]->_joinData); <ide> $this->assertSame( <ide> public function testMergeJoinDataAssociations() <ide> ] <ide> ] <ide> ]; <del> <ide> $tag1 = $entity->tags[0]; <ide> $result = $marshall->merge($entity, $data, $options); <add> <ide> $this->assertEquals($data['title'], $result->title); <ide> $this->assertEquals('My content', $result->body); <add> $this->assertTrue($entity->dirty('tags')); <ide> $this->assertSame($tag1, $entity->tags[0]); <add> <add> $this->assertTrue($tag1->dirty('_joinData')); <ide> $this->assertSame($tag1->_joinData, $entity->tags[0]->_joinData); <ide> $this->assertEquals('Bill', $entity->tags[0]->_joinData->user->username); <ide> $this->assertEquals('secret', $entity->tags[0]->_joinData->user->password); <ide> public function testMergeBelongsToManyIdsRetainJoinData() <ide> $result = $marshall->merge($entity, $data, ['associated' => ['Tags']]); <ide> <ide> $this->assertCount(1, $result->tags); <add> $this->assertTrue($result->dirty('tags')); <ide> $this->assertInstanceOf('Cake\ORM\Entity', $result->tags[0]); <ide> $this->assertInstanceOf('Cake\ORM\Entity', $result->tags[0]->_joinData); <ide> $this->assertSame($original, $result->tags[0]->_joinData, 'Should be same object'); <ide><path>tests/TestCase/ORM/TableTest.php <ide> public function testSaveHasMany() <ide> $this->assertEquals(5, $entity->articles[1]->author_id); <ide> } <ide> <add> /** <add> * Tests overwriting hasMany associations in an integration scenario. <add> * <add> * @return void <add> */ <add> public function testSaveHasManyOverwrite() <add> { <add> $table = TableRegistry::get('authors'); <add> $table->hasMany('articles'); <add> <add> $entity = $table->get(3, ['contain' => ['articles']]); <add> $data = [ <add> 'name' => 'big jose', <add> 'articles' => [ <add> [ <add> 'id' => 2, <add> 'title' => 'New title' <add> ] <add> ] <add> ]; <add> $entity = $table->patchEntity($entity, $data, ['associated' => 'articles']); <add> $this->assertSame($entity, $table->save($entity)); <add> <add> $entity = $table->get(3, ['contain' => ['articles']]); <add> $this->assertEquals('big jose', $entity->name, 'Author did not persist'); <add> $this->assertEquals('New title', $entity->articles[0]->title, 'Article did not persist'); <add> } <add> <ide> /** <ide> * Tests saving belongsToMany records <ide> *
3
Text
Text
fix command in upgrade guide
3b76d3371a4eca007c09e40afe4818bac6590d02
<ide><path>docs/upgrading.md <ide> npm install react@latest react-dom@latest <ide> Or using `yarn`: <ide> <ide> ``` <del>yarn add next@latest react-dom@latest <add>yarn add react@latest react-dom@latest <ide> ``` <ide> <ide> ### Remove `super.componentDidCatch()` from `pages/_app.js`
1
Ruby
Ruby
pass headers through to payload for logging
2c5c1276a84692ba58f60c8ff5fdad744959b69a
<ide><path>actionpack/lib/action_controller/metal/instrumentation.rb <ide> def process_action(*args) <ide> :controller => self.class.name, <ide> :action => self.action_name, <ide> :params => request.filtered_parameters, <add> :headers => request.headers, <ide> :format => request.format.ref, <ide> :method => request.request_method, <ide> :path => request.fullpath <ide><path>actionpack/test/controller/log_subscriber_test.rb <ide> def test_append_info_to_payload_is_called_even_with_exception <ide> assert_equal "test_value", @controller.last_payload[:test_key] <ide> end <ide> <add> def test_process_action_headers <add> get :show <add> wait <add> assert_equal "Rails Testing", @controller.last_payload[:headers]['User-Agent'] <add> end <add> <ide> def test_process_action_with_filter_parameters <ide> @request.env["action_dispatch.parameter_filter"] = [:lifo, :amount] <ide>
2
Mixed
Javascript
add ripple config object to pressable
bd3868643d29e93610e19312571a9736df2cbdf8
<ide><path>Libraries/Components/Pressable/Pressable.js <ide> <ide> import * as React from 'react'; <ide> import {useMemo, useState, useRef, useImperativeHandle} from 'react'; <del>import useAndroidRippleForView from './useAndroidRippleForView'; <add>import useAndroidRippleForView, { <add> type RippleConfig, <add>} from './useAndroidRippleForView'; <ide> import type { <ide> AccessibilityActionEvent, <ide> AccessibilityActionInfo, <ide> type Props = $ReadOnly<{| <ide> /** <ide> * Enables the Android ripple effect and configures its color. <ide> */ <del> android_rippleColor?: ?ColorValue, <add> android_ripple?: ?RippleConfig, <ide> <ide> /** <ide> * Used only for documentation or testing (e.g. snapshot testing). <ide> function Pressable(props: Props, forwardedRef): React.Node { <ide> const { <ide> accessible, <ide> android_disableSound, <del> android_rippleColor, <add> android_ripple, <ide> children, <ide> delayLongPress, <ide> disabled, <ide> function Pressable(props: Props, forwardedRef): React.Node { <ide> const viewRef = useRef<React.ElementRef<typeof View> | null>(null); <ide> useImperativeHandle(forwardedRef, () => viewRef.current); <ide> <del> const android_ripple = useAndroidRippleForView(android_rippleColor, viewRef); <add> const android_rippleConfig = useAndroidRippleForView(android_ripple, viewRef); <ide> <ide> const [pressed, setPressed] = usePressState(testOnly_pressed === true); <ide> <ide> function Pressable(props: Props, forwardedRef): React.Node { <ide> onLongPress, <ide> onPress, <ide> onPressIn(event: PressEvent): void { <del> if (android_ripple != null) { <del> android_ripple.onPressIn(event); <add> if (android_rippleConfig != null) { <add> android_rippleConfig.onPressIn(event); <ide> } <ide> setPressed(true); <ide> if (onPressIn != null) { <ide> onPressIn(event); <ide> } <ide> }, <del> onPressMove: android_ripple?.onPressMove, <add> onPressMove: android_rippleConfig?.onPressMove, <ide> onPressOut(event: PressEvent): void { <del> if (android_ripple != null) { <del> android_ripple.onPressOut(event); <add> if (android_rippleConfig != null) { <add> android_rippleConfig.onPressOut(event); <ide> } <ide> setPressed(false); <ide> if (onPressOut != null) { <ide> function Pressable(props: Props, forwardedRef): React.Node { <ide> }), <ide> [ <ide> android_disableSound, <del> android_ripple, <add> android_rippleConfig, <ide> delayLongPress, <ide> disabled, <ide> hitSlop, <ide> function Pressable(props: Props, forwardedRef): React.Node { <ide> <View <ide> {...restProps} <ide> {...eventHandlers} <del> {...android_ripple?.viewProps} <add> {...android_rippleConfig?.viewProps} <ide> accessible={accessible !== false} <ide> focusable={focusable !== false} <ide> hitSlop={hitSlop} <ide> function usePressState(forcePressed: boolean): [boolean, (boolean) => void] { <ide> return [pressed || forcePressed, setPressed]; <ide> } <ide> <del>const MemodPressable = React.memo(React.forwardRef(Pressable)); <del>MemodPressable.displayName = 'Pressable'; <add>const MemoedPressable = React.memo(React.forwardRef(Pressable)); <add>MemoedPressable.displayName = 'Pressable'; <ide> <del>export default (MemodPressable: React.AbstractComponent< <add>export default (MemoedPressable: React.AbstractComponent< <ide> Props, <ide> React.ElementRef<typeof View>, <ide> >); <ide><path>Libraries/Components/Pressable/useAndroidRippleForView.js <ide> type NativeBackgroundProp = $ReadOnly<{| <ide> type: 'RippleAndroid', <ide> color: ?number, <ide> borderless: boolean, <add> rippleRadius: ?number, <ide> |}>; <ide> <add>export type RippleConfig = {| <add> color?: ?ColorValue, <add> borderless?: ?boolean, <add> radius?: ?number, <add>|}; <add> <ide> /** <ide> * Provides the event handlers and props for configuring the ripple effect on <ide> * supported versions of Android. <ide> */ <ide> export default function useAndroidRippleForView( <del> rippleColor: ?ColorValue, <add> rippleConfig: ?RippleConfig, <ide> viewRef: {|current: null | React.ElementRef<typeof View>|}, <ide> ): ?$ReadOnly<{| <ide> onPressIn: (event: PressEvent) => void, <ide> export default function useAndroidRippleForView( <ide> nativeBackgroundAndroid: NativeBackgroundProp, <ide> |}>, <ide> |}> { <add> const {color, borderless, radius} = rippleConfig ?? {}; <add> const normalizedBorderless = borderless === true; <add> <ide> return useMemo(() => { <ide> if ( <ide> Platform.OS === 'android' && <ide> Platform.Version >= 21 && <del> rippleColor != null <add> (color != null || normalizedBorderless || radius != null) <ide> ) { <del> const processedColor = processColor(rippleColor); <add> const processedColor = processColor(color); <ide> invariant( <ide> processedColor == null || typeof processedColor === 'number', <ide> 'Unexpected color given for Ripple color', <ide> ); <ide> <ide> return { <ide> viewProps: { <del> // Consider supporting `nativeForegroundAndroid` and `borderless`. <add> // Consider supporting `nativeForegroundAndroid` <ide> nativeBackgroundAndroid: { <ide> type: 'RippleAndroid', <ide> color: processedColor, <del> borderless: false, <add> borderless: normalizedBorderless, <add> rippleRadius: radius, <ide> }, <ide> }, <ide> onPressIn(event: PressEvent): void { <ide> export default function useAndroidRippleForView( <ide> }; <ide> } <ide> return null; <del> }, [rippleColor, viewRef]); <add> }, [color, normalizedBorderless, radius, viewRef]); <ide> } <ide><path>Libraries/Components/View/ViewPropTypes.js <ide> type AndroidDrawableRipple = $ReadOnly<{| <ide> type: 'RippleAndroid', <ide> color?: ?number, <ide> borderless?: ?boolean, <add> rippleRadius?: ?number, <ide> |}>; <ide> <ide> type AndroidDrawable = AndroidDrawableThemeAttr | AndroidDrawableRipple; <ide><path>RNTester/js/examples/Pressable/PressableExample.js <ide> exports.examples = [ <ide> }; <ide> return ( <ide> <View style={styles.row}> <del> <Pressable android_rippleColor="green"> <add> <Pressable android_ripple={{color: 'green'}}> <ide> <Animated.View style={style} /> <ide> </Pressable> <ide> </View> <ide> ); <ide> }, <ide> }, <add> { <add> title: 'Pressable with custom Ripple', <add> description: ("Pressable can specify ripple's radius and borderless params": string), <add> platform: 'android', <add> render: function(): React.Node { <add> const nativeFeedbackButton = { <add> textAlign: 'center', <add> margin: 10, <add> }; <add> return ( <add> <View <add> style={[ <add> styles.row, <add> {justifyContent: 'space-around', alignItems: 'center'}, <add> ]}> <add> <Pressable <add> android_ripple={{color: 'orange', borderless: true, radius: 30}}> <add> <View> <add> <Text style={[styles.button, nativeFeedbackButton]}> <add> radius 30 <add> </Text> <add> </View> <add> </Pressable> <add> <add> <Pressable android_ripple={{borderless: true, radius: 150}}> <add> <View> <add> <Text style={[styles.button, nativeFeedbackButton]}> <add> radius 150 <add> </Text> <add> </View> <add> </Pressable> <add> <add> <Pressable android_ripple={{borderless: false, radius: 70}}> <add> <View style={styles.block}> <add> <Text style={[styles.button, nativeFeedbackButton]}> <add> radius 70, with border <add> </Text> <add> </View> <add> </Pressable> <add> </View> <add> ); <add> }, <add> }, <ide> { <ide> title: '<Text onPress={fn}> with highlight', <ide> render: function(): React.Node { <ide><path>RNTester/js/examples/Touchable/TouchableExample.js <ide> function CustomRippleRadius() { <ide> <ide> <TouchableNativeFeedback <ide> onPress={() => console.log('custom TNF has been clicked')} <del> background={TouchableNativeFeedback.SelectableBackgroundBorderless(50)}> <add> background={TouchableNativeFeedback.SelectableBackgroundBorderless( <add> 150, <add> )}> <ide> <View> <ide> <Text style={[styles.button, styles.nativeFeedbackButton]}> <del> radius 50 <add> radius 150 <ide> </Text> <ide> </View> <ide> </TouchableNativeFeedback> <ide> exports.examples = [ <ide> }, <ide> }, <ide> { <del> title: 'Disabled Touchable*', <del> description: ('<Touchable*> components accept disabled prop which prevents ' + <del> 'any interaction with component': string), <add> title: 'Custom Ripple Radius (Android-only)', <add> description: ('Ripple radius on TouchableNativeFeedback can be controlled': string), <ide> render: function(): React.Element<any> { <del> return <TouchableDisabled />; <add> return <CustomRippleRadius />; <ide> }, <ide> }, <ide> { <del> title: 'Custom Ripple Radius (Android-only)', <del> description: ('Ripple radius on TouchableNativeFeedback can be controlled': string), <add> title: 'Disabled Touchable*', <add> description: ('<Touchable*> components accept disabled prop which prevents ' + <add> 'any interaction with component': string), <ide> render: function(): React.Element<any> { <del> return <CustomRippleRadius />; <add> return <TouchableDisabled />; <ide> }, <ide> }, <ide> ]; <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/view/ReactDrawableHelper.java <ide> private static RippleDrawable getRippleDrawable( <ide> Context context, ReadableMap drawableDescriptionDict) { <ide> if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { <ide> throw new JSApplicationIllegalArgumentException( <del> "Ripple drawable is not available on " + "android API <21"); <add> "Ripple drawable is not available on android API <21"); <ide> } <ide> int color = getColor(context, drawableDescriptionDict); <ide> Drawable mask = getMask(drawableDescriptionDict); <ide> private static int getColor(Context context, ReadableMap drawableDescriptionDict <ide> return context.getResources().getColor(sResolveOutValue.resourceId); <ide> } else { <ide> throw new JSApplicationIllegalArgumentException( <del> "Attribute colorControlHighlight " + "couldn't be resolved into a drawable"); <add> "Attribute colorControlHighlight couldn't be resolved into a drawable"); <ide> } <ide> } <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewGroup.java <ide> public void setBackground(Drawable drawable) { <ide> <ide> public void setTranslucentBackgroundDrawable(@Nullable Drawable background) { <ide> // it's required to call setBackground to null, as in some of the cases we may set new <del> // background to be a layer drawable that contains a drawable that has been previously setup <add> // background to be a layer drawable that contains a drawable that has been setup <ide> // as a background previously. This will not work correctly as the drawable callback logic is <ide> // messed up in AOSP <ide> updateBackgroundDrawable(null);
7
Ruby
Ruby
remove warning from plugin generator
39af02aa3c07ccb3c1872790741c16defd8d5c48
<ide><path>railties/lib/rails/generators/rails/plugin/plugin_generator.rb <ide> def modules <ide> @modules ||= namespaced_name.camelize.split("::") <ide> end <ide> <del> def wrap_in_modules(content) <del> content = "#{content}".strip.gsub(/\W$\n/, '') <del> modules.reverse.inject(content) do |content, mod| <add> def wrap_in_modules(unwrapped_code) <add> unwrapped_code = "#{unwrapped_code}".strip.gsub(/\W$\n/, '') <add> modules.reverse.inject(unwrapped_code) do |content, mod| <ide> str = "module #{mod}\n" <ide> str += content.lines.map { |line| " #{line}" }.join <ide> str += content.present? ? "\nend" : "end"
1
Ruby
Ruby
remove dead code
a29db738b2e07804b1adf8e3f2b8a5b83b91892d
<ide><path>activerecord/lib/active_record/migration.rb <ide> def migrations_paths <ide> Array(@migrations_paths) <ide> end <ide> <del> def migrations_path <del> migrations_paths.first <del> end <del> <ide> def migrations(paths) <ide> paths = Array(paths) <ide>
1
Go
Go
remove unused task.setro()
5b2f8e91039fe1d0bdda146103ba91833cb66011
<ide><path>pkg/devicemapper/devmapper.go <ide> var ( <ide> ErrTaskSetName = errors.New("dm_task_set_name failed") <ide> ErrTaskSetMessage = errors.New("dm_task_set_message failed") <ide> ErrTaskSetAddNode = errors.New("dm_task_set_add_node failed") <del> ErrTaskSetRo = errors.New("dm_task_set_ro failed") <ide> ErrTaskAddTarget = errors.New("dm_task_add_target failed") <ide> ErrTaskSetSector = errors.New("dm_task_set_sector failed") <ide> ErrTaskGetDeps = errors.New("dm_task_get_deps failed") <ide> func (t *Task) setAddNode(addNode AddNodeType) error { <ide> return nil <ide> } <ide> <del>func (t *Task) setRo() error { <del> if res := DmTaskSetRo(t.unmanaged); res != 1 { <del> return ErrTaskSetRo <del> } <del> return nil <del>} <del> <ide> func (t *Task) addTarget(start, size uint64, ttype, params string) error { <ide> if res := DmTaskAddTarget(t.unmanaged, start, size, <ide> ttype, params); res != 1 { <ide><path>pkg/devicemapper/devmapper_wrapper.go <ide> var ( <ide> DmTaskSetCookie = dmTaskSetCookieFct <ide> DmTaskSetMessage = dmTaskSetMessageFct <ide> DmTaskSetName = dmTaskSetNameFct <del> DmTaskSetRo = dmTaskSetRoFct <ide> DmTaskSetSector = dmTaskSetSectorFct <ide> DmUdevWait = dmUdevWaitFct <ide> DmUdevSetSyncSupport = dmUdevSetSyncSupportFct <ide> func dmTaskSetAddNodeFct(task *cdmTask, addNode AddNodeType) int { <ide> return int(C.dm_task_set_add_node((*C.struct_dm_task)(task), C.dm_add_node_t(addNode))) <ide> } <ide> <del>func dmTaskSetRoFct(task *cdmTask) int { <del> return int(C.dm_task_set_ro((*C.struct_dm_task)(task))) <del>} <del> <ide> func dmTaskAddTargetFct(task *cdmTask, <ide> start, size uint64, ttype, params string) int { <ide>
2
Ruby
Ruby
use fetch rather than both hash#key? and hash#[]
0581c1a95c7ea9df88d5fd975ada40b0d8540d46
<ide><path>activerecord/lib/active_record/attribute_methods/read.rb <ide> def type_cast_attribute(attr_name, attributes, cache = {}) #:nodoc: <ide> end <ide> <ide> protected <del> # We want to generate the methods via module_eval rather than define_method, <del> # because define_method is slower on dispatch and uses more memory (because it <del> # creates a closure). <del> # <del> # But sometimes the database might return columns with characters that are not <del> # allowed in normal method names (like 'my_column(omg)'. So to work around this <del> # we first define with the __temp__ identifier, and then use alias method to <del> # rename it to what we want. <del> def define_method_attribute(attr_name) <del> cast_code = attribute_cast_code(attr_name) <del> <del> generated_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ + 1 <del> def __temp__ <del> #{internal_attribute_access_code(attr_name, cast_code)} <del> end <del> alias_method '#{attr_name}', :__temp__ <del> undef_method :__temp__ <del> STR <del> <del> generated_external_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ + 1 <del> def __temp__(v, attributes, attributes_cache, attr_name) <del> #{external_attribute_access_code(attr_name, cast_code)} <del> end <del> alias_method '#{attr_name}', :__temp__ <del> undef_method :__temp__ <del> STR <del> end <add> # We want to generate the methods via module_eval rather than define_method, <add> # because define_method is slower on dispatch and uses more memory (because it <add> # creates a closure). <add> # <add> # But sometimes the database might return columns with characters that are not <add> # allowed in normal method names (like 'my_column(omg)'. So to work around this <add> # we first define with the __temp__ identifier, and then use alias method to <add> # rename it to what we want. <add> def define_method_attribute(attr_name) <add> cast_code = attribute_cast_code(attr_name) <add> <add> generated_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ + 1 <add> def __temp__ <add> #{internal_attribute_access_code(attr_name, cast_code)} <add> end <add> alias_method '#{attr_name}', :__temp__ <add> undef_method :__temp__ <add> STR <ide> <del> private <del> def cacheable_column?(column) <del> attribute_types_cached_by_default.include?(column.type) <del> end <add> generated_external_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ + 1 <add> def __temp__(v, attributes, attributes_cache, attr_name) <add> #{external_attribute_access_code(attr_name, cast_code)} <add> end <add> alias_method '#{attr_name}', :__temp__ <add> undef_method :__temp__ <add> STR <add> end <ide> <del> def internal_attribute_access_code(attr_name, cast_code) <del> access_code = "(v=@attributes[attr_name]) && #{cast_code}" <add> private <add> def cacheable_column?(column) <add> attribute_types_cached_by_default.include?(column.type) <add> end <ide> <del> unless attr_name == primary_key <del> access_code.insert(0, "missing_attribute(attr_name, caller) unless @attributes.has_key?(attr_name); ") <del> end <add> def internal_attribute_access_code(attr_name, cast_code) <add> if attr_name == primary_key <add> access_code = "v = @attributes[attr_name];" <add> else <add> access_code = "v = @attributes.fetch(attr_name) { missing_attribute(attr_name, caller) };" <add> end <ide> <del> if cache_attribute?(attr_name) <del> access_code = "@attributes_cache[attr_name] ||= (#{access_code})" <del> end <add> access_code << "v && #{cast_code};" <ide> <del> "attr_name = '#{attr_name}'; #{access_code}" <add> if cache_attribute?(attr_name) <add> access_code = "@attributes_cache[attr_name] ||= (#{access_code})" <ide> end <ide> <del> def external_attribute_access_code(attr_name, cast_code) <del> access_code = "v && #{cast_code}" <add> "attr_name = '#{attr_name}'; #{access_code}" <add> end <ide> <del> if cache_attribute?(attr_name) <del> access_code = "attributes_cache[attr_name] ||= (#{access_code})" <del> end <add> def external_attribute_access_code(attr_name, cast_code) <add> access_code = "v && #{cast_code}" <ide> <del> access_code <add> if cache_attribute?(attr_name) <add> access_code = "attributes_cache[attr_name] ||= (#{access_code})" <ide> end <ide> <del> def attribute_cast_code(attr_name) <del> columns_hash[attr_name].type_cast_code('v') <del> end <add> access_code <add> end <add> <add> def attribute_cast_code(attr_name) <add> columns_hash[attr_name].type_cast_code('v') <add> end <ide> end <ide> <ide> # Returns the value of the attribute identified by <tt>attr_name</tt> after it has been typecast (for example,
1
PHP
PHP
fix regex for php 7.3
72dda637c0855914fd6f95a66cad9b8d5c5217cc
<ide><path>src/Database/SqlDialectTrait.php <ide> public function quoteIdentifier($identifier) <ide> return $this->_startQuote . $field . $this->_endQuote . $matches[2]; <ide> } <ide> <del> if (preg_match('/^[\w-_\s]*[\w-_]+/u', $identifier)) { <add> if (preg_match('/^[\w_\s-]*[\w_-]+/u', $identifier)) { <ide> return $this->_startQuote . $identifier . $this->_endQuote; <ide> } <ide>
1
Text
Text
fix typo in example
06f379ffadd263a35d0a7d2c2e3c13449a66a2a2
<ide><path>examples/with-env-from-next-config-js/README.md <ide> # With env From next.config.js <ide> <ide> This example demonstrates setting parameters that will be used by your application and set at build time (not run time). <del>More specifically, what that means, is that environmental variables are programmed into the special configuration file `next.js.config` and then <add>More specifically, what that means, is that environmental variables are programmed into the special configuration file `next.config.js` and then <ide> returned to your react components when the program is built with `next build`. <ide> <ide> As the build process (`next build`) is proceeding, `next.config.js` is processed and passed in as a parameter is the variable `phase`.
1
Text
Text
bring consistency to oxford comma usage
06bd4d3c10fea9f5dec91ee33d73a2490aa2c32a
<ide><path>README.md <ide> <ide> _NOTE: The transition from 1.8.0 (or before) to 1.8.1 (or after) requires uninstalling Airflow before installing the new version. The package name was changed from `airflow` to `apache-airflow` as of version 1.8.1._ <ide> <del>Airflow is a platform to programmatically author, schedule and monitor <add>Airflow is a platform to programmatically author, schedule, and monitor <ide> workflows. <ide> <ide> When workflows are defined as code, they become more maintainable,
1
Javascript
Javascript
remove third param from assert.strictequal
0c2cc89f3aab58a118f5e584cbeb4b20a6366cb0
<ide><path>test/parallel/test-fs-mkdir-rmdir.js <ide> fs.mkdir(d, 0o666, common.mustCall(function(err) { <ide> assert.strictEqual(this, undefined); <ide> assert.ok(err, 'got no error'); <ide> assert.ok(/^EEXIST/.test(err.message), 'got no EEXIST message'); <del> assert.strictEqual(err.code, 'EEXIST', 'got no EEXIST code'); <del> assert.strictEqual(err.path, d, 'got no proper path for EEXIST'); <add> assert.strictEqual(err.code, 'EEXIST'); <add> assert.strictEqual(err.path, d); <ide> <ide> fs.rmdir(d, assert.ifError); <ide> }));
1
Go
Go
improve trusted location detection
daa89c420caac0881b09e2a36feff977ec43d7cd
<ide><path>registry/registry.go <ide> func trustedLocation(req *http.Request) bool { <ide> } <ide> <ide> for _, trusted := range trusteds { <del> if strings.HasSuffix(hostname, trusted) { <add> if hostname == trusted || strings.HasSuffix(hostname, "."+trusted) { <ide> return true <ide> } <ide> } <ide><path>registry/registry_test.go <ide> func TestValidRepositoryName(t *testing.T) { <ide> } <ide> <ide> func TestTrustedLocation(t *testing.T) { <del> for _, url := range []string{"http://example.com", "https://example.com:7777", "http://docker.io", "http://test.docker.io"} { <add> for _, url := range []string{"http://example.com", "https://example.com:7777", "http://docker.io", "http://test.docker.io", "https://fakedocker.com"} { <ide> req, _ := http.NewRequest("GET", url, nil) <ide> if trustedLocation(req) == true { <ide> t.Fatalf("'%s' shouldn't be detected as a trusted location", url)
2
Ruby
Ruby
provide a unique point for running initializers
c2e3ce8d1e1174e66536d59d8d97eb2cc8ce6f25
<ide><path>railties/lib/rails/application.rb <ide> module Rails <ide> # 5) Load config/environments/ENV.rb <ide> # 6) Run config.before_initialize callbacks <ide> # 7) Run Railtie#initializer defined by railties, engines and application. <del> # One by one, each engine sets up its load paths, routes and runs its initializer files. <del> # 8) Build the middleware stack and run to_prepare callbacks <del> # 9) Run config.before_eager_load and eager_load if cache classes is true <del> # 10) Run config.after_initialize callbacks <add> # One by one, each engine sets up its load paths, routes, locales and so on. <add> # 8) Runs all registered config/initializers/*, executing the engines one first <add> # 9) Build the middleware stack and run to_prepare callbacks <add> # 10) Run config.before_eager_load and eager_load if cache classes is true <add> # 11) Run config.after_initialize callbacks <ide> # <ide> class Application < Engine <ide> autoload :Bootstrap, 'rails/application/bootstrap' <ide><path>railties/lib/rails/application/configuration.rb <ide> class Configuration < ::Rails::Engine::Configuration <ide> :force_ssl, :helpers_paths, :logger, :log_tags, :preload_frameworks, <ide> :reload_plugins, :secret_token, :serve_static_assets, <ide> :ssl_options, :static_cache_control, :session_options, <del> :time_zone, :whiny_nils, :railties_order <add> :time_zone, :whiny_nils, :railties_order, :all_initializers <ide> <ide> attr_writer :log_level <ide> attr_reader :encoding <ide> def initialize(*) <ide> @generators = app_generators <ide> @cache_store = [ :file_store, "#{root}/tmp/cache/" ] <ide> @railties_order = [:all] <add> @all_initializers = [] <ide> <ide> @assets = ActiveSupport::OrderedOptions.new <ide> @assets.enabled = false <ide><path>railties/lib/rails/application/finisher.rb <ide> module Finisher <ide> include Initializable <ide> $rails_rake_task = nil <ide> <add> initializer :load_config_initializers do <add> config.all_initializers.each { |init| load(init) } <add> end <add> <ide> initializer :add_generator_templates do <ide> config.generators.templates.unshift(*paths["lib/templates"].existent) <ide> end <ide><path>railties/lib/rails/engine.rb <ide> def load_seed <ide> end <ide> end <ide> <del> initializer :load_config_initializers do <del> config.paths["config/initializers"].existent.sort.each do |initializer| <del> load(initializer) <del> end <add> initializer :append_config_initializers do |app| <add> app.config.all_initializers.concat config.paths["config/initializers"].existent.sort <ide> end <ide> <ide> initializer :engines_blank_point do
4
Javascript
Javascript
escape module names
f9e7a17666471dab9e51889d090d6b9e449d554c
<ide><path>lib/node/NodeMainTemplatePlugin.js <ide> module.exports = class NodeMainTemplatePlugin { <ide> "// object to store loaded chunks", <ide> '// "0" means "already loaded"', <ide> "var installedChunks = {", <del> Template.indent(chunk.ids.map(id => `${id}: 0`).join(",\n")), <add> Template.indent( <add> chunk.ids.map(id => `${JSON.stringify(id)}: 0`).join(",\n") <add> ), <ide> "};" <ide> ]); <ide> } <ide><path>test/configCases/async-commons-chunk/node/index.js <add>import "./modules/a"; <add> <add>it("should load", done => { <add> Promise.all([import("./modules/b"), import("./modules/c")]).then(() => { <add> done(); <add> }); <add>}); <ide><path>test/configCases/async-commons-chunk/node/modules/a.js <add>import "./b"; <add> <add>export default "a"; <ide><path>test/configCases/async-commons-chunk/node/modules/b.js <add>export default "b"; <ide><path>test/configCases/async-commons-chunk/node/modules/c.js <add>import("./a"); <add> <add>export default "c"; <ide><path>test/configCases/async-commons-chunk/node/webpack.config.js <add>module.exports = { <add> mode: "none", <add> entry: { <add> "foo/bar": "./" <add> }, <add> target: "node", <add> optimization: { <add> namedChunks: true, <add> namedModules: true <add> } <add>};
6
Text
Text
remove invalid padding from privateencrypt
be0ce60af6293c1e1e74bca8849af36286f06582
<ide><path>doc/api/crypto.md <ide> keys: <ide> * `padding` : An optional padding value, one of the following: <ide> * `crypto.constants.RSA_NO_PADDING` <ide> * `crypto.constants.RSA_PKCS1_PADDING` <del> * `crypto.constants.RSA_PKCS1_OAEP_PADDING` <ide> <ide> All paddings are defined in `crypto.constants`. <ide>
1
Mixed
Ruby
return sized enumerator from enumerable#index_by
a476020567a47f5fbec3629707d5bf31b400a284
<ide><path>activerecord/CHANGELOG.md <del><<<<<<< HEAD <del>* `find_in_batches`, `find_each` now <add>* `find_in_batches`, `find_each`, `Result#each` and `Enumerable#index_by` now <ide> return an `Enumerator` that can calculate its size. <del>======= <del>* `find_in_batches`, `find_each`, `Result#each` now returns an `Enumerator` <del> that can calculate its size. <del>>>>>>>> 5863938... Return sized enumerator from Result#each <ide> <ide> See also #13938. <ide> <ide><path>activesupport/lib/active_support/core_ext/enumerable.rb <ide> def index_by <ide> if block_given? <ide> Hash[map { |elem| [yield(elem), elem] }] <ide> else <del> to_enum(:index_by) { size } <add> to_enum(:index_by) { size if respond_to?(:size) } <ide> end <ide> end <ide> <ide><path>activesupport/test/core_ext/enumerable_test.rb <ide> def test_index_by <ide> assert_equal({ 5 => Payment.new(5), 15 => Payment.new(15), 10 => Payment.new(10) }, <ide> payments.index_by { |p| p.price }) <ide> assert_equal Enumerator, payments.index_by.class <add> if Enumerator.method_defined? :size <add> assert_equal nil, payments.index_by.size <add> assert_equal 42, (1..42).index_by.size <add> end <ide> assert_equal({ 5 => Payment.new(5), 15 => Payment.new(15), 10 => Payment.new(10) }, <ide> payments.index_by.each { |p| p.price }) <ide> end
3
Javascript
Javascript
write more unit tests for the lexer and the parser
4a4b197b9d2ce1a20690837df64db8fd183c70ac
<ide><path>test/unit/parser_spec.js <ide> */ <ide> /* eslint no-var: error */ <ide> <del>import { Lexer, Linearization } from '../../src/core/parser'; <add>import { Lexer, Linearization, Parser } from '../../src/core/parser'; <ide> import { FormatError } from '../../src/shared/util'; <ide> import { Name } from '../../src/core/primitives'; <ide> import { StringStream } from '../../src/core/stream'; <ide> <ide> describe('parser', function() { <del> describe('Lexer', function() { <del> it('should stop parsing numbers at the end of stream', function() { <del> const input = new StringStream('11.234'); <del> const lexer = new Lexer(input); <del> expect(lexer.getNumber()).toEqual(11.234); <del> }); <add> describe('Parser', function() { <add> describe('inlineStreamSkipEI', function() { <add> it('should skip over the EI marker if it is found', function() { <add> const string = 'q 1 0 0 1 0 0 cm BI /W 10 /H 10 /BPC 1 ' + <add> '/F /A85 ID abc123~> EI Q'; <add> const input = new StringStream(string); <add> const lexer = new Lexer(input); <add> const parser = new Parser(lexer, /* allowStreams = */ true, <add> /* xref = */ null); <add> parser.inlineStreamSkipEI(input); <add> expect(input.pos).toEqual(string.indexOf('Q')); <add> expect(input.peekByte()).toEqual(0x51); // 'Q' <add> }); <ide> <del> it('should parse PostScript numbers', function() { <del> const numbers = ['-.002', '34.5', '-3.62', '123.6e10', '1E-5', '-1.', <del> '0.0', '123', '-98', '43445', '0', '+17']; <del> for (const number of numbers) { <del> const input = new StringStream(number); <add> it('should skip to the end of stream if the EI marker is not found', <add> function() { <add> const string = 'q 1 0 0 1 0 0 cm BI /W 10 /H 10 /BPC 1 ' + <add> '/F /A85 ID abc123~> Q'; <add> const input = new StringStream(string); <ide> const lexer = new Lexer(input); <del> expect(lexer.getNumber()).toEqual(parseFloat(number)); <del> } <add> const parser = new Parser(lexer, /* allowStreams = */ true, <add> /* xref = */ null); <add> parser.inlineStreamSkipEI(input); <add> expect(input.pos).toEqual(string.length); <add> expect(input.peekByte()).toEqual(-1); <add> }); <ide> }); <add> }); <ide> <del> it('should ignore double negative before number', function() { <del> const input = new StringStream('--205.88'); <del> const lexer = new Lexer(input); <del> expect(lexer.getNumber()).toEqual(-205.88); <del> }); <add> describe('Lexer', function() { <add> describe('nextChar', function() { <add> it('should return and set -1 when the end of the stream is reached', <add> function() { <add> const input = new StringStream(''); <add> const lexer = new Lexer(input); <add> expect(lexer.nextChar()).toEqual(-1); <add> expect(lexer.currentChar).toEqual(-1); <add> }); <ide> <del> it('should ignore minus signs in the middle of number', function() { <del> const input = new StringStream('205--.88'); <del> const lexer = new Lexer(input); <del> expect(lexer.getNumber()).toEqual(205.88); <add> it('should return and set the character after the current position', <add> function() { <add> const input = new StringStream('123'); <add> const lexer = new Lexer(input); <add> expect(lexer.nextChar()).toEqual(0x32); // '2' <add> expect(lexer.currentChar).toEqual(0x32); // '2' <add> }); <ide> }); <ide> <del> it('should ignore line-breaks between operator and digit in number', <del> function() { <del> const minusInput = new StringStream('-\r\n205.88'); <del> const minusLexer = new Lexer(minusInput); <del> expect(minusLexer.getNumber()).toEqual(-205.88); <add> describe('peekChar', function() { <add> it('should only return -1 when the end of the stream is reached', <add> function() { <add> const input = new StringStream(''); <add> const lexer = new Lexer(input); <add> expect(lexer.peekChar()).toEqual(-1); <add> expect(lexer.currentChar).toEqual(-1); <add> }); <ide> <del> const plusInput = new StringStream('+\r\n205.88'); <del> const plusLexer = new Lexer(plusInput); <del> expect(plusLexer.getNumber()).toEqual(205.88); <add> it('should only return the character after the current position', <add> function() { <add> const input = new StringStream('123'); <add> const lexer = new Lexer(input); <add> expect(lexer.peekChar()).toEqual(0x32); // '2' <add> expect(lexer.currentChar).toEqual(0x31); // '1' <add> }); <ide> }); <ide> <del> it('should treat a single decimal point as zero', function() { <del> const input = new StringStream('.'); <del> const lexer = new Lexer(input); <del> expect(lexer.getNumber()).toEqual(0); <add> describe('getNumber', function() { <add> it('should stop parsing numbers at the end of stream', function() { <add> const input = new StringStream('11.234'); <add> const lexer = new Lexer(input); <add> expect(lexer.getNumber()).toEqual(11.234); <add> }); <add> <add> it('should parse PostScript numbers', function() { <add> const numbers = ['-.002', '34.5', '-3.62', '123.6e10', '1E-5', '-1.', <add> '0.0', '123', '-98', '43445', '0', '+17']; <add> for (const number of numbers) { <add> const input = new StringStream(number); <add> const lexer = new Lexer(input); <add> expect(lexer.getNumber()).toEqual(parseFloat(number)); <add> } <add> }); <ide> <del> const numbers = ['..', '-.', '+.', '-\r\n.', '+\r\n.']; <del> for (const number of numbers) { <del> const input = new StringStream(number); <add> it('should ignore double negative before number', function() { <add> const input = new StringStream('--205.88'); <ide> const lexer = new Lexer(input); <add> expect(lexer.getNumber()).toEqual(-205.88); <add> }); <ide> <del> expect(function() { <del> return lexer.getNumber(); <del> }).toThrowError(FormatError, /^Invalid number:\s/); <del> } <del> }); <add> it('should ignore minus signs in the middle of number', function() { <add> const input = new StringStream('205--.88'); <add> const lexer = new Lexer(input); <add> expect(lexer.getNumber()).toEqual(205.88); <add> }); <ide> <del> it('should handle glued numbers and operators', function() { <del> const input = new StringStream('123ET'); <del> const lexer = new Lexer(input); <del> expect(lexer.getNumber()).toEqual(123); <del> // The lexer must not have consumed the 'E' <del> expect(lexer.currentChar).toEqual(0x45); // 'E' <del> }); <add> it('should ignore line-breaks between operator and digit in number', <add> function() { <add> const minusInput = new StringStream('-\r\n205.88'); <add> const minusLexer = new Lexer(minusInput); <add> expect(minusLexer.getNumber()).toEqual(-205.88); <add> <add> const plusInput = new StringStream('+\r\n205.88'); <add> const plusLexer = new Lexer(plusInput); <add> expect(plusLexer.getNumber()).toEqual(205.88); <add> }); <add> <add> it('should treat a single decimal point as zero', function() { <add> const input = new StringStream('.'); <add> const lexer = new Lexer(input); <add> expect(lexer.getNumber()).toEqual(0); <add> <add> const numbers = ['..', '-.', '+.', '-\r\n.', '+\r\n.']; <add> for (const number of numbers) { <add> const input = new StringStream(number); <add> const lexer = new Lexer(input); <add> <add> expect(function() { <add> return lexer.getNumber(); <add> }).toThrowError(FormatError, /^Invalid number:\s/); <add> } <add> }); <ide> <del> it('should stop parsing strings at the end of stream', function() { <del> const input = new StringStream('(1$4)'); <del> input.getByte = function(super_getByte) { <del> // Simulating end of file using null (see issue 2766). <del> const ch = super_getByte.call(input); <del> return (ch === 0x24 /* '$' */ ? -1 : ch); <del> }.bind(input, input.getByte); <del> const lexer = new Lexer(input); <del> expect(lexer.getString()).toEqual('1'); <add> it('should handle glued numbers and operators', function() { <add> const input = new StringStream('123ET'); <add> const lexer = new Lexer(input); <add> expect(lexer.getNumber()).toEqual(123); <add> // The lexer must not have consumed the 'E' <add> expect(lexer.currentChar).toEqual(0x45); // 'E' <add> }); <ide> }); <ide> <del> it('should not throw exception on bad input', function() { <del> // '7 0 2 15 5 2 2 2 4 3 2 4' should be parsed as '70 21 55 22 24 32'. <del> const input = new StringStream('<7 0 2 15 5 2 2 2 4 3 2 4>'); <del> const lexer = new Lexer(input); <del> expect(lexer.getHexString()).toEqual('p!U"$2'); <add> describe('getString', function() { <add> it('should stop parsing strings at the end of stream', function() { <add> const input = new StringStream('(1$4)'); <add> input.getByte = function(super_getByte) { <add> // Simulating end of file using null (see issue 2766). <add> const ch = super_getByte.call(input); <add> return (ch === 0x24 /* '$' */ ? -1 : ch); <add> }.bind(input, input.getByte); <add> const lexer = new Lexer(input); <add> expect(lexer.getString()).toEqual('1'); <add> }); <add> <add> it('should ignore escaped CR and LF', function() { <add> // '(\101\<CR><LF>\102)' should be parsed as 'AB'. <add> const input = new StringStream('(\\101\\\r\n\\102\\\r\\103\\\n\\104)'); <add> const lexer = new Lexer(input); <add> expect(lexer.getString()).toEqual('ABCD'); <add> }); <ide> }); <ide> <del> it('should ignore escaped CR and LF', function() { <del> // '(\101\<CR><LF>\102)' should be parsed as 'AB'. <del> const input = new StringStream('(\\101\\\r\n\\102\\\r\\103\\\n\\104)'); <del> const lexer = new Lexer(input); <del> expect(lexer.getString()).toEqual('ABCD'); <add> describe('getHexString', function() { <add> it('should not throw exception on bad input', function() { <add> // '7 0 2 15 5 2 2 2 4 3 2 4' should be parsed as '70 21 55 22 24 32'. <add> const input = new StringStream('<7 0 2 15 5 2 2 2 4 3 2 4>'); <add> const lexer = new Lexer(input); <add> expect(lexer.getHexString()).toEqual('p!U"$2'); <add> }); <ide> }); <ide> <del> it('should handle Names with invalid usage of NUMBER SIGN (#)', function() { <del> const inputNames = ['/# 680 0 R', '/#AQwerty', '/#A<</B']; <del> const expectedNames = ['#', '#AQwerty', '#A']; <add> describe('getName', function() { <add> it('should handle Names with invalid usage of NUMBER SIGN (#)', <add> function() { <add> const inputNames = ['/# 680 0 R', '/#AQwerty', '/#A<</B']; <add> const expectedNames = ['#', '#AQwerty', '#A']; <ide> <del> for (let i = 0, ii = inputNames.length; i < ii; i++) { <del> const input = new StringStream(inputNames[i]); <del> const lexer = new Lexer(input); <del> expect(lexer.getName()).toEqual(Name.get(expectedNames[i])); <del> } <add> for (let i = 0, ii = inputNames.length; i < ii; i++) { <add> const input = new StringStream(inputNames[i]); <add> const lexer = new Lexer(input); <add> expect(lexer.getName()).toEqual(Name.get(expectedNames[i])); <add> } <add> }); <ide> }); <ide> }); <ide>
1
Python
Python
avoid double split call
8f2e551437cc2ab7e8a447fd159e03c1e56171e5
<ide><path>libcloud/dns/drivers/route53.py <ide> def _to_record(self, elem, zone, index=0): <ide> extra = {'ttl': ttl} <ide> <ide> if type == 'MX': <del> priority = int(data.split()[0]) <del> data = data.split()[1] <add> split = data.split() <add> priority, data = int(split[0]), split[1] <ide> extra['priority'] = priority <ide> <ide> id = ':'.join((self.RECORD_TYPE_MAP[type], name))
1