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
|
---|---|---|---|---|---|
Python | Python | fix npy_pkg_config script | a71977d8e6a2e7f543a131dbebd557471fce64c5 | <ide><path>numpy/distutils/npy_pkg_config.py
<ide> def read_config(pkgname, dirs=None):
<ide> import os
<ide> d = os.environ.get('NPY_PKG_CONFIG_PATH')
<ide> if d:
<del> info = read_info(pkg_name, ['numpy/core/lib/npy-pkg-config', '.', d])
<add> info = read_config(pkg_name, ['numpy/core/lib/npy-pkg-config', '.', d])
<ide> else:
<del> info = read_info(pkg_name, ['numpy/core/lib/npy-pkg-config', '.'])
<add> info = read_config(pkg_name, ['numpy/core/lib/npy-pkg-config', '.'])
<ide>
<ide> if options.section:
<ide> section = options.section | 1 |
Python | Python | fix weights in model.test | 24df6a9f9bda51784ce3d41bc23830eae72a118e | <ide><path>keras/models.py
<ide> def train(self, X, y, accuracy=False, sample_weight=None):
<ide> def test(self, X, y, accuracy=False):
<ide> X = standardize_X(X)
<ide> y = standardize_y(y)
<del> ins = X + [y]
<add> sample_weight = np.ones(y.shape[:-1] + (1,))
<add> ins = X + [y, sample_weight]
<ide> if accuracy:
<ide> return self._test_with_acc(*ins)
<ide> else: | 1 |
Javascript | Javascript | combine parsejson tests and fix style | 32051e97c1e77d0b678648832d090168b534841c | <ide><path>test/unit/core.js
<ide> test("jQuery.parseHTML", function() {
<ide> });
<ide>
<ide> test("jQuery.parseJSON", function(){
<del> expect(8);
<add> expect( 9 );
<ide>
<add> equal( jQuery.parseJSON( null ), null, "Actual null returns null" );
<add> equal( jQuery.isEmptyObject( jQuery.parseJSON("{}") ), true, "Empty object returns empty object" );
<add> deepEqual( jQuery.parseJSON("{\"test\":1}"), { "test": 1 }, "Plain object parses" );
<add> deepEqual( jQuery.parseJSON("\n{\"test\":1}"), { "test": 1 }, "Leading whitespaces are ignored." );
<ide> raises(function() {
<ide> jQuery.parseJSON();
<del> }, null, "parseJson now matches JSON.parse for empty input." );
<del> equal(jQuery.parseJSON( null ), null, "parseJson now matches JSON.parse on null input." );
<add> }, null, "Undefined raises an error" );
<ide> raises( function() {
<ide> jQuery.parseJSON( "" );
<del> }, null, "parseJson now matches JSON.parse for empty strings." );
<del>
<del> deepEqual( jQuery.parseJSON("{}"), {}, "Plain object parsing." );
<del> deepEqual( jQuery.parseJSON("{\"test\":1}"), {"test":1}, "Plain object parsing." );
<del>
<del> deepEqual( jQuery.parseJSON("\n{\"test\":1}"), {"test":1}, "Make sure leading whitespaces are handled." );
<del>
<del> try {
<add> }, null, "Empty string raises an error" );
<add> raises(function() {
<add> jQuery.parseJSON("''");
<add> }, null, "Single-quoted string raises an error" );
<add> raises(function() {
<ide> jQuery.parseJSON("{a:1}");
<del> ok( false, "Test malformed JSON string." );
<del> } catch( e ) {
<del> ok( true, "Test malformed JSON string." );
<del> }
<del>
<del> try {
<add> }, null, "Unquoted property raises an error" );
<add> raises(function() {
<ide> jQuery.parseJSON("{'a':1}");
<del> ok( false, "Test malformed JSON string." );
<del> } catch( e ) {
<del> ok( true, "Test malformed JSON string." );
<del> }
<add> }, null, "Single-quoted property raises an error" );
<ide> });
<ide>
<ide> test("jQuery.parseXML", 8, function(){
<ide> test("jQuery.camelCase()", function() {
<ide> equal( jQuery.camelCase( key ), val, "Converts: " + key + " => " + val );
<ide> });
<ide> });
<del>
<del>// Ensure our window.JSON matches behavior of the native one, if it exists
<del>if ( window.JSON ) {
<del> test( "JQuery.parseJSON() equivalence to JSON.parse", function() {
<del> expect( 10 );
<del>
<del> var jsonParse = window.JSON;
<del> window.JSON = null;
<del>
<del> raises(function() {
<del> jsonParse.parse("''");
<del> });
<del>
<del> raises(function() {
<del> jQuery.parseJSON("''");
<del> });
<del>
<del> raises(function() {
<del> jsonParse.parse("");
<del> });
<del>
<del> raises(function() {
<del> jQuery.parseJSON("");
<del> });
<del>
<del> raises(function() {
<del> jsonParse.parse({});
<del> });
<del>
<del> raises(function() {
<del> jQuery.parseJSON({});
<del> });
<del>
<del> var parsedValue = jsonParse.parse(null);
<del> equal( parsedValue, null, "parsed null" );
<del>
<del> parsedValue = jQuery.parseJSON(null);
<del> equal( parsedValue, null, "parsed null" );
<del>
<del> parsedValue = jsonParse.parse("{}");
<del> equal( (typeof parsedValue === "object"), true );
<del>
<del> parsedValue = jQuery.parseJSON("{}");
<del> equal( (typeof parsedValue === "object"), true );
<del>
<del>
<del> window.JSON = jsonParse;
<del> });
<del>}
<del> | 1 |
PHP | PHP | use func_get_arg(0) instead of argument $viewfile | 98e8aaaf682883ebcfd19cbfd05e10d5bf7dc2a5 | <ide><path>src/View/View.php
<ide> protected function _evaluate($viewFile, $dataForView)
<ide> extract($dataForView);
<ide> ob_start();
<ide>
<del> include $viewFile;
<add> include func_get_arg(0);
<ide>
<ide> return ob_get_clean();
<ide> } | 1 |
Python | Python | fix doc on python2 | 183fedfed5e302d581714173d9ac1f232a128fbd | <ide><path>pytorch_transformers/modeling_bert.py
<ide> def init_weights(self, module):
<ide> @add_start_docstrings("The bare Bert Model transformer outputing raw hidden-states without any specific head on top.",
<ide> BERT_START_DOCSTRING, BERT_INPUTS_DOCSTRING)
<ide> class BertModel(BertPreTrainedModel):
<del> r"""
<add> __doc__ = r"""
<ide> Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs:
<ide> **last_hidden_state**: ``torch.FloatTensor`` of shape ``(batch_size, sequence_length, hidden_size)``
<ide> Sequence of hidden-states at the last layer of the model.
<ide> def forward(self, input_ids, token_type_ids=None, attention_mask=None, head_mask
<ide> a `masked language modeling` head and a `next sentence prediction (classification)` head. """,
<ide> BERT_START_DOCSTRING, BERT_INPUTS_DOCSTRING)
<ide> class BertForPreTraining(BertPreTrainedModel):
<del> r"""
<add> __doc__ = r"""
<ide> **masked_lm_labels**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``:
<ide> Labels for computing the masked language modeling loss.
<ide> Indices should be in ``[-1, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring)
<ide> def forward(self, input_ids, token_type_ids=None, attention_mask=None, masked_lm
<ide> @add_start_docstrings("""Bert Model transformer BERT model with a `language modeling` head on top. """,
<ide> BERT_START_DOCSTRING, BERT_INPUTS_DOCSTRING)
<ide> class BertForMaskedLM(BertPreTrainedModel):
<del> r"""
<add> __doc__ = r"""
<ide> **masked_lm_labels**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``:
<ide> Labels for computing the masked language modeling loss.
<ide> Indices should be in ``[-1, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring)
<ide> def forward(self, input_ids, token_type_ids=None, attention_mask=None, masked_lm
<ide> @add_start_docstrings("""Bert Model transformer BERT model with a `next sentence prediction (classification)` head on top. """,
<ide> BERT_START_DOCSTRING, BERT_INPUTS_DOCSTRING)
<ide> class BertForNextSentencePrediction(BertPreTrainedModel):
<del> r"""
<add> __doc__ = r"""
<ide> **next_sentence_label**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size,)``:
<ide> Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair (see ``input_ids`` docstring)
<ide> Indices should be in ``[0, 1]``.
<ide> def forward(self, input_ids, token_type_ids=None, attention_mask=None, next_sent
<ide> the pooled output) e.g. for GLUE tasks. """,
<ide> BERT_START_DOCSTRING, BERT_INPUTS_DOCSTRING)
<ide> class BertForSequenceClassification(BertPreTrainedModel):
<del> r"""
<add> __doc__ = r"""
<ide> **labels**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size,)``:
<ide> Labels for computing the sequence classification/regression loss.
<ide> Indices should be in ``[0, ..., config.num_labels]``.
<ide> def forward(self, input_ids, token_type_ids=None, attention_mask=None, labels=No
<ide> the pooled output and a softmax) e.g. for RocStories/SWAG tasks. """,
<ide> BERT_START_DOCSTRING)
<ide> class BertForMultipleChoice(BertPreTrainedModel):
<del> r"""
<add> __doc__ = r"""
<ide> Inputs:
<ide> **input_ids**: ``torch.LongTensor`` of shape ``(batch_size, num_choices, sequence_length)``:
<ide> Indices of input sequence tokens in the vocabulary.
<ide> def forward(self, input_ids, token_type_ids=None, attention_mask=None, labels=No
<ide> the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks. """,
<ide> BERT_START_DOCSTRING, BERT_INPUTS_DOCSTRING)
<ide> class BertForTokenClassification(BertPreTrainedModel):
<del> r"""
<add> __doc__ = r"""
<ide> **labels**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``:
<ide> Labels for computing the token classification loss.
<ide> Indices should be in ``[0, ..., config.num_labels]``. | 1 |
Javascript | Javascript | fix typos in the inline testing package docs | 9a86b20c98fab82b8b6c583f0ae077bc4e7184ed | <ide><path>packages/ember-testing/lib/helpers.js
<ide> helper('visit', visit);
<ide> * ```
<ide> *
<ide> * @method click
<del>* @param {String} selcetor jQuery selector for finding element on the DOM
<add>* @param {String} selector jQuery selector for finding element on the DOM
<ide> * @returns {RSVP.Promise}
<ide> */
<ide> helper('click', click);
<ide> helper('click', click);
<ide> * });
<ide> * ```
<ide> *
<del>* @method click
<del>* @param {String} selcetor jQuery selector for finding element on the DOM
<add>* @method keyEvent
<add>* @param {String} selector jQuery selector for finding element on the DOM
<ide> * @param {String} the type of key event, e.g. `keypress`, `keydown`, `keyup`
<ide> * @param {Number} the keyCode of the simulated key event
<ide> * @returns {RSVP.Promise}
<ide><path>packages/ember-testing/lib/test.js
<ide> Ember.Test = {
<ide>
<ide> For example:
<ide> ```javascript
<del> Ember.Test.registerHelper('boot', function(app)) {
<add> Ember.Test.registerHelper('boot', function(app) {
<ide> Ember.run(app, app.deferReadiness);
<del> }
<add> });
<ide> ```
<ide>
<ide> This helper can later be called without arguments | 2 |
PHP | PHP | use static instead of self | 7fe79c5f43820ed64d1bed86ed6d709c7bf51e73 | <ide><path>src/Illuminate/Support/Arr.php
<ide> public static function sortRecursive($array)
<ide> {
<ide> foreach ($array as &$value) {
<ide> if (is_array($value)) {
<del> $value = self::sortRecursive($value);
<add> $value = static::sortRecursive($value);
<ide> }
<ide> }
<ide>
<del> if (self::isAssoc($array)) {
<add> if (static::isAssoc($array)) {
<ide> ksort($array);
<ide> } else {
<ide> sort($array); | 1 |
Python | Python | fix lint error | 4fabdee4a3e5425619b516b5b2200c0c16d235d7 | <ide><path>tests/test_description.py
<ide> from rest_framework.views import APIView
<ide>
<ide>
<del>
<del>
<ide> # We check that docstrings get nicely un-indented.
<ide> DESCRIPTION = """an example docstring
<ide> ==================== | 1 |
Javascript | Javascript | save test file in temporary directory | 2f53eb46e86443ed86f0e69044e420f3e7082f56 | <ide><path>test/parallel/test-fs-readv-sync.js
<ide> require('../common');
<ide> const assert = require('assert');
<ide> const fs = require('fs');
<add>const path = require('path');
<ide> const tmpdir = require('../common/tmpdir');
<ide>
<ide> tmpdir.refresh();
<ide> const expected = 'ümlaut. Лорем 運務ホソモ指及 आपको कर
<ide> const exptectedBuff = Buffer.from(expected);
<ide> const expectedLength = exptectedBuff.length;
<ide>
<del>const filename = 'readv_sync.txt';
<add>const filename = path.join(tmpdir.path, 'readv_sync.txt');
<ide> fs.writeFileSync(filename, exptectedBuff);
<ide>
<ide> const allocateEmptyBuffers = (combinedLength) => { | 1 |
Javascript | Javascript | use strict comparison for controller === '@' | bbd3db14f857aab996ad129f2f15ca6348e9fd9f | <ide><path>src/ng/compile.js
<ide> function $CompileProvider($provide, $$sanitizeUriProvider) {
<ide> };
<ide>
<ide> var controller = directive.controller;
<del> if (controller == '@') {
<add> if (controller === '@') {
<ide> controller = attrs[directive.name];
<ide> }
<ide> | 1 |
Javascript | Javascript | hide example for angular.filter | dfa8baf59a1dafe6cc4c4e46da123cb85e85e0a4 | <ide><path>src/Angular.js
<ide> var _undefined = undefined,
<ide> * * `$element` — The DOM element containing the binding. This allows the filter to manipulate
<ide> * the DOM in addition to transforming the input.
<ide> *
<del> * The following example filter reverses a text string. In addition, it conditionally makes the
<del> * text upper-case (to demonstrate optional arguments) and assigns color (to demonstrate DOM
<del> * modification).
<ide> *
<ide> * @example
<add> * //TODO this example current doesn't show up anywhere because the overview template doesn't
<add> * // render it.
<add> *
<add> * The following example filter reverses a text string. In addition, it conditionally makes the
<add> * text upper-case (to demonstrate optional arguments) and assigns color (to demonstrate DOM
<add> * modification).
<add>
<ide> <script type="text/javascript">
<ide> angular.filter.reverse = function(input, uppercase, color) {
<ide> var out = ""; | 1 |
Ruby | Ruby | add rbenv requirement | 1b4cc77e14401480111cbd5a53e38bead641d8d8 | <ide><path>Library/Homebrew/requirements.rb
<ide> class PostgresqlRequirement < Requirement
<ide> satisfy { which "pg_config" }
<ide> end
<ide>
<add>class RbenvRequirement < Requirement
<add> fatal true
<add> default_formula "rbenv"
<add>
<add> satisfy { which "rbenv" }
<add>end
<add>
<ide> class GPGRequirement < Requirement
<ide> fatal true
<ide> default_formula "gpg"
<ide> class GitRequirement < Requirement
<ide> default_formula "git"
<ide> satisfy { Utils.git_available? }
<ide> end
<del> | 1 |
PHP | PHP | redirect() helper method | 55bee118c323c7b1deec8da081eafd2e649cbd41 | <ide><path>src/Illuminate/Routing/RedirectController.php
<add><?php
<add>
<add>namespace Illuminate\Routing;
<add>
<add>use Illuminate\Http\RedirectResponse;
<add>
<add>class RedirectController extends Controller
<add>{
<add> public function __invoke($destination, $status = 301)
<add> {
<add> return new RedirectResponse($destination, $status);
<add> }
<add>}
<ide><path>src/Illuminate/Routing/Router.php
<ide> public function group(array $attributes, $routes)
<ide> array_pop($this->groupStack);
<ide> }
<ide>
<add> /**
<add> * Create a redirect from one route to another.
<add> *
<add> * @param string $url
<add> * @param string $destination
<add> * @param int $status
<add> * @return Route
<add> */
<add> public function redirect($url, $destination, $status = 301)
<add> {
<add> return $this->any($url, '\Illuminate\Routing\RedirectController')
<add> ->defaults('destination', $destination)
<add> ->defaults('status', $status);
<add> }
<add>
<ide> /**
<ide> * Update the group stack with the given attributes.
<ide> *
<ide><path>tests/Routing/RoutingRouteTest.php
<ide> public function testJsonResponseIsReturned()
<ide> $this->assertInstanceOf(\Illuminate\Http\JsonResponse::class, $response);
<ide> }
<ide>
<add> public function testRouteRedirect()
<add> {
<add> $router = $this->getRouter();
<add> $router->get('contact_us', function () {
<add> throw new \Exception('Route should not be reachable.');
<add> });
<add> $router->redirect('contact_us', 'contact', 302);
<add>
<add> $response = $router->dispatch(Request::create('contact_us', 'GET'));
<add> $this->assertTrue($response->isRedirect('contact'));
<add> $this->assertEquals(302, $response->getStatusCode());
<add> }
<add>
<ide> protected function getRouter()
<ide> {
<ide> $container = new Container; | 3 |
Javascript | Javascript | add test case | 67b8a886f9042bc6fb573607fdf9118dfa0f50de | <ide><path>test/PersistentCaching.test.js
<ide> const rimraf = require("rimraf");
<ide> const vm = require("vm");
<ide> const webpack = require("../");
<ide>
<del>const readFile = util.promisify(fs.readFile);
<ide> const readdir = util.promisify(fs.readdir);
<ide> const writeFile = util.promisify(fs.writeFile);
<ide> const utimes = util.promisify(fs.utimes);
<ide> describe("Persistent Caching", () => {
<ide> },
<ide> target: "node",
<ide> output: {
<del> library: "result",
<del> libraryExport: "default",
<add> library: { type: "commonjs-module", export: "default" },
<ide> path: outputPath
<ide> }
<ide> };
<ide> describe("Persistent Caching", () => {
<ide> });
<ide> };
<ide>
<del> const execute = async () => {
<del> const p = path.resolve(outputPath, "main.js");
<del> const source = await readFile(p, "utf-8");
<del> const context = {};
<del> const fn = vm.runInThisContext(
<del> `(function() { ${source}\nreturn result; })`,
<del> context,
<del> p
<del> );
<del> return fn();
<add> const execute = () => {
<add> const cache = {};
<add> const require = name => {
<add> if (cache[name]) return cache[name].exports;
<add> if (!name.endsWith(".js")) name += ".js";
<add> const p = path.resolve(outputPath, name);
<add> const source = fs.readFileSync(p, "utf-8");
<add> const context = {};
<add> const fn = vm.runInThisContext(
<add> `(function(require, module, exports) { ${source} })`,
<add> context,
<add> {
<add> filename: p
<add> }
<add> );
<add> const m = { exports: {} };
<add> cache[name] = m;
<add> fn(require, m, m.exports);
<add> return m.exports;
<add> };
<add> return require("./main");
<ide> };
<ide>
<ide> it("should merge multiple small files", async () => {
<ide> const files = Array.from({ length: 30 }).map((_, i) => `file${i}.js`);
<ide> const data = {
<ide> "index.js": `
<add>
<ide> ${files.map((f, i) => `import f${i} from "./${f}";`).join("\n")}
<ide>
<ide> export default ${files.map((_, i) => `f${i}`).join(" + ")};
<ide> export default ${files.map((_, i) => `f${i}`).join(" + ")};
<ide> }
<ide> await updateSrc(data);
<ide> await compile();
<del> expect(await execute()).toBe(30);
<add> expect(execute()).toBe(30);
<ide> for (let i = 0; i < 30; i++) {
<ide> updateSrc({
<ide> [files[i]]: `export default 2;`
<ide> });
<ide> await compile();
<del> expect(await execute()).toBe(31 + i);
<add> expect(execute()).toBe(31 + i);
<ide> }
<ide> const cacheFiles = await readdir(cachePath);
<ide> expect(cacheFiles.length).toBeLessThan(20);
<ide> export default ${files.map((_, i) => `f${i}`).join(" + ")};
<ide> const cacheFiles = await readdir(cachePath);
<ide> expect(cacheFiles.length).toBeGreaterThan(4);
<ide> }, 60000);
<add>
<add> it("should allow persistent caching of container related objects", async () => {
<add> const data = {
<add> "index.js":
<add> "export default import('container/src/exposed').then(m => m.default);",
<add> "exposed.js": "export default 42;"
<add> };
<add> await updateSrc(data);
<add> const configAdditions = {
<add> plugins: [
<add> new webpack.container.ModuleFederationPlugin({
<add> name: "container",
<add> library: { type: "commonjs-module" },
<add> exposes: ["./src/exposed"],
<add> remotes: ["./container"]
<add> })
<add> ]
<add> };
<add> await compile(configAdditions);
<add> await expect(execute()).resolves.toBe(42);
<add> await updateSrc({
<add> "exposed.js": "module.exports = { ok: true };"
<add> });
<add> await compile(configAdditions);
<add> await expect(execute()).resolves.toEqual({ ok: true });
<add> });
<ide> }); | 1 |
Python | Python | use an example that also shows default value | 6000e438ea56e7eb622fe99ce28321eb81faec59 | <ide><path>numpy/lib/function_base.py
<ide> def select(condlist, choicelist, default=0):
<ide>
<ide> Examples
<ide> --------
<del> >>> x = np.arange(10)
<del> >>> condlist = [x<3, x>5]
<add> >>> x = np.arange(6)
<add> >>> condlist = [x<3, x>3]
<ide> >>> choicelist = [x, x**2]
<ide> >>> np.select(condlist, choicelist)
<del> array([ 0, 1, 2, ..., 49, 64, 81])
<add> array([ 0, 1, 2, 0, 16, 25])
<ide>
<ide> """
<ide> # Check the size of condlist and choicelist are the same, or abort. | 1 |
Ruby | Ruby | update version detection for 2.x | 19fba42c69de00888461a14ab75d3e3bb2b3fc13 | <ide><path>Library/Homebrew/os/mac/xcode.rb
<ide> def uncached_version
<ide> if File.file? path
<ide> Utils.popen_read(path, "-version") =~ /Xcode (\d(\.\d)*)/
<ide> return $1 if $1
<add>
<add> # Xcode 2.x's xcodebuild has a different version string
<add> Utils.popen_read(path, "-version") =~ /DevToolsCore-(\d+\.\d)/
<add> case $1
<add> when "515.0" then return "2.0"
<add> when "798.0" then return "2.5"
<add> end
<ide> end
<ide> end
<ide> | 1 |
Python | Python | replace print by logger.debug | 651095e3602756237920f4fa7ac170e1322c1939 | <ide><path>celery/utils/functional.py
<ide> """Functional-style utilities."""
<ide> import inspect
<del>import sys
<ide> from collections import UserList
<ide> from functools import partial
<ide> from itertools import islice, tee, zip_longest
<add>from typing import Any, Callable
<ide>
<ide> from kombu.utils.functional import LRUCache, dictfilter, is_list, lazy, maybe_evaluate, maybe_list, memoize
<ide> from vine import promise
<ide>
<add>from celery.utils.log import get_logger
<add>
<add>logger = get_logger(__name__)
<add>
<ide> __all__ = (
<ide> 'LRUCache', 'is_list', 'maybe_list', 'memoize', 'mlazy', 'noop',
<ide> 'first', 'firstmethod', 'chunks', 'padlist', 'mattrgetter', 'uniq',
<ide> def _argsfromspec(spec, replace_defaults=True):
<ide> ]))
<ide>
<ide>
<del>def head_from_fun(fun, bound=False, debug=False):
<add>def head_from_fun(fun: Callable[..., Any], bound: bool = False) -> str:
<ide> """Generate signature function from actual function."""
<ide> # we could use inspect.Signature here, but that implementation
<ide> # is very slow since it implements the argument checking
<ide> def head_from_fun(fun, bound=False, debug=False):
<ide> fun_args=_argsfromspec(inspect.getfullargspec(fun)),
<ide> fun_value=1,
<ide> )
<del> if debug: # pragma: no cover
<del> print(definition, file=sys.stderr)
<add> logger.debug(definition)
<ide> namespace = {'__name__': fun.__module__}
<ide> # pylint: disable=exec-used
<ide> # Tasks are rarely, if ever, created at runtime - exec here is fine. | 1 |
Java | Java | increase streamutils.buffer_size to 8192 | cdb38e8482bc7307163e2e87d029565bf07aeaa6 | <ide><path>spring-core/src/main/java/org/springframework/util/StreamUtils.java
<ide> /**
<ide> * Simple utility methods for dealing with streams. The copy methods of this class are
<ide> * similar to those defined in {@link FileCopyUtils} except that all affected streams are
<del> * left open when done. All copy methods use a block size of 4096 bytes.
<add> * left open when done. All copy methods use a block size of 8192 bytes.
<ide> *
<ide> * <p>Mainly for use within the framework, but also useful for application code.
<ide> *
<ide> public abstract class StreamUtils {
<ide> /**
<ide> * The default buffer size used when copying bytes.
<ide> */
<del> public static final int BUFFER_SIZE = 4096;
<add> public static final int BUFFER_SIZE = 8192;
<ide>
<ide> private static final byte[] EMPTY_CONTENT = new byte[0];
<ide>
<ide> public static String copyToString(@Nullable InputStream in, Charset charset) thr
<ide> return "";
<ide> }
<ide>
<del> StringBuilder out = new StringBuilder(BUFFER_SIZE);
<add> StringBuilder out = new StringBuilder();
<ide> InputStreamReader reader = new InputStreamReader(in, charset);
<ide> char[] buffer = new char[BUFFER_SIZE];
<ide> int charsRead; | 1 |
Javascript | Javascript | use https in the og image on the website | 93ed185c3d237717742672fb3086f6ef82fb7ba7 | <ide><path>website/core/Site.js
<ide> var Site = React.createClass({
<ide> },
<ide> {
<ide> property: "og:image",
<del> content: this.props.image ? this.props.image : "http://facebook.github.io/react-native/img/opengraph.png",
<add> content: this.props.image ? this.props.image : "https://facebook.github.io/react-native/img/opengraph.png",
<ide> },
<ide> {
<ide> property: "og:description", | 1 |
Text | Text | improve questions section in contributing doc | 6e92c4d6749e4ee4b68f74157a1c4539f19deb2d | <ide><path>CONTRIBUTING.md
<ide> First off, thank you for taking the time to contribute! :+1: :tada:
<ide>
<ide> * [Code of Conduct](#code-of-conduct)
<ide> * [How to Contribute](#how-to-contribute)
<del> * [Discuss](#discuss)
<add> * [Ask questions](#ask-questions)
<ide> * [Create an Issue](#create-an-issue)
<ide> * [Issue Lifecycle](#issue-lifecycle)
<ide> * [Submit a Pull Request](#submit-a-pull-request)
<ide> Please report unacceptable behavior to spring-code-of-conduct@pivotal.io.
<ide>
<ide> ### How to Contribute
<ide>
<del>#### Discuss
<add>#### Ask questions
<ide>
<ide> If you have a question, check Stack Overflow using
<del>[this list of tags](https://stackoverflow.com/questions/tagged/spring+or+spring-mvc+or+spring-aop+or+spring-jdbc+or+spring-transactions+or+spring-annotations+or+spring-jms+or+spring-el+or+spring-test+or+spring+or+spring-remoting+or+spring-orm+or+spring-jmx+or+spring-cache+or+spring-webflux?tab=Newest).
<del>Find an existing discussion, or start a new one if necessary.
<add>[this list of tags](https://stackoverflow.com/questions/tagged/spring+or+spring-mvc+or+spring-aop+or+spring-jdbc+or+spring-transactions+or+spring-annotations+or+spring-jms+or+spring-el+or+spring-test+or+spring+or+spring-remoting+or+spring-orm+or+spring-jmx+or+spring-cache+or+spring-webflux?tab=Newest). Find an existing discussion, or start a new one if necessary.
<ide>
<ide> If you believe there is an issue, search through
<ide> [existing issues](https://github.com/spring-projects/spring-framework/issues) trying a
<ide> decision.
<ide>
<ide> Reporting an issue or making a feature request is a great way to contribute. Your feedback
<ide> and the conversations that result from it provide a continuous flow of ideas. However,
<del>before creating a ticket, please take the time to [discuss and research](#discuss) first.
<add>before creating a ticket, please take the time to [ask and research](#ask-questions) first.
<ide>
<ide> If creating an issue after a discussion on Stack Overflow, please provide a description
<ide> in the issue instead of simply referring to Stack Overflow. The issue tracker is an
<ide> important place of record for design discussions and should be self-sufficient.
<ide>
<del>Once you're ready, create an issue on
<del>[GitHub](https://github.com/spring-projects/spring-framework/issues).
<add>Once you're ready, create an issue on [GitHub](https://github.com/spring-projects/spring-framework/issues).
<add>
<add>Many issues are caused by subtle behavior, typos and unintended configuration.
<add>Creating a [Minimal Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example)
<add>(starting with https://start.spring.io for example) of the problem helps the team
<add>triage quickly your issue adn get to the core of the problem.
<ide>
<ide> #### Issue Lifecycle
<ide>
<ide> When making changes locally, execute `./gradlew asciidoctor` and then browse the
<ide>
<ide> Asciidoctor also supports live editing. For more details see
<ide> [AsciiDoc Tooling](https://docs.asciidoctor.org/asciidoctor/latest/tooling/).
<add> | 1 |
Javascript | Javascript | use strict (in)equalities | dad328077dfc50ab44bdc9a70634787374d45253 | <ide><path>src/core/BufferGeometry.js
<ide> THREE.BufferGeometry.prototype = {
<ide> var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0;
<ide> var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0;
<ide>
<del> var hasFaceVertexNormals = faces[ 0 ] && faces[ 0 ].vertexNormals.length == 3;
<add> var hasFaceVertexNormals = faces[ 0 ] && faces[ 0 ].vertexNormals.length === 3;
<ide>
<ide> var positions = new Float32Array( faces.length * 3 * 3 );
<ide> this.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
<ide> THREE.BufferGeometry.prototype = {
<ide>
<ide> for ( var vo = 0; vo < 3; vo ++ ) {
<ide> var vid = indices[ findex * 3 + vo ];
<del> if ( vertexMap[ vid ] == - 1 ) {
<add> if ( vertexMap[ vid ] === - 1 ) {
<ide> //Unmapped vertice
<ide> faceVertices[ vo * 2 ] = vid;
<ide> faceVertices[ vo * 2 + 1 ] = - 1;
<ide> THREE.BufferGeometry.prototype = {
<ide> /* Create a copy of all attributes for reordering. */
<ide> var sortedAttributes = {};
<ide> for ( var attr in this.attributes ) {
<del> if ( attr == 'index' )
<add> if ( attr === 'index' )
<ide> continue;
<ide> var sourceArray = this.attributes[ attr ].array;
<ide> sortedAttributes[ attr ] = new sourceArray.constructor( this.attributes[ attr ].itemSize * vertexCount );
<ide> THREE.BufferGeometry.prototype = {
<ide> for ( var new_vid = 0; new_vid < vertexCount; new_vid ++ ) {
<ide> var vid = indexMap[ new_vid ];
<ide> for ( var attr in this.attributes ) {
<del> if ( attr == 'index' )
<add> if ( attr === 'index' )
<ide> continue;
<ide> var attrArray = this.attributes[ attr ].array;
<ide> var attrSize = this.attributes[ attr ].itemSize;
<ide> THREE.BufferGeometry.prototype = {
<ide> /* Carry the new sorted buffers locally */
<ide> this.attributes[ 'index' ].array = indexBuffer;
<ide> for ( var attr in this.attributes ) {
<del> if ( attr == 'index' )
<add> if ( attr === 'index' )
<ide> continue;
<ide> this.attributes[ attr ].array = sortedAttributes[ attr ];
<ide> this.attributes[ attr ].numItems = this.attributes[ attr ].itemSize * vertexCount;
<ide><path>src/core/Geometry.js
<ide> THREE.Geometry.prototype = {
<ide> // if any duplicate vertices are found in a Face3
<ide> // we have to remove the face as nothing can be saved
<ide> for ( var n = 0; n < 3; n ++ ) {
<del> if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) {
<add> if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {
<ide>
<ide> dupIndex = n;
<ide> faceIndicesToRemove.push( i );
<ide><path>src/extras/animation/MorphAnimation.js
<ide> THREE.MorphAnimation.prototype = {
<ide>
<ide> var influences = this.mesh.morphTargetInfluences;
<ide>
<del> if ( frame != this.currentFrame ) {
<add> if ( frame !== this.currentFrame ) {
<ide>
<ide> influences[ this.lastFrame ] = 0;
<ide> influences[ this.currentFrame ] = 1;
<ide><path>src/extras/core/Curve.js
<ide> THREE.Curve.prototype.getLengths = function ( divisions ) {
<ide> if ( ! divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions) : 200;
<ide>
<ide> if ( this.cacheArcLengths
<del> && ( this.cacheArcLengths.length == divisions + 1 )
<add> && ( this.cacheArcLengths.length === divisions + 1 )
<ide> && ! this.needsUpdate) {
<ide>
<ide> //THREE.log( "cached", this.cacheArcLengths );
<ide> THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
<ide>
<ide> //THREE.log('b' , i, low, high, Date.now()- time);
<ide>
<del> if ( arcLengths[ i ] == targetArcLength ) {
<add> if ( arcLengths[ i ] === targetArcLength ) {
<ide>
<ide> var t = i / ( il - 1 );
<ide> return t;
<ide><path>src/extras/core/CurvePath.js
<ide> THREE.CurvePath = function () {
<ide>
<ide> this.curves = [];
<ide> this.bends = [];
<del>
<add>
<ide> this.autoClose = false; // Automatically closes the path
<ide> };
<ide>
<ide> THREE.CurvePath.prototype.closePath = function() {
<ide> // Add a line curve if start and end of lines are not connected
<ide> var startPoint = this.curves[0].getPoint(0);
<ide> var endPoint = this.curves[this.curves.length - 1].getPoint(1);
<del>
<add>
<ide> if (! startPoint.equals(endPoint)) {
<ide> this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
<ide> }
<del>
<add>
<ide> };
<ide>
<ide> // To get accurate point with reference to
<ide> THREE.CurvePath.prototype.getCurveLengths = function() {
<ide>
<ide> // We use cache values if curves and cache array are same length
<ide>
<del> if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
<add> if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
<ide>
<ide> return this.cacheLengths;
<ide>
<ide> THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
<ide> return oldPts;
<ide>
<ide> };
<del>
<ide><path>src/extras/core/Path.js
<ide> THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
<ide> //THREE.log(points);
<ide>
<ide> break;
<del>
<add>
<ide> case THREE.PathActions.ELLIPSE:
<ide>
<ide> var aX = args[ 0 ], aY = args[ 1 ],
<ide> THREE.Path.prototype.toShapes = function( isCCW, noHoles ) {
<ide> args = item.args;
<ide> action = item.action;
<ide>
<del> if ( action == THREE.PathActions.MOVE_TO ) {
<add> if ( action === THREE.PathActions.MOVE_TO ) {
<ide>
<del> if ( lastPath.actions.length != 0 ) {
<add> if ( lastPath.actions.length !== 0 ) {
<ide>
<ide> subPaths.push( lastPath );
<ide> lastPath = new THREE.Path();
<ide> THREE.Path.prototype.toShapes = function( isCCW, noHoles ) {
<ide>
<ide> }
<ide>
<del> if ( lastPath.actions.length != 0 ) {
<add> if ( lastPath.actions.length !== 0 ) {
<ide>
<ide> subPaths.push( lastPath );
<ide>
<ide> THREE.Path.prototype.toShapes = function( isCCW, noHoles ) {
<ide> }
<ide> if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
<ide>
<del> if ( inPt.y == edgeLowPt.y ) {
<del> if ( inPt.x == edgeLowPt.x ) return true; // inPt is on contour ?
<add> if ( inPt.y === edgeLowPt.y ) {
<add> if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
<ide> // continue; // no intersection or edgeLowPt => doesn't count !!!
<ide> } else {
<ide> var perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
<del> if ( perpEdge == 0 ) return true; // inPt is on contour ?
<add> if ( perpEdge === 0 ) return true; // inPt is on contour ?
<ide> if ( perpEdge < 0 ) continue;
<ide> inside = ! inside; // true intersection left of inPt
<ide> }
<ide> } else { // parallel or colinear
<del> if ( inPt.y != edgeLowPt.y ) continue; // parallel
<add> if ( inPt.y !== edgeLowPt.y ) continue; // parallel
<ide> // egde lies on the same horizontal line as inPt
<ide> if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
<ide> ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
<ide> THREE.Path.prototype.toShapes = function( isCCW, noHoles ) {
<ide>
<ide>
<ide> var subPaths = extractSubpaths( this.actions );
<del> if ( subPaths.length == 0 ) return [];
<add> if ( subPaths.length === 0 ) return [];
<ide>
<ide> if ( noHoles === true ) return toShapesNoHoles( subPaths );
<ide>
<ide>
<ide> var solid, tmpPath, tmpShape, shapes = [];
<ide>
<del> if ( subPaths.length == 1) {
<add> if ( subPaths.length === 1) {
<ide>
<ide> tmpPath = subPaths[0];
<ide> tmpShape = new THREE.Shape();
<ide> THREE.Path.prototype.toShapes = function( isCCW, noHoles ) {
<ide> holesFirst = isCCW ? ! holesFirst : holesFirst;
<ide>
<ide> // THREE.log("Holes first", holesFirst);
<del>
<add>
<ide> var betterShapeHoles = [];
<ide> var newShapes = [];
<ide> var newShapeHoles = [];
<ide> THREE.Path.prototype.toShapes = function( isCCW, noHoles ) {
<ide> newShapes[mainIdx] = { s: new THREE.Shape(), p: tmpPoints };
<ide> newShapes[mainIdx].s.actions = tmpPath.actions;
<ide> newShapes[mainIdx].s.curves = tmpPath.curves;
<del>
<add>
<ide> if ( holesFirst ) mainIdx ++;
<ide> newShapeHoles[mainIdx] = [];
<ide>
<ide> THREE.Path.prototype.toShapes = function( isCCW, noHoles ) {
<ide> var hole_unassigned = true;
<ide> for (var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
<ide> if ( isPointInsidePolygon( ho.p, newShapes[s2Idx].p ) ) {
<del> if ( sIdx != s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
<add> if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
<ide> if ( hole_unassigned ) {
<ide> hole_unassigned = false;
<ide> betterShapeHoles[s2Idx].push( ho );
<ide><path>src/extras/core/Shape.js
<ide> THREE.Shape.Utils = {
<ide>
<ide> function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
<ide> // inOtherPt needs to be colinear to the inSegment
<del> if ( inSegPt1.x != inSegPt2.x ) {
<add> if ( inSegPt1.x !== inSegPt2.x ) {
<ide> if ( inSegPt1.x < inSegPt2.x ) {
<ide> return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
<ide> } else {
<ide> THREE.Shape.Utils = {
<ide>
<ide> // i.e. to reduce rounding errors
<ide> // intersection at endpoint of segment#1?
<del> if ( perpSeg2 == 0 ) {
<add> if ( perpSeg2 === 0 ) {
<ide> if ( ( inExcludeAdjacentSegs ) &&
<del> ( ( perpSeg1 == 0 ) || ( perpSeg1 == limit ) ) ) return [];
<add> ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
<ide> return [ inSeg1Pt1 ];
<ide> }
<del> if ( perpSeg2 == limit ) {
<add> if ( perpSeg2 === limit ) {
<ide> if ( ( inExcludeAdjacentSegs ) &&
<del> ( ( perpSeg1 == 0 ) || ( perpSeg1 == limit ) ) ) return [];
<add> ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
<ide> return [ inSeg1Pt2 ];
<ide> }
<ide> // intersection at endpoint of segment#2?
<del> if ( perpSeg1 == 0 ) return [ inSeg2Pt1 ];
<del> if ( perpSeg1 == limit ) return [ inSeg2Pt2 ];
<add> if ( perpSeg1 === 0 ) return [ inSeg2Pt1 ];
<add> if ( perpSeg1 === limit ) return [ inSeg2Pt2 ];
<ide>
<ide> // return real intersection point
<ide> var factorSeg1 = perpSeg2 / limit;
<ide> return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
<ide> y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
<ide>
<ide> } else { // parallel or colinear
<del> if ( ( perpSeg1 != 0 ) ||
<del> ( seg2dy * seg1seg2dx != seg2dx * seg1seg2dy ) ) return [];
<add> if ( ( perpSeg1 !== 0 ) ||
<add> ( seg2dy * seg1seg2dx !== seg2dx * seg1seg2dy ) ) return [];
<ide>
<ide> // they are collinear or degenerate
<del> var seg1Pt = ( (seg1dx == 0) && (seg1dy == 0) ); // segment1 ist just a point?
<del> var seg2Pt = ( (seg2dx == 0) && (seg2dy == 0) ); // segment2 ist just a point?
<add> var seg1Pt = ( (seg1dx === 0) && (seg1dy === 0) ); // segment1 ist just a point?
<add> var seg2Pt = ( (seg2dx === 0) && (seg2dy === 0) ); // segment2 ist just a point?
<ide> // both segments are points
<ide> if ( seg1Pt && seg2Pt ) {
<del> if ( (inSeg1Pt1.x != inSeg2Pt1.x) ||
<del> (inSeg1Pt1.y != inSeg2Pt1.y) ) return []; // they are distinct points
<del> return [ inSeg1Pt1 ]; // they are the same point
<add> if ( (inSeg1Pt1.x !== inSeg2Pt1.x) ||
<add> (inSeg1Pt1.y !== inSeg2Pt1.y) ) return []; // they are distinct points
<add> return [ inSeg1Pt1 ]; // they are the same point
<ide> }
<ide> // segment#1 is a single point
<ide> if ( seg1Pt ) {
<ide> THREE.Shape.Utils = {
<ide> // they are collinear segments, which might overlap
<ide> var seg1min, seg1max, seg1minVal, seg1maxVal;
<ide> var seg2min, seg2max, seg2minVal, seg2maxVal;
<del> if (seg1dx != 0) { // the segments are NOT on a vertical line
<add> if (seg1dx !== 0) { // the segments are NOT on a vertical line
<ide> if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
<ide> seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
<ide> seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
<ide> THREE.Shape.Utils = {
<ide> }
<ide> if ( seg1minVal <= seg2minVal ) {
<ide> if ( seg1maxVal < seg2minVal ) return [];
<del> if ( seg1maxVal == seg2minVal ) {
<add> if ( seg1maxVal === seg2minVal ) {
<ide> if ( inExcludeAdjacentSegs ) return [];
<ide> return [ seg2min ];
<ide> }
<ide> if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
<ide> return [ seg2min, seg2max ];
<ide> } else {
<ide> if ( seg1minVal > seg2maxVal ) return [];
<del> if ( seg1minVal == seg2maxVal ) {
<add> if ( seg1minVal === seg2maxVal ) {
<ide> if ( inExcludeAdjacentSegs ) return [];
<ide> return [ seg1min ];
<ide> }
<ide> THREE.Shape.Utils = {
<ide> }
<ide>
<ide> };
<del>
<ide><path>src/extras/curves/CatmullRomCurve3.js
<ide> THREE.CatmullRomCurve3 = ( function() {
<ide> intPoint = Math.floor( point );
<ide> weight = point - intPoint;
<ide>
<del> if ( weight == 0 && intPoint == l - 1 ) {
<add> if ( weight === 0 && intPoint === l - 1 ) {
<ide>
<ide> intPoint = l - 2;
<ide> weight = 1;
<ide> THREE.CatmullRomCurve3 = ( function() {
<ide>
<ide> var p0, p1, p2, p3;
<ide>
<del> if ( intPoint == 0 ) {
<add> if ( intPoint === 0 ) {
<ide>
<ide> // extrapolate first point
<ide> tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
<ide><path>src/extras/curves/SplineCurve.js
<ide> THREE.SplineCurve.prototype.getPoint = function ( t ) {
<ide> var intPoint = Math.floor( point );
<ide> var weight = point - intPoint;
<ide>
<del> var point0 = points[ intPoint == 0 ? intPoint : intPoint - 1 ];
<add> var point0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
<ide> var point1 = points[ intPoint ];
<ide> var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
<ide> var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
<ide><path>src/extras/geometries/ExtrudeGeometry.js
<ide> THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
<ide> if ( v_prev_x < - EPSILON ) {
<ide> if ( v_next_x < - EPSILON ) { direction_eq = true; }
<ide> } else {
<del> if ( Math.sign(v_prev_y) == Math.sign(v_next_y) ) { direction_eq = true; }
<add> if ( Math.sign(v_prev_y) === Math.sign(v_next_y) ) { direction_eq = true; }
<ide> }
<ide> }
<ide>
<ide><path>src/extras/geometries/PolyhedronGeometry.js
<ide> THREE.PolyhedronGeometry = function ( vertices, indices, radius, detail ) {
<ide>
<ide> for ( var j = 0; j <= rows; j ++) {
<ide>
<del> if ( j == 0 && i == cols ) {
<add> if ( j === 0 && i === cols ) {
<ide>
<ide> v[ i ][ j ] = aj;
<ide>
<ide> THREE.PolyhedronGeometry = function ( vertices, indices, radius, detail ) {
<ide>
<ide> var k = Math.floor( j / 2 );
<ide>
<del> if ( j % 2 == 0 ) {
<add> if ( j % 2 === 0 ) {
<ide>
<ide> make(
<ide> v[ i ][ k + 1],
<ide><path>src/loaders/CompressedTextureLoader.js
<ide> THREE.CompressedTextureLoader.prototype = {
<ide>
<ide> if ( loaded === 6 ) {
<ide>
<del> if (texDatas.mipmapCount == 1)
<add> if (texDatas.mipmapCount === 1)
<ide> texture.minFilter = THREE.LinearFilter;
<ide>
<ide> texture.format = texDatas.format;
<ide><path>src/materials/Material.js
<ide> THREE.Material.prototype = {
<ide>
<ide> currentValue.copy( newValue );
<ide>
<del> } else if ( key == 'overdraw' ) {
<add> } else if ( key === 'overdraw' ) {
<ide>
<ide> // ensure overdraw is backwards-compatable with legacy boolean type
<ide> this[ key ] = Number( newValue );
<ide><path>src/math/Math.js
<ide> THREE.Math = {
<ide>
<ide> for ( var i = 0; i < 36; i ++ ) {
<ide>
<del> if ( i == 8 || i == 13 || i == 18 || i == 23 ) {
<add> if ( i === 8 || i === 13 || i === 18 || i === 23 ) {
<ide>
<ide> uuid[ i ] = '-';
<ide>
<del> } else if ( i == 14 ) {
<add> } else if ( i === 14 ) {
<ide>
<ide> uuid[ i ] = '4';
<ide>
<ide> THREE.Math = {
<ide> if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0;
<ide> r = rnd & 0xf;
<ide> rnd = rnd >> 4;
<del> uuid[ i ] = chars[ ( i == 19 ) ? ( r & 0x3 ) | 0x8 : r ];
<add> uuid[ i ] = chars[ ( i === 19 ) ? ( r & 0x3 ) | 0x8 : r ];
<ide>
<ide> }
<ide> }
<ide><path>src/math/Matrix4.js
<ide> THREE.Matrix4.prototype = {
<ide>
<ide> var det = n11 * te[ 0 ] + n21 * te[ 4 ] + n31 * te[ 8 ] + n41 * te[ 12 ];
<ide>
<del> if ( det == 0 ) {
<add> if ( det === 0 ) {
<ide>
<ide> var msg = "THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0";
<ide>
<ide><path>src/math/Plane.js
<ide> THREE.Plane.prototype = {
<ide>
<ide> var denominator = this.normal.dot( direction );
<ide>
<del> if ( denominator == 0 ) {
<add> if ( denominator === 0 ) {
<ide>
<ide> // line is coplanar, return origin
<del> if ( this.distanceToPoint( line.start ) == 0 ) {
<add> if ( this.distanceToPoint( line.start ) === 0 ) {
<ide>
<ide> return result.copy( line.start );
<ide>
<ide> THREE.Plane.prototype = {
<ide>
<ide> equals: function ( plane ) {
<ide>
<del> return plane.normal.equals( this.normal ) && ( plane.constant == this.constant );
<add> return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
<ide>
<ide> },
<ide>
<ide><path>src/math/Ray.js
<ide> THREE.Ray.prototype = {
<ide> // in order to always return an intersect point that is in front of the ray.
<ide> if ( t0 < 0 ) return this.at( t1, optionalTarget );
<ide>
<del> // else t0 is in front of the ray, so return the first collision point scaled by t0
<add> // else t0 is in front of the ray, so return the first collision point scaled by t0
<ide> return this.at( t0, optionalTarget );
<ide>
<ide> }
<ide> THREE.Ray.prototype = {
<ide> distanceToPlane: function ( plane ) {
<ide>
<ide> var denominator = plane.normal.dot( this.direction );
<del> if ( denominator == 0 ) {
<add> if ( denominator === 0 ) {
<ide>
<ide> // line is coplanar, return origin
<del> if ( plane.distanceToPoint( this.origin ) == 0 ) {
<add> if ( plane.distanceToPoint( this.origin ) === 0 ) {
<ide>
<ide> return 0;
<ide>
<ide><path>src/math/Spline.js
<ide> THREE.Spline = function ( points ) {
<ide> point = ( this.points.length - 1 ) * index;
<ide> intPoint = Math.floor( point );
<ide>
<del> if ( intPoint != oldIntPoint ) {
<add> if ( intPoint !== oldIntPoint ) {
<ide>
<ide> chunkLengths[ intPoint ] = totalLength;
<ide> oldIntPoint = intPoint;
<ide><path>src/math/Triangle.js
<ide> THREE.Triangle.barycoordFromPoint = function () {
<ide> var result = optionalTarget || new THREE.Vector3();
<ide>
<ide> // colinear or singular triangle
<del> if ( denom == 0 ) {
<add> if ( denom === 0 ) {
<ide> // arbitrary location outside of triangle?
<ide> // not sure if this is the best idea, maybe should be returning undefined
<ide> return result.set( - 2, - 1, - 1 ); | 19 |
PHP | PHP | update usage of deprecated method | db0e253cdf6dddc452a4de85b9081fd475a3ce07 | <ide><path>src/ORM/ResultSet.php
<ide> protected function _getTypes($table, $fields)
<ide> {
<ide> $types = [];
<ide> $schema = $table->getSchema();
<del> $map = array_keys((array)Type::map() + ['string' => 1, 'text' => 1, 'boolean' => 1]);
<add> $map = array_keys((array)Type::getMap() + ['string' => 1, 'text' => 1, 'boolean' => 1]);
<ide> $typeMap = array_combine(
<ide> $map,
<ide> array_map(['Cake\Database\Type', 'build'], $map) | 1 |
Javascript | Javascript | expand worker test for non-shared arraybuffer | 4201cdde89af76d80ec794e82ee0b1c47c107299 | <ide><path>test/parallel/test-worker-sharedarraybuffer-from-worker-thread.js
<ide> const assert = require('assert');
<ide> const { Worker } = require('worker_threads');
<ide>
<ide> // Regression test for https://github.com/nodejs/node/issues/28777
<del>// Make sure that SharedArrayBuffers created in Worker threads are accessible
<del>// after the creating thread ended.
<add>// Make sure that SharedArrayBuffers and transferred ArrayBuffers created in
<add>// Worker threads are accessible after the creating thread ended.
<ide>
<del>const w = new Worker(`
<del>const { parentPort } = require('worker_threads');
<del>const sharedArrayBuffer = new SharedArrayBuffer(4);
<del>parentPort.postMessage(sharedArrayBuffer);
<del>`, { eval: true });
<add>for (const ctor of ['ArrayBuffer', 'SharedArrayBuffer']) {
<add> const w = new Worker(`
<add> const { parentPort } = require('worker_threads');
<add> const arrayBuffer = new ${ctor}(4);
<add> parentPort.postMessage(
<add> arrayBuffer,
<add> '${ctor}' === 'SharedArrayBuffer' ? [] : [arrayBuffer]);
<add> `, { eval: true });
<ide>
<del>let sharedArrayBuffer;
<del>w.once('message', common.mustCall((message) => sharedArrayBuffer = message));
<del>w.once('exit', common.mustCall(() => {
<del> const uint8array = new Uint8Array(sharedArrayBuffer);
<del> uint8array[0] = 42;
<del> assert.deepStrictEqual(uint8array, new Uint8Array([42, 0, 0, 0]));
<del>}));
<add> let arrayBuffer;
<add> w.once('message', common.mustCall((message) => arrayBuffer = message));
<add> w.once('exit', common.mustCall(() => {
<add> assert.strictEqual(arrayBuffer.constructor.name, ctor);
<add> const uint8array = new Uint8Array(arrayBuffer);
<add> uint8array[0] = 42;
<add> assert.deepStrictEqual(uint8array, new Uint8Array([42, 0, 0, 0]));
<add> }));
<add>} | 1 |
Javascript | Javascript | fix template injection tests | a8bb87b4a1606c83cf0b30783d2addcdf6f24955 | <ide><path>packages/ember-application/tests/system/application_test.js
<ide> moduleFor('Ember.Application', class extends ApplicationTestCase {
<ide> verifyRegistration(assert, application, P`template:components/-default`);
<ide> verifyRegistration(assert, application, 'template:-outlet');
<ide> verifyInjection(assert, application, 'view:-outlet', 'template', 'template:-outlet');
<del> verifyInjection(assert, application, 'template', 'env', 'service:-glimmer-environment');
<add> verifyInjection(assert, application, 'template', 'options', P`template-options:main`);
<ide>
<ide> assert.deepEqual(application.registeredOptionsForType('helper'), { instantiate: false }, `optionsForType 'helper'`);
<ide> }
<ide><path>packages/ember-application/tests/system/engine_test.js
<ide> moduleFor('Ember.Engine', class extends TestCase {
<ide> verifyRegistration(assert, engine, P`template:components/-default`);
<ide> verifyRegistration(assert, engine, 'template:-outlet');
<ide> verifyInjection(assert, engine, 'view:-outlet', 'template', 'template:-outlet');
<del> verifyInjection(assert, engine, 'template', 'env', 'service:-glimmer-environment');
<add> verifyInjection(assert, engine, 'template', 'options', P`template-options:main`);
<ide> assert.deepEqual(engine.registeredOptionsForType('helper'), { instantiate: false }, `optionsForType 'helper'`);
<ide> }
<ide> }); | 2 |
Javascript | Javascript | reduce number of mapper calls for min/max | 4c9168f2def10ab490b4d7299480f1143f3257a6 | <ide><path>dist/immutable.js
<ide> function sortFactory(iterable, comparator, mapper) {
<ide> }
<ide> function maxFactory(iterable, comparator, mapper) {
<ide> if (mapper) {
<del> var entry = iterable.entrySeq().reduce((function(max, next) {
<del> return comparator(mapper(next[1], next[0], iterable), mapper(max[1], max[0], iterable)) > 0 ? next : max;
<add> var entry = iterable.toSeq().map((function(v, k) {
<add> return [v, mapper(v, k, iterable)];
<add> })).reduce((function(max, next) {
<add> return comparator(next[1], max[1]) > 0 ? next : max;
<ide> }));
<del> return entry && entry[1];
<add> return entry && entry[0];
<ide> } else {
<ide> return iterable.reduce((function(max, next) {
<ide> return comparator(next, max) > 0 ? next : max;
<ide><path>dist/immutable.min.js
<ide> * LICENSE file in the root directory of this source tree. An additional grant
<ide> * of patent rights can be found in the PATENTS file in the same directory.
<ide> */
<del>function t(){function t(t,e,r,n){var i;if(n){var u=n.prototype;i=lr.create(u)}else i=t.prototype;return lr.keys(e).forEach(function(t){i[t]=e[t]}),lr.keys(r).forEach(function(e){t[e]=r[e]}),i.constructor=t,t.prototype=i,t}function e(t,e,r,n){return lr.getPrototypeOf(e)[r].apply(t,n)}function r(t,r,n){e(t,r,"constructor",n)}function n(t,e){return t===e?0!==t||0!==e||1/t===1/e:t!==t?e!==e:t&&"function"==typeof t.equals?t.equals(e):!1}function i(t,e){if(!t)throw Error(e)}function u(t){return t.value=!1,t}function s(t){t&&(t.value=!0)}function o(){}function a(t,e){e=e||0;for(var r=Math.max(0,t.length-e),n=Array(r),i=0;r>i;i++)n[i]=t[i+e];return n}function h(t){i(1/0!==t,"Cannot perform this action with an infinite size.")}function c(t){return void 0===t.size&&(t.size=t.__iterate(_)),t.size}function f(t,e){return e>=0?e:c(t)+e}function _(){return!0}function l(t,e,r){return(0===t||void 0!==r&&-r>=t)&&(void 0===e||void 0!==r&&e>=r)}function v(t,e){return d(t,e,0)}function p(t,e){return d(t,e,e)}function d(t,e,r){return void 0===t?r:0>t?Math.max(0,e+t):void 0===e?t:Math.min(e,t)}function y(t){if(!t)return 0;if(t===!0)return 1;var e=typeof t;if("number"===e){if((0|t)===t)return t&br;t=""+t,e="string"}return"string"===e?t.length>Mr?g(t):m(t):t.hashCode?y("function"==typeof t.hashCode?t.hashCode():t.hashCode):w(t)}function g(t){var e=Or[t];return void 0===e&&(e=m(t),kr===Er&&(kr=0,Or={}),kr++,Or[t]=e),e}function m(t){for(var e=0,r=0;t.length>r;r++)e=31*e+t.charCodeAt(r)&br;return e}function w(t){var e=Ir&&Ir.get(t);if(e)return e;if(e=t[xr])return e;if(!zr){if(e=t.propertyIsEnumerable&&t.propertyIsEnumerable[xr])return e;if(e=S(t))return e}if(Object.isExtensible&&!Object.isExtensible(t))throw Error("Non-extensible objects are not allowed as keys.");if(e=++qr&br,Ir)Ir.set(t,e);else if(zr)Object.defineProperty(t,xr,{enumerable:!1,configurable:!1,writable:!1,value:e});else if(t.propertyIsEnumerable&&t.propertyIsEnumerable===t.constructor.prototype.propertyIsEnumerable)t.propertyIsEnumerable=function(){return this.constructor.prototype.propertyIsEnumerable.apply(this,arguments)
<add>function t(){function t(t,e,r,n){var i;if(n){var u=n.prototype;i=lr.create(u)}else i=t.prototype;return lr.keys(e).forEach(function(t){i[t]=e[t]}),lr.keys(r).forEach(function(e){t[e]=r[e]}),i.constructor=t,t.prototype=i,t}function e(t,e,r,n){return lr.getPrototypeOf(e)[r].apply(t,n)}function r(t,r,n){e(t,r,"constructor",n)}function n(t,e){return t===e?0!==t||0!==e||1/t===1/e:t!==t?e!==e:t&&"function"==typeof t.equals?t.equals(e):!1}function i(t,e){if(!t)throw Error(e)}function u(t){return t.value=!1,t}function s(t){t&&(t.value=!0)}function o(){}function a(t,e){e=e||0;for(var r=Math.max(0,t.length-e),n=Array(r),i=0;r>i;i++)n[i]=t[i+e];return n}function h(t){i(1/0!==t,"Cannot perform this action with an infinite size.")}function c(t){return void 0===t.size&&(t.size=t.__iterate(_)),t.size}function f(t,e){return e>=0?e:c(t)+e}function _(){return!0}function l(t,e,r){return(0===t||void 0!==r&&-r>=t)&&(void 0===e||void 0!==r&&e>=r)}function v(t,e){return d(t,e,0)}function p(t,e){return d(t,e,e)}function d(t,e,r){return void 0===t?r:0>t?Math.max(0,e+t):void 0===e?t:Math.min(e,t)}function y(t){if(!t)return 0;if(t===!0)return 1;var e=typeof t;if("number"===e){if((0|t)===t)return t&br;t=""+t,e="string"}return"string"===e?t.length>Mr?m(t):g(t):t.hashCode?y("function"==typeof t.hashCode?t.hashCode():t.hashCode):w(t)}function m(t){var e=Or[t];return void 0===e&&(e=g(t),kr===Er&&(kr=0,Or={}),kr++,Or[t]=e),e}function g(t){for(var e=0,r=0;t.length>r;r++)e=31*e+t.charCodeAt(r)&br;return e}function w(t){var e=Ir&&Ir.get(t);if(e)return e;if(e=t[xr])return e;if(!zr){if(e=t.propertyIsEnumerable&&t.propertyIsEnumerable[xr])return e;if(e=S(t))return e}if(Object.isExtensible&&!Object.isExtensible(t))throw Error("Non-extensible objects are not allowed as keys.");if(e=++qr&br,Ir)Ir.set(t,e);else if(zr)Object.defineProperty(t,xr,{enumerable:!1,configurable:!1,writable:!1,value:e});else if(t.propertyIsEnumerable&&t.propertyIsEnumerable===t.constructor.prototype.propertyIsEnumerable)t.propertyIsEnumerable=function(){return this.constructor.prototype.propertyIsEnumerable.apply(this,arguments)
<ide> },t.propertyIsEnumerable[xr]=e;else{if(!t.nodeType)throw Error("Unable to set a non-enumerable property on object.");t[xr]=e}return e}function S(t){if(t&&t.nodeType>0)switch(t.nodeType){case 1:return t.uniqueID;case 9:return t.documentElement&&t.documentElement.uniqueID}}function z(t,e,r,n){var i=0===t?e:1===t?r:[e,r];return n?n.value=i:n={value:i,done:!1},n}function I(){return{value:void 0,done:!0}}function b(t){return!!M(t)}function q(t){return t&&"function"==typeof t.next}function x(t){var e=M(t);return e&&e.call(t)}function M(t){var e=t&&(Rr&&t[Rr]||t[jr]);return"function"==typeof e?e:void 0}function E(t){return!(!t||!t[Br])}function k(t){return!(!t||!t[Pr])}function O(t){return!(!t||!t[Jr])}function D(t){return k(t)||O(t)}function A(t,e){return e}function C(t,e){return[e,t]}function j(t){return function(){return!t.apply(this,arguments)}}function R(t){return function(){return-t.apply(this,arguments)}}function U(t){return"string"==typeof t?JSON.stringify(t):t}function K(t,e){return t>e?1:e>t?-1:0}function L(t,e){var r=t.prototype,n=function(t){r[t]=e[t]};return Object.keys(e).forEach(n),Object.getOwnPropertySymbols&&Object.getOwnPropertySymbols(e).forEach(n),t}function T(t){return!(!t||!t[nn])}function W(){return hn||(hn=new un([]))}function B(t){var e=Array.isArray(t)?new un(t).fromEntrySeq():q(t)?new an(t).fromEntrySeq():b(t)?new on(t).fromEntrySeq():"object"==typeof t?new sn(t):void 0;if(!e)throw new TypeError("Expected Array or iterable object of [k, v] entries, or keyed object: "+t);return e}function P(t){var e=V(t);if(!e)throw new TypeError("Expected Array or iterable object of values: "+t);return e}function J(t){var e=V(t)||"object"==typeof t&&new sn(t);if(!e)throw new TypeError("Expected Array or iterable object of values, or keyed object: "+t);return e}function V(t){return N(t)?new un(t):q(t)?new an(t):b(t)?new on(t):void 0}function N(t){return t&&"number"==typeof t.length}function Y(t,e,r,n){h(t.size);var i=t._cache;if(i){for(var u=i.length-1,s=0;u>=s;s++){var o=i[r?u-s:s];if(e(o[1],n?o[0]:s,t)===!1)return s+1
<del>}return s}return t.__iterateUncached(e,r)}function Q(t,e,r,n){var i=t._cache;if(i){var u=i.length-1,s=0;return new Kr(function(){var t=i[r?u-s:s];return s++>u?I():z(e,n?t[0]:s-1,t[1])})}return t.__iteratorUncached(e,r)}function X(t,e){return e?F(e,t,"",{"":t}):G(t)}function F(t,e,r,n){return Array.isArray(e)?t.call(n,r,$r(e).map(function(r,n){return F(t,r,n,e)})):H(e)?t.call(n,r,Hr(e).map(function(r,n){return F(t,r,n,e)})):e}function G(t){return Array.isArray(t)?$r(t).map(G).toList():H(t)?Hr(t).map(G).toMap():t}function H(t){return t&&t.constructor===Object}function Z(t){return!(!t||!t[gn])}function $(t,e){return z(t,e[0],e[1])}function te(t,e){return{node:t,index:0,__prev:e}}function ee(t,e,r,n){var i=Object.create(mn);return i.size=t,i._root=e,i.__ownerID=r,i.__hash=n,i.__altered=!1,i}function re(){return kn||(kn=ee(0))}function ne(t,e,r){var n=u(wr),i=u(Sr),s=ie(t._root,t.__ownerID,0,y(e),e,r,n,i);if(!i.value)return t;var o=t.size+(n.value?r===mr?-1:1:0);return t.__ownerID?(t.size=o,t._root=s,t.__hash=void 0,t.__altered=!0,t):s?ee(o,s):re()}function ie(t,e,r,n,i,u,o,a){return t?t.update(e,r,n,i,u,o,a):u===mr?t:(s(a),s(o),new xn(e,n,[i,u]))}function ue(t){return t.constructor===xn||t.constructor===bn}function se(t,e,r,n,i){if(t.hash===n)return new bn(e,n,[t.entry,i]);var u,s=(0===r?t.hash:t.hash>>>r)&gr,o=(0===r?n:n>>>r)&gr,a=s===o?[se(t,e,r+dr,n,i)]:(u=new xn(e,n,i),o>s?[t,u]:[u,t]);return new wn(e,1<<s|1<<o,a)}function oe(t,e,r,n){for(var i=0,u=0,s=Array(r),o=0,a=1,h=e.length;h>o;o++,a<<=1){var c=e[o];void 0!==c&&o!==n&&(i|=a,s[u++]=c)}return new wn(t,i,s)}function ae(t,e,r,n,i){for(var u=0,s=Array(yr),o=0;0!==r;o++,r>>>=1)s[o]=1&r?e[u++]:void 0;return s[n]=i,new zn(t,u+1,s)}function he(t,e,r){for(var n=[],i=0;r.length>i;i++){var u=r[i],s=Nr(u);E(u)||(s=s.map(function(t){return X(t)})),n.push(s)}return fe(t,e,n)}function ce(t){return function(e,r){return e&&e.mergeDeepWith&&E(r)?e.mergeDeepWith(t,r):t?t(e,r):r}}function fe(t,e,r){return 0===r.length?t:t.withMutations(function(t){for(var n=e?function(r,n){t.update(n,mr,function(t){return t===mr?r:e(t,r)
<del>})}:function(e,r){t.set(r,e)},i=0;r.length>i;i++)r[i].forEach(n)})}function _e(t,e,r,n,u){i(!t||t.set,"updateIn with invalid keyPath");var s=e[u],o=t?t.get(s,mr):mr,a=o===mr?void 0:o,h=u===e.length-1?n(o===mr?r:o):_e(a,e,r,n,u+1);return h===a?t:h===mr?t&&t.remove(s):(t||re()).set(s,h)}function le(t){return t-=t>>1&1431655765,t=(858993459&t)+(t>>2&858993459),t=t+(t>>4)&252645135,t+=t>>8,t+=t>>16,127&t}function ve(t,e,r,n){var i=n?t:a(t);return i[e]=r,i}function pe(t,e,r,n){var i=t.length+1;if(n&&e+1===i)return t[e]=r,t;for(var u=Array(i),s=0,o=0;i>o;o++)o===e?(u[o]=r,s=-1):u[o]=t[o+s];return u}function de(t,e,r){var n=t.length-1;if(r&&e===n)return t.pop(),t;for(var i=Array(n),u=0,s=0;n>s;s++)s===e&&(u=1),i[s]=t[s+u];return i}function ye(t){var e=Ke(t);return e._iter=t,e.size=t.size,e.flip=function(){return t},e.reverse=function(){var e=t.reverse.apply(this);return e.flip=function(){return t.reverse()},e},e.has=function(e){return t.contains(e)},e.contains=function(e){return t.has(e)},e.cacheResult=Le,e.__iterateUncached=function(e,r){var n=this;return t.__iterate(function(t,r){return e(r,t,n)!==!1},r)},e.__iteratorUncached=function(e,r){if(e===Cr){var n=t.__iterator(e,r);return new Kr(function(){var t=n.next();if(!t.done){var e=t.value[0];t.value[0]=t.value[1],t.value[1]=e}return t})}return t.__iterator(e===Ar?Dr:Ar,r)},e}function ge(t,e,r){var n=Ke(t);return n.size=t.size,n.has=function(e){return t.has(e)},n.get=function(n,i){var u=t.get(n,mr);return u===mr?i:e.call(r,u,n,t)},n.__iterateUncached=function(n,i){var u=this;return t.__iterate(function(t,i,s){return n(e.call(r,t,i,s),i,u)!==!1},i)},n.__iteratorUncached=function(n,i){var u=t.__iterator(Cr,i);return new Kr(function(){var i=u.next();if(i.done)return i;var s=i.value,o=s[0];return z(n,o,e.call(r,s[1],o,t),i)})},n}function me(t,e){var r=Ke(t);return r._iter=t,r.size=t.size,r.reverse=function(){return t},t.flip&&(r.flip=function(){var e=ye(t);return e.reverse=function(){return t.flip()},e}),r.get=function(r,n){return t.get(e?r:-1-r,n)},r.has=function(r){return t.has(e?r:-1-r)
<del>},r.contains=function(e){return t.contains(e)},r.cacheResult=Le,r.__iterate=function(e,r){var n=this;return t.__iterate(function(t,r){return e(t,r,n)},!r)},r.__iterator=function(e,r){return t.__iterator(e,!r)},r}function we(t,e,r,n){var i=Ke(t);return n&&(i.has=function(n){var i=t.get(n,mr);return i!==mr&&!!e.call(r,i,n,t)},i.get=function(n,i){var u=t.get(n,mr);return u!==mr&&e.call(r,u,n,t)?u:i}),i.__iterateUncached=function(i,u){var s=this,o=0;return t.__iterate(function(t,u,a){return e.call(r,t,u,a)?(o++,i(t,n?u:o-1,s)):void 0},u),o},i.__iteratorUncached=function(i,u){var s=t.__iterator(Cr,u),o=0;return new Kr(function(){for(;;){var u=s.next();if(u.done)return u;var a=u.value,h=a[0],c=a[1];if(e.call(r,c,h,t))return z(i,n?h:o++,c,u)}})},i}function Se(t,e,r){var n=yn().asMutable();return t.__iterate(function(i,u){n.update(e.call(r,i,u,t),0,function(t){return t+1})}),n.asImmutable()}function ze(t,e,r){var n=k(t),i=yn().asMutable();t.__iterate(function(u,s){i.update(e.call(r,u,s,t),[],function(t){return t.push(n?[s,u]:u),t})});var u=Ue(t);return i.map(function(e){return Ce(t,u(e))})}function Ie(t,e){if(e>t.size)return t;0>e&&(e=0);var r=Ke(t);return r.size=t.size&&Math.min(t.size,e),r.__iterateUncached=function(r,n){var i=this;if(0===e)return 0;if(n)return this.cacheResult().__iterate(r,n);var u=0;return t.__iterate(function(t,n){return++u&&r(t,n,i)!==!1&&e>u}),u},r.__iteratorUncached=function(r,n){if(n)return this.cacheResult().__iterator(r,n);var i=e&&t.__iterator(r,n),u=0;return new Kr(function(){return u++>e?I():i.next()})},r}function be(t,e,r){var n=Ke(t);return n.__iterateUncached=function(n,i){var u=this;if(i)return this.cacheResult().__iterate(n,i);var s=0;return t.__iterate(function(t,i,o){return e.call(r,t,i,o)&&++s&&n(t,i,u)}),s},n.__iteratorUncached=function(n,i){var u=this;if(i)return this.cacheResult().__iterator(n,i);var s=t.__iterator(Cr,i),o=!0;return new Kr(function(){if(!o)return I();var t=s.next();if(t.done)return t;var i=t.value,a=i[0],h=i[1];return e.call(r,h,a,u)?n===Cr?t:z(n,a,h,t):(o=!1,I())
<add>}return s}return t.__iterateUncached(e,r)}function Q(t,e,r,n){var i=t._cache;if(i){var u=i.length-1,s=0;return new Kr(function(){var t=i[r?u-s:s];return s++>u?I():z(e,n?t[0]:s-1,t[1])})}return t.__iteratorUncached(e,r)}function X(t,e){return e?F(e,t,"",{"":t}):G(t)}function F(t,e,r,n){return Array.isArray(e)?t.call(n,r,$r(e).map(function(r,n){return F(t,r,n,e)})):H(e)?t.call(n,r,Hr(e).map(function(r,n){return F(t,r,n,e)})):e}function G(t){return Array.isArray(t)?$r(t).map(G).toList():H(t)?Hr(t).map(G).toMap():t}function H(t){return t&&t.constructor===Object}function Z(t){return!(!t||!t[mn])}function $(t,e){return z(t,e[0],e[1])}function te(t,e){return{node:t,index:0,__prev:e}}function ee(t,e,r,n){var i=Object.create(gn);return i.size=t,i._root=e,i.__ownerID=r,i.__hash=n,i.__altered=!1,i}function re(){return kn||(kn=ee(0))}function ne(t,e,r){var n=u(wr),i=u(Sr),s=ie(t._root,t.__ownerID,0,y(e),e,r,n,i);if(!i.value)return t;var o=t.size+(n.value?r===gr?-1:1:0);return t.__ownerID?(t.size=o,t._root=s,t.__hash=void 0,t.__altered=!0,t):s?ee(o,s):re()}function ie(t,e,r,n,i,u,o,a){return t?t.update(e,r,n,i,u,o,a):u===gr?t:(s(a),s(o),new xn(e,n,[i,u]))}function ue(t){return t.constructor===xn||t.constructor===bn}function se(t,e,r,n,i){if(t.hash===n)return new bn(e,n,[t.entry,i]);var u,s=(0===r?t.hash:t.hash>>>r)&mr,o=(0===r?n:n>>>r)&mr,a=s===o?[se(t,e,r+dr,n,i)]:(u=new xn(e,n,i),o>s?[t,u]:[u,t]);return new wn(e,1<<s|1<<o,a)}function oe(t,e,r,n){for(var i=0,u=0,s=Array(r),o=0,a=1,h=e.length;h>o;o++,a<<=1){var c=e[o];void 0!==c&&o!==n&&(i|=a,s[u++]=c)}return new wn(t,i,s)}function ae(t,e,r,n,i){for(var u=0,s=Array(yr),o=0;0!==r;o++,r>>>=1)s[o]=1&r?e[u++]:void 0;return s[n]=i,new zn(t,u+1,s)}function he(t,e,r){for(var n=[],i=0;r.length>i;i++){var u=r[i],s=Nr(u);E(u)||(s=s.map(function(t){return X(t)})),n.push(s)}return fe(t,e,n)}function ce(t){return function(e,r){return e&&e.mergeDeepWith&&E(r)?e.mergeDeepWith(t,r):t?t(e,r):r}}function fe(t,e,r){return 0===r.length?t:t.withMutations(function(t){for(var n=e?function(r,n){t.update(n,gr,function(t){return t===gr?r:e(t,r)
<add>})}:function(e,r){t.set(r,e)},i=0;r.length>i;i++)r[i].forEach(n)})}function _e(t,e,r,n,u){i(!t||t.set,"updateIn with invalid keyPath");var s=e[u],o=t?t.get(s,gr):gr,a=o===gr?void 0:o,h=u===e.length-1?n(o===gr?r:o):_e(a,e,r,n,u+1);return h===a?t:h===gr?t&&t.remove(s):(t||re()).set(s,h)}function le(t){return t-=t>>1&1431655765,t=(858993459&t)+(t>>2&858993459),t=t+(t>>4)&252645135,t+=t>>8,t+=t>>16,127&t}function ve(t,e,r,n){var i=n?t:a(t);return i[e]=r,i}function pe(t,e,r,n){var i=t.length+1;if(n&&e+1===i)return t[e]=r,t;for(var u=Array(i),s=0,o=0;i>o;o++)o===e?(u[o]=r,s=-1):u[o]=t[o+s];return u}function de(t,e,r){var n=t.length-1;if(r&&e===n)return t.pop(),t;for(var i=Array(n),u=0,s=0;n>s;s++)s===e&&(u=1),i[s]=t[s+u];return i}function ye(t){var e=Ke(t);return e._iter=t,e.size=t.size,e.flip=function(){return t},e.reverse=function(){var e=t.reverse.apply(this);return e.flip=function(){return t.reverse()},e},e.has=function(e){return t.contains(e)},e.contains=function(e){return t.has(e)},e.cacheResult=Le,e.__iterateUncached=function(e,r){var n=this;return t.__iterate(function(t,r){return e(r,t,n)!==!1},r)},e.__iteratorUncached=function(e,r){if(e===Cr){var n=t.__iterator(e,r);return new Kr(function(){var t=n.next();if(!t.done){var e=t.value[0];t.value[0]=t.value[1],t.value[1]=e}return t})}return t.__iterator(e===Ar?Dr:Ar,r)},e}function me(t,e,r){var n=Ke(t);return n.size=t.size,n.has=function(e){return t.has(e)},n.get=function(n,i){var u=t.get(n,gr);return u===gr?i:e.call(r,u,n,t)},n.__iterateUncached=function(n,i){var u=this;return t.__iterate(function(t,i,s){return n(e.call(r,t,i,s),i,u)!==!1},i)},n.__iteratorUncached=function(n,i){var u=t.__iterator(Cr,i);return new Kr(function(){var i=u.next();if(i.done)return i;var s=i.value,o=s[0];return z(n,o,e.call(r,s[1],o,t),i)})},n}function ge(t,e){var r=Ke(t);return r._iter=t,r.size=t.size,r.reverse=function(){return t},t.flip&&(r.flip=function(){var e=ye(t);return e.reverse=function(){return t.flip()},e}),r.get=function(r,n){return t.get(e?r:-1-r,n)},r.has=function(r){return t.has(e?r:-1-r)
<add>},r.contains=function(e){return t.contains(e)},r.cacheResult=Le,r.__iterate=function(e,r){var n=this;return t.__iterate(function(t,r){return e(t,r,n)},!r)},r.__iterator=function(e,r){return t.__iterator(e,!r)},r}function we(t,e,r,n){var i=Ke(t);return n&&(i.has=function(n){var i=t.get(n,gr);return i!==gr&&!!e.call(r,i,n,t)},i.get=function(n,i){var u=t.get(n,gr);return u!==gr&&e.call(r,u,n,t)?u:i}),i.__iterateUncached=function(i,u){var s=this,o=0;return t.__iterate(function(t,u,a){return e.call(r,t,u,a)?(o++,i(t,n?u:o-1,s)):void 0},u),o},i.__iteratorUncached=function(i,u){var s=t.__iterator(Cr,u),o=0;return new Kr(function(){for(;;){var u=s.next();if(u.done)return u;var a=u.value,h=a[0],c=a[1];if(e.call(r,c,h,t))return z(i,n?h:o++,c,u)}})},i}function Se(t,e,r){var n=yn().asMutable();return t.__iterate(function(i,u){n.update(e.call(r,i,u,t),0,function(t){return t+1})}),n.asImmutable()}function ze(t,e,r){var n=k(t),i=yn().asMutable();t.__iterate(function(u,s){i.update(e.call(r,u,s,t),[],function(t){return t.push(n?[s,u]:u),t})});var u=Ue(t);return i.map(function(e){return Ce(t,u(e))})}function Ie(t,e){if(e>t.size)return t;0>e&&(e=0);var r=Ke(t);return r.size=t.size&&Math.min(t.size,e),r.__iterateUncached=function(r,n){var i=this;if(0===e)return 0;if(n)return this.cacheResult().__iterate(r,n);var u=0;return t.__iterate(function(t,n){return++u&&r(t,n,i)!==!1&&e>u}),u},r.__iteratorUncached=function(r,n){if(n)return this.cacheResult().__iterator(r,n);var i=e&&t.__iterator(r,n),u=0;return new Kr(function(){return u++>e?I():i.next()})},r}function be(t,e,r){var n=Ke(t);return n.__iterateUncached=function(n,i){var u=this;if(i)return this.cacheResult().__iterate(n,i);var s=0;return t.__iterate(function(t,i,o){return e.call(r,t,i,o)&&++s&&n(t,i,u)}),s},n.__iteratorUncached=function(n,i){var u=this;if(i)return this.cacheResult().__iterator(n,i);var s=t.__iterator(Cr,i),o=!0;return new Kr(function(){if(!o)return I();var t=s.next();if(t.done)return t;var i=t.value,a=i[0],h=i[1];return e.call(r,h,a,u)?n===Cr?t:z(n,a,h,t):(o=!1,I())
<ide> })},n}function qe(t,e,r){if(0>=e)return t;var n=Ke(t);return n.size=t.size&&Math.max(0,t.size-e),n.__iterateUncached=function(n,i){var u=this;if(i)return this.cacheResult().__iterate(n,i);var s=0,o=!0,a=0;return t.__iterate(function(t,i){return o&&(o=s++<e)?void 0:(a++,n(t,r?i:a-1,u))}),a},n.__iteratorUncached=function(n,i){if(i)return this.cacheResult().__iterator(n,i);var u=e&&t.__iterator(n,i),s=0,o=0;return new Kr(function(){for(;e>s;)s++,u.next();var t=u.next();return r||n===Ar?t:n===Dr?z(n,o++,void 0,t):z(n,o++,t.value[1],t)})},n}function xe(t,e,r,n){var i=Ke(t);return i.__iterateUncached=function(i,u){var s=this;if(u)return this.cacheResult().__iterate(i,u);var o=!0,a=0;return t.__iterate(function(t,u,h){return o&&(o=e.call(r,t,u,h))?void 0:(a++,i(t,n?u:a-1,s))}),a},i.__iteratorUncached=function(i,u){var s=this;if(u)return this.cacheResult().__iterator(i,u);var o=t.__iterator(Cr,u),a=!0,h=0;return new Kr(function(){var t,u,c;do{if(t=o.next(),t.done)return n||i===Ar?t:i===Dr?z(i,h++,void 0,t):z(i,h++,t.value[1],t);var f=t.value;u=f[0],c=f[1],a&&(a=e.call(r,c,u,s))}while(a);return i===Cr?t:z(i,u,c,t)})},i}function Me(t,e){var r=k(t),n=new un([t].concat(e)).map(function(t){return E(t)?r&&(t=Nr(t)):t=r?B(t):P(Array.isArray(t)?t:[t]),t});r?n=n.toKeyedSeq():O(t)||(n=n.toSetSeq());var i=n.flatten(!0);return i.size=n.reduce(function(t,e){if(void 0!==t){var r=e.size;if(void 0!==r)return t+r}},0),i}function Ee(t,e,r){var n=Ke(t);return n.__iterateUncached=function(n,i){function u(t,a){var h=this;t.__iterate(function(t,i){return(!e||e>a)&&E(t)?u(t,a+1):n(t,r?i:s++,h)===!1&&(o=!0),!o},i)}var s=0,o=!1;return u(t,0),s},n.__iteratorUncached=function(n,i){var u=t.__iterator(n,i),s=[],o=0;return new Kr(function(){for(;u;){var t=u.next();if(t.done===!1){var a=t.value;if(n===Cr&&(a=a[1]),e&&!(e>s.length)||!E(a))return r?t:z(n,o++,a,t);s.push(u),u=a.__iterator(n,i)}else u=s.pop()}return I()})},n}function ke(t,e,r){var n=Ue(t);return t.toSeq().map(function(i,u){return n(e.call(r,i,u,t))}).flatten(!0)}function Oe(t,e){var r=Ke(t);
<del>return r.size=t.size&&2*t.size-1,r.__iterateUncached=function(r,n){var i=this,u=0;return t.__iterate(function(t){return(!u||r(e,u++,i)!==!1)&&r(t,u++,i)!==!1},n),u},r.__iteratorUncached=function(r,n){var i,u=t.__iterator(Ar,n),s=0;return new Kr(function(){return(!i||s%2)&&(i=u.next(),i.done)?i:s%2?z(r,s++,e):z(r,s++,i.value,i)})},r}function De(t,e,r){var n=r?function(n,i){return e(r(n[1][1],n[1][0],t),r(i[1][1],i[1][0],t))||n[0]-i[0]}:function(t,r){return e(t[1][1],r[1][1])||t[0]-r[0]},i=[];t.forEach(function(t,e){i.push([i.length,[e,t]])}),i.sort(n);var u=k(t);return i.forEach(u?function(t,e){i[e]=t[1]}:function(t,e){i[e]=t[1][1]}),u?Hr(i):O(t)?$r(i):en(i)}function Ae(t,e,r){if(r){var n=t.entrySeq().reduce(function(n,i){return e(r(i[1],i[0],t),r(n[1],n[0],t))>0?i:n});return n&&n[1]}return t.reduce(function(t,r){return e(r,t)>0?r:t})}function Ce(t,e){return T(t)?e:t.constructor(e)}function je(t){if(t!==Object(t))throw new TypeError("Expected [K, V] tuple: "+t)}function Re(t){return h(t.size),c(t)}function Ue(t){return k(t)?Nr:O(t)?Qr:Xr}function Ke(t){return Object.create((k(t)?Hr:O(t)?$r:en).prototype)}function Le(){return this._iter.cacheResult?(this._iter.cacheResult(),this.size=this._iter.size,this):Fr.prototype.cacheResult.call(this)}function Te(t){return!(!t||!t[Kn])}function We(t,e,r,n,i,u){var s,o=t&&t.array;if(0===e){var a=0>r?-r:0,h=n-r;for(h>yr&&(h=yr),s=a;h>s;s++)if(i(o&&o[u?a+h-1-s:s])===!1)return!1}else{var c=1<<e,f=e-dr;for(s=0;gr>=s;s++){var _=u?gr-s:s,l=r+(_<<e);if(n>l&&l+c>0){var v=o&&o[_];if(!We(v,f,l,n,i,u))return!1}}}return!0}function Be(t,e,r,n,i){return{array:t,level:e,offset:r,max:n,rawMax:n-r>>e,index:0,__prev:i}}function Pe(t,e,r,n,i,u,s){var o=Object.create(Ln);return o.size=e-t,o._origin=t,o._capacity=e,o._level=r,o._root=n,o._tail=i,o.__ownerID=u,o.__hash=s,o.__altered=!1,o}function Je(){return Pn||(Pn=Pe(0,0,dr))}function Ve(t,e,r){if(e=f(t,e),e>=t.size||0>e)return t.withMutations(function(t){0>e?Xe(t,e).set(0,r):Xe(t,0,e+1).set(e,r)});e+=t._origin;var n=t._tail,i=t._root,s=u(Sr);return e>=Ge(t._capacity)?n=Ne(n,t.__ownerID,0,e,r,s):i=Ne(i,t.__ownerID,t._level,e,r,s),s.value?t.__ownerID?(t._root=i,t._tail=n,t.__hash=void 0,t.__altered=!0,t):Pe(t._origin,t._capacity,t._level,i,n):t
<del>}function Ne(t,e,r,n,i,u){var o=n>>>r&gr,a=t&&t.array.length>o;if(!a&&void 0===i)return t;var h;if(r>0){var c=t&&t.array[o],f=Ne(c,e,r-dr,n,i,u);return f===c?t:(h=Ye(t,e),h.array[o]=f,h)}return a&&t.array[o]===i?t:(s(u),h=Ye(t,e),void 0===i&&o===h.array.length-1?h.array.pop():h.array[o]=i,h)}function Ye(t,e){return e&&t&&e===t.ownerID?t:new Tn(t?t.array.slice():[],e)}function Qe(t,e){if(e>=Ge(t._capacity))return t._tail;if(1<<t._level+dr>e){for(var r=t._root,n=t._level;r&&n>0;)r=r.array[e>>>n&gr],n-=dr;return r}}function Xe(t,e,r){var n=t.__ownerID||new o,i=t._origin,u=t._capacity,s=i+e,a=void 0===r?u:0>r?u+r:i+r;if(s===i&&a===u)return t;if(s>=a)return t.clear();for(var h=t._level,c=t._root,f=0;0>s+f;)c=new Tn(c&&c.array.length?[void 0,c]:[],n),h+=dr,f+=1<<h;f&&(s+=f,i+=f,a+=f,u+=f);for(var _=Ge(u),l=Ge(a);l>=1<<h+dr;)c=new Tn(c&&c.array.length?[c]:[],n),h+=dr;var v=t._tail,p=_>l?Qe(t,a-1):l>_?new Tn([],n):v;if(v&&l>_&&u>s&&v.array.length){c=Ye(c,n);for(var d=c,y=h;y>dr;y-=dr){var g=_>>>y&gr;d=d.array[g]=Ye(d.array[g],n)}d.array[_>>>dr&gr]=v}if(u>a&&(p=p&&p.removeAfter(n,0,a)),s>=l)s-=l,a-=l,h=dr,c=null,p=p&&p.removeBefore(n,0,s);else if(s>i||_>l){for(f=0;c;){var m=s>>>h&gr;if(m!==l>>>h&gr)break;m&&(f+=(1<<h)*m),h-=dr,c=c.array[m]}c&&s>i&&(c=c.removeBefore(n,h,s-f)),c&&_>l&&(c=c.removeAfter(n,h,l-f)),f&&(s-=f,a-=f)}return t.__ownerID?(t.size=a-s,t._origin=s,t._capacity=a,t._level=h,t._root=c,t._tail=p,t.__hash=void 0,t.__altered=!0,t):Pe(s,a,h,c,p)}function Fe(t,e,r){for(var n=[],i=0,u=0;r.length>u;u++){var s=r[u],o=Qr(s);o.size>i&&(i=o.size),E(s)||(o=o.map(function(t){return X(t)})),n.push(o)}return i>t.size&&(t=t.setSize(i)),fe(t,e,n)}function Ge(t){return yr>t?0:t-1>>>dr<<dr}function He(t){return!(!t||!t[Vn])}function Ze(t,e,r,n){var i=Object.create(Jn.prototype);return i.size=t?t.size:0,i._map=t,i._list=e,i.__ownerID=r,i.__hash=n,i}function $e(){return Nn||(Nn=Ze(re(),Je()))}function tr(t,e,r){var n=t._map,i=t._list,u=n.get(e),s=void 0!==u,o=r===mr;if(!s&&o||s&&r===i.get(u)[1])return t;s||(u=i.size);var a=o?n.remove(e):s?n:n.set(e,u),h=o?i.set(u,void 0):i.set(u,[e,r]);
<del>return t.__ownerID?(t.size=a.size,t._map=a,t._list=h,t.__hash=void 0,t):Ze(a,h)}function er(t){return!(!t||!t[Xn])}function rr(t,e,r,n){var i=Object.create(Fn);return i.size=t,i._head=e,i.__ownerID=r,i.__hash=n,i.__altered=!1,i}function nr(){return Gn||(Gn=rr(0))}function ir(t){return!(!t||!t[Zn])}function ur(t,e){return t.__ownerID?(t.size=e.size,t._map=e,t):e===t._map?t:0===e.size?t.__empty():t.__make(e)}function sr(t,e){var r=Object.create($n);return r.size=t?t.size:0,r._map=t,r.__ownerID=e,r}function or(){return ti||(ti=sr(re()))}function ar(t){return!(!t||!t[ri])}function hr(t,e){var r=Object.create(ni);return r.size=t?t.size:0,r._map=t,r.__ownerID=e,r}function cr(){return ii||(ii=hr($e()))}function fr(t,e,r){var n=Object.create(Object.getPrototypeOf(t));return n._map=e,n.__ownerID=r,n}function _r(t){return t._name||t.constructor.name}var lr=Object,vr={};vr.createClass=t,vr.superCall=e,vr.defaultSuperCall=r;var pr="delete",dr=5,yr=1<<dr,gr=yr-1,mr={},wr={value:!1},Sr={value:!1},zr=function(){try{return Object.defineProperty({},"x",{}),!0}catch(t){return!1}}(),Ir="function"==typeof WeakMap&&new WeakMap,br=2147483647,qr=0,xr="__immutablehash__";"function"==typeof Symbol&&(xr=Symbol(xr));var Mr=16,Er=255,kr=0,Or={},Dr=0,Ar=1,Cr=2,jr="@@iterator",Rr="function"==typeof Symbol&&Symbol.iterator,Ur=Rr||jr,Kr=function(t){this.next=t};vr.createClass(Kr,{toString:function(){return"[Iterator]"}},{}),Kr.KEYS=Dr,Kr.VALUES=Ar,Kr.ENTRIES=Cr;var Lr=Kr.prototype;Lr.inspect=Lr.toSource=function(){return""+this},Lr[Ur]=function(){return this};var Tr=function(t){return E(t)?t:Fr(t)},Wr=Tr;vr.createClass(Tr,{toArray:function(){h(this.size);var t=Array(this.size||0);return this.valueSeq().__iterate(function(e,r){t[r]=e}),t},toIndexedSeq:function(){return new Cn(this)},toJS:function(){return this.toSeq().map(function(t){return t&&"function"==typeof t.toJS?t.toJS():t}).__toJS()},toKeyedSeq:function(){return new An(this,!0)},toMap:function(){return h(this.size),yn(this.toKeyedSeq())},toObject:function(){h(this.size);var t={};return this.__iterate(function(e,r){t[r]=e
<del>}),t},toOrderedMap:function(){return h(this.size),Jn(this.toKeyedSeq())},toOrderedSet:function(){return h(this.size),ei(k(this)?this.valueSeq():this)},toSet:function(){return h(this.size),Hn(k(this)?this.valueSeq():this)},toSetSeq:function(){return new jn(this)},toSeq:function(){return O(this)?this.toIndexedSeq():k(this)?this.toKeyedSeq():this.toSetSeq()},toStack:function(){return h(this.size),Yn(k(this)?this.valueSeq():this)},toList:function(){return h(this.size),Un(k(this)?this.valueSeq():this)},toString:function(){return"[Iterable]"},__toString:function(t,e){return 0===this.size?t+e:t+" "+this.toSeq().map(this.__toStringMapper).join(", ")+" "+e},concat:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];return Ce(this,Me(this,t))},contains:function(t){return this.some(function(e){return n(e,t)})},entries:function(){return this.__iterator(Cr)},every:function(t,e){var r=!0;return this.__iterate(function(n,i,u){return t.call(e,n,i,u)?void 0:(r=!1,!1)}),r},filter:function(t,e){return Ce(this,we(this,t,e,!0))},find:function(t,e,r){var n=r;return this.__iterate(function(r,i,u){return t.call(e,r,i,u)?(n=r,!1):void 0}),n},forEach:function(t,e){return this.__iterate(e?t.bind(e):t)},join:function(t){t=void 0!==t?""+t:",";var e="",r=!0;return this.__iterate(function(n){r?r=!1:e+=t,e+=null!==n&&void 0!==n?n:""}),e},keys:function(){return this.__iterator(Dr)},map:function(t,e){return Ce(this,ge(this,t,e))},reduce:function(t,e,r){var n,i;return 2>arguments.length?i=!0:n=e,this.__iterate(function(e,u,s){i?(i=!1,n=e):n=t.call(r,n,e,u,s)}),n},reduceRight:function(){var t=this.toKeyedSeq().reverse();return t.reduce.apply(t,arguments)},reverse:function(){return Ce(this,me(this,!0))},slice:function(t,e){if(l(t,e,this.size))return this;var r=v(t,this.size),n=p(e,this.size);if(r!==r||n!==n)return this.toSeq().cacheResult().slice(t,e);var i=0===r?this:this.skip(r);return Ce(this,void 0===n||n===this.size?i:i.take(n-r))},some:function(t,e){return!this.every(j(t),e)},sort:function(t){return Ce(this,De(this,t||K))},values:function(){return this.__iterator(Ar)
<del>},butLast:function(){return this.slice(0,-1)},count:function(t,e){return c(t?this.toSeq().filter(t,e):this)},countBy:function(t,e){return Se(this,t,e)},equals:function(t){if(this===t)return!0;if(!t||"function"!=typeof t.equals)return!1;if(void 0!==this.size&&void 0!==t.size){if(this.size!==t.size)return!1;if(0===this.size&&0===t.size)return!0}return void 0!==this.__hash&&void 0!==t.__hash&&this.__hash!==t.__hash?!1:this.__deepEquals(t)},__deepEquals:function(t){var e=this.entries();return"function"==typeof t.every&&t.every(function(t,r){var i=e.next().value;return i&&n(i[0],r)&&n(i[1],t)})&&e.next().done},entrySeq:function(){var t=this;if(t._cache)return new un(t._cache);var e=t.toSeq().map(C).toIndexedSeq();return e.fromEntrySeq=function(){return t.toSeq()},e},filterNot:function(t,e){return this.filter(j(t),e)},findLast:function(t,e,r){return this.toKeyedSeq().reverse().find(t,e,r)},first:function(){return this.find(_)},flatMap:function(t,e){return Ce(this,ke(this,t,e))},flatten:function(t){return Ce(this,Ee(this,t,!0))},fromEntrySeq:function(){return new Rn(this)},get:function(t,e){return this.find(function(e,r){return n(r,t)},void 0,e)},getIn:function(t,e){var r=this;if(t)for(var n=0;t.length>n;n++)if(r=r&&r.get?r.get(t[n],mr):mr,r===mr)return e;return r},groupBy:function(t,e){return ze(this,t,e)},has:function(t){return this.get(t,mr)!==mr},isSubset:function(t){return t="function"==typeof t.contains?t:Wr(t),this.every(function(e){return t.contains(e)})},isSuperset:function(t){return t.isSubset(this)},keySeq:function(){return this.toSeq().map(A).toIndexedSeq()},last:function(){return this.toSeq().reverse().first()},max:function(t){return Ae(this,t||K)},maxBy:function(t,e){return Ae(this,e||K,t)},min:function(t){return Ae(this,R(t||K))},minBy:function(t,e){return Ae(this,R(e||K),t)},rest:function(){return this.slice(1)},skip:function(t){return Ce(this,qe(this,t,!0))},skipLast:function(t){return Ce(this,this.toSeq().reverse().skip(t).reverse())},skipWhile:function(t,e){return Ce(this,xe(this,t,e,!0))},skipUntil:function(t,e){return this.skipWhile(j(t),e)
<del>},sortBy:function(t,e){return Ce(this,De(this,e||K,t))},take:function(t){return Ce(this,Ie(this,t))},takeLast:function(t){return Ce(this,this.toSeq().reverse().take(t).reverse())},takeWhile:function(t,e){return Ce(this,be(this,t,e))},takeUntil:function(t,e){return this.takeWhile(j(t),e)},valueSeq:function(){return this.toIndexedSeq()},hashCode:function(){return this.__hash||(this.__hash=1/0===this.size?0:this.reduce(function(t,e,r){return t+(y(e)^(e===r?0:y(r)))&br},0))}},{});var Br="",Pr="",Jr="",Vr=Tr.prototype;Vr[Br]=!0,Vr[Ur]=Vr.values,Vr.toJSON=Vr.toJS,Vr.__toJS=Vr.toArray,Vr.__toStringMapper=U,Vr.inspect=Vr.toSource=function(){return""+this},Vr.chain=Vr.flatMap,function(){try{Object.defineProperty(Vr,"length",{get:function(){if(!Tr.noLengthWarning){var t;try{throw Error()}catch(e){t=e.stack}if(-1===t.indexOf("_wrapObject"))return console&&console.warn&&console.warn("iterable.length has been deprecated, use iterable.size or iterable.count(). This warning will become a silent error in a future version. "+t),this.size}}})}catch(t){}}();var Nr=function(t){return k(t)?t:Hr(t)};vr.createClass(Nr,{flip:function(){return Ce(this,ye(this))},findKey:function(t,e){var r;return this.__iterate(function(n,i,u){return t.call(e,n,i,u)?(r=i,!1):void 0}),r},findLastKey:function(t,e){return this.toSeq().reverse().findKey(t,e)},keyOf:function(t){return this.findKey(function(e){return n(e,t)})},lastKeyOf:function(t){return this.toSeq().reverse().keyOf(t)},mapEntries:function(t,e){var r=this,n=0;return Ce(this,this.toSeq().map(function(i,u){return t.call(e,[u,i],n++,r)}).fromEntrySeq())},mapKeys:function(t,e){var r=this;return Ce(this,this.toSeq().flip().map(function(n,i){return t.call(e,n,i,r)}).flip())}},{},Tr);var Yr=Nr.prototype;Yr[Pr]=!0,Yr[Ur]=Vr.entries,Yr.__toJS=Vr.toObject,Yr.__toStringMapper=function(t,e){return e+": "+U(t)};var Qr=function(t){return O(t)?t:$r(t)};vr.createClass(Qr,{toKeyedSeq:function(){return new An(this,!1)},filter:function(t,e){return Ce(this,we(this,t,e,!1))
<del>},findIndex:function(t,e){var r=this.toKeyedSeq().findKey(t,e);return void 0===r?-1:r},indexOf:function(t){var e=this.toKeyedSeq().keyOf(t);return void 0===e?-1:e},lastIndexOf:function(t){var e=this.toKeyedSeq().lastKeyOf(t);return void 0===e?-1:e},reverse:function(){return Ce(this,me(this,!1))},splice:function(t,e){var r=arguments.length;if(e=Math.max(0|e,0),0===r||2===r&&!e)return this;t=v(t,this.size);var n=this.slice(0,t);return Ce(this,1===r?n:n.concat(a(arguments,2),this.slice(t+e)))},findLastIndex:function(t,e){var r=this.toKeyedSeq().findLastKey(t,e);return void 0===r?-1:r},first:function(){return this.get(0)},flatten:function(t){return Ce(this,Ee(this,t,!1))},get:function(t,e){return t=f(this,t),0>t||1/0===this.size||void 0!==this.size&&t>this.size?e:this.find(function(e,r){return r===t},void 0,e)},has:function(t){return t=f(this,t),t>=0&&(void 0!==this.size?1/0===this.size||this.size>t:-1!==this.indexOf(t))},interpose:function(t){return Ce(this,Oe(this,t))},last:function(){return this.get(-1)},skip:function(t){var e=this,r=qe(e,t,!1);return T(e)&&r!==e&&(r.get=function(r,n){return r=f(this,r),r>=0?e.get(r+t,n):n}),Ce(this,r)},skipWhile:function(t,e){return Ce(this,xe(this,t,e,!1))},take:function(t){var e=this,r=Ie(e,t);return T(e)&&r!==e&&(r.get=function(r,n){return r=f(this,r),r>=0&&t>r?e.get(r,n):n}),Ce(this,r)}},{},Tr),Qr.prototype[Jr]=!0;var Xr=function(t){return E(t)&&!D(t)?t:en(t)};vr.createClass(Xr,{get:function(t,e){return this.has(t)?t:e},contains:function(t){return this.has(t)},keySeq:function(){return this.valueSeq()}},{},Tr),Xr.prototype.has=Vr.contains,Tr.isIterable=E,Tr.isKeyed=k,Tr.isIndexed=O,Tr.isAssociative=D,Tr.Keyed=Nr,Tr.Indexed=Qr,Tr.Set=Xr,Tr.Iterator=Kr;var Fr=function(t){return null===t||void 0===t?W():E(t)?t.toSeq():J(t)},Gr=Fr;vr.createClass(Fr,{toSeq:function(){return this},toString:function(){return this.__toString("Seq {","}")},cacheResult:function(){return!this._cache&&this.__iterateUncached&&(this._cache=this.entrySeq().toArray(),this.size=this._cache.length),this},__iterate:function(t,e){return Y(this,t,e,!0)
<del>},__iterator:function(t,e){return Q(this,t,e,!0)}},{of:function(){return Gr(arguments)}},Tr);var Hr=function(t){return null===t||void 0===t?W().toKeyedSeq():E(t)?k(t)?t.toSeq():t.fromEntrySeq():B(t)},Zr=Hr;vr.createClass(Hr,{toKeyedSeq:function(){return this},toSeq:function(){return this}},{of:function(){return Zr(arguments)}},Fr),L(Hr,Nr.prototype);var $r=function(t){return null===t||void 0===t?W():E(t)?k(t)?t.entrySeq():t.toIndexedSeq():P(t)},tn=$r;vr.createClass($r,{toIndexedSeq:function(){return this},toString:function(){return this.__toString("Seq [","]")},__iterate:function(t,e){return Y(this,t,e,!1)},__iterator:function(t,e){return Q(this,t,e,!1)}},{of:function(){return tn(arguments)}},Fr),L($r,Qr.prototype);var en=function(t){return(null===t||void 0===t?W():E(t)?k(t)?t.entrySeq():t:P(t)).toSetSeq()},rn=en;vr.createClass(en,{toSetSeq:function(){return this}},{of:function(){return rn(arguments)}},Fr),L(en,Xr.prototype),Fr.isSeq=T,Fr.Keyed=Hr,Fr.Set=en,Fr.Indexed=$r;var nn="";Fr.prototype[nn]=!0;var un=function(t){this._array=t,this.size=t.length};vr.createClass(un,{get:function(t,e){return this.has(t)?this._array[f(this,t)]:e},__iterate:function(t,e){for(var r=this._array,n=r.length-1,i=0;n>=i;i++)if(t(r[e?n-i:i],i,this)===!1)return i+1;return i},__iterator:function(t,e){var r=this._array,n=r.length-1,i=0;return new Kr(function(){return i>n?I():z(t,i,r[e?n-i++:i++])})}},{},$r);var sn=function(t){var e=Object.keys(t);this._object=t,this._keys=e,this.size=e.length};vr.createClass(sn,{get:function(t,e){return void 0===e||this.has(t)?this._object[t]:e},has:function(t){return this._object.hasOwnProperty(t)},__iterate:function(t,e){for(var r=this._object,n=this._keys,i=n.length-1,u=0;i>=u;u++){var s=n[e?i-u:u];if(t(r[s],s,this)===!1)return u+1}return u},__iterator:function(t,e){var r=this._object,n=this._keys,i=n.length-1,u=0;return new Kr(function(){var s=n[e?i-u:u];return u++>i?I():z(t,s,r[s])})}},{},Hr);var on=function(t){this._iterable=t,this.size=t.length||t.size};vr.createClass(on,{__iterateUncached:function(t,e){if(e)return this.cacheResult().__iterate(t,e);
<del>var r=this._iterable,n=x(r),i=0;if(q(n))for(var u;!(u=n.next()).done&&t(u.value,i++,this)!==!1;);return i},__iteratorUncached:function(t,e){if(e)return this.cacheResult().__iterator(t,e);var r=this._iterable,n=x(r);if(!q(n))return new Kr(I);var i=0;return new Kr(function(){var e=n.next();return e.done?e:z(t,i++,e.value)})}},{},$r);var an=function(t){this._iterator=t,this._iteratorCache=[]};vr.createClass(an,{__iterateUncached:function(t,e){if(e)return this.cacheResult().__iterate(t,e);for(var r=this._iterator,n=this._iteratorCache,i=0;n.length>i;)if(t(n[i],i++,this)===!1)return i;for(var u;!(u=r.next()).done;){var s=u.value;if(n[i]=s,t(s,i++,this)===!1)break}return i},__iteratorUncached:function(t,e){if(e)return this.cacheResult().__iterator(t,e);var r=this._iterator,n=this._iteratorCache,i=0;return new Kr(function(){if(i>=n.length){var e=r.next();if(e.done)return e;n[i]=e.value}return z(t,i,n[i++])})}},{},$r);var hn,cn=function(){throw TypeError("Abstract")};vr.createClass(cn,{},{},Tr);var fn=function(){vr.defaultSuperCall(this,_n.prototype,arguments)},_n=fn;vr.createClass(fn,{},{},cn),L(fn,Nr.prototype);var ln=function(){vr.defaultSuperCall(this,vn.prototype,arguments)},vn=ln;vr.createClass(ln,{},{},cn),L(ln,Qr.prototype);var pn=function(){vr.defaultSuperCall(this,dn.prototype,arguments)},dn=pn;vr.createClass(pn,{},{},cn),L(pn,Xr.prototype),cn.Keyed=fn,cn.Indexed=ln,cn.Set=pn;var yn=function(t){return null===t||void 0===t?re():Z(t)?t:re().merge(Nr(t))};vr.createClass(yn,{toString:function(){return this.__toString("Map {","}")},get:function(t,e){return this._root?this._root.get(0,y(t),t,e):e},set:function(t,e){return ne(this,t,e)},setIn:function(t,e){return i(t.length>0,"Requires non-empty key path."),this.updateIn(t,function(){return e})},remove:function(t){return ne(this,t,mr)},removeIn:function(t){return i(t.length>0,"Requires non-empty key path."),this.updateIn(t,function(){return mr})},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):_e(this,t,e,r,0)
<del>},clear:function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._root=null,this.__hash=void 0,this.__altered=!0,this):re()},merge:function(){return he(this,void 0,arguments)},mergeWith:function(t){for(var e=[],r=1;arguments.length>r;r++)e[r-1]=arguments[r];return he(this,t,e)},mergeDeep:function(){return he(this,ce(void 0),arguments)},mergeDeepWith:function(t){for(var e=[],r=1;arguments.length>r;r++)e[r-1]=arguments[r];return he(this,ce(t),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 o)},asImmutable:function(){return this.__ensureOwner()},wasAltered:function(){return this.__altered},__iterator:function(t,e){return new En(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?ee(this.size,this._root,t,this.__hash):(this.__ownerID=t,this.__altered=!1,this)}},{},fn),yn.isMap=Z;var gn="",mn=yn.prototype;mn[gn]=!0,mn[pr]=mn.remove;var wn=function(t,e,r){this.ownerID=t,this.bitmap=e,this.nodes=r},Sn=wn;vr.createClass(wn,{get:function(t,e,r,n){var i=1<<((0===t?e:e>>>t)&gr),u=this.bitmap;return 0===(u&i)?n:this.nodes[le(u&i-1)].get(t+dr,e,r,n)},update:function(t,e,r,n,i,u,s){var o=(0===e?r:r>>>e)&gr,a=1<<o,h=this.bitmap,c=0!==(h&a);if(!c&&i===mr)return this;var f=le(h&a-1),_=this.nodes,l=c?_[f]:void 0,v=ie(l,t,e+dr,r,n,i,u,s);if(v===l)return this;if(!c&&v&&_.length>=On)return ae(t,_,h,o,v);if(c&&!v&&2===_.length&&ue(_[1^f]))return _[1^f];if(c&&v&&1===_.length&&ue(v))return v;var p=t&&t===this.ownerID,d=c?v?h:h^a:h|a,y=c?v?ve(_,f,v,p):de(_,f,p):pe(_,f,v,p);return p?(this.bitmap=d,this.nodes=y,this):new Sn(t,d,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 zn=function(t,e,r){this.ownerID=t,this.count=e,this.nodes=r},In=zn;vr.createClass(zn,{get:function(t,e,r,n){var i=(0===t?e:e>>>t)&gr,u=this.nodes[i];
<del>return u?u.get(t+dr,e,r,n):n},update:function(t,e,r,n,i,u,s){var o=(0===e?r:r>>>e)&gr,a=i===mr,h=this.nodes,c=h[o];if(a&&!c)return this;var f=ie(c,t,e+dr,r,n,i,u,s);if(f===c)return this;var _=this.count;if(c){if(!f&&(_--,Dn>_))return oe(t,h,_,o)}else _++;var l=t&&t===this.ownerID,v=ve(h,o,f,l);return l?(this.count=_,this.nodes=v,this):new In(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 bn=function(t,e,r){this.ownerID=t,this.hash=e,this.entries=r},qn=bn;vr.createClass(bn,{get:function(t,e,r,i){for(var u=this.entries,s=0,o=u.length;o>s;s++)if(n(r,u[s][0]))return u[s][1];return i},update:function(t,e,r,i,u,o,h){var c=u===mr;if(r!==this.hash)return c?this:(s(h),s(o),se(this,t,e,r,[i,u]));for(var f=this.entries,_=0,l=f.length;l>_&&!n(i,f[_][0]);_++);var v=l>_;if(c&&!v)return this;if(s(h),(c||!v)&&s(o),c&&2===l)return new xn(t,this.hash,f[1^_]);var p=t&&t===this.ownerID,d=p?f:a(f);return v?c?_===l-1?d.pop():d[_]=d.pop():d[_]=[i,u]:d.push([i,u]),p?(this.entries=d,this):new qn(t,this.hash,d)},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 xn=function(t,e,r){this.ownerID=t,this.hash=e,this.entry=r},Mn=xn;vr.createClass(xn,{get:function(t,e,r,i){return n(r,this.entry[0])?this.entry[1]:i},update:function(t,e,r,i,u,o,a){var h=u===mr,c=n(i,this.entry[0]);return(c?u===this.entry[1]:h)?this:(s(a),h?void s(o):c?t&&t===this.ownerID?(this.entry[1]=u,this):new Mn(t,r,[i,u]):(s(o),se(this,t,e,r,[i,u])))},iterate:function(t){return t(this.entry)}},{});var En=function(t,e,r){this._type=e,this._reverse=r,this._stack=t._root&&te(t._root)};vr.createClass(En,{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 $(t,n.entry)}else if(n.entries){if(r=n.entries.length-1,r>=i)return $(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 $(t,u.entry);e=this._stack=te(u,e)
<del>}continue}e=this._stack=this._stack.__prev}return I()}},{},Kr);var kn,On=yr/2,Dn=yr/4,An=function(t,e){this._iter=t,this._useKeys=e,this.size=t.size};vr.createClass(An,{get:function(t,e){return this._iter.get(t,e)},has:function(t){return this._iter.has(t)},valueSeq:function(){return this._iter.valueSeq()},reverse:function(){var t=this,e=me(this,!0);return this._useKeys||(e.valueSeq=function(){return t._iter.toSeq().reverse()}),e},map:function(t,e){var r=this,n=ge(this,t,e);return this._useKeys||(n.valueSeq=function(){return r._iter.toSeq().map(t,e)}),n},__iterate:function(t,e){var r,n=this;return this._iter.__iterate(this._useKeys?function(e,r){return t(e,r,n)}:(r=e?Re(this):0,function(i){return t(i,e?--r:r++,n)}),e)},__iterator:function(t,e){if(this._useKeys)return this._iter.__iterator(t,e);var r=this._iter.__iterator(Ar,e),n=e?Re(this):0;return new Kr(function(){var i=r.next();return i.done?i:z(t,e?--n:n++,i.value,i)})}},{},Hr);var Cn=function(t){this._iter=t,this.size=t.size};vr.createClass(Cn,{contains:function(t){return this._iter.contains(t)},__iterate:function(t,e){var r=this,n=0;return this._iter.__iterate(function(e){return t(e,n++,r)},e)},__iterator:function(t,e){var r=this._iter.__iterator(Ar,e),n=0;return new Kr(function(){var e=r.next();return e.done?e:z(t,n++,e.value,e)})}},{},$r);var jn=function(t){this._iter=t,this.size=t.size};vr.createClass(jn,{has:function(t){return this._iter.contains(t)},__iterate:function(t,e){var r=this;return this._iter.__iterate(function(e){return t(e,e,r)},e)},__iterator:function(t,e){var r=this._iter.__iterator(Ar,e);return new Kr(function(){var e=r.next();return e.done?e:z(t,e.value,e.value,e)})}},{},en);var Rn=function(t){this._iter=t,this.size=t.size};vr.createClass(Rn,{entrySeq:function(){return this._iter.toSeq()},__iterate:function(t,e){var r=this;return this._iter.__iterate(function(e){return e?(je(e),t(e[1],e[0],r)):void 0},e)},__iterator:function(t,e){var r=this._iter.__iterator(Ar,e);return new Kr(function(){for(;;){var e=r.next();if(e.done)return e;var n=e.value;
<del>if(n)return je(n),t===Cr?e:z(t,n[0],n[1],e)}})}},{},Hr),Cn.prototype.cacheResult=An.prototype.cacheResult=jn.prototype.cacheResult=Rn.prototype.cacheResult=Le;var Un=function(t){var e=Je();if(null===t||void 0===t)return e;if(Te(t))return t;t=Qr(t);var r=t.size;return 0===r?e:r>0&&yr>r?Pe(0,r,dr,null,new Tn(t.toArray())):e.merge(t)};vr.createClass(Un,{toString:function(){return this.__toString("List [","]")},get:function(t,e){if(t=f(this,t),0>t||t>=this.size)return e;t+=this._origin;var r=Qe(this,t);return r&&r.array[t&gr]},set:function(t,e){return Ve(this,t,e)},remove:function(t){return this.has(t)?0===t?this.shift():t===this.size-1?this.pop():this.splice(t,1):this},clear:function(){return 0===this.size?this:this.__ownerID?(this.size=this._origin=this._capacity=0,this._level=dr,this._root=this._tail=null,this.__hash=void 0,this.__altered=!0,this):Je()},push:function(){var t=arguments,e=this.size;return this.withMutations(function(r){Xe(r,0,e+t.length);for(var n=0;t.length>n;n++)r.set(e+n,t[n])})},pop:function(){return Xe(this,0,-1)},unshift:function(){var t=arguments;return this.withMutations(function(e){Xe(e,-t.length);for(var r=0;t.length>r;r++)e.set(r,t[r])})},shift:function(){return Xe(this,1)},merge:function(){return Fe(this,void 0,arguments)},mergeWith:function(t){for(var e=[],r=1;arguments.length>r;r++)e[r-1]=arguments[r];return Fe(this,t,e)},mergeDeep:function(){return Fe(this,ce(void 0),arguments)},mergeDeepWith:function(t){for(var e=[],r=1;arguments.length>r;r++)e[r-1]=arguments[r];return Fe(this,ce(t),e)},setSize:function(t){return Xe(this,0,t)},slice:function(t,e){var r=this.size;return l(t,e,r)?this:Xe(this,v(t,r),p(e,r))},__iterator:function(t,e){return new Bn(this,t,e)},__iterate:function(t,e){var r=this,n=0,i=function(e){return t(e,n++,r)},u=Ge(this._capacity);return e?We(this._tail,0,u-this._origin,this._capacity-this._origin,i,e)&&We(this._root,this._level,-this._origin,u-this._origin,i,e):We(this._root,this._level,-this._origin,u-this._origin,i,e)&&We(this._tail,0,u-this._origin,this._capacity-this._origin,i,e),n
<del>},__ensureOwner:function(t){return t===this.__ownerID?this:t?Pe(this._origin,this._capacity,this._level,this._root,this._tail,t,this.__hash):(this.__ownerID=t,this)}},{of:function(){return this(arguments)}},ln),Un.isList=Te;var Kn="",Ln=Un.prototype;Ln[Kn]=!0,Ln[pr]=Ln.remove,Ln.setIn=mn.setIn,Ln.removeIn=mn.removeIn,Ln.update=mn.update,Ln.updateIn=mn.updateIn,Ln.withMutations=mn.withMutations,Ln.asMutable=mn.asMutable,Ln.asImmutable=mn.asImmutable,Ln.wasAltered=mn.wasAltered;var Tn=function(t,e){this.array=t,this.ownerID=e},Wn=Tn;vr.createClass(Tn,{removeBefore:function(t,e,r){if(r===e?1<<e:0||0===this.array.length)return this;var n=r>>>e&gr;if(n>=this.array.length)return new Wn([],t);var i,u=0===n;if(e>0){var s=this.array[n];if(i=s&&s.removeBefore(t,e-dr,r),i===s&&u)return this}if(u&&!i)return this;var o=Ye(this,t);if(!u)for(var a=0;n>a;a++)o.array[a]=void 0;return i&&(o.array[n]=i),o},removeAfter:function(t,e,r){if(r===e?1<<e:0||0===this.array.length)return this;var n=r-1>>>e&gr;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-dr,r),i===s&&u)return this}if(u&&!i)return this;var o=Ye(this,t);return u||o.array.pop(),i&&(o.array[n]=i),o}},{});var Bn=function(t,e,r){this._type=e,this._reverse=!!r,this._maxIndex=t.size-1;var n=Ge(t._capacity),i=Be(t._root&&t._root.array,t._level,-t._origin,n-t._origin-1),u=Be(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};vr.createClass(Bn,{next:function(){for(var t=this._stack;t;){var e=t.array,r=t.index++;if(this._reverse&&(r=gr-r,r>t.rawMax&&(r=t.rawMax,t.index=yr-r)),r>=0&&yr>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)),z(u,i,n)}this._stack=t=Be(n&&n.array,t.level-dr,t.offset+(r<<t.level),t.max,t)}else t=this._stack=this._stack.__prev}return I()}},{},Kr);var Pn,Jn=function(t){return null===t||void 0===t?$e():He(t)?t:$e().merge(Nr(t))
<del>};vr.createClass(Jn,{toString:function(){return this.__toString("OrderedMap {","}")},get:function(t,e){var r=this._map.get(t);return void 0!==r?this._list.get(r)[1]:e},clear:function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._map.clear(),this._list.clear(),this):$e()},set:function(t,e){return tr(this,t,e)},remove:function(t){return tr(this,t,mr)},wasAltered:function(){return this._map.wasAltered()||this._list.wasAltered()},__iterate:function(t,e){var r=this;return this._list.__iterate(function(e){return e&&t(e[1],e[0],r)},e)},__iterator:function(t,e){return this._list.fromEntrySeq().__iterator(t,e)},__ensureOwner:function(t){if(t===this.__ownerID)return this;var e=this._map.__ensureOwner(t),r=this._list.__ensureOwner(t);return t?Ze(e,r,t,this.__hash):(this.__ownerID=t,this._map=e,this._list=r,this)}},{of:function(){return this(arguments)}},yn),Jn.isOrderedMap=He;var Vn="";Jn.prototype[Vn]=!0,Jn.prototype[pr]=Jn.prototype.remove;var Nn,Yn=function(t){return null===t||void 0===t?nr():er(t)?t:nr().unshiftAll(t)},Qn=Yn;vr.createClass(Yn,{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):rr(t,e)},pushAll:function(t){if(t=Qr(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):rr(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):nr()
<del>},slice:function(t,e){if(l(t,e,this.size))return this;var r=v(t,this.size),n=p(e,this.size);if(n!==this.size)return vr.superCall(this,Qn.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):rr(i,u)},__ensureOwner:function(t){return t===this.__ownerID?this:t?rr(this.size,this._head,t,this.__hash):(this.__ownerID=t,this.__altered=!1,this)},__iterate:function(t,e){if(e)return this.toSeq().cacheResult.__iterate(t,e);for(var r=0,n=this._head;n&&t(n.value,r++,this)!==!1;)n=n.next;return r},__iterator:function(t,e){if(e)return this.toSeq().cacheResult().__iterator(t,e);var r=0,n=this._head;return new Kr(function(){if(n){var e=n.value;return n=n.next,z(t,r++,e)}return I()})}},{of:function(){return this(arguments)}},ln),Yn.isStack=er;var Xn="",Fn=Yn.prototype;Fn[Xn]=!0,Fn.withMutations=mn.withMutations,Fn.asMutable=mn.asMutable,Fn.asImmutable=mn.asImmutable,Fn.wasAltered=mn.wasAltered;var Gn,Hn=function(t){return null===t||void 0===t?or():ir(t)?t:or().union(Xr(t))};vr.createClass(Hn,{toString:function(){return this.__toString("Set {","}")},has:function(t){return this._map.has(t)},add:function(t){return ur(this,this._map.set(t,!0))},remove:function(t){return ur(this,this._map.remove(t))},clear:function(){return ur(this,this._map.clear())},union:function(){var t=arguments;return 0===t.length?this:this.withMutations(function(e){for(var r=0;t.length>r;r++)Xr(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 Xr(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 Xr(t)});var r=this;return this.withMutations(function(e){r.forEach(function(r){t.some(function(t){return t.contains(r)
<del>})&&e.remove(r)})})},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?this.__make(e,t):(this.__ownerID=t,this._map=e,this)}},{of:function(){return this(arguments)},fromKeys:function(t){return this(Nr(t).keySeq())}},pn),Hn.isSet=ir;var Zn="",$n=Hn.prototype;$n[Zn]=!0,$n[pr]=$n.remove,$n.mergeDeep=$n.merge,$n.mergeDeepWith=$n.mergeWith,$n.withMutations=mn.withMutations,$n.asMutable=mn.asMutable,$n.asImmutable=mn.asImmutable,$n.__empty=or,$n.__make=sr;var ti,ei=function(t){return null===t||void 0===t?cr():ar(t)?t:cr().union(Xr(t))};vr.createClass(ei,{toString:function(){return this.__toString("OrderedSet {","}")}},{of:function(){return this(arguments)},fromKeys:function(t){return this(Nr(t).keySeq())}},Hn),ei.isOrderedSet=ar;var ri="",ni=ei.prototype;ni[ri]=!0,ni.__empty=cr,ni.__make=hr;var ii,ui=function(t,e){var r=function(t){return this instanceof r?void(this._map=yn(t)):new r(t)},n=Object.keys(t),u=r.prototype=Object.create(si);u.constructor=r,e&&(u._name=e),u._defaultValues=t,u._keys=n,u.size=n.length;try{n.forEach(function(t){Object.defineProperty(r.prototype,t,{get:function(){return this.get(t)},set:function(e){i(this.__ownerID,"Cannot set on an immutable record."),this.set(t,e)}})})}catch(s){}return r};vr.createClass(ui,{toString:function(){return this.__toString(_r(this)+" {","}")},has:function(t){return this._defaultValues.hasOwnProperty(t)},get:function(t,e){if(!this.has(t))return e;var r=this._defaultValues[t];return this._map?this._map.get(t,r):r},clear:function(){if(this.__ownerID)return this._map&&this._map.clear(),this;
<del>var t=Object.getPrototypeOf(this).constructor;return t._empty||(t._empty=fr(this,re()))},set:function(t,e){if(!this.has(t))throw Error('Cannot set unknown key "'+t+'" on '+_r(this));var r=this._map&&this._map.set(t,e);return this.__ownerID||r===this._map?this:fr(this,r)},remove:function(t){if(!this.has(t))return this;var e=this._map&&this._map.remove(t);return this.__ownerID||e===this._map?this:fr(this,e)},wasAltered:function(){return this._map.wasAltered()},__iterator:function(t,e){var r=this;return Nr(this._defaultValues).map(function(t,e){return r.get(e)}).__iterator(t,e)},__iterate:function(t,e){var r=this;return Nr(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?fr(this,e,t):(this.__ownerID=t,this._map=e,this)}},{},fn);var si=ui.prototype;si[pr]=si.remove,si.merge=mn.merge,si.mergeWith=mn.mergeWith,si.mergeDeep=mn.mergeDeep,si.mergeDeepWith=mn.mergeDeepWith,si.update=mn.update,si.updateIn=mn.updateIn,si.withMutations=mn.withMutations,si.asMutable=mn.asMutable,si.asImmutable=mn.asImmutable;var oi=function(t,e,r){return this instanceof ai?(i(0!==r,"Cannot step a Range by 0"),t=t||0,void 0===e&&(e=1/0),t===e&&ci?ci:(r=void 0===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 ai(t,e,r)},ai=oi;vr.createClass(oi,{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+f(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 l(t,e,this.size)?this:(t=v(t,this.size),e=p(e,this.size),t>=e?ci:new ai(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)
<del>},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 Kr(function(){var s=i;return i+=e?-n:n,u>r?I():z(t,u++,s)})},__deepEquals:function(t){return t instanceof ai?this._start===t._start&&this._end===t._end&&this._step===t._step:vr.superCall(this,ai.prototype,"__deepEquals",[t])}},{},$r);var hi=oi.prototype;hi.__toJS=hi.toArray,hi.first=Ln.first,hi.last=Ln.last;var ci=oi(0,0),fi=function(t,e){return 0>=e&&vi?vi:this instanceof _i?(this._value=t,this.size=void 0===e?1/0:Math.max(0,e),void(0===this.size&&(vi=this))):new _i(t,e)},_i=fi;vr.createClass(fi,{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 l(t,e,r)?this:new _i(this._value,p(e,r)-v(t,r))},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 Kr(function(){return e.size>r?z(t,r++,e._value):I()})},__deepEquals:function(t){return t instanceof _i?n(this._value,t._value):vr.superCall(this,_i.prototype,"__deepEquals",[t])}},{},$r);var li=fi.prototype;li.last=li.first,li.has=hi.has,li.take=hi.take,li.skip=hi.skip,li.__toJS=hi.__toJS;var vi,pi={Iterable:Tr,Seq:Fr,Collection:cn,Map:yn,OrderedMap:Jn,List:Un,Stack:Yn,Set:Hn,OrderedSet:ei,Record:ui,Range:oi,Repeat:fi,is:n,fromJS:X};return pi}"object"==typeof exports?module.exports=t():"function"==typeof define&&define.amd?define(t):Immutable=t();
<ide>\ No newline at end of file
<add>return r.size=t.size&&2*t.size-1,r.__iterateUncached=function(r,n){var i=this,u=0;return t.__iterate(function(t){return(!u||r(e,u++,i)!==!1)&&r(t,u++,i)!==!1},n),u},r.__iteratorUncached=function(r,n){var i,u=t.__iterator(Ar,n),s=0;return new Kr(function(){return(!i||s%2)&&(i=u.next(),i.done)?i:s%2?z(r,s++,e):z(r,s++,i.value,i)})},r}function De(t,e,r){var n=r?function(n,i){return e(r(n[1][1],n[1][0],t),r(i[1][1],i[1][0],t))||n[0]-i[0]}:function(t,r){return e(t[1][1],r[1][1])||t[0]-r[0]},i=[];t.forEach(function(t,e){i.push([i.length,[e,t]])}),i.sort(n);var u=k(t);return i.forEach(u?function(t,e){i[e]=t[1]}:function(t,e){i[e]=t[1][1]}),u?Hr(i):O(t)?$r(i):en(i)}function Ae(t,e,r){if(r){var n=t.toSeq().map(function(e,n){return[e,r(e,n,t)]}).reduce(function(t,r){return e(r[1],t[1])>0?r:t});return n&&n[0]}return t.reduce(function(t,r){return e(r,t)>0?r:t})}function Ce(t,e){return T(t)?e:t.constructor(e)}function je(t){if(t!==Object(t))throw new TypeError("Expected [K, V] tuple: "+t)}function Re(t){return h(t.size),c(t)}function Ue(t){return k(t)?Nr:O(t)?Qr:Xr}function Ke(t){return Object.create((k(t)?Hr:O(t)?$r:en).prototype)}function Le(){return this._iter.cacheResult?(this._iter.cacheResult(),this.size=this._iter.size,this):Fr.prototype.cacheResult.call(this)}function Te(t){return!(!t||!t[Kn])}function We(t,e,r,n,i,u){var s,o=t&&t.array;if(0===e){var a=0>r?-r:0,h=n-r;for(h>yr&&(h=yr),s=a;h>s;s++)if(i(o&&o[u?a+h-1-s:s])===!1)return!1}else{var c=1<<e,f=e-dr;for(s=0;mr>=s;s++){var _=u?mr-s:s,l=r+(_<<e);if(n>l&&l+c>0){var v=o&&o[_];if(!We(v,f,l,n,i,u))return!1}}}return!0}function Be(t,e,r,n,i){return{array:t,level:e,offset:r,max:n,rawMax:n-r>>e,index:0,__prev:i}}function Pe(t,e,r,n,i,u,s){var o=Object.create(Ln);return o.size=e-t,o._origin=t,o._capacity=e,o._level=r,o._root=n,o._tail=i,o.__ownerID=u,o.__hash=s,o.__altered=!1,o}function Je(){return Pn||(Pn=Pe(0,0,dr))}function Ve(t,e,r){if(e=f(t,e),e>=t.size||0>e)return t.withMutations(function(t){0>e?Xe(t,e).set(0,r):Xe(t,0,e+1).set(e,r)});e+=t._origin;var n=t._tail,i=t._root,s=u(Sr);
<add>return e>=Ge(t._capacity)?n=Ne(n,t.__ownerID,0,e,r,s):i=Ne(i,t.__ownerID,t._level,e,r,s),s.value?t.__ownerID?(t._root=i,t._tail=n,t.__hash=void 0,t.__altered=!0,t):Pe(t._origin,t._capacity,t._level,i,n):t}function Ne(t,e,r,n,i,u){var o=n>>>r&mr,a=t&&t.array.length>o;if(!a&&void 0===i)return t;var h;if(r>0){var c=t&&t.array[o],f=Ne(c,e,r-dr,n,i,u);return f===c?t:(h=Ye(t,e),h.array[o]=f,h)}return a&&t.array[o]===i?t:(s(u),h=Ye(t,e),void 0===i&&o===h.array.length-1?h.array.pop():h.array[o]=i,h)}function Ye(t,e){return e&&t&&e===t.ownerID?t:new Tn(t?t.array.slice():[],e)}function Qe(t,e){if(e>=Ge(t._capacity))return t._tail;if(1<<t._level+dr>e){for(var r=t._root,n=t._level;r&&n>0;)r=r.array[e>>>n&mr],n-=dr;return r}}function Xe(t,e,r){var n=t.__ownerID||new o,i=t._origin,u=t._capacity,s=i+e,a=void 0===r?u:0>r?u+r:i+r;if(s===i&&a===u)return t;if(s>=a)return t.clear();for(var h=t._level,c=t._root,f=0;0>s+f;)c=new Tn(c&&c.array.length?[void 0,c]:[],n),h+=dr,f+=1<<h;f&&(s+=f,i+=f,a+=f,u+=f);for(var _=Ge(u),l=Ge(a);l>=1<<h+dr;)c=new Tn(c&&c.array.length?[c]:[],n),h+=dr;var v=t._tail,p=_>l?Qe(t,a-1):l>_?new Tn([],n):v;if(v&&l>_&&u>s&&v.array.length){c=Ye(c,n);for(var d=c,y=h;y>dr;y-=dr){var m=_>>>y&mr;d=d.array[m]=Ye(d.array[m],n)}d.array[_>>>dr&mr]=v}if(u>a&&(p=p&&p.removeAfter(n,0,a)),s>=l)s-=l,a-=l,h=dr,c=null,p=p&&p.removeBefore(n,0,s);else if(s>i||_>l){for(f=0;c;){var g=s>>>h&mr;if(g!==l>>>h&mr)break;g&&(f+=(1<<h)*g),h-=dr,c=c.array[g]}c&&s>i&&(c=c.removeBefore(n,h,s-f)),c&&_>l&&(c=c.removeAfter(n,h,l-f)),f&&(s-=f,a-=f)}return t.__ownerID?(t.size=a-s,t._origin=s,t._capacity=a,t._level=h,t._root=c,t._tail=p,t.__hash=void 0,t.__altered=!0,t):Pe(s,a,h,c,p)}function Fe(t,e,r){for(var n=[],i=0,u=0;r.length>u;u++){var s=r[u],o=Qr(s);o.size>i&&(i=o.size),E(s)||(o=o.map(function(t){return X(t)})),n.push(o)}return i>t.size&&(t=t.setSize(i)),fe(t,e,n)}function Ge(t){return yr>t?0:t-1>>>dr<<dr}function He(t){return!(!t||!t[Vn])}function Ze(t,e,r,n){var i=Object.create(Jn.prototype);return i.size=t?t.size:0,i._map=t,i._list=e,i.__ownerID=r,i.__hash=n,i
<add>}function $e(){return Nn||(Nn=Ze(re(),Je()))}function tr(t,e,r){var n=t._map,i=t._list,u=n.get(e),s=void 0!==u,o=r===gr;if(!s&&o||s&&r===i.get(u)[1])return t;s||(u=i.size);var a=o?n.remove(e):s?n:n.set(e,u),h=o?i.set(u,void 0):i.set(u,[e,r]);return t.__ownerID?(t.size=a.size,t._map=a,t._list=h,t.__hash=void 0,t):Ze(a,h)}function er(t){return!(!t||!t[Xn])}function rr(t,e,r,n){var i=Object.create(Fn);return i.size=t,i._head=e,i.__ownerID=r,i.__hash=n,i.__altered=!1,i}function nr(){return Gn||(Gn=rr(0))}function ir(t){return!(!t||!t[Zn])}function ur(t,e){return t.__ownerID?(t.size=e.size,t._map=e,t):e===t._map?t:0===e.size?t.__empty():t.__make(e)}function sr(t,e){var r=Object.create($n);return r.size=t?t.size:0,r._map=t,r.__ownerID=e,r}function or(){return ti||(ti=sr(re()))}function ar(t){return!(!t||!t[ri])}function hr(t,e){var r=Object.create(ni);return r.size=t?t.size:0,r._map=t,r.__ownerID=e,r}function cr(){return ii||(ii=hr($e()))}function fr(t,e,r){var n=Object.create(Object.getPrototypeOf(t));return n._map=e,n.__ownerID=r,n}function _r(t){return t._name||t.constructor.name}var lr=Object,vr={};vr.createClass=t,vr.superCall=e,vr.defaultSuperCall=r;var pr="delete",dr=5,yr=1<<dr,mr=yr-1,gr={},wr={value:!1},Sr={value:!1},zr=function(){try{return Object.defineProperty({},"x",{}),!0}catch(t){return!1}}(),Ir="function"==typeof WeakMap&&new WeakMap,br=2147483647,qr=0,xr="__immutablehash__";"function"==typeof Symbol&&(xr=Symbol(xr));var Mr=16,Er=255,kr=0,Or={},Dr=0,Ar=1,Cr=2,jr="@@iterator",Rr="function"==typeof Symbol&&Symbol.iterator,Ur=Rr||jr,Kr=function(t){this.next=t};vr.createClass(Kr,{toString:function(){return"[Iterator]"}},{}),Kr.KEYS=Dr,Kr.VALUES=Ar,Kr.ENTRIES=Cr;var Lr=Kr.prototype;Lr.inspect=Lr.toSource=function(){return""+this},Lr[Ur]=function(){return this};var Tr=function(t){return E(t)?t:Fr(t)},Wr=Tr;vr.createClass(Tr,{toArray:function(){h(this.size);var t=Array(this.size||0);return this.valueSeq().__iterate(function(e,r){t[r]=e}),t},toIndexedSeq:function(){return new Cn(this)},toJS:function(){return this.toSeq().map(function(t){return t&&"function"==typeof t.toJS?t.toJS():t
<add>}).__toJS()},toKeyedSeq:function(){return new An(this,!0)},toMap:function(){return h(this.size),yn(this.toKeyedSeq())},toObject:function(){h(this.size);var t={};return this.__iterate(function(e,r){t[r]=e}),t},toOrderedMap:function(){return h(this.size),Jn(this.toKeyedSeq())},toOrderedSet:function(){return h(this.size),ei(k(this)?this.valueSeq():this)},toSet:function(){return h(this.size),Hn(k(this)?this.valueSeq():this)},toSetSeq:function(){return new jn(this)},toSeq:function(){return O(this)?this.toIndexedSeq():k(this)?this.toKeyedSeq():this.toSetSeq()},toStack:function(){return h(this.size),Yn(k(this)?this.valueSeq():this)},toList:function(){return h(this.size),Un(k(this)?this.valueSeq():this)},toString:function(){return"[Iterable]"},__toString:function(t,e){return 0===this.size?t+e:t+" "+this.toSeq().map(this.__toStringMapper).join(", ")+" "+e},concat:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];return Ce(this,Me(this,t))},contains:function(t){return this.some(function(e){return n(e,t)})},entries:function(){return this.__iterator(Cr)},every:function(t,e){var r=!0;return this.__iterate(function(n,i,u){return t.call(e,n,i,u)?void 0:(r=!1,!1)}),r},filter:function(t,e){return Ce(this,we(this,t,e,!0))},find:function(t,e,r){var n=r;return this.__iterate(function(r,i,u){return t.call(e,r,i,u)?(n=r,!1):void 0}),n},forEach:function(t,e){return this.__iterate(e?t.bind(e):t)},join:function(t){t=void 0!==t?""+t:",";var e="",r=!0;return this.__iterate(function(n){r?r=!1:e+=t,e+=null!==n&&void 0!==n?n:""}),e},keys:function(){return this.__iterator(Dr)},map:function(t,e){return Ce(this,me(this,t,e))},reduce:function(t,e,r){var n,i;return 2>arguments.length?i=!0:n=e,this.__iterate(function(e,u,s){i?(i=!1,n=e):n=t.call(r,n,e,u,s)}),n},reduceRight:function(){var t=this.toKeyedSeq().reverse();return t.reduce.apply(t,arguments)},reverse:function(){return Ce(this,ge(this,!0))},slice:function(t,e){if(l(t,e,this.size))return this;var r=v(t,this.size),n=p(e,this.size);if(r!==r||n!==n)return this.toSeq().cacheResult().slice(t,e);
<add>var i=0===r?this:this.skip(r);return Ce(this,void 0===n||n===this.size?i:i.take(n-r))},some:function(t,e){return!this.every(j(t),e)},sort:function(t){return Ce(this,De(this,t||K))},values:function(){return this.__iterator(Ar)},butLast:function(){return this.slice(0,-1)},count:function(t,e){return c(t?this.toSeq().filter(t,e):this)},countBy:function(t,e){return Se(this,t,e)},equals:function(t){if(this===t)return!0;if(!t||"function"!=typeof t.equals)return!1;if(void 0!==this.size&&void 0!==t.size){if(this.size!==t.size)return!1;if(0===this.size&&0===t.size)return!0}return void 0!==this.__hash&&void 0!==t.__hash&&this.__hash!==t.__hash?!1:this.__deepEquals(t)},__deepEquals:function(t){var e=this.entries();return"function"==typeof t.every&&t.every(function(t,r){var i=e.next().value;return i&&n(i[0],r)&&n(i[1],t)})&&e.next().done},entrySeq:function(){var t=this;if(t._cache)return new un(t._cache);var e=t.toSeq().map(C).toIndexedSeq();return e.fromEntrySeq=function(){return t.toSeq()},e},filterNot:function(t,e){return this.filter(j(t),e)},findLast:function(t,e,r){return this.toKeyedSeq().reverse().find(t,e,r)},first:function(){return this.find(_)},flatMap:function(t,e){return Ce(this,ke(this,t,e))},flatten:function(t){return Ce(this,Ee(this,t,!0))},fromEntrySeq:function(){return new Rn(this)},get:function(t,e){return this.find(function(e,r){return n(r,t)},void 0,e)},getIn:function(t,e){var r=this;if(t)for(var n=0;t.length>n;n++)if(r=r&&r.get?r.get(t[n],gr):gr,r===gr)return e;return r},groupBy:function(t,e){return ze(this,t,e)},has:function(t){return this.get(t,gr)!==gr},isSubset:function(t){return t="function"==typeof t.contains?t:Wr(t),this.every(function(e){return t.contains(e)})},isSuperset:function(t){return t.isSubset(this)},keySeq:function(){return this.toSeq().map(A).toIndexedSeq()},last:function(){return this.toSeq().reverse().first()},max:function(t){return Ae(this,t||K)},maxBy:function(t,e){return Ae(this,e||K,t)},min:function(t){return Ae(this,R(t||K))},minBy:function(t,e){return Ae(this,R(e||K),t)},rest:function(){return this.slice(1)
<add>},skip:function(t){return Ce(this,qe(this,t,!0))},skipLast:function(t){return Ce(this,this.toSeq().reverse().skip(t).reverse())},skipWhile:function(t,e){return Ce(this,xe(this,t,e,!0))},skipUntil:function(t,e){return this.skipWhile(j(t),e)},sortBy:function(t,e){return Ce(this,De(this,e||K,t))},take:function(t){return Ce(this,Ie(this,t))},takeLast:function(t){return Ce(this,this.toSeq().reverse().take(t).reverse())},takeWhile:function(t,e){return Ce(this,be(this,t,e))},takeUntil:function(t,e){return this.takeWhile(j(t),e)},valueSeq:function(){return this.toIndexedSeq()},hashCode:function(){return this.__hash||(this.__hash=1/0===this.size?0:this.reduce(function(t,e,r){return t+(y(e)^(e===r?0:y(r)))&br},0))}},{});var Br="",Pr="",Jr="",Vr=Tr.prototype;Vr[Br]=!0,Vr[Ur]=Vr.values,Vr.toJSON=Vr.toJS,Vr.__toJS=Vr.toArray,Vr.__toStringMapper=U,Vr.inspect=Vr.toSource=function(){return""+this},Vr.chain=Vr.flatMap,function(){try{Object.defineProperty(Vr,"length",{get:function(){if(!Tr.noLengthWarning){var t;try{throw Error()}catch(e){t=e.stack}if(-1===t.indexOf("_wrapObject"))return console&&console.warn&&console.warn("iterable.length has been deprecated, use iterable.size or iterable.count(). This warning will become a silent error in a future version. "+t),this.size}}})}catch(t){}}();var Nr=function(t){return k(t)?t:Hr(t)};vr.createClass(Nr,{flip:function(){return Ce(this,ye(this))},findKey:function(t,e){var r;return this.__iterate(function(n,i,u){return t.call(e,n,i,u)?(r=i,!1):void 0}),r},findLastKey:function(t,e){return this.toSeq().reverse().findKey(t,e)},keyOf:function(t){return this.findKey(function(e){return n(e,t)})},lastKeyOf:function(t){return this.toSeq().reverse().keyOf(t)},mapEntries:function(t,e){var r=this,n=0;return Ce(this,this.toSeq().map(function(i,u){return t.call(e,[u,i],n++,r)}).fromEntrySeq())},mapKeys:function(t,e){var r=this;return Ce(this,this.toSeq().flip().map(function(n,i){return t.call(e,n,i,r)}).flip())}},{},Tr);var Yr=Nr.prototype;
<add>Yr[Pr]=!0,Yr[Ur]=Vr.entries,Yr.__toJS=Vr.toObject,Yr.__toStringMapper=function(t,e){return e+": "+U(t)};var Qr=function(t){return O(t)?t:$r(t)};vr.createClass(Qr,{toKeyedSeq:function(){return new An(this,!1)},filter:function(t,e){return Ce(this,we(this,t,e,!1))},findIndex:function(t,e){var r=this.toKeyedSeq().findKey(t,e);return void 0===r?-1:r},indexOf:function(t){var e=this.toKeyedSeq().keyOf(t);return void 0===e?-1:e},lastIndexOf:function(t){var e=this.toKeyedSeq().lastKeyOf(t);return void 0===e?-1:e},reverse:function(){return Ce(this,ge(this,!1))},splice:function(t,e){var r=arguments.length;if(e=Math.max(0|e,0),0===r||2===r&&!e)return this;t=v(t,this.size);var n=this.slice(0,t);return Ce(this,1===r?n:n.concat(a(arguments,2),this.slice(t+e)))},findLastIndex:function(t,e){var r=this.toKeyedSeq().findLastKey(t,e);return void 0===r?-1:r},first:function(){return this.get(0)},flatten:function(t){return Ce(this,Ee(this,t,!1))},get:function(t,e){return t=f(this,t),0>t||1/0===this.size||void 0!==this.size&&t>this.size?e:this.find(function(e,r){return r===t},void 0,e)},has:function(t){return t=f(this,t),t>=0&&(void 0!==this.size?1/0===this.size||this.size>t:-1!==this.indexOf(t))},interpose:function(t){return Ce(this,Oe(this,t))},last:function(){return this.get(-1)},skip:function(t){var e=this,r=qe(e,t,!1);return T(e)&&r!==e&&(r.get=function(r,n){return r=f(this,r),r>=0?e.get(r+t,n):n}),Ce(this,r)},skipWhile:function(t,e){return Ce(this,xe(this,t,e,!1))},take:function(t){var e=this,r=Ie(e,t);return T(e)&&r!==e&&(r.get=function(r,n){return r=f(this,r),r>=0&&t>r?e.get(r,n):n}),Ce(this,r)}},{},Tr),Qr.prototype[Jr]=!0;var Xr=function(t){return E(t)&&!D(t)?t:en(t)};vr.createClass(Xr,{get:function(t,e){return this.has(t)?t:e},contains:function(t){return this.has(t)},keySeq:function(){return this.valueSeq()}},{},Tr),Xr.prototype.has=Vr.contains,Tr.isIterable=E,Tr.isKeyed=k,Tr.isIndexed=O,Tr.isAssociative=D,Tr.Keyed=Nr,Tr.Indexed=Qr,Tr.Set=Xr,Tr.Iterator=Kr;var Fr=function(t){return null===t||void 0===t?W():E(t)?t.toSeq():J(t)},Gr=Fr;
<add>vr.createClass(Fr,{toSeq:function(){return this},toString:function(){return this.__toString("Seq {","}")},cacheResult:function(){return!this._cache&&this.__iterateUncached&&(this._cache=this.entrySeq().toArray(),this.size=this._cache.length),this},__iterate:function(t,e){return Y(this,t,e,!0)},__iterator:function(t,e){return Q(this,t,e,!0)}},{of:function(){return Gr(arguments)}},Tr);var Hr=function(t){return null===t||void 0===t?W().toKeyedSeq():E(t)?k(t)?t.toSeq():t.fromEntrySeq():B(t)},Zr=Hr;vr.createClass(Hr,{toKeyedSeq:function(){return this},toSeq:function(){return this}},{of:function(){return Zr(arguments)}},Fr),L(Hr,Nr.prototype);var $r=function(t){return null===t||void 0===t?W():E(t)?k(t)?t.entrySeq():t.toIndexedSeq():P(t)},tn=$r;vr.createClass($r,{toIndexedSeq:function(){return this},toString:function(){return this.__toString("Seq [","]")},__iterate:function(t,e){return Y(this,t,e,!1)},__iterator:function(t,e){return Q(this,t,e,!1)}},{of:function(){return tn(arguments)}},Fr),L($r,Qr.prototype);var en=function(t){return(null===t||void 0===t?W():E(t)?k(t)?t.entrySeq():t:P(t)).toSetSeq()},rn=en;vr.createClass(en,{toSetSeq:function(){return this}},{of:function(){return rn(arguments)}},Fr),L(en,Xr.prototype),Fr.isSeq=T,Fr.Keyed=Hr,Fr.Set=en,Fr.Indexed=$r;var nn="";Fr.prototype[nn]=!0;var un=function(t){this._array=t,this.size=t.length};vr.createClass(un,{get:function(t,e){return this.has(t)?this._array[f(this,t)]:e},__iterate:function(t,e){for(var r=this._array,n=r.length-1,i=0;n>=i;i++)if(t(r[e?n-i:i],i,this)===!1)return i+1;return i},__iterator:function(t,e){var r=this._array,n=r.length-1,i=0;return new Kr(function(){return i>n?I():z(t,i,r[e?n-i++:i++])})}},{},$r);var sn=function(t){var e=Object.keys(t);this._object=t,this._keys=e,this.size=e.length};vr.createClass(sn,{get:function(t,e){return void 0===e||this.has(t)?this._object[t]:e},has:function(t){return this._object.hasOwnProperty(t)},__iterate:function(t,e){for(var r=this._object,n=this._keys,i=n.length-1,u=0;i>=u;u++){var s=n[e?i-u:u];
<add>if(t(r[s],s,this)===!1)return u+1}return u},__iterator:function(t,e){var r=this._object,n=this._keys,i=n.length-1,u=0;return new Kr(function(){var s=n[e?i-u:u];return u++>i?I():z(t,s,r[s])})}},{},Hr);var on=function(t){this._iterable=t,this.size=t.length||t.size};vr.createClass(on,{__iterateUncached:function(t,e){if(e)return this.cacheResult().__iterate(t,e);var r=this._iterable,n=x(r),i=0;if(q(n))for(var u;!(u=n.next()).done&&t(u.value,i++,this)!==!1;);return i},__iteratorUncached:function(t,e){if(e)return this.cacheResult().__iterator(t,e);var r=this._iterable,n=x(r);if(!q(n))return new Kr(I);var i=0;return new Kr(function(){var e=n.next();return e.done?e:z(t,i++,e.value)})}},{},$r);var an=function(t){this._iterator=t,this._iteratorCache=[]};vr.createClass(an,{__iterateUncached:function(t,e){if(e)return this.cacheResult().__iterate(t,e);for(var r=this._iterator,n=this._iteratorCache,i=0;n.length>i;)if(t(n[i],i++,this)===!1)return i;for(var u;!(u=r.next()).done;){var s=u.value;if(n[i]=s,t(s,i++,this)===!1)break}return i},__iteratorUncached:function(t,e){if(e)return this.cacheResult().__iterator(t,e);var r=this._iterator,n=this._iteratorCache,i=0;return new Kr(function(){if(i>=n.length){var e=r.next();if(e.done)return e;n[i]=e.value}return z(t,i,n[i++])})}},{},$r);var hn,cn=function(){throw TypeError("Abstract")};vr.createClass(cn,{},{},Tr);var fn=function(){vr.defaultSuperCall(this,_n.prototype,arguments)},_n=fn;vr.createClass(fn,{},{},cn),L(fn,Nr.prototype);var ln=function(){vr.defaultSuperCall(this,vn.prototype,arguments)},vn=ln;vr.createClass(ln,{},{},cn),L(ln,Qr.prototype);var pn=function(){vr.defaultSuperCall(this,dn.prototype,arguments)},dn=pn;vr.createClass(pn,{},{},cn),L(pn,Xr.prototype),cn.Keyed=fn,cn.Indexed=ln,cn.Set=pn;var yn=function(t){return null===t||void 0===t?re():Z(t)?t:re().merge(Nr(t))};vr.createClass(yn,{toString:function(){return this.__toString("Map {","}")},get:function(t,e){return this._root?this._root.get(0,y(t),t,e):e},set:function(t,e){return ne(this,t,e)},setIn:function(t,e){return i(t.length>0,"Requires non-empty key path."),this.updateIn(t,function(){return e
<add>})},remove:function(t){return ne(this,t,gr)},removeIn:function(t){return i(t.length>0,"Requires non-empty key path."),this.updateIn(t,function(){return gr})},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):_e(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):re()},merge:function(){return he(this,void 0,arguments)},mergeWith:function(t){for(var e=[],r=1;arguments.length>r;r++)e[r-1]=arguments[r];return he(this,t,e)},mergeDeep:function(){return he(this,ce(void 0),arguments)},mergeDeepWith:function(t){for(var e=[],r=1;arguments.length>r;r++)e[r-1]=arguments[r];return he(this,ce(t),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 o)},asImmutable:function(){return this.__ensureOwner()},wasAltered:function(){return this.__altered},__iterator:function(t,e){return new En(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?ee(this.size,this._root,t,this.__hash):(this.__ownerID=t,this.__altered=!1,this)}},{},fn),yn.isMap=Z;var mn="",gn=yn.prototype;gn[mn]=!0,gn[pr]=gn.remove;var wn=function(t,e,r){this.ownerID=t,this.bitmap=e,this.nodes=r},Sn=wn;vr.createClass(wn,{get:function(t,e,r,n){var i=1<<((0===t?e:e>>>t)&mr),u=this.bitmap;return 0===(u&i)?n:this.nodes[le(u&i-1)].get(t+dr,e,r,n)},update:function(t,e,r,n,i,u,s){var o=(0===e?r:r>>>e)&mr,a=1<<o,h=this.bitmap,c=0!==(h&a);if(!c&&i===gr)return this;var f=le(h&a-1),_=this.nodes,l=c?_[f]:void 0,v=ie(l,t,e+dr,r,n,i,u,s);if(v===l)return this;if(!c&&v&&_.length>=On)return ae(t,_,h,o,v);if(c&&!v&&2===_.length&&ue(_[1^f]))return _[1^f];if(c&&v&&1===_.length&&ue(v))return v;var p=t&&t===this.ownerID,d=c?v?h:h^a:h|a,y=c?v?ve(_,f,v,p):de(_,f,p):pe(_,f,v,p);
<add>return p?(this.bitmap=d,this.nodes=y,this):new Sn(t,d,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 zn=function(t,e,r){this.ownerID=t,this.count=e,this.nodes=r},In=zn;vr.createClass(zn,{get:function(t,e,r,n){var i=(0===t?e:e>>>t)&mr,u=this.nodes[i];return u?u.get(t+dr,e,r,n):n},update:function(t,e,r,n,i,u,s){var o=(0===e?r:r>>>e)&mr,a=i===gr,h=this.nodes,c=h[o];if(a&&!c)return this;var f=ie(c,t,e+dr,r,n,i,u,s);if(f===c)return this;var _=this.count;if(c){if(!f&&(_--,Dn>_))return oe(t,h,_,o)}else _++;var l=t&&t===this.ownerID,v=ve(h,o,f,l);return l?(this.count=_,this.nodes=v,this):new In(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 bn=function(t,e,r){this.ownerID=t,this.hash=e,this.entries=r},qn=bn;vr.createClass(bn,{get:function(t,e,r,i){for(var u=this.entries,s=0,o=u.length;o>s;s++)if(n(r,u[s][0]))return u[s][1];return i},update:function(t,e,r,i,u,o,h){var c=u===gr;if(r!==this.hash)return c?this:(s(h),s(o),se(this,t,e,r,[i,u]));for(var f=this.entries,_=0,l=f.length;l>_&&!n(i,f[_][0]);_++);var v=l>_;if(c&&!v)return this;if(s(h),(c||!v)&&s(o),c&&2===l)return new xn(t,this.hash,f[1^_]);var p=t&&t===this.ownerID,d=p?f:a(f);return v?c?_===l-1?d.pop():d[_]=d.pop():d[_]=[i,u]:d.push([i,u]),p?(this.entries=d,this):new qn(t,this.hash,d)},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 xn=function(t,e,r){this.ownerID=t,this.hash=e,this.entry=r},Mn=xn;vr.createClass(xn,{get:function(t,e,r,i){return n(r,this.entry[0])?this.entry[1]:i},update:function(t,e,r,i,u,o,a){var h=u===gr,c=n(i,this.entry[0]);return(c?u===this.entry[1]:h)?this:(s(a),h?void s(o):c?t&&t===this.ownerID?(this.entry[1]=u,this):new Mn(t,r,[i,u]):(s(o),se(this,t,e,r,[i,u])))},iterate:function(t){return t(this.entry)}},{});var En=function(t,e,r){this._type=e,this._reverse=r,this._stack=t._root&&te(t._root)};vr.createClass(En,{next:function(){for(var t=this._type,e=this._stack;e;){var r,n=e.node,i=e.index++;
<add>if(n.entry){if(0===i)return $(t,n.entry)}else if(n.entries){if(r=n.entries.length-1,r>=i)return $(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 $(t,u.entry);e=this._stack=te(u,e)}continue}e=this._stack=this._stack.__prev}return I()}},{},Kr);var kn,On=yr/2,Dn=yr/4,An=function(t,e){this._iter=t,this._useKeys=e,this.size=t.size};vr.createClass(An,{get:function(t,e){return this._iter.get(t,e)},has:function(t){return this._iter.has(t)},valueSeq:function(){return this._iter.valueSeq()},reverse:function(){var t=this,e=ge(this,!0);return this._useKeys||(e.valueSeq=function(){return t._iter.toSeq().reverse()}),e},map:function(t,e){var r=this,n=me(this,t,e);return this._useKeys||(n.valueSeq=function(){return r._iter.toSeq().map(t,e)}),n},__iterate:function(t,e){var r,n=this;return this._iter.__iterate(this._useKeys?function(e,r){return t(e,r,n)}:(r=e?Re(this):0,function(i){return t(i,e?--r:r++,n)}),e)},__iterator:function(t,e){if(this._useKeys)return this._iter.__iterator(t,e);var r=this._iter.__iterator(Ar,e),n=e?Re(this):0;return new Kr(function(){var i=r.next();return i.done?i:z(t,e?--n:n++,i.value,i)})}},{},Hr);var Cn=function(t){this._iter=t,this.size=t.size};vr.createClass(Cn,{contains:function(t){return this._iter.contains(t)},__iterate:function(t,e){var r=this,n=0;return this._iter.__iterate(function(e){return t(e,n++,r)},e)},__iterator:function(t,e){var r=this._iter.__iterator(Ar,e),n=0;return new Kr(function(){var e=r.next();return e.done?e:z(t,n++,e.value,e)})}},{},$r);var jn=function(t){this._iter=t,this.size=t.size};vr.createClass(jn,{has:function(t){return this._iter.contains(t)},__iterate:function(t,e){var r=this;return this._iter.__iterate(function(e){return t(e,e,r)},e)},__iterator:function(t,e){var r=this._iter.__iterator(Ar,e);return new Kr(function(){var e=r.next();return e.done?e:z(t,e.value,e.value,e)})}},{},en);var Rn=function(t){this._iter=t,this.size=t.size};vr.createClass(Rn,{entrySeq:function(){return this._iter.toSeq()
<add>},__iterate:function(t,e){var r=this;return this._iter.__iterate(function(e){return e?(je(e),t(e[1],e[0],r)):void 0},e)},__iterator:function(t,e){var r=this._iter.__iterator(Ar,e);return new Kr(function(){for(;;){var e=r.next();if(e.done)return e;var n=e.value;if(n)return je(n),t===Cr?e:z(t,n[0],n[1],e)}})}},{},Hr),Cn.prototype.cacheResult=An.prototype.cacheResult=jn.prototype.cacheResult=Rn.prototype.cacheResult=Le;var Un=function(t){var e=Je();if(null===t||void 0===t)return e;if(Te(t))return t;t=Qr(t);var r=t.size;return 0===r?e:r>0&&yr>r?Pe(0,r,dr,null,new Tn(t.toArray())):e.merge(t)};vr.createClass(Un,{toString:function(){return this.__toString("List [","]")},get:function(t,e){if(t=f(this,t),0>t||t>=this.size)return e;t+=this._origin;var r=Qe(this,t);return r&&r.array[t&mr]},set:function(t,e){return Ve(this,t,e)},remove:function(t){return this.has(t)?0===t?this.shift():t===this.size-1?this.pop():this.splice(t,1):this},clear:function(){return 0===this.size?this:this.__ownerID?(this.size=this._origin=this._capacity=0,this._level=dr,this._root=this._tail=null,this.__hash=void 0,this.__altered=!0,this):Je()},push:function(){var t=arguments,e=this.size;return this.withMutations(function(r){Xe(r,0,e+t.length);for(var n=0;t.length>n;n++)r.set(e+n,t[n])})},pop:function(){return Xe(this,0,-1)},unshift:function(){var t=arguments;return this.withMutations(function(e){Xe(e,-t.length);for(var r=0;t.length>r;r++)e.set(r,t[r])})},shift:function(){return Xe(this,1)},merge:function(){return Fe(this,void 0,arguments)},mergeWith:function(t){for(var e=[],r=1;arguments.length>r;r++)e[r-1]=arguments[r];return Fe(this,t,e)},mergeDeep:function(){return Fe(this,ce(void 0),arguments)},mergeDeepWith:function(t){for(var e=[],r=1;arguments.length>r;r++)e[r-1]=arguments[r];return Fe(this,ce(t),e)},setSize:function(t){return Xe(this,0,t)},slice:function(t,e){var r=this.size;return l(t,e,r)?this:Xe(this,v(t,r),p(e,r))},__iterator:function(t,e){return new Bn(this,t,e)},__iterate:function(t,e){var r=this,n=0,i=function(e){return t(e,n++,r)},u=Ge(this._capacity);
<add>return e?We(this._tail,0,u-this._origin,this._capacity-this._origin,i,e)&&We(this._root,this._level,-this._origin,u-this._origin,i,e):We(this._root,this._level,-this._origin,u-this._origin,i,e)&&We(this._tail,0,u-this._origin,this._capacity-this._origin,i,e),n},__ensureOwner:function(t){return t===this.__ownerID?this:t?Pe(this._origin,this._capacity,this._level,this._root,this._tail,t,this.__hash):(this.__ownerID=t,this)}},{of:function(){return this(arguments)}},ln),Un.isList=Te;var Kn="",Ln=Un.prototype;Ln[Kn]=!0,Ln[pr]=Ln.remove,Ln.setIn=gn.setIn,Ln.removeIn=gn.removeIn,Ln.update=gn.update,Ln.updateIn=gn.updateIn,Ln.withMutations=gn.withMutations,Ln.asMutable=gn.asMutable,Ln.asImmutable=gn.asImmutable,Ln.wasAltered=gn.wasAltered;var Tn=function(t,e){this.array=t,this.ownerID=e},Wn=Tn;vr.createClass(Tn,{removeBefore:function(t,e,r){if(r===e?1<<e:0||0===this.array.length)return this;var n=r>>>e&mr;if(n>=this.array.length)return new Wn([],t);var i,u=0===n;if(e>0){var s=this.array[n];if(i=s&&s.removeBefore(t,e-dr,r),i===s&&u)return this}if(u&&!i)return this;var o=Ye(this,t);if(!u)for(var a=0;n>a;a++)o.array[a]=void 0;return i&&(o.array[n]=i),o},removeAfter:function(t,e,r){if(r===e?1<<e:0||0===this.array.length)return this;var n=r-1>>>e&mr;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-dr,r),i===s&&u)return this}if(u&&!i)return this;var o=Ye(this,t);return u||o.array.pop(),i&&(o.array[n]=i),o}},{});var Bn=function(t,e,r){this._type=e,this._reverse=!!r,this._maxIndex=t.size-1;var n=Ge(t._capacity),i=Be(t._root&&t._root.array,t._level,-t._origin,n-t._origin-1),u=Be(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};vr.createClass(Bn,{next:function(){for(var t=this._stack;t;){var e=t.array,r=t.index++;if(this._reverse&&(r=mr-r,r>t.rawMax&&(r=t.rawMax,t.index=yr-r)),r>=0&&yr>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)),z(u,i,n)
<add>}this._stack=t=Be(n&&n.array,t.level-dr,t.offset+(r<<t.level),t.max,t)}else t=this._stack=this._stack.__prev}return I()}},{},Kr);var Pn,Jn=function(t){return null===t||void 0===t?$e():He(t)?t:$e().merge(Nr(t))};vr.createClass(Jn,{toString:function(){return this.__toString("OrderedMap {","}")},get:function(t,e){var r=this._map.get(t);return void 0!==r?this._list.get(r)[1]:e},clear:function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._map.clear(),this._list.clear(),this):$e()},set:function(t,e){return tr(this,t,e)},remove:function(t){return tr(this,t,gr)},wasAltered:function(){return this._map.wasAltered()||this._list.wasAltered()},__iterate:function(t,e){var r=this;return this._list.__iterate(function(e){return e&&t(e[1],e[0],r)},e)},__iterator:function(t,e){return this._list.fromEntrySeq().__iterator(t,e)},__ensureOwner:function(t){if(t===this.__ownerID)return this;var e=this._map.__ensureOwner(t),r=this._list.__ensureOwner(t);return t?Ze(e,r,t,this.__hash):(this.__ownerID=t,this._map=e,this._list=r,this)}},{of:function(){return this(arguments)}},yn),Jn.isOrderedMap=He;var Vn="";Jn.prototype[Vn]=!0,Jn.prototype[pr]=Jn.prototype.remove;var Nn,Yn=function(t){return null===t||void 0===t?nr():er(t)?t:nr().unshiftAll(t)},Qn=Yn;vr.createClass(Yn,{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):rr(t,e)},pushAll:function(t){if(t=Qr(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):rr(e,r)},pop:function(){return this.slice(1)},unshift:function(){return this.push.apply(this,arguments)
<add>},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):nr()},slice:function(t,e){if(l(t,e,this.size))return this;var r=v(t,this.size),n=p(e,this.size);if(n!==this.size)return vr.superCall(this,Qn.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):rr(i,u)},__ensureOwner:function(t){return t===this.__ownerID?this:t?rr(this.size,this._head,t,this.__hash):(this.__ownerID=t,this.__altered=!1,this)},__iterate:function(t,e){if(e)return this.toSeq().cacheResult.__iterate(t,e);for(var r=0,n=this._head;n&&t(n.value,r++,this)!==!1;)n=n.next;return r},__iterator:function(t,e){if(e)return this.toSeq().cacheResult().__iterator(t,e);var r=0,n=this._head;return new Kr(function(){if(n){var e=n.value;return n=n.next,z(t,r++,e)}return I()})}},{of:function(){return this(arguments)}},ln),Yn.isStack=er;var Xn="",Fn=Yn.prototype;Fn[Xn]=!0,Fn.withMutations=gn.withMutations,Fn.asMutable=gn.asMutable,Fn.asImmutable=gn.asImmutable,Fn.wasAltered=gn.wasAltered;var Gn,Hn=function(t){return null===t||void 0===t?or():ir(t)?t:or().union(Xr(t))};vr.createClass(Hn,{toString:function(){return this.__toString("Set {","}")},has:function(t){return this._map.has(t)},add:function(t){return ur(this,this._map.set(t,!0))},remove:function(t){return ur(this,this._map.remove(t))},clear:function(){return ur(this,this._map.clear())},union:function(){var t=arguments;return 0===t.length?this:this.withMutations(function(e){for(var r=0;t.length>r;r++)Xr(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 Xr(t)});var r=this;return this.withMutations(function(e){r.forEach(function(r){t.every(function(t){return t.contains(r)})||e.remove(r)
<add>})})},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 Xr(t)});var r=this;return this.withMutations(function(e){r.forEach(function(r){t.some(function(t){return t.contains(r)})&&e.remove(r)})})},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?this.__make(e,t):(this.__ownerID=t,this._map=e,this)}},{of:function(){return this(arguments)},fromKeys:function(t){return this(Nr(t).keySeq())}},pn),Hn.isSet=ir;var Zn="",$n=Hn.prototype;$n[Zn]=!0,$n[pr]=$n.remove,$n.mergeDeep=$n.merge,$n.mergeDeepWith=$n.mergeWith,$n.withMutations=gn.withMutations,$n.asMutable=gn.asMutable,$n.asImmutable=gn.asImmutable,$n.__empty=or,$n.__make=sr;var ti,ei=function(t){return null===t||void 0===t?cr():ar(t)?t:cr().union(Xr(t))};vr.createClass(ei,{toString:function(){return this.__toString("OrderedSet {","}")}},{of:function(){return this(arguments)},fromKeys:function(t){return this(Nr(t).keySeq())}},Hn),ei.isOrderedSet=ar;var ri="",ni=ei.prototype;ni[ri]=!0,ni.__empty=cr,ni.__make=hr;var ii,ui=function(t,e){var r=function(t){return this instanceof r?void(this._map=yn(t)):new r(t)},n=Object.keys(t),u=r.prototype=Object.create(si);u.constructor=r,e&&(u._name=e),u._defaultValues=t,u._keys=n,u.size=n.length;try{n.forEach(function(t){Object.defineProperty(r.prototype,t,{get:function(){return this.get(t)},set:function(e){i(this.__ownerID,"Cannot set on an immutable record."),this.set(t,e)}})})}catch(s){}return r};vr.createClass(ui,{toString:function(){return this.__toString(_r(this)+" {","}")
<add>},has:function(t){return this._defaultValues.hasOwnProperty(t)},get:function(t,e){if(!this.has(t))return e;var r=this._defaultValues[t];return this._map?this._map.get(t,r):r},clear:function(){if(this.__ownerID)return this._map&&this._map.clear(),this;var t=Object.getPrototypeOf(this).constructor;return t._empty||(t._empty=fr(this,re()))},set:function(t,e){if(!this.has(t))throw Error('Cannot set unknown key "'+t+'" on '+_r(this));var r=this._map&&this._map.set(t,e);return this.__ownerID||r===this._map?this:fr(this,r)},remove:function(t){if(!this.has(t))return this;var e=this._map&&this._map.remove(t);return this.__ownerID||e===this._map?this:fr(this,e)},wasAltered:function(){return this._map.wasAltered()},__iterator:function(t,e){var r=this;return Nr(this._defaultValues).map(function(t,e){return r.get(e)}).__iterator(t,e)},__iterate:function(t,e){var r=this;return Nr(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?fr(this,e,t):(this.__ownerID=t,this._map=e,this)}},{},fn);var si=ui.prototype;si[pr]=si.remove,si.merge=gn.merge,si.mergeWith=gn.mergeWith,si.mergeDeep=gn.mergeDeep,si.mergeDeepWith=gn.mergeDeepWith,si.update=gn.update,si.updateIn=gn.updateIn,si.withMutations=gn.withMutations,si.asMutable=gn.asMutable,si.asImmutable=gn.asImmutable;var oi=function(t,e,r){return this instanceof ai?(i(0!==r,"Cannot step a Range by 0"),t=t||0,void 0===e&&(e=1/0),t===e&&ci?ci:(r=void 0===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 ai(t,e,r)},ai=oi;vr.createClass(oi,{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+f(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 l(t,e,this.size)?this:(t=v(t,this.size),e=p(e,this.size),t>=e?ci:new ai(this.get(t,this._end),this.get(e,this._end),this._step))
<add>},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 Kr(function(){var s=i;return i+=e?-n:n,u>r?I():z(t,u++,s)})},__deepEquals:function(t){return t instanceof ai?this._start===t._start&&this._end===t._end&&this._step===t._step:vr.superCall(this,ai.prototype,"__deepEquals",[t])}},{},$r);var hi=oi.prototype;hi.__toJS=hi.toArray,hi.first=Ln.first,hi.last=Ln.last;var ci=oi(0,0),fi=function(t,e){return 0>=e&&vi?vi:this instanceof _i?(this._value=t,this.size=void 0===e?1/0:Math.max(0,e),void(0===this.size&&(vi=this))):new _i(t,e)},_i=fi;vr.createClass(fi,{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 l(t,e,r)?this:new _i(this._value,p(e,r)-v(t,r))},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 Kr(function(){return e.size>r?z(t,r++,e._value):I()})},__deepEquals:function(t){return t instanceof _i?n(this._value,t._value):vr.superCall(this,_i.prototype,"__deepEquals",[t])}},{},$r);var li=fi.prototype;li.last=li.first,li.has=hi.has,li.take=hi.take,li.skip=hi.skip,li.__toJS=hi.__toJS;var vi,pi={Iterable:Tr,Seq:Fr,Collection:cn,Map:yn,OrderedMap:Jn,List:Un,Stack:Yn,Set:Hn,OrderedSet:ei,Record:ui,Range:oi,Repeat:fi,is:n,fromJS:X};
<add>return pi}"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/Operations.js
<ide> function sortFactory(iterable, comparator, mapper) {
<ide>
<ide> function maxFactory(iterable, comparator, mapper) {
<ide> if (mapper) {
<del> var entry = iterable.entrySeq().reduce(
<del> (max, next) => comparator(
<del> mapper(next[1], next[0], iterable),
<del> mapper(max[1], max[0], iterable)
<del> ) > 0 ? next : max
<del> );
<del> return entry && entry[1];
<add> var entry = iterable.toSeq()
<add> .map((v, k) => [v, mapper(v, k, iterable)])
<add> .reduce((max, next) => comparator(next[1], max[1]) > 0 ? next : max);
<add> return entry && entry[0];
<ide> } else {
<ide> return iterable.reduce(
<ide> (max, next) => comparator(next, max) > 0 ? next : max | 3 |
PHP | PHP | add helper methods to json response | 6f36d658d936b720c4e195b5f5545e51829c2ff1 | <ide><path>src/Illuminate/Http/JsonResponse.php
<ide> public function setData($data = array())
<ide> return $this->update();
<ide> }
<ide>
<add> /**
<add> * Set a header on the Response.
<add> *
<add> * @param string $key
<add> * @param string $value
<add> * @param bool $replace
<add> * @return \Illuminate\Http\Response
<add> */
<add> public function header($key, $value, $replace = true)
<add> {
<add> $this->headers->set($key, $value, $replace);
<add>
<add> return $this;
<add> }
<add>
<add> /**
<add> * Add a cookie to the response.
<add> *
<add> * @param \Symfony\Component\HttpFoundation\Cookie $cookie
<add> * @return \Illuminate\Http\Response
<add> */
<add> public function withCookie(Cookie $cookie)
<add> {
<add> $this->headers->setCookie($cookie);
<add>
<add> return $this;
<add> }
<add>
<ide> }
<ide>\ No newline at end of file | 1 |
Go | Go | add integ test for unpublished ports in ps o/p | 7b9ae696d86066f6245e2c17e7afd5ce8e868fe5 | <ide><path>integration-cli/docker_cli_port_test.go
<ide> package main
<ide>
<ide> import (
<add> "fmt"
<ide> "net"
<ide> "os/exec"
<add> "regexp"
<ide> "sort"
<ide> "strings"
<ide>
<ide> func (s *DockerSuite) TestPortExposeHostBinding(c *check.C) {
<ide> c.Error("Port is still bound after the Container is removed")
<ide> }
<ide> }
<add>
<add>func stopRemoveContainer(id string, c *check.C) {
<add> runCmd := exec.Command(dockerBinary, "rm", "-f", id)
<add> _, _, err := runCommandWithOutput(runCmd)
<add> c.Assert(err, check.IsNil)
<add>}
<add>
<add>func (s *DockerSuite) TestUnpublishedPortsInPsOutput(c *check.C) {
<add> // Run busybox with command line expose (equivalent to EXPOSE in image's Dockerfile) for the following ports
<add> port1 := 80
<add> port2 := 443
<add> expose1 := fmt.Sprintf("--expose=%d", port1)
<add> expose2 := fmt.Sprintf("--expose=%d", port2)
<add> runCmd := exec.Command(dockerBinary, "run", "-d", expose1, expose2, "busybox", "sleep", "5")
<add> out, _, err := runCommandWithOutput(runCmd)
<add> c.Assert(err, check.IsNil)
<add>
<add> // Check docker ps o/p for last created container reports the unpublished ports
<add> unpPort1 := fmt.Sprintf("%d/tcp", port1)
<add> unpPort2 := fmt.Sprintf("%d/tcp", port2)
<add> runCmd = exec.Command(dockerBinary, "ps", "-n=1")
<add> out, _, err = runCommandWithOutput(runCmd)
<add> c.Assert(err, check.IsNil)
<add> if !strings.Contains(out, unpPort1) || !strings.Contains(out, unpPort2) {
<add> c.Errorf("Missing unpublished ports(s) (%s, %s) in docker ps output: %s", unpPort1, unpPort2, out)
<add> }
<add>
<add> // Run the container forcing to publish the exposed ports
<add> runCmd = exec.Command(dockerBinary, "run", "-d", "-P", expose1, expose2, "busybox", "sleep", "5")
<add> out, _, err = runCommandWithOutput(runCmd)
<add> c.Assert(err, check.IsNil)
<add>
<add> // Check docker ps o/p for last created container reports the exposed ports in the port bindings
<add> expBndRegx1 := regexp.MustCompile(`0.0.0.0:\d\d\d\d\d->` + unpPort1)
<add> expBndRegx2 := regexp.MustCompile(`0.0.0.0:\d\d\d\d\d->` + unpPort2)
<add> runCmd = exec.Command(dockerBinary, "ps", "-n=1")
<add> out, _, err = runCommandWithOutput(runCmd)
<add> c.Assert(err, check.IsNil)
<add> if !expBndRegx1.MatchString(out) || !expBndRegx2.MatchString(out) {
<add> c.Errorf("Cannot find expected port binding ports(s) (0.0.0.0:xxxxx->%s, 0.0.0.0:xxxxx->%s) in docker ps output:\n%s",
<add> unpPort1, unpPort2, out)
<add> }
<add>
<add> // Run the container specifying explicit port bindings for the exposed ports
<add> offset := 10000
<add> pFlag1 := fmt.Sprintf("%d:%d", offset+port1, port1)
<add> pFlag2 := fmt.Sprintf("%d:%d", offset+port2, port2)
<add> runCmd = exec.Command(dockerBinary, "run", "-d", "-p", pFlag1, "-p", pFlag2, expose1, expose2, "busybox", "sleep", "5")
<add> out, _, err = runCommandWithOutput(runCmd)
<add> c.Assert(err, check.IsNil)
<add> id := strings.TrimSpace(out)
<add>
<add> // Check docker ps o/p for last created container reports the specified port mappings
<add> expBnd1 := fmt.Sprintf("0.0.0.0:%d->%s", offset+port1, unpPort1)
<add> expBnd2 := fmt.Sprintf("0.0.0.0:%d->%s", offset+port2, unpPort2)
<add> runCmd = exec.Command(dockerBinary, "ps", "-n=1")
<add> out, _, err = runCommandWithOutput(runCmd)
<add> c.Assert(err, check.IsNil)
<add> if !strings.Contains(out, expBnd1) || !strings.Contains(out, expBnd2) {
<add> c.Errorf("Cannot find expected port binding(s) (%s, %s) in docker ps output: %s", expBnd1, expBnd2, out)
<add> }
<add> // Remove container now otherwise it will interfeer with next test
<add> stopRemoveContainer(id, c)
<add>
<add> // Run the container with explicit port bindings and no exposed ports
<add> runCmd = exec.Command(dockerBinary, "run", "-d", "-p", pFlag1, "-p", pFlag2, "busybox", "sleep", "5")
<add> out, _, err = runCommandWithOutput(runCmd)
<add> c.Assert(err, check.IsNil)
<add> id = strings.TrimSpace(out)
<add>
<add> // Check docker ps o/p for last created container reports the specified port mappings
<add> runCmd = exec.Command(dockerBinary, "ps", "-n=1")
<add> out, _, err = runCommandWithOutput(runCmd)
<add> c.Assert(err, check.IsNil)
<add> if !strings.Contains(out, expBnd1) || !strings.Contains(out, expBnd2) {
<add> c.Errorf("Cannot find expected port binding(s) (%s, %s) in docker ps output: %s", expBnd1, expBnd2, out)
<add> }
<add> // Remove container now otherwise it will interfeer with next test
<add> stopRemoveContainer(id, c)
<add>
<add> // Run the container with one unpublished exposed port and one explicit port binding
<add> runCmd = exec.Command(dockerBinary, "run", "-d", expose1, "-p", pFlag2, "busybox", "sleep", "5")
<add> out, _, err = runCommandWithOutput(runCmd)
<add> c.Assert(err, check.IsNil)
<add>
<add> // Check docker ps o/p for last created container reports the specified unpublished port and port mapping
<add> runCmd = exec.Command(dockerBinary, "ps", "-n=1")
<add> out, _, err = runCommandWithOutput(runCmd)
<add> c.Assert(err, check.IsNil)
<add> if !strings.Contains(out, unpPort1) || !strings.Contains(out, expBnd2) {
<add> c.Errorf("Missing unpublished ports or port binding (%s, %s) in docker ps output: %s", unpPort1, expBnd2, out)
<add> }
<add>} | 1 |
Python | Python | add warnings section to arange docstring | 542e35e121988a9a942435da91d407d11a6ff96b | <ide><path>numpy/core/_add_newdocs.py
<ide> For integer arguments the function is equivalent to the Python built-in
<ide> `range` function, but returns an ndarray rather than a list.
<ide>
<del> When using a non-integer step, such as 0.1, the results will often not
<del> be consistent. It is better to use `numpy.linspace` for these cases.
<add> When using a non-integer step, such as 0.1, it is often better to use
<add> `numpy.linspace`. See the warnings section below for more information.
<ide>
<ide> Parameters
<ide> ----------
<ide> this rule may result in the last element of `out` being greater
<ide> than `stop`.
<ide>
<add> Warnings
<add> --------
<add> The length of the output might not be numerically stable.
<add>
<add> Another stability issue is due to the internal implementation of
<add> `numpy.arange`.
<add> The actual step value used to populate the array is
<add> ``dtype(start + step) - dtype(start)`` and not `step`. Precision loss
<add> can occur here, due to casting or due to using floating points when
<add> `start` is much larger than `step`. This can lead to unexpected
<add> behaviour. For example::
<add>
<add> >>> np.arange(0, 5, 0.5, dtype=int)
<add> array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
<add> >>> np.arange(-3, 3, 0.5, dtype=int)
<add> array([-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8])
<add>
<add> In such cases, the use of `numpy.linspace` should be preferred.
<add>
<ide> See Also
<ide> --------
<ide> numpy.linspace : Evenly spaced numbers with careful handling of endpoints. | 1 |
PHP | PHP | avoid double path checking | 021b9158a1dd11bb32ee358de18eff06e883fa13 | <ide><path>src/Illuminate/Foundation/helpers.php
<ide> function app($abstract = null, array $parameters = [])
<ide> */
<ide> function app_path($path = '')
<ide> {
<del> return app('path').($path ? DIRECTORY_SEPARATOR.$path : $path);
<add> return app()->path($path);
<ide> }
<ide> }
<ide>
<ide> function back($status = 302, $headers = [], $fallback = false)
<ide> */
<ide> function base_path($path = '')
<ide> {
<del> return app()->basePath().($path ? DIRECTORY_SEPARATOR.$path : $path);
<add> return app()->basePath($path);
<ide> }
<ide> }
<ide>
<ide> function config($key = null, $default = null)
<ide> */
<ide> function config_path($path = '')
<ide> {
<del> return app()->make('path.config').($path ? DIRECTORY_SEPARATOR.$path : $path);
<add> return app()->configPath($path);
<ide> }
<ide> }
<ide> | 1 |
PHP | PHP | remove deprecated code from expression classes | 2f7354de38841dea14608cbefe3e017aabba5f3f | <ide><path>src/Database/Expression/FunctionExpression.php
<ide> public function getName()
<ide> return $this->_name;
<ide> }
<ide>
<del> /**
<del> * Sets the name of the SQL function to be invoke in this expression,
<del> * if no value is passed it will return current name
<del> *
<del> * @deprecated 3.4.0 Use setName()/getName() instead.
<del> * @param string|null $name The name of the function
<del> * @return string|$this
<del> */
<del> public function name($name = null)
<del> {
<del> deprecationWarning(
<del> 'FunctionExpression::name() is deprecated. ' .
<del> 'Use FunctionExpression::setName()/getName() instead.'
<del> );
<del> if ($name !== null) {
<del> return $this->setName($name);
<del> }
<del>
<del> return $this->getName();
<del> }
<del>
<ide> /**
<ide> * Adds one or more arguments for the function call.
<ide> *
<ide><path>src/Database/Expression/OrderByExpression.php
<ide> public function sql(ValueBinder $generator)
<ide> */
<ide> protected function _addConditions(array $orders, array $types)
<ide> {
<del> foreach ($orders as $key => $val) {
<del> if (is_string($key) && is_string($val) && !in_array(strtoupper($val), ['ASC', 'DESC'], true)) {
<del> deprecationWarning(
<del> 'Passing extra sort expressions by associative array is deprecated. ' .
<del> 'Use QueryExpression or numeric array instead.'
<del> );
<del> }
<del> }
<ide> $this->_conditions = array_merge($this->_conditions, $orders);
<ide> }
<ide> }
<ide><path>src/Database/Expression/QueryExpression.php
<ide> public function getConjunction()
<ide> return $this->_conjunction;
<ide> }
<ide>
<del> /**
<del> * Changes the conjunction for the conditions at this level of the expression tree.
<del> * If called with no arguments it will return the currently configured value.
<del> *
<del> * @deprecated 3.4.0 Use setConjunction()/getConjunction() instead.
<del> * @param string|null $conjunction value to be used for joining conditions. If null it
<del> * will not set any value, but return the currently stored one
<del> * @return string|$this
<del> */
<del> public function tieWith($conjunction = null)
<del> {
<del> deprecationWarning(
<del> 'QueryExpression::tieWith() is deprecated. ' .
<del> 'Use QueryExpression::setConjunction()/getConjunction() instead.'
<del> );
<del> if ($conjunction !== null) {
<del> return $this->setConjunction($conjunction);
<del> }
<del>
<del> return $this->getConjunction();
<del> }
<del>
<del> /**
<del> * Backwards compatible wrapper for tieWith()
<del> *
<del> * @param string|null $conjunction value to be used for joining conditions. If null it
<del> * will not set any value, but return the currently stored one
<del> * @return string|$this
<del> * @deprecated 3.2.0 Use setConjunction()/getConjunction() instead
<del> */
<del> public function type($conjunction = null)
<del> {
<del> deprecationWarning(
<del> 'QueryExpression::type() is deprecated. ' .
<del> 'Use QueryExpression::setConjunction()/getConjunction() instead.'
<del> );
<del>
<del> return $this->tieWith($conjunction);
<del> }
<del>
<ide> /**
<ide> * Adds one or more conditions to this expression object. Conditions can be
<ide> * expressed in a one dimensional array, that will cause all conditions to
<ide><path>src/Database/Expression/ValuesExpression.php
<ide> public function getColumns()
<ide> return $this->_columns;
<ide> }
<ide>
<del> /**
<del> * Sets the columns to be inserted. If no params are passed, then it returns
<del> * the currently stored columns.
<del> *
<del> * @deprecated 3.4.0 Use setColumns()/getColumns() instead.
<del> * @param array|null $cols Array with columns to be inserted.
<del> * @return array|$this
<del> */
<del> public function columns($cols = null)
<del> {
<del> deprecationWarning(
<del> 'ValuesExpression::columns() is deprecated. ' .
<del> 'Use ValuesExpression::setColumns()/getColumns() instead.'
<del> );
<del> if ($cols !== null) {
<del> return $this->setColumns($cols);
<del> }
<del>
<del> return $this->getColumns();
<del> }
<del>
<ide> /**
<ide> * Get the bare column names.
<ide> *
<ide> public function getValues()
<ide> return $this->_values;
<ide> }
<ide>
<del> /**
<del> * Sets the values to be inserted. If no params are passed, then it returns
<del> * the currently stored values
<del> *
<del> * @deprecated 3.4.0 Use setValues()/getValues() instead.
<del> * @param array|null $values Array with values to be inserted.
<del> * @return array|$this
<del> */
<del> public function values($values = null)
<del> {
<del> deprecationWarning(
<del> 'ValuesExpression::values() is deprecated. ' .
<del> 'Use ValuesExpression::setValues()/getValues() instead.'
<del> );
<del> if ($values !== null) {
<del> return $this->setValues($values);
<del> }
<del>
<del> return $this->getValues();
<del> }
<del>
<ide> /**
<ide> * Sets the query object to be used as the values expression to be evaluated
<ide> * to insert records in the table.
<ide> public function getQuery()
<ide> return $this->_query;
<ide> }
<ide>
<del> /**
<del> * Sets the query object to be used as the values expression to be evaluated
<del> * to insert records in the table. If no params are passed, then it returns
<del> * the currently stored query
<del> *
<del> * @deprecated 3.4.0 Use setQuery()/getQuery() instead.
<del> * @param \Cake\Database\Query|null $query The query to set
<del> * @return \Cake\Database\Query|null|$this
<del> */
<del> public function query(Query $query = null)
<del> {
<del> deprecationWarning(
<del> 'ValuesExpression::query() is deprecated. ' .
<del> 'Use ValuesExpression::setQuery()/getQuery() instead.'
<del> );
<del> if ($query !== null) {
<del> return $this->setQuery($query);
<del> }
<del>
<del> return $this->getQuery();
<del> }
<del>
<ide> /**
<ide> * Convert the values into a SQL string with placeholders.
<ide> *
<ide><path>tests/TestCase/Database/Expression/QueryExpressionTest.php
<ide> public function testConjunction()
<ide> $this->assertEquals('(1 + 2)', $result);
<ide> }
<ide>
<del> /**
<del> * Test tieWith() works.
<del> *
<del> * @group deprecated
<del> * @return
<del> */
<del> public function testTieWith()
<del> {
<del> $this->deprecated(function () {
<del> $expr = new QueryExpression(['1', '2']);
<del> $binder = new ValueBinder();
<del>
<del> $this->assertSame($expr, $expr->tieWith('+'));
<del> $this->assertSame('+', $expr->tieWith());
<del>
<del> $result = $expr->sql($binder);
<del> $this->assertEquals('(1 + 2)', $result);
<del> });
<del> }
<del>
<del> /**
<del> * Test type() works.
<del> *
<del> * @group deprecated
<del> * @return
<del> */
<del> public function testType()
<del> {
<del> $this->deprecated(function () {
<del> $expr = new QueryExpression(['1', '2']);
<del> $binder = new ValueBinder();
<del>
<del> $this->assertSame($expr, $expr->type('+'));
<del> $this->assertSame('+', $expr->type());
<del>
<del> $result = $expr->sql($binder);
<del> $this->assertEquals('(1 + 2)', $result);
<del> });
<del> }
<del>
<ide> /**
<ide> * Test and() and or() calls work transparently
<ide> * | 5 |
Python | Python | add base to templated arguments for platlib | 177c45f021c1fb70f3c0111d633ff343afa69c92 | <ide><path>runtests.py
<ide> def build_project(args):
<ide> site_dir = site_dir_template.format(platbase=dst_dir,
<ide> py_version_short=py_v_s,
<ide> platlibdir=platlibdir,
<add> base=dst_dir,
<ide> )
<ide> noarch_template = sysconfig.get_path('purelib', expand=False)
<ide> site_dir_noarch = noarch_template.format(base=dst_dir, | 1 |
Java | Java | fix failing test | e6f479677916adf7dce6c3f4e5a6faa6c9a1a0bd | <ide><path>spring-messaging/src/test/java/org/springframework/messaging/core/MessageSendingTemplateTests.java
<ide> public void convertAndSendPayloadWithPostProcessorToDestination() {
<ide> public void convertAndSendNoMatchingConverter() {
<ide>
<ide> MessageConverter converter = new CompositeMessageConverter(
<del> Arrays.asList(new MappingJackson2MessageConverter()), new DefaultContentTypeResolver());
<add> Arrays.<MessageConverter>asList(new MappingJackson2MessageConverter()), new DefaultContentTypeResolver());
<ide> this.template.setMessageConverter(converter);
<ide>
<ide> this.headers.put(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_XML); | 1 |
Python | Python | remove the added json parameter | da8e8664325eec0d36ad64df86af49165c3743f3 | <ide><path>libcloud/common/base.py
<ide> def request(self, action, params=None, data=None, headers=None,
<ide> stream=stream)
<ide> else:
<ide> self.connection.request(method=method, url=url, body=data,
<del> headers=headers, stream=stream, json=json)
<add> headers=headers, stream=stream)
<ide> except socket.gaierror as e:
<ide> message = str(e)
<ide> errno = getattr(e, 'errno', None) | 1 |
Python | Python | update refresh jwt when needed | f5357ffe45a75e5440b286900585cfd2bcdee8b9 | <ide><path>libcloud/common/gig_g8.py
<ide> # limitations under the License.
<ide>
<ide> from libcloud.common.base import ConnectionKey, JsonResponse
<add>import json
<add>import base64
<add>import requests
<add>import os
<add>import time
<add>
<add># normally we only use itsyou.online but you might want to work
<add># against staging.itsyou.online for some testing
<add>IYO_URL = os.environ.get("IYO_URL", "https://itsyou.online")
<ide>
<ide>
<ide> class G8Connection(ConnectionKey):
<ide> def add_default_headers(self, headers):
<ide> """
<ide> Add headers that are necessary for every request
<ide> """
<add> self.driver.key = maybe_update_jwt(self.driver.key)
<ide> headers['Authorization'] = "bearer {}".format(self.driver.key)
<ide> headers['Content-Type'] = 'application/json'
<ide> return headers
<add>
<add>
<add>def base64url_decode(input):
<add> """
<add> Helper method to base64url_decode a string.
<add>
<add> :param input: Input to decode
<add> :type input: str
<add>
<add> :rtype: str
<add> """
<add> rem = len(input) % 4
<add>
<add> if rem > 0:
<add> input += b'=' * (4 - rem)
<add> return base64.urlsafe_b64decode(input)
<add>
<add>
<add>def is_jwt_expired(jwt):
<add> """
<add> Check if jwt is expired
<add>
<add> :param jwt: jwt token to validate expiration
<add> :type jwt: str
<add>
<add> :rtype: bool
<add> """
<add> jwt = jwt.encode('utf-8')
<add> signing_input, _ = jwt.rsplit(b'.', 1)
<add> _, claims_segment = signing_input.split(b'.', 1)
<add> claimsdata = base64url_decode(claims_segment)
<add> if isinstance(claimsdata, bytes):
<add> claimsdata = claimsdata.decode('utf-8')
<add> data = json.loads(claimsdata)
<add> # check if it's about to expire in the next minute
<add> return data['exp'] < time.time() - 60
<add>
<add>
<add>def maybe_update_jwt(jwt):
<add> """
<add> Update jwt if it is expired
<add>
<add> :param jwt: jwt token to validate expiration
<add> :type jwt: str
<add>
<add> :rtype: str
<add> """
<add>
<add> if is_jwt_expired(jwt):
<add> return refresh_jwt(jwt)
<add> return jwt
<add>
<add>
<add>def refresh_jwt(jwt):
<add> """
<add> Refresh jwt
<add>
<add> :param jwt: jwt token to refresh
<add> :type jwt: str
<add>
<add> :rtype: str
<add> """
<add> url = IYO_URL + "/v1/oauth/jwt/refresh"
<add> headers = {"Authorization": "bearer {}".format(jwt)}
<add> response = requests.get(url, headers=headers)
<add> response.raise_for_status()
<add> return response.text | 1 |
PHP | PHP | add an entity getter | 7815661deb7e01090215e6925f0fac3afe966ef1 | <ide><path>src/ORM/Exception/PersistenceFailedException.php
<ide> namespace Cake\ORM\Exception;
<ide>
<ide> use Cake\Core\Exception\Exception;
<add>use Cake\Datasource\EntityInterface;
<ide>
<ide> /**
<ide> * Used when a strict save or delete fails
<ide> */
<ide> class PersistenceFailedException extends Exception
<ide> {
<ide>
<add> /**
<add> * The entity on which the persistence operation failed
<add> *
<add> * @var \Cake\Datasource\EntityInterface
<add> */
<add> protected $_entity;
<add>
<add> /**
<add> * {@inheritDoc}
<add> */
<ide> protected $_messageTemplate = 'Entity %s failure.';
<add>
<add> /**
<add> * Constructor.
<add> *
<add> * @param \Cake\Datasource\EntityInterface $entity The entity on which the persistence operation failed
<add> * @param string|array $message Either the string of the error message, or an array of attributes
<add> * that are made available in the view, and sprintf()'d into Exception::$_messageTemplate
<add> * @param int $code The code of the error, is also the HTTP status code for the error.
<add> * @param \Exception|null $previous the previous exception.
<add> */
<add> public function __construct(EntityInterface $entity, $message, $code = 500, $previous = null)
<add> {
<add> $this->_entity = $entity;
<add> parent::__construct($message, $code, $previous);
<add> }
<add>
<add> /**
<add> * Get the passed in entity
<add> *
<add> * @return \Cake\Datasource\EntityInterface
<add> */
<add> public function getEntity()
<add> {
<add> return $this->_entity;
<add> }
<ide> }
<ide><path>src/ORM/Table.php
<ide> public function saveOrFail(EntityInterface $entity, $options = [])
<ide> {
<ide> $saved = $this->save($entity, $options);
<ide> if ($saved === false) {
<del> throw new PersistenceFailedException(['save', $entity]);
<add> throw new PersistenceFailedException($entity, ['save']);
<ide> }
<ide>
<ide> return $saved;
<ide> public function deleteOrFail(EntityInterface $entity, $options = [])
<ide> {
<ide> $deleted = $this->delete($entity, $options);
<ide> if ($deleted === false) {
<del> throw new PersistenceFailedException(['delete', $entity]);
<add> throw new PersistenceFailedException($entity, ['delete']);
<ide> }
<ide>
<ide> return $deleted;
<ide><path>tests/TestCase/ORM/TableTest.php
<ide> public function testSaveOrFail()
<ide> $this->assertSame([], $row->toArray());
<ide> }
<ide>
<add> /**
<add> * Tests that saveOrFail returns the right entity
<add> *
<add> * @return void
<add> */
<add> public function testSaveOrFailGetEntity()
<add> {
<add> $entity = new Entity([
<add> 'foo' => 'bar'
<add> ]);
<add> $table = TableRegistry::get('users');
<add>
<add> try {
<add> $table->saveOrFail($entity);
<add> } catch (\Cake\ORM\Exception\PersistenceFailedException $e) {
<add> $this->assertSame($entity, $e->getEntity());
<add> }
<add> }
<add>
<ide> /**
<ide> * Tests that deleteOrFail triggers an exception on not successful delete
<ide> *
<ide> public function testDeleteOrFail()
<ide> $result = $table->deleteOrFail($entity);
<ide> }
<ide>
<add> /**
<add> * Tests that deleteOrFail returns the right entity
<add> *
<add> * @return void
<add> */
<add> public function testDeleteOrFailGetEntity()
<add> {
<add> $entity = new Entity([
<add> 'id' => 999
<add> ]);
<add> $table = TableRegistry::get('users');
<add>
<add> try {
<add> $table->deleteOrFail($entity);
<add> } catch (\Cake\ORM\Exception\PersistenceFailedException $e) {
<add> $this->assertSame($entity, $e->getEntity());
<add> }
<add> }
<add>
<ide> /**
<ide> * Test getting the save options builder.
<ide> * | 3 |
Python | Python | fix typo in multiarray tests | 5bc4aefda5bfd7dde9599e2f75ce58696d9bc2c1 | <ide><path>numpy/core/tests/test_multiarray.py
<ide> def test_roundtrip_file(self):
<ide> y = np.fromfile(f, dtype=self.dtype)
<ide> f.close()
<ide> assert_array_equal(y, self.x.flat)
<del> os.unlink(filename)
<add> os.unlink(self.filename)
<ide>
<ide> def test_roundtrip_filename(self):
<ide> self.x.tofile(self.filename)
<ide> def test_tofile_sep(self):
<ide> s = f.read()
<ide> f.close()
<ide> assert_equal(s, '1.51,2.0,3.51,4.0')
<del> os.unlink(filename)
<add> os.unlink(self.filename)
<ide>
<ide> def test_tofile_format(self):
<ide> x = np.array([1.51, 2, 3.51, 4], dtype=float) | 1 |
Javascript | Javascript | fix some jslint warnings | ef2f3cdc24e727df30bc19f6ff44707a99c86195 | <ide><path>pdf.js
<ide> var FakeStream = (function() {
<ide> };
<ide>
<ide> constructor.prototype.getBytes = function(length) {
<del> var pos = this.pos;
<add> var end, pos = this.pos;
<ide>
<ide> if (length) {
<ide> this.ensureBuffer(pos + length);
<del> var end = pos + length;
<add> end = pos + length;
<ide>
<ide> while (!this.eof && this.bufferLength < end)
<ide> this.readBlock();
<ide> var FakeStream = (function() {
<ide> end = bufEnd;
<ide> } else {
<ide> this.eof = true;
<del> var end = this.bufferLength;
<add> end = this.bufferLength;
<ide> }
<ide>
<ide> this.pos = end;
<ide> var CCITTFaxStream = (function() {
<ide> constructor.prototype.eatBits = function(n) {
<ide> if ((this.inputBits -= n) < 0)
<ide> this.inputBits = 0;
<del> }
<add> };
<ide>
<ide> return constructor;
<ide> })();
<ide> var Lexer = (function() {
<ide>
<ide> constructor.isSpace = function(ch) {
<ide> return ch == ' ' || ch == '\t';
<del> }
<add> };
<ide>
<ide> // A '1' in this array means the character is white space. A '1' or
<ide> // '2' means the character ends a name or command.
<ide> var Lexer = (function() {
<ide> var stream = this.stream;
<ide> var ch;
<ide> do {
<del> switch (ch = stream.getChar()) {
<add> ch = stream.getChar();
<add> switch (ch) {
<ide> case undefined:
<ide> warn('Unterminated string');
<ide> done = true;
<ide> var Lexer = (function() {
<ide> }
<ide> break;
<ide> case '\\':
<del> switch (ch = stream.getChar()) {
<add> ch = stream.getChar();
<add> switch (ch) {
<ide> case undefined:
<ide> warn('Unterminated string');
<ide> done = true;
<ide> var Parser = (function() {
<ide> if (xref)
<ide> length = xref.fetchIfRef(length);
<ide> if (!IsInt(length)) {
<del> error('Bad ' + Length + ' attribute in stream');
<add> error('Bad ' + length + ' attribute in stream');
<ide> length = 0;
<ide> }
<ide>
<ide> var XRef = (function() {
<ide> if (!IsCmd(obj3, 'obj')) {
<ide> // some bad pdfs use "obj1234" and really mean 1234
<ide> if (obj3.cmd.indexOf('obj') == 0) {
<del> var num = parseInt(obj3.cmd.substring(3));
<add> num = parseInt(obj3.cmd.substring(3));
<ide> if (!isNaN(num))
<ide> return num;
<ide> }
<ide> var XRef = (function() {
<ide> var i, entries = [], nums = [];
<ide> // read the object numbers to populate cache
<ide> for (i = 0; i < n; ++i) {
<del> var num = parser.getObj();
<add> num = parser.getObj();
<ide> if (!IsInt(num)) {
<ide> error('invalid object number in the ObjStm stream: ' + num);
<ide> }
<ide> var PartialEvaluator = (function() {
<ide> return function(gfx) {
<ide> for (var i = 0, length = argsArray.length; i < length; i++)
<ide> gfx[fnArray[i]].apply(gfx, argsArray[i]);
<del> }
<add> };
<ide> },
<ide>
<ide> translateFont: function(fontDict, xref, resources) {
<ide> var CanvasGraphics = (function() {
<ide> })();
<ide>
<ide> var Util = (function() {
<del> function constructor() {};
<add> function constructor() {}
<ide> constructor.makeCssRgb = function makergb(r, g, b) {
<ide> var ri = (255 * r) | 0, gi = (255 * g) | 0, bi = (255 * b) | 0;
<ide> return 'rgb(' + ri + ',' + gi + ',' + bi + ')';
<ide> var ColorSpace = (function() {
<ide> // Constructor should define this.numComps, this.defaultColor, this.name
<ide> function constructor() {
<ide> error('should not call ColorSpace constructor');
<del> };
<add> }
<ide>
<ide> constructor.prototype = {
<ide> // Input: array of size numComps representing color component values
<ide> var ColorSpace = (function() {
<ide> case 'DeviceGray':
<ide> case 'G':
<ide> return new DeviceGrayCS();
<del> break;
<ide> case 'DeviceRGB':
<ide> case 'RGB':
<ide> return new DeviceRgbCS();
<del> break;
<ide> case 'DeviceCMYK':
<ide> case 'CMYK':
<ide> return new DeviceCmykCS();
<del> break;
<ide> case 'Pattern':
<ide> return new PatternCS(null);
<del> break;
<ide> default:
<ide> error('unrecognized colorspace ' + mode);
<ide> }
<ide> var ColorSpace = (function() {
<ide> case 'DeviceGray':
<ide> case 'G':
<ide> return new DeviceGrayCS();
<del> break;
<ide> case 'DeviceRGB':
<ide> case 'RGB':
<ide> return new DeviceRgbCS();
<del> break;
<ide> case 'DeviceCMYK':
<ide> case 'CMYK':
<ide> return new DeviceCmykCS();
<del> break;
<ide> case 'CalGray':
<ide> return new DeviceGrayCS();
<del> break;
<ide> case 'CalRGB':
<ide> return new DeviceRgbCS();
<del> break;
<ide> case 'ICCBased':
<ide> var stream = xref.fetchIfRef(cs[1]);
<ide> var dict = stream.dict;
<ide> var numComps = dict.get('N');
<ide> if (numComps == 1)
<ide> return new DeviceGrayCS();
<del> else if (numComps == 3)
<add> if (numComps == 3)
<ide> return new DeviceRgbCS();
<del> else if (numComps == 4)
<add> if (numComps == 4)
<ide> return new DeviceCmykCS();
<ide> break;
<ide> case 'Pattern':
<ide> var baseCS = cs[1];
<ide> if (baseCS)
<ide> baseCS = ColorSpace.parse(baseCS, xref, res);
<ide> return new PatternCS(baseCS);
<del> break;
<ide> case 'Indexed':
<ide> var base = ColorSpace.parse(cs[1], xref, res);
<ide> var hiVal = cs[2] + 1;
<ide> var lookup = xref.fetchIfRef(cs[3]);
<ide> return new IndexedCS(base, hiVal, lookup);
<del> break;
<ide> case 'Separation':
<ide> var name = cs[1];
<ide> var alt = ColorSpace.parse(cs[2], xref, res);
<ide> var tintFn = new PDFFunction(xref, xref.fetchIfRef(cs[3]));
<ide> return new SeparationCS(alt, tintFn);
<del> break;
<ide> case 'Lab':
<ide> case 'DeviceN':
<ide> default:
<ide> var IndexedCS = (function() {
<ide>
<ide> constructor.prototype = {
<ide> getRgb: function indexcs_getRgb(color) {
<del> var numComps = base.numComps;
<add> var numComps = this.base.numComps;
<ide>
<ide> var start = color[0] * numComps;
<ide> var c = [];
<ide> var DeviceGrayCS = (function() {
<ide> this.name = 'DeviceGray';
<ide> this.numComps = 1;
<ide> this.defaultColor = [0];
<del> };
<add> }
<ide>
<ide> constructor.prototype = {
<ide> getRgb: function graycs_getRgb(color) {
<ide> var Pattern = (function() {
<ide> // Constructor should define this.getPattern
<ide> function constructor() {
<ide> error('should not call Pattern constructor');
<del> };
<add> }
<ide>
<ide> constructor.prototype = {
<ide> // Input: current Canvas context
<ide> var Pattern = (function() {
<ide> default:
<ide> return new DummyShading();
<ide> }
<del> }
<add> };
<ide> return constructor;
<ide> })();
<ide>
<ide> var DummyShading = (function() {
<ide> function constructor() {
<ide> this.type = 'Pattern';
<del> };
<add> }
<ide> constructor.prototype = {
<ide> getPattern: function dummy_getpattern() {
<ide> return 'hotpink';
<ide> var RadialAxialShading = (function() {
<ide> var t0 = 0.0, t1 = 1.0;
<ide> if (dict.has('Domain')) {
<ide> var domainArr = dict.get('Domain');
<del> t0 = domainArr[0], t1 = domainArr[1];
<add> t0 = domainArr[0];
<add> t1 = domainArr[1];
<ide> }
<ide>
<ide> var extendStart = false, extendEnd = false;
<ide> if (dict.has('Extend')) {
<ide> var extendArr = dict.get('Extend');
<del> extendStart = extendArr[0], extendEnd = extendArr[1];
<add> extendStart = extendArr[0];
<add> extendEnd = extendArr[1];
<ide> TODO('Support extend');
<ide> }
<ide>
<ide> var RadialAxialShading = (function() {
<ide> }
<ide>
<ide> this.colorStops = colorStops;
<del> };
<add> }
<ide>
<ide> constructor.prototype = {
<ide> getPattern: function() {
<ide> var TilingPattern = (function() {
<ide> var e = m[4] * tm[0] + m[5] * tm[2] + tm[4];
<ide> var f = m[4] * tm[1] + m[5] * tm[3] + tm[5];
<ide> return [a, b, c, d, e, f];
<del> };
<add> }
<ide>
<ide> TODO('TilingType');
<ide>
<ide> var TilingPattern = (function() {
<ide> graphics.execute(code, xref, res);
<ide>
<ide> this.canvas = tmpCanvas;
<del> };
<add> }
<ide>
<ide> constructor.prototype = {
<ide> getPattern: function tiling_getPattern() {
<ide> var PDFImage = (function() {
<ide> } else if (smask) {
<ide> this.smask = new PDFImage(xref, res, smask);
<ide> }
<del> };
<add> }
<ide>
<ide> constructor.prototype = {
<ide> getComponents: function getComponents(buffer, decodeMap) {
<ide> var PDFFunction = (function() {
<ide> error('Unknown type of function');
<ide>
<ide> typeFn.call(this, fn, dict, xref);
<del> };
<add> }
<ide>
<ide> constructor.prototype = {
<ide> constructSampled: function(str, dict) {
<ide> var PDFFunction = (function() {
<ide> else if (v < min)
<ide> v = min;
<ide> return v;
<del> }
<add> };
<ide>
<ide> if (inputSize != args.length)
<ide> error('Incorrect number of arguments: ' + inputSize + ' != ' +
<ide> var PDFFunction = (function() {
<ide> }
<ide>
<ide> return output;
<del> }
<add> };
<ide> },
<ide> getSampleArray: function(size, outputSize, bps, str) {
<ide> var length = 1;
<ide> var PDFFunction = (function() {
<ide> out.push(c0[j] + (x^n * diff[i]));
<ide>
<ide> return out;
<del> }
<add> };
<ide> },
<ide> constructStiched: function(fn, dict, xref) {
<ide> var domain = dict.get('Domain');
<ide> var PDFFunction = (function() {
<ide> else if (v < min)
<ide> v = min;
<ide> return v;
<del> }
<add> };
<ide>
<ide> // clip to domain
<ide> var v = clip(args[0], domain[0], domain[1]);
<ide> var PDFFunction = (function() {
<ide>
<ide> // call the appropropriate function
<ide> return fns[i].func([v2]);
<del> }
<add> };
<ide> },
<ide> constructPostScript: function() {
<ide> TODO('unhandled type of function');
<del> this.func = function() { return [255, 105, 180]; }
<add> this.func = function() {
<add> return [255, 105, 180];
<add> };
<ide> }
<ide> };
<ide> | 1 |
Ruby | Ruby | test new head methods | 454003c4c1ea43f4fd84db96017636fc4c50b318 | <ide><path>Library/Homebrew/test/test_formula.rb
<ide> def test_installed_prefix_devel
<ide> assert_equal prefix, f.installed_prefix
<ide> end
<ide>
<add> def test_latest_head_prefix
<add> f = Testball.new
<add>
<add> stamps_with_revisions = [[111111, 1], [222222, 1], [222222, 2], [222222, 0]]
<add>
<add> stamps_with_revisions.each do |stamp, revision|
<add> version = "HEAD-#{stamp}"
<add> version += "_#{revision}" if revision > 0
<add> prefix = f.rack.join(version)
<add> prefix.mkpath
<add>
<add> tab = Tab.empty
<add> tab.tabfile = prefix.join("INSTALL_RECEIPT.json")
<add> tab.source_modified_time = stamp
<add> tab.write
<add> end
<add>
<add> prefix = HOMEBREW_CELLAR/"#{f.name}/HEAD-222222_2"
<add> assert_equal prefix, f.latest_head_prefix
<add> ensure
<add> f.rack.rmtree
<add> end
<add>
<ide> def test_equality
<ide> x = Testball.new
<ide> y = Testball.new
<ide> def test_head_uses_revisions
<ide> assert_equal PkgVersion.parse("HEAD_1"), f.pkg_version
<ide> end
<ide>
<add> def test_update_head_version
<add> initial_env = ENV.to_hash
<add>
<add> f = formula do
<add> head "foo", :using => :git
<add> end
<add>
<add> cached_location = f.head.downloader.cached_location
<add> cached_location.mkpath
<add>
<add> %w[AUTHOR COMMITTER].each do |role|
<add> ENV["GIT_#{role}_NAME"] = "brew tests"
<add> ENV["GIT_#{role}_EMAIL"] = "brew-tests@localhost"
<add> ENV["GIT_#{role}_DATE"] = "Thu May 21 00:04:11 2009 +0100"
<add> end
<add>
<add> cached_location.cd do
<add> FileUtils.touch "LICENSE"
<add> shutup do
<add> system "git", "init"
<add> system "git", "add", "--all"
<add> system "git", "commit", "-m", "Initial commit"
<add> end
<add> end
<add>
<add> f.update_head_version
<add> assert_equal Version.create("HEAD-5658946"), f.head.version
<add> ensure
<add> ENV.replace(initial_env)
<add> cached_location.rmtree
<add> end
<add>
<ide> def test_legacy_options
<ide> f = formula do
<ide> url "foo-1.0" | 1 |
Ruby | Ruby | update old link in pessimistic.rb comments | 6901a272074aaa75fb69b8f2c7cb80ebf7ae00e7 | <ide><path>activerecord/lib/active_record/locking/pessimistic.rb
<ide> module Locking
<ide> # end
<ide> #
<ide> # Database-specific information on row locking:
<del> # MySQL: http://dev.mysql.com/doc/refman/5.1/en/innodb-locking-reads.html
<add> # MySQL: http://dev.mysql.com/doc/refman/5.6/en/innodb-locking-reads.html
<ide> # PostgreSQL: http://www.postgresql.org/docs/current/interactive/sql-select.html#SQL-FOR-UPDATE-SHARE
<ide> module Pessimistic
<ide> # Obtain a row lock on this record. Reloads the record to obtain the requested | 1 |
Java | Java | polish synchandlermethodargumentresolver hiearchy | f490f3ca63a56a6e31a271b513f89f2926b491fa | <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/method/HandlerMethodArgumentResolver.java
<ide> import org.springframework.web.server.ServerWebExchange;
<ide>
<ide> /**
<del> * Strategy interface for resolving method parameters into argument values in
<del> * the context of a given request.
<add> * Strategy to resolve the argument value for a method parameter in the context
<add> * of the current HTTP request.
<ide> *
<ide> * @author Rossen Stoyanchev
<ide> * @since 5.0
<ide> */
<ide> public interface HandlerMethodArgumentResolver {
<ide>
<add> /**
<add> * Whether this resolver supports the given method parameter.
<add> * @param parameter the method parameter
<add> */
<ide> boolean supportsParameter(MethodParameter parameter);
<ide>
<ide> /**
<del> * The returned {@link Mono} may produce one or zero values if the argument
<del> * does not resolve to any value, which will result in {@code null} passed
<del> * as the argument value.
<add> * Resolve the value for the method parameter.
<ide> * @param parameter the method parameter
<ide> * @param bindingContext the binding context to use
<ide> * @param exchange the current exchange
<add> * @return {@code Mono} for the argument value, possibly empty
<ide> */
<ide> Mono<Object> resolveArgument(MethodParameter parameter, BindingContext bindingContext,
<ide> ServerWebExchange exchange);
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/method/InvocableHandlerMethod.java
<ide> import reactor.core.publisher.Mono;
<ide>
<ide> import org.springframework.core.DefaultParameterNameDiscoverer;
<del>import org.springframework.core.GenericTypeResolver;
<ide> import org.springframework.core.MethodParameter;
<ide> import org.springframework.core.ParameterNameDiscoverer;
<ide> import org.springframework.core.annotation.AnnotatedElementUtils;
<ide> public void setArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers)
<ide> this.resolvers.addAll(resolvers);
<ide> }
<ide>
<add> /**
<add> * Return the conifgured argument resolvers.
<add> */
<add> public List<HandlerMethodArgumentResolver> getResolvers() {
<add> return this.resolvers;
<add> }
<add>
<ide> /**
<ide> * Set the ParameterNameDiscoverer for resolving parameter names when needed
<ide> * (e.g. default request attribute name).
<ide> public void setParameterNameDiscoverer(ParameterNameDiscoverer nameDiscoverer) {
<ide> this.parameterNameDiscoverer = nameDiscoverer;
<ide> }
<ide>
<add> /**
<add> * Return the configured parameter name discoverer.
<add> */
<add> public ParameterNameDiscoverer getParameterNameDiscoverer() {
<add> return this.parameterNameDiscoverer;
<add> }
<add>
<ide>
<ide> /**
<ide> * Invoke the method for the given exchange.
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/method/SyncHandlerMethodArgumentResolver.java
<ide> */
<ide> public interface SyncHandlerMethodArgumentResolver extends HandlerMethodArgumentResolver {
<ide>
<add>
<add> /**
<add> * {@inheritDoc}
<add> * <p>By default this simply delegates to {@link #resolveArgumentValue} for
<add> * synchronous resolution.
<add> */
<ide> @Override
<del> default Mono<Object> resolveArgument(MethodParameter parameter, BindingContext context,
<add> default Mono<Object> resolveArgument(MethodParameter parameter, BindingContext bindingContext,
<ide> ServerWebExchange exchange) {
<ide>
<del> Optional<Object> value = resolveArgumentValue(parameter, context, exchange);
<del> return Mono.justOrEmpty(value);
<add> return Mono.justOrEmpty(resolveArgumentValue(parameter, bindingContext, exchange));
<ide> }
<ide>
<ide> /**
<del> * Resolve the method argument value synchronously returning an optional value.
<add> * Resolve the value for the method parameter synchronously.
<ide> * @param parameter the method parameter
<ide> * @param bindingContext the binding context to use
<ide> * @param exchange the current exchange
<del> * @return the resolved value if any
<add> * @return an {@code Optional} with the resolved value, possibly empty
<ide> */
<ide> Optional<Object> resolveArgumentValue(MethodParameter parameter, BindingContext bindingContext,
<ide> ServerWebExchange exchange);
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/method/SyncInvocableHandlerMethod.java
<ide> import org.springframework.web.server.ServerWebExchange;
<ide>
<ide> /**
<del> * An extension of {@code InvocableHandlerMethod} for synchronous, non-blocking
<del> * method invocation via {@link #invokeForHandlerResult}. By allowing only
<del> * {@link SyncHandlerMethodArgumentResolver}s to be configured, the invocation
<del> * is guaranteed to be non-blocking.
<add> * Extension of {@code InvocableHandlerMethod} that can only be configured with
<add> * synchronous argument resolvers and thus exposing an additional, synchronous
<add> * {@link #invokeForHandlerResult} returning a {@code HandlerResult} vs
<add> * {@code Mono<HandlerResult>}.
<ide> *
<ide> * @author Rossen Stoyanchev
<ide> * @since 5.0
<ide> */
<ide> public class SyncInvocableHandlerMethod extends InvocableHandlerMethod {
<ide>
<add>
<ide> public SyncInvocableHandlerMethod(HandlerMethod handlerMethod) {
<ide> super(handlerMethod);
<ide> }
<ide> public SyncInvocableHandlerMethod(Object bean, Method method) {
<ide> */
<ide> @Override
<ide> public void setArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
<del> resolvers.forEach(resolver ->
<del> Assert.isInstanceOf(SyncHandlerMethodArgumentResolver.class, resolver,
<del> "SyncHandlerMethodArgumentResolver requires SyncHandlerMethodArgumentResolver"));
<add> resolvers.forEach(this::assertSyncResolvers);
<ide> super.setArgumentResolvers(resolvers);
<ide> }
<ide>
<add> private void assertSyncResolvers(HandlerMethodArgumentResolver resolver) {
<add> Assert.isInstanceOf(SyncHandlerMethodArgumentResolver.class, resolver,
<add> "SyncInvocableHandlerMethod requires resolvers of type " +
<add> "SyncHandlerMethodArgumentResolver");
<add> }
<add>
<ide> /**
<ide> * Convenient alternative to {@link #setArgumentResolvers(List)} to configure
<ide> * synchronous argument resolvers.
<ide> public void setSyncArgumentResolvers(List<SyncHandlerMethodArgumentResolver> res
<ide> public HandlerResult invokeForHandlerResult(ServerWebExchange exchange,
<ide> BindingContext bindingContext, Object... providedArgs) {
<ide>
<del> // This will not block
<add> // This will not block with only sync resolvers allowed
<ide> return super.invoke(exchange, bindingContext, providedArgs).block();
<ide> }
<ide>
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/method/annotation/AbstractNamedValueArgumentResolver.java
<ide> private Object resolveStringValue(String value) {
<ide> protected abstract Mono<Object> resolveName(String name, MethodParameter parameter,
<ide> ServerWebExchange exchange);
<ide>
<add> /**
<add> * Apply type conversion if necessary.
<add> */
<ide> private Object applyConversion(Object value, NamedValueInfo namedValueInfo, MethodParameter parameter,
<ide> BindingContext bindingContext, ServerWebExchange exchange) {
<ide>
<ide> private Object applyConversion(Object value, NamedValueInfo namedValueInfo, Meth
<ide> return value;
<ide> }
<ide>
<add> /**
<add> * Resolve the default value, if any.
<add> */
<ide> private Mono<Object> getDefaultValue(NamedValueInfo namedValueInfo, MethodParameter parameter,
<ide> BindingContext bindingContext, Model model, ServerWebExchange exchange) {
<ide>
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/method/annotation/AbstractNamedValueSyncArgumentResolver.java
<ide> public abstract class AbstractNamedValueSyncArgumentResolver extends AbstractNamedValueArgumentResolver
<ide> implements SyncHandlerMethodArgumentResolver {
<ide>
<del> public AbstractNamedValueSyncArgumentResolver(ConfigurableBeanFactory beanFactory) {
<add>
<add> protected AbstractNamedValueSyncArgumentResolver(ConfigurableBeanFactory beanFactory) {
<ide> super(beanFactory);
<ide> }
<ide>
<ide>
<add> @Override
<add> public Mono<Object> resolveArgument(MethodParameter parameter, BindingContext bindingContext,
<add> ServerWebExchange exchange) {
<add>
<add> // Flip the default implementation from SyncHandlerMethodArgumentResolver:
<add> // instead of delegating to (sync) resolveArgumentValue,
<add> // call (async) super.resolveArgument shared with non-blocking resolvers;
<add> // actual resolution below still sync...
<add>
<add> return super.resolveArgument(parameter, bindingContext, exchange);
<add> }
<add>
<ide> @Override
<ide> public Optional<Object> resolveArgumentValue(MethodParameter parameter,
<del> BindingContext bindingContext, ServerWebExchange exchange) {
<add> BindingContext context, ServerWebExchange exchange) {
<add>
<add> // This won't block since resolveName below doesn't
<add> Object value = resolveArgument(parameter, context, exchange).block();
<ide>
<del> // This will not block
<del> Object value = resolveArgument(parameter, bindingContext, exchange).block();
<ide> return Optional.ofNullable(value);
<ide> }
<ide>
<ide> @Override
<del> protected Mono<Object> resolveName(String name, MethodParameter parameter, ServerWebExchange exchange) {
<del> return Mono.justOrEmpty(resolveNamedValue(name, parameter, exchange));
<add> protected final Mono<Object> resolveName(String name, MethodParameter param,
<add> ServerWebExchange exchange) {
<add>
<add> return Mono.justOrEmpty(resolveNamedValue(name, param, exchange));
<ide> }
<ide>
<ide> /**
<del> * An abstract method for synchronous resolution of method argument values
<del> * that sub-classes must implement.
<del> * @param name the name of the value being resolved
<del> * @param parameter the method parameter to resolve to an argument value
<del> * (pre-nested in case of a {@link java.util.Optional} declaration)
<del> * @param exchange the current exchange
<del> * @return the resolved argument value, if any
<add> * Actually resolve the value synchronously.
<ide> */
<del> protected abstract Optional<Object> resolveNamedValue(String name, MethodParameter parameter,
<del> ServerWebExchange exchange);
<add> protected abstract Optional<Object> resolveNamedValue(String name,
<add> MethodParameter param, ServerWebExchange exchange);
<ide>
<ide> }
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/method/annotation/InitBinderBindingContext.java
<ide> import org.springframework.web.server.ServerWebExchange;
<ide>
<ide> /**
<del> * Variant of {@link BindingContext} that further initializes {@code DataBinder}
<del> * instances through {@code @InitBinder} methods.
<add> * Extends {@link BindingContext} with {@code @InitBinder} method initialization.
<ide> *
<ide> * @author Rossen Stoyanchev
<ide> * @since 5.0
<ide> class InitBinderBindingContext extends BindingContext {
<ide> private final BindingContext binderMethodContext;
<ide>
<ide>
<del> public InitBinderBindingContext(WebBindingInitializer initializer,
<add> InitBinderBindingContext(WebBindingInitializer initializer,
<ide> List<SyncInvocableHandlerMethod> binderMethods) {
<ide>
<ide> super(initializer);
<ide> public InitBinderBindingContext(WebBindingInitializer initializer,
<ide>
<ide>
<ide> @Override
<del> protected WebExchangeDataBinder initDataBinder(WebExchangeDataBinder binder, ServerWebExchange exchange) {
<add> protected WebExchangeDataBinder initDataBinder(WebExchangeDataBinder dataBinder,
<add> ServerWebExchange exchange) {
<ide>
<ide> this.binderMethods.stream()
<ide> .filter(binderMethod -> {
<ide> InitBinder annotation = binderMethod.getMethodAnnotation(InitBinder.class);
<ide> Collection<String> names = Arrays.asList(annotation.value());
<del> return (names.size() == 0 || names.contains(binder.getObjectName()));
<add> return (names.size() == 0 || names.contains(dataBinder.getObjectName()));
<ide> })
<del> .forEach(method -> invokeBinderMethod(binder, exchange, method));
<add> .forEach(method -> invokeBinderMethod(dataBinder, exchange, method));
<ide>
<del> return binder;
<add> return dataBinder;
<ide> }
<ide>
<del> private void invokeBinderMethod(WebExchangeDataBinder binder, ServerWebExchange exchange,
<del> SyncInvocableHandlerMethod binderMethod) {
<add> private void invokeBinderMethod(WebExchangeDataBinder dataBinder,
<add> ServerWebExchange exchange, SyncInvocableHandlerMethod binderMethod) {
<ide>
<ide> Optional<Object> returnValue = binderMethod
<del> .invokeForHandlerResult(exchange, this.binderMethodContext, binder)
<add> .invokeForHandlerResult(exchange, this.binderMethodContext, dataBinder)
<ide> .getReturnValue();
<ide>
<ide> if (returnValue.isPresent()) {
<ide> throw new IllegalStateException(
<ide> "@InitBinder methods should return void: " + binderMethod);
<ide> }
<ide>
<del> // Should not happen (no argument resolvers)...
<add> // Should not happen (no Model argument resolution) ...
<ide>
<ide> if (!this.binderMethodContext.getModel().asMap().isEmpty()) {
<ide> throw new IllegalStateException(
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/method/annotation/ModelArgumentResolver.java
<ide> */
<ide> public class ModelArgumentResolver implements SyncHandlerMethodArgumentResolver {
<ide>
<add>
<ide> @Override
<ide> public boolean supportsParameter(MethodParameter parameter) {
<ide> return Model.class.isAssignableFrom(parameter.getParameterType());
<ide> }
<ide>
<ide> @Override
<del> public Optional<Object> resolveArgumentValue(MethodParameter parameter, BindingContext bindingContext,
<del> ServerWebExchange exchange) {
<add> public Optional<Object> resolveArgumentValue(MethodParameter methodParameter,
<add> BindingContext context, ServerWebExchange exchange) {
<ide>
<del> return Optional.of(bindingContext.getModel());
<add> return Optional.of(context.getModel());
<ide> }
<ide>
<ide> }
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/method/annotation/PathVariableMapMethodArgumentResolver.java
<ide> */
<ide> public class PathVariableMapMethodArgumentResolver implements SyncHandlerMethodArgumentResolver {
<ide>
<add>
<ide> @Override
<ide> public boolean supportsParameter(MethodParameter parameter) {
<ide> PathVariable ann = parameter.getParameterAnnotation(PathVariable.class);
<ide> return (ann != null && (Map.class.isAssignableFrom(parameter.getParameterType()))
<ide> && !StringUtils.hasText(ann.value()));
<ide> }
<ide>
<del> /**
<del> * Return a Map with all URI template variables or an empty map.
<del> */
<ide> @Override
<del> public Optional<Object> resolveArgumentValue(MethodParameter parameter, BindingContext bindingContext,
<del> ServerWebExchange exchange) {
<add> public Optional<Object> resolveArgumentValue(MethodParameter methodParameter,
<add> BindingContext context, ServerWebExchange exchange) {
<ide>
<ide> String name = HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE;
<ide> Object value = exchange.getAttribute(name).orElse(Collections.emptyMap());
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/method/annotation/RequestHeaderMapMethodArgumentResolver.java
<ide> */
<ide> public class RequestHeaderMapMethodArgumentResolver implements SyncHandlerMethodArgumentResolver {
<ide>
<add>
<ide> @Override
<ide> public boolean supportsParameter(MethodParameter parameter) {
<ide> return (parameter.hasParameterAnnotation(RequestHeader.class) &&
<ide> Map.class.isAssignableFrom(parameter.getParameterType()));
<ide> }
<ide>
<ide> @Override
<del> public Optional<Object> resolveArgumentValue(MethodParameter parameter, BindingContext context,
<del> ServerWebExchange exchange) {
<add> public Optional<Object> resolveArgumentValue(MethodParameter methodParameter,
<add> BindingContext context, ServerWebExchange exchange) {
<ide>
<del> HttpHeaders headers = exchange.getRequest().getHeaders();
<del> Object value = (isMultiValueMap(parameter) ? headers : headers.toSingleValueMap());
<del> return Optional.of(value);
<del> }
<add> Class<?> paramType = methodParameter.getParameterType();
<add> boolean isMultiValueMap = MultiValueMap.class.isAssignableFrom(paramType);
<ide>
<del> private boolean isMultiValueMap(MethodParameter parameter) {
<del> Class<?> paramType = parameter.getParameterType();
<del> return MultiValueMap.class.isAssignableFrom(paramType);
<add> HttpHeaders headers = exchange.getRequest().getHeaders();
<add> return Optional.of(isMultiValueMap ? headers : headers.toSingleValueMap());
<ide> }
<ide>
<ide> }
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/method/annotation/RequestParamMapMethodArgumentResolver.java
<ide> */
<ide> public class RequestParamMapMethodArgumentResolver implements SyncHandlerMethodArgumentResolver {
<ide>
<add>
<ide> @Override
<del> public boolean supportsParameter(MethodParameter parameter) {
<del> RequestParam requestParam = parameter.getParameterAnnotation(RequestParam.class);
<add> public boolean supportsParameter(MethodParameter methodParam) {
<add> RequestParam requestParam = methodParam.getParameterAnnotation(RequestParam.class);
<ide> if (requestParam != null) {
<del> if (Map.class.isAssignableFrom(parameter.getParameterType())) {
<add> if (Map.class.isAssignableFrom(methodParam.getParameterType())) {
<ide> return !StringUtils.hasText(requestParam.name());
<ide> }
<ide> }
<ide> return false;
<ide> }
<ide>
<ide> @Override
<del> public Optional<Object> resolveArgumentValue(MethodParameter parameter, BindingContext context,
<del> ServerWebExchange exchange) {
<add> public Optional<Object> resolveArgumentValue(MethodParameter methodParameter,
<add> BindingContext context, ServerWebExchange exchange) {
<ide>
<del> MultiValueMap<String, String> requestParams = getRequestParams(exchange);
<del> Object value = (isMultiValueMap(parameter) ? requestParams : requestParams.toSingleValueMap());
<del> return Optional.of(value);
<del> }
<add> Class<?> paramType = methodParameter.getParameterType();
<add> boolean isMultiValueMap = MultiValueMap.class.isAssignableFrom(paramType);
<ide>
<del> private MultiValueMap<String, String> getRequestParams(ServerWebExchange exchange) {
<del> MultiValueMap<String, String> params = exchange.getRequestParams().subscribe().peek();
<del> Assert.notNull(params, "Expected form data (if any) to be parsed.");
<del> return params;
<del> }
<add> MultiValueMap<String, String> requestParams = exchange.getRequestParams().subscribe().peek();
<add> Assert.notNull(requestParams, "Expected form data (if any) to be parsed.");
<ide>
<del> private boolean isMultiValueMap(MethodParameter parameter) {
<del> Class<?> paramType = parameter.getParameterType();
<del> return MultiValueMap.class.isAssignableFrom(paramType);
<add> return Optional.of(isMultiValueMap ? requestParams : requestParams.toSingleValueMap());
<ide> }
<ide>
<ide> }
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/method/annotation/ServerWebExchangeArgumentResolver.java
<ide> */
<ide> public class ServerWebExchangeArgumentResolver implements SyncHandlerMethodArgumentResolver {
<ide>
<add>
<ide> @Override
<ide> public boolean supportsParameter(MethodParameter parameter) {
<ide> Class<?> paramType = parameter.getParameterType();
<ide> public boolean supportsParameter(MethodParameter parameter) {
<ide> }
<ide>
<ide> @Override
<del> public Optional<Object> resolveArgumentValue(MethodParameter parameter, BindingContext context,
<del> ServerWebExchange exchange) {
<add> public Optional<Object> resolveArgumentValue(MethodParameter methodParameter,
<add> BindingContext context, ServerWebExchange exchange) {
<ide>
<del> Class<?> paramType = parameter.getParameterType();
<add> Class<?> paramType = methodParameter.getParameterType();
<ide> if (ServerWebExchange.class.isAssignableFrom(paramType)) {
<ide> return Optional.of(exchange);
<ide> }
<ide> else if (HttpMethod.class == paramType) {
<ide> }
<ide> else {
<ide> // should never happen...
<del> throw new IllegalArgumentException(
<del> "Unknown parameter type: " + paramType + " in method: " + parameter.getMethod());
<add> throw new IllegalArgumentException("Unknown parameter type: " +
<add> paramType + " in method: " + methodParameter.getMethod());
<ide> }
<ide> }
<ide> | 12 |
Python | Python | add type annotations for clip (torch) | f86235ad1b6b73e0d497d3e163039a0f93111f88 | <ide><path>src/transformers/models/clip/modeling_clip.py
<ide>
<ide>
<ide> from dataclasses import dataclass
<del>from typing import Any, Optional, Tuple
<add>from typing import Any, Optional, Tuple, Union
<ide>
<ide> import torch
<ide> import torch.utils.checkpoint
<ide> def __init__(self, config: CLIPVisionConfig):
<ide> self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
<ide> self.register_buffer("position_ids", torch.arange(self.num_positions).expand((1, -1)))
<ide>
<del> def forward(self, pixel_values):
<add> def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
<ide> batch_size = pixel_values.shape[0]
<ide> patch_embeds = self.patch_embedding(pixel_values) # shape = [*, width, grid, grid]
<ide> patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
<ide> def __init__(self, config: CLIPTextConfig):
<ide> # position_ids (1, len position emb) is contiguous in memory and exported when serialized
<ide> self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)))
<ide>
<del> def forward(self, input_ids=None, position_ids=None, inputs_embeds=None):
<add> def forward(
<add> self,
<add> input_ids: Optional[torch.LongTensor] = None,
<add> position_ids: Optional[torch.LongTensor] = None,
<add> inputs_embeds: Optional[torch.FloatTensor] = None,
<add> ) -> torch.Tensor:
<ide> seq_length = input_ids.shape[-1] if input_ids is not None else inputs_embeds.shape[-2]
<ide>
<ide> if position_ids is None:
<ide> def forward(
<ide> hidden_states: torch.Tensor,
<ide> attention_mask: Optional[torch.Tensor] = None,
<ide> causal_attention_mask: Optional[torch.Tensor] = None,
<del> output_attentions: bool = False,
<add> output_attentions: Optional[bool] = False,
<ide> ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
<ide> """Input shape: Batch x Time x Channel"""
<ide>
<ide> def __init__(self, config):
<ide> self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
<ide> self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
<ide>
<del> def forward(self, hidden_states):
<add> def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
<ide> hidden_states = self.fc1(hidden_states)
<ide> hidden_states = self.activation_fn(hidden_states)
<ide> hidden_states = self.fc2(hidden_states)
<ide> def forward(
<ide> hidden_states: torch.Tensor,
<ide> attention_mask: torch.Tensor,
<ide> causal_attention_mask: torch.Tensor,
<del> output_attentions: bool = False,
<del> ):
<add> output_attentions: Optional[bool] = False,
<add> ) -> Tuple[torch.FloatTensor]:
<ide> """
<ide> Args:
<ide> hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
<ide> def __init__(self, config: CLIPConfig):
<ide> def forward(
<ide> self,
<ide> inputs_embeds,
<del> attention_mask=None,
<del> causal_attention_mask=None,
<del> output_attentions=None,
<del> output_hidden_states=None,
<del> return_dict=None,
<del> ):
<add> attention_mask: Optional[torch.Tensor] = None,
<add> causal_attention_mask: Optional[torch.Tensor] = None,
<add> output_attentions: Optional[bool] = None,
<add> output_hidden_states: Optional[bool] = None,
<add> return_dict: Optional[bool] = None,
<add> ) -> Union[Tuple, BaseModelOutput]:
<ide> r"""
<ide> Args:
<ide> inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
<ide> def __init__(self, config: CLIPTextConfig):
<ide> @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=CLIPTextConfig)
<ide> def forward(
<ide> self,
<del> input_ids=None,
<del> attention_mask=None,
<del> position_ids=None,
<del> output_attentions=None,
<del> output_hidden_states=None,
<del> return_dict=None,
<del> ):
<add> input_ids: Optional[torch.Tensor] = None,
<add> attention_mask: Optional[torch.Tensor] = None,
<add> position_ids: Optional[torch.Tensor] = None,
<add> output_attentions: Optional[bool] = None,
<add> output_hidden_states: Optional[bool] = None,
<add> return_dict: Optional[bool] = None,
<add> ) -> Union[Tuple, BaseModelOutputWithPooling]:
<ide> r"""
<ide> Returns:
<ide>
<ide> def set_input_embeddings(self, value):
<ide> @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=CLIPTextConfig)
<ide> def forward(
<ide> self,
<del> input_ids=None,
<del> attention_mask=None,
<del> position_ids=None,
<del> output_attentions=None,
<del> output_hidden_states=None,
<del> return_dict=None,
<del> ):
<add> input_ids: Optional[torch.Tensor] = None,
<add> attention_mask: Optional[torch.Tensor] = None,
<add> position_ids: Optional[torch.Tensor] = None,
<add> output_attentions: Optional[bool] = None,
<add> output_hidden_states: Optional[bool] = None,
<add> return_dict: Optional[bool] = None,
<add> ) -> Union[Tuple, BaseModelOutputWithPooling]:
<ide> r"""
<ide> Returns:
<ide>
<ide> def __init__(self, config: CLIPVisionConfig):
<ide> @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=CLIPVisionConfig)
<ide> def forward(
<ide> self,
<del> pixel_values=None,
<del> output_attentions=None,
<del> output_hidden_states=None,
<del> return_dict=None,
<del> ):
<add> pixel_values: Optional[torch.FloatTensor] = None,
<add> output_attentions: Optional[bool] = None,
<add> output_hidden_states: Optional[bool] = None,
<add> return_dict: Optional[bool] = None,
<add> ) -> Union[Tuple, BaseModelOutputWithPooling]:
<ide> r"""
<ide> Returns:
<ide>
<ide> def get_input_embeddings(self) -> nn.Module:
<ide> @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=CLIPVisionConfig)
<ide> def forward(
<ide> self,
<del> pixel_values=None,
<del> output_attentions=None,
<del> output_hidden_states=None,
<del> return_dict=None,
<del> ):
<add> pixel_values: Optional[torch.FloatTensor] = None,
<add> output_attentions: Optional[bool] = None,
<add> output_hidden_states: Optional[bool] = None,
<add> return_dict: Optional[bool] = None,
<add> ) -> Union[Tuple, BaseModelOutputWithPooling]:
<ide> r"""
<ide> Returns:
<ide>
<ide> def __init__(self, config: CLIPConfig):
<ide> @add_start_docstrings_to_model_forward(CLIP_TEXT_INPUTS_DOCSTRING)
<ide> def get_text_features(
<ide> self,
<del> input_ids=None,
<del> attention_mask=None,
<del> position_ids=None,
<del> output_attentions=None,
<del> output_hidden_states=None,
<del> return_dict=None,
<del> ):
<add> input_ids: Optional[torch.Tensor] = None,
<add> attention_mask: Optional[torch.Tensor] = None,
<add> position_ids: Optional[torch.Tensor] = None,
<add> output_attentions: Optional[bool] = None,
<add> output_hidden_states: Optional[bool] = None,
<add> return_dict: Optional[bool] = None,
<add> ) -> torch.FloatTensor:
<ide> r"""
<ide> Returns:
<ide> text_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The text embeddings obtained by
<ide> def get_text_features(
<ide> @add_start_docstrings_to_model_forward(CLIP_VISION_INPUTS_DOCSTRING)
<ide> def get_image_features(
<ide> self,
<del> pixel_values=None,
<del> output_attentions=None,
<del> output_hidden_states=None,
<del> return_dict=None,
<del> ):
<add> pixel_values: Optional[torch.FloatTensor] = None,
<add> output_attentions: Optional[bool] = None,
<add> output_hidden_states: Optional[bool] = None,
<add> return_dict: Optional[bool] = None,
<add> ) -> torch.FloatTensor:
<ide> r"""
<ide> Returns:
<ide> image_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The image embeddings obtained by
<ide> def get_image_features(
<ide> @replace_return_docstrings(output_type=CLIPOutput, config_class=CLIPConfig)
<ide> def forward(
<ide> self,
<del> input_ids=None,
<del> pixel_values=None,
<del> attention_mask=None,
<del> position_ids=None,
<del> return_loss=None,
<del> output_attentions=None,
<del> output_hidden_states=None,
<del> return_dict=None,
<del> ):
<add> input_ids: Optional[torch.LongTensor] = None,
<add> pixel_values: Optional[torch.FloatTensor] = None,
<add> attention_mask: Optional[torch.Tensor] = None,
<add> position_ids: Optional[torch.LongTensor] = None,
<add> return_loss: Optional[bool] = None,
<add> output_attentions: Optional[bool] = None,
<add> output_hidden_states: Optional[bool] = None,
<add> return_dict: Optional[bool] = None,
<add> ) -> Union[Tuple, CLIPOutput]:
<ide> r"""
<ide> Returns:
<ide> | 1 |
Python | Python | add examples per second history to estimator hook. | dc42c4822044aa87365e0b46ca25d14e0f18adfb | <ide><path>official/resnet/estimator_cifar_benchmark.py
<ide> import tensorflow as tf # pylint: disable=g-bad-import-order
<ide>
<ide> from official.resnet import cifar10_main as cifar_main
<add>from official.utils.logs import hooks
<ide>
<ide> DATA_DIR = '/data/cifar10_data/cifar-10-batches-bin'
<ide>
<ide> def resnet56_1_gpu(self):
<ide> flags.FLAGS.model_dir = self._get_model_dir('resnet56_1_gpu')
<ide> flags.FLAGS.resnet_size = 56
<ide> flags.FLAGS.dtype = 'fp32'
<add> flags.FLAGS.hooks = ['ExamplesPerSecondHook']
<ide> self._run_and_report_benchmark()
<ide>
<ide> def resnet56_fp16_1_gpu(self):
<ide> def resnet56_fp16_1_gpu(self):
<ide> flags.FLAGS.model_dir = self._get_model_dir('resnet56_fp16_1_gpu')
<ide> flags.FLAGS.resnet_size = 56
<ide> flags.FLAGS.dtype = 'fp16'
<add> flags.FLAGS.hooks = ['ExamplesPerSecondHook']
<ide> self._run_and_report_benchmark()
<ide>
<ide> def resnet56_2_gpu(self):
<ide> def resnet56_2_gpu(self):
<ide> flags.FLAGS.model_dir = self._get_model_dir('resnet56_2_gpu')
<ide> flags.FLAGS.resnet_size = 56
<ide> flags.FLAGS.dtype = 'fp32'
<add> flags.FLAGS.hooks = ['ExamplesPerSecondHook']
<ide> self._run_and_report_benchmark()
<ide>
<ide> def resnet56_fp16_2_gpu(self):
<ide> def resnet56_fp16_2_gpu(self):
<ide> flags.FLAGS.model_dir = self._get_model_dir('resnet56_fp16_2_gpu')
<ide> flags.FLAGS.resnet_size = 56
<ide> flags.FLAGS.dtype = 'fp16'
<add> flags.FLAGS.hooks = ['ExamplesPerSecondHook']
<ide> self._run_and_report_benchmark()
<ide>
<ide> def unit_test(self):
<ide> def unit_test(self):
<ide> flags.FLAGS.model_dir = self._get_model_dir('resnet56_1_gpu')
<ide> flags.FLAGS.resnet_size = 8
<ide> flags.FLAGS.dtype = 'fp32'
<add> flags.FLAGS.hooks = ['ExamplesPerSecondHook']
<ide> self._run_and_report_benchmark()
<ide>
<ide> def _run_and_report_benchmark(self):
<ide> start_time_sec = time.time()
<ide> stats = cifar_main.run_cifar(flags.FLAGS)
<ide> wall_time_sec = time.time() - start_time_sec
<ide>
<add> examples_per_sec_hook = None
<add> for hook in stats['train_hooks']:
<add> if isinstance(hook, hooks.ExamplesPerSecondHook):
<add> examples_per_sec_hook = hook
<add> break
<add>
<add> eval_results = stats['eval_results']
<add> extras = {}
<add> extras['accuracy_top_1'] = self._json_description(
<add> eval_results['accuracy'].item(),
<add> priority=0)
<add> extras['accuracy_top_5'] = self._json_description(
<add> eval_results['accuracy_top_5'].item())
<add> if examples_per_sec_hook:
<add> exp_per_second_list = examples_per_sec_hook.current_examples_per_sec_list
<add> # ExamplesPerSecondHook skips the first 10 steps.
<add> exp_per_sec = sum(exp_per_second_list) / (len(exp_per_second_list))
<add> extras['exp_per_second'] = self._json_description(exp_per_sec)
<add>
<ide> self.report_benchmark(
<del> iters=stats['global_step'],
<add> iters=eval_results['global_step'],
<ide> wall_time=wall_time_sec,
<del> extras={
<del> 'accuracy_top_1':
<del> self._json_description(stats['accuracy'].item(), priority=0),
<del> 'accuracy_top_5':
<del> self._json_description(stats['accuracy_top_5'].item()),
<del> })
<add> extras=extras)
<ide>
<ide> def _json_description(self,
<ide> value,
<ide><path>official/resnet/resnet_run_loop.py
<ide> def input_fn_eval():
<ide> shape, batch_size=flags_obj.batch_size, dtype=export_dtype)
<ide> classifier.export_savedmodel(flags_obj.export_dir, input_receiver_fn,
<ide> strip_default_attrs=True)
<del> return eval_results
<add>
<add> stats = {}
<add> stats['eval_results'] = eval_results
<add> stats['train_hooks'] = train_hooks
<add>
<add> return stats
<add>
<ide>
<ide> def define_resnet_flags(resnet_size_choices=None):
<ide> """Add flags and validators for ResNet."""
<ide><path>official/utils/logs/hooks.py
<ide> def __init__(self,
<ide> self._total_steps = 0
<ide> self._batch_size = batch_size
<ide> self._warm_steps = warm_steps
<add> # List of examples per second logged every_n_steps.
<add> self.current_examples_per_sec_list = []
<ide>
<ide> def begin(self):
<ide> """Called once before using the session to check global step."""
<ide> def after_run(self, run_context, run_values): # pylint: disable=unused-argument
<ide> # and training time per batch
<ide> current_examples_per_sec = self._batch_size * (
<ide> elapsed_steps / elapsed_time)
<del>
<add> # Logs entries to be read from hook during or after run.
<add> self.current_examples_per_sec_list.append(current_examples_per_sec)
<ide> self._logger.log_metric(
<ide> "average_examples_per_sec", average_examples_per_sec,
<ide> global_step=global_step) | 3 |
PHP | PHP | apply fixes from styleci | f6bdc032f79e3fc3dcc517b245935aa6cd77642a | <ide><path>src/Illuminate/Log/LogServiceProvider.php
<ide> protected function channel()
<ide> {
<ide> if ($this->app->bound('config') &&
<ide> $channel = $this->app->make('config')->get('app.log_channel')) {
<del> return $channel;
<add> return $channel;
<ide> }
<ide>
<ide> return $this->app->bound('env') ? $this->app->environment() : 'production'; | 1 |
Python | Python | fix broken nested fields | 405822330958c5432dde56b07a61b223c03ca4c7 | <ide><path>rest_framework/compat.py
<ide> import StringIO
<ide>
<ide>
<add># Try to import PIL in either of the two ways it can end up installed.
<add>try:
<add> from PIL import Image
<add>except ImportError:
<add> try:
<add> import Image
<add> except ImportError:
<add> Image = None
<add>
<add>
<ide> def get_concrete_model(model_cls):
<ide> try:
<ide> return model_cls._meta.concrete_model
<ide><path>rest_framework/fields.py
<ide> def from_native(self, data):
<ide> if f is None:
<ide> return None
<ide>
<del> # Try to import PIL in either of the two ways it can end up installed.
<del> try:
<del> from PIL import Image
<del> except ImportError:
<del> import Image
<add> from compat import Image
<add> assert Image is not None, 'PIL must be installed for ImageField support'
<ide>
<ide> # We need to get a file object for PIL. We might have a path or we might
<ide> # have to read the data into memory.
<ide><path>rest_framework/serializers.py
<ide> def perform_validation(self, attrs):
<ide> except ValidationError as err:
<ide> self._errors[field_name] = self._errors.get(field_name, []) + list(err.messages)
<ide>
<del> # We don't run .validate() because field-validation failed and thus `attrs` may not be complete.
<add> # If there are already errors, we don't run .validate() because
<add> # field-validation failed and thus `attrs` may not be complete.
<ide> # which in turn can cause inconsistent validation errors.
<ide> if not self._errors:
<ide> try:
<ide> def field_to_native(self, obj, field_name):
<ide> Override default so that we can apply ModelSerializer as a nested
<ide> field to relationships.
<ide> """
<del>
<ide> if self.source:
<del> value = obj
<ide> for component in self.source.split('.'):
<del> value = getattr(value, component)
<del> if is_simple_callable(value):
<del> value = value()
<del> obj = value
<add> obj = getattr(obj, component)
<add> if is_simple_callable(obj):
<add> obj = obj()
<ide> else:
<del> value = getattr(obj, field_name)
<del> if is_simple_callable(value):
<add> obj = getattr(obj, field_name)
<add> if is_simple_callable(obj):
<ide> obj = value()
<ide>
<ide> # If the object has an "all" method, assume it's a relationship
<ide> def get_field(self, model_field):
<ide> except KeyError:
<ide> return ModelField(model_field=model_field, **kwargs)
<ide>
<del> def validate(self, attrs):
<del> copied_attrs = copy.deepcopy(attrs)
<del> restored_object = self.restore_object(copied_attrs, instance=getattr(self, 'object', None))
<del> self.perform_model_validation(restored_object)
<del> return attrs
<del>
<del> def perform_model_validation(self, restored_object):
<del> # Call Django's full_clean() which in turn calls: Model.clean_fields(), Model.clean(), Model.validat_unique()
<del> restored_object.full_clean(exclude=list(self.get_excluded_fieldnames()))
<add> # def validate(self, attrs):
<add> # restored_object = self.restore_object(attrs, instance=getattr(self, 'object', None))
<add> # restored_object.full_clean(exclude=list(self.get_excluded_fieldnames()))
<add> # return attrs
<ide>
<ide> def restore_object(self, attrs, instance=None):
<ide> """
<ide> def restore_object(self, attrs, instance=None):
<ide> for field in self.opts.model._meta.many_to_many:
<ide> if field.name in attrs:
<ide> self.m2m_data[field.name] = attrs.pop(field.name)
<del> return self.opts.model(**attrs)
<add>
<add> instance = self.opts.model(**attrs)
<add> try:
<add> instance.full_clean(exclude=list(self.get_excluded_fieldnames()))
<add> except ValidationError, err:
<add> self._errors = err.message_dict
<add> return None
<add> return instance
<ide>
<ide> def save(self, save_m2m=True):
<ide> """
<ide><path>rest_framework/tests/serializer.py
<del>import datetime, pickle
<add>import datetime
<add>import pickle
<ide> from django.test import TestCase
<ide> from rest_framework import serializers
<ide> from rest_framework.tests.models import (Album, ActionItem, Anchor, BasicModel,
<ide> class Meta:
<ide> fields = ('name', 'age')
<ide> pickle.dumps(InnerPersonSerializer(Person(name="Noah", age=950)).data)
<ide>
<add>
<ide> class DepthTest(TestCase):
<del> def test_depth(self):
<del> user = Person.objects.create(name="django",age=1)
<del> post = BlogPost.objects.create(title="Test blog post", writer=user)
<add> def test_implicit_nesting(self):
<add> writer = Person.objects.create(name="django", age=1)
<add> post = BlogPost.objects.create(title="Test blog post", writer=writer)
<add>
<add> class BlogPostSerializer(serializers.ModelSerializer):
<add> class Meta:
<add> model = BlogPost
<add> depth = 1
<add>
<add> serializer = BlogPostSerializer(instance=post)
<add> expected = {'id': 1, 'title': u'Test blog post',
<add> 'writer': {'id': 1, 'name': u'django', 'age': 1}}
<add>
<add> self.assertEqual(serializer.data, expected)
<add>
<add> def test_explicit_nesting(self):
<add> writer = Person.objects.create(name="django", age=1)
<add> post = BlogPost.objects.create(title="Test blog post", writer=writer)
<ide>
<ide> class PersonSerializer(serializers.ModelSerializer):
<ide> class Meta:
<ide> model = Person
<del> fields = ("name", "age")
<ide>
<ide> class BlogPostSerializer(serializers.ModelSerializer):
<add> writer = PersonSerializer()
<add>
<ide> class Meta:
<ide> model = BlogPost
<del> depth = 1
<ide>
<ide> serializer = BlogPostSerializer(instance=post)
<ide> expected = {'id': 1, 'title': u'Test blog post',
<del> 'writer': {'id': 1, 'name': u'django', 'age':1}}
<add> 'writer': {'id': 1, 'name': u'django', 'age': 1}}
<ide>
<ide> self.assertEqual(serializer.data, expected) | 4 |
Javascript | Javascript | when material is undefined | a25321ceb62305ecfc7ded184ebee8739076bf70 | <ide><path>src/objects/Mesh.js
<ide> Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {
<ide> function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
<ide>
<ide> var intersect;
<del>
<add> if(!material) return null;
<ide> if ( material.side === BackSide ) {
<ide>
<ide> intersect = ray.intersectTriangle( pC, pB, pA, true, point ); | 1 |
Mixed | Ruby | fix fixture syntax in cable docs and guides | cfe65cb478a44f19f3b4562cd1cf3c99d2cb930b | <ide><path>actioncable/lib/action_cable/channel/test_case.rb
<ide> def transmit(cable_message)
<ide> # You need to set up your connection manually to provide values for the identifiers.
<ide> # To do this just use:
<ide> #
<del> # stub_connection(user: users[:john])
<add> # stub_connection(user: users(:john))
<ide> #
<ide> # == Testing broadcasting
<ide> #
<ide> def transmit(cable_message)
<ide> # end
<ide> #
<ide> # def test_speak
<del> # subscribe room_id: rooms[:chat].id
<add> # subscribe room_id: rooms(:chat).id
<ide> #
<del> # assert_broadcasts_on(rooms[:chat], text: "Hello, Rails!") do
<add> # assert_broadcasts_on(rooms(:chat), text: "Hello, Rails!") do
<ide> # perform :speak, message: "Hello, Rails!"
<ide> # end
<ide> # end
<ide><path>guides/source/testing.md
<ide> require "test_helper"
<ide>
<ide> class WebNotificationsChannelTest < ActionCable::Channel::TestCase
<ide> test "subscribes and stream for user" do
<del> stub_connection current_user: users[:john]
<add> stub_connection current_user: users(:john)
<ide>
<ide> subscribe
<ide>
<del> assert_has_stream_for users[:john]
<add> assert_has_stream_for users(:john)
<ide> end
<ide> end
<ide> ```
<ide> class ChatRelayJobTest < ActiveJob::TestCase
<ide> include ActionCable::TestHelper
<ide>
<ide> test "broadcast message to room" do
<del> room = rooms[:all]
<add> room = rooms(:all)
<ide>
<ide> assert_broadcast_on(ChatChannel.broadcasting_for(room), text: "Hi!") do
<ide> ChatRelayJob.perform_now(room, "Hi!") | 2 |
PHP | PHP | fix higher order messaging annotations | b14367393e59e1d7f1a91cb889a988d5b684c54a | <ide><path>src/Illuminate/Collections/Traits/EnumeratesValues.php
<ide> * @property-read HigherOrderCollectionProxy $some
<ide> * @property-read HigherOrderCollectionProxy $sortBy
<ide> * @property-read HigherOrderCollectionProxy $sortByDesc
<add> * @property-read HigherOrderCollectionProxy $skipUntil
<add> * @property-read HigherOrderCollectionProxy $skipWhile
<ide> * @property-read HigherOrderCollectionProxy $sum
<add> * @property-read HigherOrderCollectionProxy $takeUntil
<add> * @property-read HigherOrderCollectionProxy $takeWhile
<ide> * @property-read HigherOrderCollectionProxy $unique
<ide> * @property-read HigherOrderCollectionProxy $until
<ide> */ | 1 |
Java | Java | convert non-unicode input when reading w/ jackson | 9c3417f7037b407a17ae9832a81f8d0c55677bfc | <ide><path>spring-web/src/main/java/org/springframework/http/codec/json/AbstractJackson2Encoder.java
<ide> public abstract class AbstractJackson2Encoder extends Jackson2CodecSupport imple
<ide>
<ide> private static final Map<MediaType, byte[]> STREAM_SEPARATORS;
<ide>
<add> private static final Map<Charset, JsonEncoding> ENCODINGS;
<add>
<ide> static {
<ide> STREAM_SEPARATORS = new HashMap<>(4);
<ide> STREAM_SEPARATORS.put(MediaType.APPLICATION_STREAM_JSON, NEWLINE_SEPARATOR);
<ide> STREAM_SEPARATORS.put(MediaType.parseMediaType("application/stream+x-jackson-smile"), new byte[0]);
<add>
<add> ENCODINGS = new HashMap<>(JsonEncoding.values().length);
<add> for (JsonEncoding encoding : JsonEncoding.values()) {
<add> Charset charset = Charset.forName(encoding.getJavaName());
<add> ENCODINGS.put(charset, encoding);
<add> }
<ide> }
<ide>
<ide>
<ide> public void setStreamingMediaTypes(List<MediaType> mediaTypes) {
<ide> @Override
<ide> public boolean canEncode(ResolvableType elementType, @Nullable MimeType mimeType) {
<ide> Class<?> clazz = elementType.toClass();
<del> return supportsMimeType(mimeType) && (Object.class == clazz ||
<add> if (!supportsMimeType(mimeType)) {
<add> return false;
<add> }
<add> if (mimeType != null && mimeType.getCharset() != null) {
<add> Charset charset = mimeType.getCharset();
<add> if (!ENCODINGS.containsKey(charset)) {
<add> return false;
<add> }
<add> }
<add> return (Object.class == clazz ||
<ide> (!String.class.isAssignableFrom(elementType.resolve(clazz)) && getObjectMapper().canSerialize(clazz)));
<ide> }
<ide>
<ide> private byte[] streamSeparator(@Nullable MimeType mimeType) {
<ide> protected JsonEncoding getJsonEncoding(@Nullable MimeType mimeType) {
<ide> if (mimeType != null && mimeType.getCharset() != null) {
<ide> Charset charset = mimeType.getCharset();
<del> for (JsonEncoding encoding : JsonEncoding.values()) {
<del> if (charset.name().equals(encoding.getJavaName())) {
<del> return encoding;
<del> }
<add> JsonEncoding result = ENCODINGS.get(charset);
<add> if (result != null) {
<add> return result;
<ide> }
<ide> }
<ide> return JsonEncoding.UTF8;
<ide><path>spring-web/src/main/java/org/springframework/http/codec/json/Jackson2CodecSupport.java
<ide>
<ide> import java.lang.annotation.Annotation;
<ide> import java.lang.reflect.Type;
<del>import java.nio.charset.Charset;
<ide> import java.util.Arrays;
<ide> import java.util.Collections;
<del>import java.util.EnumSet;
<ide> import java.util.HashMap;
<ide> import java.util.List;
<ide> import java.util.Map;
<del>import java.util.function.Function;
<del>import java.util.stream.Collectors;
<ide>
<ide> import com.fasterxml.jackson.annotation.JsonView;
<del>import com.fasterxml.jackson.core.JsonEncoding;
<ide> import com.fasterxml.jackson.databind.JavaType;
<ide> import com.fasterxml.jackson.databind.ObjectMapper;
<ide> import com.fasterxml.jackson.databind.type.TypeFactory;
<ide> public abstract class Jackson2CodecSupport {
<ide> new MimeType("application", "json"),
<ide> new MimeType("application", "*+json")));
<ide>
<del> private static final Map<String, JsonEncoding> ENCODINGS = jsonEncodings();
<del>
<del>
<ide>
<ide> protected final Log logger = HttpLogging.forLogName(getClass());
<ide>
<ide> protected List<MimeType> getMimeTypes() {
<ide>
<ide>
<ide> protected boolean supportsMimeType(@Nullable MimeType mimeType) {
<del> if (mimeType == null) {
<del> return true;
<del> }
<del> else if (this.mimeTypes.stream().noneMatch(m -> m.isCompatibleWith(mimeType))) {
<del> return false;
<del> }
<del> else if (mimeType.getCharset() != null) {
<del> Charset charset = mimeType.getCharset();
<del> return ENCODINGS.containsKey(charset.name());
<del> }
<del> return true;
<add> return (mimeType == null || this.mimeTypes.stream().anyMatch(m -> m.isCompatibleWith(mimeType)));
<ide> }
<ide>
<ide> protected JavaType getJavaType(Type type, @Nullable Class<?> contextClass) {
<ide> protected MethodParameter getParameter(ResolvableType type) {
<ide> @Nullable
<ide> protected abstract <A extends Annotation> A getAnnotation(MethodParameter parameter, Class<A> annotType);
<ide>
<del> private static Map<String, JsonEncoding> jsonEncodings() {
<del> return EnumSet.allOf(JsonEncoding.class).stream()
<del> .collect(Collectors.toMap(JsonEncoding::getJavaName, Function.identity()));
<del> }
<del>
<del>
<ide> }
<ide><path>spring-web/src/main/java/org/springframework/http/converter/json/AbstractJackson2HttpMessageConverter.java
<ide> package org.springframework.http.converter.json;
<ide>
<ide> import java.io.IOException;
<add>import java.io.InputStreamReader;
<add>import java.io.Reader;
<ide> import java.lang.reflect.Type;
<ide> import java.nio.charset.Charset;
<add>import java.nio.charset.StandardCharsets;
<ide> import java.util.Arrays;
<ide> import java.util.Collections;
<ide> import java.util.EnumSet;
<ide> import com.fasterxml.jackson.databind.JavaType;
<ide> import com.fasterxml.jackson.databind.JsonMappingException;
<ide> import com.fasterxml.jackson.databind.ObjectMapper;
<add>import com.fasterxml.jackson.databind.ObjectReader;
<ide> import com.fasterxml.jackson.databind.ObjectWriter;
<ide> import com.fasterxml.jackson.databind.SerializationConfig;
<ide> import com.fasterxml.jackson.databind.SerializationFeature;
<ide> */
<ide> public abstract class AbstractJackson2HttpMessageConverter extends AbstractGenericHttpMessageConverter<Object> {
<ide>
<del> private static final Map<String, JsonEncoding> ENCODINGS = jsonEncodings();
<add> private static final Map<Charset, JsonEncoding> ENCODINGS = jsonEncodings();
<ide>
<ide> /**
<ide> * The default charset used by the converter.
<ide> public boolean canRead(Type type, @Nullable Class<?> contextClass, @Nullable Med
<ide> return false;
<ide> }
<ide>
<del> @Override
<del> protected boolean canRead(@Nullable MediaType mediaType) {
<del> if (!super.canRead(mediaType)) {
<del> return false;
<del> }
<del> return checkEncoding(mediaType);
<del> }
<del>
<ide> @Override
<ide> public boolean canWrite(Class<?> clazz, @Nullable MediaType mediaType) {
<ide> if (!canWrite(mediaType)) {
<ide> return false;
<ide> }
<add> if (mediaType != null && mediaType.getCharset() != null) {
<add> Charset charset = mediaType.getCharset();
<add> if (!ENCODINGS.containsKey(charset)) {
<add> return false;
<add> }
<add> }
<ide> AtomicReference<Throwable> causeRef = new AtomicReference<>();
<ide> if (this.objectMapper.canSerialize(clazz, causeRef)) {
<ide> return true;
<ide> public boolean canWrite(Class<?> clazz, @Nullable MediaType mediaType) {
<ide> return false;
<ide> }
<ide>
<del> @Override
<del> protected boolean canWrite(@Nullable MediaType mediaType) {
<del> if (!super.canWrite(mediaType)) {
<del> return false;
<del> }
<del> return checkEncoding(mediaType);
<del> }
<del>
<ide> /**
<ide> * Determine whether to log the given exception coming from a
<ide> * {@link ObjectMapper#canDeserialize} / {@link ObjectMapper#canSerialize} check.
<ide> else if (logger.isDebugEnabled()) {
<ide> }
<ide> }
<ide>
<del> private boolean checkEncoding(@Nullable MediaType mediaType) {
<del> if (mediaType != null && mediaType.getCharset() != null) {
<del> Charset charset = mediaType.getCharset();
<del> return ENCODINGS.containsKey(charset.name());
<del> }
<del> return true;
<del> }
<del>
<ide> @Override
<ide> protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage)
<ide> throws IOException, HttpMessageNotReadableException {
<ide> public Object read(Type type, @Nullable Class<?> contextClass, HttpInputMessage
<ide> }
<ide>
<ide> private Object readJavaType(JavaType javaType, HttpInputMessage inputMessage) throws IOException {
<add> MediaType contentType = inputMessage.getHeaders().getContentType();
<add> Charset charset = getCharset(contentType);
<add>
<add> boolean isUnicode = ENCODINGS.containsKey(charset);
<ide> try {
<ide> if (inputMessage instanceof MappingJacksonInputMessage) {
<ide> Class<?> deserializationView = ((MappingJacksonInputMessage) inputMessage).getDeserializationView();
<ide> if (deserializationView != null) {
<del> return this.objectMapper.readerWithView(deserializationView).forType(javaType).
<del> readValue(inputMessage.getBody());
<add> ObjectReader objectReader = this.objectMapper.readerWithView(deserializationView).forType(javaType);
<add> if (isUnicode) {
<add> return objectReader.readValue(inputMessage.getBody());
<add> }
<add> else {
<add> Reader reader = new InputStreamReader(inputMessage.getBody(), charset);
<add> return objectReader.readValue(reader);
<add> }
<ide> }
<ide> }
<del> return this.objectMapper.readValue(inputMessage.getBody(), javaType);
<add> if (isUnicode) {
<add> return this.objectMapper.readValue(inputMessage.getBody(), javaType);
<add> }
<add> else {
<add> Reader reader = new InputStreamReader(inputMessage.getBody(), charset);
<add> return this.objectMapper.readValue(reader, javaType);
<add> }
<ide> }
<ide> catch (InvalidDefinitionException ex) {
<ide> throw new HttpMessageConversionException("Type definition error: " + ex.getType(), ex);
<ide> private Object readJavaType(JavaType javaType, HttpInputMessage inputMessage) th
<ide> }
<ide> }
<ide>
<add> private static Charset getCharset(@Nullable MediaType contentType) {
<add> if (contentType != null && contentType.getCharset() != null) {
<add> return contentType.getCharset();
<add> }
<add> else {
<add> return StandardCharsets.UTF_8;
<add> }
<add> }
<add>
<ide> @Override
<ide> protected void writeInternal(Object object, @Nullable Type type, HttpOutputMessage outputMessage)
<ide> throws IOException, HttpMessageNotWritableException {
<ide> protected JavaType getJavaType(Type type, @Nullable Class<?> contextClass) {
<ide> protected JsonEncoding getJsonEncoding(@Nullable MediaType contentType) {
<ide> if (contentType != null && contentType.getCharset() != null) {
<ide> Charset charset = contentType.getCharset();
<del> JsonEncoding encoding = ENCODINGS.get(charset.name());
<add> JsonEncoding encoding = ENCODINGS.get(charset);
<ide> if (encoding != null) {
<ide> return encoding;
<ide> }
<ide> protected Long getContentLength(Object object, @Nullable MediaType contentType)
<ide> return super.getContentLength(object, contentType);
<ide> }
<ide>
<del> private static Map<String, JsonEncoding> jsonEncodings() {
<add> private static Map<Charset, JsonEncoding> jsonEncodings() {
<ide> return EnumSet.allOf(JsonEncoding.class).stream()
<del> .collect(Collectors.toMap(JsonEncoding::getJavaName, Function.identity()));
<add> .collect(Collectors.toMap(encoding -> Charset.forName(encoding.getJavaName()), Function.identity()));
<ide> }
<ide>
<ide> }
<ide><path>spring-web/src/test/java/org/springframework/http/codec/cbor/Jackson2CborDecoderTests.java
<ide>
<ide> package org.springframework.http.codec.cbor;
<ide>
<del>import java.nio.charset.StandardCharsets;
<ide> import java.util.Arrays;
<ide> import java.util.List;
<ide>
<ide> import org.springframework.core.ResolvableType;
<ide> import org.springframework.core.io.buffer.DataBuffer;
<ide> import org.springframework.core.testfixture.codec.AbstractDecoderTests;
<del>import org.springframework.http.MediaType;
<ide> import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
<ide> import org.springframework.util.MimeType;
<ide> import org.springframework.web.testfixture.xml.Pojo;
<ide> public void canDecode() {
<ide>
<ide> assertThat(decoder.canDecode(ResolvableType.forClass(String.class), null)).isFalse();
<ide> assertThat(decoder.canDecode(ResolvableType.forClass(Pojo.class), APPLICATION_JSON)).isFalse();
<del>
<del> assertThat(this.decoder.canDecode(ResolvableType.forClass(Pojo.class),
<del> new MediaType("application", "cbor", StandardCharsets.UTF_8))).isTrue();
<del> assertThat(this.decoder.canDecode(ResolvableType.forClass(Pojo.class),
<del> new MediaType("application", "cbor", StandardCharsets.ISO_8859_1))).isFalse();
<ide> }
<ide>
<ide> @Override
<ide><path>spring-web/src/test/java/org/springframework/http/codec/cbor/Jackson2CborEncoderTests.java
<ide>
<ide> import java.io.IOException;
<ide> import java.io.UncheckedIOException;
<del>import java.nio.charset.StandardCharsets;
<ide> import java.util.function.Consumer;
<ide>
<ide> import com.fasterxml.jackson.databind.ObjectMapper;
<ide> import org.springframework.core.io.buffer.DataBuffer;
<ide> import org.springframework.core.testfixture.io.buffer.AbstractLeakCheckingTests;
<ide> import org.springframework.core.testfixture.io.buffer.DataBufferTestUtils;
<del>import org.springframework.http.MediaType;
<ide> import org.springframework.http.codec.ServerSentEvent;
<ide> import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
<ide> import org.springframework.util.MimeType;
<ide> public void canEncode() {
<ide>
<ide> // SPR-15464
<ide> assertThat(this.encoder.canEncode(ResolvableType.NONE, null)).isTrue();
<del>
<del>
<del> assertThat(this.encoder.canEncode(ResolvableType.forClass(Pojo.class),
<del> new MediaType("application", "cbor", StandardCharsets.UTF_8))).isTrue();
<del> assertThat(this.encoder.canEncode(ResolvableType.forClass(Pojo.class),
<del> new MediaType("application", "cbor", StandardCharsets.ISO_8859_1))).isFalse();
<ide> }
<ide>
<ide> @Test
<ide><path>spring-web/src/test/java/org/springframework/http/codec/json/Jackson2JsonDecoderTests.java
<ide> public void canDecode() {
<ide> assertThat(this.decoder.canDecode(ResolvableType.forClass(Pojo.class),
<ide> new MediaType("application", "json", StandardCharsets.UTF_8))).isTrue();
<ide> assertThat(this.decoder.canDecode(ResolvableType.forClass(Pojo.class),
<del> new MediaType("application", "json", StandardCharsets.ISO_8859_1))).isFalse();
<add> new MediaType("application", "json", StandardCharsets.ISO_8859_1))).isTrue();
<ide> }
<ide>
<ide> @Test // SPR-15866
<ide> public void decodeNonUtf8Encoding() {
<ide> null);
<ide> }
<ide>
<add> @Test
<add> @SuppressWarnings("unchecked")
<add> public void decodeNonUnicode() {
<add> Flux<DataBuffer> input = Flux.concat(
<add> stringBuffer("{\"føø\":\"bår\"}", StandardCharsets.ISO_8859_1)
<add> );
<add>
<add> testDecode(input, ResolvableType.forType(new ParameterizedTypeReference<Map<String, String>>() {
<add> }),
<add> step -> step.assertNext(o -> assertThat((Map<String, String>) o).containsEntry("føø", "bår"))
<add> .verifyComplete(),
<add> MediaType.parseMediaType("application/json; charset=iso-8859-1"),
<add> null);
<add> }
<add>
<ide> @Test
<ide> @SuppressWarnings("unchecked")
<ide> public void decodeMonoNonUtf8Encoding() {
<ide><path>spring-web/src/test/java/org/springframework/http/codec/json/Jackson2SmileDecoderTests.java
<ide>
<ide> package org.springframework.http.codec.json;
<ide>
<del>import java.nio.charset.StandardCharsets;
<ide> import java.util.Arrays;
<ide> import java.util.List;
<ide>
<ide> import org.springframework.core.ResolvableType;
<ide> import org.springframework.core.io.buffer.DataBuffer;
<ide> import org.springframework.core.testfixture.codec.AbstractDecoderTests;
<del>import org.springframework.http.MediaType;
<ide> import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
<ide> import org.springframework.util.MimeType;
<ide> import org.springframework.web.testfixture.xml.Pojo;
<ide> public void canDecode() {
<ide>
<ide> assertThat(decoder.canDecode(ResolvableType.forClass(String.class), null)).isFalse();
<ide> assertThat(decoder.canDecode(ResolvableType.forClass(Pojo.class), APPLICATION_JSON)).isFalse();
<del>
<del> assertThat(this.decoder.canDecode(ResolvableType.forClass(Pojo.class),
<del> new MediaType("application", "x-jackson-smile", StandardCharsets.UTF_8))).isTrue();
<del> assertThat(this.decoder.canDecode(ResolvableType.forClass(Pojo.class),
<del> new MediaType("application", "x-jackson-smile", StandardCharsets.ISO_8859_1))).isFalse();
<del>
<ide> }
<ide>
<ide> @Override
<ide><path>spring-web/src/test/java/org/springframework/http/codec/json/Jackson2SmileEncoderTests.java
<ide>
<ide> import java.io.IOException;
<ide> import java.io.UncheckedIOException;
<del>import java.nio.charset.StandardCharsets;
<ide> import java.util.Arrays;
<ide> import java.util.List;
<ide>
<ide> import org.springframework.core.io.buffer.DataBuffer;
<ide> import org.springframework.core.io.buffer.DataBufferUtils;
<ide> import org.springframework.core.testfixture.codec.AbstractEncoderTests;
<del>import org.springframework.http.MediaType;
<ide> import org.springframework.http.codec.ServerSentEvent;
<ide> import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
<ide> import org.springframework.util.MimeType;
<ide> public void canEncode() {
<ide> assertThat(this.encoder.canEncode(pojoType, STREAM_SMILE_MIME_TYPE)).isTrue();
<ide> assertThat(this.encoder.canEncode(pojoType, null)).isTrue();
<ide>
<del> assertThat(this.encoder.canEncode(ResolvableType.forClass(Pojo.class),
<del> new MediaType("application", "x-jackson-smile", StandardCharsets.UTF_8))).isTrue();
<del> assertThat(this.encoder.canEncode(ResolvableType.forClass(Pojo.class),
<del> new MediaType("application", "x-jackson-smile", StandardCharsets.ISO_8859_1))).isFalse();
<del>
<ide> // SPR-15464
<ide> assertThat(this.encoder.canEncode(ResolvableType.NONE, null)).isTrue();
<ide> }
<ide><path>spring-web/src/test/java/org/springframework/http/converter/json/MappingJackson2HttpMessageConverterTests.java
<ide>
<ide> import java.io.IOException;
<ide> import java.lang.reflect.Type;
<add>import java.nio.charset.Charset;
<ide> import java.nio.charset.StandardCharsets;
<ide> import java.util.ArrayList;
<ide> import java.util.HashMap;
<ide>
<ide> import static org.assertj.core.api.Assertions.assertThat;
<ide> import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
<add>import static org.assertj.core.api.Assertions.entry;
<ide> import static org.assertj.core.api.Assertions.within;
<ide>
<ide> /**
<ide> public void canRead() {
<ide> assertThat(converter.canRead(MyBean.class, new MediaType("application", "json"))).isTrue();
<ide> assertThat(converter.canRead(Map.class, new MediaType("application", "json"))).isTrue();
<ide> assertThat(converter.canRead(MyBean.class, new MediaType("application", "json", StandardCharsets.UTF_8))).isTrue();
<del> assertThat(converter.canRead(MyBean.class, new MediaType("application", "json", StandardCharsets.ISO_8859_1))).isFalse();
<add> assertThat(converter.canRead(MyBean.class, new MediaType("application", "json", StandardCharsets.ISO_8859_1))).isTrue();
<ide> }
<ide>
<ide> @Test
<ide> public void writeSubTypeList() throws Exception {
<ide> @Test
<ide> public void readWithNoDefaultConstructor() throws Exception {
<ide> String body = "{\"property1\":\"foo\",\"property2\":\"bar\"}";
<del> MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes("UTF-8"));
<add> MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes(StandardCharsets.UTF_8));
<ide> inputMessage.getHeaders().setContentType(new MediaType("application", "json"));
<ide> assertThatExceptionOfType(HttpMessageConversionException.class).isThrownBy(() ->
<ide> converter.read(BeanWithNoDefaultConstructor.class, inputMessage))
<ide> .withMessageStartingWith("Type definition error:");
<ide> }
<ide>
<add> @Test
<add> @SuppressWarnings("unchecked")
<add> public void readNonUnicode() throws Exception {
<add> String body = "{\"føø\":\"bår\"}";
<add> Charset charset = StandardCharsets.ISO_8859_1;
<add> MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes(charset));
<add> inputMessage.getHeaders().setContentType(new MediaType("application", "json", charset));
<add> HashMap<String, Object> result = (HashMap<String, Object>) this.converter.read(HashMap.class, inputMessage);
<add>
<add> assertThat(result).containsExactly(entry("føø", "bår"));
<add> }
<add>
<ide>
<ide> interface MyInterface {
<ide>
<ide><path>spring-web/src/test/java/org/springframework/http/converter/smile/MappingJackson2SmileHttpMessageConverterTests.java
<ide> package org.springframework.http.converter.smile;
<ide>
<ide> import java.io.IOException;
<del>import java.nio.charset.StandardCharsets;
<ide>
<ide> import com.fasterxml.jackson.databind.ObjectMapper;
<ide> import com.fasterxml.jackson.dataformat.smile.SmileFactory;
<ide> public void canRead() {
<ide> assertThat(converter.canRead(MyBean.class, new MediaType("application", "x-jackson-smile"))).isTrue();
<ide> assertThat(converter.canRead(MyBean.class, new MediaType("application", "json"))).isFalse();
<ide> assertThat(converter.canRead(MyBean.class, new MediaType("application", "xml"))).isFalse();
<del> assertThat(converter.canRead(MyBean.class, new MediaType("application", "x-jackson-smile", StandardCharsets.UTF_8))).isTrue();
<del> assertThat(converter.canRead(MyBean.class, new MediaType("application", "x-jackson-smile", StandardCharsets.ISO_8859_1))).isFalse();
<ide> }
<ide>
<ide> @Test
<ide> public void canWrite() {
<ide> assertThat(converter.canWrite(MyBean.class, new MediaType("application", "x-jackson-smile"))).isTrue();
<ide> assertThat(converter.canWrite(MyBean.class, new MediaType("application", "json"))).isFalse();
<ide> assertThat(converter.canWrite(MyBean.class, new MediaType("application", "xml"))).isFalse();
<del> assertThat(converter.canWrite(MyBean.class, new MediaType("application", "x-jackson-smile", StandardCharsets.UTF_8))).isTrue();
<del> assertThat(converter.canWrite(MyBean.class, new MediaType("application", "x-jackson-smile", StandardCharsets.ISO_8859_1))).isFalse();
<ide> }
<ide>
<ide> @Test
<ide><path>spring-web/src/test/java/org/springframework/http/converter/xml/MappingJackson2XmlHttpMessageConverterTests.java
<ide> package org.springframework.http.converter.xml;
<ide>
<ide> import java.io.IOException;
<add>import java.nio.charset.Charset;
<ide> import java.nio.charset.StandardCharsets;
<ide>
<ide> import com.fasterxml.jackson.annotation.JsonView;
<ide> public void canRead() {
<ide> assertThat(converter.canRead(MyBean.class, new MediaType("text", "xml"))).isTrue();
<ide> assertThat(converter.canRead(MyBean.class, new MediaType("application", "soap+xml"))).isTrue();
<ide> assertThat(converter.canRead(MyBean.class, new MediaType("text", "xml", StandardCharsets.UTF_8))).isTrue();
<del> assertThat(converter.canRead(MyBean.class, new MediaType("text", "xml", StandardCharsets.ISO_8859_1))).isFalse();
<add> assertThat(converter.canRead(MyBean.class, new MediaType("text", "xml", StandardCharsets.ISO_8859_1))).isTrue();
<ide> }
<ide>
<ide> @Test
<ide> public void readWithXmlBomb() throws IOException {
<ide> this.converter.read(MyBean.class, inputMessage));
<ide> }
<ide>
<add> @Test
<add> @SuppressWarnings("unchecked")
<add> public void readNonUnicode() throws Exception {
<add> String body = "<MyBean>" +
<add> "<string>føø bår</string>" +
<add> "</MyBean>";
<add>
<add> Charset charset = StandardCharsets.ISO_8859_1;
<add> MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes(charset));
<add> inputMessage.getHeaders().setContentType(new MediaType("application", "xml", charset));
<add> MyBean result = (MyBean) converter.read(MyBean.class, inputMessage);
<add> assertThat(result.getString()).isEqualTo("føø bår");
<add> }
<add>
<add>
<ide>
<ide> public static class MyBean {
<ide> | 11 |
Java | Java | invoke webmvc.fn error handlers for async errors | 6f4fb08bf8c1bf6f783e380f2c604f415fc0dfe6 | <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/function/DefaultAsyncServerResponse.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2021 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 <R> R delegate(Function<ServerResponse, R> function) {
<ide> public ModelAndView writeTo(HttpServletRequest request, HttpServletResponse response, Context context)
<ide> throws ServletException, IOException {
<ide>
<del> writeAsync(request, response, createDeferredResult());
<add> writeAsync(request, response, createDeferredResult(request));
<ide> return null;
<ide> }
<ide>
<ide> static void writeAsync(HttpServletRequest request, HttpServletResponse response,
<ide>
<ide> }
<ide>
<del> private DeferredResult<ServerResponse> createDeferredResult() {
<add> private DeferredResult<ServerResponse> createDeferredResult(HttpServletRequest request) {
<ide> DeferredResult<ServerResponse> result;
<ide> if (this.timeout != null) {
<ide> result = new DeferredResult<>(this.timeout.toMillis());
<ide> private DeferredResult<ServerResponse> createDeferredResult() {
<ide> if (ex instanceof CompletionException && ex.getCause() != null) {
<ide> ex = ex.getCause();
<ide> }
<del> result.setErrorResult(ex);
<add> ServerResponse errorResponse = errorResponse(ex, request);
<add> if (errorResponse != null) {
<add> result.setResult(errorResponse);
<add> }
<add> else {
<add> result.setErrorResult(ex);
<add> }
<ide> }
<ide> else {
<ide> result.setResult(value);
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/function/DefaultEntityResponseBuilder.java
<ide> public CompletionStageEntityResponse(int statusCode, HttpHeaders headers,
<ide> protected ModelAndView writeToInternal(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
<ide> Context context) throws ServletException, IOException {
<ide>
<del> DeferredResult<?> deferredResult = createDeferredResult(servletRequest, servletResponse, context);
<add> DeferredResult<ServerResponse> deferredResult = createDeferredResult(servletRequest, servletResponse, context);
<ide> DefaultAsyncServerResponse.writeAsync(servletRequest, servletResponse, deferredResult);
<ide> return null;
<ide> }
<ide>
<del> private DeferredResult<?> createDeferredResult(HttpServletRequest request, HttpServletResponse response,
<add> private DeferredResult<ServerResponse> createDeferredResult(HttpServletRequest request, HttpServletResponse response,
<ide> Context context) {
<ide>
<del> DeferredResult<?> result = new DeferredResult<>();
<add> DeferredResult<ServerResponse> result = new DeferredResult<>();
<ide> entity().handle((value, ex) -> {
<ide> if (ex != null) {
<ide> if (ex instanceof CompletionException && ex.getCause() != null) {
<ide> ex = ex.getCause();
<ide> }
<del> result.setErrorResult(ex);
<add> ServerResponse errorResponse = errorResponse(ex, request);
<add> if (errorResponse != null) {
<add> result.setResult(errorResponse);
<add> }
<add> else {
<add> result.setErrorResult(ex);
<add> }
<ide> }
<ide> else {
<ide> try {
<ide> public void onNext(T t) {
<ide>
<ide> @Override
<ide> public void onError(Throwable t) {
<del> this.deferredResult.setErrorResult(t);
<add> try {
<add> handleError(t, this.servletRequest, this.servletResponse, this.context);
<add> }
<add> catch (ServletException | IOException handlingThrowable) {
<add> this.deferredResult.setErrorResult(handlingThrowable);
<add> }
<ide> }
<ide>
<ide> @Override
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/function/ErrorHandlingServerResponse.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2021 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> /**
<ide> * Base class for {@link ServerResponse} implementations with error handling.
<del> *
<ide> * @author Arjen Poutsma
<ide> * @since 5.3
<ide> */
<ide> protected final <T extends ServerResponse> void addErrorHandler(Predicate<Throwa
<ide> }
<ide>
<ide> @Nullable
<del> protected ModelAndView handleError(Throwable t, HttpServletRequest servletRequest,
<add> protected final ModelAndView handleError(Throwable t, HttpServletRequest servletRequest,
<ide> HttpServletResponse servletResponse, Context context) throws ServletException, IOException {
<ide>
<add> ServerResponse serverResponse = errorResponse(t, servletRequest);
<add> if (serverResponse != null) {
<add> return serverResponse.writeTo(servletRequest, servletResponse, context);
<add> }
<add> else if (t instanceof ServletException) {
<add> throw (ServletException) t;
<add> }
<add> else if (t instanceof IOException) {
<add> throw (IOException) t;
<add> }
<add> else {
<add> throw new ServletException(t);
<add> }
<add> }
<add>
<add> @Nullable
<add> protected final ServerResponse errorResponse(Throwable t, HttpServletRequest servletRequest) {
<ide> for (ErrorHandler<?> errorHandler : this.errorHandlers) {
<ide> if (errorHandler.test(t)) {
<ide> ServerRequest serverRequest = (ServerRequest)
<ide> servletRequest.getAttribute(RouterFunctions.REQUEST_ATTRIBUTE);
<del> ServerResponse serverResponse = errorHandler.handle(t, serverRequest);
<del> return serverResponse.writeTo(servletRequest, servletResponse, context);
<add> return errorHandler.handle(t, serverRequest);
<ide> }
<ide> }
<del> throw new ServletException(t);
<add> return null;
<ide> }
<ide>
<del>
<ide> private static class ErrorHandler<T extends ServerResponse> {
<ide>
<ide> private final Predicate<Throwable> predicate; | 3 |
Text | Text | fix backticks in fs api docs | 6686d9000b64a8cbfa2077ea0e30e253c35e053a | <ide><path>doc/api/fs.md
<ide> added: v10.0.0
<ide> changes:
<ide> - version: v14.0.0
<ide> pr-url: https://github.com/nodejs/node/pull/27044
<del> description: Changed 'flags' argument to 'mode' and imposed
<add> description: Changed `flags` argument to `mode` and imposed
<ide> stricter type validation.
<ide> -->
<ide>
<ide> changes:
<ide> `ERR_INVALID_CALLBACK`.
<ide> - version: v14.0.0
<ide> pr-url: https://github.com/nodejs/node/pull/27044
<del> description: Changed 'flags' argument to 'mode' and imposed
<add> description: Changed `flags` argument to `mode` and imposed
<ide> stricter type validation.
<ide> -->
<ide>
<ide> added: v8.5.0
<ide> changes:
<ide> - version: v14.0.0
<ide> pr-url: https://github.com/nodejs/node/pull/27044
<del> description: Changed 'flags' argument to 'mode' and imposed
<add> description: Changed `flags` argument to `mode` and imposed
<ide> stricter type validation.
<ide> -->
<ide> | 1 |
Python | Python | fix py3 test | 359f91ff6c189f625a875e37592cd84f3f554d28 | <ide><path>tests/keras/test_models.py
<ide> def output_shape(input_shapes):
<ide> # test "join" mode in Lambda
<ide> def difference(input_dict):
<ide> assert(len(input_dict) == 2)
<del> keys = input_dict.keys()
<add> keys = list(input_dict.keys())
<ide> return input_dict[keys[0]] - input_dict[keys[1]]
<ide>
<ide> g = Graph() | 1 |
Javascript | Javascript | close open rows on scroll | 5c13eaccbd7136949525b6c6eb3ac7e0c63c662f | <ide><path>Libraries/Experimental/SwipeableRow/SwipeableListView.js
<ide> const SwipeableRow = require('SwipeableRow');
<ide>
<ide> const {PropTypes} = React;
<ide>
<add>type Props = {
<add> bounceFirstRowOnMount: boolean,
<add> dataSource: SwipeableListViewDataSource,
<add> maxSwipeDistance: number,
<add> renderRow: Function,
<add> renderQuickActions: Function,
<add>};
<add>
<add>type State = {
<add> dataSource: Object,
<add> scrollEnabled: boolean,
<add>};
<add>
<ide> /**
<ide> * A container component that renders multiple SwipeableRow's in a ListView
<ide> * implementation. This is designed to be a drop-in replacement for the
<ide> const {PropTypes} = React;
<ide> * - More to come
<ide> */
<ide> class SwipeableListView extends React.Component {
<del> props: {
<del> bounceFirstRowOnMount: boolean,
<del> dataSource: SwipeableListViewDataSource,
<del> maxSwipeDistance: number,
<del> renderRow: Function,
<del> renderQuickActions: Function,
<del> };
<add> props: Props;
<add> state: State;
<add>
<add> _listViewRef: ?ReactElement<any> = null;
<add> _shouldBounceFirstRowOnMount: boolean = false;
<ide>
<ide> static getNewDataSource(): Object {
<ide> return new SwipeableListViewDataSource({
<ide> getRowData: (data, sectionID, rowID) => data[sectionID][rowID],
<ide> getSectionHeaderData: (data, sectionID) => data[sectionID],
<del> sectionHeaderHasChanged: (s1, s2) => s1 !== s2,
<ide> rowHasChanged: (row1, row2) => row1 !== row2,
<add> sectionHeaderHasChanged: (s1, s2) => s1 !== s2,
<ide> });
<ide> }
<ide>
<ide> class SwipeableListView extends React.Component {
<ide> renderQuickActions: () => null,
<ide> };
<ide>
<del> state: Object = {
<del> dataSource: this.props.dataSource,
<del> };
<add> constructor(props: Props, context: any): void {
<add> super(props, context);
<ide>
<del> _listViewRef: ?ReactElement<any> = null;
<del> _shouldBounceFirstRowOnMount = false;
<del>
<del> componentWillMount(): void {
<ide> this._shouldBounceFirstRowOnMount = this.props.bounceFirstRowOnMount;
<add> this.state = {
<add> dataSource: this.props.dataSource,
<add> scrollEnabled: true,
<add> };
<ide> }
<ide>
<del> componentWillReceiveProps(nextProps: Object): void {
<del> if (
<del> this.state.dataSource.getDataSource() !== nextProps.dataSource.getDataSource()
<del> ) {
<add> componentWillReceiveProps(nextProps: Props): void {
<add> if (this.state.dataSource.getDataSource() !== nextProps.dataSource.getDataSource()) {
<ide> this.setState({
<ide> dataSource: nextProps.dataSource,
<ide> });
<ide> class SwipeableListView extends React.Component {
<ide> this._listViewRef = ref;
<ide> }}
<ide> dataSource={this.state.dataSource.getDataSource()}
<add> onScroll={this._onScroll}
<ide> renderRow={this._renderRow}
<ide> scrollEnabled={this.state.scrollEnabled}
<ide> />
<ide> );
<ide> }
<ide>
<add> _onScroll = (): void => {
<add> // Close any opens rows on ListView scroll
<add> if (this.props.dataSource.getOpenRowID()) {
<add> this.setState({
<add> dataSource: this.state.dataSource.setOpenRowID(null),
<add> });
<add> }
<add> }
<add>
<ide> /**
<ide> * This is a work-around to lock vertical `ListView` scrolling on iOS and
<ide> * mimic Android behaviour. Locking vertical scrolling when horizontal
<ide> * scrolling is active allows us to significantly improve framerates
<ide> * (from high 20s to almost consistently 60 fps)
<ide> */
<del> _setListViewScrollable = (value: boolean): void => {
<del> if (this._listViewRef &&
<del> typeof this._listViewRef.setNativeProps === 'function') {
<add> _setListViewScrollable(value: boolean): void {
<add> if (this._listViewRef && typeof this._listViewRef.setNativeProps === 'function') {
<ide> this._listViewRef.setNativeProps({
<ide> scrollEnabled: value,
<ide> });
<ide> }
<del> };
<add> }
<ide>
<ide> // Passing through ListView's getScrollResponder() function
<del> getScrollResponder = (): ?Object => {
<del> if (this._listViewRef &&
<del> typeof this._listViewRef.getScrollResponder === 'function') {
<add> getScrollResponder(): ?Object {
<add> if (this._listViewRef && typeof this._listViewRef.getScrollResponder === 'function') {
<ide> return this._listViewRef.getScrollResponder();
<ide> }
<del> };
<add> }
<ide>
<ide> _renderRow = (rowData: Object, sectionID: string, rowID: string): ReactElement<any> => {
<ide> const slideoutView = this.props.renderQuickActions(rowData, sectionID, rowID);
<ide> class SwipeableListView extends React.Component {
<ide> );
<ide> };
<ide>
<del> _onOpen = (rowID: string): void => {
<add> _onOpen(rowID: string): void {
<ide> this.setState({
<ide> dataSource: this.state.dataSource.setOpenRowID(rowID),
<ide> });
<del> };
<add> }
<ide> }
<ide>
<ide> module.exports = SwipeableListView; | 1 |
PHP | PHP | add missing test for getroutesbymethod | b28424410e46ebcdc0733f46b5a4c9aca36b1c58 | <ide><path>tests/Routing/RouteCollectionTest.php
<ide> public function testRouteCollectionCanGetRoutesByName()
<ide> $this->assertSame($routesByName, $this->routeCollection->getRoutesByName());
<ide> }
<ide>
<add> public function testRouteCollectionCanGetRoutesByMethod()
<add> {
<add> $routes = [
<add> 'foo_index' => new Route('GET', 'foo/index', [
<add> 'uses' => 'FooController@index',
<add> 'as' => 'foo_index',
<add> ]),
<add> 'foo_show' => new Route('GET', 'foo/show', [
<add> 'uses' => 'FooController@show',
<add> 'as' => 'foo_show',
<add> ]),
<add> 'bar_create' => new Route('POST', 'bar', [
<add> 'uses' => 'BarController@create',
<add> 'as' => 'bar_create',
<add> ]),
<add> ];
<add>
<add> $this->routeCollection->add($routes['foo_index']);
<add> $this->routeCollection->add($routes['foo_show']);
<add> $this->routeCollection->add($routes['bar_create']);
<add>
<add> $this->assertSame([
<add> 'GET' => [
<add> 'foo/index' => $routes['foo_index'],
<add> 'foo/show' => $routes['foo_show'],
<add> ],
<add> 'HEAD' => [
<add> 'foo/index' => $routes['foo_index'],
<add> 'foo/show' => $routes['foo_show'],
<add> ],
<add> 'POST' => [
<add> 'bar' => $routes['bar_create'],
<add> ],
<add> ], $this->routeCollection->getRoutesByMethod());
<add> }
<add>
<ide> public function testRouteCollectionCleansUpOverwrittenRoutes()
<ide> {
<ide> // Create two routes with the same path and method. | 1 |
Java | Java | require jsonpath 1.1+ | db05f43a757e92817b89cb40dcfe559747804b69 | <ide><path>spring-test/src/main/java/org/springframework/test/util/JsonPathExpectationsHelper.java
<ide>
<ide> package org.springframework.test.util;
<ide>
<del>import java.lang.reflect.Array;
<del>import java.lang.reflect.Method;
<ide> import java.text.ParseException;
<ide> import java.util.List;
<ide> import java.util.Map;
<ide>
<add>import com.jayway.jsonpath.InvalidPathException;
<add>import com.jayway.jsonpath.JsonPath;
<ide> import org.hamcrest.Matcher;
<ide>
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.util.ObjectUtils;
<del>import org.springframework.util.ReflectionUtils;
<ide> import org.springframework.util.StringUtils;
<ide>
<del>import com.jayway.jsonpath.InvalidPathException;
<del>import com.jayway.jsonpath.JsonPath;
<del>
<del>import static org.hamcrest.MatcherAssert.assertThat;
<del>import static org.hamcrest.core.IsInstanceOf.instanceOf;
<del>import static org.springframework.test.util.AssertionErrors.assertEquals;
<del>import static org.springframework.test.util.AssertionErrors.assertTrue;
<del>import static org.springframework.test.util.AssertionErrors.fail;
<add>import static org.hamcrest.MatcherAssert.*;
<add>import static org.hamcrest.core.IsInstanceOf.*;
<add>import static org.springframework.test.util.AssertionErrors.*;
<ide>
<ide> /**
<ide> * A helper class for applying assertions via JSON path expressions.
<ide> */
<ide> public class JsonPathExpectationsHelper {
<ide>
<del> private static Method compileMethod;
<del>
<del> private static Object emptyFilters;
<del>
<del> static {
<del> // Reflective bridging between JsonPath 0.9.x and 1.x
<del> for (Method candidate : JsonPath.class.getMethods()) {
<del> if (candidate.getName().equals("compile")) {
<del> Class<?>[] paramTypes = candidate.getParameterTypes();
<del> if (paramTypes.length == 2 && String.class == paramTypes[0] && paramTypes[1].isArray()) {
<del> compileMethod = candidate;
<del> emptyFilters = Array.newInstance(paramTypes[1].getComponentType(), 0);
<del> break;
<del> }
<del> }
<del> }
<del> Assert.state(compileMethod != null, "Unexpected JsonPath API - no compile(String, ...) method found");
<del> }
<del>
<del>
<ide> private final String expression;
<ide>
<ide> private final JsonPath jsonPath;
<ide> public class JsonPathExpectationsHelper {
<ide> public JsonPathExpectationsHelper(String expression, Object... args) {
<ide> Assert.hasText(expression, "expression must not be null or empty");
<ide> this.expression = String.format(expression, args);
<del> this.jsonPath = (JsonPath) ReflectionUtils.invokeMethod(
<del> compileMethod, null, this.expression, emptyFilters);
<add> this.jsonPath = JsonPath.compile(this.expression);
<ide> }
<ide>
<ide> | 1 |
PHP | PHP | fix doc block | 7114153b151f8dc861a7f89e1cabbc151843db49 | <ide><path>src/View/ViewBuilder.php
<ide> public function enableAutoLayout($enable = true)
<ide> * Returns if CakePHP's conventional mode of applying layout files is enabled.
<ide> * Disabled means that layouts will not be automatically applied to rendered views.
<ide> *
<del> * @return bool
<add> * @return bool|null
<ide> */
<ide> public function isAutoLayoutEnabled()
<ide> {
<del> return $this->_autoLayout !== null ? $this->_autoLayout : true;
<add> return $this->_autoLayout;
<ide> }
<ide>
<ide> /** | 1 |
Javascript | Javascript | load granular chunks with correct asset prefix | 8dd394a05586741fe613bb6ba330539e75f53fcf | <ide><path>packages/next/client/page-loader.js
<ide> export default class PageLoader {
<ide> ) {
<ide> scriptRoute = scriptRoute.replace(/\.js$/, '.module.js')
<ide> }
<del> const url = isDependency
<del> ? route
<del> : `${this.assetPrefix}/_next/static/${encodeURIComponent(
<del> this.buildId
<del> )}/pages${scriptRoute}`
<add> const url =
<add> this.assetPrefix +
<add> (isDependency
<add> ? route
<add> : `/_next/static/${encodeURIComponent(
<add> this.buildId
<add> )}/pages${scriptRoute}`)
<ide>
<ide> // n.b. If preload is not supported, we fall back to `loadPage` which has
<ide> // its own deduping mechanism. | 1 |
Javascript | Javascript | fix lint warnings in fonts.js | 5083774a8c653e57da463e3653fabd4f87f40c2b | <ide><path>src/fonts.js
<ide> var Type1Parser = function type1Parser() {
<ide> return program;
<ide> };
<ide>
<del> this.extractFontHeader = function Type1Parser_extractFontHeader(stream, properties) {
<add> this.extractFontHeader = function Type1Parser_extractFontHeader(stream,
<add> properties) {
<ide> var headerString = '';
<ide> for (var i = 0, ii = stream.length; i < ii; i++)
<ide> headerString += String.fromCharCode(stream[i]);
<ide> var Type1Font = function Type1Font(name, file, properties) {
<ide> };
<ide>
<ide> Type1Font.prototype = {
<del> createCFFIndexHeader: function Type1Font_createCFFIndexHeader(objects, isByte) {
<add> createCFFIndexHeader: function Type1Font_createCFFIndexHeader(objects,
<add> isByte) {
<ide> // First 2 bytes contains the number of objects contained into this index
<ide> var count = objects.length;
<ide>
<ide> Type1Font.prototype = {
<ide> return charstrings;
<ide> },
<ide>
<del> getType2Charstrings: function Type1Font_getType2Charstrings(type1Charstrings) {
<add> getType2Charstrings: function Type1Font_getType2Charstrings(
<add> type1Charstrings) {
<ide> var type2Charstrings = [];
<ide> var count = type1Charstrings.length;
<ide> for (var i = 0; i < count; i++) { | 1 |
Ruby | Ruby | remove unnecessary readme in dummy application | 65590e3c968b81f78c2ff33945ba819f607391d8 | <ide><path>railties/lib/rails/generators/rails/plugin/plugin_generator.rb
<ide> def test_dummy_clean
<ide> remove_file "Gemfile"
<ide> remove_file "lib/tasks"
<ide> remove_file "public/robots.txt"
<del> remove_file "README"
<add> remove_file "README.md"
<ide> remove_file "test"
<ide> remove_file "vendor"
<ide> end
<ide><path>railties/test/generators/plugin_generator_test.rb
<ide> def test_ensure_that_gitignore_can_be_generated_from_a_template_for_dummy_path
<ide> end
<ide> end
<ide>
<add> def test_unnecessary_files_are_not_generated_in_dummy_application
<add> run_generator
<add> assert_no_file 'test/dummy/.gitignore'
<add> assert_no_file 'test/dummy/db/seeds.rb'
<add> assert_no_file 'test/dummy/Gemfile'
<add> assert_no_file 'test/dummy/public/robots.txt'
<add> assert_no_file 'test/dummy/README.md'
<add> assert_no_directory 'test/dummy/lib/tasks'
<add> assert_no_directory 'test/dummy/doc'
<add> assert_no_directory 'test/dummy/test'
<add> assert_no_directory 'test/dummy/vendor'
<add> end
<add>
<ide> def test_skipping_test_files
<ide> run_generator [destination_root, "--skip-test"]
<ide> assert_no_file "test" | 2 |
Javascript | Javascript | add round to showcase | 05e8681cf4cb2123c130ec93cab4ab8b057d0148 | <ide><path>website/src/react-native/showcase.js
<ide> var apps = [
<ide> link: 'https://itunes.apple.com/us/app/rota-worker-shifts-on-demand/id1042111289?mt=8',
<ide> author: 'Rota',
<ide> },
<add> {
<add> name: 'Round - A better way to remember your medicine',
<add> icon: 'https://s3.mzstatic.com/us/r30/Purple69/v4/d3/ee/54/d3ee54cf-13b6-5f56-0edc-6c70ac90b2be/icon175x175.png',
<add> link: 'https://itunes.apple.com/us/app/round-beautiful-medication/id1059591124?mt=8',
<add> author: 'Circadian Design',
<add> },
<ide> {
<ide> name: 'RWpodPlayer - audio player for RWpod podcast',
<ide> icon: 'http://a1.mzstatic.com/us/r30/Purple69/v4/a8/c0/b1/a8c0b130-e44b-742d-6458-0c89fcc15b6b/icon175x175.png', | 1 |
Javascript | Javascript | pass norefs as arguments | b00b2f08bf78e735f206051942f3d22ad5b3b0ed | <ide><path>lib/_debugger.js
<ide> Client.prototype.reqFrameEval = function(expression, frame, cb) {
<ide> // reqBacktrace(cb)
<ide> // TODO: from, to, bottom
<ide> Client.prototype.reqBacktrace = function(cb) {
<del> this.req({ command: 'backtrace', noRefs: true } , cb);
<add> this.req({ command: 'backtrace', arguments: { noRefs: true } } , cb);
<ide> };
<ide>
<ide> | 1 |
Javascript | Javascript | pass sourcemap when swcminify is enabled | e7f503abd373618dfac1335dbde0f84ac0a054cf | <ide><path>packages/next/build/webpack/plugins/terser-webpack-plugin/src/index.js
<ide> export class TerserPlugin {
<ide> const result = await require('../../../../swc').minify(
<ide> options.input,
<ide> {
<add> ...(options.inputSourceMap
<add> ? {
<add> sourceMap: {
<add> content: JSON.stringify(options.inputSourceMap),
<add> },
<add> }
<add> : {}),
<ide> compress: true,
<ide> mangle: true,
<ide> } | 1 |
Ruby | Ruby | fix a json ordering issue | a3eaaf6b50b76a51080ec9ae6b217095868f3054 | <ide><path>activesupport/test/json/encoding_test.rb
<ide> def as_json(options)
<ide> StandardDateTimeTests = [[ DateTime.civil(2005,2,1,15,15,10), %("2005-02-01T15:15:10+00:00") ]]
<ide> StandardStringTests = [[ 'this is the <string>', %("this is the <string>")]]
<ide>
<add> def sorted_json(json)
<add> return json unless json =~ /^\{.*\}$/
<add> '{' + json[1..-2].split(',').sort.join(',') + '}'
<add> end
<add>
<ide> constants.grep(/Tests$/).each do |class_tests|
<ide> define_method("test_#{class_tests[0..-6].underscore}") do
<ide> begin
<ide> ActiveSupport.escape_html_entities_in_json = class_tests !~ /^Standard/
<ide> ActiveSupport.use_standard_json_time_format = class_tests =~ /^Standard/
<ide> self.class.const_get(class_tests).each do |pair|
<del> assert_equal pair.last, ActiveSupport::JSON.encode(pair.first)
<add> assert_equal pair.last, sorted_json(ActiveSupport::JSON.encode(pair.first))
<ide> end
<ide> ensure
<ide> ActiveSupport.escape_html_entities_in_json = false
<ide> def test_hash_encoding
<ide> assert_equal %({\"a\":[1,2]}), ActiveSupport::JSON.encode('a' => [1,2])
<ide> assert_equal %({"1":2}), ActiveSupport::JSON.encode(1 => 2)
<ide>
<del> sorted_json = '{' + ActiveSupport::JSON.encode(:a => :b, :c => :d)[1..-2].split(',').sort.join(',') + '}'
<del> assert_equal %({\"a\":\"b\",\"c\":\"d\"}), sorted_json
<add> assert_equal %({\"a\":\"b\",\"c\":\"d\"}), sorted_json(ActiveSupport::JSON.encode(:a => :b, :c => :d))
<ide> end
<ide>
<ide> def test_utf8_string_encoded_properly_when_kcode_is_utf8 | 1 |
Mixed | Javascript | provide dummy stdio for non-console windows apps | ab6c09b177eca67755a4c1f1d4d35fab9d2bb5d4 | <ide><path>doc/api/errors.md
<ide> An attempt was made to load a module with an unknown or unsupported format.
<ide> An invalid or unknown process signal was passed to an API expecting a valid
<ide> signal (such as [`subprocess.kill()`][]).
<ide>
<del><a id="ERR_UNKNOWN_STDIN_TYPE"></a>
<del>### ERR_UNKNOWN_STDIN_TYPE
<del>
<del>An attempt was made to launch a Node.js process with an unknown `stdin` file
<del>type. This error is usually an indication of a bug within Node.js itself,
<del>although it is possible for user code to trigger it.
<del>
<del><a id="ERR_UNKNOWN_STREAM_TYPE"></a>
<del>### ERR_UNKNOWN_STREAM_TYPE
<del>
<del>An attempt was made to launch a Node.js process with an unknown `stdout` or
<del>`stderr` file type. This error is usually an indication of a bug within Node.js
<del>itself, although it is possible for user code to trigger it.
<del>
<ide> <a id="ERR_V8BREAKITERATOR"></a>
<ide> ### ERR_V8BREAKITERATOR
<ide>
<ide> kind of internal Node.js error that should not typically be triggered by user
<ide> code. Instances of this error point to an internal bug within the Node.js
<ide> binary itself.
<ide>
<add><a id="ERR_UNKNOWN_STDIN_TYPE"></a>
<add>### ERR_UNKNOWN_STDIN_TYPE
<add><!-- YAML
<add>added: v8.0.0
<add>removed: REPLACEME
<add>-->
<add>
<add>An attempt was made to launch a Node.js process with an unknown `stdin` file
<add>type. This error is usually an indication of a bug within Node.js itself,
<add>although it is possible for user code to trigger it.
<add>
<add><a id="ERR_UNKNOWN_STREAM_TYPE"></a>
<add>### ERR_UNKNOWN_STREAM_TYPE
<add><!-- YAML
<add>added: v8.0.0
<add>removed: REPLACEME
<add>-->
<add>
<add>An attempt was made to launch a Node.js process with an unknown `stdout` or
<add>`stderr` file type. This error is usually an indication of a bug within Node.js
<add>itself, although it is possible for user code to trigger it.
<add>
<ide> <a id="ERR_VALUE_OUT_OF_RANGE"></a>
<ide> ### ERR_VALUE_OUT_OF_RANGE
<ide> <!-- YAML
<ide><path>lib/internal/errors.js
<ide> E('ERR_UNKNOWN_ENCODING', 'Unknown encoding: %s', TypeError);
<ide> E('ERR_UNKNOWN_FILE_EXTENSION', 'Unknown file extension: %s', Error);
<ide> E('ERR_UNKNOWN_MODULE_FORMAT', 'Unknown module format: %s', RangeError);
<ide> E('ERR_UNKNOWN_SIGNAL', 'Unknown signal: %s', TypeError);
<del>E('ERR_UNKNOWN_STDIN_TYPE', 'Unknown stdin file type', Error);
<ide>
<del>// This should probably be a `TypeError`.
<del>E('ERR_UNKNOWN_STREAM_TYPE', 'Unknown stream file type', Error);
<ide> E('ERR_V8BREAKITERATOR',
<ide> 'Full ICU data not installed. See https://github.com/nodejs/node/wiki/Intl',
<ide> Error);
<ide><path>lib/internal/process/stdio.js
<ide> 'use strict';
<ide>
<del>const {
<del> ERR_UNKNOWN_STDIN_TYPE,
<del> ERR_UNKNOWN_STREAM_TYPE
<del>} = require('internal/errors').codes;
<del>
<ide> exports.setupProcessStdio = setupProcessStdio;
<ide> exports.getMainThreadStdio = getMainThreadStdio;
<ide>
<ide> function getMainThreadStdio() {
<ide> break;
<ide>
<ide> default:
<del> // Probably an error on in uv_guess_handle()
<del> throw new ERR_UNKNOWN_STDIN_TYPE();
<add> // Provide a dummy contentless input for e.g. non-console
<add> // Windows applications.
<add> const { Readable } = require('stream');
<add> stdin = new Readable({ read() {} });
<add> stdin.push(null);
<ide> }
<ide>
<ide> // For supporting legacy API we put the FD here.
<ide> function getMainThreadStdio() {
<ide> return stdin;
<ide> }
<ide>
<add> exports.resetStdioForTesting = function() {
<add> stdin = undefined;
<add> stdout = undefined;
<add> stderr = undefined;
<add> };
<add>
<ide> return {
<ide> getStdout,
<ide> getStderr,
<ide> function createWritableStdioStream(fd) {
<ide> break;
<ide>
<ide> default:
<del> // Probably an error on in uv_guess_handle()
<del> throw new ERR_UNKNOWN_STREAM_TYPE();
<add> // Provide a dummy black-hole output for e.g. non-console
<add> // Windows applications.
<add> const { Writable } = require('stream');
<add> stream = new Writable({
<add> write(buf, enc, cb) {
<add> cb();
<add> }
<add> });
<ide> }
<ide>
<ide> // For supporting legacy API we put the FD here.
<ide><path>test/parallel/test-dummy-stdio.js
<add>'use strict';
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const child_process = require('child_process');
<add>
<add>if (common.isWindows)
<add> common.skip('fs.closeSync(n) does not close stdio on Windows');
<add>
<add>function runTest(fd, streamName, testOutputStream, expectedName) {
<add> const result = child_process.spawnSync(process.execPath, [
<add> '--expose-internals',
<add> '-e', `
<add> require('internal/process/stdio').resetStdioForTesting();
<add> fs.closeSync(${fd});
<add> const ctorName = process.${streamName}.constructor.name;
<add> process.${testOutputStream}.write(ctorName);
<add> `]);
<add> assert.strictEqual(result[testOutputStream].toString(), expectedName,
<add> `stdout:\n${result.stdout}\nstderr:\n${result.stderr}\n` +
<add> `while running test with fd = ${fd}`);
<add> if (testOutputStream !== 'stderr')
<add> assert.strictEqual(result.stderr.toString(), '');
<add>}
<add>
<add>runTest(0, 'stdin', 'stdout', 'Readable');
<add>runTest(1, 'stdout', 'stderr', 'Writable');
<add>runTest(2, 'stderr', 'stdout', 'Writable'); | 4 |
PHP | PHP | allow easily mocking of expected jobs | f75dd781e2f174e936cf900f1ebf601631c3ab5a | <ide><path>src/Illuminate/Foundation/Testing/ApplicationTrait.php
<ide> protected function withoutEvents()
<ide> return $this;
<ide> }
<ide>
<add> /**
<add> * Specify a list of jobs that should be dispatched for the given operation.
<add> *
<add> * These jobs will be mocked, so that handlers will not actually be executed.
<add> *
<add> * @param array|dynamic $jobs
<add> * @return $this
<add> */
<add> protected function expectsJobs($jobs)
<add> {
<add> $jobs = is_array($jobs) ? $jobs : func_get_args();
<add>
<add> $mock = Mockery::mock('Illuminate\Bus\Dispatcher[dispatch]', [$this->app]);
<add>
<add> foreach ($jobs as $job) {
<add> $mock->shouldReceive('dispatch')->atLeast()->once()
<add> ->with(Mockery::type($job));
<add> }
<add>
<add> $this->app->instance(
<add> 'Illuminate\Contracts\Bus\Dispatcher', $mock
<add> );
<add>
<add> return $this;
<add> }
<add>
<ide> /**
<ide> * Set the session to the given array.
<ide> * | 1 |
Ruby | Ruby | mark some implementation details as protected | 6641fc4017d2b279ef7ff71fc39a55830d12099a | <ide><path>Library/Homebrew/version.rb
<ide> class VersionElement
<ide> include Comparable
<ide>
<del> attr_reader :elem
<del>
<ide> def initialize elem
<ide> elem = elem.to_s.downcase
<ide> @elem = case elem
<ide> def string?
<ide> def numeric?
<ide> @elem.is_a? Numeric
<ide> end
<add>
<add> protected
<add>
<add> attr_reader :elem
<ide> end
<ide>
<ide> class Version
<ide> def detected_from_url?
<ide> @detected_from_url
<ide> end
<ide>
<del> def to_a
<del> @array ||= @version.scan(/\d+|[a-zA-Z]+/).map { |e| VersionElement.new(e) }
<del> end
<del>
<ide> def head?
<ide> @version == 'HEAD'
<ide> end
<ide> def self.parse spec
<ide> Version.new(version, true) unless version.nil?
<ide> end
<ide>
<add> protected
<add>
<add> def to_a
<add> @array ||= @version.scan(/\d+|[a-zA-Z]+/).map { |e| VersionElement.new(e) }
<add> end
<add>
<ide> private
<ide>
<ide> def self._parse spec | 1 |
Javascript | Javascript | update isvisible observer | 6aed41af0f3dca539f77c9c9c27f37482a417699 | <ide><path>lib/sproutcore-views/lib/views/view.js
<ide> SC.View = SC.Object.extend(
<ide> return view ;
<ide> },
<ide>
<del> _sccv_isVisibleDidChange: function() {
<add> /** @private
<add> When the view's `isVisible` property changes, toggle the visibility element
<add> of the actual DOM element.
<add> */
<add> _isVisibleDidChange: function() {
<ide> this.$().toggle(this.get('isVisible'));
<ide> }.observes('isVisible')
<ide> }); | 1 |
Ruby | Ruby | raise error on unknown primary key | ee2be435b1e5c0e94a4ee93a1a310e0471a77d07 | <ide><path>activerecord/lib/active_record/attribute_methods/primary_key.rb
<ide> module ClassMethods
<ide> # primary_key_prefix_type setting, though.
<ide> def primary_key
<ide> @primary_key ||= reset_primary_key
<add> raise ActiveRecord::UnknownPrimaryKey.new(self) unless @primary_key
<add> @primary_key
<ide> end
<ide>
<ide> # Returns a quoted version of the primary key name, used to construct SQL statements.
<ide> def reset_primary_key #:nodoc:
<ide> key
<ide> end
<ide>
<add> def primary_key? #:nodoc:
<add> @primary_key ||= reset_primary_key
<add> !@primary_key.nil?
<add> end
<add>
<ide> def get_primary_key(base_name) #:nodoc:
<ide> return 'id' unless base_name && !base_name.blank?
<ide>
<ide><path>activerecord/lib/active_record/attribute_methods/read.rb
<ide> def define_method_attribute(attr_name)
<ide> define_read_method(attr_name, attr_name, columns_hash[attr_name])
<ide> end
<ide>
<del> if attr_name == primary_key && attr_name != "id"
<add> if primary_key? && attr_name == primary_key && attr_name != "id"
<ide> define_read_method('id', attr_name, columns_hash[attr_name])
<ide> end
<ide> end
<ide> def define_read_method(method_name, attr_name, column)
<ide> cast_code = column.type_cast_code('v')
<ide> access_code = "(v=@attributes['#{attr_name}']) && #{cast_code}"
<ide>
<del> unless attr_name.to_s == self.primary_key.to_s
<add> unless primary_key? && attr_name.to_s == primary_key.to_s
<ide> access_code.insert(0, "missing_attribute('#{attr_name}', caller) unless @attributes.has_key?('#{attr_name}'); ")
<ide> end
<ide>
<ide> def read_attribute(attr_name)
<ide>
<ide> def _read_attribute(attr_name)
<ide> attr_name = attr_name.to_s
<del> attr_name = self.class.primary_key if attr_name == 'id'
<add> attr_name = self.class.primary_key? && self.class.primary_key if attr_name == 'id'
<ide> value = @attributes[attr_name]
<ide> unless value.nil?
<ide> if column = column_for_attribute(attr_name)
<ide><path>activerecord/lib/active_record/attribute_methods/write.rb
<ide> def define_method_attribute=(attr_name)
<ide> end
<ide> end
<ide>
<del> if attr_name == primary_key && attr_name != "id"
<add> if primary_key? && attr_name == primary_key && attr_name != "id"
<ide> generated_attribute_methods.module_eval("alias :id= :'#{primary_key}='")
<ide> end
<ide> end
<ide><path>activerecord/lib/active_record/base.rb
<ide> def table_exists?
<ide> # Returns an array of column objects for the table associated with this class.
<ide> def columns
<ide> if defined?(@primary_key)
<del> connection_pool.primary_keys[table_name] ||= primary_key
<add> connection_pool.primary_keys[table_name] ||= @primary_key
<ide> end
<ide>
<ide> connection_pool.columns[table_name]
<ide> def before_remove_const #:nodoc:
<ide> # objects of different types from the same table.
<ide> def instantiate(record)
<ide> sti_class = find_sti_class(record[inheritance_column])
<del> record_id = sti_class.primary_key && record[sti_class.primary_key]
<add> record_id = sti_class.primary_key? && record[sti_class.primary_key]
<ide>
<ide> if ActiveRecord::IdentityMap.enabled? && record_id
<ide> if (column = sti_class.columns_hash[sti_class.primary_key]) && column.number?
<ide> def ensure_proper_type
<ide>
<ide> # The primary key and inheritance column can never be set by mass-assignment for security reasons.
<ide> def self.attributes_protected_by_default
<del> default = [ primary_key, inheritance_column ]
<del> default << 'id' unless primary_key.eql? 'id'
<add> default = [ inheritance_column ]
<add> default << primary_key if primary_key?
<add> default << 'id' unless primary_key? && primary_key == 'id'
<ide> default
<ide> end
<ide>
<ide><path>activerecord/lib/active_record/errors.rb
<ide> def initialize(errors)
<ide> @errors = errors
<ide> end
<ide> end
<add>
<add> # Raised when a model attempts to fetch its primary key from the database, but the table
<add> # has no primary key declared.
<add> class UnknownPrimaryKey < ActiveRecordError
<add> attr_reader :model
<add>
<add> def initialize(model)
<add> @model = model
<add> end
<add>
<add> def message
<add> "Unknown primary key for table #{model.table_name} in model #{model}."
<add> end
<add> end
<ide> end
<ide><path>activerecord/lib/active_record/fixtures.rb
<ide> def table_rows
<ide>
<ide> private
<ide> def primary_key_name
<del> @primary_key_name ||= model_class && model_class.primary_key
<add> @primary_key_name ||= model_class && model_class.primary_key? && model_class.primary_key
<ide> end
<ide>
<ide> def has_primary_key_column?
<ide><path>activerecord/lib/active_record/persistence.rb
<ide> def create
<ide>
<ide> new_id = self.class.unscoped.insert attributes_values
<ide>
<del> self.id ||= new_id if self.class.primary_key
<add> self.id ||= new_id if self.class.primary_key?
<ide>
<ide> IdentityMap.add(self) if IdentityMap.enabled?
<ide> @new_record = false
<ide><path>activerecord/lib/active_record/relation.rb
<ide> class Relation
<ide>
<ide> # These are explicitly delegated to improve performance (avoids method_missing)
<ide> delegate :to_xml, :to_yaml, :length, :collect, :map, :each, :all?, :include?, :to => :to_a
<del> delegate :table_name, :quoted_table_name, :primary_key, :quoted_primary_key, :connection, :column_hash,:to => :klass
<add> delegate :table_name, :quoted_table_name, :primary_key, :primary_key?, :quoted_primary_key, :connection, :column_hash,:to => :klass
<ide>
<ide> attr_reader :table, :klass, :loaded
<ide> attr_accessor :extensions, :default_scoped
<ide> def initialize(klass, table)
<ide> def insert(values)
<ide> primary_key_value = nil
<ide>
<del> if primary_key && Hash === values
<add> if primary_key? && Hash === values
<ide> primary_key_value = values[values.keys.find { |k|
<ide> k.name == primary_key
<ide> }]
<ide> def insert(values)
<ide> conn.insert(
<ide> im,
<ide> 'SQL',
<del> primary_key,
<add> primary_key? && primary_key,
<ide> primary_key_value,
<ide> nil,
<ide> binds)
<ide><path>activerecord/lib/active_record/transactions.rb
<ide> def with_transaction_returning_status
<ide> # Save the new record state and id of a record so it can be restored later if a transaction fails.
<ide> def remember_transaction_record_state #:nodoc
<ide> @_start_transaction_state ||= {}
<del> @_start_transaction_state[:id] = id if has_attribute?(self.class.primary_key)
<add> @_start_transaction_state[:id] = id if self.class.primary_key?
<ide> unless @_start_transaction_state.include?(:new_record)
<ide> @_start_transaction_state[:new_record] = @new_record
<ide> end
<ide><path>activerecord/test/cases/attribute_methods/read_test.rb
<ide> def self.column_names
<ide> def self.primary_key
<ide> end
<ide>
<add> def self.primary_key?
<add> false
<add> end
<add>
<ide> def self.columns
<ide> column_names.map { FakeColumn.new(name) }
<ide> end
<ide><path>activerecord/test/cases/base_test.rb
<ide> def test_columns_should_obey_set_primary_key
<ide> assert pk.primary, 'nick should be primary key'
<ide> end
<ide>
<del> def test_primary_key_with_no_id
<del> assert_nil Edge.primary_key
<del> end
<del>
<ide> unless current_adapter?(:PostgreSQLAdapter,:OracleAdapter,:SQLServerAdapter)
<ide> def test_limit_with_comma
<ide> assert_nothing_raised do
<ide><path>activerecord/test/cases/primary_keys_test.rb
<ide> require 'models/movie'
<ide> require 'models/keyboard'
<ide> require 'models/mixed_case_monkey'
<add>require 'models/edge'
<ide>
<ide> class PrimaryKeysTest < ActiveRecord::TestCase
<ide> fixtures :topics, :subscribers, :movies, :mixed_case_monkeys
<ide> def test_set_primary_key_with_no_connection
<ide>
<ide> assert_equal 'foo', model.primary_key
<ide> end
<add>
<add> def test_no_primary_key_raises
<add> assert_raises(ActiveRecord::UnknownPrimaryKey) do
<add> Edge.primary_key
<add> end
<add>
<add> begin
<add> Edge.primary_key
<add> rescue ActiveRecord::UnknownPrimaryKey => e
<add> assert e.message.include?('edges')
<add> assert e.message.include?('Edge')
<add> end
<add> end
<ide> end | 12 |
Javascript | Javascript | normalize indentation in parentheses | e0af017a32a8f6824419c390720f8d9ceff94c7f | <ide><path>lib/_tls_legacy.js
<ide> function SecurePair(context, isServer, requestCert, rejectUnauthorized,
<ide> this._rejectUnauthorized = rejectUnauthorized ? true : false;
<ide> this._requestCert = requestCert ? true : false;
<ide>
<del> this.ssl = new Connection(this.credentials.context,
<del> this._isServer ? true : false,
<del> this._isServer ? this._requestCert :
<del> options.servername,
<del> this._rejectUnauthorized);
<add> this.ssl = new Connection(
<add> this.credentials.context,
<add> this._isServer ? true : false,
<add> this._isServer ? this._requestCert : options.servername,
<add> this._rejectUnauthorized
<add> );
<ide>
<ide> if (this._isServer) {
<ide> this.ssl.onhandshakestart = () => onhandshakestart.call(this);
<ide><path>lib/readline.js
<ide> function handleGroup(self, group, width, maxColumns) {
<ide> var item = group[idx];
<ide> self._writeToOutput(item);
<ide> if (col < maxColumns - 1) {
<del> for (var s = 0, itemLen = item.length; s < width - itemLen;
<del> s++) {
<add> for (var s = 0, itemLen = item.length; s < width - itemLen; s++) {
<ide> self._writeToOutput(' ');
<ide> }
<ide> } | 2 |
Javascript | Javascript | add @preventmunge directives to classes | 7b7eddcc720922fb42ba11e2560627ef60184a3a | <ide><path>src/renderers/testing/ReactTestEmptyComponent.js
<ide> * of patent rights can be found in the PATENTS file in the same directory.
<ide> *
<ide> * @providesModule ReactTestEmptyComponent
<add> * @preventMunge
<ide> * @flow
<ide> */
<ide>
<ide> 'use strict';
<ide>
<ide> class ReactTestEmptyComponent {
<ide> _currentElement: null;
<del>
<add>
<ide> constructor() {
<ide> this._currentElement = null;
<ide> }
<ide><path>src/renderers/testing/ReactTestRenderer.js
<ide> * of patent rights can be found in the PATENTS file in the same directory.
<ide> *
<ide> * @providesModule ReactTestRenderer
<add> * @preventMunge
<ide> * @flow
<ide> */
<ide>
<ide><path>src/renderers/testing/ReactTestTextComponent.js
<ide> * of patent rights can be found in the PATENTS file in the same directory.
<ide> *
<ide> * @providesModule ReactTestTextComponent
<add> * @preventMunge
<ide> * @flow
<ide> */
<ide>
<ide> import type { ReactText } from 'ReactTypes';
<ide>
<ide> class ReactTestTextComponent {
<ide> _currentElement: ReactText;
<del>
<add>
<ide> constructor(element: ReactText) {
<ide> this._currentElement = element;
<ide> }
<ide><path>src/test/ReactShallowRenderer.js
<ide> * of patent rights can be found in the PATENTS file in the same directory.
<ide> *
<ide> * @providesModule ReactShallowRenderer
<add> * @preventMunge
<ide> */
<ide>
<ide> 'use strict'; | 4 |
Ruby | Ruby | add broadcaster to publish to redis channels | 5743cf30ff7714c7aa83133b350af22840473733 | <ide><path>lib/action_cable.rb
<ide> module ActionCable
<ide> autoload :Connection, 'action_cable/connection'
<ide> autoload :RemoteConnection, 'action_cable/remote_connection'
<ide> autoload :RemoteConnections, 'action_cable/remote_connections'
<add> autoload :Broadcaster, 'action_cable/broadcaster'
<ide> end
<ide><path>lib/action_cable/broadcaster.rb
<add>module ActionCable
<add> class Broadcaster
<add> attr_reader :server, :channel, :redis
<add> delegate :logger, to: :server
<add>
<add> def initialize(server, channel)
<add> @server = server
<add> @channel = channel
<add> @redis = @server.threaded_redis
<add> end
<add>
<add> def broadcast(message)
<add> redis.publish channel, message.to_json
<add> logger.info "[ActionCable] Broadcasting to channel (#{channel}): #{message}"
<add> end
<add>
<add> end
<add>end
<ide><path>lib/action_cable/server.rb
<ide> def redis
<ide> end
<ide> end
<ide>
<add> def threaded_redis
<add> @threaded_redis ||= Redis.new(redis_config)
<add> end
<add>
<ide> def remote_connections
<ide> @remote_connections ||= RemoteConnections.new(self)
<ide> end
<ide>
<add> def broadcaster_for(channel)
<add> Broadcaster.new(self, channel)
<add> end
<add>
<add> def broadcast(channel, message)
<add> broadcaster_for(channel).broadcast(message)
<add> end
<add>
<ide> def connection_identifiers
<ide> @connection_class.identifiers
<ide> end | 3 |
Javascript | Javascript | remove space at end of line | 76a296cac45b655c0142997da648bc88336fd498 | <ide><path>src/fonts.js
<ide> var Font = (function FontClosure() {
<ide> styleElement = document.createElement('style');
<ide> styleElement.id = 'PDFJS_FONT_STYLE_TAG';
<ide> document.documentElement.getElementsByTagName('head')[0].appendChild(
<del> styleElement);
<add> styleElement);
<ide> }
<ide>
<ide> var styleSheet = styleElement.sheet; | 1 |
Python | Python | fix compatibility for model_builder_test.py | 1b2c67af8a035fa90dc1dc507cdd101df3f5a589 | <ide><path>object_detection/builders/model_builder_test.py
<ide> def test_create_faster_rcnn_resnet_v1_models_from_config(self):
<ide> }"""
<ide> model_proto = model_pb2.DetectionModel()
<ide> text_format.Merge(model_text_proto, model_proto)
<del> for extractor_type, extractor_class in FEATURE_EXTRACTOR_MAPS.iteritems():
<add> for extractor_type, extractor_class in FEATURE_EXTRACTOR_MAPS.items():
<ide> model_proto.faster_rcnn.feature_extractor.type = extractor_type
<ide> model = model_builder.build(model_proto, is_training=True)
<ide> self.assertIsInstance(model, faster_rcnn_meta_arch.FasterRCNNMetaArch)
<ide> def test_create_rfcn_resnet_v1_model_from_config(self):
<ide> }"""
<ide> model_proto = model_pb2.DetectionModel()
<ide> text_format.Merge(model_text_proto, model_proto)
<del> for extractor_type, extractor_class in FEATURE_EXTRACTOR_MAPS.iteritems():
<add> for extractor_type, extractor_class in FEATURE_EXTRACTOR_MAPS.items():
<ide> model_proto.faster_rcnn.feature_extractor.type = extractor_type
<ide> model = model_builder.build(model_proto, is_training=True)
<ide> self.assertIsInstance(model, rfcn_meta_arch.RFCNMetaArch) | 1 |
PHP | PHP | add head method to integrationtestcase | 76ce7f037ae3930462db8d19dd99f0b0555d310a | <ide><path>src/TestSuite/IntegrationTestCase.php
<ide> public function delete($url)
<ide> $this->_sendRequest($url, 'DELETE');
<ide> }
<ide>
<add> /**
<add> * Performs a HEAD request using the current request data.
<add> *
<add> * The response of the dispatched request will be stored as
<add> * a property. You can use various assert methods to check the
<add> * response.
<add> *
<add> * @param string|array $url The URL to request.
<add> * @return void
<add> */
<add> public function head($url)
<add> {
<add> $this->_sendRequest($url, 'HEAD');
<add> }
<add>
<ide> /**
<ide> * Performs an OPTION request using the current request data.
<ide> * | 1 |
Ruby | Ruby | add libepoxy 1.5.4 to whitelist | e704bf7184bb8ab87acbb61dfabce3772bd326a0 | <ide><path>Library/Homebrew/dev-cmd/audit.rb
<ide> def audit_specs
<ide> gtk-mac-integration 2.1.3
<ide> gtk-doc 1.31
<ide> gcab 1.3
<add> libepoxy 1.5.4
<ide> ].each_slice(2).to_a.map do |formula, version|
<ide> [formula, version.split(".")[0..1].join(".")]
<ide> end | 1 |
Javascript | Javascript | update initial worker config values | 2ca7b89846423adbe0d2ec5a98785e02c8523969 | <ide><path>examples/js/loaders/BasisTextureLoader.js
<ide> THREE.BasisTextureLoader = function ( manager ) {
<ide> this.workerConfig = {
<ide> format: null,
<ide> astcSupported: false,
<add> bptcSupported: false,
<ide> etcSupported: false,
<ide> dxtSupported: false,
<ide> pvrtcSupported: false,
<ide> THREE.BasisTextureLoader.prototype = Object.assign( Object.create( THREE.Loader.
<ide> var config = this.workerConfig;
<ide>
<ide> config.astcSupported = !! renderer.extensions.get( 'WEBGL_compressed_texture_astc' );
<add> config.bptcSupported = !! renderer.extensions.get( 'EXT_texture_compression_bptc' );
<ide> config.etcSupported = !! renderer.extensions.get( 'WEBGL_compressed_texture_etc1' );
<ide> config.dxtSupported = !! renderer.extensions.get( 'WEBGL_compressed_texture_s3tc' );
<ide> config.pvrtcSupported = !! renderer.extensions.get( 'WEBGL_compressed_texture_pvrtc' )
<ide> || !! renderer.extensions.get( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
<del> config.bptcSupported = !! renderer.extensions.get( 'EXT_texture_compression_bptc' );
<ide>
<ide> if ( config.astcSupported ) {
<ide>
<ide><path>examples/jsm/loaders/BasisTextureLoader.js
<ide> var BasisTextureLoader = function ( manager ) {
<ide> this.workerConfig = {
<ide> format: null,
<ide> astcSupported: false,
<add> bptcSupported: false,
<ide> etcSupported: false,
<ide> dxtSupported: false,
<ide> pvrtcSupported: false,
<ide> BasisTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ),
<ide> var config = this.workerConfig;
<ide>
<ide> config.astcSupported = !! renderer.extensions.get( 'WEBGL_compressed_texture_astc' );
<add> config.bptcSupported = !! renderer.extensions.get( 'EXT_texture_compression_bptc' );
<ide> config.etcSupported = !! renderer.extensions.get( 'WEBGL_compressed_texture_etc1' );
<ide> config.dxtSupported = !! renderer.extensions.get( 'WEBGL_compressed_texture_s3tc' );
<ide> config.pvrtcSupported = !! renderer.extensions.get( 'WEBGL_compressed_texture_pvrtc' )
<ide> || !! renderer.extensions.get( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
<del> config.bptcSupported = !! renderer.extensions.get( 'EXT_texture_compression_bptc' );
<ide>
<ide> if ( config.astcSupported ) {
<ide> | 2 |
Text | Text | remove duplicate entries [ci skip] | 94ffebab62bb53ff0a5b903ec597d30539cfe047 | <ide><path>guides/source/5_0_release_notes.md
<ide> Please refer to the [Changelog][action-view] for detailed changes.
<ide> * Changed the default template handler from `ERB` to `Raw`.
<ide> ([commit](https://github.com/rails/rails/commit/4be859f0fdf7b3059a28d03c279f03f5938efc80))
<ide>
<del>* Collection rendering can cache and fetches multiple partials.
<add>* Collection rendering can cache and fetches multiple partials at once.
<ide> ([Pull Request](https://github.com/rails/rails/pull/18948),
<ide> [commit](https://github.com/rails/rails/commit/e93f0f0f133717f9b06b1eaefd3442bd0ff43985))
<ide>
<ide> Please refer to the [Changelog][action-view] for detailed changes.
<ide> button on submit to prevent double submits.
<ide> ([Pull Request](https://github.com/rails/rails/pull/21135))
<ide>
<del>* Collection rendering can cache and fetch multiple partials at once.
<del> ([Pull Request](https://github.com/rails/rails/pull/21135))
<del>
<del>
<ide> Action Mailer
<ide> -------------
<ide>
<ide> Please refer to the [Changelog][active-record] for detailed changes.
<ide> * Added `#cache_key` to `ActiveRecord::Relation`.
<ide> ([Pull Request](https://github.com/rails/rails/pull/20884))
<ide>
<del>* Require `belongs_to` by default.
<del> ([Pull Request](https://github.com/rails/rails/pull/18937)) - Deprecate
<del> `required` option in favor of `optional` for `belongs_to`
<del>
<ide> * Changed the default `null` value for `timestamps` to `false`.
<ide> ([commit](https://github.com/rails/rails/commit/a939506f297b667291480f26fa32a373a18ae06a))
<ide>
<ide> Please refer to the [Changelog][active-record] for detailed changes.
<ide>
<ide> * `belongs_to` will now trigger a validation error by default if the
<ide> association is not present. You can turn this off on a per-association basis
<del> with `optional: true`.
<add> with `optional: true`. Also deprecate `required` option in favor of `optional`
<add> for `belongs_to`.
<ide> ([Pull Request](https://github.com/rails/rails/pull/18937))
<ide>
<ide> * Added `config.active_record.dump_schemas` to configure the behavior of | 1 |
PHP | PHP | remove path hint | 33ce7bbb6a7f536036b58b66cc760fbb9eda80de | <ide><path>src/Illuminate/View/Compilers/BladeCompiler.php
<ide> public function compile($path = null)
<ide> $this->files->get($this->getPath())
<ide> );
<ide>
<del> if (! empty($this->getPath())) {
<del> $contents .= "\n<?php /* {$this->getPath()} */ ?>";
<del> }
<del>
<ide> $this->files->put(
<ide> $this->getCompiledPath($this->getPath()), $contents
<ide> );
<ide><path>tests/View/ViewBladeCompilerTest.php
<ide> public function testCompileCompilesFileAndReturnsContents()
<ide> {
<ide> $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__);
<ide> $files->shouldReceive('get')->once()->with('foo')->andReturn('Hello World');
<del> $files->shouldReceive('put')->once()->with(__DIR__.'/'.sha1('foo').'.php', "Hello World\n<?php /* foo */ ?>");
<add> $files->shouldReceive('put')->once()->with(__DIR__.'/'.sha1('foo').'.php', "Hello World");
<ide> $compiler->compile('foo');
<ide> }
<ide>
<ide> public function testCompileCompilesAndGetThePath()
<ide> {
<ide> $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__);
<ide> $files->shouldReceive('get')->once()->with('foo')->andReturn('Hello World');
<del> $files->shouldReceive('put')->once()->with(__DIR__.'/'.sha1('foo').'.php', "Hello World\n<?php /* foo */ ?>");
<add> $files->shouldReceive('put')->once()->with(__DIR__.'/'.sha1('foo').'.php', "Hello World");
<ide> $compiler->compile('foo');
<ide> $this->assertEquals('foo', $compiler->getPath());
<ide> }
<ide> public function testCompileWithPathSetBefore()
<ide> {
<ide> $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__);
<ide> $files->shouldReceive('get')->once()->with('foo')->andReturn('Hello World');
<del> $files->shouldReceive('put')->once()->with(__DIR__.'/'.sha1('foo').'.php', "Hello World\n<?php /* foo */ ?>");
<add> $files->shouldReceive('put')->once()->with(__DIR__.'/'.sha1('foo').'.php', "Hello World");
<ide> // set path before compilation
<ide> $compiler->setPath('foo');
<ide> // trigger compilation with null $path
<ide> public function testIncludePathToTemplate()
<ide> {
<ide> $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__);
<ide> $files->shouldReceive('get')->once()->with('foo')->andReturn('Hello World');
<del> $files->shouldReceive('put')->once()->with(__DIR__.'/'.sha1('foo').'.php', "Hello World\n<?php /* foo */ ?>");
<add> $files->shouldReceive('put')->once()->with(__DIR__.'/'.sha1('foo').'.php', "Hello World");
<ide> $compiler->compile('foo');
<ide> }
<ide> | 2 |
Ruby | Ruby | introduce std_cmake_args method | a13857b15057586d1cfc268708c8112e2999a39b | <ide><path>Library/Homebrew/compat/compatibility.rb
<ide> def self.fails_with_llvm msg=nil, data=nil
<ide> @cc_failures ||= CompilerFailures.new
<ide> @cc_failures << fails_with_llvm_reason
<ide> end
<add>
<add> def std_cmake_parameters
<add> "-DCMAKE_INSTALL_PREFIX='#{prefix}' -DCMAKE_BUILD_TYPE=None -Wno-dev"
<add> end
<ide> end
<ide>
<ide> class UnidentifiedFormula < Formula
<ide><path>Library/Homebrew/formula.rb
<ide> def to_s
<ide> # Setting it to Release would ignore our flags.
<ide> # Note: there isn't a std_autotools variant because autotools is a lot
<ide> # less consistent and the standard parameters are more memorable.
<del> def std_cmake_parameters
<del> "-DCMAKE_INSTALL_PREFIX='#{prefix}' -DCMAKE_BUILD_TYPE=None -Wno-dev"
<add> def std_cmake_args
<add> %W[-DCMAKE_INSTALL_PREFIX=#{prefix} -DCMAKE_BUILD_TYPE=None -Wno-dev]
<ide> end
<ide>
<ide> def self.class_s name | 2 |
Javascript | Javascript | remove usage of styles type | 852084ad454565bb856e85f09e098f1a4a0771a6 | <ide><path>Libraries/StyleSheet/StyleSheet.js
<ide> const flatten = require('flattenStyle');
<ide>
<ide> import type {
<ide> ____StyleSheetInternalStyleIdentifier_Internal as StyleSheetInternalStyleIdentifier,
<del> Styles as _Styles,
<add> ____Styles_Internal,
<ide> ____StyleObj_Internal,
<ide> ____ViewStyleProp_Internal,
<ide> ____TextStyleProp_Internal,
<ide> export type ViewStyleProp = ____ViewStyleProp_Internal;
<ide> export type TextStyleProp = ____TextStyleProp_Internal;
<ide> export type ImageStyleProp = ____ImageStyleProp_Internal;
<ide>
<del>export type Styles = _Styles;
<del>
<ide> let hairlineWidth = PixelRatio.roundToNearestPixel(0.4);
<ide> if (hairlineWidth === 0) {
<ide> hairlineWidth = 1 / PixelRatio.get();
<ide> module.exports = {
<ide> /**
<ide> * Creates a StyleSheet style reference from the given object.
<ide> */
<del> create<+S: Styles>(obj: S): $ObjMap<S, (Object) => StyleSheetInternalStyleIdentifier> {
<add> create<+S: ____Styles_Internal>(obj: S): $ObjMap<S, (Object) => StyleSheetInternalStyleIdentifier> {
<ide> const result = {};
<ide> for (const key in obj) {
<ide> StyleSheetValidation.validateStyle(key, obj);
<ide><path>Libraries/StyleSheet/StyleSheetTypes.js
<ide> export type ____ImageStyleProp_Internal = GenericStyleProp<
<ide> $ReadOnly<$Shape<ImageStyle>>,
<ide> >;
<ide>
<del>export type Styles = {
<add>export type ____Styles_Internal = {
<ide> +[key: string]: $Shape<Style>,
<ide> };
<ide> | 2 |
Javascript | Javascript | resolve deprecation warnings for jasmine | 016c2761dafeb7e131db7253bb3e356fb63ecf7d | <ide><path>test/font/jasmine-boot.js
<ide> function initializePDFJS(callback) {
<ide> },
<ide> });
<ide>
<del> var stoppingOnSpecFailure = queryString.getParam('failFast');
<del> env.stopOnSpecFailure(typeof stoppingOnSpecFailure === 'undefined' ?
<del> false : stoppingOnSpecFailure);
<del>
<del> var throwingExpectationFailures = queryString.getParam('throwFailures');
<del> env.throwOnExpectationFailure(throwingExpectationFailures);
<add> var config = {
<add> failFast: queryString.getParam('failFast'),
<add> oneFailurePerSpec: queryString.getParam('oneFailurePerSpec'),
<add> hideDisabled: queryString.getParam('hideDisabled'),
<add> };
<ide>
<ide> var random = queryString.getParam('random');
<del> env.randomizeTests(random);
<add> if (random !== undefined && random !== '') {
<add> config.random = random;
<add> }
<ide>
<ide> var seed = queryString.getParam('seed');
<ide> if (seed) {
<del> env.seed(seed);
<add> config.seed = seed;
<ide> }
<ide>
<ide> // Reporters
<ide> var htmlReporter = new jasmine.HtmlReporter({
<ide> env,
<del> onStopExecutionClick() {
<del> queryString.navigateWithNewParam('failFast',
<del> env.stoppingOnSpecFailure());
<del> },
<del> onThrowExpectationsClick() {
<del> queryString.navigateWithNewParam('throwFailures',
<del> !env.throwingExpectationFailures());
<del> },
<del> onRandomClick() {
<del> queryString.navigateWithNewParam('random', !env.randomTests());
<add> navigateWithNewParam(key, value) {
<add> return queryString.navigateWithNewParam(key, value);
<ide> },
<ide> addToExistingQueryString(key, value) {
<ide> return queryString.fullStringWithNewParam(key, value);
<ide> function initializePDFJS(callback) {
<ide> },
<ide> });
<ide>
<del> env.specFilter = function(spec) {
<add> config.specFilter = function(spec) {
<ide> return specFilter.matches(spec.getFullName());
<ide> };
<ide>
<add> env.configure(config);
<add>
<ide> // Sets longer timeout.
<ide> jasmine.DEFAULT_TIMEOUT_INTERVAL = 30000;
<ide>
<ide><path>test/unit/jasmine-boot.js
<ide> function initializePDFJS(callback) {
<ide> },
<ide> });
<ide>
<del> var stoppingOnSpecFailure = queryString.getParam('failFast');
<del> env.stopOnSpecFailure(typeof stoppingOnSpecFailure === 'undefined' ?
<del> false : stoppingOnSpecFailure);
<del>
<del> var throwingExpectationFailures = queryString.getParam('throwFailures');
<del> env.throwOnExpectationFailure(throwingExpectationFailures);
<add> var config = {
<add> failFast: queryString.getParam('failFast'),
<add> oneFailurePerSpec: queryString.getParam('oneFailurePerSpec'),
<add> hideDisabled: queryString.getParam('hideDisabled'),
<add> };
<ide>
<ide> var random = queryString.getParam('random');
<del> env.randomizeTests(random);
<add> if (random !== undefined && random !== '') {
<add> config.random = random;
<add> }
<ide>
<ide> var seed = queryString.getParam('seed');
<ide> if (seed) {
<del> env.seed(seed);
<add> config.seed = seed;
<ide> }
<ide>
<ide> // Reporters
<ide> var htmlReporter = new jasmine.HtmlReporter({
<ide> env,
<del> onStopExecutionClick() {
<del> queryString.navigateWithNewParam('failFast',
<del> env.stoppingOnSpecFailure());
<del> },
<del> onThrowExpectationsClick() {
<del> queryString.navigateWithNewParam('throwFailures',
<del> !env.throwingExpectationFailures());
<del> },
<del> onRandomClick() {
<del> queryString.navigateWithNewParam('random', !env.randomTests());
<add> navigateWithNewParam(key, value) {
<add> return queryString.navigateWithNewParam(key, value);
<ide> },
<ide> addToExistingQueryString(key, value) {
<ide> return queryString.fullStringWithNewParam(key, value);
<ide> function initializePDFJS(callback) {
<ide> },
<ide> });
<ide>
<del> env.specFilter = function(spec) {
<add> config.specFilter = function(spec) {
<ide> return specFilter.matches(spec.getFullName());
<ide> };
<ide>
<add> env.configure(config);
<add>
<ide> // Sets longer timeout.
<ide> jasmine.DEFAULT_TIMEOUT_INTERVAL = 30000;
<ide> | 2 |
Go | Go | expand hostname before passing it to newregistry() | 676308b853a43bb7be4838e937ab4effff670b1a | <ide><path>registry/service.go
<ide> func (s *Service) Search(job *engine.Job) engine.Status {
<ide> if err != nil {
<ide> return job.Error(err)
<ide> }
<del> r, err := NewSession(authConfig, HTTPRequestFactory(metaHeaders), IndexServerAddress(), true)
<add> r, err := NewSession(authConfig, HTTPRequestFactory(metaHeaders), hostname, true)
<ide> if err != nil {
<ide> return job.Error(err)
<ide> } | 1 |
Javascript | Javascript | remove workaround for function redefinition | 007386ee81ceeffd65c2248869717b0717db3e46 | <ide><path>lib/repl.js
<ide> function REPLServer(prompt,
<ide> // an expression.
<ide> cmd = `(${cmd})`;
<ide> self.wrappedCmd = true;
<del> } else {
<del> // Mitigate https://github.com/nodejs/node/issues/548
<del> cmd = cmd.replace(
<del> /^\s*function(?:\s*(\*)\s*|\s+)([^(]+)/,
<del> (_, genStar, name) => `var ${name} = function ${genStar || ''}${name}`
<del> );
<ide> }
<ide> // Append a \n so that it will be either
<ide> // terminated, or continued onto the next expression if it's an | 1 |
Python | Python | fix fp16 transformer model. | 58340818e4aa9becc5f38e51287d1d7ab7800046 | <ide><path>official/transformer/model/beam_search.py
<ide> https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/utils/beam_search.py
<ide> """
<ide>
<add>import numpy as np
<ide> import tensorflow as tf
<ide> from tensorflow.python.util import nest
<ide>
<del># Default value for INF
<del>INF = 1. * 1e7
<add>
<add>def inf(dtype):
<add> """Returns a value close to infinity, but is still finite in `dtype`.
<add>
<add> This is useful to get a very large value that is still zero when multiplied by
<add> zero. The floating-point "Inf" value is NaN when multiplied by zero.
<add>
<add> Args:
<add> dtype: A dtype. The returned value will be finite when casted to this dtype.
<add>
<add> Returns:
<add> A very large value.
<add> """
<add> if dtype == "float32":
<add> return 1e7
<add> elif dtype == "float16":
<add> # Disable no-member lint error, as the linter thinks np.float16 does not
<add> # exist for some reason.
<add> return np.finfo(np.float16).max # pylint: disable=no-member
<add> else:
<add> raise AssertionError('Invalid dtype: %s' % dtype)
<ide>
<ide>
<ide> class _StateKeys(object):
<ide> class SequenceBeamSearch(object):
<ide> """Implementation of beam search loop."""
<ide>
<ide> def __init__(self, symbols_to_logits_fn, vocab_size, batch_size,
<del> beam_size, alpha, max_decode_length, eos_id):
<add> beam_size, alpha, max_decode_length, eos_id, dtype=tf.float32):
<ide> self.symbols_to_logits_fn = symbols_to_logits_fn
<ide> self.vocab_size = vocab_size
<ide> self.batch_size = batch_size
<ide> self.beam_size = beam_size
<ide> self.alpha = alpha
<ide> self.max_decode_length = max_decode_length
<ide> self.eos_id = eos_id
<add> self.dtype = tf.as_dtype(dtype)
<ide>
<ide> def search(self, initial_ids, initial_cache):
<ide> """Beam search for sequences with highest scores."""
<ide> def _create_initial_state(self, initial_ids, initial_cache):
<ide> Returns:
<ide> state and shape invariant dictionaries with keys from _StateKeys
<ide> """
<add> for key, value in initial_cache.items():
<add> for inner_value in nest.flatten(value):
<add> if inner_value.dtype != self.dtype:
<add> raise TypeError(
<add> "initial_cache element for key '%s' has dtype %s that does not "
<add> "match SequenceBeamSearch's dtype of %s. Value: %s" %
<add> (key, value.dtype.name, self.dtype.name, inner_value))
<add>
<ide> # Current loop index (starts at 0)
<ide> cur_index = tf.constant(0)
<ide>
<ide> def _create_initial_state(self, initial_ids, initial_cache):
<ide> # Create tensor for storing initial log probabilities.
<ide> # Assume initial_ids are prob 1.0
<ide> initial_log_probs = tf.constant(
<del> [[0.] + [-float("inf")] * (self.beam_size - 1)])
<add> [[0.] + [-float("inf")] * (self.beam_size - 1)], dtype=self.dtype)
<ide> alive_log_probs = tf.tile(initial_log_probs, [self.batch_size, 1])
<ide>
<ide> # Expand all values stored in the dictionary to the beam size, so that each
<ide> def _create_initial_state(self, initial_ids, initial_cache):
<ide> finished_seq = tf.zeros(tf.shape(alive_seq), tf.int32)
<ide>
<ide> # Set scores of the initial finished seqs to negative infinity.
<del> finished_scores = tf.ones([self.batch_size, self.beam_size]) * -INF
<add> finished_scores = tf.ones([self.batch_size, self.beam_size],
<add> dtype=self.dtype) * -inf(self.dtype)
<ide>
<ide> # Initialize finished flags with all False values.
<ide> finished_flags = tf.zeros([self.batch_size, self.beam_size], tf.bool)
<ide> def _continue_search(self, state):
<ide> not_at_max_decode_length = tf.less(i, self.max_decode_length)
<ide>
<ide> # Calculate largest length penalty (the larger penalty, the better score).
<del> max_length_norm = _length_normalization(self.alpha, self.max_decode_length)
<add> max_length_norm = _length_normalization(self.alpha, self.max_decode_length,
<add> dtype=self.dtype)
<ide> # Get the best possible scores from alive sequences.
<ide> best_alive_scores = alive_log_probs[:, 0] / max_length_norm
<ide>
<ide> # Compute worst score in finished sequences for each batch element
<ide> finished_scores *= tf.cast(finished_flags,
<del> tf.float32) # set filler scores to zero
<add> self.dtype) # set filler scores to zero
<ide> lowest_finished_scores = tf.reduce_min(finished_scores, axis=1)
<ide>
<ide> # If there are no finished sequences in a batch element, then set the lowest
<ide> # finished score to -INF for that element.
<ide> finished_batches = tf.reduce_any(finished_flags, 1)
<del> lowest_finished_scores += (1.0 -
<del> tf.cast(finished_batches, tf.float32)) * -INF
<add> lowest_finished_scores += ((1.0 -
<add> tf.cast(finished_batches, self.dtype)) *
<add> -inf(self.dtype))
<ide>
<ide> worst_finished_score_better_than_best_alive_score = tf.reduce_all(
<ide> tf.greater(lowest_finished_scores, best_alive_scores)
<ide> def _get_new_alive_state(self, new_seq, new_log_probs, new_cache):
<ide> Log probabilities of top alive sequences
<ide> Dict cache storing decoder states for top alive sequences}
<ide> """
<del> # To prevent finished sequences from being considered, set log probs to -INF
<add> # To prevent finished sequences from being considered, set log probs to -inf
<ide> new_finished_flags = tf.equal(new_seq[:, :, -1], self.eos_id)
<del> new_log_probs += tf.cast(new_finished_flags, tf.float32) * -INF
<add> new_log_probs += tf.cast(new_finished_flags, self.dtype) * -inf(self.dtype)
<ide>
<ide> top_alive_seq, top_alive_log_probs, top_alive_cache = _gather_topk_beams(
<ide> [new_seq, new_log_probs, new_cache], new_log_probs, self.batch_size,
<ide> def _get_new_finished_state(self, state, new_seq, new_log_probs):
<ide> tf.zeros([self.batch_size, self.beam_size, 1], tf.int32)], axis=2)
<ide>
<ide> # Calculate new seq scores from log probabilities.
<del> length_norm = _length_normalization(self.alpha, i + 1)
<add> length_norm = _length_normalization(self.alpha, i + 1, dtype=self.dtype)
<ide> new_scores = new_log_probs / length_norm
<ide>
<ide> # Set the scores of the still-alive seq in new_seq to large negative values.
<ide> new_finished_flags = tf.equal(new_seq[:, :, -1], self.eos_id)
<del> new_scores += (1. - tf.cast(new_finished_flags, tf.float32)) * -INF
<add> new_scores += ((1. - tf.cast(new_finished_flags, self.dtype)) *
<add> -inf(self.dtype))
<ide>
<ide> # Combine sequences, scores, and flags.
<ide> finished_seq = tf.concat([finished_seq, new_seq], axis=1)
<ide> def _log_prob_from_logits(logits):
<ide> return logits - tf.reduce_logsumexp(logits, axis=2, keepdims=True)
<ide>
<ide>
<del>def _length_normalization(alpha, length):
<add>def _length_normalization(alpha, length, dtype=tf.float32):
<ide> """Return length normalization factor."""
<del> return tf.pow(((5. + tf.cast(length, tf.float32)) / 6.), alpha)
<add> return tf.pow(((5. + tf.cast(length, dtype)) / 6.), alpha)
<ide>
<ide>
<ide> def _expand_to_beam_size(tensor, beam_size):
<ide><path>official/transformer/v2/beam_search.py
<ide> def search(self, initial_ids, initial_cache):
<ide>
<ide> def sequence_beam_search(
<ide> symbols_to_logits_fn, initial_ids, initial_cache, vocab_size, beam_size,
<del> alpha, max_decode_length, eos_id):
<add> alpha, max_decode_length, eos_id, dtype="float32"):
<ide> """Search for sequence of subtoken ids with the largest probability.
<ide>
<ide> Args:
<ide> def sequence_beam_search(
<ide> beam_size: int number of beams
<ide> alpha: float defining the strength of length normalization
<ide> max_decode_length: maximum length to decoded sequence
<del> eos_id: int id of eos token, used to determine when a sequence has finished
<add> eos_id: int id of eos token, used to determine when a sequence has finished,
<add> dtype: The dtype to use.
<ide>
<ide> Returns:
<ide> Top decoded sequences [batch_size, beam_size, max_decode_length]
<ide> def sequence_beam_search(
<ide> batch_size = tf.shape(initial_ids)[0]
<ide> if misc.is_v2():
<ide> sbs = SequenceBeamSearchV2(symbols_to_logits_fn, vocab_size, batch_size,
<del> beam_size, alpha, max_decode_length, eos_id)
<add> beam_size, alpha, max_decode_length, eos_id,
<add> dtype)
<ide> else:
<ide> sbs = v1.SequenceBeamSearch(symbols_to_logits_fn, vocab_size, batch_size,
<del> beam_size, alpha, max_decode_length, eos_id)
<add> beam_size, alpha, max_decode_length, eos_id,
<add> dtype)
<ide> return sbs.search(initial_ids, initial_cache)
<ide>
<ide>
<ide><path>official/transformer/v2/embedding_layer.py
<ide> class EmbeddingSharedWeights(tf.keras.layers.Layer):
<ide> """Calculates input embeddings and pre-softmax linear with shared weights."""
<ide>
<del> def __init__(self, vocab_size, hidden_size):
<add> def __init__(self, vocab_size, hidden_size, dtype=None):
<ide> """Specify characteristic parameters of embedding layer.
<ide>
<ide> Args:
<ide> vocab_size: Number of tokens in the embedding. (Typically ~32,000)
<ide> hidden_size: Dimensionality of the embedding. (Typically 512 or 1024)
<add> dtype: The dtype of the layer: float16 or float32.
<ide> """
<del> super(EmbeddingSharedWeights, self).__init__()
<add> if dtype == tf.float16:
<add> # We cannot rely on the global policy of "infer_with_float32_vars", as
<add> # this layer is called on both int64 inputs and floating-point inputs.
<add> # If "infer_with_float32_vars" is used, the dtype will be inferred to be
<add> # int64, which means floating-point inputs would not be casted.
<add> # TODO(b/138859351): Remove this logic once we stop using the deprecated
<add> # "infer_with_float32_vars" policy
<add> dtype = tf.keras.mixed_precision.experimental.Policy(
<add> "float16_with_float32_vars")
<add> super(EmbeddingSharedWeights, self).__init__(dtype=dtype)
<ide> self.vocab_size = vocab_size
<ide> self.hidden_size = hidden_size
<ide>
<ide> def _embedding(self, inputs):
<ide> """Applies embedding based on inputs tensor."""
<ide> with tf.name_scope("embedding"):
<ide> # Create binary mask of size [batch_size, length]
<del> mask = tf.cast(tf.not_equal(inputs, 0), tf.float32)
<ide> embeddings = tf.gather(self.shared_weights, inputs)
<add> mask = tf.cast(tf.not_equal(inputs, 0), embeddings.dtype)
<ide> embeddings *= tf.expand_dims(mask, -1)
<ide> # Scale embedding by the sqrt of the hidden size
<ide> embeddings *= self.hidden_size ** 0.5
<ide><path>official/transformer/v2/transformer.py
<ide> from official.transformer.v2 import metrics
<ide>
<ide>
<add># Disable the not-callable lint error, since it claims many objects are not
<add># callable when they actually are.
<add># pylint: disable=not-callable
<add>
<add>
<ide> def create_model(params, is_train):
<ide> """Creates transformer model."""
<ide> with tf.name_scope("model"):
<ide> def __init__(self, params, name=None):
<ide> super(Transformer, self).__init__(name=name)
<ide> self.params = params
<ide> self.embedding_softmax_layer = embedding_layer.EmbeddingSharedWeights(
<del> params["vocab_size"], params["hidden_size"])
<add> params["vocab_size"], params["hidden_size"], dtype=params["dtype"])
<ide> self.encoder_stack = EncoderStack(params)
<ide> self.decoder_stack = DecoderStack(params)
<ide>
<ide> def _get_symbols_to_logits_fn(self, max_decode_length, training):
<ide>
<ide> timing_signal = model_utils.get_position_encoding(
<ide> max_decode_length + 1, self.params["hidden_size"])
<add> timing_signal = tf.cast(timing_signal, self.params["dtype"])
<ide> decoder_self_attention_bias = model_utils.get_decoder_self_attention_bias(
<del> max_decode_length)
<add> max_decode_length, dtype=self.params["dtype"])
<ide>
<ide> def symbols_to_logits_fn(ids, i, cache):
<ide> """Generate logits for next potential IDs.
<ide> def symbols_to_logits_fn(ids, i, cache):
<ide>
<ide> def predict(self, encoder_outputs, encoder_decoder_attention_bias, training):
<ide> """Return predicted sequence."""
<del> # Currently, we always do prediction in float32.
<del> # TODO(reedwm): Add float16 support.
<del> encoder_outputs = tf.cast(encoder_outputs, tf.float32)
<ide> batch_size = tf.shape(encoder_outputs)[0]
<ide> input_length = tf.shape(encoder_outputs)[1]
<ide> max_decode_length = input_length + self.params["extra_decode_length"]
<add> encoder_decoder_attention_bias = tf.cast(encoder_decoder_attention_bias,
<add> self.params["dtype"])
<ide>
<ide> symbols_to_logits_fn = self._get_symbols_to_logits_fn(
<ide> max_decode_length, training)
<ide> def predict(self, encoder_outputs, encoder_decoder_attention_bias, training):
<ide> # pylint: disable=g-complex-comprehension
<ide> cache = {
<ide> "layer_%d" % layer: {
<del> "k": tf.zeros([batch_size, 0, self.params["hidden_size"]]),
<del> "v": tf.zeros([batch_size, 0, self.params["hidden_size"]])
<add> "k": tf.zeros([batch_size, 0, self.params["hidden_size"]],
<add> dtype=self.params["dtype"]),
<add> "v": tf.zeros([batch_size, 0, self.params["hidden_size"]],
<add> dtype=self.params["dtype"])
<ide> } for layer in range(self.params["num_hidden_layers"])
<ide> }
<ide> # pylint: enable=g-complex-comprehension
<ide> def predict(self, encoder_outputs, encoder_decoder_attention_bias, training):
<ide> beam_size=self.params["beam_size"],
<ide> alpha=self.params["alpha"],
<ide> max_decode_length=max_decode_length,
<del> eos_id=EOS_ID)
<add> eos_id=EOS_ID,
<add> dtype=self.params["dtype"])
<ide>
<ide> # Get the top sequence for each batch element
<ide> top_decoded_ids = decoded_ids[:, 0, 1:]
<ide><path>official/transformer/v2/transformer_main_test.py
<ide> def test_train_1_gpu_with_dist_strat(self):
<ide> t = tm.TransformerTask(FLAGS)
<ide> t.train()
<ide>
<add> @unittest.skipUnless(tf.test.is_built_with_cuda(), 'requires GPU')
<add> def test_train_fp16(self):
<add> FLAGS.dtype = 'fp16'
<add> t = tm.TransformerTask(FLAGS)
<add> t.train()
<add>
<ide> @unittest.skipUnless(tf.test.is_built_with_cuda(), 'requires GPU')
<ide> def test_train_2_gpu(self):
<ide> if context.num_gpus() < 2: | 5 |
Text | Text | add a note about default_scope and create records | 2ef1de02ed2e19638aebdbca1aea209a7591b5fe | <ide><path>guides/source/active_record_querying.md
<ide> class Client < ActiveRecord::Base
<ide> end
<ide> ```
<ide>
<add>NOTE: The `default_scope` is also applied while creating/building a record.
<add>It is not applied while updating a record. E.g.:
<add>
<add>```ruby
<add>class Client < ActiveRecord::Base
<add> default_scope { where(active: true) }
<add>end
<add>
<add>Client.new # => #<Client id: nil, active: true>
<add>Client.unscoped.new # => #<Client id: nil, active: nil>
<add>```
<add>
<ide> ### Merging of scopes
<ide>
<ide> Just like `where` clauses scopes are merged using `AND` conditions. | 1 |
PHP | PHP | use anevent when creating the view | 74f1784564cb38a2afbf79d86ffb91b9eaaf6474 | <ide><path>src/Shell/Task/TemplateTask.php
<ide> use Cake\Core\App;
<ide> use Cake\Core\ConventionsTrait;
<ide> use Cake\Core\Plugin;
<add>use Cake\Event\Event;
<add>use Cake\Event\EventManager;
<ide> use Cake\Filesystem\Folder;
<ide> use Cake\Network\Request;
<ide> use Cake\Network\Response;
<ide> class TemplateTask extends Shell {
<ide>
<ide> use ConventionsTrait;
<ide>
<del> use ViewVarsTrait {
<del> getView as _getView;
<del> }
<add> use ViewVarsTrait;
<ide>
<ide> /**
<ide> * BakeView instance
<ide> class TemplateTask extends Shell {
<ide> */
<ide> public $View;
<ide>
<del>/**
<del> * Which view class to use for baking
<del> *
<del> * @var string
<del> */
<del> public $viewClass = 'Cake\View\BakeView';
<del>
<del>/**
<del> * An array containing the names of helpers to use when baking
<del> *
<del> * Example: `public $helpers = ['Bake', 'BakePlusPlus'];`
<del> *
<del> * @var array
<del> */
<del> public $helpers = [
<del> 'Bake',
<del> ];
<del>
<del>/**
<del> * The bake theme to use
<del> *
<del> * @var string
<del> */
<del> public $theme = '';
<del>
<del>/**
<del> * These properties will be passed from the template task to the View as options.
<del> *
<del> * @var array
<del> * @see \Cake\View\View
<del> */
<del> protected $_validViewOptions = ['helpers', 'theme'];
<del>
<ide> /**
<ide> * Get view instance
<ide> *
<ide> public function getView() {
<ide> return $this->View;
<ide> }
<ide>
<del> $this->theme = isset($this->params['template']) ? $this->params['template'] : '';
<add> $theme = isset($this->params['template']) ? $this->params['template'] : '';
<add>
<add> $viewOptions = [
<add> 'helpers' => ['Bake'],
<add> 'theme' => $theme
<add> ];
<add> $view = new BakeView(new Request(), new Response(), null, $viewOptions);
<add> $event = new Event('Bake.initialize', $view);
<add> EventManager::instance()->dispatch($event);
<add> $this->View = $event->subject;
<ide>
<del> return $this->_getView();
<add> return $this->View;
<ide> }
<ide>
<ide> /**
<ide> public function getView() {
<ide> * @throws \Cake\View\Exception\MissingViewException If view class was not found.
<ide> */
<ide> public function createView($viewClass = null) {
<del> if ($viewClass === null) {
<del> $viewClass = $this->viewClass;
<del> }
<del> $className = App::className($viewClass, 'View');
<del> if (!$className) {
<del> throw new Exception\MissingViewException([$viewClass]);
<del> }
<del> return new $className(new Request(), new Response());
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/Shell/Task/ControllerTaskTest.php
<ide> public function setUp() {
<ide> $this->Task->connection = 'test';
<ide>
<ide> $this->Task->Template = new TemplateTask($io);
<del> $this->Task->Template->params['theme'] = 'default';
<ide>
<ide> $this->Task->Model = $this->getMock('Cake\Shell\Task\ModelTask',
<ide> array('in', 'out', 'err', 'createFile', '_stop'),
<ide><path>tests/TestCase/Shell/Task/ViewTaskTest.php
<ide> protected function _setupTask($methods) {
<ide> );
<ide> $this->Task->Template = new TemplateTask($io);
<ide> $this->Task->Model = $this->getMock('Cake\Shell\Task\ModelTask', [], [$io]);
<del>
<del> $this->Task->Template->params['template'] = 'default';
<del> $this->Task->Template->templatePaths = ['default' => CAKE . 'Template/Bake/default/'];
<ide> }
<ide>
<ide> /** | 3 |
PHP | PHP | remove code related to "disabledfields" config | 790b07a27cc0fd5fff6e776e1581c68ce8ba4ad0 | <ide><path>src/Controller/Component/SecurityComponent.php
<ide> protected function _fieldsList(array $check): array
<ide> }
<ide>
<ide> $unlockedFields = array_unique(
<del> array_merge((array)$this->getConfig('disabledFields'), (array)$this->_config['unlockedFields'], $unlocked)
<add> array_merge(
<add> (array)$this->_config['unlockedFields'],
<add> $unlocked
<add> )
<ide> );
<ide>
<ide> /** @var (string|int)[] $fieldList */
<ide><path>tests/TestCase/Controller/Component/SecurityComponentTest.php
<ide> public function testValidatePostHidden(): void
<ide> $this->assertNull($result);
<ide> }
<ide>
<del> /**
<del> * testValidatePostWithDisabledFields method
<del> *
<del> * @return void
<del> * @triggers Controller.startup $this->Controller
<del> */
<del> public function testValidatePostWithDisabledFields(): void
<del> {
<del> $event = new Event('Controller.startup', $this->Controller);
<del> $this->Security->setConfig('disabledFields', ['Model.username', 'Model.password']);
<del> $this->Security->startup($event);
<del> $fields = '0313460e1136e1227044399fe10a6edc0cbca279%3AModel.hidden';
<del> $unlocked = '';
<del> $debug = 'not used';
<del>
<del> $this->Controller->setRequest($this->Controller->getRequest()->withParsedBody([
<del> 'Model' => [
<del> 'username' => '', 'password' => '', 'hidden' => '0',
<del> ],
<del> '_Token' => compact('fields', 'unlocked', 'debug'),
<del> ]));
<del>
<del> $result = $this->validatePost();
<del> $this->assertNull($result);
<del> }
<del>
<ide> /**
<ide> * testValidatePostDisabledFieldsInData method
<ide> *
<ide> public function testValidateHasManyRecordsFail(): void
<ide> $this->assertFalse($result);
<ide> }
<ide>
<del> /**
<del> * testFormDisabledFields method
<del> *
<del> * @return void
<del> * @triggers Controller.startup $this->Controller
<del> */
<del> public function testFormDisabledFields(): void
<del> {
<del> $event = new Event('Controller.startup', $this->Controller);
<del>
<del> $this->Security->startup($event);
<del> $fields = '4eaf5c6b93d5140c24171d5fdce16ed5b904f288%3An%3A0%3A%7B%7D';
<del> $unlocked = '';
<del> $debug = urlencode(json_encode([
<del> '/articles/index',
<del> [],
<del> [],
<del> ]));
<del>
<del> $this->Controller->setRequest($this->Controller->getRequest()->withParsedBody([
<del> 'MyModel' => ['name' => 'some data'],
<del> '_Token' => compact('fields', 'unlocked', 'debug'),
<del> ]));
<del> $result = $this->validatePost('SecurityException', 'Unexpected field \'MyModel.name\' in POST data');
<del> $this->assertFalse($result);
<del>
<del> $this->Security->startup($event);
<del> $this->Security->setConfig('disabledFields', ['MyModel.name']);
<del>
<del> $this->Controller->setRequest($this->Controller->getRequest()->withParsedBody([
<del> 'MyModel' => ['name' => 'some data'],
<del> '_Token' => compact('fields', 'unlocked', 'debug'),
<del> ]));
<del>
<del> $result = $this->validatePost();
<del> $this->assertNull($result);
<del> }
<del>
<ide> /**
<ide> * testValidatePostRadio method
<ide> * | 2 |
Text | Text | update readme to latest beta version | 8487375730a0c932792a6b8b52922cfc875771ac | <ide><path>README.md
<ide>
<ide> ## v2.0 Beta
<ide>
<del>Current Release: [2.0.0-beta](https://github.com/nnnick/Chart.js/releases/tag/2.0.0-beta)
<add>Current Release: [2.0.0-beta2](https://github.com/nnnick/Chart.js/releases/tag/2.0.0-beta2)
<ide>
<ide> The next generation and release of Chart.js has been well under way this year and we are very close to releasing some amazing new features including, but not limited to:
<ide> - Rewritten, optimized, and unit-tested | 1 |
Text | Text | add v2.17.0-beta.1 to changelog | 70a3d879b8b7a64b7bf11da5479fd3dfc6191241 | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### 2.17.0-beta.1 (October 9, 2017)
<add>
<add>- [#15265](https://github.com/emberjs/ember.js/pull/15265) [BUGFIX] fixed issue when passing `false` to `activeClass` for `{{link-to}}`
<add>- [#15672](https://github.com/emberjs/ember.js/pull/15672) Update router_js to 2.0.0.
<add>
<ide> ### 2.16.0 (October 9, 2017)
<ide>
<ide> - [#15604](https://github.com/emberjs/ember.js/pull/15604) Data Adapter: Only trigger model type update if the record live array count actually changed | 1 |
Go | Go | allow dot in repo name | d61fce9af770f0adaf4f178a5217dd46a02dd201 | <ide><path>registry/registry.go
<ide> func ResolveRepositoryName(reposName string) (string, string, error) {
<ide> return "", "", ErrInvalidRepositoryName
<ide> }
<ide> nameParts := strings.SplitN(reposName, "/", 2)
<del> if !strings.Contains(nameParts[0], ".") && !strings.Contains(nameParts[0], ":") &&
<del> nameParts[0] != "localhost" {
<add> if len(nameParts) == 1 || (!strings.Contains(nameParts[0], ".") && !strings.Contains(nameParts[0], ":") &&
<add> nameParts[0] != "localhost") {
<ide> // This is a Docker Index repos (ex: samalba/hipache or ubuntu)
<ide> err := validateRepositoryName(reposName)
<ide> return IndexServerAddress(), reposName, err
<ide> }
<del> if len(nameParts) < 2 {
<del> // There is a dot in repos name (and no registry address)
<del> // Is it a Registry address without repos name?
<del> return "", "", ErrInvalidRepositoryName
<del> }
<ide> hostname := nameParts[0]
<ide> reposName = nameParts[1]
<ide> if strings.Contains(hostname, "index.docker.io") {
<ide><path>registry/registry_test.go
<ide> func TestResolveRepositoryName(t *testing.T) {
<ide> }
<ide> assertEqual(t, ep, u, "Expected endpoint to be "+u)
<ide> assertEqual(t, repo, "private/moonbase", "Expected endpoint to be private/moonbase")
<add>
<add> ep, repo, err = ResolveRepositoryName("ubuntu-12.04-base")
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> assertEqual(t, ep, IndexServerAddress(), "Expected endpoint to be "+IndexServerAddress())
<add> assertEqual(t, repo, "ubuntu-12.04-base", "Expected endpoint to be ubuntu-12.04-base")
<ide> }
<ide>
<ide> func TestPushRegistryTag(t *testing.T) { | 2 |
Text | Text | add metrics docs to cli reference | 66c2549be33213fa333457d090ada506ef39c5bb | <ide><path>docs/reference/commandline/dockerd.md
<ide> Options:
<ide> --log-opt value Default log driver options for containers (default map[])
<ide> --max-concurrent-downloads int Set the max concurrent downloads for each pull (default 3)
<ide> --max-concurrent-uploads int Set the max concurrent uploads for each push (default 5)
<add> --metrics-addr string Set address and port to serve the metrics api (default "")
<ide> --mtu int Set the containers network MTU
<ide> --oom-score-adjust int Set the oom_score_adj for the daemon (default -500)
<ide> -p, --pidfile string Path to use for daemon PID file (default "/var/run/docker.pid")
<ide> This setting can also be set per container, using the `--cgroup-parent`
<ide> option on `docker create` and `docker run`, and takes precedence over
<ide> the `--cgroup-parent` option on the daemon.
<ide>
<add>## Daemon Metrics
<add>
<add>The `--metrics-addr` option takes a tcp address to serve the metrics API.
<add>This feature is still experimental, therefore, the daemon must be running in experimental
<add>mode for this feature to work.
<add>
<add>To serve the metrics API on localhost:1337 you would specify `--metrics-addr 127.0.0.1:1337`
<add>allowing you to make requests on the API at `127.0.0.1:1337/metrics` to receive metrics in the
<add>[prometheus](https://prometheus.io/docs/instrumenting/exposition_formats/) format.
<add>
<add>If you are running a prometheus server you can add this address to your scrape configs
<add>to have prometheus collect metrics on Docker. For more information
<add>on prometheus you can view the website [here](https://prometheus.io/).
<add>
<add>```yml
<add>scrape_configs:
<add> - job_name: 'docker'
<add> static_configs:
<add> - targets: ['127.0.0.1:1337']
<add>```
<add>
<add>Please note that this feature is still marked as experimental as metrics and metric
<add>names could change while this feature is still in experimental. Please provide
<add>feedback on what you would like to see collected in the API.
<add>
<ide> ## Daemon configuration file
<ide>
<ide> The `--config-file` option allows you to set any configuration option | 1 |
Python | Python | set version to v2.2.0.dev9 | eced2f32116df0b01c423cb169d7d2c775b46597 | <ide><path>spacy/about.py
<ide> # fmt: off
<ide> __title__ = "spacy"
<del>__version__ = "2.2.0.dev8"
<add>__version__ = "2.2.0.dev9"
<ide> __summary__ = "Industrial-strength Natural Language Processing (NLP) in Python"
<ide> __uri__ = "https://spacy.io"
<ide> __author__ = "Explosion" | 1 |
PHP | PHP | remove unnecessary loadfixtures() calls | 75882507bc75e04736cebf2b42c21a5da32d62d4 | <ide><path>lib/Cake/Test/Case/Model/Behavior/TreeBehaviorNumberTest.php
<ide> public function testArraySyntax() {
<ide> * @return void
<ide> */
<ide> public function testFindThreaded() {
<del> $this->loadFixtures('Person');
<ide> $Model = new Person();
<ide> $Model->recursive = -1;
<ide> $Model->Behaviors->attach('Tree', array('parent' => 'mother_id'));
<ide><path>lib/Cake/Test/Case/Model/BehaviorCollectionTest.php
<ide> public function testBehaviorMethodDispatchingWithData() {
<ide> * @return void
<ide> */
<ide> public function testBindModelCallsInBehaviors() {
<del> $this->loadFixtures('Article', 'Comment');
<del>
<ide> // hasMany
<ide> $Article = new Article();
<ide> $Article->unbindModel(array('hasMany' => array('Comment'))); | 2 |
Java | Java | add check for long.max_value | cd476832cc23e9b52b7d3d7d194ff9e33b734224 | <ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/AbstractListenerReadPublisher.java
<ide> public final void onError(Throwable t) {
<ide> * @return {@code true} if there is more demand; {@code false} otherwise
<ide> */
<ide> private boolean readAndPublish() throws IOException {
<del> while (hasDemand()) {
<add> long r;
<add> while ((r = demand) > 0) {
<ide> T data = read();
<ide> if (data != null) {
<del> Operators.addAndGet(DEMAND_FIELD_UPDATER, this, -1L);
<add> if (r != Long.MAX_VALUE) {
<add> DEMAND_FIELD_UPDATER.addAndGet(this, -1L);
<add> }
<ide> this.subscriber.onNext(data);
<ide> }
<ide> else {
<ide> private boolean readAndPublish() throws IOException {
<ide> return false;
<ide> }
<ide>
<del> private boolean hasDemand() {
<del> return (this.demand > 0);
<del> }
<del>
<ide> private boolean changeState(State oldState, State newState) {
<ide> return this.state.compareAndSet(oldState, newState);
<ide> } | 1 |
Go | Go | fix race with concurrent daemon startup in tests | 9e3193810da91d81f6b2dba3171443557f756794 | <ide><path>integration/container/restart_test.go
<ide> func TestDaemonRestartKillContainers(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> var args []string
<add> args := []string{"--iptables=false"}
<ide> if liveRestoreEnabled {
<del> args = []string{"--live-restore"}
<add> args = append(args, "--live-restore")
<ide> }
<ide>
<ide> d.StartWithBusybox(t, args...) | 1 |
Text | Text | replace page with page_size to avoide confusion | e45e52a255c0dfbecfc5048697534ffbe0e2648e | <ide><path>docs/topics/release-notes.md
<ide> You can determine your currently installed version using `pip freeze`:
<ide> * Bugfix: `client.force_authenticate(None)` should also clear session info if it exists.
<ide> * Bugfix: Client sending empty string instead of file now clears `FileField`.
<ide> * Bugfix: Empty values on ChoiceFields with `required=False` now consistently return `None`.
<del>* Bugfix: Clients setting `page=0` now simply returns the default page size, instead of disabling pagination. [*]
<add>* Bugfix: Clients setting `page_size=0` now simply returns the default page size, instead of disabling pagination. [*]
<ide>
<ide> ---
<ide>
<del>[*] Note that the change in `page=0` behaviour fixes what is considered to be a bug in how clients can effect the pagination size. However if you were relying on this behavior you will need to add the following mixin to your list views in order to preserve the existing behavior.
<add>[*] Note that the change in `page_size=0` behaviour fixes what is considered to be a bug in how clients can effect the pagination size. However if you were relying on this behavior you will need to add the following mixin to your list views in order to preserve the existing behavior.
<ide>
<ide> class DisablePaginationMixin(object):
<ide> def get_paginate_by(self, queryset=None): | 1 |
Text | Text | reduce abstraction and make it easier to read | 70b97f6f5a92cfd5c0c008a1f5e0e33c392c952e | <ide><path>docs/_sidebar.md
<ide> - **Code Contribution**
<ide> - [Set up freeCodeCamp locally](how-to-setup-freecodecamp-locally.md)
<ide> - [Work on mobile app](how-to-setup-freecodecamp-mobile-app-locally.md)
<add> - [How to contribute to the codebase](how-to-contribute-to-the-codebase.md)
<ide> - [Follow coding best practices](codebase-best-practices.md)
<ide> - [Open a pull request](how-to-open-a-pull-request.md)
<ide> - [Work on coding challenges](how-to-work-on-coding-challenges.md)
<ide> - [Debug outgoing emails locally](how-to-catch-outgoing-emails-locally.md)
<ide> - [Set up freeCodeCamp on Windows (WSL)](how-to-setup-wsl.md)
<ide> - [User Token Workflow](user-token-workflow.md)
<add> - [Troubleshooting Development Issues](troubleshooting-development-issues.md)
<ide>
<ide> ---
<ide>
<ide><path>docs/how-to-contribute-to-the-codebase.md
<add>Follow these guidelines to contribute to the codebase. This is highly recommended if you want to contribute regularly.
<add>
<add>Ignoring these steps may soil your copy which makes the contributing, maintaining, and reviewing processes difficult.
<add>
<add>## Contributing to the Codebase
<add>
<add>You can now make changes to files and commit your changes to your fork, which you can prepare by reading [how to set up freecodecamp](how-to-setup-freecodecamp-locally.md).
<add>
<add>Follow these steps:
<add>
<add>1. Validate that you are on the `main` branch:
<add>
<add> ```console
<add> git status
<add> ```
<add>
<add> You should get an output like this:
<add>
<add> ```console
<add> On branch main
<add> Your branch is up-to-date with 'origin/main'.
<add>
<add> nothing to commit, working directory clean
<add> ```
<add>
<add> If you got different message, then you aren't on main or your working directory isn't clean, resolve any outstanding files/commits and checkout `main`:
<add>
<add> ```console
<add> git checkout main
<add> ```
<add>
<add>2. Sync the latest changes from the freeCodeCamp upstream `main` branch to your `main` fork branch:
<add>
<add> > [!WARNING]
<add> > If you have any outstanding pull requests that you made from the `main` branch of your fork, you will lose them at the end of this step.
<add> >
<add> > You should ensure your pull request is merged by a moderator before performing this step. To avoid this scenario, you should **always** work on a branch other than the `main`.
<add>
<add> This step **will sync the latest changes** from the main repository of freeCodeCamp.
<add>
<add> Update your copy of the freeCodeCamp upstream repository:
<add>
<add> ```console
<add> git fetch upstream
<add> ```
<add>
<add> Hard reset your main branch with the freeCodeCamp main:
<add>
<add> ```console
<add> git reset --hard upstream/main
<add> ```
<add>
<add> Push your main branch to your origin to have a clean history on your fork on GitHub:
<add>
<add> ```console
<add> git push origin main --force
<add> ```
<add>
<add> You can validate your current main matches the upstream/main by performing a diff:
<add>
<add> ```console
<add> git diff upstream/main
<add> ```
<add>
<add> The resulting output should be empty. This process is important, because you will be rebase your branch on top of the latest `upstream/main` as often as possible to avoid conflicts later.
<add>
<add>3. Create a fresh new branch:
<add>
<add> Working on a separate branch for each issue helps you keep your work copy clean. You should never work on the `main`. This will soil your copy of freeCodeCamp and you may have to start over with a fresh clone or fork.
<add>
<add> Check that you are on `main` as explained previously, and branch off from there:
<add>
<add> ```console
<add> git checkout -b fix/update-guide-for-xyz
<add> ```
<add>
<add> Your branch name should start with a `fix/`, `feat/`, `docs/`, etc. Avoid using issue numbers in branches. Keep them short, meaningful and unique.
<add>
<add> Some examples of good branch names are:
<add>
<add> ```md
<add> fix/update-challenges-for-react
<add> fix/update-guide-for-html-css
<add> fix/platform-bug-sign-in-issues
<add> feat/add-guide-article-for-javascript
<add> translate/add-spanish-basic-html
<add> ```
<add>
<add>4. Edit pages and work on code in your favorite text editor.
<add>
<add>5. Once you are happy with the changes you should optionally run freeCodeCamp to preview the changes.
<add>
<add>6. Make sure you fix any errors and check the formatting of your changes.
<add>
<add>7. Check and confirm the files you are updating:
<add>
<add> ```console
<add> git status
<add> ```
<add>
<add> This should show a list of `unstaged` files that you have edited.
<add>
<add> ```console
<add> On branch feat/documentation
<add> Your branch is up to date with 'upstream/feat/documentation'.
<add>
<add> Changes were not staged for commit:
<add> (use "git add/rm <file>..." to update what will be committed)
<add> (use "git checkout -- <file>..." to discard changes in the working directory)
<add>
<add> modified: CONTRIBUTING.md
<add> modified: docs/README.md
<add> modified: docs/how-to-setup-freecodecamp-locally.md
<add> modified: docs/how-to-work-on-guide-articles.md
<add> ...
<add> ```
<add>
<add>8. Stage the changes and make a commit:
<add>
<add> In this step, you should only mark files that you have edited or added yourself. You can perform a reset and resolve files that you did not intend to change if needed.
<add>
<add> ```console
<add> git add path/to/my/changed/file.ext
<add> ```
<add>
<add> Or you can add all the `unstaged` files to the staging area:
<add>
<add> ```console
<add> git add .
<add> ```
<add>
<add> Only the files that were moved to the staging area will be added when you make a commit.
<add>
<add> ```console
<add> git status
<add> ```
<add>
<add> Output:
<add>
<add> ```console
<add> On branch feat/documentation
<add> Your branch is up to date with 'upstream/feat/documentation'.
<add>
<add> Changes to be committed:
<add> (use "git reset HEAD <file>..." to unstage)
<add>
<add> modified: CONTRIBUTING.md
<add> modified: docs/README.md
<add> modified: docs/how-to-setup-freecodecamp-locally.md
<add> modified: docs/how-to-work-on-guide-articles.md
<add> ```
<add>
<add> Now, you can commit your changes with a short message like so:
<add>
<add> ```console
<add> git commit -m "fix: my short commit message"
<add> ```
<add>
<add> Some examples:
<add>
<add> ```md
<add> fix: add test for JavaScript - for loop step
<add> feat: add link for article for alexa skills
<add> ```
<add>
<add> Make a conventional commit message. This is a good practice As a developer, and you will be following standard practices.
<add>
<add> Some examples of conventional commit messages are:
<add>
<add> ```md
<add> fix: improve HTML step
<add> fix: fix build scripts for Travis-CI
<add> feat: add link article JavaScript hoisting
<add> docs: update contributing guidelines
<add> ```
<add>
<add> Keep these short, not more than 50 characters. You can always add additional information in the description of the commit message.
<add>
<add> This does not take any more time than an unconventional message like 'update file' or 'add index.md'
<add>
<add> You can learn more about why you should use conventional commits [here](https://www.conventionalcommits.org/en/v1.0.0-beta.2/#why-use-conventional-commits).
<add>
<add>9. If you realize that you need to edit a file or update the commit message after making a commit you can do so after editing the files with:
<add>
<add> ```console
<add> git commit --amend
<add> ```
<add>
<add> This will open up a default text editor like `nano` or `vi` where you can edit the commit message title and add/edit the description.
<add>
<add>10. Next, you can push your changes to your fork:
<add>
<add> ```console
<add> git push origin branch/name-here
<add> ```
<add>
<add>## Proposing a Pull Request (PR)
<add>
<add>After you've committed your changes, check here for [how to open a Pull Request](how-to-open-a-pull-request.md).
<add>
<add>## Quick commands reference
<add>
<add>A quick reference to the commands that you will need when working.
<add>
<add>| command | description |
<add>| -------------------------------------------------------------- | ----------------------------------------------------------------------------------- |
<add>| `npm run storybook` | Starts Storybook for component library development. |
<add>| `npm test` | Run all JS tests in the system, including client, server, lint and challenge tests. |
<add>| `npm run test-client` | Run the client test suite. |
<add>| `npm run test:curriculum` | Run the curriculum test suite. |
<add>| `npm run test:curriculum --block='Basic HTML and HTML5'` | Test a specific Block. |
<add>| `npm run test:curriculum --superblock='responsive-web-design'` | Test a specific SuperBlock. |
<add>| `npm run test-curriculum-full-output` | Run the curriculum test suite, without bailing after the first error |
<add>| `npm run test-server` | Run the server test suite. |
<add>| `npm run e2e` | Run the Cypress end to end tests. |
<add>| `npm run clean` | Uninstalls all dependencies and cleans up caches. |
<ide><path>docs/how-to-enable-new-languages.md
<ide> Note that the `download_language` key needs to be set to the language code displ
<ide>
<ide> There are a few steps to take in order to allow the codebase to build in your desired language.
<ide>
<del>First, visit the `config/i18n/all-langs.ts` file to add the language to the available languages list and configure the values. There are several objects here.
<add>First, visit the `config/i18n.ts` file to add the language to the list of available languages and configure the values. There are several objects here.
<ide>
<ide> - `availableLangs`: For both the `client` and `curriculum` arrays, add the text name of the language. This is the value that will be used in the `.env` file later.
<ide> - `auditedCerts`: Add the text name of the language as the _key_, and add an array of `SuperBlocks.{cert}` variables as the _value_. This tells the client which certifications are fully translated.
<ide> - `i18nextCodes`: These are the ISO language codes for each language. You will need to add the appropriate ISO code for the language you are enabling. These do need to be unique for each language.
<ide> - `LangNames`: These are the display names for the language selector in the navigation menu.
<ide> - `LangCodes`: These are the language codes used for formatting dates and numbers. These should be Unicode CLDR codes instead of ISO codes.
<ide> - `hiddenLangs`: These languages will not be displayed in the navigation menu. This is used for languages that are not yet ready for release.
<add>- `rtlLangs`: These are languages that read from right to left.
<ide>
<del>As an example, if you wanted to enable Dothraki as a language, your `all-langs.js` objects should look like this:
<add>As an example, if you wanted to enable Dothraki as a language, your `i18n.ts` objects should look like this:
<ide>
<ide> ```js
<ide> export const availableLangs = {
<ide> export enum LangCodes = {
<ide> };
<ide>
<ide> export const hiddenLangs = ['dothraki'];
<add>
<add>export const rtlLangs = [''];
<ide> ```
<ide>
<ide> > [!NOTE]
<ide> For the video challenges, you need to change a few things. First add the new loc
<ide> ...
<ide> ```
<ide>
<del>Then add an id for the new language to any video challenge in an audited block. For example, if `auditedCerts` in `all-langs.ts` includes `scientific-computing-with-python` for `dothraki`, then you must add a `dothraki` entry in `videoLocaleIds`. The frontmatter should then look like this:
<add>Then add an id for the new language to any video challenge in an audited block. For example, if `auditedCerts` in `i18n.ts` includes `scientific-computing-with-python` for `dothraki`, then you must add a `dothraki` entry in `videoLocaleIds`. The frontmatter should then look like this:
<ide>
<ide> ```yml
<ide> videoLocaleIds:
<ide><path>docs/how-to-setup-freecodecamp-locally.md
<ide> Follow these guidelines for setting up freeCodeCamp locally on your system. This
<ide>
<ide> Some of these contribution workflows – like fixing bugs in the codebase or curriculum – need you to run freeCodeCamp locally on your computer.
<ide>
<del>> [!TIP]
<del>> If you are not interested in setting up freeCodeCamp locally, consider using Gitpod, a free online dev environment.
<del>>
<del>> [![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/freeCodeCamp/freeCodeCamp)
<del>>
<del>> (Starts a ready-to-code dev environment for freeCodeCamp in your browser.)
<del>
<ide> ### How to prepare your local machine
<ide>
<ide> Start by installing the prerequisite software for your operating system.
<ide> If you do run into issues, first perform a web search for your issue and see if
<ide>
<ide> And as always, feel free to ask questions on the ['Contributors' category on our forum](https://forum.freecodecamp.org/c/contributors) or [our chat server](https://discord.gg/PRyKn3Vbay).
<ide>
<del>> [!TIP]
<del>> You may skip running freeCodeCamp locally if you are simply editing files. For instance, performing a `rebase`, or resolving `merge` conflicts.
<del>>
<del>> You can always return to this part of the instructions later. You should **only** skip this step if you do not need to run the apps on your machine.
<del>>
<del>> [Skip to making changes](#making-changes-locally).
<del>
<ide> ### Configuring dependencies
<ide>
<add>We have automated the process of setting up the development environment in Gitpod for you.
<add>
<add>[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/freeCodeCamp/freeCodeCamp)
<add>
<add>(You will still need to create your own fork and branch.)
<add>
<ide> #### Step 1: Set up the environment variable file
<ide>
<ide> The default API keys and environment variables are stored in the file `sample.env`. This file needs to be copied to a new file named `.env` that is accessed dynamically during the installation step.
<ide> npm run develop
<ide>
<ide> This single command will fire up all the services, including the API server and the client applications available for you to work on.
<ide>
<del>> [!NOTE]
<del>> Once ready, open a web browser and **visit <http://localhost:8000>**. If the app loads, sign in. Congratulations – you're all set! You now have a copy of freeCodeCamp's entire learning platform running on your local machine.
<add>Once ready, open a web browser and **visit <http://localhost:8000>**. If the app loads, sign in. Congratulations – you're all set! You now have a copy of freeCodeCamp's entire learning platform running on your local machine.
<ide>
<del>> [!TIP]
<del>> The API Server serves APIs at `http://localhost:3000`. The Gatsby app serves the client application at `http://localhost:8000`
<add>The API serves endpoints at `http://localhost:3000`. The Gatsby app serves the client application at `http://localhost:8000`
<ide>
<del>> While you are logged in, if you visit <http://localhost:3000/explorer> you should see the available APIs.
<add>While you are logged in, if you visit <http://localhost:3000/explorer> you should see the available APIs.
<ide>
<ide> > [!WARNING]
<ide> > Clearing your cookies or running `npm run seed:certified-user` will log you out, and you will have to sign in again.
<ide>
<del>## Sign in with a local user
<del>
<del>Your local setup automatically populates a local user in the database. Clicking the `Sign In` button will automatically authenticate you into the local application.
<del>
<del>However, accessing the user portfolio page is a little tricky. In development, Gatsby takes over serving the client-side pages and hence you will get a `404` page for the user portfolio when working locally.
<del>
<del>Simply clicking the **"Preview Custom 404 Page"** button will forward you to the correct page.
<del>
<del><details>
<del> <summary>
<del> How to sign in when working locally (screenshot)
<del> </summary>
<del> <br>
<del> <img src="https://user-images.githubusercontent.com/29990697/71541249-f63cdf00-2923-11ea-8a85-cefb6f9c9977.gif" alt="How to sign in when working locally">
<del></details>
<del>
<del>## Making changes locally
<del>
<del>You can now make changes to files and commit your changes to your local clone of your fork.
<del>
<del>Follow these steps:
<del>
<del>1. Validate that you are on the `main` branch:
<del>
<del> ```console
<del> git status
<del> ```
<del>
<del> You should get an output like this:
<del>
<del> ```console
<del> On branch main
<del> Your branch is up-to-date with 'origin/main'.
<del>
<del> nothing to commit, working directory clean
<del> ```
<del>
<del> If you are not on main or your working directory is not clean, resolve any outstanding files/commits and checkout `main`:
<del>
<del> ```console
<del> git checkout main
<del> ```
<del>
<del>2. Sync the latest changes from the freeCodeCamp upstream `main` branch to your local main branch:
<del>
<del> > [!WARNING]
<del> > If you have any outstanding pull request that you made from the `main` branch of your fork, you will lose them at the end of this step.
<del> >
<del> > You should ensure your pull request is merged by a moderator before performing this step. To avoid this scenario, you should **always** work on a branch other than the `main`.
<del>
<del> This step **will sync the latest changes** from the main repository of freeCodeCamp. It is important that you rebase your branch on top of the latest `upstream/main` as often as possible to avoid conflicts later.
<del>
<del> Update your local copy of the freeCodeCamp upstream repository:
<del>
<del> ```console
<del> git fetch upstream
<del> ```
<del>
<del> Hard reset your main branch with the freeCodeCamp main:
<del>
<del> ```console
<del> git reset --hard upstream/main
<del> ```
<del>
<del> Push your main branch to your origin to have a clean history on your fork on GitHub:
<del>
<del> ```console
<del> git push origin main --force
<del> ```
<del>
<del> You can validate your current main matches the upstream/main by performing a diff:
<del>
<del> ```console
<del> git diff upstream/main
<del> ```
<del>
<del> The resulting output should be empty.
<del>
<del>3. Create a fresh new branch:
<del>
<del> Working on a separate branch for each issue helps you keep your local work copy clean. You should never work on the `main`. This will soil your copy of freeCodeCamp and you may have to start over with a fresh clone or fork.
<del>
<del> Check that you are on `main` as explained previously, and branch off from there:
<del>
<del> ```console
<del> git checkout -b fix/update-guide-for-xyz
<del> ```
<del>
<del> Your branch name should start with a `fix/`, `feat/`, `docs/`, etc. Avoid using issue numbers in branches. Keep them short, meaningful and unique.
<del>
<del> Some examples of good branch names are:
<del>
<del> ```md
<del> fix/update-challenges-for-react
<del> fix/update-guide-for-html-css
<del> fix/platform-bug-sign-in-issues
<del> feat/add-guide-article-for-javascript
<del> translate/add-spanish-basic-html
<del> ```
<del>
<del>4. Edit pages and work on code in your favorite text editor.
<del>
<del>5. Once you are happy with the changes you should optionally run freeCodeCamp locally to preview the changes.
<del>
<del>6. Make sure you fix any errors and check the formatting of your changes.
<del>
<del>7. Check and confirm the files you are updating:
<del>
<del> ```console
<del> git status
<del> ```
<del>
<del> This should show a list of `unstaged` files that you have edited.
<del>
<del> ```console
<del> On branch feat/documentation
<del> Your branch is up to date with 'upstream/feat/documentation'.
<del>
<del> Changes were not staged for commit:
<del> (use "git add/rm <file>..." to update what will be committed)
<del> (use "git checkout -- <file>..." to discard changes in the working directory)
<del>
<del> modified: CONTRIBUTING.md
<del> modified: docs/README.md
<del> modified: docs/how-to-setup-freecodecamp-locally.md
<del> modified: docs/how-to-work-on-guide-articles.md
<del> ...
<del> ```
<del>
<del>8. Stage the changes and make a commit:
<del>
<del> In this step, you should only mark files that you have edited or added yourself. You can perform a reset and resolve files that you did not intend to change if needed.
<del>
<del> ```console
<del> git add path/to/my/changed/file.ext
<del> ```
<del>
<del> Or you can add all the `unstaged` files to the staging area:
<del>
<del> ```console
<del> git add .
<del> ```
<del>
<del> Only the files that were moved to the staging area will be added when you make a commit.
<del>
<del> ```console
<del> git status
<del> ```
<del>
<del> Output:
<del>
<del> ```console
<del> On branch feat/documentation
<del> Your branch is up to date with 'upstream/feat/documentation'.
<del>
<del> Changes to be committed:
<del> (use "git reset HEAD <file>..." to unstage)
<del>
<del> modified: CONTRIBUTING.md
<del> modified: docs/README.md
<del> modified: docs/how-to-setup-freecodecamp-locally.md
<del> modified: docs/how-to-work-on-guide-articles.md
<del> ```
<del>
<del> Now, you can commit your changes with a short message like so:
<del>
<del> ```console
<del> git commit -m "fix: my short commit message"
<del> ```
<del>
<del> Some examples:
<del>
<del> ```md
<del> fix: update guide article for Java - for loop
<del> feat: add guide article for alexa skills
<del> ```
<del>
<del> Optional:
<del>
<del> We highly recommend making a conventional commit message. This is a good practice that you will see on some of the popular Open Source repositories. As a developer, this encourages you to follow standard practices.
<del>
<del> Some examples of conventional commit messages are:
<del>
<del> ```md
<del> fix: update HTML guide article
<del> fix: update build scripts for Travis-CI
<del> feat: add article for JavaScript hoisting
<del> docs: update contributing guidelines
<del> ```
<del>
<del> Keep these short, not more than 50 characters. You can always add additional information in the description of the commit message.
<del>
<del> This does not take any additional time than an unconventional message like 'update file' or 'add index.md'
<del>
<del> You can learn more about why you should use conventional commits [here](https://www.conventionalcommits.org/en/v1.0.0-beta.2/#why-use-conventional-commits).
<del>
<del>9. If you realize that you need to edit a file or update the commit message after making a commit you can do so after editing the files with:
<del>
<del> ```console
<del> git commit --amend
<del> ```
<del>
<del> This will open up a default text editor like `nano` or `vi` where you can edit the commit message title and add/edit the description.
<del>
<del>10. Next, you can push your changes to your fork:
<del>
<del> ```console
<del> git push origin branch/name-here
<del> ```
<del>
<del>## Proposing a Pull Request (PR)
<del>
<del>After you've committed your changes, check here for [how to open a Pull Request](how-to-open-a-pull-request.md).
<add>If you have issues while installing it, check out the [troubleshooting section](troubleshooting-development-issues.md)
<ide>
<ide> ## Quick commands reference
<ide>
<ide> A quick reference to the commands that you will need when working locally.
<ide>
<del>| command | description |
<del>| -------------------------------------------------------------- | ----------------------------------------------------------------------------------- |
<del>| `npm ci` | Installs / re-install all dependencies and bootstraps the different services. |
<del>| `npm run seed` | Parses all the challenge markdown files and inserts them into MongoDB. |
<del>| `npm run develop` | Starts the freeCodeCamp API Server and Client Applications. |
<del>| `npm run storybook` | Starts Storybook for component library development. |
<del>| `npm test` | Run all JS tests in the system, including client, server, lint and challenge tests. |
<del>| `npm run test-client` | Run the client test suite. |
<del>| `npm run test:curriculum` | Run the curriculum test suite. |
<del>| `npm run test:curriculum --block='Basic HTML and HTML5'` | Test a specific Block. |
<del>| `npm run test:curriculum --superblock='responsive-web-design'` | Test a specific SuperBlock. |
<del>| `npm run test-curriculum-full-output` | Run the curriculum test suite, without bailing after the first error |
<del>| `npm run test-server` | Run the server test suite. |
<del>| `npm run e2e` | Run the Cypress end to end tests. |
<del>| `npm run clean` | Uninstalls all dependencies and cleans up caches. |
<del>
<del>## Troubleshooting
<del>
<del>### Issues with installing the recommended prerequisites
<del>
<del>We regularly develop on the latest or most popular operating systems like macOS 10.15 or later, Ubuntu 18.04 or later, and Windows 10 (with WSL2).
<del>
<del>It is recommended to research your specific issue on resources such as Google, Stack Overflow, and Stack Exchange. There is a good chance that someone has faced the same issue and there is already an answer to your specific query.
<del>
<del>If you are on a different OS and/or are still running into issues, see [getting help](#getting-help).
<del>
<del>> [!WARNING]
<del>>
<del>> Please avoid creating GitHub issues for prerequisite issues. They are out of the scope of this project.
<del>
<del>### Issues with the UI, Fonts, build errors, etc.
<del>
<del>If you face issues with the UI, Fonts or see builds errors a cleanup can be useful:
<del>
<del>```console
<del>npm run clean
<del>npm ci
<del>npm run seed
<del>npm run develop
<del>```
<del>
<del>OR
<del>
<del>Use the shortcut
<del>
<del>```
<del>npm run clean-and-develop
<del>```
<del>
<del>If you continue to face issues with the build, cleaning up the workspace is recommend.
<del>
<del>Use `git clean` in interactive mode:
<del>
<del>```
<del>git clean -ifdX
<del>```
<del>
<del><details>
<del> <summary>
<del> How to clean git untracked files (screenshot)
<del> </summary>
<del> <br>
<del> <img src="https://user-images.githubusercontent.com/1884376/94270515-ca579400-ff5d-11ea-8ff1-152cade31654.gif" alt="How to clean git untracked files">
<del></details>
<del>
<del>### Issues with API, login, Challenge Submissions, etc.
<del>
<del>If you can't sign in, and instead you see a banner with an error message that it will be reported to freeCodeCamp, please double-check that your local port `3000` is not in use by a different program.
<del>
<del><!-- tabs:start -->
<del>
<del>#### **macOS/Linux/WSL on Windows - From Terminal:**
<del>
<del>```console
<del>netstat -a | grep "3000"
<del>
<del>tcp4 0 0 0.0.0.0:3000 DESKTOP LISTEN
<del>```
<del>
<del>#### **On Windows - From Elevated PowerShell:**
<del>
<del>```powershell
<del>netstat -ab | Select-String "3000"
<del>
<del>TCP 0.0.0.0:3000 DESKTOP LISTENING
<del>```
<del>
<del><!-- tabs:end -->
<del>
<del>---
<del>
<del>### Issues installing dependencies
<del>
<del>If you get errors while installing the dependencies, please make sure that you are not in a restricted network or your firewall settings do not prevent you from accessing resources.
<del>
<del>The first time setup can take a while depending on your network bandwidth. Be patient, and if you are still stuck we recommend using GitPod instead of an offline setup.
<del>
<del>> [!NOTE]
<del>> If you are using Apple Devices with M1 Chip to run the application locally, it is suggested to use Node v14.7 or above. You might run into issues with dependencies like Sharp otherwise.
<del>
<del>## Getting Help
<del>
<del>If you are stuck and need help, feel free to ask questions on the ['Contributors' category on our forum](https://forum.freecodecamp.org/c/contributors) or [the contributors chat room](https://discord.gg/PRyKn3Vbay).
<del>
<del>There might be an error in the console of your browser or in Bash / Terminal / Command Line that will help identify the problem. Provide this error message in your problem description so others can more easily identify the issue and help you find a resolution.
<add>| command | description |
<add>| ----------------- | ----------------------------------------------------------------------------- |
<add>| `npm ci` | Installs / re-install all dependencies and bootstraps the different services. |
<add>| `npm run seed` | Parses all the challenge markdown files and inserts them into MongoDB. |
<add>| `npm run develop` | Starts the freeCodeCamp API Server and Client Applications. |
<add>| `npm run clean` | Uninstalls all dependencies and cleans up caches. |
<ide><path>docs/how-to-work-on-the-docs-theme.md
<ide> git clone https://github.com/freeCodeCamp/freeCodeCamp.git
<ide> Install `docsify`:
<ide>
<ide> ```console
<del>npm install -g docsify
<del>```
<del>
<del>and serve the `/docs` directory
<del>
<del>```console
<del>docsify serve docs
<add>npx docsify serve docs
<ide> ```
<ide>
<ide> Alternatively, if you have installed freeCodeCamp locally (see the local setup guide), we bundled the CLI with the development tools so you can run any of the below commands as needed from the root of the repo:
<ide><path>docs/troubleshooting-development-issues.md
<add>If you are facing issue, there is a high chance that the resolution is in this documentation.
<add>
<add>### Issues with installing the recommended prerequisites
<add>
<add>We regularly develop on the latest or most popular operating systems like macOS 10.15 or later, Ubuntu 18.04 or later, and Windows 10 (with WSL2).
<add>
<add>It is recommended to research your specific issue on resources such as Google, Stack Overflow, and Stack Exchange. There is a good chance that someone has faced the same issue and there is already an answer to your specific query.
<add>
<add>If you are on a different OS or are still facing issues, see [getting help](#getting-help).
<add>
<add>> [!WARNING]
<add>>
<add>> Please avoid creating GitHub issues for problems with the prerequisite technologies. They are out of the scope of this project.
<add>
<add>### Issues missing the UI, Fonts, language strings, or build errors.
<add>
<add>When you build the client, Gatsby will cache the Fonts, language strings and UI. If one of them isn't cached, run the following:
<add>
<add>```console
<add>npm run clean
<add>npm ci
<add>npm run seed
<add>npm run develop
<add>```
<add>
<add>OR
<add>
<add>Use the shortcut
<add>
<add>```
<add>npm run clean-and-develop
<add>```
<add>
<add>If you continue to face issues with the build, cleaning up the workspace is recommend.
<add>
<add>Use `git clean` in interactive mode:
<add>
<add>```
<add>git clean -ifdX
<add>```
<add>
<add><details>
<add> <summary>
<add> How to clean git untracked files (screenshot)
<add> </summary>
<add> <br>
<add> <img src="https://user-images.githubusercontent.com/1884376/94270515-ca579400-ff5d-11ea-8ff1-152cade31654.gif" alt="How to clean git untracked files">
<add></details>
<add>
<add>### Issues with API, login, Challenge Submissions, etc.
<add>
<add>If you can't sign in, and instead you see a banner with an error message that it will be reported to freeCodeCamp, please double-check that your local port `3000` is not in use by a different program.
<add>
<add><!-- tabs:start -->
<add>
<add>#### **macOS/Linux/WSL on Windows - From Terminal:**
<add>
<add>```console
<add>netstat -a | grep "3000"
<add>
<add>tcp4 0 0 0.0.0.0:3000 DESKTOP LISTEN
<add>```
<add>
<add>#### **On Windows - From Elevated PowerShell:**
<add>
<add>```powershell
<add>netstat -ab | Select-String "3000"
<add>
<add>TCP 0.0.0.0:3000 DESKTOP LISTENING
<add>```
<add>
<add><!-- tabs:end -->
<add>
<add>---
<add>
<add>### Issues signing out while navigating
<add>
<add>While in development, your session is stored as cookies. Clearing them will sign you out of your development account.
<add>
<add>Running `npm run seed:certified-user` will log you out, too. It will overwrite the development user in your local database.
<add>
<add>### Issue getting 404 when navigating profile page
<add>
<add>When you try to navigate to http://localhost:8000/developmentuser to view the profile page, Gatsby takes over serving the client-side pages and hence you will get a 404 page for the user profile when working.
<add>
<add>There is a "Preview Custom 404 Page" button, click it to see the profile.
<add>
<add>### Issues installing dependencies
<add>
<add>If you get errors while installing the dependencies, please make sure that you are not in a restricted network or your firewall settings do not prevent you from accessing resources.
<add>
<add>The first time setup can take a while depending on your network bandwidth. Be patient, and if you are still stuck we recommend using GitPod instead of an offline setup.
<add>
<add>> [!NOTE]
<add>> If you are using Apple Devices with M1 Chip to run the application locally, it is suggested to use Node v14.7 or above. You might run into issues with dependencies like Sharp otherwise.
<add>
<add>## Getting Help
<add>
<add>If you are stuck and need help, feel free to ask questions in the ['Contributors' category on our forum](https://forum.freecodecamp.org/c/contributors) or [the contributors chat room](https://discord.gg/PRyKn3Vbay).
<add>
<add>There might be an error in the console of your browser or in Bash / Terminal / Command Line that will help identify the problem. Provide this error message in your problem description so others can more easily identify the issue and help you find a resolution. | 6 |
Text | Text | add asan build instructions | 9c00af07160d8e3aef84e319ca7dd01667b96cd8 | <ide><path>BUILDING.md
<ide> file a new issue.
<ide> * [Running Coverage](#running-coverage)
<ide> * [Building the documentation](#building-the-documentation)
<ide> * [Building a debug build](#building-a-debug-build)
<add> * [Building an ASAN build](#building-an-asan-build)
<ide> * [Troubleshooting Unix and macOS builds](#troubleshooting-unix-and-macos-builds)
<ide> * [Windows](#windows)
<ide> * [Prerequisites](#prerequisites)
<ide> $ gdb /opt/node-debug/node core.node.8.1535359906
<ide> $ backtrace
<ide> ```
<ide>
<add>#### Building an ASAN build
<add>
<add>[ASAN](https://github.com/google/sanitizers) can help detect various memory
<add>related bugs. ASAN builds are currently only supported on linux.
<add>If you want to check it on Windows or macOS or you want a consistent toolchain
<add>on Linux, you can try [Docker](https://www.docker.com/products/docker-desktop)
<add> (using an image like `gengjiawen/node-build:2020-02-14`).
<add>
<add>The `--debug` is not necessary and will slow down build and testing, but it can
<add>show clear stacktrace if ASAN hits an issue.
<add>
<add>``` console
<add>$ ./configure --debug --enable-asan && make -j4
<add>$ make test-only
<add>```
<add>
<ide> #### Troubleshooting Unix and macOS builds
<ide>
<ide> Stale builds can sometimes result in `file not found` errors while building. | 1 |
Python | Python | fix loading flax bf16 weights in pt | 3d607df8f42dc13d18e0c2798880cd3d99beb8bc | <ide><path>src/transformers/modeling_flax_pytorch_utils.py
<ide>
<ide> import numpy as np
<ide>
<add>import jax
<ide> import jax.numpy as jnp
<ide> import transformers
<ide> from flax.serialization import from_bytes
<ide> def load_flax_weights_in_pytorch_model(pt_model, flax_state):
<ide> )
<ide> raise
<ide>
<add> # check if we have bf16 weights
<add> is_type_bf16 = flatten_dict(jax.tree_map(lambda x: x.dtype == jnp.bfloat16, flax_state)).values()
<add> if any(is_type_bf16):
<add> # convert all weights to fp32 if the are bf16 since torch.from_numpy can-not handle bf16
<add> # and bf16 is not fully supported in PT yet.
<add> logger.warning(
<add> "Found ``bfloat16`` weights in Flax model. Casting all ``bfloat16`` weights to ``float32`` "
<add> "before loading those in PyTorch model."
<add> )
<add> flax_state = jax.tree_map(
<add> lambda params: params.astype(np.float32) if params.dtype == jnp.bfloat16 else params, flax_state
<add> )
<add>
<ide> flax_state_dict = flatten_dict(flax_state)
<ide> pt_model_dict = pt_model.state_dict()
<ide>
<ide><path>tests/test_modeling_flax_clip.py
<ide> def test_save_load_from_base_pt(self):
<ide> def test_save_load_to_base_pt(self):
<ide> pass
<ide>
<add> # FlaxCLIPVisionModel does not have any base model
<add> @is_pt_flax_cross_test
<add> def test_save_load_bf16_to_base_pt(self):
<add> pass
<add>
<ide> @slow
<ide> def test_model_from_pretrained(self):
<ide> for model_class_name in self.all_model_classes:
<ide> def test_save_load_from_base_pt(self):
<ide> def test_save_load_to_base_pt(self):
<ide> pass
<ide>
<add> # FlaxCLIPVisionModel does not have any base model
<add> @is_pt_flax_cross_test
<add> def test_save_load_bf16_to_base_pt(self):
<add> pass
<add>
<ide> @slow
<ide> def test_model_from_pretrained(self):
<ide> for model_class_name in self.all_model_classes:
<ide><path>tests/test_modeling_flax_common.py
<ide> def test_save_load_to_base_pt(self):
<ide> max_diff = (base_params[key] - base_params_from_head[key]).sum().item()
<ide> self.assertLessEqual(max_diff, 1e-3, msg=f"{key} not identical")
<ide>
<add> @is_pt_flax_cross_test
<add> def test_save_load_bf16_to_base_pt(self):
<add> config, _ = self.model_tester.prepare_config_and_inputs_for_common()
<add> base_class = FLAX_MODEL_MAPPING[config.__class__]
<add>
<add> for model_class in self.all_model_classes:
<add> if model_class == base_class:
<add> continue
<add>
<add> model = model_class(config)
<add> model.params = model.to_bf16(model.params)
<add> base_params_from_head = flatten_dict(unfreeze(model.params[model.base_model_prefix]))
<add>
<add> # convert Flax model to PyTorch model
<add> pt_model_class = getattr(transformers, model_class.__name__[4:]) # Skip the "Flax" at the beginning
<add> pt_model = pt_model_class(config).eval()
<add> pt_model = load_flax_weights_in_pytorch_model(pt_model, model.params)
<add>
<add> # check that all base model weights are loaded correctly
<add> with tempfile.TemporaryDirectory() as tmpdirname:
<add> pt_model.save_pretrained(tmpdirname)
<add> base_model = base_class.from_pretrained(tmpdirname, from_pt=True)
<add>
<add> base_params = flatten_dict(unfreeze(base_model.params))
<add>
<add> for key in base_params_from_head.keys():
<add> max_diff = (base_params[key] - base_params_from_head[key]).sum().item()
<add> self.assertLessEqual(max_diff, 1e-3, msg=f"{key} not identical")
<add>
<ide> def test_jit_compilation(self):
<ide> config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
<ide>
<ide><path>tests/test_modeling_flax_t5.py
<ide> def test_save_load_to_base_pt(self):
<ide> max_diff = (base_params[key] - base_params_from_head[key]).sum().item()
<ide> self.assertLessEqual(max_diff, 1e-3, msg=f"{key} not identical")
<ide>
<add> # overwrite since special base model prefix is used
<add> @is_pt_flax_cross_test
<add> def test_save_load_bf16_to_base_pt(self):
<add> config, _ = self.model_tester.prepare_config_and_inputs_for_common()
<add> base_class = FLAX_MODEL_MAPPING[config.__class__]
<add>
<add> for model_class in self.all_model_classes:
<add> if model_class == base_class:
<add> continue
<add>
<add> model = model_class(config)
<add> model.params = model.to_bf16(model.params)
<add> base_params_from_head = flatten_dict(unfreeze(model.params))
<add>
<add> # convert Flax model to PyTorch model
<add> pt_model_class = getattr(transformers, model_class.__name__[4:]) # Skip the "Flax" at the beginning
<add> pt_model = pt_model_class(config).eval()
<add> pt_model = load_flax_weights_in_pytorch_model(pt_model, model.params)
<add>
<add> # check that all base model weights are loaded correctly
<add> with tempfile.TemporaryDirectory() as tmpdirname:
<add> pt_model.save_pretrained(tmpdirname)
<add> base_model = base_class.from_pretrained(tmpdirname, from_pt=True)
<add>
<add> base_params = flatten_dict(unfreeze(base_model.params))
<add>
<add> for key in base_params_from_head.keys():
<add> max_diff = (base_params[key] - base_params_from_head[key]).sum().item()
<add> self.assertLessEqual(max_diff, 1e-3, msg=f"{key} not identical")
<add>
<ide>
<ide> @require_sentencepiece
<ide> @require_tokenizers | 4 |
PHP | PHP | apply fixes from styleci | 3be65cc66fe1fbee88ffb385e9468513c7592fa2 | <ide><path>src/Illuminate/Console/Scheduling/Event.php
<ide>
<ide> use Closure;
<ide> use Carbon\Carbon;
<del>use LogicException;
<ide> use Cron\CronExpression;
<ide> use GuzzleHttp\Client as HttpClient;
<ide> use Illuminate\Contracts\Mail\Mailer; | 1 |
PHP | PHP | fix various formatting issues | f67e081cb48ef1bdbe7821a03f850442b501461f | <ide><path>src/Illuminate/Validation/Validator.php
<ide> protected function hydrateFiles(array $data, $arrayKey = null)
<ide> }
<ide>
<ide> foreach ($data as $key => $value) {
<del> $new_key = ($arrayKey) ? "$arrayKey.$key" : $key;
<add> $newKey = ($arrayKey) ? "$arrayKey.$key" : $key;
<ide>
<ide> // If this value is an instance of the HttpFoundation File class we will
<ide> // remove it from the data array and add it to the files array, which
<ide> // we use to conveniently separate out these files from other data.
<ide> if ($value instanceof File) {
<del> $this->files[$new_key] = $value;
<add> $this->files[$newKey] = $value;
<ide>
<ide> unset($data[$key]);
<ide> } elseif (is_array($value)) {
<ide> if (! empty($value)) {
<del> $value = $this->hydrateFiles($value, $new_key);
<add> $value = $this->hydrateFiles($value, $newKey);
<add>
<ide> if (empty($value)) {
<ide> unset($data[$key]);
<ide> }
<ide> public function sometimes($attribute, $rules, callable $callback)
<ide> public function each($attribute, $rules)
<ide> {
<ide> $data = array_merge(
<del> Arr::dot($this->initializeAttributeOnData($attribute)),
<del> $this->files
<add> Arr::dot($this->initializeAttributeOnData($attribute)), $this->files
<ide> );
<ide>
<ide> $pattern = str_replace('\*', '[^\.]+', preg_quote($attribute)); | 1 |