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 |
|---|---|---|---|---|---|
Go | Go | normalize the log for docker subcommand usage, | 2b051bcbda06ec48287e75da506bacf95be2b652 | <ide><path>api/client/cli.go
<ide> func (cli *DockerCli) Subcmd(name, signature, description string, exitOnError bo
<ide> flags := flag.NewFlagSet(name, errorHandling)
<ide> flags.Usage = func() {
<ide> options := ""
<add> if signature != "" {
<add> signature = " " + signature
<add> }
<ide> if flags.FlagCountUndeprecated() > 0 {
<del> options = "[OPTIONS] "
<add> options = " [OPTIONS]"
<ide> }
<del> fmt.Fprintf(cli.out, "\nUsage: docker %s %s%s\n\n%s\n\n", name, options, signature, description)
<add> fmt.Fprintf(cli.out, "\nUsage: docker %s%s%s\n\n%s\n\n", name, options, signature, description)
<ide> flags.SetOutput(cli.out)
<ide> flags.PrintDefaults()
<ide> os.Exit(0)
<ide><path>integration-cli/docker_cli_help_test.go
<ide> func TestHelpTextVerify(t *testing.T) {
<ide> if strings.HasPrefix(line, " -") && strings.HasSuffix(line, ".") {
<ide> t.Fatalf("Help for %q should not end with a period: %s", cmd, line)
<ide> }
<del>
<add>
<ide> // Options should not end with a space
<ide> if strings.HasSuffix(line, " ") {
<ide> t.Fatalf("Help for %q should not end with a space: %s", cmd, line) | 2 |
Javascript | Javascript | fix polar clock example | 540d3ace3e4e4c25ff93c011b62f157684c510ca | <ide><path>examples/clock/clock.js
<ide> var width = 960,
<ide>
<ide> var fill = d3.scale.linear()
<ide> .range(["hsl(-180, 50%, 50%)", "hsl(180, 50%, 50%)"])
<del> .interpolate(d3.interpolateHsl);
<add> .interpolate(d3.interpolateString);
<ide>
<ide> var arc = d3.svg.arc()
<ide> .startAngle(0) | 1 |
PHP | PHP | fix return value for getrelatedids | 6d33dca4bd09829bb0de4b6e3e3f6f067c5579ba | <ide><path>src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php
<ide> public function touch()
<ide> /**
<ide> * Get all of the IDs for the related models.
<ide> *
<del> * @return array
<add> * @return Illuminate\Support\Collection
<ide> */
<ide> public function getRelatedIds()
<ide> { | 1 |
Text | Text | fix typo in documentation | aafa091541d8420717265baf5bf403d52e32fde9 | <ide><path>.github/contributors/zqianem.md
<add># spaCy contributor agreement
<add>
<add>This spaCy Contributor Agreement (**"SCA"**) is based on the
<add>[Oracle Contributor Agreement](http://www.oracle.com/technetwork/oca-405177.pdf).
<add>The SCA applies to any contribution that you make to any product or project
<add>managed by us (the **"project"**), and sets out the intellectual property rights
<add>you grant to us in the contributed materials. The term **"us"** shall mean
<add>[ExplosionAI GmbH](https://explosion.ai/legal). The term
<add>**"you"** shall mean the person or entity identified below.
<add>
<add>If you agree to be bound by these terms, fill in the information requested
<add>below and include the filled-in version with your first pull request, under the
<add>folder [`.github/contributors/`](/.github/contributors/). The name of the file
<add>should be your GitHub username, with the extension `.md`. For example, the user
<add>example_user would create the file `.github/contributors/example_user.md`.
<add>
<add>Read this agreement carefully before signing. These terms and conditions
<add>constitute a binding legal agreement.
<add>
<add>## Contributor Agreement
<add>
<add>1. The term "contribution" or "contributed materials" means any source code,
<add>object code, patch, tool, sample, graphic, specification, manual,
<add>documentation, or any other material posted or submitted by you to the project.
<add>
<add>2. With respect to any worldwide copyrights, or copyright applications and
<add>registrations, in your contribution:
<add>
<add> * you hereby assign to us joint ownership, and to the extent that such
<add> assignment is or becomes invalid, ineffective or unenforceable, you hereby
<add> grant to us a perpetual, irrevocable, non-exclusive, worldwide, no-charge,
<add> royalty-free, unrestricted license to exercise all rights under those
<add> copyrights. This includes, at our option, the right to sublicense these same
<add> rights to third parties through multiple levels of sublicensees or other
<add> licensing arrangements;
<add>
<add> * you agree that each of us can do all things in relation to your
<add> contribution as if each of us were the sole owners, and if one of us makes
<add> a derivative work of your contribution, the one who makes the derivative
<add> work (or has it made will be the sole owner of that derivative work;
<add>
<add> * you agree that you will not assert any moral rights in your contribution
<add> against us, our licensees or transferees;
<add>
<add> * you agree that we may register a copyright in your contribution and
<add> exercise all ownership rights associated with it; and
<add>
<add> * you agree that neither of us has any duty to consult with, obtain the
<add> consent of, pay or render an accounting to the other for any use or
<add> distribution of your contribution.
<add>
<add>3. With respect to any patents you own, or that you can license without payment
<add>to any third party, you hereby grant to us a perpetual, irrevocable,
<add>non-exclusive, worldwide, no-charge, royalty-free license to:
<add>
<add> * make, have made, use, sell, offer to sell, import, and otherwise transfer
<add> your contribution in whole or in part, alone or in combination with or
<add> included in any product, work or materials arising out of the project to
<add> which your contribution was submitted, and
<add>
<add> * at our option, to sublicense these same rights to third parties through
<add> multiple levels of sublicensees or other licensing arrangements.
<add>
<add>4. Except as set out above, you keep all right, title, and interest in your
<add>contribution. The rights that you grant to us under these terms are effective
<add>on the date you first submitted a contribution to us, even if your submission
<add>took place before the date you sign these terms.
<add>
<add>5. You covenant, represent, warrant and agree that:
<add>
<add> * Each contribution that you submit is and shall be an original work of
<add> authorship and you can legally grant the rights set out in this SCA;
<add>
<add> * to the best of your knowledge, each contribution will not violate any
<add> third party's copyrights, trademarks, patents, or other intellectual
<add> property rights; and
<add>
<add> * each contribution shall be in compliance with U.S. export control laws and
<add> other applicable export and import laws. You agree to notify us if you
<add> become aware of any circumstance which would make any of the foregoing
<add> representations inaccurate in any respect. We may publicly disclose your
<add> participation in the project, including the fact that you have signed the SCA.
<add>
<add>6. This SCA is governed by the laws of the State of California and applicable
<add>U.S. Federal law. Any choice of law rules will not apply.
<add>
<add>7. Please place an “x” on one of the applicable statement below. Please do NOT
<add>mark both statements:
<add>
<add> * [x] I am signing on behalf of myself as an individual and no other person
<add> or entity, including my employer, has or will have rights with respect to my
<add> contributions.
<add>
<add> * [ ] I am signing on behalf of my employer or a legal entity and I have the
<add> actual authority to contractually bind that entity.
<add>
<add>## Contributor Details
<add>
<add>| Field | Entry |
<add>|------------------------------- | -------------------- |
<add>| Name | Em Zhan |
<add>| Company name (if applicable) | |
<add>| Title or role (if applicable) | |
<add>| Date | 2019-09-25 |
<add>| GitHub username | zqianem |
<add>| Website (optional) | |
<ide><path>website/docs/usage/101/_pos-deps.md
<ide> for token in doc:
<ide> | for | for | `ADP` | `IN` | `prep` | `xxx` | `True` | `True` |
<ide> | \$ | \$ | `SYM` | `$` | `quantmod` | `$` | `False` | `False` |
<ide> | 1 | 1 | `NUM` | `CD` | `compound` | `d` | `False` | `False` |
<del>| billion | billion | `NUM` | `CD` | `probj` | `xxxx` | `True` | `False` |
<add>| billion | billion | `NUM` | `CD` | `pobj` | `xxxx` | `True` | `False` |
<ide>
<ide> > #### Tip: Understanding tags and labels
<ide> > | 2 |
PHP | PHP | maintain package.json formatting | 5ec0641b2945705120a3bc8f84ee7d1713caaf16 | <ide><path>src/Illuminate/Foundation/Console/Presets/Preset.php
<ide> protected static function updatePackages()
<ide>
<ide> file_put_contents(
<ide> base_path('package.json'),
<del> json_encode($packages, JSON_PRETTY_PRINT)
<add> preg_replace(
<add> '/^( +?)\\1(?=[^ ])/m',
<add> '$1',
<add> json_encode($packages, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT) . PHP_EOL
<add> )
<ide> );
<ide> }
<ide> | 1 |
Javascript | Javascript | fix brotli flush range | 9c7aa96703a9afe1ff115d95ad5727df90c0b78a | <ide><path>lib/zlib.js
<ide> const {
<ide> BROTLI_DECODE, BROTLI_ENCODE,
<ide> // Brotli operations (~flush levels)
<ide> BROTLI_OPERATION_PROCESS, BROTLI_OPERATION_FLUSH,
<del> BROTLI_OPERATION_FINISH
<add> BROTLI_OPERATION_FINISH, BROTLI_OPERATION_EMIT_METADATA,
<ide> } = constants;
<ide>
<ide> // Translation table for return codes.
<ide> const checkRangesOrGetDefault = hideStackFrames(
<ide> }
<ide> );
<ide>
<add>const FLUSH_BOUND = [
<add> [ Z_NO_FLUSH, Z_BLOCK ],
<add> [ BROTLI_OPERATION_PROCESS, BROTLI_OPERATION_EMIT_METADATA ],
<add>];
<add>const FLUSH_BOUND_IDX_NORMAL = 0;
<add>const FLUSH_BOUND_IDX_BROTLI = 1;
<add>
<ide> // The base class for all Zlib-style streams.
<ide> function ZlibBase(opts, mode, handle, { flush, finishFlush, fullFlush }) {
<ide> let chunkSize = Z_DEFAULT_CHUNK;
<ide> function ZlibBase(opts, mode, handle, { flush, finishFlush, fullFlush }) {
<ide> assert(typeof mode === 'number');
<ide> assert(mode >= DEFLATE && mode <= BROTLI_ENCODE);
<ide>
<add> let flushBoundIdx;
<add> if (mode !== BROTLI_ENCODE && mode !== BROTLI_DECODE) {
<add> flushBoundIdx = FLUSH_BOUND_IDX_NORMAL;
<add> } else {
<add> flushBoundIdx = FLUSH_BOUND_IDX_BROTLI;
<add> }
<add>
<ide> if (opts) {
<ide> chunkSize = opts.chunkSize;
<ide> if (!checkFiniteNumber(chunkSize, 'options.chunkSize')) {
<ide> function ZlibBase(opts, mode, handle, { flush, finishFlush, fullFlush }) {
<ide>
<ide> flush = checkRangesOrGetDefault(
<ide> opts.flush, 'options.flush',
<del> Z_NO_FLUSH, Z_BLOCK, flush);
<add> FLUSH_BOUND[flushBoundIdx][0], FLUSH_BOUND[flushBoundIdx][1], flush);
<ide>
<ide> finishFlush = checkRangesOrGetDefault(
<ide> opts.finishFlush, 'options.finishFlush',
<del> Z_NO_FLUSH, Z_BLOCK, finishFlush);
<add> FLUSH_BOUND[flushBoundIdx][0], FLUSH_BOUND[flushBoundIdx][1],
<add> finishFlush);
<ide>
<ide> maxOutputLength = checkRangesOrGetDefault(
<ide> opts.maxOutputLength, 'options.maxOutputLength',
<ide><path>test/parallel/test-zlib-brotli.js
<ide> const sampleBuffer = fixtures.readSync('/pss-vectors.json');
<ide> message: 'Initialization failed'
<ide> });
<ide> }
<add>
<add>{
<add> // Test options.flush range
<add> assert.throws(() => {
<add> zlib.brotliCompressSync('', { flush: zlib.constants.Z_FINISH });
<add> }, {
<add> code: 'ERR_OUT_OF_RANGE',
<add> name: 'RangeError',
<add> message: 'The value of "options.flush" is out of range. It must be >= 0 ' +
<add> 'and <= 3. Received 4',
<add> });
<add>
<add> assert.throws(() => {
<add> zlib.brotliCompressSync('', { finishFlush: zlib.constants.Z_FINISH });
<add> }, {
<add> code: 'ERR_OUT_OF_RANGE',
<add> name: 'RangeError',
<add> message: 'The value of "options.finishFlush" is out of range. It must be ' +
<add> '>= 0 and <= 3. Received 4',
<add> });
<add>} | 2 |
Text | Text | improve assert documentation | c1483bac9496d341dc428105d3c3e4b07600a933 | <ide><path>doc/api/assert.md
<ide> parameter is undefined, a default error message is assigned. If the `message`
<ide> parameter is an instance of an [`Error`][] then it will be thrown instead of the
<ide> `AssertionError`.
<ide>
<del>## assert.doesNotReject(block[, error][, message])
<add>## assert.doesNotReject(asyncFn[, error][, message])
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> -->
<del>* `block` {Function|Promise}
<add>* `asyncFn` {Function|Promise}
<ide> * `error` {RegExp|Function}
<del>* `message` {string|Error}
<add>* `message` {string}
<ide>
<del>Awaits the `block` promise or, if `block` is a function, immediately calls the
<del>function and awaits the returned promise to complete. It will then check that
<del>the promise is not rejected.
<add>Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately
<add>calls the function and awaits the returned promise to complete. It will then
<add>check that the promise is not rejected.
<ide>
<del>If `block` is a function and it throws an error synchronously,
<add>If `asyncFn` is a function and it throws an error synchronously,
<ide> `assert.doesNotReject()` will return a rejected `Promise` with that error. If
<ide> the function does not return a promise, `assert.doesNotReject()` will return a
<ide> rejected `Promise` with an [`ERR_INVALID_RETURN_VALUE`][] error. In both cases
<ide> assert.doesNotReject(Promise.reject(new TypeError('Wrong value')))
<ide> });
<ide> ```
<ide>
<del>## assert.doesNotThrow(block[, error][, message])
<add>## assert.doesNotThrow(fn[, error][, message])
<ide> <!-- YAML
<ide> added: v0.1.21
<ide> changes:
<ide> changes:
<ide> pr-url: https://github.com/nodejs/node/pull/3276
<ide> description: The `error` parameter can now be an arrow function.
<ide> -->
<del>* `block` {Function}
<add>* `fn` {Function}
<ide> * `error` {RegExp|Function}
<del>* `message` {string|Error}
<add>* `message` {string}
<ide>
<del>Asserts that the function `block` does not throw an error.
<add>Asserts that the function `fn` does not throw an error.
<ide>
<ide> Please note: Using `assert.doesNotThrow()` is actually not useful because there
<ide> is no benefit by catching an error and then rethrowing it. Instead, consider
<ide> adding a comment next to the specific code path that should not throw and keep
<ide> error messages as expressive as possible.
<ide>
<del>When `assert.doesNotThrow()` is called, it will immediately call the `block`
<add>When `assert.doesNotThrow()` is called, it will immediately call the `fn`
<ide> function.
<ide>
<ide> If an error is thrown and it is the same type as that specified by the `error`
<ide> assert(0);
<ide> // assert(0)
<ide> ```
<ide>
<del>## assert.rejects(block[, error][, message])
<add>## assert.rejects(asyncFn[, error][, message])
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> -->
<del>* `block` {Function|Promise}
<add>* `asyncFn` {Function|Promise}
<ide> * `error` {RegExp|Function|Object|Error}
<del>* `message` {string|Error}
<add>* `message` {string}
<ide>
<del>Awaits the `block` promise or, if `block` is a function, immediately calls the
<del>function and awaits the returned promise to complete. It will then check that
<del>the promise is rejected.
<add>Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately
<add>calls the function and awaits the returned promise to complete. It will then
<add>check that the promise is rejected.
<ide>
<del>If `block` is a function and it throws an error synchronously,
<add>If `asyncFn` is a function and it throws an error synchronously,
<ide> `assert.rejects()` will return a rejected `Promise` with that error. If the
<ide> function does not return a promise, `assert.rejects()` will return a rejected
<ide> `Promise` with an [`ERR_INVALID_RETURN_VALUE`][] error. In both cases the error
<ide> each property will be tested for including the non-enumerable `message` and
<ide> `name` properties.
<ide>
<ide> If specified, `message` will be the message provided by the `AssertionError` if
<del>the block fails to reject.
<add>the `asyncFn` fails to reject.
<ide>
<ide> ```js
<ide> (async () => {
<ide> If the values are not strictly equal, an `AssertionError` is thrown with a
<ide> `message` parameter is an instance of an [`Error`][] then it will be thrown
<ide> instead of the `AssertionError`.
<ide>
<del>## assert.throws(block[, error][, message])
<add>## assert.throws(fn[, error][, message])
<ide> <!-- YAML
<ide> added: v0.1.21
<ide> changes:
<ide> changes:
<ide> pr-url: https://github.com/nodejs/node/pull/3276
<ide> description: The `error` parameter can now be an arrow function.
<ide> -->
<del>* `block` {Function}
<add>* `fn` {Function}
<ide> * `error` {RegExp|Function|Object|Error}
<del>* `message` {string|Error}
<add>* `message` {string}
<ide>
<del>Expects the function `block` to throw an error.
<add>Expects the function `fn` to throw an error.
<ide>
<ide> If specified, `error` can be a [`Class`][], [`RegExp`][], a validation function,
<ide> a validation object where each property will be tested for strict deep equality,
<ide> equality including the non-enumerable `message` and `name` properties. When
<ide> using an object, it is also possible to use a regular expression, when
<ide> validating against a string property. See below for examples.
<ide>
<del>If specified, `message` will be the message provided by the `AssertionError` if
<del>the block fails to throw.
<add>If specified, `message` will be appended to the message provided by the
<add>`AssertionError` if the `fn` call fails to throw or in case the error validation
<add>fails.
<ide>
<ide> Custom validation object/error instance:
<ide>
<ide> second argument. This might lead to difficult-to-spot errors.
<ide> [`WeakSet`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet
<ide> [`assert.deepEqual()`]: #assert_assert_deepequal_actual_expected_message
<ide> [`assert.deepStrictEqual()`]: #assert_assert_deepstrictequal_actual_expected_message
<del>[`assert.doesNotThrow()`]: #assert_assert_doesnotthrow_block_error_message
<add>[`assert.doesNotThrow()`]: #assert_assert_doesnotthrow_fn_error_message
<ide> [`assert.notDeepStrictEqual()`]: #assert_assert_notdeepstrictequal_actual_expected_message
<ide> [`assert.notStrictEqual()`]: #assert_assert_notstrictequal_actual_expected_message
<ide> [`assert.ok()`]: #assert_assert_ok_value_message
<ide> [`assert.strictEqual()`]: #assert_assert_strictequal_actual_expected_message
<del>[`assert.throws()`]: #assert_assert_throws_block_error_message
<add>[`assert.throws()`]: #assert_assert_throws_fn_error_message
<ide> [`strict mode`]: #assert_strict_mode
<ide> [Abstract Equality Comparison]: https://tc39.github.io/ecma262/#sec-abstract-equality-comparison
<ide> [Object.prototype.toString()]: https://tc39.github.io/ecma262/#sec-object.prototype.tostring | 1 |
PHP | PHP | add better exception output | d16e720a2421c7534ddd9bc2240a6a1d371d1203 | <ide><path>src/Database/Expression/QueryExpression.php
<ide> protected function _parseCondition(string $field, $value)
<ide> [$expression, $operator] = $parts;
<ide> $operator = strtolower(trim($operator));
<ide> }
<del> $type = $this->getTypeMap() ->type($expression);
<add> $type = $this->getTypeMap()->type($expression);
<ide>
<ide> $typeMultiple = (is_string($type) && strpos($type, '[]') !== false);
<ide> if (in_array($operator, ['in', 'not in']) || $typeMultiple) {
<ide> protected function _parseCondition(string $field, $value)
<ide> }
<ide>
<ide> if ($value === null && $this->_conjunction !== ',') {
<del> throw new InvalidArgumentException('Expression is missing operator (IS, IS NOT) with `null` value.');
<add> throw new InvalidArgumentException(
<add> sprintf('Expression `%s` is missing operator (IS, IS NOT) with `null` value.', $expression)
<add> );
<ide> }
<ide>
<ide> return new ComparisonExpression($expression, $value, $type, $operator); | 1 |
Javascript | Javascript | avoid boolean coarsion in `computed` | e2f4d058a4e766b49c5917c3f32f951e842c3557 | <ide><path>packages/ember-metal/lib/computed.js
<ide> function ComputedProperty(config, opts) {
<ide> this._meta = undefined;
<ide> this._volatile = false;
<ide> this._dependentKeys = opts && opts.dependentKeys;
<del> this._readOnly = false;
<add> this._readOnly = false;
<ide> }
<ide>
<ide> ComputedProperty.prototype = new Descriptor();
<ide> ComputedPropertyPrototype.didChange = function(obj, keyName) {
<ide> }
<ide>
<ide> let cache = meta.readableCache();
<del> if (cache && cache[keyName] !== undefined) {
<add> if (cache !== undefined && cache[keyName] !== undefined) {
<ide> cache[keyName] = undefined;
<ide> removeDependentKeys(this, obj, keyName, meta);
<ide> }
<ide> ComputedPropertyPrototype.get = function(obj, keyName) {
<ide> }
<ide>
<ide> let ret = this._getter.call(obj, keyName);
<del> if (ret === undefined) {
<del> cache[keyName] = UNDEFINED;
<del> } else {
<del> cache[keyName] = ret;
<del> }
<add> cache[keyName] = ret === undefined ? UNDEFINED : ret;
<ide>
<ide> let chainWatchers = meta.readableChainWatchers();
<del> if (chainWatchers) {
<add> if (chainWatchers !== undefined) {
<ide> chainWatchers.revalidate(keyName);
<ide> }
<ide> addDependentKeys(this, obj, keyName, meta);
<ide> ComputedPropertyPrototype.setWithSuspend = function computedPropertySetWithSuspe
<ide> };
<ide>
<ide> ComputedPropertyPrototype._set = function computedPropertySet(obj, keyName, value) {
<del> // cache requires own meta
<del> let meta = metaFor(obj);
<del> // either there is a writable cache or we need one to update
<del> let cache = meta.writableCache();
<add> let meta = metaFor(obj);
<add> let cache = meta.writableCache();
<ide> let hadCachedValue = false;
<ide> let cachedValue;
<del> if (cache[keyName] !== undefined) {
<del> if (cache[keyName] !== UNDEFINED) {
<del> cachedValue = cache[keyName];
<add> let val = cache[keyName];
<add> if (val !== undefined) {
<add> if (val !== UNDEFINED) {
<add> cachedValue = val;
<ide> }
<ide> hadCachedValue = true;
<ide> } | 1 |
Java | Java | introduce emptyreactnativeconfig inside java | e6fc9b6f2950a1a55237f242791d0f9131e78284 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/fabric/EmptyReactNativeConfig.java
<add>/*
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> */
<add>
<add>package com.facebook.react.fabric;
<add>
<add>/**
<add> * An empty {@link ReactNativeConfig} that is returning empty responses and false for all the
<add> * requested keys.
<add> */
<add>public class EmptyReactNativeConfig implements ReactNativeConfig {
<add>
<add> @Override
<add> public boolean getBool(final String s) {
<add> return false;
<add> }
<add>
<add> @Override
<add> public int getInt64(final String s) {
<add> return 0;
<add> }
<add>
<add> @Override
<add> public String getString(final String s) {
<add> return "";
<add> }
<add>
<add> @Override
<add> public double getDouble(final String s) {
<add> return 0;
<add> }
<add>}
<ide><path>ReactAndroid/src/main/java/com/facebook/react/fabric/ReactNativeConfig.java
<ide> import androidx.annotation.NonNull;
<ide> import com.facebook.proguard.annotations.DoNotStrip;
<ide>
<del>// This is a wrapper for the ReactNativeConfig object in C++
<add>/**
<add> * ReactNative Configuration that allows to customize the behavior of key/value pairs used by the
<add> * framework to enable/disable capabilities.
<add> *
<add> * <p>The hosting app should provide an implementation of this interface to allow specific
<add> * customization of single keys. An empty implementation is available as {@link
<add> * EmptyReactNativeConfig}.
<add> *
<add> * <p>This is a wrapper for the ReactNativeConfig object in C++
<add> */
<ide> @DoNotStrip
<ide> public interface ReactNativeConfig {
<ide> /**
<ide><path>packages/rn-tester/android/app/src/main/java/com/facebook/react/uiapp/RNTesterApplication.java
<ide> import com.facebook.react.config.ReactFeatureFlags;
<ide> import com.facebook.react.fabric.ComponentFactory;
<ide> import com.facebook.react.fabric.CoreComponentsRegistry;
<add>import com.facebook.react.fabric.EmptyReactNativeConfig;
<ide> import com.facebook.react.fabric.FabricJSIModuleProvider;
<del>import com.facebook.react.fabric.ReactNativeConfig;
<ide> import com.facebook.react.module.model.ReactModuleInfo;
<ide> import com.facebook.react.module.model.ReactModuleInfoProvider;
<ide> import com.facebook.react.shell.MainReactPackage;
<ide> public JSIModuleProvider<UIManager> getJSIModuleProvider() {
<ide> reactApplicationContext,
<ide> componentFactory,
<ide> // TODO: T71362667 add ReactNativeConfig's support in RNTester
<del> new ReactNativeConfig() {
<del> @Override
<del> public boolean getBool(final String s) {
<del> return false;
<del> }
<del>
<del> @Override
<del> public int getInt64(final String s) {
<del> return 0;
<del> }
<del>
<del> @Override
<del> public String getString(final String s) {
<del> return "";
<del> }
<del>
<del> @Override
<del> public double getDouble(final String s) {
<del> return 0;
<del> }
<del> },
<add> new EmptyReactNativeConfig(),
<ide> viewManagerRegistry);
<ide> }
<ide> }); | 3 |
Ruby | Ruby | remove debug print | 542f92935cdc1b23078364e547f923ec180e7efe | <ide><path>activerecord/test/cases/connection_pool_test.rb
<ide> def test_disconnect_and_clear_reloadable_connections_are_able_to_preempt_other_w
<ide> if failed
<ide> second_thread_done.set
<ide>
<del> puts
<del> puts ">>> test_disconnect_and_clear_reloadable_connections_are_able_to_preempt_other_waiting_threads / #{group_action_method}"
<del> p [first_thread, second_thread]
<del> p pool.stat
<del> p pool.connections.map(&:owner)
<del>
<ide> first_thread.join(2)
<ide> second_thread.join(2)
<del>
<del> puts "---"
<del> p [first_thread, second_thread]
<del> p pool.stat
<del> p pool.connections.map(&:owner)
<del> puts "<<<"
<del> puts
<ide> end
<ide>
<ide> first_thread.join(10) || raise("first_thread got stuck") | 1 |
Python | Python | set version to v2.1.0a7.dev11 | 1dc314bada02fccf3d6644905eaa0e43ba53cd1b | <ide><path>spacy/about.py
<ide> # fmt: off
<ide>
<ide> __title__ = "spacy-nightly"
<del>__version__ = "2.1.0a7.dev10"
<add>__version__ = "2.1.0a7.dev11"
<ide> __summary__ = "Industrial-strength Natural Language Processing (NLP) with Python and Cython"
<ide> __uri__ = "https://spacy.io"
<ide> __author__ = "Explosion AI" | 1 |
Ruby | Ruby | fix buggy tests | 5b3b9b0ebcbe35038adaf7b1636032e6f436ed1c | <ide><path>actionpack/test/controller/parameters/parameters_permit_test.rb
<ide> class ParametersPermitTest < ActiveSupport::TestCase
<ide> assert !@params.slice(:person).permitted?
<ide> assert !@params[:person][:name].permitted?
<ide>
<del> @params.each { |key, value| assert(value.permitted?) if key == :person }
<add> @params.each { |key, value| assert(!value.permitted?) if key == "person" }
<ide>
<ide> assert !@params.fetch(:person).permitted?
<ide>
<ide> assert !@params.values_at(:person).first.permitted?
<ide> end
<ide>
<ide> test "permitted is sticky on mutators" do
<del> assert !@params.delete_if { |k| k == :person }.permitted?
<del> assert !@params.keep_if { |k,v| k == :person }.permitted?
<add> assert !@params.delete_if { |k| k == "person" }.permitted?
<add> assert !@params.keep_if { |k,v| k == "person" }.permitted?
<ide> end
<ide>
<ide> test "permitted is sticky beyond merges" do
<ide> class ParametersPermitTest < ActiveSupport::TestCase
<ide> ActionController::Parameters.permit_all_parameters = false
<ide> end
<ide> end
<del>
<add>
<ide> test "permitting parameters as an array" do
<ide> assert_equal "32", @params[:person].permit([ :age ])[:age]
<ide> end | 1 |
Ruby | Ruby | add strip_patch method | 61cda1465f6d5db241801f8e5a4ec66453711835 | <ide><path>Library/Homebrew/os/mac/version.rb
<ide> def <=>(other)
<ide> end
<ide> end
<ide>
<add> sig { returns(T.self_type) }
<add> def strip_patch
<add> # Big Sur is 11.x but Catalina is 10.15.x.
<add> if major >= 11
<add> self.class.new(major.to_s)
<add> else
<add> major_minor
<add> end
<add> end
<add>
<ide> sig { returns(Symbol) }
<ide> def to_sym
<del> @to_sym ||= begin
<del> # Big Sur is 11.x but Catalina is 10.15.
<del> major_macos = if major >= 11
<del> major
<del> else
<del> major_minor
<del> end.to_s
<del> SYMBOLS.invert.fetch(major_macos, :dunno)
<del> end
<add> @to_sym ||= SYMBOLS.invert.fetch(strip_patch.to_s, :dunno)
<ide> end
<ide>
<ide> sig { returns(String) } | 1 |
Javascript | Javascript | fix unique node | 52836bac07ba318fbed18e918e78012ca6215d6b | <ide><path>examples/js/nodes/TempNode.js
<ide> THREE.TempNode.prototype.build = function( builder, output, uuid, ns ) {
<ide>
<ide> return THREE.GLNode.prototype.build.call( this, builder, output, uuid );
<ide>
<add> } else if ( isUnique ) {
<add>
<add> data.name = data.name || THREE.GLNode.prototype.build.call( this, builder, output, uuid )
<add>
<add> return data.name;
<add>
<ide> } else if ( ! builder.optimize || data.deps == 1 ) {
<ide>
<ide> return THREE.GLNode.prototype.build.call( this, builder, output, uuid ); | 1 |
Javascript | Javascript | improve asset msg in test | c80d9d6a93ab9f20c150faf11d2e24f695f76501 | <ide><path>test/parallel/test-zlib-from-gzip-with-trailing-garbage.js
<ide> zlib.gunzip(data, common.mustCall((err, result) => {
<ide> assert.strictEqual(
<ide> result.toString(),
<ide> 'abcdef',
<del> 'result should match original string'
<add> `result '${result.toString()}' should match original string`
<ide> );
<ide> }));
<ide> | 1 |
Ruby | Ruby | generate html5 number_field tag for integer fields | 4d1752bfb225e6e973375e10f52063060b49e666 | <ide><path>railties/lib/rails/generators/generated_attribute.rb
<ide> def initialize(name, type)
<ide>
<ide> def field_type
<ide> @field_type ||= case type
<del> when :integer, :float, :decimal then :text_field
<del> when :time then :time_select
<del> when :datetime, :timestamp then :datetime_select
<del> when :date then :date_select
<del> when :text then :text_area
<del> when :boolean then :check_box
<add> when :integer then :number_field
<add> when :float, :decimal then :text_field
<add> when :time then :time_select
<add> when :datetime, :timestamp then :datetime_select
<add> when :date then :date_select
<add> when :text then :text_area
<add> when :boolean then :check_box
<ide> else
<ide> :text_field
<ide> end
<ide><path>railties/test/generators/generated_attribute_test.rb
<ide> class GeneratedAttributeTest < Rails::Generators::TestCase
<ide> include GeneratorsTestHelper
<ide>
<add> def test_field_type_returns_number_field
<add> assert_field_type :integer, :number_field
<add> end
<add>
<ide> def test_field_type_returns_text_field
<del> %w(integer float decimal string).each do |attribute_type|
<add> %w(float decimal string).each do |attribute_type|
<ide> assert_field_type attribute_type, :text_field
<ide> end
<ide> end | 2 |
Text | Text | update docker inspect part of docs | 8d414fd434c55f1d9ac9387e17dd16608fca1bfd | <ide><path>docs/sources/reference/api/docker_remote_api_v1.17.md
<ide> Return low-level information on the container `id`
<ide> HTTP/1.1 200 OK
<ide> Content-Type: application/json
<ide>
<del> {
<del> "Id": "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2",
<del> "Created": "2013-05-07T14:51:42.041847+02:00",
<del> "Path": "date",
<del> "Args": [],
<del> "Config": {
<del> "Hostname": "4fa6e0f0c678",
<del> "User": "",
<del> "Memory": 0,
<del> "MemorySwap": 0,
<del> "AttachStdin": false,
<del> "AttachStdout": true,
<del> "AttachStderr": true,
<del> "PortSpecs": null,
<del> "Tty": false,
<del> "OpenStdin": false,
<del> "StdinOnce": false,
<del> "Env": null,
<del> "Cmd": [
<del> "date"
<del> ],
<del> "Dns": null,
<del> "Image": "base",
<del> "Volumes": {},
<del> "VolumesFrom": "",
<del> "WorkingDir": ""
<del> },
<del> "State": {
<del> "Running": false,
<del> "Pid": 0,
<del> "ExitCode": 0,
<del> "StartedAt": "2013-05-07T14:51:42.087658+02:01360",
<del> "Ghost": false
<del> },
<del> "Image": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc",
<del> "NetworkSettings": {
<del> "IpAddress": "",
<del> "IpPrefixLen": 0,
<del> "Gateway": "",
<del> "Bridge": "",
<del> "PortMapping": null
<del> },
<del> "SysInitPath": "/home/kitty/go/src/github.com/docker/docker/bin/docker",
<del> "ResolvConfPath": "/etc/resolv.conf",
<del> "Volumes": {},
<del> "ExecIDs": [
<del> "15f211491dced6a353a2e0f37fe3f3692ee2370a4782418e9bf7052865c10fde"
<del> ],
<del> "HostConfig": {
<del> "Binds": null,
<del> "ContainerIDFile": "",
<del> "LxcConf": [],
<del> "Privileged": false,
<del> "PortBindings": {
<del> "80/tcp": [
<del> {
<del> "HostIp": "0.0.0.0",
<del> "HostPort": "49153"
<del> }
<del> ]
<del> },
<del> "Links": ["/name:alias"],
<del> "PublishAllPorts": false,
<del> "CapAdd": ["NET_ADMIN"],
<del> "CapDrop": ["MKNOD"]
<del> }
<del> }
<add> {
<add> "AppArmorProfile": "",
<add> "Args": [
<add> "-c",
<add> "exit 9"
<add> ],
<add> "Config": {
<add> "AttachStderr": true,
<add> "AttachStdin": false,
<add> "AttachStdout": true,
<add> "Cmd": [
<add> "/bin/sh",
<add> "-c",
<add> "exit 9"
<add> ],
<add> "CpuShares": 0,
<add> "Cpuset": "",
<add> "Domainname": "",
<add> "Entrypoint": null,
<add> "Env": [
<add> "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
<add> ],
<add> "ExposedPorts": null,
<add> "Hostname": "ba033ac44011",
<add> "Image": "ubuntu",
<add> "MacAddress": "",
<add> "Memory": 0,
<add> "MemorySwap": 0,
<add> "NetworkDisabled": false,
<add> "OnBuild": null,
<add> "OpenStdin": false,
<add> "PortSpecs": null,
<add> "StdinOnce": false,
<add> "Tty": false,
<add> "User": "",
<add> "Volumes": null,
<add> "WorkingDir": ""
<add> },
<add> "Created": "2015-01-06T15:47:31.485331387Z",
<add> "Driver": "devicemapper",
<add> "ExecDriver": "native-0.2",
<add> "ExecIDs": null,
<add> "HostConfig": {
<add> "Binds": null,
<add> "CapAdd": null,
<add> "CapDrop": null,
<add> "ContainerIDFile": "",
<add> "Devices": [],
<add> "Dns": null,
<add> "DnsSearch": null,
<add> "ExtraHosts": null,
<add> "IpcMode": "",
<add> "Links": null,
<add> "LxcConf": [],
<add> "NetworkMode": "bridge",
<add> "PortBindings": {},
<add> "Privileged": false,
<add> "PublishAllPorts": false,
<add> "RestartPolicy": {
<add> "MaximumRetryCount": 2,
<add> "Name": "on-failure"
<add> },
<add> "SecurityOpt": null,
<add> "VolumesFrom": null
<add> },
<add> "HostnamePath": "/var/lib/docker/containers/ba033ac4401106a3b513bc9d639eee123ad78ca3616b921167cd74b20e25ed39/hostname",
<add> "HostsPath": "/var/lib/docker/containers/ba033ac4401106a3b513bc9d639eee123ad78ca3616b921167cd74b20e25ed39/hosts",
<add> "Id": "ba033ac4401106a3b513bc9d639eee123ad78ca3616b921167cd74b20e25ed39",
<add> "Image": "04c5d3b7b0656168630d3ba35d8889bd0e9caafcaeb3004d2bfbc47e7c5d35d2",
<add> "MountLabel": "",
<add> "Name": "/boring_euclid",
<add> "NetworkSettings": {
<add> "Bridge": "",
<add> "Gateway": "",
<add> "IPAddress": "",
<add> "IPPrefixLen": 0,
<add> "MacAddress": "",
<add> "PortMapping": null,
<add> "Ports": null
<add> },
<add> "Path": "/bin/sh",
<add> "ProcessLabel": "",
<add> "ResolvConfPath": "/var/lib/docker/containers/ba033ac4401106a3b513bc9d639eee123ad78ca3616b921167cd74b20e25ed39/resolv.conf",
<add> "RestartCount": 1,
<add> "State": {
<add> "Error": "",
<add> "ExitCode": 9,
<add> "FinishedAt": "2015-01-06T15:47:32.080254511Z",
<add> "OOMKilled": false,
<add> "Paused": false,
<add> "Pid": 0,
<add> "Restarting": false,
<add> "Running": false,
<add> "StartedAt": "2015-01-06T15:47:32.072697474Z"
<add> },
<add> "Volumes": {},
<add> "VolumesRW": {}
<add> }
<ide>
<ide> Status Codes:
<ide> | 1 |
Javascript | Javascript | fix lint error | b1047ad3e7a4fb0f3c8a5203e8ec983f97c21f91 | <ide><path>node-tests/blueprints/mixin-test.js
<ide> const setupTestHooks = blueprintHelpers.setupTestHooks;
<ide> const emberNew = blueprintHelpers.emberNew;
<ide> const emberGenerateDestroy = blueprintHelpers.emberGenerateDestroy;
<ide> const setupPodConfig = blueprintHelpers.setupPodConfig;
<del>const EOL = require('os').EOL;
<ide>
<ide> const chai = require('ember-cli-blueprint-test-helpers/chai');
<ide> const expect = chai.expect; | 1 |
Javascript | Javascript | use global chunkloading option | bbbe300e3a702d234f73009cf3e69bf3cb155bc9 | <ide><path>lib/RuntimePlugin.js
<ide> class RuntimePlugin {
<ide> */
<ide> apply(compiler) {
<ide> compiler.hooks.compilation.tap("RuntimePlugin", compilation => {
<add> const globalChunkLoading = compilation.outputOptions.chunkLoading;
<add> const isChunkLoadingDisabledForChunk = chunk => {
<add> const options = chunk.getEntryOptions();
<add> const chunkLoading =
<add> options && options.chunkLoading !== undefined
<add> ? options.chunkLoading
<add> : globalChunkLoading;
<add> return chunkLoading === false;
<add> };
<ide> compilation.dependencyTemplates.set(
<ide> RuntimeRequirementsDependency,
<ide> new RuntimeRequirementsDependency.Template()
<ide> class RuntimePlugin {
<ide> compilation.hooks.runtimeRequirementInTree
<ide> .for(RuntimeGlobals.baseURI)
<ide> .tap("RuntimePlugin", chunk => {
<del> const { chunkLoading } = chunk.getEntryOptions();
<del> if (chunkLoading === false) {
<add> if (isChunkLoadingDisabledForChunk(chunk)) {
<ide> compilation.addRuntimeModule(chunk, new BaseUriRuntimeModule());
<ide> return true;
<ide> } | 1 |
Go | Go | fix bad rebase where bridgeiface was removed | 347dc3942704742c1d24983a1e9cb10ae7ab8839 | <ide><path>config.go
<ide> func DaemonConfigFromJob(job *engine.Job) *DaemonConfig {
<ide> EnableIptables: job.GetenvBool("EnableIptables"),
<ide> EnableIpForward: job.GetenvBool("EnableIpForward"),
<ide> BridgeIP: job.Getenv("BridgeIP"),
<add> BridgeIface: job.Getenv("BridgeIface"),
<ide> DefaultIp: net.ParseIP(job.Getenv("DefaultIp")),
<ide> InterContainerCommunication: job.GetenvBool("InterContainerCommunication"),
<ide> GraphDriver: job.Getenv("GraphDriver"),
<ide> func DaemonConfigFromJob(job *engine.Job) *DaemonConfig {
<ide> } else {
<ide> config.Mtu = GetDefaultNetworkMtu()
<ide> }
<del> config.DisableNetwork = job.Getenv("BridgeIface") == DisableNetworkBridge
<add> config.DisableNetwork = config.BridgeIface == DisableNetworkBridge
<ide>
<ide> return config
<ide> } | 1 |
Javascript | Javascript | allow null, but not undefined state | 30f989d50b7368c4fa11c40f529909a196c21c33 | <ide><path>src/createDispatcher.js
<ide> export default function createDispatcher() {
<ide> (store, key) => {
<ide> const nextStoreState = store(state[key], action);
<ide> invariant(
<del> nextStoreState != null,
<del> 'State returned by %s is null or undefined.',
<add> typeof nextStoreState !== 'undefined',
<add> 'State returned by %s may not be undefined.',
<ide> key
<ide> );
<ide> return nextStoreState; | 1 |
Text | Text | add hint to replacing if else chains with switch | 2ab6d429f596ebae6f58b99192291357c861834e | <ide><path>client/src/pages/guide/english/certifications/javascript-algorithms-and-data-structures/basic-javascript/replacing-if-else-chains-with-switch/index.md
<del>---
<del>title: Replacing If Else Chains with Switch
<del>---
<add>
<ide> ## Replacing If Else Chains with Switch
<ide>
<del>This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/javascript-algorithms-and-data-structures/basic-javascript/replacing-if-else-chains-with-switch/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<add><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
<ide>
<del><a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<add>Here’s the setup:
<ide>
<del><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
<add>```javascript
<add>function chainToSwitch(val) {
<add> var answer = "";
<add> // Only change code below this line
<add> switch(val) {
<add> case "bob":
<add> answer = "Marley";
<add> break;
<add> case 42:
<add> answer = "The Answer";
<add> break;
<add> case 1:
<add> answer = "There is no #1";
<add> break;
<add> case 99:
<add> answer = "Missed me by this much!";
<add> break;
<add> case 7:
<add> answer = "Ate Nine";
<add> break;
<add> }
<add> // Only change code above this line
<add> return answer;
<add>}
<add>// Change this value to test
<add>chainToSwitch(7);
<add>```
<add>
<add>We need to change the chained ```if/else if``` statements into a ```switch``` statement.
<add>
<add> Here’s a solution:
<add>
<add> Now, we need to comment (```//``` - select all lines and ```ctrl+/```) all chained ```if/else if``` statements:
<add>
<add> ```javascript
<add> // if (val === "bob") {
<add>// answer = "Marley";
<add>// } else if (val === 42) {
<add>// answer = "The Answer";
<add>// } else if (val === 1) {
<add>// answer = "There is no #1";
<add>// } else if (val === 99) {
<add>// answer = "Missed me by this much!";
<add>// } else if (val === 7) {
<add>// answer = "Ate Nine";
<add>// }
<add> ```
<add>
<add> Next, we need to create simple ```switch``` statement:
<add>
<add> ```javascript
<add> switch(val) {
<add> }
<add> ```
<add>
<add> and add in this ```switch``` statement ```case``` - for all ```if/else if``` statement (just copy it from our commented code above):
<add>
<add> ```javascript
<add> switch(val) {
<add> case "bob":
<add> answer = "Marley";
<add> break;
<add> case 42:
<add> answer = "The Answer";
<add> break;
<add> case 1:
<add> answer = "There is no #1";
<add> break;
<add> case 99:
<add> answer = "Missed me by this much!";
<add> break;
<add> case 7:
<add> answer = "Ate Nine";
<add> break;
<add> }
<add> ```
<add>
<add> Dont forget to use ```break``` in each ```case```!
<add> Now, we can delete commented code with ```if/else if``` statement above.
<add>
<add> Here’s a full solution:
<add>
<add> ```javascript
<add> function chainToSwitch(val) {
<add> var answer = "";
<add> // Only change code below this line
<add> switch(val) {
<add> case "bob":
<add> answer = "Marley";
<add> break;
<add> case 42:
<add> answer = "The Answer";
<add> break;
<add> case 1:
<add> answer = "There is no #1";
<add> break;
<add> case 99:
<add> answer = "Missed me by this much!";
<add> break;
<add> case 7:
<add> answer = "Ate Nine";
<add> break;
<add> }
<add> // Only change code above this line
<add> return answer;
<add>}
<add>// Change this value to test
<add>chainToSwitch(7);
<add> ``` | 1 |
Go | Go | remove dupl setting of oomscoreadj in oci spec | f0b44881b5d43b18871dee2ecc2bb313046038f6 | <ide><path>daemon/oci_linux.go
<ide> func (daemon *Daemon) createSpec(c *container.Container) (*specs.Spec, error) {
<ide> if err := setResources(&s, c.HostConfig.Resources); err != nil {
<ide> return nil, fmt.Errorf("linux runtime spec resources: %v", err)
<ide> }
<del> s.Process.OOMScoreAdj = &c.HostConfig.OomScoreAdj
<ide> s.Linux.Sysctl = c.HostConfig.Sysctls
<ide>
<ide> p := s.Linux.CgroupsPath | 1 |
Javascript | Javascript | target src files from #142 | de564326b098583bf4edd95d698d6c97a8e612b3 | <ide><path>src/Chart.Core.js
<ide> this.ctx = context;
<ide>
<ide> //Variables global to the chart
<add> var computeDimension = function(element,dimension)
<add> {
<add> if (element['offset'+dimension])
<add> {
<add> return element['offset'+dimension];
<add> }
<add> else
<add> {
<add> return document.defaultView.getComputedStyle(element).getPropertyValue(dimension);
<add> }
<add> }
<add>
<add> var width = this.width = computeDimension(context.canvas,'Width');
<add> var height = this.height = computeDimension(context.canvas,'Height');
<add>
<add> // Firefox requires this to work correctly
<add> context.canvas.width = width;
<add> context.canvas.height = height;
<add>
<ide> var width = this.width = context.canvas.width;
<ide> var height = this.height = context.canvas.height;
<ide> this.aspectRatio = this.width / this.height; | 1 |
Python | Python | fix multiarray from/to-file test under windows | 4b76f6253521f5dd7b6cc1be890f2e4cb08f3ac6 | <ide><path>numpy/core/tests/test_multiarray.py
<ide> def setUp(self):
<ide> rand = np.random.random
<ide>
<ide> self.x = rand(shape) + rand(shape).astype(np.complex)*1j
<del> self.dtype = np.complex
<add> self.dtype = self.x.dtype
<ide>
<ide> def test_file(self):
<del> # Python under Windows does not believe that TemporaryFile
<del> # is an open file
<del> if sys.platform.startswith('win'):
<del> filename = tempfile.mktemp()
<del> f = open(filename,'wb')
<del> else:
<del> f = tempfile.TemporaryFile()
<del>
<del> self.x.tofile(f)
<del> f.flush()
<del> f.seek(0)
<del> y = np.fromfile(f,dtype=self.dtype)
<del> assert_array_equal(y,self.x.flat)
<add> # Test disabled on Windows, since the tempfile does not flush
<add> # properly. The test ensures that both filenames and file
<add> # objects are accepted in tofile and fromfile, so as long as
<add> # it runs on at least one platform, we should be ok.
<add> if not sys.platform.startswith('win'):
<add> tmp_file = tempfile.NamedTemporaryFile('wb',
<add> prefix='numpy_tofromfile')
<add> self.x.tofile(tmp_file.file)
<add> tmp_file.flush()
<add> y = np.fromfile(tmp_file.name,dtype=self.dtype)
<add> assert_array_equal(y,self.x.flat)
<ide>
<ide> def test_filename(self):
<ide> filename = tempfile.mktemp() | 1 |
Go | Go | add unit test for file deletion | 97535e5a6466dcad6ed9767960e869eadf68204f | <ide><path>container_test.go
<ide> func TestMultipleAttachRestart(t *testing.T) {
<ide> }
<ide> }
<ide>
<add>func TestDiff(t *testing.T) {
<add> runtime, err := newTestRuntime()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> defer nuke(runtime)
<add>
<add> // Create a container and remove a file
<add> container1, err := runtime.Create(
<add> &Config{
<add> Image: GetTestImage(runtime).Id,
<add> Cmd: []string{"/bin/rm", "/etc/passwd"},
<add> },
<add> )
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> defer runtime.Destroy(container1)
<add>
<add> if err := container1.Run(); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> // Check the changelog
<add> c, err := container1.Changes()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> success := false
<add> for _, elem := range c {
<add> if elem.Path == "/etc/passwd" && elem.Kind == 2 {
<add> success = true
<add> }
<add> }
<add> if !success {
<add> t.Fatalf("/etc/passwd as been removed but is not present in the diff")
<add> }
<add>
<add> // Commit the container
<add> rwTar, err := container1.ExportRw()
<add> if err != nil {
<add> t.Error(err)
<add> }
<add> img, err := runtime.graph.Create(rwTar, container1, "unit test commited image - diff", "")
<add> if err != nil {
<add> t.Error(err)
<add> }
<add>
<add> // Create a new container from the commited image
<add> container2, err := runtime.Create(
<add> &Config{
<add> Image: img.Id,
<add> Cmd: []string{"cat", "/etc/passwd"},
<add> },
<add> )
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> defer runtime.Destroy(container2)
<add>
<add> if err := container2.Run(); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> // Check the changelog
<add> c, err = container2.Changes()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> for _, elem := range c {
<add> if elem.Path == "/etc/passwd" {
<add> t.Fatalf("/etc/passwd should not be present in the diff after commit.")
<add> }
<add> }
<add>}
<add>
<ide> func TestCommitRun(t *testing.T) {
<ide> runtime, err := newTestRuntime()
<ide> if err != nil { | 1 |
Java | Java | add resolvedresource in resource handling chain | ccb3c44dbcd4ab4741aec7b366ed43efa2f90b44 | <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/resource/EncodedResource.java
<del>/*
<del> * Copyright 2002-2015 the original author or authors.
<del> *
<del> * Licensed under the Apache License, Version 2.0 (the "License");
<del> * you may not use this file except in compliance with the License.
<del> * You may obtain a copy of the License at
<del> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS,
<del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del> * See the License for the specific language governing permissions and
<del> * limitations under the License.
<del> */
<del>
<del>package org.springframework.web.reactive.resource;
<del>
<del>import org.springframework.core.io.Resource;
<del>
<del>/**
<del> * Interface for a resource descriptor that describes the encoding
<del> * applied to the entire resource content.
<del> *
<del> * <p>This information is required if the client consuming that resource
<del> * needs additional decoding capabilities to retrieve the resource's content.
<del> *
<del> * @author Rossen Stoyanchev
<del> * @since 5.0
<del> * @see <a href="http://tools.ietf.org/html/rfc7231#section-3.1.2.2">
<del> * HTTP/1.1: Semantics and Content, section 3.1.2.2</a>
<del> */
<del>public interface EncodedResource extends Resource {
<del>
<del> /**
<del> * The content coding value, as defined in the IANA registry
<del> * @return the content encoding
<del> * @see <a href="http://tools.ietf.org/html/rfc7231#section-3.1.2.1">HTTP/1.1: Semantics
<del> * and Content, section 3.1.2.1</a>
<del> */
<del> String getContentEncoding();
<del>
<del>}
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/resource/GzipResourceResolver.java
<ide>
<ide> import org.springframework.core.io.AbstractResource;
<ide> import org.springframework.core.io.Resource;
<add>import org.springframework.http.HttpHeaders;
<ide> import org.springframework.web.server.ServerWebExchange;
<ide>
<ide> /**
<ide> protected String resolveUrlPathInternal(String resourceUrlPath, List<? extends R
<ide> }
<ide>
<ide>
<del> private static final class GzippedResource extends AbstractResource implements EncodedResource {
<add> private static final class GzippedResource extends AbstractResource implements ResolvedResource {
<ide>
<ide> private final Resource original;
<ide>
<ide> public String getDescription() {
<ide> return this.gzipped.getDescription();
<ide> }
<ide>
<del> public String getContentEncoding() {
<del> return "gzip";
<add> @Override
<add> public HttpHeaders getResponseHeaders() {
<add> HttpHeaders headers;
<add> if(this.original instanceof ResolvedResource) {
<add> headers = ((ResolvedResource) this.original).getResponseHeaders();
<add> }
<add> else {
<add> headers = new HttpHeaders();
<add> }
<add> headers.add(HttpHeaders.CONTENT_ENCODING, "gzip");
<add> return headers;
<ide> }
<ide> }
<ide>
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/resource/ResolvedResource.java
<add>package org.springframework.web.reactive.resource;
<add>
<add>import org.springframework.core.io.Resource;
<add>import org.springframework.http.HttpHeaders;
<add>
<add>/**
<add> * Interface for resources resolved through the
<add> * {@link org.springframework.web.reactive.resource.ResourceResolverChain}
<add> * that may contribute HTTP response headers as they're served to HTTP clients.
<add> *
<add> * <p>Some resource implementations, while served by the
<add> * {@link org.springframework.web.reactive.resource.ResourceResolverChain} need
<add> * to contribute resource metadata as HTTP response headers so that HTTP clients
<add> * can interpret them properly.
<add> *
<add> * @author Brian Clozel
<add> * @since 5.0
<add> */
<add>public interface ResolvedResource extends Resource {
<add>
<add> /**
<add> * The HTTP headers to be contributed to the HTTP response
<add> * that serves the current resource.
<add> * @return the HTTP response headers
<add> */
<add> HttpHeaders getResponseHeaders();
<add>}
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/resource/ResourceWebHandler.java
<ide> protected void setHeaders(ServerWebExchange exchange, Resource resource, MediaTy
<ide> if (mediaType != null) {
<ide> headers.setContentType(mediaType);
<ide> }
<del> if (resource instanceof EncodedResource) {
<del> headers.set(HttpHeaders.CONTENT_ENCODING, ((EncodedResource) resource).getContentEncoding());
<del> }
<del> if (resource instanceof VersionedResource) {
<del> headers.setETag("\"" + ((VersionedResource) resource).getVersion() + "\"");
<add> if (resource instanceof ResolvedResource) {
<add> HttpHeaders resourceHeaders = ((ResolvedResource) resource).getResponseHeaders();
<add> exchange.getResponse().getHeaders().putAll(resourceHeaders);
<ide> }
<ide> headers.set(HttpHeaders.ACCEPT_RANGES, "bytes");
<ide> }
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/resource/VersionResourceResolver.java
<ide>
<ide> import org.springframework.core.io.AbstractResource;
<ide> import org.springframework.core.io.Resource;
<add>import org.springframework.http.HttpHeaders;
<ide> import org.springframework.util.AntPathMatcher;
<ide> import org.springframework.util.StringUtils;
<ide> import org.springframework.web.server.ServerWebExchange;
<ide> protected VersionStrategy getStrategyForPath(String requestPath) {
<ide> }
<ide>
<ide>
<del> private class FileNameVersionedResource extends AbstractResource implements VersionedResource {
<add> private class FileNameVersionedResource extends AbstractResource implements ResolvedResource {
<ide>
<ide> private final Resource original;
<ide>
<ide> public InputStream getInputStream() throws IOException {
<ide> }
<ide>
<ide> @Override
<del> public String getVersion() {
<del> return this.version;
<add> public HttpHeaders getResponseHeaders() {
<add> HttpHeaders headers;
<add> if(this.original instanceof ResolvedResource) {
<add> headers = ((ResolvedResource) this.original).getResponseHeaders();
<add> }
<add> else {
<add> headers = new HttpHeaders();
<add> }
<add> headers.setETag("\"" + this.version + "\"");
<add> return headers;
<ide> }
<ide> }
<ide>
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/resource/VersionedResource.java
<del>/*
<del> * Copyright 2002-2016 the original author or authors.
<del> *
<del> * Licensed under the Apache License, Version 2.0 (the "License");
<del> * you may not use this file except in compliance with the License.
<del> * You may obtain a copy of the License at
<del> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS,
<del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del> * See the License for the specific language governing permissions and
<del> * limitations under the License.
<del> */
<del>
<del>package org.springframework.web.reactive.resource;
<del>
<del>import org.springframework.core.io.Resource;
<del>
<del>/**
<del> * Interface for a resource descriptor that describes its version with a
<del> * version string that can be derived from its content and/or metadata.
<del> *
<del> * @author Rossen Stoyanchev
<del> * @author Brian Clozel
<del> * @since 5.0
<del> * @see VersionResourceResolver
<del> */
<del>public interface VersionedResource extends Resource {
<del>
<del> String getVersion();
<del>
<del>}
<ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/resource/GzipResourceResolverTests.java
<ide> public void resolveGzippedFile() throws IOException {
<ide> Resource resource = new ClassPathResource("test/" + gzFile, getClass());
<ide> assertEquals(resource.getDescription(), resolved.getDescription());
<ide> assertEquals(new ClassPathResource("test/" + file).getFilename(), resolved.getFilename());
<del> assertTrue("Expected " + resolved + " to be of type " + EncodedResource.class,
<del> resolved instanceof EncodedResource);
<add> assertTrue("Expected " + resolved + " to be of type " + ResolvedResource.class,
<add> resolved instanceof ResolvedResource);
<ide> }
<ide>
<ide> @Test
<ide> public void resolveFingerprintedGzippedFile() throws IOException {
<ide> Resource resource = new ClassPathResource("test/" + gzFile, getClass());
<ide> assertEquals(resource.getDescription(), resolved.getDescription());
<ide> assertEquals(new ClassPathResource("test/"+file).getFilename(), resolved.getFilename());
<del> assertTrue("Expected " + resolved + " to be of type " + EncodedResource.class,
<del> resolved instanceof EncodedResource);
<add> assertTrue("Expected " + resolved + " to be of type " + ResolvedResource.class,
<add> resolved instanceof ResolvedResource);
<ide> }
<ide>
<ide> @Test
<ide> public void resolveFromCacheWithEncodingVariants() throws IOException {
<ide> Resource gzResource = new ClassPathResource("test/"+gzFile, getClass());
<ide> assertEquals(gzResource.getDescription(), resolved.getDescription());
<ide> assertEquals(new ClassPathResource("test/" + file).getFilename(), resolved.getFilename());
<del> assertTrue("Expected " + resolved + " to be of type " + EncodedResource.class,
<del> resolved instanceof EncodedResource);
<add> assertTrue("Expected " + resolved + " to be of type " + ResolvedResource.class,
<add> resolved instanceof ResolvedResource);
<ide>
<ide> // resolved resource is now cached in CachingResourceResolver
<ide>
<ide> public void resolveFromCacheWithEncodingVariants() throws IOException {
<ide> Resource resource = new ClassPathResource("test/"+file, getClass());
<ide> assertEquals(resource.getDescription(), resolved.getDescription());
<ide> assertEquals(new ClassPathResource("test/" + file).getFilename(), resolved.getFilename());
<del> assertFalse("Expected " + resolved + " to *not* be of type " + EncodedResource.class,
<del> resolved instanceof EncodedResource);
<add> assertFalse("Expected " + resolved + " to *not* be of type " + ResolvedResource.class,
<add> resolved instanceof ResolvedResource);
<ide> }
<ide>
<ide> @Test // SPR-13149
<ide> public void resolveWithNullRequest() throws IOException {
<ide> Resource gzResource = new ClassPathResource("test/" + gzFile, getClass());
<ide> assertEquals(gzResource.getDescription(), resolved.getDescription());
<ide> assertEquals(new ClassPathResource("test/" + file).getFilename(), resolved.getFilename());
<del> assertTrue("Expected " + resolved + " to be of type " + EncodedResource.class,
<del> resolved instanceof EncodedResource);
<add> assertTrue("Expected " + resolved + " to be of type " + ResolvedResource.class,
<add> resolved instanceof ResolvedResource);
<ide> }
<ide> }
<ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/resource/VersionResourceResolverTests.java
<ide> public void resolveResourceSuccess() throws Exception {
<ide> Resource actual = this.resolver.resolveResourceInternal(exchange, versionFile, this.locations, this.chain);
<ide> assertEquals(expected.getFilename(), actual.getFilename());
<ide> verify(this.versionStrategy, times(1)).getResourceVersion(expected);
<del> assertThat(actual, instanceOf(VersionedResource.class));
<del> assertEquals(version, ((VersionedResource)actual).getVersion());
<add> assertThat(actual, instanceOf(ResolvedResource.class));
<add> assertEquals("\"" + version + "\"", ((ResolvedResource)actual).getResponseHeaders().getETag());
<ide> }
<ide>
<ide> @Test
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/resource/EncodedResource.java
<del>/*
<del> * Copyright 2002-2015 the original author or authors.
<del> *
<del> * Licensed under the Apache License, Version 2.0 (the "License");
<del> * you may not use this file except in compliance with the License.
<del> * You may obtain a copy of the License at
<del> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS,
<del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del> * See the License for the specific language governing permissions and
<del> * limitations under the License.
<del> */
<del>
<del>package org.springframework.web.servlet.resource;
<del>
<del>import org.springframework.core.io.Resource;
<del>
<del>/**
<del> * Interface for a resource descriptor that describes the encoding
<del> * applied to the entire resource content.
<del> *
<del> * <p>This information is required if the client consuming that resource
<del> * needs additional decoding capabilities to retrieve the resource's content.
<del> *
<del> * @author Jeremy Grelle
<del> * @since 4.1
<del> * @see <a href="http://tools.ietf.org/html/rfc7231#section-3.1.2.2">HTTP/1.1: Semantics
<del> * and Content, section 3.1.2.2</a>
<del> */
<del>public interface EncodedResource extends Resource {
<del>
<del> /**
<del> * The content coding value, as defined in the IANA registry
<del> * @return the content encoding
<del> * @see <a href="http://tools.ietf.org/html/rfc7231#section-3.1.2.1">HTTP/1.1: Semantics
<del> * and Content, section 3.1.2.1</a>
<del> */
<del> String getContentEncoding();
<del>
<del>}
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/resource/GzipResourceResolver.java
<ide> import java.net.URI;
<ide> import java.net.URL;
<ide> import java.util.List;
<add>
<ide> import javax.servlet.http.HttpServletRequest;
<ide>
<ide> import org.springframework.core.io.AbstractResource;
<ide> import org.springframework.core.io.Resource;
<add>import org.springframework.http.HttpHeaders;
<ide>
<ide> /**
<ide> * A {@code ResourceResolver} that delegates to the chain to locate a resource
<ide> protected String resolveUrlPathInternal(String resourceUrlPath, List<? extends R
<ide> }
<ide>
<ide>
<del> private static final class GzippedResource extends AbstractResource implements EncodedResource {
<add> private static final class GzippedResource extends AbstractResource implements ResolvedResource {
<ide>
<ide> private final Resource original;
<ide>
<ide> public String getDescription() {
<ide> return this.gzipped.getDescription();
<ide> }
<ide>
<del> public String getContentEncoding() {
<del> return "gzip";
<add> @Override
<add> public HttpHeaders getResponseHeaders() {
<add> HttpHeaders headers;
<add> if(this.original instanceof ResolvedResource) {
<add> headers = ((ResolvedResource) this.original).getResponseHeaders();
<add> }
<add> else {
<add> headers = new HttpHeaders();
<add> }
<add> headers.add(HttpHeaders.CONTENT_ENCODING, "gzip");
<add> return headers;
<ide> }
<add>
<ide> }
<ide>
<ide> }
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/resource/ResolvedResource.java
<add>package org.springframework.web.servlet.resource;
<add>
<add>import org.springframework.core.io.Resource;
<add>import org.springframework.http.HttpHeaders;
<add>
<add>/**
<add> * Interface for resources resolved through the
<add> * {@link org.springframework.web.servlet.resource.ResourceResolverChain}
<add> * that may contribute HTTP response headers as they're served to HTTP clients.
<add> *
<add> * <p>Some resource implementations, while served by the
<add> * {@link org.springframework.web.servlet.resource.ResourceResolverChain} need
<add> * to contribute resource metadata as HTTP response headers so that HTTP clients
<add> * can interpret them properly.
<add> *
<add> * @author Brian Clozel
<add> * @since 5.0
<add> */
<add>public interface ResolvedResource extends Resource {
<add>
<add> /**
<add> * The HTTP headers to be contributed to the HTTP response
<add> * that serves the current resource.
<add> * @return the HTTP response headers
<add> */
<add> HttpHeaders getResponseHeaders();
<add>}
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandler.java
<ide> protected void setHeaders(HttpServletResponse response, Resource resource, Media
<ide> if (mediaType != null) {
<ide> response.setContentType(mediaType.toString());
<ide> }
<del> if (resource instanceof EncodedResource) {
<del> response.setHeader(HttpHeaders.CONTENT_ENCODING, ((EncodedResource) resource).getContentEncoding());
<del> }
<del> if (resource instanceof VersionedResource) {
<del> response.setHeader(HttpHeaders.ETAG, "\"" + ((VersionedResource) resource).getVersion() + "\"");
<add> if (resource instanceof ResolvedResource) {
<add> HttpHeaders resourceHeaders = ((ResolvedResource) resource).getResponseHeaders();
<add> resourceHeaders.toSingleValueMap().entrySet()
<add> .stream().forEach(entry -> response.setHeader(entry.getKey(), entry.getValue()));
<ide> }
<ide> response.setHeader(HttpHeaders.ACCEPT_RANGES, "bytes");
<ide> }
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/resource/VersionResourceResolver.java
<ide>
<ide> import org.springframework.core.io.AbstractResource;
<ide> import org.springframework.core.io.Resource;
<add>import org.springframework.http.HttpHeaders;
<ide> import org.springframework.util.AntPathMatcher;
<ide> import org.springframework.util.StringUtils;
<ide>
<ide> protected VersionStrategy getStrategyForPath(String requestPath) {
<ide> }
<ide>
<ide>
<del> private class FileNameVersionedResource extends AbstractResource implements VersionedResource {
<add> private class FileNameVersionedResource extends AbstractResource implements ResolvedResource {
<ide>
<ide> private final Resource original;
<ide>
<ide> public InputStream getInputStream() throws IOException {
<ide> }
<ide>
<ide> @Override
<del> public String getVersion() {
<del> return this.version;
<add> public HttpHeaders getResponseHeaders() {
<add> HttpHeaders headers;
<add> if(this.original instanceof ResolvedResource) {
<add> headers = ((ResolvedResource) this.original).getResponseHeaders();
<add> }
<add> else {
<add> headers = new HttpHeaders();
<add> }
<add> headers.setETag("\"" + this.version + "\"");
<add> return headers;
<ide> }
<add>
<ide> }
<ide>
<ide> }
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/resource/VersionedResource.java
<del>/*
<del> * Copyright 2002-2016 the original author or authors.
<del> *
<del> * Licensed under the Apache License, Version 2.0 (the "License");
<del> * you may not use this file except in compliance with the License.
<del> * You may obtain a copy of the License at
<del> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS,
<del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del> * See the License for the specific language governing permissions and
<del> * limitations under the License.
<del> */
<del>
<del>package org.springframework.web.servlet.resource;
<del>
<del>import org.springframework.core.io.Resource;
<del>
<del>/**
<del> * Interface for a resource descriptor that describes its version with a
<del> * version string that can be derived from its content and/or metadata.
<del> *
<del> * @author Brian Clozel
<del> * @since 4.2.5
<del> * @see VersionResourceResolver
<del> */
<del>public interface VersionedResource extends Resource {
<del>
<del> String getVersion();
<del>
<del>}
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/resource/GzipResourceResolverTests.java
<ide> public void resolveGzippedFile() throws IOException {
<ide> Resource resource = new ClassPathResource("test/"+gzFile, getClass());
<ide> assertEquals(resource.getDescription(), resolved.getDescription());
<ide> assertEquals(new ClassPathResource("test/" + file).getFilename(), resolved.getFilename());
<del> assertTrue("Expected " + resolved + " to be of type " + EncodedResource.class,
<del> resolved instanceof EncodedResource);
<add> assertTrue("Expected " + resolved + " to be of type " + ResolvedResource.class,
<add> resolved instanceof ResolvedResource);
<ide> }
<ide>
<ide> @Test
<ide> public void resolveFingerprintedGzippedFile() throws IOException {
<ide> Resource resource = new ClassPathResource("test/"+gzFile, getClass());
<ide> assertEquals(resource.getDescription(), resolved.getDescription());
<ide> assertEquals(new ClassPathResource("test/"+file).getFilename(), resolved.getFilename());
<del> assertTrue("Expected " + resolved + " to be of type " + EncodedResource.class,
<del> resolved instanceof EncodedResource);
<add> assertTrue("Expected " + resolved + " to be of type " + ResolvedResource.class,
<add> resolved instanceof ResolvedResource);
<ide> }
<ide>
<ide> @Test
<ide> public void resolveFromCacheWithEncodingVariants() throws IOException {
<ide> Resource gzResource = new ClassPathResource("test/"+gzFile, getClass());
<ide> assertEquals(gzResource.getDescription(), resolved.getDescription());
<ide> assertEquals(new ClassPathResource("test/" + file).getFilename(), resolved.getFilename());
<del> assertTrue("Expected " + resolved + " to be of type " + EncodedResource.class,
<del> resolved instanceof EncodedResource);
<add> assertTrue("Expected " + resolved + " to be of type " + ResolvedResource.class,
<add> resolved instanceof ResolvedResource);
<ide>
<ide> // resolved resource is now cached in CachingResourceResolver
<ide>
<ide> public void resolveFromCacheWithEncodingVariants() throws IOException {
<ide> Resource resource = new ClassPathResource("test/"+file, getClass());
<ide> assertEquals(resource.getDescription(), resolved.getDescription());
<ide> assertEquals(new ClassPathResource("test/" + file).getFilename(), resolved.getFilename());
<del> assertFalse("Expected " + resolved + " to *not* be of type " + EncodedResource.class,
<del> resolved instanceof EncodedResource);
<add> assertFalse("Expected " + resolved + " to *not* be of type " + ResolvedResource.class,
<add> resolved instanceof ResolvedResource);
<ide> }
<ide>
<ide> @Test // SPR-13149
<ide> public void resolveWithNullRequest() throws IOException {
<ide> Resource gzResource = new ClassPathResource("test/"+gzFile, getClass());
<ide> assertEquals(gzResource.getDescription(), resolved.getDescription());
<ide> assertEquals(new ClassPathResource("test/" + file).getFilename(), resolved.getFilename());
<del> assertTrue("Expected " + resolved + " to be of type " + EncodedResource.class,
<del> resolved instanceof EncodedResource);
<add> assertTrue("Expected " + resolved + " to be of type " + ResolvedResource.class,
<add> resolved instanceof ResolvedResource);
<ide> }
<ide>
<ide> }
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/resource/VersionResourceResolverTests.java
<ide> public void resolveResourceSuccess() throws Exception {
<ide> Resource actual = this.resolver.resolveResourceInternal(request, versionFile, this.locations, this.chain);
<ide> assertEquals(expected.getFilename(), actual.getFilename());
<ide> verify(this.versionStrategy, times(1)).getResourceVersion(expected);
<del> assertThat(actual, instanceOf(VersionedResource.class));
<del> assertEquals(version, ((VersionedResource)actual).getVersion());
<add> assertThat(actual, instanceOf(ResolvedResource.class));
<add> assertEquals("\"" + version + "\"", ((ResolvedResource)actual).getResponseHeaders().getETag());
<ide> }
<ide>
<ide> @Test | 16 |
PHP | PHP | deprecate public properties on serverrequest | fcb3f086d38c0ed4553f15a5fc8ea426d60d5f17 | <ide><path>src/Http/ServerRequest.php
<ide> class ServerRequest implements ArrayAccess, ServerRequestInterface
<ide> * @var array
<ide> * @deprecated 3.4.0 This public property will be removed in 4.0.0. Use getParam() instead.
<ide> */
<del> public $params = [
<add> protected $params = [
<ide> 'plugin' => null,
<ide> 'controller' => null,
<ide> 'action' => null,
<ide> class ServerRequest implements ArrayAccess, ServerRequestInterface
<ide> * @var array
<ide> * @deprecated 3.4.0 This public property will be removed in 4.0.0. Use getData() instead.
<ide> */
<del> public $data = [];
<add> protected $data = [];
<ide>
<ide> /**
<ide> * Array of query string arguments
<ide> *
<ide> * @var array
<ide> * @deprecated 3.4.0 This public property will be removed in 4.0.0. Use getQuery() or getQueryParams() instead.
<ide> */
<del> public $query = [];
<add> protected $query = [];
<ide>
<ide> /**
<ide> * Array of cookie data.
<ide> *
<ide> * @var array
<ide> * @deprecated 3.4.0 This public property will be removed in 4.0.0. Use getCookie() instead.
<ide> */
<del> public $cookies = [];
<add> protected $cookies = [];
<ide>
<ide> /**
<ide> * Array of environment data.
<ide> class ServerRequest implements ArrayAccess, ServerRequestInterface
<ide> * The URL string used for the request.
<ide> *
<ide> * @var string
<add> * @deprecated 3.6.0 This public property will be removed in 4.0.0. Use getRequestTarget() instead.
<ide> */
<del> public $url;
<add> protected $url;
<ide>
<ide> /**
<ide> * Base URL path.
<ide> *
<ide> * @var string
<ide> * @deprecated 3.4.0 This public property will be removed in 4.0.0. Use getAttribute('base') instead.
<ide> */
<del> public $base;
<add> protected $base;
<ide>
<ide> /**
<ide> * webroot path segment for the request.
<ide> *
<ide> * @var string
<ide> * @deprecated 3.4.0 This public property will be removed in 4.0.0. Use getAttribute('webroot') instead.
<ide> */
<del> public $webroot = '/';
<add> protected $webroot = '/';
<ide>
<ide> /**
<ide> * The full address to the current request
<ide> *
<ide> * @var string
<ide> * @deprecated 3.4.0 This public property will be removed in 4.0.0. Use getUri()->getPath() instead.
<ide> */
<del> public $here;
<add> protected $here;
<ide>
<ide> /**
<ide> * Whether or not to trust HTTP_X headers set by most load balancers.
<ide> class ServerRequest implements ArrayAccess, ServerRequestInterface
<ide> */
<ide> protected $requestTarget;
<ide>
<add> /**
<add> * List of deprecated properties that have backwards
<add> * compatibility offered through magic methods.
<add> *
<add> * @var array
<add> */
<add> private $deprecatedProperties = [
<add> 'data' => ['get' => 'getData()', 'set' => 'withData()'],
<add> 'query' => ['get' => 'getQuery()', 'set' => 'withQueryParams()'],
<add> 'params' => ['get' => 'getParam()', 'set' => 'withParam()'],
<add> 'cookies' => ['get' => 'getCookie()', 'set' => 'withCookieParams()'],
<add> 'url' => ['get' => 'getRequestTarget()', 'set' => 'withRequestTarget()'],
<add> 'base' => ['get' => 'getAttribute("base")', 'set' => 'withAttribute("base")'],
<add> 'webroot' => ['get' => 'getAttribute("webroot")', 'set' => 'withAttribute("webroot")'],
<add> 'here' => ['get' => 'getRequestTarget()', 'set' => 'withRequestTarget()'],
<add> ];
<add>
<ide> /**
<ide> * Wrapper method to create a new request from PHP superglobals.
<ide> *
<ide> public function __call($name, $params)
<ide> throw new BadMethodCallException(sprintf('Method %s does not exist', $name));
<ide> }
<ide>
<add> /**
<add> * Magic set method allows backward compatibility for former public properties
<add> *
<add> *
<add> * @param string $name The property being accessed.
<add> * @param mixed $value The property value.
<add> * @return mixed Either the value of the parameter or null.
<add> * @deprecated 3.6.0 Public properties will be removed in 4.0.0.
<add> * Use appropriate setters instead.
<add> */
<add> public function __set($name, $value)
<add> {
<add> if (isset($this->deprecatedProperties[$name])) {
<add> $method = $this->deprecatedProperties[$name]['set'];
<add> deprecationWarning(
<add> "Setting {$name} as a property will be removed in 4.0.0. " .
<add> "Use {$method} instead."
<add> );
<add> return $this->{$name} = $value;
<add> }
<add> throw new BadMethodCallException("Cannot set {$name} it is not a known property.");
<add> }
<add>
<ide> /**
<ide> * Magic get method allows access to parsed routing parameters directly on the object.
<ide> *
<ide> public function __call($name, $params)
<ide> * @deprecated 3.4.0 Accessing routing parameters through __get will removed in 4.0.0.
<ide> * Use getParam() instead.
<ide> */
<del> public function __get($name)
<add> public function &__get($name)
<ide> {
<add> if (isset($this->deprecatedProperties[$name])) {
<add> $method = $this->deprecatedProperties[$name]['get'];
<add> deprecationWarning(
<add> "Accessing `{$name}` as a property will be removed in 4.0.0. " .
<add> "Use request->{$method} instead."
<add> );
<add> return $this->{$name};
<add> }
<add>
<ide> deprecationWarning(sprintf(
<ide> 'Accessing routing parameters through `%s` will removed in 4.0.0. ' .
<ide> 'Use `getParam()` instead.',
<ide> public function __get($name)
<ide> if (isset($this->params[$name])) {
<ide> return $this->params[$name];
<ide> }
<add> $value = null;
<ide>
<del> return null;
<add> return $value;
<ide> }
<ide>
<ide> /**
<ide> public function __get($name)
<ide> */
<ide> public function __isset($name)
<ide> {
<add> if (isset($this->deprecatedProperties[$name])) {
<add> $method = $this->deprecatedProperties[$name]['get'];
<add> deprecationWarning(
<add> "Accessing {$name} as a property will be removed in 4.0.0. " .
<add> "Use {$method} instead."
<add> );
<add> return isset($this->{$name});
<add> }
<add>
<ide> deprecationWarning(
<ide> 'Accessing routing parameters through __isset will removed in 4.0.0. ' .
<ide> 'Use getParam() instead.'
<ide><path>tests/TestCase/Http/ServerRequestTest.php
<ide> public function testNoAutoParseConstruction()
<ide> 'one' => 'param'
<ide> ];
<ide> $request = new ServerRequest();
<del> $this->assertFalse(isset($request->query['one']));
<add> $this->assertNull($request->getQuery('one'));
<ide> }
<ide>
<ide> /**
<ide> public function testConstructionQueryData()
<ide> 'url' => 'some/path'
<ide> ];
<ide> $request = new ServerRequest($data);
<del> $this->assertEquals($request->query, $data['query']);
<del> $this->assertEquals('some/path', $request->url);
<add> $this->assertEquals($request->getQueryParams(), $data['query']);
<add> $this->assertEquals('/some/path', $request->getRequestTarget());
<ide> }
<ide>
<ide> /**
<ide> public function testQueryStringParsingFromInputUrl()
<ide> $_GET = [];
<ide> $request = new ServerRequest(['url' => 'some/path?one=something&two=else']);
<ide> $expected = ['one' => 'something', 'two' => 'else'];
<del> $this->assertEquals($expected, $request->query);
<del> $this->assertEquals('some/path', $request->url);
<add> $this->assertEquals($expected, $request->getQueryParams());
<add> $this->assertEquals('/some/path', $request->getUri()->getPath());
<ide> $this->assertEquals('one=something&two=else', $request->getUri()->getQuery());
<ide> }
<ide>
<ide> public function testQueryStringAndNamedParams()
<ide> {
<ide> $_SERVER['REQUEST_URI'] = '/tasks/index?ts=123456';
<ide> $request = ServerRequestFactory::fromGlobals();
<del> $this->assertEquals('tasks/index', $request->url);
<add> $this->assertEquals('/tasks/index', $request->getRequestTarget());
<ide>
<ide> $_SERVER['REQUEST_URI'] = '/tasks/index/?ts=123456';
<ide> $request = ServerRequestFactory::fromGlobals();
<del> $this->assertEquals('tasks/index/', $request->url);
<add> $this->assertEquals('/tasks/index/', $request->getRequestTarget());
<ide>
<ide> $_SERVER['REQUEST_URI'] = '/some/path?url=http://cakephp.org';
<ide> $request = ServerRequestFactory::fromGlobals();
<del> $this->assertEquals('some/path', $request->url);
<add> $this->assertEquals('/some/path', $request->getRequestTarget());
<ide>
<ide> $_SERVER['REQUEST_URI'] = Configure::read('App.fullBaseUrl') . '/other/path?url=http://cakephp.org';
<ide> $request = ServerRequestFactory::fromGlobals();
<del> $this->assertEquals('other/path', $request->url);
<add> $this->assertEquals('/other/path', $request->getRequestTarget());
<ide> }
<ide>
<ide> /**
<ide> public function testUrlInPath()
<ide> {
<ide> $_SERVER['REQUEST_URI'] = '/jump/http://cakephp.org';
<ide> $request = ServerRequestFactory::fromGlobals();
<del> $this->assertEquals('jump/http://cakephp.org', $request->url);
<add> $this->assertEquals('/jump/http://cakephp.org', $request->getRequestTarget());
<ide>
<ide> $_SERVER['REQUEST_URI'] = Configure::read('App.fullBaseUrl') . '/jump/http://cakephp.org';
<ide> $request = ServerRequestFactory::fromGlobals();
<del> $this->assertEquals('jump/http://cakephp.org', $request->url);
<add> $this->assertEquals('/jump/http://cakephp.org', $request->getRequestTarget());
<ide> }
<ide>
<ide> /**
<ide> public function testPostParsing()
<ide> 'Article' => ['title']
<ide> ];
<ide> $request = new ServerRequest(compact('post'));
<del> $this->assertEquals($post, $request->data);
<add> $this->assertEquals($post, $request->getData());
<ide>
<ide> $post = ['one' => 1, 'two' => 'three'];
<ide> $request = new ServerRequest(compact('post'));
<del> $this->assertEquals($post, $request->data);
<add> $this->assertEquals($post, $request->getData());
<ide>
<ide> $post = [
<ide> 'Article' => ['title' => 'Testing'],
<ide> 'action' => 'update'
<ide> ];
<ide> $request = new ServerRequest(compact('post'));
<del> $this->assertEquals($post, $request->data);
<add> $this->assertEquals($post, $request->getData());
<ide> }
<ide>
<ide> /**
<ide> public function testPutParsing()
<ide> 'CONTENT_TYPE' => 'application/x-www-form-urlencoded; charset=UTF-8'
<ide> ]
<ide> ]);
<del> $this->assertEquals($data, $request->data);
<add> $this->assertEquals($data, $request->getData());
<ide>
<ide> $data = ['one' => 1, 'two' => 'three'];
<ide> $request = new ServerRequest([
<ide> public function testPutParsing()
<ide> 'CONTENT_TYPE' => 'application/x-www-form-urlencoded; charset=UTF-8'
<ide> ]
<ide> ]);
<del> $this->assertEquals($data, $request->data);
<add> $this->assertEquals($data, $request->getData());
<ide>
<ide> $request = new ServerRequest([
<ide> 'input' => 'Article[title]=Testing&action=update',
<ide> public function testPutParsing()
<ide> 'Article' => ['title' => 'Testing'],
<ide> 'action' => 'update'
<ide> ];
<del> $this->assertEquals($expected, $request->data);
<add> $this->assertEquals($expected, $request->getData());
<ide>
<ide> $data = [
<ide> 'Article' => ['title'],
<ide> public function testPutParsing()
<ide> 'CONTENT_TYPE' => 'application/x-www-form-urlencoded; charset=UTF-8'
<ide> ]
<ide> ]);
<del> $this->assertEquals($data, $request->data);
<add> $this->assertEquals($data, $request->getData());
<ide> }
<ide>
<ide> /**
<ide> public function testPutParsingJSON()
<ide> 'CONTENT_TYPE' => 'application/json'
<ide> ]
<ide> ]);
<del> $this->assertEquals([], $request->data);
<add> $this->assertEquals([], $request->getData());
<ide> $result = $request->input('json_decode', true);
<ide> $this->assertEquals(['title'], $result['Article']);
<ide> }
<ide> public function testFilesNested()
<ide> ]
<ide> ]
<ide> ];
<del> $this->assertEquals($expected, $request->data);
<add> $this->assertEquals($expected, $request->getData());
<ide>
<ide> $uploads = $request->getUploadedFiles();
<ide> $this->assertCount(3, $uploads);
<ide> public function testFilesFlat()
<ide> 'size' => 123
<ide> ]
<ide> ];
<del> $this->assertEquals($expected, $request->data);
<add> $this->assertEquals($expected, $request->getData());
<ide>
<ide> $uploads = $request->getUploadedFiles();
<ide> $this->assertCount(1, $uploads);
<ide> public function testFilesZeroithIndex()
<ide> $request = new ServerRequest([
<ide> 'files' => $files
<ide> ]);
<del> $this->assertEquals($files, $request->data);
<add> $this->assertEquals($files, $request->getData());
<ide>
<ide> $uploads = $request->getUploadedFiles();
<ide> $this->assertCount(1, $uploads);
<ide> public function testClientIp()
<ide> */
<ide> public function testReferer()
<ide> {
<del> $request = new ServerRequest();
<del> $request->webroot = '/';
<add> $request = new ServerRequest(['webroot' => '/']);
<ide>
<ide> $request = $request->withEnv('HTTP_REFERER', 'http://cakephp.org');
<ide> $result = $request->referer();
<ide> public function testReferer()
<ide> */
<ide> public function testRefererBasePath()
<ide> {
<del> $request = new ServerRequest('some/path');
<del> $request->url = 'users/login';
<del> $request->webroot = '/waves/';
<del> $request->base = '/waves';
<del> $request->here = '/waves/users/login';
<del>
<add> $request = new ServerRequest([
<add> 'url' => '/waves/users/login',
<add> 'webroot' => '/waves/',
<add> 'base' => '/waves'
<add> ]);
<ide> $request = $request->withEnv('HTTP_REFERER', Configure::read('App.fullBaseUrl') . '/waves/waves/add');
<ide>
<ide> $result = $request->referer(true);
<ide> public function testAddDetector()
<ide> $request->clearDetectorCache();
<ide> $this->assertFalse($request->isIndex());
<ide>
<del> ServerRequest::addDetector('callme', [$this, 'detectCallback']);
<del> $request->return = true;
<add> ServerRequest::addDetector('callme', function ($request) {
<add> return $request->getAttribute('return');
<add> });
<add> $request = $request->withAttribute('return', true);;
<ide> $request->clearDetectorCache();
<ide> $this->assertTrue($request->isCallMe());
<ide>
<ide> public function testAddDetector()
<ide> $this->assertFalse($request->isExtension());
<ide> }
<ide>
<del> /**
<del> * Helper function for testing callbacks.
<del> *
<del> * @param $request
<del> * @return bool
<del> */
<del> public function detectCallback($request)
<del> {
<del> return (bool)$request->return;
<del> }
<del>
<ide> /**
<ide> * Test getting headers
<ide> *
<ide> public function testBaseUrlAndWebrootWithModRewrite()
<ide> $_SERVER['PATH_INFO'] = '/posts/view/1';
<ide>
<ide> $request = ServerRequestFactory::fromGlobals();
<del> $this->assertEquals('/urlencode%20me', $request->base);
<del> $this->assertEquals('/urlencode%20me/', $request->webroot);
<del> $this->assertEquals('posts/view/1', $request->url);
<add> $this->assertEquals('/urlencode%20me', $request->getAttribute('base'));
<add> $this->assertEquals('/urlencode%20me/', $request->getAttribute('webroot'));
<add> $this->assertEquals('/posts/view/1', $request->getRequestTarget());
<ide>
<ide> $_SERVER['DOCUMENT_ROOT'] = '/cake/repo/branches';
<ide> $_SERVER['PHP_SELF'] = '/1.2.x.x/webroot/index.php';
<ide> $_SERVER['PATH_INFO'] = '/posts/view/1';
<ide>
<ide> $request = ServerRequestFactory::fromGlobals();
<del> $this->assertEquals('/1.2.x.x', $request->base);
<del> $this->assertEquals('/1.2.x.x/', $request->webroot);
<del> $this->assertEquals('posts/view/1', $request->url);
<add> $this->assertEquals('/1.2.x.x', $request->getAttribute('base'));
<add> $this->assertEquals('/1.2.x.x/', $request->getAttribute('webroot'));
<add> $this->assertEquals('/posts/view/1', $request->getRequestTarget());
<ide>
<ide> $_SERVER['DOCUMENT_ROOT'] = '/cake/repo/branches/1.2.x.x/webroot';
<ide> $_SERVER['PHP_SELF'] = '/index.php';
<ide> $_SERVER['PATH_INFO'] = '/posts/add';
<ide> $request = ServerRequestFactory::fromGlobals();
<ide>
<del> $this->assertEquals('', $request->base);
<del> $this->assertEquals('/', $request->webroot);
<del> $this->assertEquals('posts/add', $request->url);
<add> $this->assertEquals('', $request->getAttribute('base'));
<add> $this->assertEquals('/', $request->getAttribute('webroot'));
<add> $this->assertEquals('/posts/add', $request->getRequestTarget());
<ide>
<ide> $_SERVER['DOCUMENT_ROOT'] = '/cake/repo/branches/1.2.x.x/test/';
<ide> $_SERVER['PHP_SELF'] = '/webroot/index.php';
<ide> $request = ServerRequestFactory::fromGlobals();
<ide>
<del> $this->assertEquals('', $request->base);
<del> $this->assertEquals('/', $request->webroot);
<add> $this->assertEquals('', $request->getAttribute('base'));
<add> $this->assertEquals('/', $request->getAttribute('webroot'));
<ide>
<ide> $_SERVER['DOCUMENT_ROOT'] = '/some/apps/where';
<ide> $_SERVER['PHP_SELF'] = '/webroot/index.php';
<ide> $request = ServerRequestFactory::fromGlobals();
<ide>
<del> $this->assertEquals('', $request->base);
<del> $this->assertEquals('/', $request->webroot);
<add> $this->assertEquals('', $request->getAttribute('base'));
<add> $this->assertEquals('/', $request->getAttribute('webroot'));
<ide>
<ide> Configure::write('App.dir', 'auth');
<ide>
<ide> public function testBaseUrlAndWebrootWithModRewrite()
<ide>
<ide> $request = ServerRequestFactory::fromGlobals();
<ide>
<del> $this->assertEquals('/demos', $request->base);
<del> $this->assertEquals('/demos/', $request->webroot);
<add> $this->assertEquals('/demos', $request->getAttribute('base'));
<add> $this->assertEquals('/demos/', $request->getAttribute('webroot'));
<ide>
<ide> Configure::write('App.dir', 'code');
<ide>
<ide> $_SERVER['DOCUMENT_ROOT'] = '/Library/WebServer/Documents';
<ide> $_SERVER['PHP_SELF'] = '/clients/PewterReport/webroot/index.php';
<ide> $request = ServerRequestFactory::fromGlobals();
<ide>
<del> $this->assertEquals('/clients/PewterReport', $request->base);
<del> $this->assertEquals('/clients/PewterReport/', $request->webroot);
<add> $this->assertEquals('/clients/PewterReport', $request->getAttribute('base'));
<add> $this->assertEquals('/clients/PewterReport/', $request->getAttribute('webroot'));
<ide> }
<ide>
<ide> /**
<ide> public function testBaseUrlwithModRewriteAlias()
<ide>
<ide> $request = ServerRequestFactory::fromGlobals();
<ide>
<del> $this->assertEquals('/control', $request->base);
<del> $this->assertEquals('/control/', $request->webroot);
<add> $this->assertEquals('/control', $request->getAttribute('base'));
<add> $this->assertEquals('/control/', $request->getAttribute('webroot'));
<ide>
<ide> Configure::write('App.base', false);
<ide> Configure::write('App.dir', 'affiliate');
<ide> public function testBaseUrlwithModRewriteAlias()
<ide> $_SERVER['PHP_SELF'] = '/newaffiliate/index.php';
<ide> $request = ServerRequestFactory::fromGlobals();
<ide>
<del> $this->assertEquals('', $request->base);
<del> $this->assertEquals('/', $request->webroot);
<add> $this->assertEquals('', $request->getAttribute('base'));
<add> $this->assertEquals('/', $request->getAttribute('webroot'));
<ide> }
<ide>
<ide> /**
<ide> public function testBaseUrlWithModRewriteAndIndexPhp()
<ide> unset($_SERVER['PATH_INFO']);
<ide> $request = ServerRequestFactory::fromGlobals();
<ide>
<del> $this->assertEquals('/cakephp', $request->base);
<del> $this->assertEquals('/cakephp/', $request->webroot);
<del> $this->assertEquals('', $request->url);
<del> $this->assertEquals('/cakephp/', $request->here);
<add> $this->assertEquals('/cakephp', $request->getAttribute('base'));
<add> $this->assertEquals('/cakephp/', $request->getAttribute('webroot'));
<add> $this->assertEquals('/', $request->getRequestTarget());
<ide>
<ide> $_SERVER['REQUEST_URI'] = '/cakephp/webroot/index.php/';
<ide> $_SERVER['PHP_SELF'] = '/cakephp/webroot/index.php/';
<ide> $_SERVER['PATH_INFO'] = '/';
<ide> $request = ServerRequestFactory::fromGlobals();
<ide>
<del> $this->assertEquals('/cakephp', $request->base);
<del> $this->assertEquals('/cakephp/', $request->webroot);
<del> $this->assertEquals('', $request->url);
<del> $this->assertEquals('/cakephp/', $request->here);
<add> $this->assertEquals('/cakephp', $request->getAttribute('base'));
<add> $this->assertEquals('/cakephp/', $request->getAttribute('webroot'));
<add> $this->assertEquals('/', $request->getRequestTarget());
<ide>
<ide> $_SERVER['REQUEST_URI'] = '/cakephp/webroot/index.php/apples';
<ide> $_SERVER['PHP_SELF'] = '/cakephp/webroot/index.php/apples';
<ide> $_SERVER['PATH_INFO'] = '/apples';
<ide> $request = ServerRequestFactory::fromGlobals();
<ide>
<del> $this->assertEquals('/cakephp', $request->base);
<del> $this->assertEquals('/cakephp/', $request->webroot);
<del> $this->assertEquals('apples', $request->url);
<del> $this->assertEquals('/cakephp/apples', $request->here);
<add> $this->assertEquals('/cakephp', $request->getAttribute('base'));
<add> $this->assertEquals('/cakephp/', $request->getAttribute('webroot'));
<add> $this->assertEquals('/apples', $request->getRequestTarget());
<ide>
<ide> $_SERVER['REQUEST_URI'] = '/cakephp/webroot/index.php/melons/share/';
<ide> $_SERVER['PHP_SELF'] = '/cakephp/webroot/index.php/melons/share/';
<ide> $_SERVER['PATH_INFO'] = '/melons/share/';
<ide> $request = ServerRequestFactory::fromGlobals();
<ide>
<del> $this->assertEquals('/cakephp', $request->base);
<del> $this->assertEquals('/cakephp/', $request->webroot);
<del> $this->assertEquals('melons/share/', $request->url);
<del> $this->assertEquals('/cakephp/melons/share/', $request->here);
<add> $this->assertEquals('/cakephp', $request->getAttribute('base'));
<add> $this->assertEquals('/cakephp/', $request->getAttribute('webroot'));
<add> $this->assertEquals('/melons/share/', $request->getRequestTarget());
<ide>
<ide> $_SERVER['REQUEST_URI'] = '/cakephp/webroot/index.php/bananas/eat/tasty_banana';
<ide> $_SERVER['PHP_SELF'] = '/cakephp/webroot/index.php/bananas/eat/tasty_banana';
<ide> $_SERVER['PATH_INFO'] = '/bananas/eat/tasty_banana';
<ide> $request = ServerRequestFactory::fromGlobals();
<ide>
<del> $this->assertEquals('/cakephp', $request->base);
<del> $this->assertEquals('/cakephp/', $request->webroot);
<del> $this->assertEquals('bananas/eat/tasty_banana', $request->url);
<del> $this->assertEquals('/cakephp/bananas/eat/tasty_banana', $request->here);
<add> $this->assertEquals('/cakephp', $request->getAttribute('base'));
<add> $this->assertEquals('/cakephp/', $request->getAttribute('webroot'));
<add> $this->assertEquals('/bananas/eat/tasty_banana', $request->getRequestTarget());
<ide> }
<ide>
<ide> /**
<ide> public function testBaseUrlWithModRewriteAndExtraSlashes()
<ide> $_SERVER['PATH_INFO'] = '/bananas/eat';
<ide> $request = ServerRequestFactory::fromGlobals();
<ide>
<del> $this->assertEquals('/cakephp', $request->base);
<del> $this->assertEquals('/cakephp/', $request->webroot);
<del> $this->assertEquals('bananas/eat', $request->url);
<del> $this->assertEquals('/cakephp/bananas/eat', $request->here);
<add> $this->assertEquals('/cakephp', $request->getAttribute('base'));
<add> $this->assertEquals('/cakephp/', $request->getAttribute('webroot'));
<add> $this->assertEquals('/bananas/eat', $request->getRequestTarget());
<ide> }
<ide>
<ide> /**
<ide> public function testBaseUrlWithNoModRewrite()
<ide> ]);
<ide>
<ide> $request = ServerRequestFactory::fromGlobals();
<del> $this->assertEquals('/cake/index.php', $request->base);
<del> $this->assertEquals('/cake/webroot/', $request->webroot);
<del> $this->assertEquals('posts/index', $request->url);
<add> $this->assertEquals('/cake/index.php', $request->getAttribute('base'));
<add> $this->assertEquals('/cake/webroot/', $request->getAttribute('webroot'));
<add> $this->assertEquals('/posts/index', $request->getRequestTarget());
<ide> }
<ide>
<ide> /**
<ide> public function testBaseUrlAndWebrootWithBaseUrl()
<ide> Configure::write('App.baseUrl', '/App/webroot/index.php');
<ide>
<ide> $request = ServerRequestFactory::fromGlobals();
<del> $this->assertEquals('/App/webroot/index.php', $request->base);
<del> $this->assertEquals('/App/webroot/', $request->webroot);
<add> $this->assertEquals('/App/webroot/index.php', $request->getAttribute('base'));
<add> $this->assertEquals('/App/webroot/', $request->getAttribute('webroot'));
<ide>
<ide> Configure::write('App.baseUrl', '/App/webroot/test.php');
<ide> $request = ServerRequestFactory::fromGlobals();
<del> $this->assertEquals('/App/webroot/test.php', $request->base);
<del> $this->assertEquals('/App/webroot/', $request->webroot);
<add> $this->assertEquals('/App/webroot/test.php', $request->getAttribute('base'));
<add> $this->assertEquals('/App/webroot/', $request->getAttribute('webroot'));
<ide>
<ide> Configure::write('App.baseUrl', '/App/index.php');
<ide> $request = ServerRequestFactory::fromGlobals();
<del> $this->assertEquals('/App/index.php', $request->base);
<del> $this->assertEquals('/App/webroot/', $request->webroot);
<add> $this->assertEquals('/App/index.php', $request->getAttribute('base'));
<add> $this->assertEquals('/App/webroot/', $request->getAttribute('webroot'));
<ide>
<ide> Configure::write('App.baseUrl', '/CakeBB/App/webroot/index.php');
<ide> $request = ServerRequestFactory::fromGlobals();
<del> $this->assertEquals('/CakeBB/App/webroot/index.php', $request->base);
<del> $this->assertEquals('/CakeBB/App/webroot/', $request->webroot);
<add> $this->assertEquals('/CakeBB/App/webroot/index.php', $request->getAttribute('base'));
<add> $this->assertEquals('/CakeBB/App/webroot/', $request->getAttribute('webroot'));
<ide>
<ide> Configure::write('App.baseUrl', '/CakeBB/App/index.php');
<ide> $request = ServerRequestFactory::fromGlobals();
<ide>
<del> $this->assertEquals('/CakeBB/App/index.php', $request->base);
<del> $this->assertEquals('/CakeBB/App/webroot/', $request->webroot);
<add> $this->assertEquals('/CakeBB/App/index.php', $request->getAttribute('base'));
<add> $this->assertEquals('/CakeBB/App/webroot/', $request->getAttribute('webroot'));
<ide>
<ide> Configure::write('App.baseUrl', '/CakeBB/index.php');
<ide> $request = ServerRequestFactory::fromGlobals();
<ide>
<del> $this->assertEquals('/CakeBB/index.php', $request->base);
<del> $this->assertEquals('/CakeBB/webroot/', $request->webroot);
<add> $this->assertEquals('/CakeBB/index.php', $request->getAttribute('base'));
<add> $this->assertEquals('/CakeBB/webroot/', $request->getAttribute('webroot'));
<ide>
<ide> Configure::write('App.baseUrl', '/dbhauser/index.php');
<ide> $_SERVER['DOCUMENT_ROOT'] = '/kunden/homepages/4/d181710652/htdocs/joomla';
<ide> $_SERVER['SCRIPT_FILENAME'] = '/kunden/homepages/4/d181710652/htdocs/joomla/dbhauser/index.php';
<ide> $request = ServerRequestFactory::fromGlobals();
<ide>
<del> $this->assertEquals('/dbhauser/index.php', $request->base);
<del> $this->assertEquals('/dbhauser/webroot/', $request->webroot);
<add> $this->assertEquals('/dbhauser/index.php', $request->getAttribute('base'));
<add> $this->assertEquals('/dbhauser/webroot/', $request->getAttribute('webroot'));
<ide> }
<ide>
<ide> /**
<ide> public function testBaseUrlNoRewriteTopLevelIndex()
<ide> $_SERVER['SCRIPT_FILENAME'] = '/Users/markstory/Sites/cake_dev/index.php';
<ide>
<ide> $request = ServerRequestFactory::fromGlobals();
<del> $this->assertEquals('/index.php', $request->base);
<del> $this->assertEquals('/webroot/', $request->webroot);
<add> $this->assertEquals('/index.php', $request->getAttribute('base'));
<add> $this->assertEquals('/webroot/', $request->getAttribute('webroot'));
<ide> }
<ide>
<ide> /**
<ide> public function testBaseUrlWithAppAndWebrootInDirname()
<ide> $_SERVER['SCRIPT_FILENAME'] = '/Users/markstory/Sites/approval/index.php';
<ide>
<ide> $request = ServerRequestFactory::fromGlobals();
<del> $this->assertEquals('/approval/index.php', $request->base);
<del> $this->assertEquals('/approval/webroot/', $request->webroot);
<add> $this->assertEquals('/approval/index.php', $request->getAttribute('base'));
<add> $this->assertEquals('/approval/webroot/', $request->getAttribute('webroot'));
<ide>
<ide> Configure::write('App.baseUrl', '/webrootable/index.php');
<ide> $_SERVER['DOCUMENT_ROOT'] = '/Users/markstory/Sites/';
<ide> $_SERVER['SCRIPT_FILENAME'] = '/Users/markstory/Sites/webrootable/index.php';
<ide>
<ide> $request = ServerRequestFactory::fromGlobals();
<del> $this->assertEquals('/webrootable/index.php', $request->base);
<del> $this->assertEquals('/webrootable/webroot/', $request->webroot);
<add> $this->assertEquals('/webrootable/index.php', $request->getAttribute('base'));
<add> $this->assertEquals('/webrootable/webroot/', $request->getAttribute('webroot'));
<ide> }
<ide>
<ide> /**
<ide> public function testBaseUrlNoRewriteWebrootIndex()
<ide> $_SERVER['SCRIPT_FILENAME'] = '/Users/markstory/Sites/cake_dev/webroot/index.php';
<ide>
<ide> $request = ServerRequestFactory::fromGlobals();
<del> $this->assertEquals('/index.php', $request->base);
<del> $this->assertEquals('/', $request->webroot);
<add> $this->assertEquals('/index.php', $request->getAttribute('base'));
<add> $this->assertEquals('/', $request->getAttribute('webroot'));
<ide> }
<ide>
<ide> /**
<ide> public function testGetParamsWithDot()
<ide> $_SERVER['PHP_SELF'] = '/webroot/index.php';
<ide> $_SERVER['REQUEST_URI'] = '/posts/index/add.add';
<ide> $request = ServerRequestFactory::fromGlobals();
<del> $this->assertEquals('', $request->base);
<add> $this->assertEquals('', $request->getAttribute('base'));
<ide> $this->assertEquals([], $request->getQueryParams());
<ide>
<ide> $_GET = [];
<ide> $_GET['/cake_dev/posts/index/add_add'] = '';
<ide> $_SERVER['PHP_SELF'] = '/cake_dev/webroot/index.php';
<ide> $_SERVER['REQUEST_URI'] = '/cake_dev/posts/index/add.add';
<ide> $request = ServerRequestFactory::fromGlobals();
<del> $this->assertEquals('/cake_dev', $request->base);
<add> $this->assertEquals('/cake_dev', $request->getAttribute('base'));
<ide> $this->assertEquals([], $request->getQueryParams());
<ide> }
<ide>
<ide> public function testGetParamWithUrlencodedElement()
<ide> $_SERVER['PHP_SELF'] = '/webroot/index.php';
<ide> $_SERVER['REQUEST_URI'] = '/posts/add/%E2%88%82%E2%88%82';
<ide> $request = ServerRequestFactory::fromGlobals();
<del> $this->assertEquals('', $request->base);
<add> $this->assertEquals('', $request->getAttribute('base'));
<ide> $this->assertEquals([], $request->getQueryParams());
<ide>
<ide> $_GET = [];
<ide> $_GET['/cake_dev/posts/add/∂∂'] = '';
<ide> $_SERVER['PHP_SELF'] = '/cake_dev/webroot/index.php';
<ide> $_SERVER['REQUEST_URI'] = '/cake_dev/posts/add/%E2%88%82%E2%88%82';
<ide> $request = ServerRequestFactory::fromGlobals();
<del> $this->assertEquals('/cake_dev', $request->base);
<add> $this->assertEquals('/cake_dev', $request->getAttribute('base'));
<ide> $this->assertEquals([], $request->getQueryParams());
<ide> }
<ide>
<ide> public function testEnvironmentDetection($name, $env, $expected)
<ide> $request = ServerRequestFactory::fromGlobals();
<ide> $uri = $request->getUri();
<ide>
<del> $this->assertEquals($expected['url'], $request->url, 'URL is incorrect');
<ide> $this->assertEquals('/' . $expected['url'], $uri->getPath(), 'Uri->getPath() is incorrect');
<del>
<del> $this->assertEquals($expected['base'], $request->base, 'base is incorrect');
<ide> $this->assertEquals($expected['base'], $request->getAttribute('base'), 'base is incorrect');
<del>
<del> $this->assertEquals($expected['webroot'], $request->webroot, 'webroot error');
<ide> $this->assertEquals($expected['webroot'], $request->getAttribute('webroot'), 'webroot is incorrect');
<ide>
<ide> if (isset($expected['urlParams'])) {
<del> $this->assertEquals($expected['urlParams'], $request->query, 'GET param mismatch');
<add> $this->assertEquals($expected['urlParams'], $request->getQueryParams(), 'GET param mismatch');
<ide> }
<add>
<add> $this->deprecated(function () use ($request, $expected) {
<add> $this->assertEquals($expected['url'], $request->url, 'URL is incorrect');
<add> $this->assertEquals($expected['base'], $request->base, 'base is incorrect');
<add> $this->assertEquals($expected['webroot'], $request->webroot, 'webroot error');
<add> });
<ide> }
<ide>
<ide> /**
<ide> public function testWithBody()
<ide> public function testGetUri()
<ide> {
<ide> $request = new ServerRequest(['url' => 'articles/view/3']);
<del> $this->assertEquals('articles/view/3', $request->url);
<del>
<ide> $result = $request->getUri();
<ide> $this->assertInstanceOf('Psr\Http\Message\UriInterface', $result);
<ide> $this->assertEquals('/articles/view/3', $result->getPath());
<ide> }
<ide>
<add> /**
<add> * test url property
<add> *
<add> * @group deprecated
<add> * @return void
<add> */
<add> public function testUrlProperty()
<add> {
<add> $this->deprecated(function () {
<add> $request = new ServerRequest(['url' => 'articles/view/3']);
<add> $this->assertEquals('articles/view/3', $request->url);
<add> });
<add> }
<add>
<ide> /**
<ide> * Test withUri
<ide> *
<ide> public function testWithUri()
<ide> $this->assertNotSame($new, $request);
<ide> $this->assertNotSame($uri, $request->getUri());
<ide> $this->assertSame($uri, $new->getUri());
<del> $this->assertSame('articles/view/3', $new->url);
<del> $this->assertSame('articles/view/3', $request->url);
<del> $this->assertSame('example.com', $new->getHeaderLine('Host'));
<add> }
<add>
<add> /**
<add> * Test withUri
<add> *
<add> * @group deprecated
<add> * @return void
<add> */
<add> public function testWithUriCompatibility()
<add> {
<add> $this->deprecated(function () {
<add> $request = new ServerRequest([
<add> 'environment' => [
<add> 'HTTP_HOST' => 'example.com',
<add> ],
<add> 'url' => 'articles/view/3'
<add> ]);
<add> $uri = $this->getMockBuilder('Psr\Http\Message\UriInterface')->getMock();
<add> $new = $request->withUri($uri);
<add> $this->assertNotSame($new, $request);
<add> $this->assertNotSame($uri, $request->getUri());
<add> $this->assertSame($uri, $new->getUri());
<add> $this->assertSame('articles/view/3', $new->url);
<add> $this->assertSame('articles/view/3', $request->url);
<add> $this->assertSame('example.com', $new->getHeaderLine('Host'));
<add> });
<ide> }
<ide>
<ide> /**
<ide> public function testWithAttribute()
<ide> /**
<ide> * Test that withAttribute() can modify the deprecated public properties.
<ide> *
<add> * @group deprecated
<ide> * @return void
<ide> */
<ide> public function testWithAttributesCompatibility()
<ide> {
<del> $request = new ServerRequest([
<del> 'params' => [
<del> 'controller' => 'Articles',
<del> 'action' => 'index'
<del> ],
<del> 'base' => '/cakeapp',
<del> 'webroot' => '/cakeapp/'
<del> ]);
<del>
<del> $new = $request->withAttribute('base', '/replace')
<del> ->withAttribute('webroot', '/replace/')
<del> ->withAttribute('params', ['controller' => 'Tags']);
<del>
<del> // Original request should not change.
<del> $this->assertSame('/cakeapp', $request->getAttribute('base'));
<del> $this->assertSame('/cakeapp/', $request->getAttribute('webroot'));
<del> $this->assertSame(
<del> ['controller' => 'Articles', 'action' => 'index'],
<del> $request->getAttribute('params')
<del> );
<del>
<del> $this->assertSame('/replace', $new->getAttribute('base'));
<del> $this->assertSame('/replace', $new->base);
<del> $this->assertSame('/replace/', $new->getAttribute('webroot'));
<del> $this->assertSame('/replace/', $new->webroot);
<add> $this->deprecated(function () {
<add> $request = new ServerRequest([
<add> 'params' => [
<add> 'controller' => 'Articles',
<add> 'action' => 'index'
<add> ],
<add> 'base' => '/cakeapp',
<add> 'webroot' => '/cakeapp/'
<add> ]);
<ide>
<del> $this->assertSame(['controller' => 'Tags'], $new->getAttribute('params'));
<del> $this->assertSame(['controller' => 'Tags'], $new->params);
<add> $new = $request->withAttribute('base', '/replace')
<add> ->withAttribute('webroot', '/replace/')
<add> ->withAttribute('params', ['controller' => 'Tags']);
<add>
<add> // Original request should not change.
<add> $this->assertSame('/cakeapp', $request->getAttribute('base'));
<add> $this->assertSame('/cakeapp/', $request->getAttribute('webroot'));
<add> $this->assertSame(
<add> ['controller' => 'Articles', 'action' => 'index'],
<add> $request->getAttribute('params')
<add> );
<add>
<add> $this->assertSame('/replace', $new->getAttribute('base'));
<add> $this->assertSame('/replace', $new->base);
<add> $this->assertSame('/replace/', $new->getAttribute('webroot'));
<add> $this->assertSame('/replace/', $new->webroot);
<add>
<add> $this->assertSame(['controller' => 'Tags'], $new->getAttribute('params'));
<add> $this->assertSame(['controller' => 'Tags'], $new->params);
<add> });
<ide> }
<ide>
<ide> /**
<ide> * Test that getAttribute() can read deprecated public properties.
<ide> *
<add> * @group deprecated
<ide> * @dataProvider emulatedPropertyProvider
<ide> * @return void
<ide> */
<ide> public function testGetAttributesCompatibility($prop)
<ide> {
<del> $request = new ServerRequest([
<del> 'params' => [
<del> 'controller' => 'Articles',
<del> 'action' => 'index'
<del> ],
<del> 'base' => '/cakeapp',
<del> 'webroot' => '/cakeapp/'
<del> ]);
<add> $this->deprecated(function () use ($prop) {
<add> $request = new ServerRequest([
<add> 'params' => [
<add> 'controller' => 'Articles',
<add> 'action' => 'index'
<add> ],
<add> 'base' => '/cakeapp',
<add> 'webroot' => '/cakeapp/'
<add> ]);
<ide>
<del> if ($prop === 'session') {
<del> $this->assertSame($request->getSession(), $request->getAttribute($prop));
<del> } else {
<del> $this->assertSame($request->{$prop}, $request->getAttribute($prop));
<del> }
<add> if ($prop === 'session') {
<add> $this->assertSame($request->getSession(), $request->getAttribute($prop));
<add> } else {
<add> $this->assertSame($request->{$prop}, $request->getAttribute($prop));
<add> }
<add> });
<ide> }
<ide>
<ide> /** | 2 |
Javascript | Javascript | change var to let | eb30b2c8199f00b711ef1c49b8cde3934836cbaa | <ide><path>lib/internal/readline/utils.js
<ide> let isFullWidthCodePoint;
<ide>
<ide> function CSI(strings, ...args) {
<ide> let ret = `${kEscape}[`;
<del> for (var n = 0; n < strings.length; n++) {
<add> for (let n = 0; n < strings.length; n++) {
<ide> ret += strings[n];
<ide> if (n < args.length)
<ide> ret += args[n];
<ide> if (internalBinding('config').hasIntl) {
<ide>
<ide> str = stripVTControlCharacters(String(str));
<ide>
<del> for (var i = 0; i < str.length; i++) {
<add> for (let i = 0; i < str.length; i++) {
<ide> const code = str.codePointAt(i);
<ide>
<ide> if (code >= kUTF16SurrogateThreshold) { // Surrogates. | 1 |
Mixed | Text | use class to specify the middleware [ci skip] | 70b09eda034766efcd2cac9280d42c7bbaaadff9 | <ide><path>guides/source/rails_on_rack.md
<ide> Add the following lines to your application configuration:
<ide>
<ide> ```ruby
<ide> # config/application.rb
<del>config.middleware.delete "Rack::Lock"
<add>config.middleware.delete Rack::Lock
<ide> ```
<ide>
<ide> And now if you inspect the middleware stack, you'll find that `Rack::Lock` is
<ide> If you want to remove session related middleware, do the following:
<ide>
<ide> ```ruby
<ide> # config/application.rb
<del>config.middleware.delete "ActionDispatch::Cookies"
<del>config.middleware.delete "ActionDispatch::Session::CookieStore"
<del>config.middleware.delete "ActionDispatch::Flash"
<add>config.middleware.delete ActionDispatch::Cookies
<add>config.middleware.delete ActionDispatch::Session::CookieStore
<add>config.middleware.delete ActionDispatch::Flash
<ide> ```
<ide>
<ide> And to remove browser related middleware,
<ide>
<ide> ```ruby
<ide> # config/application.rb
<del>config.middleware.delete "Rack::MethodOverride"
<add>config.middleware.delete Rack::MethodOverride
<ide> ```
<ide>
<ide> ### Internal Middleware Stack
<ide><path>railties/lib/rails/generators/rails/app/templates/config/initializers/cors.rb
<ide>
<ide> # Read more: https://github.com/cyu/rack-cors
<ide>
<del># Rails.application.config.middleware.insert_before 0, "Rack::Cors" do
<add># Rails.application.config.middleware.insert_before 0, Rack::Cors do
<ide> # allow do
<ide> # origins 'example.com'
<ide> # | 2 |
Ruby | Ruby | update the comments for timewithzone subtraction | 018ff582a5aaa58d4bce7d634ecae80d107f8304 | <ide><path>activesupport/lib/active_support/time_with_zone.rb
<ide> def +(other)
<ide> alias_method :since, :+
<ide> alias_method :in, :+
<ide>
<del> # Returns a new TimeWithZone object that represents the difference between
<del> # the current object's time and the +other+ time.
<add> # Subtracts an interval of time and returns a new TimeWithZone object unless
<add> # the other value `acts_like?` time. Then it will return a Float of the difference
<add> # between the two times that represents the difference between the current
<add> # object's time and the +other+ time.
<ide> #
<ide> # Time.zone = 'Eastern Time (US & Canada)' # => 'Eastern Time (US & Canada)'
<ide> # now = Time.zone.now # => Mon, 03 Nov 2014 00:26:28 EST -05:00
<ide> def +(other)
<ide> #
<ide> # now - 24.hours # => Sun, 02 Nov 2014 01:26:28 EDT -04:00
<ide> # now - 1.day # => Sun, 02 Nov 2014 00:26:28 EDT -04:00
<add> #
<add> # If both the TimeWithZone object and the other value act like Time, a Float
<add> # will be returned.
<add> #
<add> # Time.zone.now - 1.day.ago # => 86399.999967
<add> #
<ide> def -(other)
<ide> if other.acts_like?(:time)
<ide> to_time - other.to_time | 1 |
Ruby | Ruby | add spec for `conflicts_with cask` | f89e09b7857e8e3a6f6cd30258aa5927a1ac2872 | <ide><path>Library/Homebrew/test/cask/conflicts_with_spec.rb
<add>describe "conflicts_with", :cask do
<add> describe "conflicts_with cask" do
<add> let(:local_caffeine) {
<add> Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/local-caffeine.rb")
<add> }
<add>
<add> let(:with_conflicts_with) {
<add> Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/with-conflicts-with.rb")
<add> }
<add>
<add> it "installs the dependency of a Cask and the Cask itself", :focus do
<add> Hbc::Installer.new(local_caffeine).install
<add>
<add> expect(local_caffeine).to be_installed
<add>
<add> expect {
<add> Hbc::Installer.new(with_conflicts_with).install
<add> }.to raise_error(Hbc::CaskConflictError, "Cask 'with-conflicts-with' conflicts with 'local-caffeine'.")
<add>
<add> expect(with_conflicts_with).not_to be_installed
<add> end
<add> end
<add>end
<ide><path>Library/Homebrew/test/support/fixtures/cask/Casks/with-conflicts-with.rb
<ide> url "file://#{TEST_FIXTURE_DIR}/cask/caffeine.zip"
<ide> homepage 'http://example.com/with-conflicts-with'
<ide>
<del> conflicts_with formula: 'unar'
<add> conflicts_with cask: 'local-caffeine'
<ide>
<ide> app 'Caffeine.app'
<ide> end | 2 |
Text | Text | add a proposal step for potential maintainers | b59dea67679fefcfe9716b855ef906b377d9993d | <ide><path>CONTRIBUTING.md
<ide> For more details see [MAINTAINERS.md](hack/MAINTAINERS.md)
<ide> * Step 1: learn the component inside out
<ide> * Step 2: make yourself useful by contributing code, bugfixes, support etc.
<ide> * Step 3: volunteer on the irc channel (#docker@freenode)
<add>* Step 4: propose yourself at a scheduled #docker-meeting
<ide>
<ide> Don't forget: being a maintainer is a time investment. Make sure you will have time to make yourself available.
<ide> You don't have to be a maintainer to make a difference on the project! | 1 |
Text | Text | clarify `uncaughtexception` `origin` for esm | 7edb50dec7193163bad25fcce9640a7bc39ba079 | <ide><path>doc/api/cli.md
<ide> occurs. One of the following modes can be chosen:
<ide> set, trigger a warning, and set the process exit code to 1.
<ide> * `none`: Silence all warnings.
<ide>
<add>If a rejection happens during the command line entry point's ES module static
<add>loading phase, it will always raise it as an uncaught exception.
<add>
<ide> ### `--use-bundled-ca`, `--use-openssl-ca`
<ide>
<ide> <!-- YAML
<ide><path>doc/api/process.md
<ide> changes:
<ide> * `err` {Error} The uncaught exception.
<ide> * `origin` {string} Indicates if the exception originates from an unhandled
<ide> rejection or from an synchronous error. Can either be `'uncaughtException'` or
<del> `'unhandledRejection'`. The latter is only used in conjunction with the
<del> [`--unhandled-rejections`][] flag set to `strict` or `throw` and
<del> an unhandled rejection.
<add> `'unhandledRejection'`. The latter is used when in an exception happens in a
<add> `Promise` based async context (or if a `Promise` is rejected) and
<add> [`--unhandled-rejections`][] flag set to `strict` or `throw` (which is the
<add> default) and the rejection is not handled, or when a rejection happens during
<add> the command line entry point's ES module static loading phase.
<ide>
<ide> The `'uncaughtException'` event is emitted when an uncaught JavaScript
<ide> exception bubbles all the way back to the event loop. By default, Node.js
<ide> added:
<ide> * `err` {Error} The uncaught exception.
<ide> * `origin` {string} Indicates if the exception originates from an unhandled
<ide> rejection or from synchronous errors. Can either be `'uncaughtException'` or
<del> `'unhandledRejection'`. The latter is only used in conjunction with the
<del> [`--unhandled-rejections`][] flag set to `strict` or `throw` and
<del> an unhandled rejection.
<add> `'unhandledRejection'`. The latter is used when in an exception happens in a
<add> `Promise` based async context (or if a `Promise` is rejected) and
<add> [`--unhandled-rejections`][] flag set to `strict` or `throw` (which is the
<add> default) and the rejection is not handled, or when a rejection happens during
<add> the command line entry point's ES module static loading phase.
<ide>
<ide> The `'uncaughtExceptionMonitor'` event is emitted before an
<ide> `'uncaughtException'` event is emitted or a hook installed via | 2 |
Javascript | Javascript | fix a bug in path z-index | d8557e0efe18c887612c61667b749d27625a8bea | <ide><path>d3.chart.js
<ide> d3.chart.axis = function() {
<ide> var ticks = scale.ticks.apply(scale, tickArguments_),
<ide> tickFormat = tickFormat_ || scale.tickFormat.apply(scale, tickArguments_),
<ide> tick = g.selectAll("g.tick").data(ticks, String),
<del> tickEnter = tick.enter().append("svg:g").attr("class", "tick").style("opacity", 1e-6),
<add> tickEnter = tick.enter().insert("svg:g", "path").attr("class", "tick").style("opacity", 1e-6),
<ide> tickExit = transition(tick.exit()).style("opacity", 1e-6).remove(),
<ide> tickUpdate = transition(tick).style("opacity", 1),
<ide> tickTransform;
<ide><path>d3.chart.min.js
<del>(function(){function p(a){return a.y}function o(a){return a.x}function n(a,b){var c=b.length-1;b=b.slice().sort(d3.ascending);return d3.range(a).map(function(d){return b[~~(d*c/a)]})}function m(a){return a[1]}function l(a){return a[0]}function i(a){var b=a(0);return function(c){return Math.abs(a(c)-b)}}function h(a){return function(b){return"translate("+a(b)+",0)"}}function g(a){return a.measures}function f(a){return a.markers}function e(a){return a.ranges}function d(a){return[d3.quantile(a,.25),d3.quantile(a,.5),d3.quantile(a,.75)]}function c(a){return[0,a.length-1]}function b(a,b){a.attr("transform",function(a){return"translate(0,"+b(a)+")"})}function a(a,b){a.attr("transform",function(a){return"translate("+b(a)+",0)"})}d3.chart={},d3.chart.axis=function(){function i(i){i.each(function(j,k,l){function z(a){return i.delay?a.transition().delay(i[l][k].delay).duration(i[l][k].duration).ease(i.ease()):a}var m=d3.select(this),n=c.ticks.apply(c,g),o=h||c.tickFormat.apply(c,g),p=m.selectAll("g.tick").data(n,String),q=p.enter().append("svg:g").attr("class","tick").style("opacity",1e-6),r=z(p.exit()).style("opacity",1e-6).remove(),s=z(p).style("opacity",1),t,u=c.range(),v=m.selectAll("path.domain").data([]),w=v.enter().append("svg:path").attr("class","domain"),x=z(v),y=this.__chart__||c;this.__chart__=c.copy(),q.append("svg:line"),q.append("svg:text"),s.select("text").text(o);switch(d){case"bottom":t=a,q.select("text").attr("dy",".71em").attr("text-anchor","middle"),s.select("line").attr("y2",e),s.select("text").attr("y",Math.max(e,0)+f),x.attr("d","M"+u[0]+","+e+"V0H"+u[1]+"V"+e);break;case"top":t=a,q.select("text").attr("text-anchor","middle"),s.select("line").attr("y2",-e),s.select("text").attr("y",-(Math.max(e,0)+f)),x.attr("d","M"+u[0]+","+ -e+"V0H"+u[1]+"V"+ -e);break;case"left":t=b,q.select("text").attr("dy",".32em").attr("text-anchor","end"),s.select("line").attr("x2",-e),s.select("text").attr("x",-(Math.max(e,0)+f)),x.attr("d","M"+ -e+","+u[0]+"H0V"+u[1]+"H"+ -e);break;case"right":t=b,q.select("text").attr("dy",".32em"),s.select("line").attr("x2",e),s.select("text").attr("x",Math.max(e,0)+f),x.attr("d","M"+e+","+u[0]+"H0V"+u[1]+"H"+e)}q.call(t,y),s.call(t,c),r.call(t,c)})}var c=d3.scale.linear(),d="bottom",e=6,f=3,g=[10],h;i.scale=function(a){if(!arguments.length)return c;c=a;return i},i.orient=function(a){if(!arguments.length)return d;d=a;return i},i.tickSize=function(a){if(!arguments.length)return e;e=+a;return i},i.tickPadding=function(a){if(!arguments.length)return f;f=+a;return i},i.ticks=function(){if(!arguments.length)return g;g=arguments;return i},i.tickFormat=function(a){if(!arguments.length)return h;h=a;return i};return i},d3.chart.box=function(){function k(c){c.each(function(c,d){c=c.map(g).sort(d3.ascending);var k=d3.select(this),l=c.length,m=c[0],n=c[l-1],o=c.quartiles=i(c),p=h&&h.call(this,c,d),q=p&&p.map(function(a){return c[a]}),r=p?d3.range(0,p[0]).concat(d3.range(p[1]+1,l)):d3.range(l),s=d3.scale.linear().domain(f&&f.call(this,c,d)||[m,n]).range([b,0]),t=this.__chart__||d3.scale.linear().domain([0,Infinity]).range(s.range());this.__chart__=s;var u=k.selectAll("line.center").data(q?[q]:[]);u.enter().insert("svg:line","rect").attr("class","center").attr("x1",a/2).attr("y1",function(a){return t(a[0])}).attr("x2",a/2).attr("y2",function(a){return t(a[1])}).style("opacity",1e-6).transition().duration(e).style("opacity",1).attr("y1",function(a){return s(a[0])}).attr("y2",function(a){return s(a[1])}),u.transition().duration(e).style("opacity",1).attr("y1",function(a){return s(a[0])}).attr("y2",function(a){return s(a[1])}),u.exit().transition().duration(e).style("opacity",1e-6).attr("y1",function(a){return s(a[0])}).attr("y2",function(a){return s(a[1])}).remove();var v=k.selectAll("rect.box").data([o]);v.enter().append("svg:rect").attr("class","box").attr("x",0).attr("y",function(a){return t(a[2])}).attr("width",a).attr("height",function(a){return t(a[0])-t(a[2])}).transition().duration(e).attr("y",function(a){return s(a[2])}).attr("height",function(a){return s(a[0])-s(a[2])}),v.transition().duration(e).attr("y",function(a){return s(a[2])}).attr("height",function(a){return s(a[0])-s(a[2])});var w=k.selectAll("line.median").data([o[1]]);w.enter().append("svg:line").attr("class","median").attr("x1",0).attr("y1",t).attr("x2",a).attr("y2",t).transition().duration(e).attr("y1",s).attr("y2",s),w.transition().duration(e).attr("y1",s).attr("y2",s);var x=k.selectAll("line.whisker").data(q||[]);x.enter().insert("svg:line","circle, text").attr("class","whisker").attr("x1",0).attr("y1",t).attr("x2",a).attr("y2",t).style("opacity",1e-6).transition().duration(e).attr("y1",s).attr("y2",s).style("opacity",1),x.transition().duration(e).attr("y1",s).attr("y2",s).style("opacity",1),x.exit().transition().duration(e).attr("y1",s).attr("y2",s).style("opacity",1e-6).remove();var y=k.selectAll("circle.outlier").data(r,Number);y.enter().insert("svg:circle","text").attr("class","outlier").attr("r",5).attr("cx",a/2).attr("cy",function(a){return t(c[a])}).style("opacity",1e-6).transition().duration(e).attr("cy",function(a){return s(c[a])}).style("opacity",1),y.transition().duration(e).attr("cy",function(a){return s(c[a])}).style("opacity",1),y.exit().transition().duration(e).attr("cy",function(a){return s(c[a])}).style("opacity",1e-6).remove();var z=j||s.tickFormat(8),A=k.selectAll("text.box").data(o);A.enter().append("svg:text").attr("class","box").attr("dy",".3em").attr("dx",function(a,b){return b&1?6:-6}).attr("x",function(b,c){return c&1?a:0}).attr("y",t).attr("text-anchor",function(a,b){return b&1?"start":"end"}).text(z).transition().duration(e).attr("y",s),A.transition().duration(e).text(z).attr("y",s);var B=k.selectAll("text.whisker").data(q||[]);B.enter().append("svg:text").attr("class","whisker").attr("dy",".3em").attr("dx",6).attr("x",a).attr("y",t).text(z).style("opacity",1e-6).transition().duration(e).attr("y",s).style("opacity",1),B.transition().duration(e).text(z).attr("y",s).style("opacity",1),B.exit().transition().duration(e).attr("y",s).style("opacity",1e-6).remove()}),d3.timer.flush()}var a=1,b=1,e=0,f=null,g=Number,h=c,i=d,j=null;k.width=function(b){if(!arguments.length)return a;a=b;return k},k.height=function(a){if(!arguments.length)return b;b=a;return k},k.tickFormat=function(a){if(!arguments.length)return j;j=a;return k},k.duration=function(a){if(!arguments.length)return e;e=a;return k},k.domain=function(a){if(!arguments.length)return f;f=a==null?a:d3.functor(a);return k},k.value=function(a){if(!arguments.length)return g;g=a;return k},k.whiskers=function(a){if(!arguments.length)return h;h=a;return k},k.quartiles=function(a){if(!arguments.length)return i;i=a;return k};return k},d3.chart.bullet=function(){function o(a){a.each(function(a,e){var f=d.call(this,a,e).slice().sort(d3.descending),g=j.call(this,a,e).slice().sort(d3.descending),o=k.call(this,a,e).slice().sort(d3.descending),p=d3.select(this),q=d3.scale.linear().domain([0,Math.max(f[0],g[0],o[0])]).range(b?[l,0]:[0,l]),r=this.__chart__||d3.scale.linear().domain([0,Infinity]).range(q.range());this.__chart__=q;var s=i(r),t=i(q),u=p.selectAll("rect.range").data(f);u.enter().append("svg:rect").attr("class",function(a,b){return"range s"+b}).attr("width",s).attr("height",m).attr("x",b?r:0).transition().duration(c).attr("width",t).attr("x",b?q:0),u.transition().duration(c).attr("x",b?q:0).attr("width",t).attr("height",m);var v=p.selectAll("rect.measure").data(o);v.enter().append("svg:rect").attr("class",function(a,b){return"measure s"+b}).attr("width",s).attr("height",m/3).attr("x",b?r:0).attr("y",m/3).transition().duration(c).attr("width",t).attr("x",b?q:0),v.transition().duration(c).attr("width",t).attr("height",m/3).attr("x",b?q:0).attr("y",m/3);var w=p.selectAll("line.marker").data(g);w.enter().append("svg:line").attr("class","marker").attr("x1",r).attr("x2",r).attr("y1",m/6).attr("y2",m*5/6).transition().duration(c).attr("x1",q).attr("x2",q),w.transition().duration(c).attr("x1",q).attr("x2",q).attr("y1",m/6).attr("y2",m*5/6);var x=n||q.tickFormat(8),y=p.selectAll("g.tick").data(q.ticks(8),function(a){return this.textContent||x(a)}),z=y.enter().append("svg:g").attr("class","tick").attr("transform",h(r)).style("opacity",1e-6);z.append("svg:line").attr("y1",m).attr("y2",m*7/6),z.append("svg:text").attr("text-anchor","middle").attr("dy","1em").attr("y",m*7/6).text(x),z.transition().duration(c).attr("transform",h(q)).style("opacity",1);var A=y.transition().duration(c).attr("transform",h(q)).style("opacity",1);A.select("line").attr("y1",m).attr("y2",m*7/6),A.select("text").attr("y",m*7/6),y.exit().transition().duration(c).attr("transform",h(q)).style("opacity",1e-6).remove()}),d3.timer.flush()}var a="left",b=!1,c=0,d=e,j=f,k=g,l=380,m=30,n=null;o.orient=function(c){if(!arguments.length)return a;a=c,b=a=="right"||a=="bottom";return o},o.ranges=function(a){if(!arguments.length)return d;d=a;return o},o.markers=function(a){if(!arguments.length)return j;j=a;return o},o.measures=function(a){if(!arguments.length)return k;k=a;return o},o.width=function(a){if(!arguments.length)return l;l=a;return o},o.height=function(a){if(!arguments.length)return m;m=a;return o},o.tickFormat=function(a){if(!arguments.length)return n;n=a;return o},o.duration=function(a){if(!arguments.length)return c;c=a;return o};return o},d3.chart.horizon=function(){function n(l){l.each(function(l,m){var n=d3.select(this),o=2*a+1,p=Infinity,q=-Infinity,r=-Infinity,s,t,u,v=l.map(function(a,b){var c=d.call(this,a,b),f=e.call(this,a,b);c<p&&(p=c),c>q&&(q=c),-f>r&&(r=-f),f>r&&(r=f);return[c,f]}),z=d3.scale.linear().domain([p,q]).range([0,f]),A=d3.scale.linear().domain([0,r]).range([0,g*a]);this.__chart__?(s=this.__chart__.x,t=this.__chart__.y,u=this.__chart__.id):(s=d3.scale.linear().domain([0,Infinity]).range(z.range()),t=d3.scale.linear().domain([0,Infinity]).range(A.range()),u=++k);var B=n.selectAll("defs").data([v]),C=B.enter().append("svg:defs");C.append("svg:clipPath").attr("id","d3_chart_horizon_clip"+u).append("svg:rect").attr("width",f).attr("height",g),B.select("rect").transition().duration(h).attr("width",f).attr("height",g),C.append("svg:path").attr("id","d3_chart_horizon_path"+u).attr("d",j.interpolate(c).x(function(a){return s(a[0])}).y0(g*a).y1(function(b){return g*a-t(b[1])})).transition().duration(h).attr("d",j.x(function(a){return z(a[0])}).y1(function(b){return g*a-A(b[1])})),B.select("path").transition().duration(h).attr("d",j),n.selectAll("g").data([null]).enter().append("svg:g").attr("clip-path","url(#d3_chart_horizon_clip"+u+")");var D=b=="offset"?function(b){return"translate(0,"+(b+(b<0)-a)*g+")"}:function(b){return(b<0?"scale(1,-1)":"")+"translate(0,"+(b-a)*g+")"},E=n.select("g").selectAll("use").data(d3.range(-1,-a-1,-1).concat(d3.range(1,a+1)),Number);E.enter().append("svg:use").attr("xlink:href","#d3_chart_horizon_path"+u).attr("transform",function(a){return D(a+(a>0?1:-1))}).style("fill",i).transition().duration(h).attr("transform",D),E.transition().duration(h).attr("transform",D).style("fill",i),E.exit().transition().duration(h).attr("transform",D).remove(),this.__chart__={x:z,y:A,id:u}}),d3.timer.flush()}var a=1,b="offset",c="linear",d=l,e=m,f=960,g=40,h=0,i=d3.scale.linear().domain([-1,0,1]).range(["#d62728","#fff","#1f77b4"]);n.duration=function(a){if(!arguments.length)return h;h=+a;return n},n.bands=function(b){if(!arguments.length)return a;a=+b,i.domain([-a,0,a]);return n},n.mode=function(a){if(!arguments.length)return b;b=a+"";return n},n.colors=function(a){if(!arguments.length)return i.range();i.range(a);return n},n.interpolate=function(a){if(!arguments.length)return c;c=a+"";return n},n.x=function(a){if(!arguments.length)return d;d=a;return n},n.y=function(a){if(!arguments.length)return e;e=a;return n},n.width=function(a){if(!arguments.length)return f;f=+a;return n},n.height=function(a){if(!arguments.length)return g;g=+a;return n};return n};var j=d3.svg.area(),k=0;d3.chart.qq=function(){function i(i){i.each(function(i,j){var k=d3.select(this),l=n(f,g.call(this,i,j)),m=n(f,h.call(this,i,j)),o=d&&d.call(this,i,j)||[d3.min(l),d3.max(l)],p=d&&d.call(this,i,j)||[d3.min(m),d3.max(m)],q,r,s=d3.scale.linear().domain(o).range([0,a]),t=d3.scale.linear().domain(p).range([b,0]);this.__chart__?(q=this.__chart__.x,r=this.__chart__.y):(q=d3.scale.linear().domain([0,Infinity]).range(s.range()),r=d3.scale.linear().domain([0,Infinity]).range(t.range())),this.__chart__={x:s,y:t};var u=k.selectAll("line.diagonal").data([null]);u.enter().append("svg:line").attr("class","diagonal").attr("x1",s(p[0])).attr("y1",t(o[0])).attr("x2",s(p[1])).attr("y2",t(o[1])),u.transition().duration(c).attr("x1",s(p[0])).attr("y1",t(o[0])).attr("x2",s(p[1])).attr("y2",t(o[1]));var v=k.selectAll("circle").data(d3.range(f).map(function(a){return{x:l[a],y:m[a]}}));v.enter().append("svg:circle").attr("class","quantile").attr("r",4.5).attr("cx",function(a){return q(a.x)}).attr("cy",function(a){return r(a.y)}).style("opacity",1e-6).transition().duration(c).attr("cx",function(a){return s(a.x)}).attr("cy",function(a){return t(a.y)}).style("opacity",1),v.transition().duration(c).attr("cx",function(a){return s(a.x)}).attr("cy",function(a){return t(a.y)}).style("opacity",1),v.exit().transition().duration(c).attr("cx",function(a){return s(a.x)}).attr("cy",function(a){return t(a.y)}).style("opacity",1e-6).remove();var w=e||s.tickFormat(4),z=e||t.tickFormat(4),A=function(a){return"translate("+s(a)+","+b+")"},B=function(a){return"translate(0,"+t(a)+")"},C=k.selectAll("g.x.tick").data(s.ticks(4),function(a){return this.textContent||w(a)}),D=C.enter().append("svg:g").attr("class","x tick").attr("transform",function(a){return"translate("+q(a)+","+b+")"}).style("opacity",1e-6);D.append("svg:line").attr("y1",0).attr("y2",-6),D.append("svg:text").attr("text-anchor","middle").attr("dy","1em").text(w),D.transition().duration(c).attr("transform",A).style("opacity",1),C.transition().duration(c).attr("transform",A).style("opacity",1),C.exit().transition().duration(c).attr("transform",A).style("opacity",1e-6).remove();var E=k.selectAll("g.y.tick").data(t.ticks(4),function(a){return this.textContent||z(a)}),F=E.enter().append("svg:g").attr("class","y tick").attr("transform",function(a){return"translate(0,"+r(a)+")"}).style("opacity",1e-6);F.append("svg:line").attr("x1",0).attr("x2",6),F.append("svg:text").attr("text-anchor","end").attr("dx","-.5em").attr("dy",".3em").text(z),F.transition().duration(c).attr("transform",B).style("opacity",1),E.transition().duration(c).attr("transform",B).style("opacity",1),E.exit().transition().duration(c).attr("transform",B).style("opacity",1e-6).remove()})}var a=1,b=1,c=0,d=null,e=null,f=100,g=o,h=p;i.width=function(b){if(!arguments.length)return a;a=b;return i},i.height=function(a){if(!arguments.length)return b;b=a;return i},i.duration=function(a){if(!arguments.length)return c;c=a;return i},i.domain=function(a){if(!arguments.length)return d;d=a==null?a:d3.functor(a);return i},i.count=function(a){if(!arguments.length)return f;f=a;return i},i.x=function(a){if(!arguments.length)return g;g=a;return i},i.y=function(a){if(!arguments.length)return h;h=a;return i},i.tickFormat=function(a){if(!arguments.length)return e;e=a;return i};return i}})()
<ide>\ No newline at end of file
<add>(function(){function p(a){return a.y}function o(a){return a.x}function n(a,b){var c=b.length-1;b=b.slice().sort(d3.ascending);return d3.range(a).map(function(d){return b[~~(d*c/a)]})}function m(a){return a[1]}function l(a){return a[0]}function i(a){var b=a(0);return function(c){return Math.abs(a(c)-b)}}function h(a){return function(b){return"translate("+a(b)+",0)"}}function g(a){return a.measures}function f(a){return a.markers}function e(a){return a.ranges}function d(a){return[d3.quantile(a,.25),d3.quantile(a,.5),d3.quantile(a,.75)]}function c(a){return[0,a.length-1]}function b(a,b){a.attr("transform",function(a){return"translate(0,"+b(a)+")"})}function a(a,b){a.attr("transform",function(a){return"translate("+b(a)+",0)"})}d3.chart={},d3.chart.axis=function(){function i(i){i.each(function(j,k,l){function z(a){return i.delay?a.transition().delay(i[l][k].delay).duration(i[l][k].duration).ease(i.ease()):a}var m=d3.select(this),n=c.ticks.apply(c,g),o=h||c.tickFormat.apply(c,g),p=m.selectAll("g.tick").data(n,String),q=p.enter().insert("svg:g","path").attr("class","tick").style("opacity",1e-6),r=z(p.exit()).style("opacity",1e-6).remove(),s=z(p).style("opacity",1),t,u=c.range(),v=m.selectAll("path.domain").data([]),w=v.enter().append("svg:path").attr("class","domain"),x=z(v),y=this.__chart__||c;this.__chart__=c.copy(),q.append("svg:line"),q.append("svg:text"),s.select("text").text(o);switch(d){case"bottom":t=a,q.select("text").attr("dy",".71em").attr("text-anchor","middle"),s.select("line").attr("y2",e),s.select("text").attr("y",Math.max(e,0)+f),x.attr("d","M"+u[0]+","+e+"V0H"+u[1]+"V"+e);break;case"top":t=a,q.select("text").attr("text-anchor","middle"),s.select("line").attr("y2",-e),s.select("text").attr("y",-(Math.max(e,0)+f)),x.attr("d","M"+u[0]+","+ -e+"V0H"+u[1]+"V"+ -e);break;case"left":t=b,q.select("text").attr("dy",".32em").attr("text-anchor","end"),s.select("line").attr("x2",-e),s.select("text").attr("x",-(Math.max(e,0)+f)),x.attr("d","M"+ -e+","+u[0]+"H0V"+u[1]+"H"+ -e);break;case"right":t=b,q.select("text").attr("dy",".32em"),s.select("line").attr("x2",e),s.select("text").attr("x",Math.max(e,0)+f),x.attr("d","M"+e+","+u[0]+"H0V"+u[1]+"H"+e)}q.call(t,y),s.call(t,c),r.call(t,c)})}var c=d3.scale.linear(),d="bottom",e=6,f=3,g=[10],h;i.scale=function(a){if(!arguments.length)return c;c=a;return i},i.orient=function(a){if(!arguments.length)return d;d=a;return i},i.tickSize=function(a){if(!arguments.length)return e;e=+a;return i},i.tickPadding=function(a){if(!arguments.length)return f;f=+a;return i},i.ticks=function(){if(!arguments.length)return g;g=arguments;return i},i.tickFormat=function(a){if(!arguments.length)return h;h=a;return i};return i},d3.chart.box=function(){function k(c){c.each(function(c,d){c=c.map(g).sort(d3.ascending);var k=d3.select(this),l=c.length,m=c[0],n=c[l-1],o=c.quartiles=i(c),p=h&&h.call(this,c,d),q=p&&p.map(function(a){return c[a]}),r=p?d3.range(0,p[0]).concat(d3.range(p[1]+1,l)):d3.range(l),s=d3.scale.linear().domain(f&&f.call(this,c,d)||[m,n]).range([b,0]),t=this.__chart__||d3.scale.linear().domain([0,Infinity]).range(s.range());this.__chart__=s;var u=k.selectAll("line.center").data(q?[q]:[]);u.enter().insert("svg:line","rect").attr("class","center").attr("x1",a/2).attr("y1",function(a){return t(a[0])}).attr("x2",a/2).attr("y2",function(a){return t(a[1])}).style("opacity",1e-6).transition().duration(e).style("opacity",1).attr("y1",function(a){return s(a[0])}).attr("y2",function(a){return s(a[1])}),u.transition().duration(e).style("opacity",1).attr("y1",function(a){return s(a[0])}).attr("y2",function(a){return s(a[1])}),u.exit().transition().duration(e).style("opacity",1e-6).attr("y1",function(a){return s(a[0])}).attr("y2",function(a){return s(a[1])}).remove();var v=k.selectAll("rect.box").data([o]);v.enter().append("svg:rect").attr("class","box").attr("x",0).attr("y",function(a){return t(a[2])}).attr("width",a).attr("height",function(a){return t(a[0])-t(a[2])}).transition().duration(e).attr("y",function(a){return s(a[2])}).attr("height",function(a){return s(a[0])-s(a[2])}),v.transition().duration(e).attr("y",function(a){return s(a[2])}).attr("height",function(a){return s(a[0])-s(a[2])});var w=k.selectAll("line.median").data([o[1]]);w.enter().append("svg:line").attr("class","median").attr("x1",0).attr("y1",t).attr("x2",a).attr("y2",t).transition().duration(e).attr("y1",s).attr("y2",s),w.transition().duration(e).attr("y1",s).attr("y2",s);var x=k.selectAll("line.whisker").data(q||[]);x.enter().insert("svg:line","circle, text").attr("class","whisker").attr("x1",0).attr("y1",t).attr("x2",a).attr("y2",t).style("opacity",1e-6).transition().duration(e).attr("y1",s).attr("y2",s).style("opacity",1),x.transition().duration(e).attr("y1",s).attr("y2",s).style("opacity",1),x.exit().transition().duration(e).attr("y1",s).attr("y2",s).style("opacity",1e-6).remove();var y=k.selectAll("circle.outlier").data(r,Number);y.enter().insert("svg:circle","text").attr("class","outlier").attr("r",5).attr("cx",a/2).attr("cy",function(a){return t(c[a])}).style("opacity",1e-6).transition().duration(e).attr("cy",function(a){return s(c[a])}).style("opacity",1),y.transition().duration(e).attr("cy",function(a){return s(c[a])}).style("opacity",1),y.exit().transition().duration(e).attr("cy",function(a){return s(c[a])}).style("opacity",1e-6).remove();var z=j||s.tickFormat(8),A=k.selectAll("text.box").data(o);A.enter().append("svg:text").attr("class","box").attr("dy",".3em").attr("dx",function(a,b){return b&1?6:-6}).attr("x",function(b,c){return c&1?a:0}).attr("y",t).attr("text-anchor",function(a,b){return b&1?"start":"end"}).text(z).transition().duration(e).attr("y",s),A.transition().duration(e).text(z).attr("y",s);var B=k.selectAll("text.whisker").data(q||[]);B.enter().append("svg:text").attr("class","whisker").attr("dy",".3em").attr("dx",6).attr("x",a).attr("y",t).text(z).style("opacity",1e-6).transition().duration(e).attr("y",s).style("opacity",1),B.transition().duration(e).text(z).attr("y",s).style("opacity",1),B.exit().transition().duration(e).attr("y",s).style("opacity",1e-6).remove()}),d3.timer.flush()}var a=1,b=1,e=0,f=null,g=Number,h=c,i=d,j=null;k.width=function(b){if(!arguments.length)return a;a=b;return k},k.height=function(a){if(!arguments.length)return b;b=a;return k},k.tickFormat=function(a){if(!arguments.length)return j;j=a;return k},k.duration=function(a){if(!arguments.length)return e;e=a;return k},k.domain=function(a){if(!arguments.length)return f;f=a==null?a:d3.functor(a);return k},k.value=function(a){if(!arguments.length)return g;g=a;return k},k.whiskers=function(a){if(!arguments.length)return h;h=a;return k},k.quartiles=function(a){if(!arguments.length)return i;i=a;return k};return k},d3.chart.bullet=function(){function o(a){a.each(function(a,e){var f=d.call(this,a,e).slice().sort(d3.descending),g=j.call(this,a,e).slice().sort(d3.descending),o=k.call(this,a,e).slice().sort(d3.descending),p=d3.select(this),q=d3.scale.linear().domain([0,Math.max(f[0],g[0],o[0])]).range(b?[l,0]:[0,l]),r=this.__chart__||d3.scale.linear().domain([0,Infinity]).range(q.range());this.__chart__=q;var s=i(r),t=i(q),u=p.selectAll("rect.range").data(f);u.enter().append("svg:rect").attr("class",function(a,b){return"range s"+b}).attr("width",s).attr("height",m).attr("x",b?r:0).transition().duration(c).attr("width",t).attr("x",b?q:0),u.transition().duration(c).attr("x",b?q:0).attr("width",t).attr("height",m);var v=p.selectAll("rect.measure").data(o);v.enter().append("svg:rect").attr("class",function(a,b){return"measure s"+b}).attr("width",s).attr("height",m/3).attr("x",b?r:0).attr("y",m/3).transition().duration(c).attr("width",t).attr("x",b?q:0),v.transition().duration(c).attr("width",t).attr("height",m/3).attr("x",b?q:0).attr("y",m/3);var w=p.selectAll("line.marker").data(g);w.enter().append("svg:line").attr("class","marker").attr("x1",r).attr("x2",r).attr("y1",m/6).attr("y2",m*5/6).transition().duration(c).attr("x1",q).attr("x2",q),w.transition().duration(c).attr("x1",q).attr("x2",q).attr("y1",m/6).attr("y2",m*5/6);var x=n||q.tickFormat(8),y=p.selectAll("g.tick").data(q.ticks(8),function(a){return this.textContent||x(a)}),z=y.enter().append("svg:g").attr("class","tick").attr("transform",h(r)).style("opacity",1e-6);z.append("svg:line").attr("y1",m).attr("y2",m*7/6),z.append("svg:text").attr("text-anchor","middle").attr("dy","1em").attr("y",m*7/6).text(x),z.transition().duration(c).attr("transform",h(q)).style("opacity",1);var A=y.transition().duration(c).attr("transform",h(q)).style("opacity",1);A.select("line").attr("y1",m).attr("y2",m*7/6),A.select("text").attr("y",m*7/6),y.exit().transition().duration(c).attr("transform",h(q)).style("opacity",1e-6).remove()}),d3.timer.flush()}var a="left",b=!1,c=0,d=e,j=f,k=g,l=380,m=30,n=null;o.orient=function(c){if(!arguments.length)return a;a=c,b=a=="right"||a=="bottom";return o},o.ranges=function(a){if(!arguments.length)return d;d=a;return o},o.markers=function(a){if(!arguments.length)return j;j=a;return o},o.measures=function(a){if(!arguments.length)return k;k=a;return o},o.width=function(a){if(!arguments.length)return l;l=a;return o},o.height=function(a){if(!arguments.length)return m;m=a;return o},o.tickFormat=function(a){if(!arguments.length)return n;n=a;return o},o.duration=function(a){if(!arguments.length)return c;c=a;return o};return o},d3.chart.horizon=function(){function n(l){l.each(function(l,m){var n=d3.select(this),o=2*a+1,p=Infinity,q=-Infinity,r=-Infinity,s,t,u,v=l.map(function(a,b){var c=d.call(this,a,b),f=e.call(this,a,b);c<p&&(p=c),c>q&&(q=c),-f>r&&(r=-f),f>r&&(r=f);return[c,f]}),z=d3.scale.linear().domain([p,q]).range([0,f]),A=d3.scale.linear().domain([0,r]).range([0,g*a]);this.__chart__?(s=this.__chart__.x,t=this.__chart__.y,u=this.__chart__.id):(s=d3.scale.linear().domain([0,Infinity]).range(z.range()),t=d3.scale.linear().domain([0,Infinity]).range(A.range()),u=++k);var B=n.selectAll("defs").data([v]),C=B.enter().append("svg:defs");C.append("svg:clipPath").attr("id","d3_chart_horizon_clip"+u).append("svg:rect").attr("width",f).attr("height",g),B.select("rect").transition().duration(h).attr("width",f).attr("height",g),C.append("svg:path").attr("id","d3_chart_horizon_path"+u).attr("d",j.interpolate(c).x(function(a){return s(a[0])}).y0(g*a).y1(function(b){return g*a-t(b[1])})).transition().duration(h).attr("d",j.x(function(a){return z(a[0])}).y1(function(b){return g*a-A(b[1])})),B.select("path").transition().duration(h).attr("d",j),n.selectAll("g").data([null]).enter().append("svg:g").attr("clip-path","url(#d3_chart_horizon_clip"+u+")");var D=b=="offset"?function(b){return"translate(0,"+(b+(b<0)-a)*g+")"}:function(b){return(b<0?"scale(1,-1)":"")+"translate(0,"+(b-a)*g+")"},E=n.select("g").selectAll("use").data(d3.range(-1,-a-1,-1).concat(d3.range(1,a+1)),Number);E.enter().append("svg:use").attr("xlink:href","#d3_chart_horizon_path"+u).attr("transform",function(a){return D(a+(a>0?1:-1))}).style("fill",i).transition().duration(h).attr("transform",D),E.transition().duration(h).attr("transform",D).style("fill",i),E.exit().transition().duration(h).attr("transform",D).remove(),this.__chart__={x:z,y:A,id:u}}),d3.timer.flush()}var a=1,b="offset",c="linear",d=l,e=m,f=960,g=40,h=0,i=d3.scale.linear().domain([-1,0,1]).range(["#d62728","#fff","#1f77b4"]);n.duration=function(a){if(!arguments.length)return h;h=+a;return n},n.bands=function(b){if(!arguments.length)return a;a=+b,i.domain([-a,0,a]);return n},n.mode=function(a){if(!arguments.length)return b;b=a+"";return n},n.colors=function(a){if(!arguments.length)return i.range();i.range(a);return n},n.interpolate=function(a){if(!arguments.length)return c;c=a+"";return n},n.x=function(a){if(!arguments.length)return d;d=a;return n},n.y=function(a){if(!arguments.length)return e;e=a;return n},n.width=function(a){if(!arguments.length)return f;f=+a;return n},n.height=function(a){if(!arguments.length)return g;g=+a;return n};return n};var j=d3.svg.area(),k=0;d3.chart.qq=function(){function i(i){i.each(function(i,j){var k=d3.select(this),l=n(f,g.call(this,i,j)),m=n(f,h.call(this,i,j)),o=d&&d.call(this,i,j)||[d3.min(l),d3.max(l)],p=d&&d.call(this,i,j)||[d3.min(m),d3.max(m)],q,r,s=d3.scale.linear().domain(o).range([0,a]),t=d3.scale.linear().domain(p).range([b,0]);this.__chart__?(q=this.__chart__.x,r=this.__chart__.y):(q=d3.scale.linear().domain([0,Infinity]).range(s.range()),r=d3.scale.linear().domain([0,Infinity]).range(t.range())),this.__chart__={x:s,y:t};var u=k.selectAll("line.diagonal").data([null]);u.enter().append("svg:line").attr("class","diagonal").attr("x1",s(p[0])).attr("y1",t(o[0])).attr("x2",s(p[1])).attr("y2",t(o[1])),u.transition().duration(c).attr("x1",s(p[0])).attr("y1",t(o[0])).attr("x2",s(p[1])).attr("y2",t(o[1]));var v=k.selectAll("circle").data(d3.range(f).map(function(a){return{x:l[a],y:m[a]}}));v.enter().append("svg:circle").attr("class","quantile").attr("r",4.5).attr("cx",function(a){return q(a.x)}).attr("cy",function(a){return r(a.y)}).style("opacity",1e-6).transition().duration(c).attr("cx",function(a){return s(a.x)}).attr("cy",function(a){return t(a.y)}).style("opacity",1),v.transition().duration(c).attr("cx",function(a){return s(a.x)}).attr("cy",function(a){return t(a.y)}).style("opacity",1),v.exit().transition().duration(c).attr("cx",function(a){return s(a.x)}).attr("cy",function(a){return t(a.y)}).style("opacity",1e-6).remove();var w=e||s.tickFormat(4),z=e||t.tickFormat(4),A=function(a){return"translate("+s(a)+","+b+")"},B=function(a){return"translate(0,"+t(a)+")"},C=k.selectAll("g.x.tick").data(s.ticks(4),function(a){return this.textContent||w(a)}),D=C.enter().append("svg:g").attr("class","x tick").attr("transform",function(a){return"translate("+q(a)+","+b+")"}).style("opacity",1e-6);D.append("svg:line").attr("y1",0).attr("y2",-6),D.append("svg:text").attr("text-anchor","middle").attr("dy","1em").text(w),D.transition().duration(c).attr("transform",A).style("opacity",1),C.transition().duration(c).attr("transform",A).style("opacity",1),C.exit().transition().duration(c).attr("transform",A).style("opacity",1e-6).remove();var E=k.selectAll("g.y.tick").data(t.ticks(4),function(a){return this.textContent||z(a)}),F=E.enter().append("svg:g").attr("class","y tick").attr("transform",function(a){return"translate(0,"+r(a)+")"}).style("opacity",1e-6);F.append("svg:line").attr("x1",0).attr("x2",6),F.append("svg:text").attr("text-anchor","end").attr("dx","-.5em").attr("dy",".3em").text(z),F.transition().duration(c).attr("transform",B).style("opacity",1),E.transition().duration(c).attr("transform",B).style("opacity",1),E.exit().transition().duration(c).attr("transform",B).style("opacity",1e-6).remove()})}var a=1,b=1,c=0,d=null,e=null,f=100,g=o,h=p;i.width=function(b){if(!arguments.length)return a;a=b;return i},i.height=function(a){if(!arguments.length)return b;b=a;return i},i.duration=function(a){if(!arguments.length)return c;c=a;return i},i.domain=function(a){if(!arguments.length)return d;d=a==null?a:d3.functor(a);return i},i.count=function(a){if(!arguments.length)return f;f=a;return i},i.x=function(a){if(!arguments.length)return g;g=a;return i},i.y=function(a){if(!arguments.length)return h;h=a;return i},i.tickFormat=function(a){if(!arguments.length)return e;e=a;return i};return i}})()
<ide>\ No newline at end of file
<ide><path>src/chart/axis.js
<ide> d3.chart.axis = function() {
<ide> var ticks = scale.ticks.apply(scale, tickArguments_),
<ide> tickFormat = tickFormat_ || scale.tickFormat.apply(scale, tickArguments_),
<ide> tick = g.selectAll("g.tick").data(ticks, String),
<del> tickEnter = tick.enter().append("svg:g").attr("class", "tick").style("opacity", 1e-6),
<add> tickEnter = tick.enter().insert("svg:g", "path").attr("class", "tick").style("opacity", 1e-6),
<ide> tickExit = transition(tick.exit()).style("opacity", 1e-6).remove(),
<ide> tickUpdate = transition(tick).style("opacity", 1),
<ide> tickTransform;
<ide><path>test/chart/axis-test.js
<ide> suite.addBatch({
<ide> "updates the domain path": function(axis) {
<ide> var a = axis(),
<ide> g = d3.select("body").html("").append("svg:g").call(a);
<del> a.scale().range([1, 2]);
<add> a.scale().domain([0, 2]).range([1, 2]);
<ide> a.tickSize(3);
<ide> g.call(a);
<ide> var path = g.selectAll("path.domain");
<ide> assert.equal(path[0].length, 1);
<ide> assert.equal(path.attr("d"), "M1,3V0H2V3");
<del> assert.isNull(path.node().nextSibling);
<add> assert.domEqual(path.node().nextSibling, null);
<ide> },
<ide> "enters, exits and updates tick marks": function(axis) {
<ide> var a = axis(),
<ide> suite.addBatch({
<ide> assert.equal(t.select("text").text(), tickFormat(ticks[i]));
<ide> });
<ide> }
<del> },
<add> }
<ide> }
<ide> });
<ide> | 4 |
Ruby | Ruby | install svn on catalina and newer | dbbc14040d7acc94ca6e40c39ca60b38aa1419b0 | <ide><path>Library/Homebrew/extend/os/mac/dependency_collector.rb
<ide> class DependencyCollector
<ide>
<ide> def git_dep_if_needed(tags); end
<ide>
<del> def subversion_dep_if_needed(tags); end
<add> def subversion_dep_if_needed(tags)
<add> Dependency.new("subversion", tags) if MacOS.version >= :catalina
<add> end
<ide>
<ide> def cvs_dep_if_needed(tags)
<ide> Dependency.new("cvs", tags)
<ide><path>Library/Homebrew/test/os/mac/dependency_collector_spec.rb
<ide> specify "Resource dependency from a Subversion URL" do
<ide> resource = Resource.new
<ide> resource.url("svn://brew.sh/foo/bar")
<del> expect(subject.add(resource)).to be nil
<add> if MacOS.version < :catalina
<add> expect(subject.add(resource)).to be nil
<add> else
<add> expect(subject.add(resource)).not_to be nil
<add> end
<ide> end
<ide> end | 2 |
PHP | PHP | fix bug with routing and dashes | 3413503c0a616d4b9e1c1cf550b6b576174d1b9c | <ide><path>src/Illuminate/Routing/Route.php
<ide> public function domain()
<ide> return array_get($this->action, 'domain');
<ide> }
<ide>
<add> /**
<add> * Get the URI that the route responds to.
<add> *
<add> * @return string
<add> */
<add> public function getUri()
<add> {
<add> return $this->uri;
<add> }
<add>
<ide> /**
<ide> * Get the name of the route instance.
<ide> *
<ide><path>src/Illuminate/Routing/Router.php
<ide> public function resource($name, $controller, array $options = array())
<ide> // We need to extract the base resource from the resource name. Nested resources
<ide> // are supported in the framework, but we need to know what name to use for a
<ide> // place-holder on the route wildcards, which should be the base resources.
<del> $base = last(explode('.', $name));
<add> $base = $this->getResourceWildcard(last(explode('.', $name)));
<ide>
<ide> $defaults = $this->resourceDefaults;
<ide>
<ide> public function getResourceUri($resource)
<ide>
<ide> $uri = $this->getNestedResourceUri($segments);
<ide>
<del> return str_replace('/{'.last($segments).'}', '', $uri);
<add> return str_replace('/{'.$this->getResourceWildcard(last($segments)).'}', '', $uri);
<ide> }
<ide>
<ide> /**
<ide> public function getResourceUri($resource)
<ide> */
<ide> protected function getNestedResourceUri(array $segments)
<ide> {
<add> $me = $this;
<add>
<ide> // We will spin through the segments and create a place-holder for each of the
<ide> // resource segments, as well as the resource itself. Then we should get an
<ide> // entire string for the resource URI that contains all nested resources.
<del> return implode('/', array_map(function($s)
<add> return implode('/', array_map(function($s) use ($me)
<ide> {
<del> return $s.'/{'.$s.'}';
<add> return $s.'/{'.$me->getResourceWildcard($s).'}';
<ide>
<ide> }, $segments));
<ide> }
<ide> protected function getGroupResourceName($resource, $method)
<ide> return trim("{$prefix}.{$resource}.{$method}", '.');
<ide> }
<ide>
<add> /**
<add> * Format a resource wildcard for usage.
<add> *
<add> * @param string $value
<add> * @return string
<add> */
<add> public function getResourceWildcard($value)
<add> {
<add> return str_replace('-', '_', $value);
<add> }
<add>
<ide> /**
<ide> * Add the index method for a resourceful route.
<ide> *
<ide> public function model($key, $class, Closure $callback = null)
<ide> */
<ide> public function bind($key, $binder)
<ide> {
<del> $this->binders[$key] = $binder;
<add> $this->binders[str_replace('-', '_', $key)] = $binder;
<ide> }
<ide>
<ide> /**
<ide><path>tests/Routing/RoutingRouteTest.php
<ide> public function testResourceRouting()
<ide> $routes = $router->getRoutes();
<ide>
<ide> $this->assertEquals(6, count($routes));
<add>
<add> $router = $this->getRouter();
<add> $router->resource('foo-bars', 'FooController', array('only' => array('show')));
<add> $routes = $router->getRoutes();
<add> $routes = $routes->getRoutes();
<add>
<add> $this->assertEquals('foo-bars/{foo_bars}', $routes[0]->getUri());
<add>
<add> $router = $this->getRouter();
<add> $router->resource('foo-bars.foo-bazs', 'FooController', array('only' => array('show')));
<add> $routes = $router->getRoutes();
<add> $routes = $routes->getRoutes();
<add>
<add> $this->assertEquals('foo-bars/{foo_bars}/foo-bazs/{foo_bazs}', $routes[0]->getUri());
<ide> }
<ide>
<ide> | 3 |
Python | Python | support gpu in ud training script | 8bbd26579cad81a8a347ed8c097e389110569312 | <ide><path>spacy/cli/ud_train.py
<ide> def load_nlp(corpus, config):
<ide> nlp.vocab.from_disk(Path(config.vectors) / 'vocab')
<ide> return nlp
<ide>
<del>def initialize_pipeline(nlp, docs, golds, config):
<add>def initialize_pipeline(nlp, docs, golds, config, device):
<ide> nlp.add_pipe(nlp.create_pipe('parser'))
<ide> if config.multitask_tag:
<ide> nlp.parser.add_multitask_objective('tag')
<ide> def initialize_pipeline(nlp, docs, golds, config):
<ide> for tag in gold.tags:
<ide> if tag is not None:
<ide> nlp.tagger.add_label(tag)
<del> return nlp.begin_training(lambda: golds_to_gold_tuples(docs, golds))
<add> return nlp.begin_training(lambda: golds_to_gold_tuples(docs, golds), device=device)
<ide>
<ide>
<ide> ########################
<ide> def __init__(self, ud_path, treebank, **cfg):
<ide> "positional", None, str),
<ide> parses_dir=("Directory to write the development parses", "positional", None, Path),
<ide> config=("Path to json formatted config file", "positional"),
<del> limit=("Size limit", "option", "n", int)
<add> limit=("Size limit", "option", "n", int),
<add> use_gpu=("Use GPU", "option", "g", int)
<ide> )
<del>def main(ud_dir, parses_dir, config, corpus, limit=0):
<add>def main(ud_dir, parses_dir, config, corpus, limit=0, use_gpu=-1):
<add> spacy.util.fix_random_seed()
<ide> lang.zh.Chinese.Defaults.use_jieba = False
<ide> lang.ja.Japanese.Defaults.use_janome = False
<ide>
<del> random.seed(0)
<del> numpy.random.seed(0)
<del>
<ide> config = Config.load(config)
<ide> paths = TreebankPaths(ud_dir, corpus)
<ide> if not (parses_dir / corpus).exists():
<ide> def main(ud_dir, parses_dir, config, corpus, limit=0):
<ide> docs, golds = read_data(nlp, paths.train.conllu.open(), paths.train.text.open(),
<ide> max_doc_length=config.max_doc_length, limit=limit)
<ide>
<del> optimizer = initialize_pipeline(nlp, docs, golds, config)
<add> optimizer = initialize_pipeline(nlp, docs, golds, config, use_gpu)
<ide>
<del> batch_sizes = compounding(config.batch_size //10, config.batch_size, 1.001)
<add> batch_sizes = compounding(config.batch_size//10, config.batch_size, 1.001)
<ide> for i in range(config.nr_epoch):
<ide> docs = [nlp.make_doc(doc.text) for doc in docs]
<ide> Xs = list(zip(docs, golds)) | 1 |
PHP | PHP | fix failing build | d217a2094cf0cbc9ab1a15aeab7c19533e08178c | <ide><path>tests/Database/DatabaseQueryBuilderTest.php
<ide> public function testWhereTimeOperatorOptionalMySql()
<ide> $this->assertEquals([0 => '22:00'], $builder->getBindings());
<ide> }
<ide>
<del> public function testWhereTimePostgres()
<del> {
<del> $builder = $this->getPostgresBuilder();
<del> $builder->select('*')->from('users')->whereTime('created_at', '>=', '22:00');
<del> $this->assertEquals('select * from "users" where "created_at"::time >= ?', $builder->toSql());
<del> $this->assertEquals([0 => '22:00'], $builder->getBindings());
<del> }
<del>
<ide> public function testWhereTimeOperatorOptionalPostgres()
<ide> {
<ide> $builder = $this->getPostgresBuilder(); | 1 |
Ruby | Ruby | use delegator for a cleaner queuedmessage class | 5337149caf28b9d8bfe907584511453044890ebd | <ide><path>actionmailer/lib/action_mailer/async.rb
<add>require 'delegate'
<add>
<ide> module ActionMailer::Async
<ide> def self.included(base)
<ide> base.extend(ClassMethods)
<ide> def method_missing(method_name, *args)
<ide> end
<ide> end
<ide>
<del> class QueuedMessage
<del> delegate :to_s, :to => :actual_message
<del>
<add> class QueuedMessage < ::Delegator
<ide> def initialize(mailer_class, method_name, *args)
<ide> @mailer_class = mailer_class
<ide> @method_name = method_name
<ide> *@args = *args
<ide> end
<ide>
<add> def __getobj__
<add> @actual_message ||= @mailer_class.send(:new, @method_name, *@args).message
<add> end
<add>
<ide> def run
<del> actual_message.deliver
<add> __getobj__.deliver
<ide> end
<ide>
<ide> # Will push the message onto the Queue to be processed
<ide> def deliver(force = false)
<ide> Rails.queue << self
<ide> end
<ide> end
<del>
<del> # The original ActionMailer message
<del> def actual_message
<del> @actual_message ||= @mailer_class.send(:new, @method_name, *@args).message
<del> end
<del>
<del> def method_missing(method_name, *args)
<del> actual_message.send(method_name, *args)
<del> end
<ide> end
<ide> end | 1 |
Ruby | Ruby | add todo for removal of server_addr | 52dc8ed28fe998cfd25cc79052de4e08fb5faf3b | <ide><path>actionpack/lib/action_dispatch/http/request.rb
<ide> class Request
<ide> SERVER_ADDR
<ide> ].freeze
<ide>
<add> # TODO: Remove SERVER_ADDR when we remove support to Rack 2.1.
<add> # See https://github.com/rack/rack/commit/c173b188d81ee437b588c1e046a1c9f031dea550
<ide> ENV_METHODS.each do |env|
<ide> class_eval <<-METHOD, __FILE__, __LINE__ + 1
<ide> def #{env.sub(/^HTTP_/n, '').downcase} # def accept_charset | 1 |
Javascript | Javascript | fix stat with long paths on windows | a4f4909f3d15dbc02f4742ad168afbe11d6d8dc4 | <ide><path>lib/module.js
<ide> Module._findPath = function(request, paths) {
<ide> // For each path
<ide> for (var i = 0, PL = paths.length; i < PL; i++) {
<ide> // Don't search further if path doesn't exist
<del> if (paths[i] && internalModuleStat(paths[i]) < 1) continue;
<add> if (paths[i] && internalModuleStat(path._makeLong(paths[i])) < 1) continue;
<ide> var basePath = path.resolve(paths[i], request);
<ide> var filename;
<ide>
<ide><path>test/parallel/test-require-long-path.js
<ide> 'use strict';
<del>var common = require('../common');
<del>var fs = require('fs');
<del>var path = require('path');
<del>var assert = require('assert');
<add>const common = require('../common');
<add>const fs = require('fs');
<add>const path = require('path');
<ide>
<ide> // make a path that is more than 260 chars long.
<del>var fileNameLen = Math.max(261 - common.tmpDir.length - 1, 1);
<del>var fileName = path.join(common.tmpDir, new Array(fileNameLen + 1).join('x'));
<del>var fullPath = path.resolve(fileName);
<add>const dirNameLen = Math.max(260 - common.tmpDir.length, 1);
<add>const dirName = path.join(common.tmpDir, 'x'.repeat(dirNameLen));
<add>const fullDirPath = path.resolve(dirName);
<add>
<add>const indexFile = path.join(fullDirPath, 'index.js');
<add>const otherFile = path.join(fullDirPath, 'other.js');
<ide>
<ide> common.refreshTmpDir();
<del>fs.writeFileSync(fullPath, 'module.exports = 42;');
<ide>
<del>assert.equal(require(fullPath), 42);
<add>fs.mkdirSync(fullDirPath);
<add>fs.writeFileSync(indexFile, 'require("./other");');
<add>fs.writeFileSync(otherFile, '');
<add>
<add>require(indexFile);
<add>require(otherFile);
<ide>
<del>fs.unlinkSync(fullPath);
<add>common.refreshTmpDir(); | 2 |
PHP | PHP | remove invalid test | 21d12eb658f80f4903fda6be0428d9d730dbf4aa | <ide><path>tests/TestCase/Validation/ValidationTest.php
<ide> public function testNotAsciiAlphaNumeric()
<ide> $this->assertTrue(Validation::notAsciiAlphaNumeric('ÆΔΩЖÇ'));
<ide> $this->assertTrue(Validation::notAsciiAlphaNumeric('12 234'));
<ide> $this->assertTrue(Validation::notAsciiAlphaNumeric('dfd 234'));
<del> $this->assertTrue(Validation::notAsciiAlphaNumeric("0\n"));
<ide> $this->assertTrue(Validation::notAsciiAlphaNumeric("\n"));
<ide> $this->assertTrue(Validation::notAsciiAlphaNumeric("\t"));
<ide> $this->assertTrue(Validation::notAsciiAlphaNumeric("\r")); | 1 |
Mixed | Go | move cgroupnsmode feature to api v1.41 | 7bacd1d6dc890c209cd76e9a22fc7baab003aab1 | <ide><path>api/server/router/container/container_routes.go
<ide> func (s *containerRouter) postContainersCreate(ctx context.Context, w http.Respo
<ide> if hostConfig.IpcMode.IsEmpty() {
<ide> hostConfig.IpcMode = container.IpcMode("shareable")
<ide> }
<del>
<add> }
<add> if hostConfig != nil && versions.LessThan(version, "1.41") {
<ide> // Older clients expect the default to be "host"
<ide> if hostConfig.CgroupnsMode.IsEmpty() {
<ide> hostConfig.CgroupnsMode = container.CgroupnsMode("host")
<ide><path>docs/api/version-history.md
<ide> keywords: "API, Docker, rcli, REST, documentation"
<ide>
<ide> [Docker Engine API v1.41](https://docs.docker.com/engine/api/v1.41/) documentation
<ide>
<add>* `POST /containers/create` on Linux now accepts the `HostConfig.CgroupnsMode` property.
<add> Set the property to `host` to create the container in the daemon's cgroup namespace, or
<add> `private` to create the container in its own private cgroup namespace. The per-daemon
<add> default is `host`, and can be changed by using the`CgroupNamespaceMode` daemon configuration
<add> parameter.
<ide>
<ide>
<ide> ## v1.40 API changes
<ide> keywords: "API, Docker, rcli, REST, documentation"
<ide> * `POST /containers/{id}/update` now accepts a `PidsLimit` field to tune a container's
<ide> PID limit. Set `0` or `-1` for unlimited. Leave `null` to not change the current value.
<ide> * `POST /build` now accepts `outputs` key for configuring build outputs when using BuildKit mode.
<del>* `POST /containers/create` on Linux now accepts the `HostConfig.CgroupnsMode` property.
<del> Set the property to `host` to create the container in the daemon's cgroup namespace, or
<del> `private` to create the container in its own private cgroup namespace. The per-daemon
<del> default is `host`, and can be changed by using the`CgroupNamespaceMode` daemon configuration
<del> parameter.
<ide>
<ide> ## V1.39 API changes
<ide> | 2 |
Javascript | Javascript | remove duplicated buffer negative allocation test | 6f6f6d4087ed2a60b6a443151dc75c76812a8d80 | <ide><path>test/parallel/test-buffer-negative-length.js
<del>'use strict';
<del>
<del>const common = require('../common');
<del>const assert = require('assert');
<del>const SlowBuffer = require('buffer').SlowBuffer;
<del>
<del>const bufferNegativeMsg = common.expectsError({
<del> code: 'ERR_INVALID_OPT_VALUE',
<del> type: RangeError,
<del> message: /^The value "[^"]*" is invalid for option "size"$/
<del>}, 5);
<del>assert.throws(() => Buffer(-1).toString('utf8'), bufferNegativeMsg);
<del>assert.throws(() => SlowBuffer(-1).toString('utf8'), bufferNegativeMsg);
<del>assert.throws(() => Buffer.alloc(-1).toString('utf8'), bufferNegativeMsg);
<del>assert.throws(() => Buffer.allocUnsafe(-1).toString('utf8'), bufferNegativeMsg);
<del>assert.throws(() => Buffer.allocUnsafeSlow(-1).toString('utf8'),
<del> bufferNegativeMsg);
<ide><path>test/parallel/test-buffer-no-negative-allocation.js
<ide>
<ide> const common = require('../common');
<ide> const assert = require('assert');
<add>const { SlowBuffer } = require('buffer');
<ide>
<ide> const msg = common.expectsError({
<ide> code: 'ERR_INVALID_OPT_VALUE',
<ide> type: RangeError,
<ide> message: /^The value "[^"]*" is invalid for option "size"$/
<del>}, 16);
<add>}, 20);
<ide>
<ide> // Test that negative Buffer length inputs throw errors.
<ide>
<ide> assert.throws(() => Buffer.allocUnsafeSlow(-Buffer.poolSize), msg);
<ide> assert.throws(() => Buffer.allocUnsafeSlow(-100), msg);
<ide> assert.throws(() => Buffer.allocUnsafeSlow(-1), msg);
<ide> assert.throws(() => Buffer.allocUnsafeSlow(NaN), msg);
<add>
<add>assert.throws(() => SlowBuffer(-Buffer.poolSize), msg);
<add>assert.throws(() => SlowBuffer(-100), msg);
<add>assert.throws(() => SlowBuffer(-1), msg);
<add>assert.throws(() => SlowBuffer(NaN), msg); | 2 |
Javascript | Javascript | explain wondrous mathematics | 3f265835d884f609b71ab39658bdb2241f94d500 | <ide><path>src/geo/area.js
<ide> function d3_geo_areaRingStart() {
<ide> // If the previous point is at the north pole, then compute lune area.
<ide> if (Math.abs(φ0 - π / 2) < ε) d3_geo_areaRing += (λ - λ1) * 2;
<ide>
<del> // TODO Explain this wonderous mathematics.
<add> // Area of spherical triangle with vertices at south pole, previous point
<add> // and current point = ER², where E is the spherical excess, and in our
<add> // case, R = 1.
<ide> else {
<ide> var dλ = λ - λ0,
<ide> cosdλ = Math.cos(dλ),
<add> // Distance from previous point to current point, well-conditioned
<add> // for all angles.
<ide> d = Math.atan2(Math.sqrt((d = cosφ * Math.sin(dλ)) * d + (d = cosφ0 * sinφ - sinφ0 * cosφ * cosdλ) * d), sinφ0 * sinφ + cosφ0 * cosφ * cosdλ),
<add> // Half the semiperimeter (a + b + c) / 2, where a, b and c are the
<add> // lengths of the triangle sides.
<ide> s = (d + π + φ0 + φ) / 4;
<add> // Compute the spherical excess E using l’Huilier’s theorem,
<add> // tan(E / 4) = √[tan(s)tan(s - a / 2)tan(s - b / 2)tan(s - c / 2)].
<ide> d3_geo_areaRing += (dλ < 0 && dλ > -π || dλ > π ? -4 : 4) * Math.atan(Math.sqrt(Math.abs(Math.tan(s) * Math.tan(s - d / 2) * Math.tan(s - π / 4 - φ0 / 2) * Math.tan(s - π / 4 - φ / 2))));
<ide> }
<ide> | 1 |
PHP | PHP | support mixed target data in data_get | 2286d156388ac57b7de8824ade3676298626aaf6 | <ide><path>src/Illuminate/Support/helpers.php
<ide> function csrf_token()
<ide> * @param string $key
<ide> * @param mixed $default
<ide> * @return mixed
<del> *
<del> * @throws \InvalidArgumentException
<ide> */
<ide> function data_get($target, $key, $default = null)
<ide> {
<del> if (is_array($target))
<del> {
<del> return array_get($target, $key, $default);
<del> }
<del> elseif (is_object($target))
<del> {
<del> return object_get($target, $key, $default);
<del> }
<del> else
<add> if (is_null($key)) return $target;
<add>
<add> foreach (explode('.', $key) as $segment)
<ide> {
<del> throw new \InvalidArgumentException("Array or object must be passed to data_get.");
<add> if (is_array($target))
<add> {
<add> if ( ! array_key_exists($segment, $target))
<add> {
<add> return value($default);
<add> }
<add>
<add> $target = $target[$segment];
<add> }
<add> elseif (is_object($target))
<add> {
<add> if ( ! isset($target->{$segment}))
<add> {
<add> return value($default);
<add> }
<add>
<add> $target = $target->{$segment};
<add> }
<add> else
<add> {
<add> return value($default);
<add> }
<ide> }
<add>
<add> return $target;
<ide> }
<ide> }
<ide>
<ide><path>tests/Support/SupportHelpersTest.php
<ide> public function testObjectGet()
<ide> $this->assertEquals('Taylor', object_get($class, 'name.first'));
<ide> }
<ide>
<add> public function testDataGet()
<add> {
<add> $object = (object) array('users' => array('name' => array('Taylor', 'Otwell')));
<add> $array = array((object) array('users' => array((object) array('name' => 'Taylor'))));
<add>
<add> $this->assertEquals('Taylor', data_get($object, 'users.name.0'));
<add> $this->assertEquals('Taylor', data_get($array, '0.users.0.name'));
<add> $this->assertNull(data_get($array, '0.users.3'));
<add> $this->assertEquals('Not found', data_get($array, '0.users.3', 'Not found'));
<add> $this->assertEquals('Not found', data_get($array, '0.users.3', function (){ return 'Not found'; }));
<add> }
<ide>
<ide> public function testArraySort()
<ide> { | 2 |
Javascript | Javascript | update gulp lint task | 8087db11f0f2b83f47c8e28f4fcf8ac3d0907f39 | <ide><path>gulpfile.js
<ide> gulp.task('sync', syncDepenedents, function() {
<ide> });
<ide>
<ide> gulp.task('lint-js', function() {
<del> return gulp.src(['public/js/lib/**/*'])
<add> return gulp.src([
<add> 'common/**/*.js',
<add> 'common/**/*.jsx',
<add> 'client/**/*.js',
<add> 'client/**/*.jsx',
<add> 'server/**/*.js',
<add> 'config/**/*.js'
<add> ])
<ide> .pipe(eslint())
<ide> .pipe(eslint.format());
<ide> }); | 1 |
Ruby | Ruby | skip image analysis on imagemagick error | 165785e8cf43456816c8152ca4295640b21d1765 | <ide><path>activestorage/lib/active_storage/analyzer/image_analyzer.rb
<ide> def read_image
<ide> rescue LoadError
<ide> logger.info "Skipping image analysis because the mini_magick gem isn't installed"
<ide> {}
<add> rescue MiniMagick::Error => error
<add> logger.error "Skipping image analysis due to an ImageMagick error: #{error.message}"
<add> {}
<ide> end
<ide>
<ide> def rotated_image?(image) | 1 |
Ruby | Ruby | remove useless parameter | cab85e9926c62094d1bada4437b6d1b6bc51e5e8 | <ide><path>actionview/lib/action_view/template.rb
<ide> def compile!(view) #:nodoc:
<ide> end
<ide>
<ide> instrument("!compile_template") do
<del> compile(view, mod)
<add> compile(mod)
<ide> end
<ide>
<ide> # Just discard the source if we have a virtual path. This
<ide> def compile!(view) #:nodoc:
<ide> # encode the source into <tt>Encoding.default_internal</tt>.
<ide> # In general, this means that templates will be UTF-8 inside of Rails,
<ide> # regardless of the original source encoding.
<del> def compile(view, mod) #:nodoc:
<add> def compile(mod) #:nodoc:
<ide> encode!
<ide> method_name = self.method_name
<ide> code = @handler.call(self) | 1 |
Python | Python | fix yosoconfig doc | 4df69506a8250d4bd298d457090b321b26b0c77f | <ide><path>src/transformers/models/yoso/configuration_yoso.py
<ide> class YosoConfig(PretrainedConfig):
<ide> The epsilon used by the layer normalization layers.
<ide> position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
<ide> Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`.
<del> use_expectation (*bool*, *optional*, defaults to *True*):
<add> use_expectation (`bool`, *optional*, defaults to `True`):
<ide> Whether or not to use YOSO Expectation. Overrides any effect of num_hash.
<ide> hash_code_len (`int`, *optional*, defaults to 9):
<ide> The length of hashes generated by the hash functions.
<ide> num_hash (`int`, *optional*, defaults to 64):
<ide> Number of hash functions used in [`YosoSelfAttention`].
<del> conv_window (`int`, *optional*, defaults to None):
<add> conv_window (`int`, *optional*):
<ide> Kernel size of depth-wise convolution.
<del> use_fast_hash (*bool*, *optional*, defaults to *False*):
<add> use_fast_hash (`bool`, *optional*, defaults to `False`):
<ide> Whether or not to use custom cuda kernels which perform fast random projection via hadamard transform.
<del> lsh_backward (*bool*, *optional*, defaults to *True*):
<add> lsh_backward (`bool`, *optional*, defaults to `True`):
<ide> Whether or not to perform backpropagation using Locality Sensitive Hashing.
<ide>
<ide> Example: | 1 |
PHP | PHP | apply fixes from styleci | 198eea4c6cf86f2073ea9366b1bf4453aa7979c2 | <ide><path>src/Illuminate/Http/Client/Factory.php
<ide> public function assertSentInOrder($callbacks)
<ide> $this->assertSentCount(count($callbacks));
<ide>
<ide> foreach ($callbacks as $index => $url) {
<del> $callback = is_callable($url) ? $url : function($request) use ($url) {
<add> $callback = is_callable($url) ? $url : function ($request) use ($url) {
<ide> return $request->url() == $url;
<ide> };
<ide>
<ide><path>tests/Http/HttpClientTest.php
<ide> public function testWrongNumberOfRequestsThrowAssertionFailed()
<ide> $this->factory->assertSentInOrder($exampleUrls);
<ide> }
<ide>
<del> public function testCanAssertAgainstOrderOfHttpRequestsWithCallables() {
<add> public function testCanAssertAgainstOrderOfHttpRequestsWithCallables()
<add> {
<ide> $this->factory->fake();
<ide>
<ide> $exampleUrls = [
<del> function($request) {
<add> function ($request) {
<ide> return $request->url() == 'http://example.com/1';
<ide> },
<del> function($request) {
<add> function ($request) {
<ide> return $request->url() == 'http://example.com/2';
<ide> },
<del> function($request) {
<add> function ($request) {
<ide> return $request->url() == 'http://example.com/3';
<ide> },
<ide> ];
<del>
<add>
<ide> $this->factory->get('http://example.com/1');
<ide> $this->factory->get('http://example.com/2');
<ide> $this->factory->get('http://example.com/3');
<ide>
<ide> $this->factory->assertSentInOrder($exampleUrls);
<ide> }
<ide>
<del> public function testCanAssertAgainstOrderOfHttpRequestsWithCallablesAndHeaders() {
<add> public function testCanAssertAgainstOrderOfHttpRequestsWithCallablesAndHeaders()
<add> {
<ide> $this->factory->fake();
<ide>
<ide> $executionOrder = [
<ide> function (Request $request) {
<ide> $request->hasHeader('X-Test-Header', 'bar') &&
<ide> $request->hasHeader('X-Test-ArrayHeader', ['bar', 'baz']) &&
<ide> $request['name'] === 'Taylor';
<del> }
<add> },
<ide> ];
<ide>
<ide> $this->factory->withHeaders([
<ide> function (Request $request) {
<ide> $this->factory->assertSentInOrder($executionOrder);
<ide> }
<ide>
<del> public function testCanAssertAgainstOrderOfHttpRequestsWithCallablesAndHeadersFailsCorrectly() {
<add> public function testCanAssertAgainstOrderOfHttpRequestsWithCallablesAndHeadersFailsCorrectly()
<add> {
<ide> $this->factory->fake();
<ide>
<ide> $executionOrder = [ | 2 |
Text | Text | add a note about how to turn pagination off | 23460bfa41f9dedbdd448c921618a6ed244a0f3b | <ide><path>docs/api-guide/pagination.md
<ide> The built-in styles currently all use links included as part of the content of t
<ide>
<ide> Pagination is only performed automatically if you're using the generic views or viewsets. If you're using a regular `APIView`, you'll need to call into the pagination API yourself to ensure you return a paginated response. See the source code for the `mixins.ListModelMixin` and `generics.GenericAPIView` classes for an example.
<ide>
<add>Pagination can be turned off by setting the pagination class to `None`.
<add>
<ide> ## Setting the pagination style
<ide>
<ide> The default pagination style may be set globally, using the `DEFAULT_PAGINATION_CLASS` settings key. For example, to use the built-in limit/offset pagination, you would do: | 1 |
PHP | PHP | resolve the authenticated user out of the ioc | 89de045a17eec307837c351eaa58922cac1b3db8 | <ide><path>src/Illuminate/Auth/AuthServiceProvider.php
<ide> class AuthServiceProvider extends ServiceProvider {
<ide> */
<ide> public function register()
<ide> {
<add> $this->registerUserResolver();
<add>
<ide> $this->app->bindShared('auth', function($app)
<ide> {
<ide> // Once the authentication service has actually been requested by the developer
<ide> public function register()
<ide> });
<ide> }
<ide>
<add> /**
<add> * Register a resolver for the authenticated user.
<add> *
<add> * @return void
<add> */
<add> protected function registerUserResolver()
<add> {
<add> $this->app->bind('Illuminate\Contracts\Auth\User', function($app)
<add> {
<add> return $app['auth']->user();
<add> });
<add> }
<add>
<ide> /**
<ide> * Get the services provided by the provider.
<ide> *
<ide> * @return array
<ide> */
<ide> public function provides()
<ide> {
<del> return ['auth', 'auth.driver'];
<add> return ['auth', 'auth.driver', 'Illuminate\Contracts\Auth\User'];
<ide> }
<ide>
<ide> } | 1 |
Javascript | Javascript | move stream test to parallel | 110c25d5ac9cb7af2c4b589de853ce42f5e13b7a | <add><path>test/parallel/test-stream-writable-clear-buffer.js
<del><path>test/sequential/test-stream-writable-clear-buffer.js
<ide> class StreamWritable extends Stream.Writable {
<ide> // Refs: https://github.com/nodejs/node/issues/6758
<ide> // We need a timer like on the original issue thread.
<ide> // Otherwise the code will never reach our test case.
<del> // This means this should go in the sequential folder.
<ide> _write(chunk, encoding, cb) {
<ide> setImmediate(cb);
<ide> } | 1 |
Python | Python | handle none default args in cython methods | dba26186efa4eb437e0f4f50d8dba395027164ec | <ide><path>spacy/schemas.py
<ide>
<ide> from .attrs import NAMES
<ide> from .lookups import Lookups
<add>from .util import is_cython_func
<ide>
<ide> if TYPE_CHECKING:
<ide> # This lets us add type hints for mypy etc. without causing circular imports
<ide> def get_arg_model(
<ide> continue
<ide> # If no annotation is specified assume it's anything
<ide> annotation = param.annotation if param.annotation != param.empty else Any
<del> # If no default value is specified assume that it's required
<del> default = param.default if param.default != param.empty else ...
<add> # If no default value is specified assume that it's required. Cython
<add> # functions/methods will have param.empty for default value None so we
<add> # need to treat them differently
<add> default_empty = None if is_cython_func(func) else ...
<add> default = param.default if param.default != param.empty else default_empty
<ide> sig_args[param.name] = (annotation, default)
<ide> is_strict = strict and not has_variable
<ide> sig_args["__config__"] = ArgSchemaConfig if is_strict else ArgSchemaConfigExtra
<ide><path>spacy/util.py
<ide> def minibatch(items, size):
<ide> if len(batch) == 0:
<ide> break
<ide> yield list(batch)
<add>
<add>
<add>def is_cython_func(func: Callable) -> bool:
<add> """Slightly hacky check for whether a callable is implemented in Cython.
<add> Can be used to implement slightly different behaviors, especially around
<add> inspecting and parameter annotations.
<add>
<add> func (Callable): The callable to check.
<add> RETURNS (bool): Whether the callable is Cython (probably).
<add> """
<add> attr = "__reduce_cython__"
<add> if hasattr(func, attr): # function or class instance
<add> return True
<add> # https://stackoverflow.com/a/55767059
<add> if hasattr(func, "__qualname__") and hasattr(func, "__module__"): # method
<add> cls_func = vars(sys.modules[func.__module__])[func.__qualname__.split(".")[0]]
<add> return hasattr(cls_func, attr)
<add> return False | 2 |
Ruby | Ruby | remove odd spaces [ci skip] | 50d1e00625091bf7f4c84afbdabb9006402a94ea | <ide><path>activesupport/lib/active_support/core_ext/hash/slice.rb
<ide> def slice(*keys)
<ide> # Returns a hash containing the removed key/value pairs.
<ide> #
<ide> # hash = { a: 1, b: 2, c: 3, d: 4 }
<del> # hash.slice!(:a, :b) # => {:c=>3, :d=>4 }
<del> # hash # => {:a=>1, :b=>2 }
<add> # hash.slice!(:a, :b) # => {:c=>3, :d=>4}
<add> # hash # => {:a=>1, :b=>2}
<ide> def slice!(*keys)
<ide> omit = slice(*self.keys - keys)
<ide> hash = slice(*keys) | 1 |
Python | Python | improve description, add more notes | 5e65b7c77461ac749a79377448ec70204e648392 | <ide><path>numpy/core/shape_base.py
<ide> def walk(self, x, index=()):
<ide>
<ide> def block(arrays):
<ide> """
<del> Assemble an array from nested lists of blocks.
<add> Assemble an nd-array from nested lists of blocks.
<ide>
<del> You can create a 2-D blocked array with the same notation you use for
<del> `np.array`.
<add> Blocks in the innermost lists are `concatenate`d along the last
<add> dimension (-1), then these are `concatenate`d along the second-last
<add> dimension (-2), and so on until the outermost list is reached
<add>
<add> Blocks can be of any dimension, but will not be broadcasted using the normal
<add> rules. Instead, leading axes of size 1 are inserted, to make ``block.ndim``
<add> the same for all blocks. This is primarily useful for working with scalars,
<add> and means that code like ``np.block([v, 1])`` is valid, where
<add> ``v.ndim == 1``.
<add>
<add> When the nested list is two levels deep, this allows block matrices to be
<add> constructed from their components.
<ide>
<ide> .. versionadded:: 1.13.0
<ide>
<ide> Parameters
<ide> ----------
<ide> arrays : nested list of ndarrays or scalars
<del> Elements of the innermost lists are `concatenate`d along the last
<del> dimension, then theses are concatenated along the second-last
<del> dimensions, etc.
<del>
<ide> If passed a single ndarray or scalar (a nested list of depth 0), this
<del> is returned unmodified.
<add> is returned unmodified (and not copied).
<ide>
<del> Elements shapes must match along the appropiate axes (without
<del> broadcasting), but leading 1s will be appended as necessary to make the
<del> dimensions match.
<add> Elements shapes must match along the appropriate axes (without
<add> broadcasting), but leading 1s will be prepended to the shape as
<add> necessary to make the dimensions match.
<ide>
<ide> Returns
<ide> -------
<del> blocked : ndarray
<add> block_array : ndarray
<ide> The array assembled from the given blocks.
<del> The dimensionality of the output is determined by the dimensionality of
<del> all the inputs, and the degree to which the input list is nested -
<del> whichever is greatest.
<add>
<add> The dimensionality of the output is equal to the greatest of:
<add> * the dimensionality of all the inputs
<add> * the depth to which the input list is nested
<ide>
<ide> Raises
<ide> ------
<ide> def block(arrays):
<ide>
<ide> Notes
<ide> -----
<del> ``block`` is similar to Matlab's "square bracket stacking": ``[A B; C D]``
<add>
<add> When called with only scalars, ``np.block`` is equivalent to an ndarray
<add> call. So ``np.block([[1, 2], [3, 4]])`` is equivalent to
<add> ``np.array([[1, 2], [3, 4]])``.
<add>
<add> This function does not enforce that the blocks lie on a fixed grid.
<add> ``np.block([[a, b], [c, d]])`` is not restricted to arrays of the form::
<add>
<add> AAAbb
<add> AAAbb
<add> cccDD
<add>
<add> But is also allowed to produce, for some ``a, b, c, d``::
<add>
<add> AAAbb
<add> AAAbb
<add> cDDDD
<add>
<add> Since concatenation happens along the last axis first, `block` is _not_
<add> capable of producing the following directly::
<add>
<add> AAAbb
<add> cccbb
<add> cccDD
<add>
<add> Matlab's "square bracket stacking", ``[A, B, ...; p, q, ...]``, is
<add> equivalent to ``np.block([[A, B, ...], [p, q, ...]])``.
<ide>
<ide> Examples
<ide> -------- | 1 |
Python | Python | fix tokenizers serialization | 7044ed6b059c7305b0a1ab8576c775829afd9226 | <ide><path>pytorch_transformers/tests/tokenization_dilbert_test.py
<ide> class DistilBertTokenizationTest(BertTokenizationTest):
<ide>
<ide> tokenizer_class = DistilBertTokenizer
<ide>
<del> def get_tokenizer(self):
<del> return DistilBertTokenizer.from_pretrained(self.tmpdirname)
<add> def get_tokenizer(self, **kwargs):
<add> return DistilBertTokenizer.from_pretrained(self.tmpdirname, **kwargs)
<ide>
<ide> def test_sequence_builders(self):
<ide> tokenizer = DistilBertTokenizer.from_pretrained("distilbert-base-uncased")
<ide><path>pytorch_transformers/tests/tokenization_tests_commons.py
<ide> def test_save_and_load_tokenizer(self):
<ide>
<ide> with TemporaryDirectory() as tmpdirname:
<ide> tokenizer.save_pretrained(tmpdirname)
<del> tokenizer = tokenizer.from_pretrained(tmpdirname)
<add> tokenizer = self.tokenizer_class.from_pretrained(tmpdirname)
<ide>
<ide> after_tokens = tokenizer.encode(u"He is very happy, UNwant\u00E9d,running")
<ide> self.assertListEqual(before_tokens, after_tokens)
<ide>
<ide> self.assertEqual(tokenizer.max_len, 42)
<del> tokenizer = tokenizer.from_pretrained(tmpdirname, max_len=43)
<add> tokenizer = self.tokenizer_class.from_pretrained(tmpdirname, max_len=43)
<ide> self.assertEqual(tokenizer.max_len, 43)
<ide>
<ide> def test_pickle_tokenizer(self):
<ide><path>pytorch_transformers/tokenization_transfo_xl.py
<ide> def __init__(self, special=None, min_freq=0, max_size=None, lower_case=False,
<ide> # in a library like ours, at all.
<ide> vocab_dict = torch.load(pretrained_vocab_file)
<ide> for key, value in vocab_dict.items():
<del> self.__dict__[key] = value
<add> if key not in self.__dict__:
<add> self.__dict__[key] = value
<ide>
<ide> if vocab_file is not None:
<ide> self.build_vocab()
<ide><path>pytorch_transformers/tokenization_xlnet.py
<ide> class XLNetTokenizer(PreTrainedTokenizer):
<ide> pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
<ide> max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
<ide>
<del> def __init__(self, vocab_file, max_len=None,
<add> def __init__(self, vocab_file,
<ide> do_lower_case=False, remove_space=True, keep_accents=False,
<ide> bos_token="<s>", eos_token="</s>", unk_token="<unk>", sep_token="<sep>",
<ide> pad_token="<pad>", cls_token="<cls>", mask_token="<mask>", | 4 |
Javascript | Javascript | use console directly instead of warning() modules | 0cf22a56a18790ef34c71bef14f64695c0498619 | <ide><path>.eslintrc.js
<ide> module.exports = {
<ide> 'comma-dangle': [ERROR, 'always-multiline'],
<ide> 'consistent-return': OFF,
<ide> 'dot-location': [ERROR, 'property'],
<del> 'dot-notation': ERROR,
<add> // We use console['error']() as a signal to not transform it:
<add> 'dot-notation': [ERROR, {allowPattern: '^(error|warn)$'}],
<ide> 'eol-last': ERROR,
<ide> eqeqeq: [ERROR, 'allow-null'],
<ide> indent: OFF,
<ide> module.exports = {
<ide> 'jest/valid-expect-in-promise': ERROR,
<ide> },
<ide> },
<add> {
<add> files: [
<add> '**/__tests__/**/*.js',
<add> 'scripts/**/*.js',
<add> 'packages/*/npm/**/*.js',
<add> 'packages/react-devtools*/**/*.js'
<add> ],
<add> rules: {
<add> 'react-internal/no-production-logging': OFF,
<add> 'react-internal/warning-args': OFF,
<add> },
<add> },
<ide> {
<ide> files: ['packages/react-native-renderer/**/*.js'],
<ide> globals: {
<ide><path>packages/create-subscription/src/createSubscription.js
<ide>
<ide> import React from 'react';
<ide> import invariant from 'shared/invariant';
<del>import warning from 'shared/warning';
<ide>
<ide> type Unsubscribe = () => void;
<ide>
<ide> export function createSubscription<Property, Value>(
<ide>
<ide> if (__DEV__) {
<ide> if (typeof getCurrentValue !== 'function') {
<del> warning('Subscription must specify a getCurrentValue function');
<add> console.error('Subscription must specify a getCurrentValue function');
<ide> }
<ide> if (typeof subscribe !== 'function') {
<del> warning('Subscription must specify a subscribe function');
<add> console.error('Subscription must specify a subscribe function');
<ide> }
<ide> }
<ide>
<ide><path>packages/legacy-events/EventPluginUtils.js
<ide>
<ide> import {invokeGuardedCallbackAndCatchFirstError} from 'shared/ReactErrorUtils';
<ide> import invariant from 'shared/invariant';
<del>import warning from 'shared/warning';
<ide>
<ide> export let getFiberCurrentPropsFromNode = null;
<ide> export let getInstanceFromNode = null;
<ide> export function setComponentTree(
<ide> getNodeFromInstance = getNodeFromInstanceImpl;
<ide> if (__DEV__) {
<ide> if (!getNodeFromInstance || !getInstanceFromNode) {
<del> warning(
<add> console.error(
<ide> 'EventPluginUtils.setComponentTree(...): Injected ' +
<ide> 'module is missing getNodeFromInstance or getInstanceFromNode.',
<ide> );
<ide> if (__DEV__) {
<ide> : 0;
<ide>
<ide> if (instancesIsArr !== listenersIsArr || instancesLen !== listenersLen) {
<del> warning('EventPluginUtils: Invalid `event`.');
<add> console.error('EventPluginUtils: Invalid `event`.');
<ide> }
<ide> };
<ide> }
<ide><path>packages/legacy-events/EventPropagators.js
<ide> import {
<ide> traverseTwoPhase,
<ide> traverseEnterLeave,
<ide> } from 'shared/ReactTreeTraversal';
<del>import warning from 'shared/warning';
<ide>
<ide> import {getListener} from './EventPluginHub';
<ide> import accumulateInto from './accumulateInto';
<ide> function listenerAtPhase(inst, event, propagationPhase: PropagationPhases) {
<ide> function accumulateDirectionalDispatches(inst, phase, event) {
<ide> if (__DEV__) {
<ide> if (!inst) {
<del> warning('Dispatching inst must not be null');
<add> console.error('Dispatching inst must not be null');
<ide> }
<ide> }
<ide> const listener = listenerAtPhase(inst, event, phase);
<ide><path>packages/legacy-events/ResponderEventPlugin.js
<ide> const ResponderEventPlugin = {
<ide> if (trackedTouchCount >= 0) {
<ide> trackedTouchCount -= 1;
<ide> } else {
<del> console.warn(
<del> 'Ended a touch event which was not counted in `trackedTouchCount`.',
<del> );
<add> if (__DEV__) {
<add> console.warn(
<add> 'Ended a touch event which was not counted in `trackedTouchCount`.',
<add> );
<add> }
<ide> return null;
<ide> }
<ide> }
<ide><path>packages/legacy-events/ResponderTouchHistoryStore.js
<ide> */
<ide>
<ide> import invariant from 'shared/invariant';
<del>import warning from 'shared/warning';
<ide>
<ide> import {isStartish, isMoveish, isEndish} from './ResponderTopLevelEventTypes';
<ide>
<ide> function getTouchIdentifier({identifier}: Touch): number {
<ide> invariant(identifier != null, 'Touch object is missing identifier.');
<ide> if (__DEV__) {
<ide> if (identifier > MAX_TOUCH_BANK) {
<del> warning(
<add> console.error(
<ide> 'Touch identifier %s is greater than maximum supported %s which causes ' +
<ide> 'performance issues backfilling array locations for all of the indices.',
<ide> identifier,
<ide> function recordTouchMove(touch: Touch): void {
<ide> touchRecord.currentTimeStamp = timestampForTouch(touch);
<ide> touchHistory.mostRecentTimeStamp = timestampForTouch(touch);
<ide> } else {
<del> console.warn(
<del> 'Cannot record touch move without a touch start.\n' + 'Touch Move: %s\n',
<del> 'Touch Bank: %s',
<del> printTouch(touch),
<del> printTouchBank(),
<del> );
<add> if (__DEV__) {
<add> console.warn(
<add> 'Cannot record touch move without a touch start.\n' +
<add> 'Touch Move: %s\n' +
<add> 'Touch Bank: %s',
<add> printTouch(touch),
<add> printTouchBank(),
<add> );
<add> }
<ide> }
<ide> }
<ide>
<ide> function recordTouchEnd(touch: Touch): void {
<ide> touchRecord.currentTimeStamp = timestampForTouch(touch);
<ide> touchHistory.mostRecentTimeStamp = timestampForTouch(touch);
<ide> } else {
<del> console.warn(
<del> 'Cannot record touch end without a touch start.\n' + 'Touch End: %s\n',
<del> 'Touch Bank: %s',
<del> printTouch(touch),
<del> printTouchBank(),
<del> );
<add> if (__DEV__) {
<add> console.warn(
<add> 'Cannot record touch end without a touch start.\n' +
<add> 'Touch End: %s\n' +
<add> 'Touch Bank: %s',
<add> printTouch(touch),
<add> printTouchBank(),
<add> );
<add> }
<ide> }
<ide> }
<ide>
<ide> const ResponderTouchHistoryStore = {
<ide> if (__DEV__) {
<ide> const activeRecord = touchBank[touchHistory.indexOfSingleActiveTouch];
<ide> if (activeRecord == null || !activeRecord.touchActive) {
<del> warning('Cannot find single active touch.');
<add> console.error('Cannot find single active touch.');
<ide> }
<ide> }
<ide> }
<ide><path>packages/legacy-events/SyntheticEvent.js
<ide> /* eslint valid-typeof: 0 */
<ide>
<ide> import invariant from 'shared/invariant';
<del>import warning from 'shared/warning';
<ide>
<ide> const EVENT_POOL_SIZE = 10;
<ide>
<ide> function getPooledWarningPropertyDefinition(propName, getVal) {
<ide>
<ide> function warn(action, result) {
<ide> if (__DEV__) {
<del> warning(
<add> console.error(
<ide> "This synthetic event is reused for performance reasons. If you're seeing this, " +
<ide> "you're %s `%s` on a released/nullified synthetic event. %s. " +
<ide> 'If you must keep the original synthetic event around, use event.persist(). ' +
<ide><path>packages/react-cache/src/ReactCache.js
<ide> */
<ide>
<ide> import React from 'react';
<del>import warning from 'shared/warning';
<ide>
<ide> import {createLRU} from './LRU';
<ide>
<ide> function identityHashFn(input) {
<ide> input !== undefined &&
<ide> input !== null
<ide> ) {
<del> warning(
<add> console.error(
<ide> 'Invalid key type. Expected a string, number, symbol, or boolean, ' +
<ide> 'but instead received: %s' +
<ide> '\n\nTo use non-primitive values as keys, you must pass a hash ' +
<ide><path>packages/react-dom/src/client/ReactDOM.js
<ide> import {
<ide> } from 'legacy-events/EventPropagators';
<ide> import ReactVersion from 'shared/ReactVersion';
<ide> import invariant from 'shared/invariant';
<del>import lowPriorityWarning from 'shared/lowPriorityWarning';
<del>import warning from 'shared/warning';
<ide> import {exposeConcurrentModeAPIs} from 'shared/ReactFeatureFlags';
<ide>
<ide> import {
<ide> if (__DEV__) {
<ide> typeof Set.prototype.clear !== 'function' ||
<ide> typeof Set.prototype.forEach !== 'function'
<ide> ) {
<del> warning(
<add> console.error(
<ide> 'React depends on Map and Set built-in types. Make sure that you load a ' +
<ide> 'polyfill in older browsers. https://fb.me/react-polyfills',
<ide> );
<ide> const ReactDOM: Object = {
<ide> if (__DEV__) {
<ide> if (!didWarnAboutUnstableCreatePortal) {
<ide> didWarnAboutUnstableCreatePortal = true;
<del> lowPriorityWarning(
<add> console.warn(
<ide> 'The ReactDOM.unstable_createPortal() alias has been deprecated, ' +
<ide> 'and will be removed in React 17+. Update your code to use ' +
<ide> 'ReactDOM.createPortal() instead. It has the exact same API, ' +
<ide> if (__DEV__) {
<ide> const protocol = window.location.protocol;
<ide> // Don't warn in exotic cases like chrome-extension://.
<ide> if (/^(https?|file):$/.test(protocol)) {
<add> // eslint-disable-next-line react-internal/no-production-logging
<ide> console.info(
<ide> '%cDownload the React DevTools ' +
<ide> 'for a better development experience: ' +
<ide><path>packages/react-dom/src/client/ReactDOMComponent.js
<ide> import {getCurrentFiberOwnerNameInDevOrNull} from 'react-reconciler/src/ReactCurrentFiber';
<ide> import {registrationNameModules} from 'legacy-events/EventPluginRegistry';
<ide> import {canUseDOM} from 'shared/ExecutionEnvironment';
<del>import warning from 'shared/warning';
<ide> import endsWith from 'shared/endsWith';
<ide> import {setListenToResponderEventTypes} from '../events/DOMEventResponderSystem';
<ide>
<ide> if (__DEV__) {
<ide> return;
<ide> }
<ide> didWarnInvalidHydration = true;
<del> warning(
<add> console.error(
<ide> 'Text content did not match. Server: "%s" Client: "%s"',
<ide> normalizedServerText,
<ide> normalizedClientText,
<ide> if (__DEV__) {
<ide> return;
<ide> }
<ide> didWarnInvalidHydration = true;
<del> warning(
<add> console.error(
<ide> 'Prop `%s` did not match. Server: %s Client: %s',
<ide> propName,
<ide> JSON.stringify(normalizedServerValue),
<ide> if (__DEV__) {
<ide> attributeNames.forEach(function(name) {
<ide> names.push(name);
<ide> });
<del> warning('Extra attributes from the server: %s', names);
<add> console.error('Extra attributes from the server: %s', names);
<ide> };
<ide>
<ide> warnForInvalidEventListener = function(registrationName, listener) {
<ide> if (listener === false) {
<del> warning(
<add> console.error(
<ide> 'Expected `%s` listener to be a function, instead got `false`.\n\n' +
<ide> 'If you used to conditionally omit it with %s={condition && value}, ' +
<ide> 'pass %s={condition ? value : undefined} instead.',
<ide> if (__DEV__) {
<ide> registrationName,
<ide> );
<ide> } else {
<del> warning(
<add> console.error(
<ide> 'Expected `%s` listener to be a function, instead got a value of `%s` type.',
<ide> registrationName,
<ide> typeof listener,
<ide> export function createElement(
<ide> // Should this check be gated by parent namespace? Not sure we want to
<ide> // allow <SVG> or <mATH>.
<ide> if (!isCustomComponentTag && type !== type.toLowerCase()) {
<del> warning(
<add> console.error(
<ide> '<%s /> is using incorrect casing. ' +
<ide> 'Use PascalCase for React components, ' +
<ide> 'or lowercase for HTML elements.',
<ide> export function createElement(
<ide> const div = ownerDocument.createElement('div');
<ide> if (__DEV__) {
<ide> if (enableTrustedTypesIntegration && !didWarnScriptTags) {
<del> warning(
<add> console.error(
<ide> 'Encountered a script tag while rendering React component. ' +
<ide> 'Scripts inside React components are never executed when rendering ' +
<ide> 'on the client. Consider using template tag instead ' +
<ide> export function createElement(
<ide> !Object.prototype.hasOwnProperty.call(warnedUnknownTags, type)
<ide> ) {
<ide> warnedUnknownTags[type] = true;
<del> warning(
<add> console.error(
<ide> 'The tag <%s> is unrecognized in this browser. ' +
<ide> 'If you meant to render a React component, start its name with ' +
<ide> 'an uppercase letter.',
<ide> export function setInitialProperties(
<ide> !didWarnShadyDOM &&
<ide> (domElement: any).shadyRoot
<ide> ) {
<del> warning(
<add> console.error(
<ide> '%s is using shady DOM. Using shady DOM with React can ' +
<ide> 'cause things to break subtly.',
<ide> getCurrentFiberOwnerNameInDevOrNull() || 'A component',
<ide> export function diffHydratedProperties(
<ide> !didWarnShadyDOM &&
<ide> (domElement: any).shadyRoot
<ide> ) {
<del> warning(
<add> console.error(
<ide> '%s is using shady DOM. Using shady DOM with React can ' +
<ide> 'cause things to break subtly.',
<ide> getCurrentFiberOwnerNameInDevOrNull() || 'A component',
<ide> export function warnForDeletedHydratableElement(
<ide> return;
<ide> }
<ide> didWarnInvalidHydration = true;
<del> warning(
<add> console.error(
<ide> 'Did not expect server HTML to contain a <%s> in <%s>.',
<ide> child.nodeName.toLowerCase(),
<ide> parentNode.nodeName.toLowerCase(),
<ide> export function warnForDeletedHydratableText(
<ide> return;
<ide> }
<ide> didWarnInvalidHydration = true;
<del> warning(
<add> console.error(
<ide> 'Did not expect server HTML to contain the text node "%s" in <%s>.',
<ide> child.nodeValue,
<ide> parentNode.nodeName.toLowerCase(),
<ide> export function warnForInsertedHydratedElement(
<ide> return;
<ide> }
<ide> didWarnInvalidHydration = true;
<del> warning(
<add> console.error(
<ide> 'Expected server HTML to contain a matching <%s> in <%s>.',
<ide> tag,
<ide> parentNode.nodeName.toLowerCase(),
<ide> export function warnForInsertedHydratedText(
<ide> return;
<ide> }
<ide> didWarnInvalidHydration = true;
<del> warning(
<add> console.error(
<ide> 'Expected server HTML to contain a matching text node for "%s" in <%s>.',
<ide> text,
<ide> parentNode.nodeName.toLowerCase(),
<ide><path>packages/react-dom/src/client/ReactDOMInput.js
<ide> // TODO: direct imports like some-package/src/* are bad. Fix me.
<ide> import {getCurrentFiberOwnerNameInDevOrNull} from 'react-reconciler/src/ReactCurrentFiber';
<ide> import invariant from 'shared/invariant';
<del>import warning from 'shared/warning';
<ide>
<ide> import {setValueForProperty} from './DOMPropertyOperations';
<ide> import {getFiberCurrentPropsFromNode} from './ReactDOMComponentTree';
<ide> export function initWrapperState(element: Element, props: Object) {
<ide> props.defaultChecked !== undefined &&
<ide> !didWarnCheckedDefaultChecked
<ide> ) {
<del> warning(
<add> console.error(
<ide> '%s contains an input of type %s with both checked and defaultChecked props. ' +
<ide> 'Input elements must be either controlled or uncontrolled ' +
<ide> '(specify either the checked prop, or the defaultChecked prop, but not ' +
<ide> export function initWrapperState(element: Element, props: Object) {
<ide> props.defaultValue !== undefined &&
<ide> !didWarnValueDefaultValue
<ide> ) {
<del> warning(
<add> console.error(
<ide> '%s contains an input of type %s with both value and defaultValue props. ' +
<ide> 'Input elements must be either controlled or uncontrolled ' +
<ide> '(specify either the value prop, or the defaultValue prop, but not ' +
<ide> export function updateWrapper(element: Element, props: Object) {
<ide> controlled &&
<ide> !didWarnUncontrolledToControlled
<ide> ) {
<del> warning(
<add> console.error(
<ide> 'A component is changing an uncontrolled input of type %s to be controlled. ' +
<ide> 'Input elements should not switch from uncontrolled to controlled (or vice versa). ' +
<ide> 'Decide between using a controlled or uncontrolled input ' +
<ide> export function updateWrapper(element: Element, props: Object) {
<ide> !controlled &&
<ide> !didWarnControlledToUncontrolled
<ide> ) {
<del> warning(
<add> console.error(
<ide> 'A component is changing a controlled input of type %s to be uncontrolled. ' +
<ide> 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
<ide> 'Decide between using a controlled or uncontrolled input ' +
<ide><path>packages/react-dom/src/client/ReactDOMLegacy.js
<ide> import {
<ide> } from 'react-reconciler/inline.dom';
<ide> import getComponentName from 'shared/getComponentName';
<ide> import invariant from 'shared/invariant';
<del>import lowPriorityWarning from 'shared/lowPriorityWarning';
<del>import warning from 'shared/warning';
<ide> import ReactSharedInternals from 'shared/ReactSharedInternals';
<ide> import {has as hasInstance} from 'shared/ReactInstanceMap';
<ide>
<ide> if (__DEV__) {
<ide> );
<ide> if (hostInstance) {
<ide> if (hostInstance.parentNode !== container) {
<del> warning(
<add> console.error(
<ide> 'render(...): It looks like the React-rendered content of this ' +
<ide> 'container was removed without using React. This is not ' +
<ide> 'supported and will cause errors. Instead, call ' +
<ide> if (__DEV__) {
<ide> const hasNonRootReactChild = !!(rootEl && getInstanceFromNode(rootEl));
<ide>
<ide> if (hasNonRootReactChild && !isRootRenderedBySomeReact) {
<del> warning(
<add> console.error(
<ide> 'render(...): Replacing React-rendered children with a new root ' +
<ide> 'component. If you intended to update the children of this node, ' +
<ide> 'you should instead have the existing children update their state ' +
<ide> if (__DEV__) {
<ide> ((container: any): Element).tagName &&
<ide> ((container: any): Element).tagName.toUpperCase() === 'BODY'
<ide> ) {
<del> warning(
<add> console.error(
<ide> 'render(): Rendering components directly into document.body is ' +
<ide> 'discouraged, since its children are often manipulated by third-party ' +
<ide> 'scripts and browser extensions. This may lead to subtle ' +
<ide> function legacyCreateRootFromDOMContainer(
<ide> (rootSibling: any).hasAttribute(ROOT_ATTRIBUTE_NAME)
<ide> ) {
<ide> warned = true;
<del> warning(
<add> console.error(
<ide> 'render(): Target node has markup rendered by React, but there ' +
<ide> 'are unrelated nodes as well. This is most commonly caused by ' +
<ide> 'white-space inserted around server-rendered markup.',
<ide> function legacyCreateRootFromDOMContainer(
<ide> if (__DEV__) {
<ide> if (shouldHydrate && !forceHydrate && !warnedAboutHydrateAPI) {
<ide> warnedAboutHydrateAPI = true;
<del> lowPriorityWarning(
<add> console.warn(
<ide> 'render(): Calling ReactDOM.render() to hydrate server-rendered markup ' +
<ide> 'will stop working in React v17. Replace the ReactDOM.render() call ' +
<ide> 'with ReactDOM.hydrate() if you want React to attach to the server HTML.',
<ide> export function findDOMNode(
<ide> if (owner !== null && owner.stateNode !== null) {
<ide> const warnedAboutRefsInRender = owner.stateNode._warnedAboutRefsInRender;
<ide> if (!warnedAboutRefsInRender) {
<del> warning(
<add> console.error(
<ide> '%s is accessing findDOMNode inside its render(). ' +
<ide> 'render() should be a pure function of props and state. It should ' +
<ide> 'never access something that requires stale data from the previous ' +
<ide> export function hydrate(
<ide> isContainerMarkedAsRoot(container) &&
<ide> container._reactRootContainer === undefined;
<ide> if (isModernRoot) {
<del> warning(
<add> console.error(
<ide> 'You are calling ReactDOM.hydrate() on a container that was previously ' +
<ide> 'passed to ReactDOM.createRoot(). This is not supported. ' +
<ide> 'Did you mean to call createRoot(container, {hydrate: true}).render(element)?',
<ide> export function render(
<ide> isContainerMarkedAsRoot(container) &&
<ide> container._reactRootContainer === undefined;
<ide> if (isModernRoot) {
<del> warning(
<add> console.error(
<ide> 'You are calling ReactDOM.render() on a container that was previously ' +
<ide> 'passed to ReactDOM.createRoot(). This is not supported. ' +
<ide> 'Did you mean to call root.render(element)?',
<ide> export function unmountComponentAtNode(container: DOMContainer) {
<ide> isContainerMarkedAsRoot(container) &&
<ide> container._reactRootContainer === undefined;
<ide> if (isModernRoot) {
<del> warning(
<add> console.error(
<ide> 'You are calling ReactDOM.unmountComponentAtNode() on a container that was previously ' +
<ide> 'passed to ReactDOM.createRoot(). This is not supported. Did you mean to call root.unmount()?',
<ide> );
<ide> export function unmountComponentAtNode(container: DOMContainer) {
<ide> const rootEl = getReactRootElementInContainer(container);
<ide> const renderedByDifferentReact = rootEl && !getInstanceFromNode(rootEl);
<ide> if (renderedByDifferentReact) {
<del> warning(
<add> console.error(
<ide> "unmountComponentAtNode(): The node you're attempting to unmount " +
<ide> 'was rendered by another copy of React.',
<ide> );
<ide> export function unmountComponentAtNode(container: DOMContainer) {
<ide> !!container.parentNode._reactRootContainer;
<ide>
<ide> if (hasNonRootReactChild) {
<del> warning(
<add> console.error(
<ide> "unmountComponentAtNode(): The node you're attempting to unmount " +
<ide> 'was rendered by React and is not a top-level container. %s',
<ide> isContainerReactRoot
<ide><path>packages/react-dom/src/client/ReactDOMOption.js
<ide> */
<ide>
<ide> import React from 'react';
<del>import warning from 'shared/warning';
<ide> import {getToStringValue, toString} from './ToStringValue';
<ide>
<ide> let didWarnSelectedSetOnOption = false;
<ide> export function validateProps(element: Element, props: Object) {
<ide> }
<ide> if (!didWarnInvalidChild) {
<ide> didWarnInvalidChild = true;
<del> warning(
<add> console.error(
<ide> 'Only strings and numbers are supported as <option> children.',
<ide> );
<ide> }
<ide> export function validateProps(element: Element, props: Object) {
<ide>
<ide> // TODO: Remove support for `selected` in <option>.
<ide> if (props.selected != null && !didWarnSelectedSetOnOption) {
<del> warning(
<add> console.error(
<ide> 'Use the `defaultValue` or `value` props on <select> instead of ' +
<ide> 'setting `selected` on <option>.',
<ide> );
<ide><path>packages/react-dom/src/client/ReactDOMRoot.js
<ide> import {
<ide>
<ide> import {createContainer, updateContainer} from 'react-reconciler/inline.dom';
<ide> import invariant from 'shared/invariant';
<del>import warning from 'shared/warning';
<ide> import {BlockingRoot, ConcurrentRoot, LegacyRoot} from 'shared/ReactRootTags';
<ide>
<ide> function ReactDOMRoot(container: DOMContainer, options: void | RootOptions) {
<ide> export function warnOnInvalidCallback(
<ide> ): void {
<ide> if (__DEV__) {
<ide> if (callback !== null && typeof callback !== 'function') {
<del> warning(
<add> console.error(
<ide> '%s(...): Expected the last optional `callback` argument to be a ' +
<ide> 'function. Instead received: %s.',
<ide> callerName,
<ide> function warnIfReactDOMContainerInDEV(container) {
<ide> if (__DEV__) {
<ide> if (isContainerMarkedAsRoot(container)) {
<ide> if (container._reactRootContainer) {
<del> warning(
<add> console.error(
<ide> 'You are calling ReactDOM.createRoot() on a container that was previously ' +
<ide> 'passed to ReactDOM.render(). This is not supported.',
<ide> );
<ide> } else {
<del> warning(
<add> console.error(
<ide> 'You are calling ReactDOM.createRoot() on a container that ' +
<ide> 'has already been passed to createRoot() before. Instead, call ' +
<ide> 'root.render() on the existing root instead if you want to update it.',
<ide><path>packages/react-dom/src/client/ReactDOMSelect.js
<ide>
<ide> // TODO: direct imports like some-package/src/* are bad. Fix me.
<ide> import {getCurrentFiberOwnerNameInDevOrNull} from 'react-reconciler/src/ReactCurrentFiber';
<del>import warning from 'shared/warning';
<ide>
<ide> import ReactControlledValuePropTypes from '../shared/ReactControlledValuePropTypes';
<ide> import {getToStringValue, toString} from './ToStringValue';
<ide> function checkSelectPropTypes(props) {
<ide> }
<ide> const isArray = Array.isArray(props[propName]);
<ide> if (props.multiple && !isArray) {
<del> warning(
<add> console.error(
<ide> 'The `%s` prop supplied to <select> must be an array if ' +
<ide> '`multiple` is true.%s',
<ide> propName,
<ide> getDeclarationErrorAddendum(),
<ide> );
<ide> } else if (!props.multiple && isArray) {
<del> warning(
<add> console.error(
<ide> 'The `%s` prop supplied to <select> must be a scalar ' +
<ide> 'value if `multiple` is false.%s',
<ide> propName,
<ide> export function initWrapperState(element: Element, props: Object) {
<ide> props.defaultValue !== undefined &&
<ide> !didWarnValueDefaultValue
<ide> ) {
<del> warning(
<add> console.error(
<ide> 'Select elements must be either controlled or uncontrolled ' +
<ide> '(specify either the value prop, or the defaultValue prop, but not ' +
<ide> 'both). Decide between using a controlled or uncontrolled select ' +
<ide><path>packages/react-dom/src/client/ReactDOMTextarea.js
<ide> */
<ide>
<ide> import invariant from 'shared/invariant';
<del>import warning from 'shared/warning';
<ide>
<ide> import ReactControlledValuePropTypes from '../shared/ReactControlledValuePropTypes';
<ide> import {getCurrentFiberOwnerNameInDevOrNull} from 'react-reconciler/src/ReactCurrentFiber';
<ide> export function initWrapperState(element: Element, props: Object) {
<ide> props.defaultValue !== undefined &&
<ide> !didWarnValDefaultVal
<ide> ) {
<del> warning(
<add> console.error(
<ide> '%s contains a textarea with both value and defaultValue props. ' +
<ide> 'Textarea elements must be either controlled or uncontrolled ' +
<ide> '(specify either the value prop, or the defaultValue prop, but not ' +
<ide> export function initWrapperState(element: Element, props: Object) {
<ide> let children = props.children;
<ide> if (children != null) {
<ide> if (__DEV__) {
<del> warning(
<add> console.error(
<ide> 'Use the `defaultValue` or `value` props instead of setting ' +
<ide> 'children on <textarea>.',
<ide> );
<ide><path>packages/react-dom/src/client/setInnerHTML.js
<ide>
<ide> import {Namespaces} from '../shared/DOMNamespaces';
<ide> import createMicrosoftUnsafeLocalFunction from '../shared/createMicrosoftUnsafeLocalFunction';
<del>import warning from 'shared/warning';
<ide> import type {TrustedValue} from './ToStringValue';
<ide> import {enableTrustedTypesIntegration} from 'shared/ReactFeatureFlags';
<ide>
<ide> const setInnerHTML = createMicrosoftUnsafeLocalFunction(function(
<ide> // TODO: reconsider the text of this warning and when it should show
<ide> // before enabling the feature flag.
<ide> if (typeof trustedTypes !== 'undefined') {
<del> warning(
<add> console.error(
<ide> "Using 'dangerouslySetInnerHTML' in an svg element with " +
<ide> 'Trusted Types enabled in an Internet Explorer will cause ' +
<ide> 'the trusted value to be converted to string. Assigning string ' +
<ide><path>packages/react-dom/src/client/validateDOMNesting.js
<ide> * LICENSE file in the root directory of this source tree.
<ide> */
<ide>
<del>import warning from 'shared/warning';
<ide> // TODO: direct imports like some-package/src/* are bad. Fix me.
<ide> import {getCurrentFiberStackInDev} from 'react-reconciler/src/ReactCurrentFiber';
<ide>
<ide> if (__DEV__) {
<ide>
<ide> if (childText != null) {
<ide> if (childTag != null) {
<del> warning(
<add> console.error(
<ide> 'validateDOMNesting: when childText is passed, childTag should be null',
<ide> );
<ide> }
<ide> if (__DEV__) {
<ide> ' Add a <tbody>, <thead> or <tfoot> to your code to match the DOM tree generated by ' +
<ide> 'the browser.';
<ide> }
<del> warning(
<add> console.error(
<ide> 'validateDOMNesting(...): %s cannot appear as a child of <%s>.%s%s',
<ide> tagDisplayName,
<ide> ancestorTag,
<ide> whitespaceInfo,
<ide> info,
<ide> );
<ide> } else {
<del> warning(
<add> console.error(
<ide> 'validateDOMNesting(...): %s cannot appear as a descendant of ' +
<ide> '<%s>.',
<ide> tagDisplayName,
<ide><path>packages/react-dom/src/events/DOMEventResponderSystem.js
<ide> import {
<ide> } from 'legacy-events/ReactGenericBatching';
<ide> import {enqueueStateRestore} from 'legacy-events/ReactControlledComponent';
<ide> import type {Fiber} from 'react-reconciler/src/ReactFiber';
<del>import warning from 'shared/warning';
<ide> import {enableFlareAPI} from 'shared/ReactFeatureFlags';
<ide> import invariant from 'shared/invariant';
<ide>
<ide> function validateEventValue(eventValue: any): void {
<ide> }
<ide> const showWarning = name => {
<ide> if (__DEV__) {
<del> warning(
<add> console.error(
<ide> '%s is not available on event objects created from event responder modules (React Flare). ' +
<ide> 'Try wrapping in a conditional, i.e. `if (event.type !== "press") { event.%s }`',
<ide> name,
<ide><path>packages/react-dom/src/events/SimpleEventPlugin.js
<ide> import {accumulateTwoPhaseDispatches} from 'legacy-events/EventPropagators';
<ide> import SyntheticEvent from 'legacy-events/SyntheticEvent';
<ide>
<ide> import * as DOMTopLevelEventTypes from './DOMTopLevelEventTypes';
<del>import warning from 'shared/warning';
<ide>
<ide> import SyntheticAnimationEvent from './SyntheticAnimationEvent';
<ide> import SyntheticClipboardEvent from './SyntheticClipboardEvent';
<ide> const SimpleEventPlugin: PluginModule<MouseEvent> & {
<ide> default:
<ide> if (__DEV__) {
<ide> if (knownHTMLTopLevelTypes.indexOf(topLevelType) === -1) {
<del> warning(
<add> console.error(
<ide> 'SimpleEventPlugin: Unhandled event type, `%s`. This warning ' +
<ide> 'is likely caused by a bug in React. Please file an issue.',
<ide> topLevelType,
<ide><path>packages/react-dom/src/server/ReactPartialRenderer.js
<ide> import type {ReactProvider, ReactContext} from 'shared/ReactTypes';
<ide> import React from 'react';
<ide> import invariant from 'shared/invariant';
<ide> import getComponentName from 'shared/getComponentName';
<del>import lowPriorityWarning from 'shared/lowPriorityWarning';
<del>import warning from 'shared/warning';
<ide> import describeComponentFrame from 'shared/describeComponentFrame';
<ide> import ReactSharedInternals from 'shared/ReactSharedInternals';
<ide> import {
<ide> function warnNoop(
<ide> return;
<ide> }
<ide>
<del> warning(
<add> console.error(
<ide> '%s(...): Can only update a mounting component. ' +
<ide> 'This usually means you called %s() outside componentWillMount() on the server. ' +
<ide> 'This is a no-op.\n\nPlease check the code for the %s component.',
<ide> function flattenOptionChildren(children: mixed): ?string {
<ide> typeof child !== 'number'
<ide> ) {
<ide> didWarnInvalidOptionChildren = true;
<del> warning('Only strings and numbers are supported as <option> children.');
<add> console.error(
<add> 'Only strings and numbers are supported as <option> children.',
<add> );
<ide> }
<ide> }
<ide> });
<ide> function resolve(
<ide> if (inst.state === null || inst.state === undefined) {
<ide> const componentName = getComponentName(Component) || 'Unknown';
<ide> if (!didWarnAboutUninitializedState[componentName]) {
<del> warning(
<add> console.error(
<ide> '`%s` uses `getDerivedStateFromProps` but its initial state is ' +
<ide> '%s. This is not recommended. Instead, define the initial state by ' +
<ide> 'assigning an object to `this.state` in the constructor of `%s`. ' +
<ide> function resolve(
<ide> if (partialState === undefined) {
<ide> const componentName = getComponentName(Component) || 'Unknown';
<ide> if (!didWarnAboutUndefinedDerivedState[componentName]) {
<del> warning(
<add> console.error(
<ide> '%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' +
<ide> 'You have returned undefined.',
<ide> componentName,
<ide> function resolve(
<ide> const componentName = getComponentName(Component) || 'Unknown';
<ide>
<ide> if (!didWarnAboutBadClass[componentName]) {
<del> warning(
<add> console.error(
<ide> "The <%s /> component appears to have a render method, but doesn't extend React.Component. " +
<ide> 'This is likely to cause errors. Change %s to extend React.Component instead.',
<ide> componentName,
<ide> function resolve(
<ide> if (__DEV__) {
<ide> const componentName = getComponentName(Component) || 'Unknown';
<ide> if (!didWarnAboutModulePatternComponent[componentName]) {
<del> warning(
<add> console.error(
<ide> 'The <%s /> component appears to be a function component that returns a class instance. ' +
<ide> 'Change %s to a class that extends React.Component instead. ' +
<ide> "If you can't use a class try assigning the prototype on the function as a workaround. " +
<ide> function resolve(
<ide> const componentName = getComponentName(Component) || 'Unknown';
<ide>
<ide> if (!didWarnAboutDeprecatedWillMount[componentName]) {
<del> lowPriorityWarning(
<add> console.warn(
<ide> // keep this warning in sync with ReactStrictModeWarning.js
<ide> 'componentWillMount has been renamed, and is not recommended for use. ' +
<ide> 'See https://fb.me/react-unsafe-component-lifecycles for details.\n\n' +
<ide> function resolve(
<ide> if (__DEV__) {
<ide> let childContextTypes = Component.childContextTypes;
<ide> if (childContextTypes !== undefined) {
<del> warning(
<add> console.error(
<ide> '%s uses the legacy childContextTypes API which is no longer supported. ' +
<ide> 'Use React.createContext() instead.',
<ide> getComponentName(Component) || 'Unknown',
<ide> function resolve(
<ide> }
<ide> } else {
<ide> if (__DEV__) {
<del> warning(
<add> console.error(
<ide> '%s.getChildContext(): childContextTypes must be defined in order to ' +
<ide> 'use getChildContext().',
<ide> getComponentName(Component) || 'Unknown',
<ide> class ReactDOMServerRenderer {
<ide> const index = this.contextIndex;
<ide> if (__DEV__) {
<ide> if (index < 0 || provider !== (this.contextProviderStack: any)[index]) {
<del> warning('Unexpected pop.');
<add> console.error('Unexpected pop.');
<ide> }
<ide> }
<ide>
<ide> class ReactDOMServerRenderer {
<ide> if (reactContext !== reactContext.Consumer) {
<ide> if (!hasWarnedAboutUsingContextAsConsumer) {
<ide> hasWarnedAboutUsingContextAsConsumer = true;
<del> warning(
<add> console.error(
<ide> 'Rendering <Context> directly is not supported and will be removed in ' +
<ide> 'a future major release. Did you mean to render <Context.Consumer> instead?',
<ide> );
<ide> class ReactDOMServerRenderer {
<ide> // Should this check be gated by parent namespace? Not sure we want to
<ide> // allow <SVG> or <mATH>.
<ide> if (tag !== element.type) {
<del> warning(
<add> console.error(
<ide> '<%s /> is using incorrect casing. ' +
<ide> 'Use PascalCase for React components, ' +
<ide> 'or lowercase for HTML elements.',
<ide> class ReactDOMServerRenderer {
<ide> props.defaultChecked !== undefined &&
<ide> !didWarnDefaultChecked
<ide> ) {
<del> warning(
<add> console.error(
<ide> '%s contains an input of type %s with both checked and defaultChecked props. ' +
<ide> 'Input elements must be either controlled or uncontrolled ' +
<ide> '(specify either the checked prop, or the defaultChecked prop, but not ' +
<ide> class ReactDOMServerRenderer {
<ide> props.defaultValue !== undefined &&
<ide> !didWarnDefaultInputValue
<ide> ) {
<del> warning(
<add> console.error(
<ide> '%s contains an input of type %s with both value and defaultValue props. ' +
<ide> 'Input elements must be either controlled or uncontrolled ' +
<ide> '(specify either the value prop, or the defaultValue prop, but not ' +
<ide> class ReactDOMServerRenderer {
<ide> props.defaultValue !== undefined &&
<ide> !didWarnDefaultTextareaValue
<ide> ) {
<del> warning(
<add> console.error(
<ide> 'Textarea elements must be either controlled or uncontrolled ' +
<ide> '(specify either the value prop, or the defaultValue prop, but not ' +
<ide> 'both). Decide between using a controlled or uncontrolled textarea ' +
<ide> class ReactDOMServerRenderer {
<ide> let textareaChildren = props.children;
<ide> if (textareaChildren != null) {
<ide> if (__DEV__) {
<del> warning(
<add> console.error(
<ide> 'Use the `defaultValue` or `value` props instead of setting ' +
<ide> 'children on <textarea>.',
<ide> );
<ide> class ReactDOMServerRenderer {
<ide> }
<ide> const isArray = Array.isArray(props[propName]);
<ide> if (props.multiple && !isArray) {
<del> warning(
<add> console.error(
<ide> 'The `%s` prop supplied to <select> must be an array if ' +
<ide> '`multiple` is true.',
<ide> propName,
<ide> );
<ide> } else if (!props.multiple && isArray) {
<del> warning(
<add> console.error(
<ide> 'The `%s` prop supplied to <select> must be a scalar ' +
<ide> 'value if `multiple` is false.',
<ide> propName,
<ide> class ReactDOMServerRenderer {
<ide> props.defaultValue !== undefined &&
<ide> !didWarnDefaultSelectValue
<ide> ) {
<del> warning(
<add> console.error(
<ide> 'Select elements must be either controlled or uncontrolled ' +
<ide> '(specify either the value prop, or the defaultValue prop, but not ' +
<ide> 'both). Decide between using a controlled or uncontrolled select ' +
<ide><path>packages/react-dom/src/server/ReactPartialRendererContext.js
<ide> import {disableLegacyContext} from 'shared/ReactFeatureFlags';
<ide> import {REACT_CONTEXT_TYPE, REACT_PROVIDER_TYPE} from 'shared/ReactSymbols';
<ide> import ReactSharedInternals from 'shared/ReactSharedInternals';
<ide> import getComponentName from 'shared/getComponentName';
<del>import warning from 'shared/warning';
<ide> import checkPropTypes from 'prop-types/checkPropTypes';
<ide>
<ide> let ReactDebugCurrentFrame;
<ide> export function processContext(
<ide> Object.keys(contextType).join(', ') +
<ide> '}.';
<ide> }
<del> warning(
<add> console.error(
<ide> '%s defines an invalid contextType. ' +
<ide> 'contextType should point to the Context object returned by React.createContext().%s',
<ide> getComponentName(type) || 'Component',
<ide> export function processContext(
<ide> if (disableLegacyContext) {
<ide> if (__DEV__) {
<ide> if (type.contextTypes) {
<del> warning(
<add> console.error(
<ide> '%s uses the legacy contextTypes API which is no longer supported. ' +
<ide> 'Use React.createContext() with static contextType instead.',
<ide> getComponentName(type) || 'Unknown',
<ide> export function processContext(
<ide> if (disableLegacyContext) {
<ide> if (__DEV__) {
<ide> if (type.contextTypes) {
<del> warning(
<add> console.error(
<ide> '%s uses the legacy contextTypes API which is no longer supported. ' +
<ide> 'Use React.createContext() with React.useContext() instead.',
<ide> getComponentName(type) || 'Unknown',
<ide><path>packages/react-dom/src/server/ReactPartialRendererHooks.js
<ide> import type {SuspenseConfig} from 'react-reconciler/src/ReactFiberSuspenseConfig
<ide> import {validateContextBounds} from './ReactPartialRendererContext';
<ide>
<ide> import invariant from 'shared/invariant';
<del>import warning from 'shared/warning';
<ide> import is from 'shared/objectIs';
<ide>
<ide> type BasicStateAction<S> = (S => S) | S;
<ide> function resolveCurrentlyRenderingComponent(): Object {
<ide> );
<ide> if (__DEV__) {
<ide> if (isInHookUserCodeInDev) {
<del> warning(
<add> console.error(
<ide> 'Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. ' +
<ide> 'You can only call Hooks at the top level of your React function. ' +
<ide> 'For more information, see ' +
<ide> function areHookInputsEqual(
<ide> ) {
<ide> if (prevDeps === null) {
<ide> if (__DEV__) {
<del> warning(
<add> console.error(
<ide> '%s received a final argument during this render, but not during ' +
<ide> 'the previous render. Even though the final argument is optional, ' +
<ide> 'its type cannot change between renders.',
<ide> function areHookInputsEqual(
<ide> // Don't bother comparing lengths in prod because these arrays should be
<ide> // passed inline.
<ide> if (nextDeps.length !== prevDeps.length) {
<del> warning(
<add> console.error(
<ide> 'The final argument passed to %s changed size between renders. The ' +
<ide> 'order and size of this array must remain constant.\n\n' +
<ide> 'Previous: %s\n' +
<ide> function readContext<T>(
<ide> validateContextBounds(context, threadID);
<ide> if (__DEV__) {
<ide> if (isInHookUserCodeInDev) {
<del> warning(
<add> console.error(
<ide> 'Context can only be read while React is rendering. ' +
<ide> 'In classes, you can read it in the render method or getDerivedStateFromProps. ' +
<ide> 'In function components, you can read it directly in the function body, but not ' +
<ide> export function useLayoutEffect(
<ide> ) {
<ide> if (__DEV__) {
<ide> currentHookNameInDev = 'useLayoutEffect';
<del> warning(
<add> console.error(
<ide> 'useLayoutEffect does nothing on the server, because its effect cannot ' +
<ide> "be encoded into the server renderer's output format. This will lead " +
<ide> 'to a mismatch between the initial, non-hydrated UI and the intended ' +
<ide><path>packages/react-dom/src/shared/CSSPropertyOperations.js
<ide> import {shorthandToLonghand} from './CSSShorthandProperty';
<ide> import dangerousStyleValue from './dangerousStyleValue';
<ide> import hyphenateStyleName from './hyphenateStyleName';
<ide> import warnValidStyle from './warnValidStyle';
<del>import warning from 'shared/warning';
<ide>
<ide> import {warnAboutShorthandPropertyCollision} from 'shared/ReactFeatureFlags';
<ide>
<ide> export function validateShorthandPropertyCollisionInDev(
<ide> continue;
<ide> }
<ide> warnedAbout[warningKey] = true;
<del> warning(
<add> console.error(
<ide> '%s a style property during rerender (%s) when a ' +
<ide> 'conflicting property is set (%s) can lead to styling bugs. To ' +
<ide> "avoid this, don't mix shorthand and non-shorthand properties " +
<ide><path>packages/react-dom/src/shared/DOMProperty.js
<ide> * @flow
<ide> */
<ide>
<del>import warning from 'shared/warning';
<ide> import {enableFlareAPI} from 'shared/ReactFeatureFlags';
<ide>
<ide> type PropertyType = 0 | 1 | 2 | 3 | 4 | 5 | 6;
<ide> export function isAttributeNameSafe(attributeName: string): boolean {
<ide> }
<ide> illegalAttributeNameCache[attributeName] = true;
<ide> if (__DEV__) {
<del> warning('Invalid attribute name: `%s`', attributeName);
<add> console.error('Invalid attribute name: `%s`', attributeName);
<ide> }
<ide> return false;
<ide> }
<ide><path>packages/react-dom/src/shared/ReactDOMInvalidARIAHook.js
<ide> * LICENSE file in the root directory of this source tree.
<ide> */
<ide>
<del>import warning from 'shared/warning';
<del>
<ide> import {ATTRIBUTE_NAME_CHAR} from './DOMProperty';
<ide> import isCustomComponent from './isCustomComponent';
<ide> import validAriaProperties from './validAriaProperties';
<ide> function validateProperty(tagName, name) {
<ide> // If this is an aria-* attribute, but is not listed in the known DOM
<ide> // DOM properties, then it is an invalid aria-* attribute.
<ide> if (correctName == null) {
<del> warning(
<add> console.error(
<ide> 'Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.',
<ide> name,
<ide> );
<ide> function validateProperty(tagName, name) {
<ide> }
<ide> // aria-* attributes should be lowercase; suggest the lowercase version.
<ide> if (name !== correctName) {
<del> warning(
<add> console.error(
<ide> 'Invalid ARIA attribute `%s`. Did you mean `%s`?',
<ide> name,
<ide> correctName,
<ide> function validateProperty(tagName, name) {
<ide> }
<ide> // aria-* attributes should be lowercase; suggest the lowercase version.
<ide> if (name !== standardName) {
<del> warning(
<add> console.error(
<ide> 'Unknown ARIA attribute `%s`. Did you mean `%s`?',
<ide> name,
<ide> standardName,
<ide> function warnInvalidARIAProps(type, props) {
<ide> .join(', ');
<ide>
<ide> if (invalidProps.length === 1) {
<del> warning(
<add> console.error(
<ide> 'Invalid aria prop %s on <%s> tag. ' +
<ide> 'For details, see https://fb.me/invalid-aria-prop',
<ide> unknownPropString,
<ide> type,
<ide> );
<ide> } else if (invalidProps.length > 1) {
<del> warning(
<add> console.error(
<ide> 'Invalid aria props %s on <%s> tag. ' +
<ide> 'For details, see https://fb.me/invalid-aria-prop',
<ide> unknownPropString,
<ide><path>packages/react-dom/src/shared/ReactDOMNullInputValuePropHook.js
<ide> * LICENSE file in the root directory of this source tree.
<ide> */
<ide>
<del>import warning from 'shared/warning';
<del>
<ide> let didWarnValueNull = false;
<ide>
<ide> export function validateProperties(type, props) {
<ide> export function validateProperties(type, props) {
<ide> if (props != null && props.value === null && !didWarnValueNull) {
<ide> didWarnValueNull = true;
<ide> if (type === 'select' && props.multiple) {
<del> warning(
<add> console.error(
<ide> '`value` prop on `%s` should not be null. ' +
<ide> 'Consider using an empty array when `multiple` is set to `true` ' +
<ide> 'to clear the component or `undefined` for uncontrolled components.',
<ide> type,
<ide> );
<ide> } else {
<del> warning(
<add> console.error(
<ide> '`value` prop on `%s` should not be null. ' +
<ide> 'Consider using an empty string to clear the component or `undefined` ' +
<ide> 'for uncontrolled components.',
<ide><path>packages/react-dom/src/shared/ReactDOMUnknownPropertyHook.js
<ide> import {
<ide> registrationNameModules,
<ide> possibleRegistrationNames,
<ide> } from 'legacy-events/EventPluginRegistry';
<del>import warning from 'shared/warning';
<ide>
<ide> import {
<ide> ATTRIBUTE_NAME_CHAR,
<ide> if (__DEV__) {
<ide>
<ide> const lowerCasedName = name.toLowerCase();
<ide> if (lowerCasedName === 'onfocusin' || lowerCasedName === 'onfocusout') {
<del> warning(
<add> console.error(
<ide> 'React uses onFocus and onBlur instead of onFocusIn and onFocusOut. ' +
<ide> 'All React events are normalized to bubble, so onFocusIn and onFocusOut ' +
<ide> 'are not needed/supported by React.',
<ide> if (__DEV__) {
<ide> ? possibleRegistrationNames[lowerCasedName]
<ide> : null;
<ide> if (registrationName != null) {
<del> warning(
<add> console.error(
<ide> 'Invalid event handler property `%s`. Did you mean `%s`?',
<ide> name,
<ide> registrationName,
<ide> if (__DEV__) {
<ide> return true;
<ide> }
<ide> if (EVENT_NAME_REGEX.test(name)) {
<del> warning(
<add> console.error(
<ide> 'Unknown event handler property `%s`. It will be ignored.',
<ide> name,
<ide> );
<ide> if (__DEV__) {
<ide> // So we can't tell if the event name is correct for sure, but we can filter
<ide> // out known bad ones like `onclick`. We can't suggest a specific replacement though.
<ide> if (INVALID_EVENT_NAME_REGEX.test(name)) {
<del> warning(
<add> console.error(
<ide> 'Invalid event handler property `%s`. ' +
<ide> 'React events use the camelCase naming convention, for example `onClick`.',
<ide> name,
<ide> if (__DEV__) {
<ide> }
<ide>
<ide> if (lowerCasedName === 'innerhtml') {
<del> warning(
<add> console.error(
<ide> 'Directly setting property `innerHTML` is not permitted. ' +
<ide> 'For more information, lookup documentation on `dangerouslySetInnerHTML`.',
<ide> );
<ide> if (__DEV__) {
<ide> }
<ide>
<ide> if (lowerCasedName === 'aria') {
<del> warning(
<add> console.error(
<ide> 'The `aria` attribute is reserved for future use in React. ' +
<ide> 'Pass individual `aria-` attributes instead.',
<ide> );
<ide> if (__DEV__) {
<ide> value !== undefined &&
<ide> typeof value !== 'string'
<ide> ) {
<del> warning(
<add> console.error(
<ide> 'Received a `%s` for a string attribute `is`. If this is expected, cast ' +
<ide> 'the value to a string.',
<ide> typeof value,
<ide> if (__DEV__) {
<ide> }
<ide>
<ide> if (typeof value === 'number' && isNaN(value)) {
<del> warning(
<add> console.error(
<ide> 'Received NaN for the `%s` attribute. If this is expected, cast ' +
<ide> 'the value to a string.',
<ide> name,
<ide> if (__DEV__) {
<ide> if (possibleStandardNames.hasOwnProperty(lowerCasedName)) {
<ide> const standardName = possibleStandardNames[lowerCasedName];
<ide> if (standardName !== name) {
<del> warning(
<add> console.error(
<ide> 'Invalid DOM property `%s`. Did you mean `%s`?',
<ide> name,
<ide> standardName,
<ide> if (__DEV__) {
<ide> } else if (!isReserved && name !== lowerCasedName) {
<ide> // Unknown attributes should have lowercase casing since that's how they
<ide> // will be cased anyway with server rendering.
<del> warning(
<add> console.error(
<ide> 'React does not recognize the `%s` prop on a DOM element. If you ' +
<ide> 'intentionally want it to appear in the DOM as a custom ' +
<ide> 'attribute, spell it as lowercase `%s` instead. ' +
<ide> if (__DEV__) {
<ide> shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)
<ide> ) {
<ide> if (value) {
<del> warning(
<add> console.error(
<ide> 'Received `%s` for a non-boolean attribute `%s`.\n\n' +
<ide> 'If you want to write it to the DOM, pass a string instead: ' +
<ide> '%s="%s" or %s={value.toString()}.',
<ide> if (__DEV__) {
<ide> name,
<ide> );
<ide> } else {
<del> warning(
<add> console.error(
<ide> 'Received `%s` for a non-boolean attribute `%s`.\n\n' +
<ide> 'If you want to write it to the DOM, pass a string instead: ' +
<ide> '%s="%s" or %s={value.toString()}.\n\n' +
<ide> if (__DEV__) {
<ide> propertyInfo !== null &&
<ide> propertyInfo.type === BOOLEAN
<ide> ) {
<del> warning(
<add> console.error(
<ide> 'Received the string `%s` for the boolean attribute `%s`. ' +
<ide> '%s ' +
<ide> 'Did you mean %s={%s}?',
<ide> const warnUnknownProperties = function(type, props, canUseEventSystem) {
<ide> .map(prop => '`' + prop + '`')
<ide> .join(', ');
<ide> if (unknownProps.length === 1) {
<del> warning(
<add> console.error(
<ide> 'Invalid value for prop %s on <%s> tag. Either remove it from the element, ' +
<ide> 'or pass a string or number value to keep it in the DOM. ' +
<ide> 'For details, see https://fb.me/react-attribute-behavior',
<ide> unknownPropString,
<ide> type,
<ide> );
<ide> } else if (unknownProps.length > 1) {
<del> warning(
<add> console.error(
<ide> 'Invalid values for props %s on <%s> tag. Either remove them from the element, ' +
<ide> 'or pass a string or number value to keep them in the DOM. ' +
<ide> 'For details, see https://fb.me/react-attribute-behavior',
<ide><path>packages/react-dom/src/shared/assertValidProps.js
<ide> */
<ide>
<ide> import invariant from 'shared/invariant';
<del>import warning from 'shared/warning';
<ide> // TODO: We can remove this if we add invariantWithStack()
<ide> // or add stack by default to invariants where possible.
<ide> import ReactSharedInternals from 'shared/ReactSharedInternals';
<ide> function assertValidProps(tag: string, props: ?Object) {
<ide> props.contentEditable &&
<ide> props.children != null
<ide> ) {
<del> warning(
<add> console.error(
<ide> 'A component is `contentEditable` and contains `children` managed by ' +
<ide> 'React. It is now your responsibility to guarantee that none of ' +
<ide> 'those nodes are unexpectedly modified or duplicated. This is ' +
<ide><path>packages/react-dom/src/shared/sanitizeURL.js
<ide> */
<ide>
<ide> import invariant from 'shared/invariant';
<del>import warning from 'shared/warning';
<ide> import ReactSharedInternals from 'shared/ReactSharedInternals';
<ide> import {disableJavaScriptURLs} from 'shared/ReactFeatureFlags';
<ide>
<ide> function sanitizeURL(url: string) {
<ide> } else if (__DEV__) {
<ide> if (!didWarn && isJavaScriptProtocol.test(url)) {
<ide> didWarn = true;
<del> warning(
<add> console.error(
<ide> 'A future version of React will block javascript: URLs as a security precaution. ' +
<ide> 'Use event handlers instead if you can. If you need to generate unsafe HTML try ' +
<ide> 'using dangerouslySetInnerHTML instead. React was passed %s.',
<ide><path>packages/react-dom/src/shared/warnValidStyle.js
<ide> * LICENSE file in the root directory of this source tree.
<ide> */
<ide>
<del>import warning from 'shared/warning';
<del>
<ide> let warnValidStyle = () => {};
<ide>
<ide> if (__DEV__) {
<ide> if (__DEV__) {
<ide> }
<ide>
<ide> warnedStyleNames[name] = true;
<del> warning(
<add> console.error(
<ide> 'Unsupported style property %s. Did you mean %s?',
<ide> name,
<ide> // As Andi Smith suggests
<ide> if (__DEV__) {
<ide> }
<ide>
<ide> warnedStyleNames[name] = true;
<del> warning(
<add> console.error(
<ide> 'Unsupported vendor-prefixed style property %s. Did you mean %s?',
<ide> name,
<ide> name.charAt(0).toUpperCase() + name.slice(1),
<ide> if (__DEV__) {
<ide> }
<ide>
<ide> warnedStyleValues[value] = true;
<del> warning(
<add> console.error(
<ide> "Style property values shouldn't contain a semicolon. " +
<ide> 'Try "%s: %s" instead.',
<ide> name,
<ide> if (__DEV__) {
<ide> }
<ide>
<ide> warnedForNaNValue = true;
<del> warning('`NaN` is an invalid value for the `%s` css style property.', name);
<add> console.error(
<add> '`NaN` is an invalid value for the `%s` css style property.',
<add> name,
<add> );
<ide> };
<ide>
<ide> const warnStyleValueIsInfinity = function(name, value) {
<ide> if (__DEV__) {
<ide> }
<ide>
<ide> warnedForInfinityValue = true;
<del> warning(
<add> console.error(
<ide> '`Infinity` is an invalid value for the `%s` css style property.',
<ide> name,
<ide> );
<ide><path>packages/react-dom/src/test-utils/ReactTestUtils.js
<ide> import {
<ide> } from 'shared/ReactWorkTags';
<ide> import SyntheticEvent from 'legacy-events/SyntheticEvent';
<ide> import invariant from 'shared/invariant';
<del>import lowPriorityWarning from 'shared/lowPriorityWarning';
<ide> import {ELEMENT_NODE} from '../shared/HTMLNodeType';
<ide> import * as DOMTopLevelEventTypes from '../events/DOMTopLevelEventTypes';
<ide> import {PLUGIN_EVENT_SYSTEM} from 'legacy-events/EventSystemFlags';
<ide> const ReactTestUtils = {
<ide> if (__DEV__) {
<ide> if (!hasWarnedAboutDeprecatedMockComponent) {
<ide> hasWarnedAboutDeprecatedMockComponent = true;
<del> lowPriorityWarning(
<add> console.warn(
<ide> 'ReactTestUtils.mockComponent() is deprecated. ' +
<ide> 'Use shallow rendering or jest.mock() instead.\n\n' +
<ide> 'See https://fb.me/test-utils-mock-component for more information.',
<ide><path>packages/react-dom/src/test-utils/ReactTestUtilsAct.js
<ide>
<ide> import type {Thenable} from 'react-reconciler/src/ReactFiberWorkLoop';
<ide>
<del>import warning from 'shared/warning';
<ide> import ReactDOM from 'react-dom';
<ide> import ReactSharedInternals from 'shared/ReactSharedInternals';
<ide> import enqueueTask from 'shared/enqueueTask';
<ide> function act(callback: () => Thenable) {
<ide> if (!__DEV__) {
<ide> if (didWarnAboutUsingActInProd === false) {
<ide> didWarnAboutUsingActInProd = true;
<add> // eslint-disable-next-line react-internal/no-production-logging
<ide> console.error(
<ide> 'act(...) is not supported in production builds of React, and might not behave as expected.',
<ide> );
<ide> function act(callback: () => Thenable) {
<ide> if (__DEV__) {
<ide> if (actingUpdatesScopeDepth > previousActingUpdatesScopeDepth) {
<ide> // if it's _less than_ previousActingUpdatesScopeDepth, then we can assume the 'other' one has warned
<del> warning(
<add> console.error(
<ide> 'You seem to have overlapping act() calls, this is not supported. ' +
<ide> 'Be sure to await previous act() calls before making a new one. ',
<ide> );
<ide> function act(callback: () => Thenable) {
<ide> .then(() => {})
<ide> .then(() => {
<ide> if (called === false) {
<del> warning(
<add> console.error(
<ide> 'You called act(async () => ...) without await. ' +
<ide> 'This could lead to unexpected testing behaviour, interleaving multiple act ' +
<ide> 'calls and mixing their scopes. You should - await act(async () => ...);',
<ide> function act(callback: () => Thenable) {
<ide> } else {
<ide> if (__DEV__) {
<ide> if (result !== undefined) {
<del> warning(
<add> console.error(
<ide> 'The callback passed to act(...) function ' +
<ide> 'must return undefined, or a Promise. You returned %s',
<ide> result,
<ide> function act(callback: () => Thenable) {
<ide> return {
<ide> then(resolve: () => void) {
<ide> if (__DEV__) {
<del> warning(
<add> console.error(
<ide> 'Do not await the result of calling act(...) with sync logic, it is not a Promise.',
<ide> );
<ide> }
<ide><path>packages/react-interactions/events/src/dom/Press.js
<ide> import type {PointerType} from 'shared/ReactDOMTypes';
<ide> import React from 'react';
<ide> import {useTap} from 'react-interactions/events/tap';
<ide> import {useKeyboard} from 'react-interactions/events/keyboard';
<del>import warning from 'shared/warning';
<ide>
<ide> const emptyObject = {};
<ide>
<ide> function createGestureState(e: any, type: PressEventType): PressEvent {
<ide> preventDefault() {
<ide> // NO-OP, we should remove this in the future
<ide> if (__DEV__) {
<del> warning(
<add> console.error(
<ide> 'preventDefault is not available on event objects created from event responder modules (React Flare). ' +
<ide> 'Try wrapping in a conditional, i.e. `if (event.type !== "press") { event.preventDefault() }`',
<ide> );
<ide> function createGestureState(e: any, type: PressEventType): PressEvent {
<ide> stopPropagation() {
<ide> // NO-OP, we should remove this in the future
<ide> if (__DEV__) {
<del> warning(
<add> console.error(
<ide> 'stopPropagation is not available on event objects created from event responder modules (React Flare). ' +
<ide> 'Try wrapping in a conditional, i.e. `if (event.type !== "press") { event.stopPropagation() }`',
<ide> );
<ide><path>packages/react-interactions/events/src/dom/PressLegacy.js
<ide> import type {
<ide>
<ide> import React from 'react';
<ide> import {DiscreteEvent, UserBlockingEvent} from 'shared/ReactTypes';
<del>import warning from 'shared/warning';
<ide>
<ide> type PressProps = {|
<ide> disabled: boolean,
<ide> function createPressEvent(
<ide> stopPropagation() {
<ide> // NO-OP, we should remove this in the future
<ide> if (__DEV__) {
<del> warning(
<add> console.error(
<ide> 'stopPropagation is not available on event objects created from event responder modules (React Flare). ' +
<ide> 'Try wrapping in a conditional, i.e. `if (event.type !== "press") { event.stopPropagation() }`',
<ide> );
<ide><path>packages/react-interactions/events/src/dom/testing-library/domEnvironment.js
<ide> export function hasPointerEvent() {
<ide> export function setPointerEvent(bool) {
<ide> const pointerCaptureFn = name => id => {
<ide> if (typeof id !== 'number') {
<del> console.error(`A pointerId must be passed to "${name}"`);
<add> if (__DEV__) {
<add> console.error('A pointerId must be passed to "%s"', name);
<add> }
<ide> }
<ide> };
<ide> global.PointerEvent = bool ? emptyFunction : undefined;
<ide><path>packages/react-is/src/ReactIs.js
<ide> import {
<ide> REACT_SUSPENSE_TYPE,
<ide> } from 'shared/ReactSymbols';
<ide> import isValidElementType from 'shared/isValidElementType';
<del>import lowPriorityWarningWithoutStack from 'shared/lowPriorityWarningWithoutStack';
<ide>
<ide> export function typeOf(object: any) {
<ide> if (typeof object === 'object' && object !== null) {
<ide> export function isAsyncMode(object: any) {
<ide> if (__DEV__) {
<ide> if (!hasWarnedAboutDeprecatedIsAsyncMode) {
<ide> hasWarnedAboutDeprecatedIsAsyncMode = true;
<del> lowPriorityWarningWithoutStack(
<add> // Using console['warn'] to evade Babel and ESLint
<add> console['warn'](
<ide> 'The ReactIs.isAsyncMode() alias has been deprecated, ' +
<ide> 'and will be removed in React 17+. Update your code to use ' +
<ide> 'ReactIs.isConcurrentMode() instead. It has the exact same API.',
<ide><path>packages/react-native-renderer/src/NativeMethodsMixin.js
<ide> import {
<ide> warnForStyleProps,
<ide> } from './NativeMethodsMixinUtils';
<ide>
<del>import warning from 'shared/warning';
<del>
<ide> export default function(
<ide> findNodeHandle: any => ?number,
<ide> findHostInstance: any => any,
<ide> export default function(
<ide>
<ide> if (maybeInstance.canonical) {
<ide> if (__DEV__) {
<del> warning(
<add> console.error(
<ide> 'Warning: measureLayout on components using NativeMethodsMixin ' +
<ide> 'or ReactNative.NativeComponent is not currently supported in Fabric. ' +
<ide> 'measureLayout must be called on a native ref. Consider using forwardRef.',
<ide> export default function(
<ide>
<ide> if (relativeNode == null) {
<ide> if (__DEV__) {
<del> warning(
<add> console.error(
<ide> 'Warning: ref.measureLayout must be called with a node handle or a ref to a native component.',
<ide> );
<ide> }
<ide> export default function(
<ide>
<ide> if (maybeInstance.canonical) {
<ide> if (__DEV__) {
<del> warning(
<add> console.error(
<ide> 'Warning: setNativeProps is not currently supported in Fabric',
<ide> );
<ide> }
<ide><path>packages/react-native-renderer/src/NativeMethodsMixinUtils.js
<ide> export function throwOnStylesProp(component: any, props: any) {
<ide> }
<ide>
<ide> export function warnForStyleProps(props: any, validAttributes: any) {
<del> for (const key in validAttributes.style) {
<del> if (!(validAttributes[key] || props[key] === undefined)) {
<del> console.error(
<del> 'You are setting the style `{ ' +
<del> key +
<del> ': ... }` as a prop. You ' +
<del> 'should nest it in a style object. ' +
<del> 'E.g. `{ style: { ' +
<del> key +
<del> ': ... } }`',
<del> );
<add> if (__DEV__) {
<add> for (const key in validAttributes.style) {
<add> if (!(validAttributes[key] || props[key] === undefined)) {
<add> console.error(
<add> 'You are setting the style `{ %s' +
<add> ': ... }` as a prop. You ' +
<add> 'should nest it in a style object. ' +
<add> 'E.g. `{ style: { %s' +
<add> ': ... } }`',
<add> key,
<add> key,
<add> );
<add> }
<ide> }
<ide> }
<ide> }
<ide><path>packages/react-native-renderer/src/ReactFabric.js
<ide> import {getInspectorDataForViewTag} from './ReactNativeFiberInspector';
<ide> import {LegacyRoot} from 'shared/ReactRootTags';
<ide> import ReactSharedInternals from 'shared/ReactSharedInternals';
<ide> import getComponentName from 'shared/getComponentName';
<del>import warning from 'shared/warning';
<ide>
<ide> const {dispatchCommand: fabricDispatchCommand} = nativeFabricUIManager;
<ide>
<ide> function findHostInstance_DEPRECATED(
<ide> const owner = ReactCurrentOwner.current;
<ide> if (owner !== null && owner.stateNode !== null) {
<ide> if (!owner.stateNode._warnedAboutRefsInRender) {
<del> warning(
<add> console.error(
<ide> '%s is accessing findNodeHandle inside its render(). ' +
<ide> 'render() should be a pure function of props and state. It should ' +
<ide> 'never access something that requires stale data from the previous ' +
<ide> function findNodeHandle(componentOrHandle: any): ?number {
<ide> const owner = ReactCurrentOwner.current;
<ide> if (owner !== null && owner.stateNode !== null) {
<ide> if (!owner.stateNode._warnedAboutRefsInRender) {
<del> warning(
<add> console.error(
<ide> '%s is accessing findNodeHandle inside its render(). ' +
<ide> 'render() should be a pure function of props and state. It should ' +
<ide> 'never access something that requires stale data from the previous ' +
<ide> const ReactFabric: ReactFabricType = {
<ide> if (invalid) {
<ide> if (__DEV__) {
<ide> if (invalid) {
<del> warning(
<add> console.error(
<ide> "dispatchCommand was called with a ref that isn't a " +
<ide> 'native component. Use React.forwardRef to get access to the underlying native component',
<ide> );
<ide><path>packages/react-native-renderer/src/ReactFabricEventResponderSystem.js
<ide> import {
<ide> UserBlockingEvent,
<ide> DiscreteEvent,
<ide> } from './ReactNativeTypes';
<del>import warning from 'shared/warning';
<ide> import invariant from 'shared/invariant';
<ide>
<ide> // Intentionally not named imports because Rollup would use dynamic dispatch for
<ide> function validateEventValue(eventValue: any): void {
<ide> }
<ide> const showWarning = name => {
<ide> if (__DEV__) {
<del> warning(
<add> console.error(
<ide> '%s is not available on event objects created from event responder modules (React Flare). ' +
<ide> 'Try wrapping in a conditional, i.e. `if (event.type !== "press") { event.%s }`',
<ide> name,
<ide><path>packages/react-native-renderer/src/ReactFabricHostConfig.js
<ide> import {mountSafeCallback_NOT_REALLY_SAFE} from './NativeMethodsMixinUtils';
<ide> import {create, diff} from './ReactNativeAttributePayload';
<ide>
<ide> import invariant from 'shared/invariant';
<del>import warning from 'shared/warning';
<ide>
<ide> import {dispatchEvent} from './ReactFabricEventEmitter';
<ide> import {
<ide> class ReactFabricHostComponent {
<ide> !(relativeToNativeNode instanceof ReactFabricHostComponent)
<ide> ) {
<ide> if (__DEV__) {
<del> warning(
<add> console.error(
<ide> 'Warning: ref.measureLayout must be called with a ref to a native component.',
<ide> );
<ide> }
<ide> class ReactFabricHostComponent {
<ide>
<ide> setNativeProps(nativeProps: Object) {
<ide> if (__DEV__) {
<del> warning('Warning: setNativeProps is not currently supported in Fabric');
<add> console.error(
<add> 'Warning: setNativeProps is not currently supported in Fabric',
<add> );
<ide> }
<ide>
<ide> return;
<ide><path>packages/react-native-renderer/src/ReactNativeComponent.js
<ide> import {
<ide> import {create} from './ReactNativeAttributePayload';
<ide> import {mountSafeCallback_NOT_REALLY_SAFE} from './NativeMethodsMixinUtils';
<ide>
<del>import warning from 'shared/warning';
<del>
<ide> export default function(
<ide> findNodeHandle: any => ?number,
<ide> findHostInstance: any => any,
<ide> export default function(
<ide>
<ide> if (maybeInstance.canonical) {
<ide> if (__DEV__) {
<del> warning(
<add> console.error(
<ide> 'Warning: measureLayout on components using NativeMethodsMixin ' +
<ide> 'or ReactNative.NativeComponent is not currently supported in Fabric. ' +
<ide> 'measureLayout must be called on a native ref. Consider using forwardRef.',
<ide> export default function(
<ide>
<ide> if (relativeNode == null) {
<ide> if (__DEV__) {
<del> warning(
<add> console.error(
<ide> 'Warning: ref.measureLayout must be called with a node handle or a ref to a native component.',
<ide> );
<ide> }
<ide> export default function(
<ide>
<ide> if (maybeInstance.canonical) {
<ide> if (__DEV__) {
<del> warning(
<add> console.error(
<ide> 'Warning: setNativeProps is not currently supported in Fabric',
<ide> );
<ide> }
<ide><path>packages/react-native-renderer/src/ReactNativeEventEmitter.js
<ide> import {
<ide> } from 'legacy-events/EventPluginHub';
<ide> import {registrationNameModules} from 'legacy-events/EventPluginRegistry';
<ide> import {batchedUpdates} from 'legacy-events/ReactGenericBatching';
<del>import warning from 'shared/warning';
<ide> import {enableNativeTargetAsInstance} from 'shared/ReactFeatureFlags';
<ide>
<ide> import {getInstanceFromNode} from './ReactNativeComponentTree';
<ide> export function receiveTouches(
<ide> if (target !== null && target !== undefined) {
<ide> if (target < 1) {
<ide> if (__DEV__) {
<del> warning('A view is reporting that a touch occurred on tag zero.');
<add> console.error(
<add> 'A view is reporting that a touch occurred on tag zero.',
<add> );
<ide> }
<ide> } else {
<ide> rootNodeID = target;
<ide><path>packages/react-native-renderer/src/ReactNativeFiberHostComponent.js
<ide> import {
<ide> warnForStyleProps,
<ide> } from './NativeMethodsMixinUtils';
<ide>
<del>import warning from 'shared/warning';
<del>
<ide> /**
<ide> * This component defines the same methods as NativeMethodsMixin but without the
<ide> * findNodeHandle wrapper. This wrapper is unnecessary for HostComponent views
<ide> class ReactNativeFiberHostComponent {
<ide>
<ide> if (relativeNode == null) {
<ide> if (__DEV__) {
<del> warning(
<add> console.error(
<ide> 'Warning: ref.measureLayout must be called with a node handle or a ref to a native component.',
<ide> );
<ide> }
<ide><path>packages/react-native-renderer/src/ReactNativeRenderer.js
<ide> import {getInspectorDataForViewTag} from './ReactNativeFiberInspector';
<ide> import {LegacyRoot} from 'shared/ReactRootTags';
<ide> import ReactSharedInternals from 'shared/ReactSharedInternals';
<ide> import getComponentName from 'shared/getComponentName';
<del>import warning from 'shared/warning';
<ide>
<ide> const ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
<ide>
<ide> function findHostInstance_DEPRECATED(
<ide> const owner = ReactCurrentOwner.current;
<ide> if (owner !== null && owner.stateNode !== null) {
<ide> if (!owner.stateNode._warnedAboutRefsInRender) {
<del> warning(
<add> console.error(
<ide> '%s is accessing findNodeHandle inside its render(). ' +
<ide> 'render() should be a pure function of props and state. It should ' +
<ide> 'never access something that requires stale data from the previous ' +
<ide> function findNodeHandle(componentOrHandle: any): ?number {
<ide> const owner = ReactCurrentOwner.current;
<ide> if (owner !== null && owner.stateNode !== null) {
<ide> if (!owner.stateNode._warnedAboutRefsInRender) {
<del> warning(
<add> console.error(
<ide> '%s is accessing findNodeHandle inside its render(). ' +
<ide> 'render() should be a pure function of props and state. It should ' +
<ide> 'never access something that requires stale data from the previous ' +
<ide> const ReactNativeRenderer: ReactNativeType = {
<ide> if (handle._nativeTag == null) {
<ide> if (__DEV__) {
<ide> if (handle._nativeTag == null) {
<del> warning(
<add> console.error(
<ide> "dispatchCommand was called with a ref that isn't a " +
<ide> 'native component. Use React.forwardRef to get access to the underlying native component',
<ide> );
<ide><path>packages/react-noop-renderer/src/createReactNoop.js
<ide> import {createPortal} from 'shared/ReactPortal';
<ide> import {REACT_FRAGMENT_TYPE, REACT_ELEMENT_TYPE} from 'shared/ReactSymbols';
<ide> import enqueueTask from 'shared/enqueueTask';
<ide> import ReactSharedInternals from 'shared/ReactSharedInternals';
<del>import warning from 'shared/warning';
<ide> import {ConcurrentRoot, BlockingRoot, LegacyRoot} from 'shared/ReactRootTags';
<ide>
<ide> type Container = {
<ide> function createReactNoop(reconciler: Function, useMutation: boolean) {
<ide> if (!__DEV__) {
<ide> if (didWarnAboutUsingActInProd === false) {
<ide> didWarnAboutUsingActInProd = true;
<add> // eslint-disable-next-line react-internal/no-production-logging
<ide> console.error(
<ide> 'act(...) is not supported in production builds of React, and might not behave as expected.',
<ide> );
<ide> function createReactNoop(reconciler: Function, useMutation: boolean) {
<ide> if (__DEV__) {
<ide> if (actingUpdatesScopeDepth > previousActingUpdatesScopeDepth) {
<ide> // if it's _less than_ previousActingUpdatesScopeDepth, then we can assume the 'other' one has warned
<del> warning(
<add> console.error(
<ide> 'You seem to have overlapping act() calls, this is not supported. ' +
<ide> 'Be sure to await previous act() calls before making a new one. ',
<ide> );
<ide> function createReactNoop(reconciler: Function, useMutation: boolean) {
<ide> .then(() => {})
<ide> .then(() => {
<ide> if (called === false) {
<del> warning(
<add> console.error(
<ide> 'You called act(async () => ...) without await. ' +
<ide> 'This could lead to unexpected testing behaviour, interleaving multiple act ' +
<ide> 'calls and mixing their scopes. You should - await act(async () => ...);',
<ide> function createReactNoop(reconciler: Function, useMutation: boolean) {
<ide> } else {
<ide> if (__DEV__) {
<ide> if (result !== undefined) {
<del> warning(
<add> console.error(
<ide> 'The callback passed to act(...) function ' +
<ide> 'must return undefined, or a Promise. You returned %s',
<ide> result,
<ide> function createReactNoop(reconciler: Function, useMutation: boolean) {
<ide> return {
<ide> then(resolve: () => void) {
<ide> if (__DEV__) {
<del> warning(
<add> console.error(
<ide> 'Do not await the result of calling act(...) with sync logic, it is not a Promise.',
<ide> );
<ide> }
<ide> function createReactNoop(reconciler: Function, useMutation: boolean) {
<ide> const root = roots.get(rootID);
<ide> const rootContainer = rootContainers.get(rootID);
<ide> if (!root || !rootContainer) {
<add> // eslint-disable-next-line react-internal/no-production-logging
<ide> console.log('Nothing rendered yet.');
<ide> return;
<ide> }
<ide> function createReactNoop(reconciler: Function, useMutation: boolean) {
<ide> log('FIBERS:');
<ide> logFiber(root.current, 0);
<ide>
<add> // eslint-disable-next-line react-internal/no-production-logging
<ide> console.log(...bufferedLog);
<ide> },
<ide>
<ide><path>packages/react-reconciler/src/ReactChildFiber.js
<ide> import {
<ide> Fragment,
<ide> } from 'shared/ReactWorkTags';
<ide> import invariant from 'shared/invariant';
<del>import warning from 'shared/warning';
<ide> import {warnAboutStringRefs} from 'shared/ReactFeatureFlags';
<ide>
<ide> import {
<ide> if (__DEV__) {
<ide> }
<ide> ownerHasKeyUseWarning[currentComponentErrorInfo] = true;
<ide>
<del> warning(
<add> console.error(
<ide> 'Each child in a list should have a unique ' +
<ide> '"key" prop. See https://fb.me/react-warning-keys for ' +
<ide> 'more information.',
<ide> function coerceRef(
<ide> const componentName = getComponentName(returnFiber.type) || 'Component';
<ide> if (!didWarnAboutStringRefs[componentName]) {
<ide> if (warnAboutStringRefs) {
<del> warning(
<add> console.error(
<ide> 'Component "%s" contains the string ref "%s". Support for string refs ' +
<ide> 'will be removed in a future major release. We recommend using ' +
<ide> 'useRef() or createRef() instead. ' +
<ide> function coerceRef(
<ide> getStackByFiberInDevAndProd(returnFiber),
<ide> );
<ide> } else {
<del> warning(
<add> console.error(
<ide> 'A string ref, "%s", has been found within a strict mode tree. ' +
<ide> 'String refs are a source of potential bugs and should be avoided. ' +
<ide> 'We recommend using useRef() or createRef() instead. ' +
<ide> function warnOnFunctionType() {
<ide> }
<ide> ownerHasFunctionTypeWarning[currentComponentErrorInfo] = true;
<ide>
<del> warning(
<add> console.error(
<ide> 'Functions are not valid as a React child. This may happen if ' +
<ide> 'you return a Component instead of <Component /> from render. ' +
<ide> 'Or maybe you meant to call this function rather than return it.',
<ide> function ChildReconciler(shouldTrackSideEffects) {
<ide> knownKeys.add(key);
<ide> break;
<ide> }
<del> warning(
<add> console.error(
<ide> 'Encountered two children with the same key, `%s`. ' +
<ide> 'Keys should be unique so that components maintain their identity ' +
<ide> 'across updates. Non-unique keys may cause children to be ' +
<ide> function ChildReconciler(shouldTrackSideEffects) {
<ide> newChildrenIterable[Symbol.toStringTag] === 'Generator'
<ide> ) {
<ide> if (!didWarnAboutGenerators) {
<del> warning(
<add> console.error(
<ide> 'Using Generators as children is unsupported and will likely yield ' +
<ide> 'unexpected results because enumerating a generator mutates it. ' +
<ide> 'You may convert it to an array with `Array.from()` or the ' +
<ide> function ChildReconciler(shouldTrackSideEffects) {
<ide> // Warn about using Maps as children
<ide> if ((newChildrenIterable: any).entries === iteratorFn) {
<ide> if (!didWarnAboutMaps) {
<del> warning(
<add> console.error(
<ide> 'Using Maps as children is unsupported and will likely yield ' +
<ide> 'unexpected results. Convert it to a sequence/iterable of keyed ' +
<ide> 'ReactElements instead.',
<ide><path>packages/react-reconciler/src/ReactFiber.js
<ide> import type {HookType} from './ReactFiberHooks';
<ide> import type {SuspenseInstance} from './ReactFiberHostConfig';
<ide>
<ide> import invariant from 'shared/invariant';
<del>import warning from 'shared/warning';
<ide> import {
<ide> enableProfilerTimer,
<ide> enableFundamentalAPI,
<ide> function createFiberFromProfiler(
<ide> typeof pendingProps.id !== 'string' ||
<ide> typeof pendingProps.onRender !== 'function'
<ide> ) {
<del> warning(
<add> console.error(
<ide> 'Profiler must specify an "id" string and "onRender" function as props',
<ide> );
<ide> }
<ide><path>packages/react-reconciler/src/ReactFiberBeginWork.js
<ide> import getComponentName from 'shared/getComponentName';
<ide> import ReactStrictModeWarnings from './ReactStrictModeWarnings';
<ide> import {refineResolvedLazyComponent} from 'shared/ReactLazyComponent';
<ide> import {REACT_LAZY_TYPE, getIteratorFn} from 'shared/ReactSymbols';
<del>import warning from 'shared/warning';
<ide> import {
<ide> setCurrentPhase,
<ide> getCurrentFiberOwnerNameInDevOrNull,
<ide> function updateClassComponent(
<ide> let inst = workInProgress.stateNode;
<ide> if (inst.props !== nextProps) {
<ide> if (!didWarnAboutReassigningProps) {
<del> warning(
<add> console.error(
<ide> 'It looks like %s is reassigning its own `this.props` while rendering. ' +
<ide> 'This is not supported and can lead to confusing bugs.',
<ide> getComponentName(workInProgress.type) || 'a component',
<ide> function mountIndeterminateComponent(
<ide> const componentName = getComponentName(Component) || 'Unknown';
<ide>
<ide> if (!didWarnAboutBadClass[componentName]) {
<del> warning(
<add> console.error(
<ide> "The <%s /> component appears to have a render method, but doesn't extend React.Component. " +
<ide> 'This is likely to cause errors. Change %s to extend React.Component instead.',
<ide> componentName,
<ide> function mountIndeterminateComponent(
<ide> if (__DEV__) {
<ide> const componentName = getComponentName(Component) || 'Unknown';
<ide> if (!didWarnAboutModulePatternComponent[componentName]) {
<del> warning(
<add> console.error(
<ide> 'The <%s /> component appears to be a function component that returns a class instance. ' +
<ide> 'Change %s to a class that extends React.Component instead. ' +
<ide> "If you can't use a class try assigning the prototype on the function as a workaround. " +
<ide> function mountIndeterminateComponent(
<ide> workInProgress.tag = FunctionComponent;
<ide> if (__DEV__) {
<ide> if (disableLegacyContext && Component.contextTypes) {
<del> warning(
<add> console.error(
<ide> '%s uses the legacy contextTypes API which is no longer supported. ' +
<ide> 'Use React.createContext() with React.useContext() instead.',
<ide> getComponentName(Component) || 'Unknown',
<ide> function validateFunctionComponentInDev(workInProgress: Fiber, Component: any) {
<ide> if (__DEV__) {
<ide> if (Component) {
<ide> if (Component.childContextTypes) {
<del> warning(
<add> console.error(
<ide> '%s(...): childContextTypes cannot be defined on a function component.',
<ide> Component.displayName || Component.name || 'Component',
<ide> );
<ide> function validateFunctionComponentInDev(workInProgress: Fiber, Component: any) {
<ide> }
<ide> if (!didWarnAboutFunctionRefs[warningKey]) {
<ide> didWarnAboutFunctionRefs[warningKey] = true;
<del> warning(
<add> console.error(
<ide> 'Function components cannot be given refs. ' +
<ide> 'Attempts to access this ref will fail. ' +
<ide> 'Did you mean to use React.forwardRef()?%s',
<ide> function validateFunctionComponentInDev(workInProgress: Fiber, Component: any) {
<ide> const componentName = getComponentName(Component) || 'Unknown';
<ide>
<ide> if (!didWarnAboutDefaultPropsOnFunctionComponent[componentName]) {
<del> warning(
<add> console.error(
<ide> '%s: Support for defaultProps will be removed from function components ' +
<ide> 'in a future major release. Use JavaScript default parameters instead.',
<ide> componentName,
<ide> function validateFunctionComponentInDev(workInProgress: Fiber, Component: any) {
<ide> const componentName = getComponentName(Component) || 'Unknown';
<ide>
<ide> if (!didWarnAboutGetDerivedStateOnFunctionComponent[componentName]) {
<del> warning(
<add> console.error(
<ide> '%s: Function components do not support getDerivedStateFromProps.',
<ide> componentName,
<ide> );
<ide> function validateFunctionComponentInDev(workInProgress: Fiber, Component: any) {
<ide> const componentName = getComponentName(Component) || 'Unknown';
<ide>
<ide> if (!didWarnAboutContextTypeOnFunctionComponent[componentName]) {
<del> warning(
<add> console.error(
<ide> '%s: Function components do not support contextType.',
<ide> componentName,
<ide> );
<ide> function updateSuspenseComponent(
<ide> if ('maxDuration' in nextProps) {
<ide> if (!didWarnAboutMaxDuration) {
<ide> didWarnAboutMaxDuration = true;
<del> warning(
<add> console.error(
<ide> 'maxDuration has been removed from React. ' +
<ide> 'Remove the maxDuration prop.',
<ide> );
<ide> function mountDehydratedSuspenseComponent(
<ide> // Instead, we'll leave the content in place and try to hydrate it later.
<ide> if ((workInProgress.mode & BlockingMode) === NoMode) {
<ide> if (__DEV__) {
<del> warning(
<add> console.error(
<ide> 'Cannot hydrate Suspense in legacy mode. Switch from ' +
<ide> 'ReactDOM.hydrate(element, container) to ' +
<ide> 'ReactDOM.createBlockingRoot(container, { hydrate: true })' +
<ide> function validateRevealOrder(revealOrder: SuspenseListRevealOrder) {
<ide> case 'together':
<ide> case 'forwards':
<ide> case 'backwards': {
<del> warning(
<add> console.error(
<ide> '"%s" is not a valid value for revealOrder on <SuspenseList />. ' +
<ide> 'Use lowercase "%s" instead.',
<ide> revealOrder,
<ide> function validateRevealOrder(revealOrder: SuspenseListRevealOrder) {
<ide> }
<ide> case 'forward':
<ide> case 'backward': {
<del> warning(
<add> console.error(
<ide> '"%s" is not a valid value for revealOrder on <SuspenseList />. ' +
<ide> 'React uses the -s suffix in the spelling. Use "%ss" instead.',
<ide> revealOrder,
<ide> function validateRevealOrder(revealOrder: SuspenseListRevealOrder) {
<ide> break;
<ide> }
<ide> default:
<del> warning(
<add> console.error(
<ide> '"%s" is not a supported revealOrder on <SuspenseList />. ' +
<ide> 'Did you mean "together", "forwards" or "backwards"?',
<ide> revealOrder,
<ide> );
<ide> break;
<ide> }
<ide> } else {
<del> warning(
<add> console.error(
<ide> '%s is not a supported value for revealOrder on <SuspenseList />. ' +
<ide> 'Did you mean "together", "forwards" or "backwards"?',
<ide> revealOrder,
<ide> function validateTailOptions(
<ide> if (tailMode !== undefined && !didWarnAboutTailOptions[tailMode]) {
<ide> if (tailMode !== 'collapsed' && tailMode !== 'hidden') {
<ide> didWarnAboutTailOptions[tailMode] = true;
<del> warning(
<add> console.error(
<ide> '"%s" is not a supported value for tail on <SuspenseList />. ' +
<ide> 'Did you mean "collapsed" or "hidden"?',
<ide> tailMode,
<ide> );
<ide> } else if (revealOrder !== 'forwards' && revealOrder !== 'backwards') {
<ide> didWarnAboutTailOptions[tailMode] = true;
<del> warning(
<add> console.error(
<ide> '<SuspenseList tail="%s" /> is only valid if revealOrder is ' +
<ide> '"forwards" or "backwards". ' +
<ide> 'Did you mean to specify revealOrder="forwards"?',
<ide> function validateSuspenseListNestedChild(childSlot: mixed, index: number) {
<ide> let isIterable = !isArray && typeof getIteratorFn(childSlot) === 'function';
<ide> if (isArray || isIterable) {
<ide> let type = isArray ? 'array' : 'iterable';
<del> warning(
<add> console.error(
<ide> 'A nested %s was passed to row #%s in <SuspenseList />. Wrap it in ' +
<ide> 'an additional SuspenseList to configure its revealOrder: ' +
<ide> '<SuspenseList revealOrder=...> ... ' +
<ide> function validateSuspenseListChildren(
<ide> }
<ide> }
<ide> } else {
<del> warning(
<add> console.error(
<ide> 'A single row was passed to a <SuspenseList revealOrder="%s" />. ' +
<ide> 'This is not useful since it needs multiple rows. ' +
<ide> 'Did you mean to pass multiple children or an array?',
<ide> function updateContextConsumer(
<ide> if (context !== context.Consumer) {
<ide> if (!hasWarnedAboutUsingContextAsConsumer) {
<ide> hasWarnedAboutUsingContextAsConsumer = true;
<del> warning(
<add> console.error(
<ide> 'Rendering <Context> directly is not supported and will be removed in ' +
<ide> 'a future major release. Did you mean to render <Context.Consumer> instead?',
<ide> );
<ide> function updateContextConsumer(
<ide>
<ide> if (__DEV__) {
<ide> if (typeof render !== 'function') {
<del> warning(
<add> console.error(
<ide> 'A context consumer was rendered with multiple children, or a child ' +
<ide> "that isn't a function. A context consumer expects a single child " +
<ide> 'that is a function. If you did pass a function, make sure there ' +
<ide><path>packages/react-reconciler/src/ReactFiberClassComponent.js
<ide> import {get as getInstance, set as setInstance} from 'shared/ReactInstanceMap';
<ide> import shallowEqual from 'shared/shallowEqual';
<ide> import getComponentName from 'shared/getComponentName';
<ide> import invariant from 'shared/invariant';
<del>import warning from 'shared/warning';
<ide> import {REACT_CONTEXT_TYPE, REACT_PROVIDER_TYPE} from 'shared/ReactSymbols';
<ide>
<ide> import {startPhaseTimer, stopPhaseTimer} from './ReactDebugFiberPerf';
<ide> if (__DEV__) {
<ide> const key = `${callerName}_${(callback: any)}`;
<ide> if (!didWarnOnInvalidCallback.has(key)) {
<ide> didWarnOnInvalidCallback.add(key);
<del> warning(
<add> console.error(
<ide> '%s(...): Expected the last optional `callback` argument to be a ' +
<ide> 'function. Instead received: %s.',
<ide> callerName,
<ide> if (__DEV__) {
<ide> const componentName = getComponentName(type) || 'Component';
<ide> if (!didWarnAboutUndefinedDerivedState.has(componentName)) {
<ide> didWarnAboutUndefinedDerivedState.add(componentName);
<del> warning(
<add> console.error(
<ide> '%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' +
<ide> 'You have returned undefined.',
<ide> componentName,
<ide> function checkShouldComponentUpdate(
<ide>
<ide> if (__DEV__) {
<ide> if (shouldUpdate === undefined) {
<del> warning(
<add> console.error(
<ide> '%s.shouldComponentUpdate(): Returned undefined instead of a ' +
<ide> 'boolean value. Make sure to return true or false.',
<ide> getComponentName(ctor) || 'Component',
<ide> function checkClassInstance(workInProgress: Fiber, ctor: any, newProps: any) {
<ide>
<ide> if (!renderPresent) {
<ide> if (ctor.prototype && typeof ctor.prototype.render === 'function') {
<del> warning(
<add> console.error(
<ide> '%s(...): No `render` method found on the returned component ' +
<ide> 'instance: did you accidentally return an object from the constructor?',
<ide> name,
<ide> );
<ide> } else {
<del> warning(
<add> console.error(
<ide> '%s(...): No `render` method found on the returned component ' +
<ide> 'instance: you may have forgotten to define `render`.',
<ide> name,
<ide> function checkClassInstance(workInProgress: Fiber, ctor: any, newProps: any) {
<ide> !instance.getInitialState.isReactClassApproved &&
<ide> !instance.state
<ide> ) {
<del> warning(
<add> console.error(
<ide> 'getInitialState was defined on %s, a plain JavaScript class. ' +
<ide> 'This is only supported for classes created using React.createClass. ' +
<ide> 'Did you mean to define a state property instead?',
<ide> function checkClassInstance(workInProgress: Fiber, ctor: any, newProps: any) {
<ide> instance.getDefaultProps &&
<ide> !instance.getDefaultProps.isReactClassApproved
<ide> ) {
<del> warning(
<add> console.error(
<ide> 'getDefaultProps was defined on %s, a plain JavaScript class. ' +
<ide> 'This is only supported for classes created using React.createClass. ' +
<ide> 'Use a static property to define defaultProps instead.',
<ide> name,
<ide> );
<ide> }
<ide> if (instance.propTypes) {
<del> warning(
<add> console.error(
<ide> 'propTypes was defined as an instance property on %s. Use a static ' +
<ide> 'property to define propTypes instead.',
<ide> name,
<ide> );
<ide> }
<ide> if (instance.contextType) {
<del> warning(
<add> console.error(
<ide> 'contextType was defined as an instance property on %s. Use a static ' +
<ide> 'property to define contextType instead.',
<ide> name,
<ide> function checkClassInstance(workInProgress: Fiber, ctor: any, newProps: any) {
<ide>
<ide> if (disableLegacyContext) {
<ide> if (ctor.childContextTypes) {
<del> warning(
<add> console.error(
<ide> '%s uses the legacy childContextTypes API which is no longer supported. ' +
<ide> 'Use React.createContext() instead.',
<ide> name,
<ide> );
<ide> }
<ide> if (ctor.contextTypes) {
<del> warning(
<add> console.error(
<ide> '%s uses the legacy contextTypes API which is no longer supported. ' +
<ide> 'Use React.createContext() with static contextType instead.',
<ide> name,
<ide> );
<ide> }
<ide> } else {
<ide> if (instance.contextTypes) {
<del> warning(
<add> console.error(
<ide> 'contextTypes was defined as an instance property on %s. Use a static ' +
<ide> 'property to define contextTypes instead.',
<ide> name,
<ide> function checkClassInstance(workInProgress: Fiber, ctor: any, newProps: any) {
<ide> !didWarnAboutContextTypeAndContextTypes.has(ctor)
<ide> ) {
<ide> didWarnAboutContextTypeAndContextTypes.add(ctor);
<del> warning(
<add> console.error(
<ide> '%s declares both contextTypes and contextType static properties. ' +
<ide> 'The legacy contextTypes property will be ignored.',
<ide> name,
<ide> function checkClassInstance(workInProgress: Fiber, ctor: any, newProps: any) {
<ide> }
<ide>
<ide> if (typeof instance.componentShouldUpdate === 'function') {
<del> warning(
<add> console.error(
<ide> '%s has a method called ' +
<ide> 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' +
<ide> 'The name is phrased as a question because the function is ' +
<ide> function checkClassInstance(workInProgress: Fiber, ctor: any, newProps: any) {
<ide> ctor.prototype.isPureReactComponent &&
<ide> typeof instance.shouldComponentUpdate !== 'undefined'
<ide> ) {
<del> warning(
<add> console.error(
<ide> '%s has a method called shouldComponentUpdate(). ' +
<ide> 'shouldComponentUpdate should not be used when extending React.PureComponent. ' +
<ide> 'Please extend React.Component if shouldComponentUpdate is used.',
<ide> getComponentName(ctor) || 'A pure component',
<ide> );
<ide> }
<ide> if (typeof instance.componentDidUnmount === 'function') {
<del> warning(
<add> console.error(
<ide> '%s has a method called ' +
<ide> 'componentDidUnmount(). But there is no such lifecycle method. ' +
<ide> 'Did you mean componentWillUnmount()?',
<ide> name,
<ide> );
<ide> }
<ide> if (typeof instance.componentDidReceiveProps === 'function') {
<del> warning(
<add> console.error(
<ide> '%s has a method called ' +
<ide> 'componentDidReceiveProps(). But there is no such lifecycle method. ' +
<ide> 'If you meant to update the state in response to changing props, ' +
<ide> function checkClassInstance(workInProgress: Fiber, ctor: any, newProps: any) {
<ide> );
<ide> }
<ide> if (typeof instance.componentWillRecieveProps === 'function') {
<del> warning(
<add> console.error(
<ide> '%s has a method called ' +
<ide> 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?',
<ide> name,
<ide> );
<ide> }
<ide> if (typeof instance.UNSAFE_componentWillRecieveProps === 'function') {
<del> warning(
<add> console.error(
<ide> '%s has a method called ' +
<ide> 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?',
<ide> name,
<ide> );
<ide> }
<ide> const hasMutatedProps = instance.props !== newProps;
<ide> if (instance.props !== undefined && hasMutatedProps) {
<del> warning(
<add> console.error(
<ide> '%s(...): When calling super() in `%s`, make sure to pass ' +
<ide> "up the same props that your component's constructor was passed.",
<ide> name,
<ide> name,
<ide> );
<ide> }
<ide> if (instance.defaultProps) {
<del> warning(
<add> console.error(
<ide> 'Setting defaultProps as an instance property on %s is not supported and will be ignored.' +
<ide> ' Instead, define defaultProps as a static property on %s.',
<ide> name,
<ide> function checkClassInstance(workInProgress: Fiber, ctor: any, newProps: any) {
<ide> !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)
<ide> ) {
<ide> didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor);
<del> warning(
<add> console.error(
<ide> '%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' +
<ide> 'This component defines getSnapshotBeforeUpdate() only.',
<ide> getComponentName(ctor),
<ide> );
<ide> }
<ide>
<ide> if (typeof instance.getDerivedStateFromProps === 'function') {
<del> warning(
<add> console.error(
<ide> '%s: getDerivedStateFromProps() is defined as an instance method ' +
<ide> 'and will be ignored. Instead, declare it as a static method.',
<ide> name,
<ide> );
<ide> }
<ide> if (typeof instance.getDerivedStateFromError === 'function') {
<del> warning(
<add> console.error(
<ide> '%s: getDerivedStateFromError() is defined as an instance method ' +
<ide> 'and will be ignored. Instead, declare it as a static method.',
<ide> name,
<ide> );
<ide> }
<ide> if (typeof ctor.getSnapshotBeforeUpdate === 'function') {
<del> warning(
<add> console.error(
<ide> '%s: getSnapshotBeforeUpdate() is defined as a static method ' +
<ide> 'and will be ignored. Instead, declare it as an instance method.',
<ide> name,
<ide> );
<ide> }
<ide> const state = instance.state;
<ide> if (state && (typeof state !== 'object' || isArray(state))) {
<del> warning('%s.state: must be set to an object or null', name);
<add> console.error('%s.state: must be set to an object or null', name);
<ide> }
<ide> if (
<ide> typeof instance.getChildContext === 'function' &&
<ide> typeof ctor.childContextTypes !== 'object'
<ide> ) {
<del> warning(
<add> console.error(
<ide> '%s.getChildContext(): childContextTypes must be defined in order to ' +
<ide> 'use getChildContext().',
<ide> name,
<ide> function constructClassInstance(
<ide> Object.keys(contextType).join(', ') +
<ide> '}.';
<ide> }
<del> warning(
<add> console.error(
<ide> '%s defines an invalid contextType. ' +
<ide> 'contextType should point to the Context object returned by React.createContext().%s',
<ide> getComponentName(ctor) || 'Component',
<ide> function constructClassInstance(
<ide> const componentName = getComponentName(ctor) || 'Component';
<ide> if (!didWarnAboutUninitializedState.has(componentName)) {
<ide> didWarnAboutUninitializedState.add(componentName);
<del> warning(
<add> console.error(
<ide> '`%s` uses `getDerivedStateFromProps` but its initial state is ' +
<ide> '%s. This is not recommended. Instead, define the initial state by ' +
<ide> 'assigning an object to `this.state` in the constructor of `%s`. ' +
<ide> function constructClassInstance(
<ide> : 'getSnapshotBeforeUpdate()';
<ide> if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(componentName)) {
<ide> didWarnAboutLegacyLifecyclesAndDerivedState.add(componentName);
<del> warning(
<add> console.error(
<ide> 'Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n' +
<ide> '%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n' +
<ide> 'The above lifecycles should be removed. Learn more about this warning here:\n' +
<ide> function callComponentWillMount(workInProgress, instance) {
<ide>
<ide> if (oldState !== instance.state) {
<ide> if (__DEV__) {
<del> warning(
<add> console.error(
<ide> '%s.componentWillMount(): Assigning directly to this.state is ' +
<ide> "deprecated (except inside a component's " +
<ide> 'constructor). Use setState instead.',
<ide> function callComponentWillReceiveProps(
<ide> getComponentName(workInProgress.type) || 'Component';
<ide> if (!didWarnAboutStateAssignmentForComponent.has(componentName)) {
<ide> didWarnAboutStateAssignmentForComponent.add(componentName);
<del> warning(
<add> console.error(
<ide> '%s.componentWillReceiveProps(): Assigning directly to ' +
<ide> "this.state is deprecated (except inside a component's " +
<ide> 'constructor). Use setState instead.',
<ide> function mountClassInstance(
<ide> const componentName = getComponentName(ctor) || 'Component';
<ide> if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) {
<ide> didWarnAboutDirectlyAssigningPropsToState.add(componentName);
<del> warning(
<add> console.error(
<ide> '%s: It is not recommended to assign props directly to state ' +
<ide> "because updates to props won't be reflected in state. " +
<ide> 'In most cases, it is better to use props directly.',
<ide><path>packages/react-reconciler/src/ReactFiberCommitWork.js
<ide> import {
<ide> } from 'shared/ReactSideEffectTags';
<ide> import getComponentName from 'shared/getComponentName';
<ide> import invariant from 'shared/invariant';
<del>import warning from 'shared/warning';
<ide>
<ide> import {onCommitUnmount} from './ReactFiberDevToolsHook';
<ide> import {startPhaseTimer, stopPhaseTimer} from './ReactDebugFiberPerf';
<ide> function commitBeforeMutationLifeCycles(
<ide> !didWarnAboutReassigningProps
<ide> ) {
<ide> if (instance.props !== finishedWork.memoizedProps) {
<del> warning(
<add> console.error(
<ide> 'Expected %s props to match memoized props before ' +
<ide> 'getSnapshotBeforeUpdate. ' +
<ide> 'This might either be because of a bug in React, or because ' +
<ide> function commitBeforeMutationLifeCycles(
<ide> );
<ide> }
<ide> if (instance.state !== finishedWork.memoizedState) {
<del> warning(
<add> console.error(
<ide> 'Expected %s state to match memoized state before ' +
<ide> 'getSnapshotBeforeUpdate. ' +
<ide> 'This might either be because of a bug in React, or because ' +
<ide> function commitBeforeMutationLifeCycles(
<ide> >);
<ide> if (snapshot === undefined && !didWarnSet.has(finishedWork.type)) {
<ide> didWarnSet.add(finishedWork.type);
<del> warning(
<add> console.error(
<ide> '%s.getSnapshotBeforeUpdate(): A snapshot value (or null) ' +
<ide> 'must be returned. You have returned undefined.',
<ide> getComponentName(finishedWork.type),
<ide> function commitHookEffectList(
<ide> } else {
<ide> addendum = ' You returned: ' + destroy;
<ide> }
<del> warning(
<add> console.error(
<ide> 'An effect function must not return anything besides a function, ' +
<ide> 'which is used for clean-up.%s%s',
<ide> addendum,
<ide> function commitLifeCycles(
<ide> !didWarnAboutReassigningProps
<ide> ) {
<ide> if (instance.props !== finishedWork.memoizedProps) {
<del> warning(
<add> console.error(
<ide> 'Expected %s props to match memoized props before ' +
<ide> 'componentDidMount. ' +
<ide> 'This might either be because of a bug in React, or because ' +
<ide> function commitLifeCycles(
<ide> );
<ide> }
<ide> if (instance.state !== finishedWork.memoizedState) {
<del> warning(
<add> console.error(
<ide> 'Expected %s state to match memoized state before ' +
<ide> 'componentDidMount. ' +
<ide> 'This might either be because of a bug in React, or because ' +
<ide> function commitLifeCycles(
<ide> !didWarnAboutReassigningProps
<ide> ) {
<ide> if (instance.props !== finishedWork.memoizedProps) {
<del> warning(
<add> console.error(
<ide> 'Expected %s props to match memoized props before ' +
<ide> 'componentDidUpdate. ' +
<ide> 'This might either be because of a bug in React, or because ' +
<ide> function commitLifeCycles(
<ide> );
<ide> }
<ide> if (instance.state !== finishedWork.memoizedState) {
<del> warning(
<add> console.error(
<ide> 'Expected %s state to match memoized state before ' +
<ide> 'componentDidUpdate. ' +
<ide> 'This might either be because of a bug in React, or because ' +
<ide> function commitLifeCycles(
<ide> !didWarnAboutReassigningProps
<ide> ) {
<ide> if (instance.props !== finishedWork.memoizedProps) {
<del> warning(
<add> console.error(
<ide> 'Expected %s props to match memoized props before ' +
<ide> 'processing the update queue. ' +
<ide> 'This might either be because of a bug in React, or because ' +
<ide> function commitLifeCycles(
<ide> );
<ide> }
<ide> if (instance.state !== finishedWork.memoizedState) {
<del> warning(
<add> console.error(
<ide> 'Expected %s state to match memoized state before ' +
<ide> 'processing the update queue. ' +
<ide> 'This might either be because of a bug in React, or because ' +
<ide> function commitAttachRef(finishedWork: Fiber) {
<ide> } else {
<ide> if (__DEV__) {
<ide> if (!ref.hasOwnProperty('current')) {
<del> warning(
<add> console.error(
<ide> 'Unexpected ref object provided for %s. ' +
<ide> 'Use either a ref-setter function or React.createRef().%s',
<ide> getComponentName(finishedWork.type),
<ide> function commitSuspenseComponent(finishedWork: Fiber) {
<ide> }
<ide> } else if (__DEV__) {
<ide> if (suspenseCallback !== undefined) {
<del> warning('Unexpected type for suspenseCallback.');
<add> console.error('Unexpected type for suspenseCallback.');
<ide> }
<ide> }
<ide> }
<ide><path>packages/react-reconciler/src/ReactFiberContext.js
<ide> import {disableLegacyContext} from 'shared/ReactFeatureFlags';
<ide> import {ClassComponent, HostRoot} from 'shared/ReactWorkTags';
<ide> import getComponentName from 'shared/getComponentName';
<ide> import invariant from 'shared/invariant';
<del>import warning from 'shared/warning';
<ide> import checkPropTypes from 'prop-types/checkPropTypes';
<ide>
<ide> import {setCurrentPhase, getCurrentFiberStackInDev} from './ReactCurrentFiber';
<ide> function processChildContext(
<ide>
<ide> if (!warnedAboutMissingGetChildContext[componentName]) {
<ide> warnedAboutMissingGetChildContext[componentName] = true;
<del> warning(
<add> console.error(
<ide> '%s.childContextTypes is specified but there is no getChildContext() method ' +
<ide> 'on the instance. You can either define getChildContext() on %s or remove ' +
<ide> 'childContextTypes from it.',
<ide><path>packages/react-reconciler/src/ReactFiberDevToolsHook.js
<ide> import type {ExpirationTime} from './ReactFiberExpirationTime';
<ide> import type {ReactNodeList} from 'shared/ReactTypes';
<ide>
<ide> import {DidCapture} from 'shared/ReactSideEffectTags';
<del>import warning from 'shared/warning';
<ide>
<ide> declare var __REACT_DEVTOOLS_GLOBAL_HOOK__: Object | void;
<ide>
<ide> export function injectInternals(internals: Object): boolean {
<ide> }
<ide> if (!hook.supportsFiber) {
<ide> if (__DEV__) {
<del> warning(
<add> console.error(
<ide> 'The installed version of React DevTools is too old and will not work ' +
<ide> 'with the current version of React. Please update React DevTools. ' +
<ide> 'https://fb.me/react-devtools',
<ide> export function injectInternals(internals: Object): boolean {
<ide> } catch (err) {
<ide> if (__DEV__ && !hasLoggedError) {
<ide> hasLoggedError = true;
<del> warning('React instrumentation encountered an error: %s', err);
<add> console.error(
<add> 'React instrumentation encountered an error: %s',
<add> err,
<add> );
<ide> }
<ide> }
<ide> };
<ide> export function injectInternals(internals: Object): boolean {
<ide> if (__DEV__) {
<ide> if (!hasLoggedError) {
<ide> hasLoggedError = true;
<del> warning('React instrumentation encountered an error: %s', err);
<add> console.error(
<add> 'React instrumentation encountered an error: %s',
<add> err,
<add> );
<ide> }
<ide> }
<ide> }
<ide> export function injectInternals(internals: Object): boolean {
<ide> if (__DEV__) {
<ide> if (!hasLoggedError) {
<ide> hasLoggedError = true;
<del> warning('React instrumentation encountered an error: %s', err);
<add> console.error(
<add> 'React instrumentation encountered an error: %s',
<add> err,
<add> );
<ide> }
<ide> }
<ide> }
<ide> };
<ide> } catch (err) {
<ide> // Catch all errors because it is unsafe to throw during initialization.
<ide> if (__DEV__) {
<del> warning('React instrumentation encountered an error: %s.', err);
<add> console.error('React instrumentation encountered an error: %s.', err);
<ide> }
<ide> }
<ide> // DevTools exists
<ide><path>packages/react-reconciler/src/ReactFiberErrorLogger.js
<ide> export function logCapturedError(capturedError: CapturedError): void {
<ide> // been accidental, we'll surface it anyway.
<ide> // However, the browser would have silenced the original error
<ide> // so we'll print it first, and then print the stack addendum.
<del> console.error(error);
<add> console['error'](error); // Don't transform to our wrapper
<ide> // For a more detailed description of this block, see:
<ide> // https://github.com/facebook/react/pull/13384
<ide> }
<ide> export function logCapturedError(capturedError: CapturedError): void {
<ide> // We don't include the original error message and JS stack because the browser
<ide> // has already printed it. Even if the application swallows the error, it is still
<ide> // displayed by the browser thanks to the DEV-only fake event trick in ReactErrorUtils.
<del> console.error(combinedMessage);
<add> console['error'](combinedMessage); // Don't transform to our wrapper
<ide> } else {
<ide> // In production, we print the error directly.
<ide> // This will include the message, the JS stack, and anything the browser wants to show.
<ide> // We pass the error object instead of custom message so that the browser displays the error natively.
<del> console.error(error);
<add> console['error'](error); // Don't transform to our wrapper
<ide> }
<ide> }
<ide><path>packages/react-reconciler/src/ReactFiberEvents.js
<ide> import {
<ide> } from './ReactFiberHostConfig';
<ide> import {NoWork} from './ReactFiberExpirationTime';
<ide>
<del>import warning from 'shared/warning';
<ide> import {REACT_RESPONDER_TYPE} from 'shared/ReactSymbols';
<ide>
<ide> import invariant from 'shared/invariant';
<ide> function updateEventListener(
<ide> if (visistedResponders.has(responder)) {
<ide> // show warning
<ide> if (__DEV__) {
<del> warning(
<add> console.error(
<ide> 'Duplicate event responder "%s" found in event listeners. ' +
<ide> 'Event listeners passed to elements cannot use the same event responder more than once.',
<ide> responder.displayName,
<ide><path>packages/react-reconciler/src/ReactFiberHooks.js
<ide> import {
<ide> } from './ReactFiberWorkLoop';
<ide>
<ide> import invariant from 'shared/invariant';
<del>import warning from 'shared/warning';
<ide> import getComponentName from 'shared/getComponentName';
<ide> import is from 'shared/objectIs';
<ide> import {markWorkInProgressReceivedUpdate} from './ReactFiberBeginWork';
<ide> function checkDepsAreArrayDev(deps: mixed) {
<ide> if (deps !== undefined && deps !== null && !Array.isArray(deps)) {
<ide> // Verify deps, but only on mount to avoid extra checks.
<ide> // It's unlikely their type would change as usually you define them inline.
<del> warning(
<add> console.error(
<ide> '%s received a final argument that is not an array (instead, received `%s`). When ' +
<ide> 'specified, the final argument must be an array.',
<ide> currentHookNameInDev,
<ide> function warnOnHookMismatchInDev(currentHookName: HookType) {
<ide> table += row;
<ide> }
<ide>
<del> warning(
<add> console.error(
<ide> 'React has detected a change in the order of Hooks called by %s. ' +
<ide> 'This will lead to bugs and errors if not fixed. ' +
<ide> 'For more information, read the Rules of Hooks: https://fb.me/rules-of-hooks\n\n' +
<ide> function areHookInputsEqual(
<ide>
<ide> if (prevDeps === null) {
<ide> if (__DEV__) {
<del> warning(
<add> console.error(
<ide> '%s received a final argument during this render, but not during ' +
<ide> 'the previous render. Even though the final argument is optional, ' +
<ide> 'its type cannot change between renders.',
<ide> function areHookInputsEqual(
<ide> // Don't bother comparing lengths in prod because these arrays should be
<ide> // passed inline.
<ide> if (nextDeps.length !== prevDeps.length) {
<del> warning(
<add> console.error(
<ide> 'The final argument passed to %s changed size between renders. The ' +
<ide> 'order and size of this array must remain constant.\n\n' +
<ide> 'Previous: %s\n' +
<ide> function imperativeHandleEffect<T>(
<ide> const refObject = ref;
<ide> if (__DEV__) {
<ide> if (!refObject.hasOwnProperty('current')) {
<del> warning(
<add> console.error(
<ide> 'Expected useImperativeHandle() first argument to either be a ' +
<ide> 'ref callback or React.createRef() object. Instead received: %s.',
<ide> 'an object with keys {' + Object.keys(refObject).join(', ') + '}',
<ide> function mountImperativeHandle<T>(
<ide> ): void {
<ide> if (__DEV__) {
<ide> if (typeof create !== 'function') {
<del> warning(
<add> console.error(
<ide> 'Expected useImperativeHandle() second argument to be a function ' +
<ide> 'that creates a handle. Instead received: %s.',
<ide> create !== null ? typeof create : 'null',
<ide> function updateImperativeHandle<T>(
<ide> ): void {
<ide> if (__DEV__) {
<ide> if (typeof create !== 'function') {
<del> warning(
<add> console.error(
<ide> 'Expected useImperativeHandle() second argument to be a function ' +
<ide> 'that creates a handle. Instead received: %s.',
<ide> create !== null ? typeof create : 'null',
<ide> function dispatchAction<S, A>(
<ide> ) {
<ide> if (__DEV__) {
<ide> if (typeof arguments[3] === 'function') {
<del> warning(
<add> console.error(
<ide> "State updates from the useState() and useReducer() Hooks don't support the " +
<ide> 'second callback argument. To execute a side effect after ' +
<ide> 'rendering, declare it in the component body with useEffect().',
<ide> let InvalidNestedHooksDispatcherOnRerenderInDEV: Dispatcher | null = null;
<ide>
<ide> if (__DEV__) {
<ide> const warnInvalidContextAccess = () => {
<del> warning(
<add> console.error(
<ide> 'Context can only be read while React is rendering. ' +
<ide> 'In classes, you can read it in the render method or getDerivedStateFromProps. ' +
<ide> 'In function components, you can read it directly in the function body, but not ' +
<ide> if (__DEV__) {
<ide> };
<ide>
<ide> const warnInvalidHookAccess = () => {
<del> warning(
<add> console.error(
<ide> 'Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. ' +
<ide> 'You can only call Hooks at the top level of your React function. ' +
<ide> 'For more information, see ' +
<ide><path>packages/react-reconciler/src/ReactFiberHydrationContext.js
<ide> import {
<ide> didNotFindHydratableSuspenseInstance,
<ide> } from './ReactFiberHostConfig';
<ide> import {enableSuspenseServerRenderer} from 'shared/ReactFeatureFlags';
<del>import warning from 'shared/warning';
<ide> import {Never} from './ReactFiberExpirationTime';
<ide>
<ide> // The deepest Fiber on the stack involved in a hydration context.
<ide> let isHydrating: boolean = false;
<ide> function warnIfHydrating() {
<ide> if (__DEV__) {
<ide> if (isHydrating) {
<del> warning(
<add> console.error(
<ide> 'We should not be hydrating here. This is a bug in React. Please file a bug.',
<ide> );
<ide> }
<ide><path>packages/react-reconciler/src/ReactFiberNewContext.js
<ide> import {
<ide> } from 'shared/ReactWorkTags';
<ide>
<ide> import invariant from 'shared/invariant';
<del>import warning from 'shared/warning';
<ide> import is from 'shared/objectIs';
<ide> import {
<ide> createUpdate,
<ide> export function pushProvider<T>(providerFiber: Fiber, nextValue: T): void {
<ide> context._currentRenderer !== null &&
<ide> context._currentRenderer !== rendererSigil
<ide> ) {
<del> warning(
<add> console.error(
<ide> 'Detected multiple renderers concurrently rendering the ' +
<ide> 'same context provider. This is currently unsupported.',
<ide> );
<ide> export function pushProvider<T>(providerFiber: Fiber, nextValue: T): void {
<ide> context._currentRenderer2 !== null &&
<ide> context._currentRenderer2 !== rendererSigil
<ide> ) {
<del> warning(
<add> console.error(
<ide> 'Detected multiple renderers concurrently rendering the ' +
<ide> 'same context provider. This is currently unsupported.',
<ide> );
<ide> export function calculateChangedBits<T>(
<ide>
<ide> if (__DEV__) {
<ide> if ((changedBits & MAX_SIGNED_31_BIT_INT) !== changedBits) {
<del> warning(
<add> console.error(
<ide> 'calculateChangedBits: Expected the return value to be a ' +
<ide> '31-bit integer. Instead received: %s',
<ide> changedBits,
<ide> export function readContext<T>(
<ide> // This warning would fire if you read context inside a Hook like useMemo.
<ide> // Unlike the class check below, it's not enforced in production for perf.
<ide> if (isDisallowedContextReadInDEV) {
<del> warning(
<add> console.error(
<ide> 'Context can only be read while React is rendering. ' +
<ide> 'In classes, you can read it in the render method or getDerivedStateFromProps. ' +
<ide> 'In function components, you can read it directly in the function body, but not ' +
<ide><path>packages/react-reconciler/src/ReactFiberReconciler.js
<ide> import {
<ide> } from 'shared/ReactWorkTags';
<ide> import getComponentName from 'shared/getComponentName';
<ide> import invariant from 'shared/invariant';
<del>import warning from 'shared/warning';
<ide> import ReactSharedInternals from 'shared/ReactSharedInternals';
<ide>
<ide> import {getPublicInstance} from './ReactFiberHostConfig';
<ide> function findHostInstanceWithWarning(
<ide> if (!didWarnAboutFindNodeInStrictMode[componentName]) {
<ide> didWarnAboutFindNodeInStrictMode[componentName] = true;
<ide> if (fiber.mode & StrictMode) {
<del> warning(
<add> console.error(
<ide> '%s is deprecated in StrictMode. ' +
<ide> '%s was passed an instance of %s which is inside StrictMode. ' +
<ide> 'Instead, add a ref directly to the element you want to reference. ' +
<ide> function findHostInstanceWithWarning(
<ide> getStackByFiberInDevAndProd(hostFiber),
<ide> );
<ide> } else {
<del> warning(
<add> console.error(
<ide> '%s is deprecated in StrictMode. ' +
<ide> '%s was passed an instance of %s which renders StrictMode children. ' +
<ide> 'Instead, add a ref directly to the element you want to reference. ' +
<ide> export function updateContainer(
<ide> !didWarnAboutNestedUpdates
<ide> ) {
<ide> didWarnAboutNestedUpdates = true;
<del> warning(
<add> console.error(
<ide> 'Render methods should be a pure function of props and state; ' +
<ide> 'triggering nested component updates from render is not allowed. ' +
<ide> 'If necessary, trigger nested updates in componentDidUpdate.\n\n' +
<ide> export function updateContainer(
<ide> if (callback !== null) {
<ide> if (__DEV__) {
<ide> if (typeof callback !== 'function') {
<del> warning(
<add> console.error(
<ide> 'render(...): Expected the last optional `callback` argument to be a ' +
<ide> 'function. Instead received: %s.',
<ide> callback,
<ide><path>packages/react-reconciler/src/ReactFiberStack.js
<ide>
<ide> import type {Fiber} from './ReactFiber';
<ide>
<del>import warning from 'shared/warning';
<del>
<ide> export type StackCursor<T> = {
<ide> current: T,
<ide> };
<ide> function isEmpty(): boolean {
<ide> function pop<T>(cursor: StackCursor<T>, fiber: Fiber): void {
<ide> if (index < 0) {
<ide> if (__DEV__) {
<del> warning('Unexpected pop.');
<add> console.error('Unexpected pop.');
<ide> }
<ide> return;
<ide> }
<ide>
<ide> if (__DEV__) {
<ide> if (fiber !== fiberStack[index]) {
<del> warning('Unexpected Fiber popped.');
<add> console.error('Unexpected Fiber popped.');
<ide> }
<ide> }
<ide>
<ide> function push<T>(cursor: StackCursor<T>, value: T, fiber: Fiber): void {
<ide> function checkThatStackIsEmpty() {
<ide> if (__DEV__) {
<ide> if (index !== -1) {
<del> warning('Expected an empty stack. Something was not reset properly.');
<add> console.error(
<add> 'Expected an empty stack. Something was not reset properly.',
<add> );
<ide> }
<ide> }
<ide> }
<ide><path>packages/react-reconciler/src/ReactFiberThrow.js
<ide> import type {Thenable} from './ReactFiberWorkLoop';
<ide> import type {SuspenseContext} from './ReactFiberSuspenseContext';
<ide>
<ide> import getComponentName from 'shared/getComponentName';
<del>import warning from 'shared/warning';
<ide> import {
<ide> ClassComponent,
<ide> HostRoot,
<ide> function createClassErrorUpdate(
<ide> // then it needs to call setState to recover from errors.
<ide> // If no state update is scheduled then the boundary will swallow the error.
<ide> if (fiber.expirationTime !== Sync) {
<del> warning(
<add> console.error(
<ide> '%s: Error boundaries should implement getDerivedStateFromError(). ' +
<ide> 'In that method, return a state update to display an error message or fallback UI.',
<ide> getComponentName(fiber.type) || 'Unknown',
<ide><path>packages/react-reconciler/src/ReactFiberTreeReflection.js
<ide> import type {Container, SuspenseInstance} from './ReactFiberHostConfig';
<ide> import type {SuspenseState} from './ReactFiberSuspenseComponent';
<ide>
<ide> import invariant from 'shared/invariant';
<del>import warning from 'shared/warning';
<ide>
<ide> import {get as getInstance} from 'shared/ReactInstanceMap';
<ide> import ReactSharedInternals from 'shared/ReactSharedInternals';
<ide> export function isMounted(component: React$Component<any, any>): boolean {
<ide> const ownerFiber: Fiber = owner;
<ide> const instance = ownerFiber.stateNode;
<ide> if (!instance._warnedAboutRefsInRender) {
<del> warning(
<add> console.error(
<ide> '%s is accessing isMounted inside its render() function. ' +
<ide> 'render() should be a pure function of props and state. It should ' +
<ide> 'never access something that requires stale data from the previous ' +
<ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.js
<ide> import {
<ide> } from './ReactProfilerTimer';
<ide>
<ide> // DEV stuff
<del>import warning from 'shared/warning';
<ide> import getComponentName from 'shared/getComponentName';
<ide> import ReactStrictModeWarnings from './ReactStrictModeWarnings';
<ide> import {
<ide> export function flushDiscreteUpdates() {
<ide> ) {
<ide> if (__DEV__) {
<ide> if ((executionContext & RenderContext) !== NoContext) {
<del> warning(
<add> console.error(
<ide> 'unstable_flushDiscreteUpdates: Cannot flush updates when React is ' +
<ide> 'already rendering.',
<ide> );
<ide> function checkForNestedUpdates() {
<ide> if (__DEV__) {
<ide> if (nestedPassiveUpdateCount > NESTED_PASSIVE_UPDATE_LIMIT) {
<ide> nestedPassiveUpdateCount = 0;
<del> warning(
<add> console.error(
<ide> 'Maximum update depth exceeded. This can happen when a component ' +
<ide> "calls setState inside useEffect, but useEffect either doesn't " +
<ide> 'have a dependency array, or one of the dependencies changes on ' +
<ide> function warnAboutUpdateOnUnmountedFiberInDEV(fiber) {
<ide> } else {
<ide> didWarnStateUpdateForUnmountedComponent = new Set([componentName]);
<ide> }
<del> warning(
<add> console.error(
<ide> "Can't perform a React state update on an unmounted component. This " +
<ide> 'is a no-op, but it indicates a memory leak in your application. To ' +
<ide> 'fix, cancel all subscriptions and asynchronous tasks in %s.%s',
<ide> function warnAboutInvalidUpdatesOnClassComponentsInDEV(fiber) {
<ide> if (didWarnAboutUpdateInGetChildContext) {
<ide> return;
<ide> }
<del> warning(
<add> console.error(
<ide> 'setState(...): Cannot call setState() inside getChildContext()',
<ide> );
<ide> didWarnAboutUpdateInGetChildContext = true;
<ide> function warnAboutInvalidUpdatesOnClassComponentsInDEV(fiber) {
<ide> if (didWarnAboutUpdateInRender) {
<ide> return;
<ide> }
<del> warning(
<add> console.error(
<ide> 'Cannot update during an existing state transition (such as ' +
<ide> 'within `render`). Render methods should be a pure function of ' +
<ide> 'props and state.',
<ide> export function warnIfNotScopedWithMatchingAct(fiber: Fiber): void {
<ide> IsSomeRendererActing.current === true &&
<ide> IsThisRendererActing.current !== true
<ide> ) {
<del> warning(
<add> console.error(
<ide> "It looks like you're using the wrong act() around your test interactions.\n" +
<ide> 'Be sure to use the matching version of act() corresponding to your renderer:\n\n' +
<ide> '// for react-dom:\n' +
<ide> export function warnIfNotCurrentlyActingEffectsInDEV(fiber: Fiber): void {
<ide> IsSomeRendererActing.current === false &&
<ide> IsThisRendererActing.current === false
<ide> ) {
<del> warning(
<add> console.error(
<ide> 'An update to %s ran an effect, but was not wrapped in act(...).\n\n' +
<ide> 'When testing, code that causes React state updates should be ' +
<ide> 'wrapped into act(...):\n\n' +
<ide> function warnIfNotCurrentlyActingUpdatesInDEV(fiber: Fiber): void {
<ide> IsSomeRendererActing.current === false &&
<ide> IsThisRendererActing.current === false
<ide> ) {
<del> warning(
<add> console.error(
<ide> 'An update to %s inside a test was not wrapped in act(...).\n\n' +
<ide> 'When testing, code that causes React state updates should be ' +
<ide> 'wrapped into act(...):\n\n' +
<ide> export function warnIfUnmockedScheduler(fiber: Fiber) {
<ide> ) {
<ide> if (fiber.mode & BlockingMode || fiber.mode & ConcurrentMode) {
<ide> didWarnAboutUnmockedScheduler = true;
<del> warning(
<add> console.error(
<ide> 'In Concurrent or Sync modes, the "scheduler" module needs to be mocked ' +
<ide> 'to guarantee consistent behaviour across tests and browsers. ' +
<ide> 'For example, with jest: \n' +
<ide> export function warnIfUnmockedScheduler(fiber: Fiber) {
<ide> );
<ide> } else if (warnAboutUnmockedScheduler === true) {
<ide> didWarnAboutUnmockedScheduler = true;
<del> warning(
<add> console.error(
<ide> 'Starting from React v17, the "scheduler" module will need to be mocked ' +
<ide> 'to guarantee consistent behaviour across tests and browsers. ' +
<ide> 'For example, with jest: \n' +
<ide> function flushSuspensePriorityWarningInDEV() {
<ide> componentsThatTriggeredHighPriSuspend = null;
<ide>
<ide> if (componentNames.length > 0) {
<del> warning(
<add> console.error(
<ide> '%s triggered a user-blocking update that suspended.' +
<ide> '\n\n' +
<ide> 'The fix is to split the update into multiple parts: a user-blocking ' +
<ide><path>packages/react-reconciler/src/ReactStrictModeWarnings.js
<ide> import {getStackByFiberInDevAndProd} from './ReactCurrentFiber';
<ide>
<ide> import getComponentName from 'shared/getComponentName';
<ide> import {StrictMode} from './ReactTypeOfMode';
<del>import lowPriorityWarning from 'shared/lowPriorityWarning';
<del>import warning from 'shared/warning';
<ide>
<ide> type FiberArray = Array<Fiber>;
<ide> type FiberToFiberComponentsMap = Map<Fiber, FiberArray>;
<ide> if (__DEV__) {
<ide> const sortedNames = setToSortedString(
<ide> UNSAFE_componentWillMountUniqueNames,
<ide> );
<del> warning(
<add> console.error(
<ide> 'Using UNSAFE_componentWillMount in strict mode is not recommended and may indicate bugs in your code. ' +
<ide> 'See https://fb.me/react-unsafe-component-lifecycles for details.\n\n' +
<ide> '* Move code with side effects to componentDidMount, and set initial state in the constructor.\n' +
<ide> if (__DEV__) {
<ide> const sortedNames = setToSortedString(
<ide> UNSAFE_componentWillReceivePropsUniqueNames,
<ide> );
<del> warning(
<add> console.error(
<ide> 'Using UNSAFE_componentWillReceiveProps in strict mode is not recommended ' +
<ide> 'and may indicate bugs in your code. ' +
<ide> 'See https://fb.me/react-unsafe-component-lifecycles for details.\n\n' +
<ide> if (__DEV__) {
<ide> const sortedNames = setToSortedString(
<ide> UNSAFE_componentWillUpdateUniqueNames,
<ide> );
<del> warning(
<add> console.error(
<ide> 'Using UNSAFE_componentWillUpdate in strict mode is not recommended ' +
<ide> 'and may indicate bugs in your code. ' +
<ide> 'See https://fb.me/react-unsafe-component-lifecycles for details.\n\n' +
<ide> if (__DEV__) {
<ide> if (componentWillMountUniqueNames.size > 0) {
<ide> const sortedNames = setToSortedString(componentWillMountUniqueNames);
<ide>
<del> lowPriorityWarning(
<add> console.warn(
<ide> 'componentWillMount has been renamed, and is not recommended for use. ' +
<ide> 'See https://fb.me/react-unsafe-component-lifecycles for details.\n\n' +
<ide> '* Move code with side effects to componentDidMount, and set initial state in the constructor.\n' +
<ide> if (__DEV__) {
<ide> componentWillReceivePropsUniqueNames,
<ide> );
<ide>
<del> lowPriorityWarning(
<add> console.warn(
<ide> 'componentWillReceiveProps has been renamed, and is not recommended for use. ' +
<ide> 'See https://fb.me/react-unsafe-component-lifecycles for details.\n\n' +
<ide> '* Move data fetching code or side effects to componentDidUpdate.\n' +
<ide> if (__DEV__) {
<ide> if (componentWillUpdateUniqueNames.size > 0) {
<ide> const sortedNames = setToSortedString(componentWillUpdateUniqueNames);
<ide>
<del> lowPriorityWarning(
<add> console.warn(
<ide> 'componentWillUpdate has been renamed, and is not recommended for use. ' +
<ide> 'See https://fb.me/react-unsafe-component-lifecycles for details.\n\n' +
<ide> '* Move data fetching code or side effects to componentDidUpdate.\n' +
<ide> if (__DEV__) {
<ide> ) => {
<ide> const strictRoot = findStrictRoot(fiber);
<ide> if (strictRoot === null) {
<del> warning(
<add> console.error(
<ide> 'Expected to find a StrictMode component in a strict mode tree. ' +
<ide> 'This error is likely caused by a bug in React. Please file an issue.',
<ide> );
<ide> if (__DEV__) {
<ide> strictRoot,
<ide> );
<ide>
<del> warning(
<add> console.error(
<ide> 'Legacy context API has been detected within a strict-mode tree.' +
<ide> '\n\nThe old API will be supported in all 16.x releases, but applications ' +
<ide> 'using it should migrate to the new version.' +
<ide><path>packages/react-reconciler/src/ReactUpdateQueue.js
<ide> import {
<ide> } from './ReactFiberWorkLoop';
<ide>
<ide> import invariant from 'shared/invariant';
<del>import warning from 'shared/warning';
<ide> import {getCurrentPriorityLevel} from './SchedulerWithReactIntegration';
<ide>
<ide> export type Update<State> = {
<ide> export function enqueueUpdate<State>(fiber: Fiber, update: Update<State>) {
<ide> currentlyProcessingQueue === sharedQueue &&
<ide> !didWarnUpdateInsideUpdate
<ide> ) {
<del> warning(
<add> console.error(
<ide> 'An update (setState, replaceState, or forceUpdate) was scheduled ' +
<ide> 'from inside an update function. Update functions should be pure, ' +
<ide> 'with zero side-effects. Consider using componentDidUpdate or a ' +
<ide><path>packages/react-test-renderer/src/ReactShallowRenderer.js
<ide> import shallowEqual from 'shared/shallowEqual';
<ide> import invariant from 'shared/invariant';
<ide> import checkPropTypes from 'prop-types/checkPropTypes';
<ide> import ReactSharedInternals from 'shared/ReactSharedInternals';
<del>import warning from 'shared/warning';
<ide> import is from 'shared/objectIs';
<ide>
<ide> import type {Dispatcher as DispatcherType} from 'react-reconciler/src/ReactFiberHooks';
<ide> function areHookInputsEqual(
<ide> ) {
<ide> if (prevDeps === null) {
<ide> if (__DEV__) {
<del> warning(
<add> console.error(
<ide> '%s received a final argument during this render, but not during ' +
<ide> 'the previous render. Even though the final argument is optional, ' +
<ide> 'its type cannot change between renders.',
<ide> function areHookInputsEqual(
<ide> // Don't bother comparing lengths in prod because these arrays should be
<ide> // passed inline.
<ide> if (nextDeps.length !== prevDeps.length) {
<del> warning(
<add> console.error(
<ide> 'The final argument passed to %s changed size between renders. The ' +
<ide> 'order and size of this array must remain constant.\n\n' +
<ide> 'Previous: %s\n' +
<ide><path>packages/react-test-renderer/src/ReactTestHostConfig.js
<ide> * @flow
<ide> */
<ide>
<del>import warning from 'shared/warning';
<del>
<ide> import type {
<ide> ReactEventResponder,
<ide> ReactEventResponderInstance,
<ide> export function appendChild(
<ide> ): void {
<ide> if (__DEV__) {
<ide> if (!Array.isArray(parentInstance.children)) {
<del> warning(
<add> console.error(
<ide> 'An invalid container has been provided. ' +
<ide> 'This may indicate that another renderer is being used in addition to the test renderer. ' +
<ide> '(For example, ReactDOM.createPortal inside of a ReactTestRenderer tree.) ' +
<ide> export function createTextInstance(
<ide> if (__DEV__) {
<ide> if (enableFlareAPI) {
<ide> if (hostContext === EVENT_COMPONENT_CONTEXT) {
<del> warning(
<add> console.error(
<ide> 'validateDOMNesting: React event components cannot have text DOM nodes as children. ' +
<ide> 'Wrap the child text "%s" in an element.',
<ide> text,
<ide><path>packages/react-test-renderer/src/ReactTestRendererAct.js
<ide> import {
<ide> IsThisRendererActing,
<ide> } from 'react-reconciler/inline.test';
<ide> import ReactSharedInternals from 'shared/ReactSharedInternals';
<del>import warning from 'shared/warning';
<ide> import enqueueTask from 'shared/enqueueTask';
<ide> import * as Scheduler from 'scheduler';
<ide>
<ide> function act(callback: () => Thenable) {
<ide> if (!__DEV__) {
<ide> if (didWarnAboutUsingActInProd === false) {
<ide> didWarnAboutUsingActInProd = true;
<add> // eslint-disable-next-line react-internal/no-production-logging
<ide> console.error(
<ide> 'act(...) is not supported in production builds of React, and might not behave as expected.',
<ide> );
<ide> function act(callback: () => Thenable) {
<ide> if (__DEV__) {
<ide> if (actingUpdatesScopeDepth > previousActingUpdatesScopeDepth) {
<ide> // if it's _less than_ previousActingUpdatesScopeDepth, then we can assume the 'other' one has warned
<del> warning(
<add> console.error(
<ide> 'You seem to have overlapping act() calls, this is not supported. ' +
<ide> 'Be sure to await previous act() calls before making a new one. ',
<ide> );
<ide> function act(callback: () => Thenable) {
<ide> .then(() => {})
<ide> .then(() => {
<ide> if (called === false) {
<del> warning(
<add> console.error(
<ide> 'You called act(async () => ...) without await. ' +
<ide> 'This could lead to unexpected testing behaviour, interleaving multiple act ' +
<ide> 'calls and mixing their scopes. You should - await act(async () => ...);',
<ide> function act(callback: () => Thenable) {
<ide> } else {
<ide> if (__DEV__) {
<ide> if (result !== undefined) {
<del> warning(
<add> console.error(
<ide> 'The callback passed to act(...) function ' +
<ide> 'must return undefined, or a Promise. You returned %s',
<ide> result,
<ide> function act(callback: () => Thenable) {
<ide> return {
<ide> then(resolve: () => void) {
<ide> if (__DEV__) {
<del> warning(
<add> console.error(
<ide> 'Do not await the result of calling act(...) with sync logic, it is not a Promise.',
<ide> );
<ide> }
<ide><path>packages/react/src/ReactBaseClasses.js
<ide> */
<ide>
<ide> import invariant from 'shared/invariant';
<del>import lowPriorityWarning from 'shared/lowPriorityWarning';
<ide>
<ide> import ReactNoopUpdateQueue from './ReactNoopUpdateQueue';
<ide>
<ide> if (__DEV__) {
<ide> const defineDeprecationWarning = function(methodName, info) {
<ide> Object.defineProperty(Component.prototype, methodName, {
<ide> get: function() {
<del> lowPriorityWarning(
<add> console.warn(
<ide> '%s(...) is deprecated in plain JavaScript React classes. %s',
<ide> info[0],
<ide> info[1],
<ide><path>packages/react/src/ReactChildren.js
<ide> */
<ide>
<ide> import invariant from 'shared/invariant';
<del>import warning from 'shared/warning';
<ide> import {
<ide> getIteratorFn,
<ide> REACT_ELEMENT_TYPE,
<ide> function traverseAllChildrenImpl(
<ide> // Warn about using Maps as children
<ide> if (iteratorFn === children.entries) {
<ide> if (!didWarnAboutMaps) {
<del> warning(
<add> console.error(
<ide> 'Using Maps as children is unsupported and will likely yield ' +
<ide> 'unexpected results. Convert it to a sequence/iterable of keyed ' +
<ide> 'ReactElements instead.',
<ide><path>packages/react/src/ReactContext.js
<ide> import {REACT_PROVIDER_TYPE, REACT_CONTEXT_TYPE} from 'shared/ReactSymbols';
<ide>
<ide> import type {ReactContext} from 'shared/ReactTypes';
<ide>
<del>import warning from 'shared/warning';
<del>
<ide> export function createContext<T>(
<ide> defaultValue: T,
<ide> calculateChangedBits: ?(a: T, b: T) => number,
<ide> export function createContext<T>(
<ide> calculateChangedBits !== null &&
<ide> typeof calculateChangedBits !== 'function'
<ide> ) {
<del> warning(
<add> console.error(
<ide> 'createContext: Expected the optional second argument to be a ' +
<ide> 'function. Instead received: %s',
<ide> calculateChangedBits,
<ide> export function createContext<T>(
<ide> get() {
<ide> if (!hasWarnedAboutUsingConsumerProvider) {
<ide> hasWarnedAboutUsingConsumerProvider = true;
<del> warning(
<add> console.error(
<ide> 'Rendering <Context.Consumer.Provider> is not supported and will be removed in ' +
<ide> 'a future major release. Did you mean to render <Context.Provider> instead?',
<ide> );
<ide> export function createContext<T>(
<ide> get() {
<ide> if (!hasWarnedAboutUsingNestedContextConsumers) {
<ide> hasWarnedAboutUsingNestedContextConsumers = true;
<del> warning(
<add> console.error(
<ide> 'Rendering <Context.Consumer.Consumer> is not supported and will be removed in ' +
<ide> 'a future major release. Did you mean to render <Context.Consumer> instead?',
<ide> );
<ide><path>packages/react/src/ReactElement.js
<ide> */
<ide>
<ide> import invariant from 'shared/invariant';
<del>import warning from 'shared/warning';
<ide> import {REACT_ELEMENT_TYPE} from 'shared/ReactSymbols';
<ide>
<ide> import ReactCurrentOwner from './ReactCurrentOwner';
<ide> function defineKeyPropWarningGetter(props, displayName) {
<ide> if (__DEV__) {
<ide> if (!specialPropKeyWarningShown) {
<ide> specialPropKeyWarningShown = true;
<del> warning(
<add> console.error(
<ide> '%s: `key` is not a prop. Trying to access it will result ' +
<ide> 'in `undefined` being returned. If you need to access the same ' +
<ide> 'value within the child component, you should pass it as a different ' +
<ide> function defineRefPropWarningGetter(props, displayName) {
<ide> if (__DEV__) {
<ide> if (!specialPropRefWarningShown) {
<ide> specialPropRefWarningShown = true;
<del> warning(
<add> console.error(
<ide> '%s: `ref` is not a prop. Trying to access it will result ' +
<ide> 'in `undefined` being returned. If you need to access the same ' +
<ide> 'value within the child component, you should pass it as a different ' +
<ide><path>packages/react/src/ReactElementValidator.js
<ide> * that support it.
<ide> */
<ide>
<del>import lowPriorityWarning from 'shared/lowPriorityWarning';
<ide> import isValidElementType from 'shared/isValidElementType';
<ide> import getComponentName from 'shared/getComponentName';
<ide> import {
<ide> import {
<ide> REACT_ELEMENT_TYPE,
<ide> } from 'shared/ReactSymbols';
<ide> import checkPropTypes from 'prop-types/checkPropTypes';
<del>import warning from 'shared/warning';
<ide>
<ide> import ReactCurrentOwner from './ReactCurrentOwner';
<ide> import {
<ide> function validateExplicitKey(element, parentType) {
<ide>
<ide> setCurrentlyValidatingElement(element);
<ide> if (__DEV__) {
<del> warning(
<add> console.error(
<ide> 'Each child in a list should have a unique "key" prop.' +
<ide> '%s%s See https://fb.me/react-warning-keys for more information.',
<ide> currentComponentErrorInfo,
<ide> function validatePropTypes(element) {
<ide> setCurrentlyValidatingElement(null);
<ide> } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) {
<ide> propTypesMisspellWarningShown = true;
<del> warning(
<add> console.error(
<ide> 'Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?',
<ide> name || 'Unknown',
<ide> );
<ide> function validatePropTypes(element) {
<ide> typeof type.getDefaultProps === 'function' &&
<ide> !type.getDefaultProps.isReactClassApproved
<ide> ) {
<del> warning(
<add> console.error(
<ide> 'getDefaultProps is only used on classic React.createClass ' +
<ide> 'definitions. Use a static property named `defaultProps` instead.',
<ide> );
<ide> function validateFragmentProps(fragment) {
<ide> for (let i = 0; i < keys.length; i++) {
<ide> const key = keys[i];
<ide> if (key !== 'children' && key !== 'key') {
<del> warning(
<add> console.error(
<ide> 'Invalid prop `%s` supplied to `React.Fragment`. ' +
<ide> 'React.Fragment can only have `key` and `children` props.',
<ide> key,
<ide> function validateFragmentProps(fragment) {
<ide> }
<ide>
<ide> if (fragment.ref !== null) {
<del> warning('Invalid attribute `ref` supplied to `React.Fragment`.');
<add> console.error('Invalid attribute `ref` supplied to `React.Fragment`.');
<ide> }
<ide>
<ide> setCurrentlyValidatingElement(null);
<ide> export function jsxWithValidation(
<ide> }
<ide>
<ide> if (__DEV__) {
<del> warning(
<add> console.error(
<ide> 'React.jsx: type is invalid -- expected a string (for ' +
<ide> 'built-in components) or a class/function (for composite ' +
<ide> 'components) but got: %s.%s',
<ide> export function jsxWithValidation(
<ide> }
<ide> } else {
<ide> if (__DEV__) {
<del> warning(
<add> console.error(
<ide> 'React.jsx: Static children should always be an array. ' +
<ide> 'You are likely explicitly calling React.jsxs or React.jsxDEV. ' +
<ide> 'Use the Babel transform instead.',
<ide> export function jsxWithValidation(
<ide>
<ide> if (hasOwnProperty.call(props, 'key')) {
<ide> if (__DEV__) {
<del> warning(
<add> console.error(
<ide> 'React.jsx: Spreading a key to JSX is a deprecated pattern. ' +
<ide> 'Explicitly pass a key after spreading props in your JSX call. ' +
<ide> 'E.g. <ComponentName {...props} key={key} />',
<ide> export function createElementWithValidation(type, props, children) {
<ide> }
<ide>
<ide> if (__DEV__) {
<del> warning(
<add> console.error(
<ide> 'React.createElement: type is invalid -- expected a string (for ' +
<ide> 'built-in components) or a class/function (for composite ' +
<ide> 'components) but got: %s.%s',
<ide> export function createFactoryWithValidation(type) {
<ide> Object.defineProperty(validatedFactory, 'type', {
<ide> enumerable: false,
<ide> get: function() {
<del> lowPriorityWarning(
<add> console.warn(
<ide> 'Factory.type is deprecated. Access the class directly ' +
<ide> 'before passing it to createFactory.',
<ide> );
<ide><path>packages/react/src/ReactHooks.js
<ide> import type {
<ide> ReactEventResponderListener,
<ide> } from 'shared/ReactTypes';
<ide> import invariant from 'shared/invariant';
<del>import warning from 'shared/warning';
<ide> import {REACT_RESPONDER_TYPE} from 'shared/ReactSymbols';
<ide>
<ide> import ReactCurrentDispatcher from './ReactCurrentDispatcher';
<ide> export function useContext<T>(
<ide> const dispatcher = resolveDispatcher();
<ide> if (__DEV__) {
<ide> if (unstable_observedBits !== undefined) {
<del> warning(
<add> console.error(
<ide> 'useContext() second argument is reserved for future ' +
<ide> 'use in React. Passing it is not supported. ' +
<ide> 'You passed: %s.%s',
<ide> export function useContext<T>(
<ide> // Don't deduplicate because this legitimately causes bugs
<ide> // and nobody should be using this in existing code.
<ide> if (realContext.Consumer === Context) {
<del> warning(
<add> console.error(
<ide> 'Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be ' +
<ide> 'removed in a future major release. Did you mean to call useContext(Context) instead?',
<ide> );
<ide> } else if (realContext.Provider === Context) {
<del> warning(
<add> console.error(
<ide> 'Calling useContext(Context.Provider) is not supported. ' +
<ide> 'Did you mean to call useContext(Context) instead?',
<ide> );
<ide> export function useResponder(
<ide> const dispatcher = resolveDispatcher();
<ide> if (__DEV__) {
<ide> if (responder == null || responder.$$typeof !== REACT_RESPONDER_TYPE) {
<del> warning(
<add> console.error(
<ide> 'useResponder: invalid first argument. Expected an event responder, but instead got %s',
<ide> responder,
<ide> );
<ide><path>packages/react/src/ReactLazy.js
<ide> import type {LazyComponent, Thenable} from 'shared/ReactLazyComponent';
<ide>
<ide> import {REACT_LAZY_TYPE} from 'shared/ReactSymbols';
<del>import warning from 'shared/warning';
<ide>
<ide> export function lazy<T, R>(ctor: () => Thenable<T, R>): LazyComponent<T> {
<ide> let lazyType = {
<ide> export function lazy<T, R>(ctor: () => Thenable<T, R>): LazyComponent<T> {
<ide> return defaultProps;
<ide> },
<ide> set(newDefaultProps) {
<del> warning(
<add> console.error(
<ide> 'React.lazy(...): It is not supported to assign `defaultProps` to ' +
<ide> 'a lazy component import. Either specify them where the component ' +
<ide> 'is defined, or create a wrapping component around it.',
<ide> export function lazy<T, R>(ctor: () => Thenable<T, R>): LazyComponent<T> {
<ide> return propTypes;
<ide> },
<ide> set(newPropTypes) {
<del> warning(
<add> console.error(
<ide> 'React.lazy(...): It is not supported to assign `propTypes` to ' +
<ide> 'a lazy component import. Either specify them where the component ' +
<ide> 'is defined, or create a wrapping component around it.',
<ide><path>packages/react/src/ReactNoopUpdateQueue.js
<ide> * LICENSE file in the root directory of this source tree.
<ide> */
<ide>
<del>import warning from 'shared/warning';
<del>
<ide> const didWarnStateUpdateForUnmountedComponent = {};
<ide>
<ide> function warnNoop(publicInstance, callerName) {
<ide> function warnNoop(publicInstance, callerName) {
<ide> if (didWarnStateUpdateForUnmountedComponent[warningKey]) {
<ide> return;
<ide> }
<del> warning(
<add> console.error(
<ide> "Can't call %s on a component that is not yet mounted. " +
<ide> 'This is a no-op, but it might indicate a bug in your application. ' +
<ide> 'Instead, assign to `this.state` directly or define a `state = {};` ' +
<ide><path>packages/react/src/forwardRef.js
<ide>
<ide> import {REACT_FORWARD_REF_TYPE, REACT_MEMO_TYPE} from 'shared/ReactSymbols';
<ide>
<del>import warning from 'shared/warning';
<del>
<ide> export default function forwardRef<Props, ElementType: React$ElementType>(
<ide> render: (props: Props, ref: React$Ref<ElementType>) => React$Node,
<ide> ) {
<ide> if (__DEV__) {
<ide> if (render != null && render.$$typeof === REACT_MEMO_TYPE) {
<del> warning(
<add> console.error(
<ide> 'forwardRef requires a render function but received a `memo` ' +
<ide> 'component. Instead of forwardRef(memo(...)), use ' +
<ide> 'memo(forwardRef(...)).',
<ide> );
<ide> } else if (typeof render !== 'function') {
<del> warning(
<add> console.error(
<ide> 'forwardRef requires a render function but was given %s.',
<ide> render === null ? 'null' : typeof render,
<ide> );
<ide> } else {
<ide> if (render.length !== 0 && render.length !== 2) {
<del> warning(
<add> console.error(
<ide> 'forwardRef render functions accept exactly two parameters: props and ref. %s',
<ide> render.length === 1
<ide> ? 'Did you forget to use the ref parameter?'
<ide> export default function forwardRef<Props, ElementType: React$ElementType>(
<ide>
<ide> if (render != null) {
<ide> if (render.defaultProps != null || render.propTypes != null) {
<del> warning(
<add> console.error(
<ide> 'forwardRef render functions do not support propTypes or defaultProps. ' +
<ide> 'Did you accidentally pass a React component?',
<ide> );
<ide><path>packages/react/src/memo.js
<ide> import {REACT_MEMO_TYPE} from 'shared/ReactSymbols';
<ide>
<ide> import isValidElementType from 'shared/isValidElementType';
<del>import warning from 'shared/warning';
<ide>
<ide> export default function memo<Props>(
<ide> type: React$ElementType,
<ide> compare?: (oldProps: Props, newProps: Props) => boolean,
<ide> ) {
<ide> if (__DEV__) {
<ide> if (!isValidElementType(type)) {
<del> warning(
<add> console.error(
<ide> 'memo: The first argument must be a component. Instead ' +
<ide> 'received: %s',
<ide> type === null ? 'null' : typeof type,
<ide><path>packages/scheduler/src/SchedulerProfiling.js
<ide> function logEvent(entries) {
<ide> if (eventLogIndex + 1 > eventLogSize) {
<ide> eventLogSize *= 2;
<ide> if (eventLogSize > MAX_EVENT_LOG_SIZE) {
<del> console.error(
<add> // Using console['error'] to evade Babel and ESLint
<add> console['error'](
<ide> "Scheduler Profiling: Event log exceeded maximum size. Don't " +
<ide> 'forget to call `stopLoggingProfilingEvents()`.',
<ide> );
<ide><path>packages/scheduler/src/forks/SchedulerHostConfig.default.js
<ide> if (
<ide> const cancelAnimationFrame = window.cancelAnimationFrame;
<ide> // TODO: Remove fb.me link
<ide> if (typeof requestAnimationFrame !== 'function') {
<del> console.error(
<add> // Using console['error'] to evade Babel and ESLint
<add> console['error'](
<ide> "This browser doesn't support requestAnimationFrame. " +
<ide> 'Make sure that you load a ' +
<ide> 'polyfill in older browsers. https://fb.me/react-polyfills',
<ide> );
<ide> }
<ide> if (typeof cancelAnimationFrame !== 'function') {
<del> console.error(
<add> // Using console['error'] to evade Babel and ESLint
<add> console['error'](
<ide> "This browser doesn't support cancelAnimationFrame. " +
<ide> 'Make sure that you load a ' +
<ide> 'polyfill in older browsers. https://fb.me/react-polyfills',
<ide> if (
<ide>
<ide> forceFrameRate = function(fps) {
<ide> if (fps < 0 || fps > 125) {
<del> console.error(
<add> // Using console['error'] to evade Babel and ESLint
<add> console['error'](
<ide> 'forceFrameRate takes a positive int between 0 and 125, ' +
<ide> 'forcing framerates higher than 125 fps is not unsupported',
<ide> );
<ide><path>packages/shared/ReactLazyComponent.js
<ide> * @flow
<ide> */
<ide>
<del>import warning from 'shared/warning';
<del>
<ide> export type Thenable<T, R> = {
<ide> then(resolve: (T) => mixed, reject: (mixed) => mixed): R,
<ide> };
<ide> export function initializeLazyComponentType(
<ide> const defaultExport = moduleObject.default;
<ide> if (__DEV__) {
<ide> if (defaultExport === undefined) {
<del> warning(
<add> console.error(
<ide> 'lazy: Expected the result of a dynamic import() call. ' +
<ide> 'Instead received: %s\n\nYour code should look like: \n ' +
<ide> "const MyComponent = lazy(() => import('./MyComponent'))",
<ide><path>packages/shared/consoleWithStackDev.js
<add>/**
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> */
<add>
<add>import ReactSharedInternals from 'shared/ReactSharedInternals';
<add>
<add>// In DEV, calls to console.warn and console.error get replaced
<add>// by calls to these methods by a Babel plugin.
<add>//
<add>// In PROD (or in packages without access to React internals),
<add>// they are left as they are instead.
<add>
<add>export function warn(format, ...args) {
<add> if (__DEV__) {
<add> printWarning('warn', format, args);
<add> }
<add>}
<add>
<add>export function error(format, ...args) {
<add> if (__DEV__) {
<add> printWarning('error', format, args);
<add> }
<add>}
<add>
<add>function printWarning(level, format, args) {
<add> if (__DEV__) {
<add> const hasExistingStack =
<add> args.length > 0 &&
<add> typeof args[args.length - 1] === 'string' &&
<add> args[args.length - 1].indexOf('\n in') === 0;
<add>
<add> if (!hasExistingStack) {
<add> const ReactDebugCurrentFrame =
<add> ReactSharedInternals.ReactDebugCurrentFrame;
<add> const stack = ReactDebugCurrentFrame.getStackAddendum();
<add> if (stack !== '') {
<add> format += '%s';
<add> args = args.concat([stack]);
<add> }
<add> }
<add>
<add> const argsWithFormat = args.map(item => '' + item);
<add> // Careful: RN currently depends on this prefix
<add> argsWithFormat.unshift('Warning: ' + format);
<add> // We intentionally don't use spread (or .apply) directly because it
<add> // breaks IE9: https://github.com/facebook/react/issues/13610
<add> // eslint-disable-next-line react-internal/no-production-logging
<add> Function.prototype.apply.call(console[level], console, argsWithFormat);
<add>
<add> try {
<add> // --- Welcome to debugging React ---
<add> // This error was thrown as a convenience so that you can use this stack
<add> // to find the callsite that caused this warning to fire.
<add> let argIndex = 0;
<add> const message =
<add> 'Warning: ' + format.replace(/%s/g, () => args[argIndex++]);
<add> throw new Error(message);
<add> } catch (x) {}
<add> }
<add>}
<ide><path>packages/shared/enqueueTask.js
<ide> * @flow
<ide> */
<ide>
<del>import warningWithoutStack from 'shared/warningWithoutStack';
<del>
<ide> let didWarnAboutMessageChannel = false;
<ide> let enqueueTask;
<ide> try {
<ide> try {
<ide> if (didWarnAboutMessageChannel === false) {
<ide> didWarnAboutMessageChannel = true;
<ide> if (typeof MessageChannel === 'undefined') {
<del> warningWithoutStack(
<add> console.error(
<ide> 'This browser does not have a MessageChannel implementation, ' +
<ide> 'so enqueuing tasks via await act(async () => ...) will fail. ' +
<ide> 'Please file an issue at https://github.com/facebook/react/issues ' +
<ide><path>packages/shared/forks/consoleWithStackDev.www.js
<add>/**
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> */
<add>
<add>// This refers to a WWW module.
<add>const warningWWW = require('warning');
<add>
<add>export function warn() {
<add> // TODO: use different level for "warn".
<add> const args = Array.prototype.slice.call(arguments);
<add> args.unshift(false);
<add> warningWWW.apply(null, args);
<add>}
<add>
<add>export function error() {
<add> const args = Array.prototype.slice.call(arguments);
<add> args.unshift(false);
<add> warningWWW.apply(null, args);
<add>}
<ide><path>packages/shared/forks/lowPriorityWarningWithoutStack.www.js
<del>/**
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<del> *
<del> * This source code is licensed under the MIT license found in the
<del> * LICENSE file in the root directory of this source tree.
<del> */
<del>
<del>// This refers to a WWW module.
<del>const lowPriorityWarningWWW = require('lowPriorityWarning');
<del>
<del>export default function lowPriorityWarningWithoutStack(format, ...args) {
<del> return lowPriorityWarningWWW(false, format, ...args);
<del>}
<ide><path>packages/shared/forks/warningWithoutStack.www.js
<del>/**
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<del> *
<del> * This source code is licensed under the MIT license found in the
<del> * LICENSE file in the root directory of this source tree.
<del> */
<del>
<del>// This refers to a WWW module.
<del>const warningWWW = require('warning');
<del>
<del>export default function warningWithoutStack(format, ...args) {
<del> return warningWWW(false, format, ...args);
<del>}
<ide><path>packages/shared/getComponentName.js
<ide>
<ide> import type {LazyComponent} from 'shared/ReactLazyComponent';
<ide>
<del>import warning from 'shared/warning';
<ide> import {
<ide> REACT_CONTEXT_TYPE,
<ide> REACT_FORWARD_REF_TYPE,
<ide> function getComponentName(type: mixed): string | null {
<ide> }
<ide> if (__DEV__) {
<ide> if (typeof (type: any).tag === 'number') {
<del> warning(
<add> console.error(
<ide> 'Received an unexpected object in getComponentName(). ' +
<ide> 'This is likely a bug in React. Please file an issue.',
<ide> );
<ide><path>packages/shared/lowPriorityWarning.js
<del>/**
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<del> *
<del> * This source code is licensed under the MIT license found in the
<del> * LICENSE file in the root directory of this source tree.
<del> */
<del>
<del>import lowPriorityWarningWithoutStack from 'shared/lowPriorityWarningWithoutStack';
<del>import ReactSharedInternals from 'shared/ReactSharedInternals';
<del>
<del>/**
<del> * Similar to invariant but only logs a warning if the condition is not met.
<del> * This can be used to log issues in development environments in critical
<del> * paths. Removing the logging code for production environments will keep the
<del> * same logic and follow the same code paths.
<del> */
<del>
<del>let lowPriorityWarning = lowPriorityWarningWithoutStack;
<del>
<del>if (__DEV__) {
<del> lowPriorityWarning = function(format, ...args) {
<del> let finalFormat = format;
<del> let finalArgs = args;
<del>
<del> const hasExistingStack =
<del> args.length > 0 &&
<del> typeof args[args.length - 1] === 'string' &&
<del> args[args.length - 1].indexOf('\n in') === 0;
<del>
<del> if (!hasExistingStack) {
<del> const ReactDebugCurrentFrame =
<del> ReactSharedInternals.ReactDebugCurrentFrame;
<del> const stack = ReactDebugCurrentFrame.getStackAddendum();
<del> finalFormat += '%s';
<del> finalArgs.push(stack);
<del> }
<del>
<del> // eslint-disable-next-line react-internal/warning-args
<del> lowPriorityWarningWithoutStack(finalFormat, ...finalArgs);
<del> };
<del>}
<del>
<del>export default lowPriorityWarning;
<ide><path>packages/shared/lowPriorityWarningWithoutStack.js
<del>/**
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<del> *
<del> * This source code is licensed under the MIT license found in the
<del> * LICENSE file in the root directory of this source tree.
<del> */
<del>
<del>/**
<del> * Forked from fbjs/warning:
<del> * https://github.com/facebook/fbjs/blob/e66ba20ad5be433eb54423f2b097d829324d9de6/packages/fbjs/src/__forks__/warning.js
<del> *
<del> * Only change is we use console.warn instead of console.error,
<del> * and do nothing when 'console' is not supported.
<del> * This really simplifies the code.
<del> * ---
<del> * Similar to invariant but only logs a warning if the condition is not met.
<del> * This can be used to log issues in development environments in critical
<del> * paths. Removing the logging code for production environments will keep the
<del> * same logic and follow the same code paths.
<del> */
<del>
<del>let lowPriorityWarningWithoutStack = function() {};
<del>
<del>if (__DEV__) {
<del> const printWarning = function(format, ...args) {
<del> let argIndex = 0;
<del> const message = 'Warning: ' + format.replace(/%s/g, () => args[argIndex++]);
<del> if (typeof console !== 'undefined') {
<del> console.warn(message);
<del> }
<del> try {
<del> // --- Welcome to debugging React ---
<del> // This error was thrown as a convenience so that you can use this stack
<del> // to find the callsite that caused this warning to fire.
<del> throw new Error(message);
<del> } catch (x) {}
<del> };
<del>
<del> lowPriorityWarningWithoutStack = function(format, ...args) {
<del> if (format === undefined) {
<del> throw new Error(
<del> '`lowPriorityWarningWithoutStack(condition, format, ...args)` requires a warning ' +
<del> 'message argument',
<del> );
<del> }
<del>
<del> printWarning(format, ...args);
<del> };
<del>}
<del>
<del>export default lowPriorityWarningWithoutStack;
<ide><path>packages/shared/warning.js
<del>/**
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<del> *
<del> * This source code is licensed under the MIT license found in the
<del> * LICENSE file in the root directory of this source tree.
<del> */
<del>
<del>import warningWithoutStack from 'shared/warningWithoutStack';
<del>import ReactSharedInternals from 'shared/ReactSharedInternals';
<del>
<del>/**
<del> * Similar to invariant but only logs a warning if the condition is not met.
<del> * This can be used to log issues in development environments in critical
<del> * paths. Removing the logging code for production environments will keep the
<del> * same logic and follow the same code paths.
<del> */
<del>
<del>let warning = warningWithoutStack;
<del>
<del>if (__DEV__) {
<del> warning = function(format, ...args) {
<del> let finalFormat = format;
<del> let finalArgs = args;
<del>
<del> const hasExistingStack =
<del> args.length > 0 &&
<del> typeof args[args.length - 1] === 'string' &&
<del> args[args.length - 1].indexOf('\n in') === 0;
<del>
<del> if (!hasExistingStack) {
<del> const ReactDebugCurrentFrame =
<del> ReactSharedInternals.ReactDebugCurrentFrame;
<del> const stack = ReactDebugCurrentFrame.getStackAddendum();
<del> finalFormat += '%s';
<del> finalArgs.push(stack);
<del> }
<del>
<del> // eslint-disable-next-line react-internal/warning-args
<del> warningWithoutStack(finalFormat, ...finalArgs);
<del> };
<del>}
<del>
<del>export default warning;
<ide><path>packages/shared/warningWithoutStack.js
<del>/**
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<del> *
<del> * This source code is licensed under the MIT license found in the
<del> * LICENSE file in the root directory of this source tree.
<del> */
<del>
<del>/**
<del> * This can be used to log issues in development environments in critical
<del> * paths. Removing the logging code for production environments will keep the
<del> * same logic and follow the same code paths.
<del> */
<del>
<del>let warningWithoutStack = () => {};
<del>
<del>if (__DEV__) {
<del> warningWithoutStack = function(format, ...args) {
<del> if (format === undefined) {
<del> throw new Error(
<del> '`warningWithoutStack(condition, format, ...args)` requires a warning ' +
<del> 'message argument',
<del> );
<del> }
<del> if (args.length > 8) {
<del> // Check before the condition to catch violations early.
<del> throw new Error(
<del> 'warningWithoutStack() currently supports at most 8 arguments.',
<del> );
<del> }
<del> if (typeof console !== 'undefined') {
<del> const argsWithFormat = args.map(item => '' + item);
<del> argsWithFormat.unshift('Warning: ' + format);
<del>
<del> // We intentionally don't use spread (or .apply) directly because it
<del> // breaks IE9: https://github.com/facebook/react/issues/13610
<del> Function.prototype.apply.call(console.error, console, argsWithFormat);
<del> }
<del> try {
<del> // --- Welcome to debugging React ---
<del> // This error was thrown as a convenience so that you can use this stack
<del> // to find the callsite that caused this warning to fire.
<del> let argIndex = 0;
<del> const message =
<del> 'Warning: ' + format.replace(/%s/g, () => args[argIndex++]);
<del> throw new Error(message);
<del> } catch (x) {}
<del> };
<del>}
<del>
<del>export default warningWithoutStack;
<ide><path>scripts/babel/transform-replace-console-calls.js
<add>/**
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> */
<add>'use strict';
<add>
<add>const helperModuleImports = require('@babel/helper-module-imports');
<add>
<add>module.exports = function replaceConsoleCalls(babel) {
<add> let consoleErrors = new WeakMap();
<add> function getConsoleError(path, file) {
<add> if (!consoleErrors.has(file)) {
<add> consoleErrors.set(
<add> file,
<add> helperModuleImports.addNamed(
<add> path,
<add> 'error',
<add> 'shared/consoleWithStackDev',
<add> {nameHint: 'consoleError'}
<add> )
<add> );
<add> }
<add> return babel.types.cloneDeep(consoleErrors.get(file));
<add> }
<add>
<add> let consoleWarns = new WeakMap();
<add> function getConsoleWarn(path, file) {
<add> if (!consoleWarns.has(file)) {
<add> consoleWarns.set(
<add> file,
<add> helperModuleImports.addNamed(
<add> path,
<add> 'warn',
<add> 'shared/consoleWithStackDev',
<add> {nameHint: 'consoleWarn'}
<add> )
<add> );
<add> }
<add> return babel.types.cloneDeep(consoleWarns.get(file));
<add> }
<add>
<add> return {
<add> visitor: {
<add> CallExpression: function(path, pass) {
<add> if (path.node.callee.type !== 'MemberExpression') {
<add> return;
<add> }
<add> if (path.node.callee.property.type !== 'Identifier') {
<add> // Don't process calls like console['error'](...)
<add> // because they serve as an escape hatch.
<add> return;
<add> }
<add> if (path.get('callee').matchesPattern('console.error')) {
<add> if (this.opts.shouldError) {
<add> throw path.buildCodeFrameError(
<add> "This module has no access to the React object, so it can't " +
<add> 'use console.error() with automatically appended stack. ' +
<add> "As a workaround, you can use console['error'] which won't " +
<add> 'be transformed.'
<add> );
<add> }
<add> const id = getConsoleError(path, pass.file);
<add> path.node.callee = id;
<add> }
<add> if (path.get('callee').matchesPattern('console.warn')) {
<add> if (this.opts.shouldError) {
<add> throw path.buildCodeFrameError(
<add> "This module has no access to the React object, so it can't " +
<add> 'use console.warn() with automatically appended stack. ' +
<add> "As a workaround, you can use console['warn'] which won't " +
<add> 'be transformed.'
<add> );
<add> }
<add> const id = getConsoleWarn(path, pass.file);
<add> path.node.callee = id;
<add> }
<add> },
<add> },
<add> };
<add>};
<ide><path>scripts/eslint-rules/__tests__/no-production-logging-test.internal.js
<ide> ruleTester.run('no-production-logging', rule, {
<ide> {
<ide> code: `
<ide> if (__DEV__) {
<del> warning(test, 'Oh no');
<add> console.error('Oh no');
<ide> }
<ide> `,
<ide> },
<ide> {
<ide> code: `
<ide> if (__DEV__) {
<del> warningWithoutStack(test, 'Oh no');
<add> console.error('Hello %s', foo)
<ide> }
<ide> `,
<ide> },
<ide> {
<ide> code: `
<ide> if (__DEV__) {
<del> lowPriorityWarning(test, 'Oh no');
<add> console.error('Hello %s %s', foo, bar)
<ide> }
<ide> `,
<ide> },
<ide> {
<ide> code: `
<ide> if (__DEV__) {
<del> lowPriorityWarningWithoutStack(test, 'Oh no');
<add> console.warn('Oh no');
<add> }
<add> `,
<add> },
<add> {
<add> code: `
<add> if (__DEV__) {
<add> console.warn('Oh no');
<ide> }
<ide> `,
<ide> },
<ide> ruleTester.run('no-production-logging', rule, {
<ide> if (__DEV__) {
<ide> if (potato) {
<ide> while (true) {
<del> warning(test, 'Oh no');
<add> console.error('Oh no');
<ide> }
<ide> }
<ide> }`,
<ide> ruleTester.run('no-production-logging', rule, {
<ide> f = function() {
<ide> if (potato) {
<ide> while (true) {
<del> warning(test, 'Oh no');
<add> console.error('Oh no');
<ide> }
<ide> }
<ide> };
<ide> ruleTester.run('no-production-logging', rule, {
<ide> if (foo) {
<ide> if (__DEV__) {
<ide> } else {
<del> warning(test, 'Oh no');
<add> console.error('Oh no');
<ide> }
<ide> }
<ide> }`,
<ide> },
<del> ],
<del> invalid: [
<del> {
<del> code: 'warning(test);',
<del> errors: [
<del> {
<del> message: `Wrap warning() in an "if (__DEV__) {}" check`,
<del> },
<del> ],
<del> },
<del> {
<del> code: 'warningWithoutStack(test)',
<del> errors: [
<del> {
<del> message: `Wrap warningWithoutStack() in an "if (__DEV__) {}" check`,
<del> },
<del> ],
<del> },
<ide> {
<add> // This is an escape hatch that makes it fire in production.
<ide> code: `
<del> if (potato) {
<del> warningWithoutStack(test);
<del> }
<add> console['error']('Oh no');
<ide> `,
<add> },
<add> ],
<add> invalid: [
<add> {
<add> code: "console.error('Oh no');",
<ide> errors: [
<ide> {
<del> message: `Wrap warningWithoutStack() in an "if (__DEV__) {}" check`,
<add> message: `Wrap console.error() in an "if (__DEV__) {}" check`,
<ide> },
<ide> ],
<ide> },
<ide> {
<del> code: 'lowPriorityWarning(test);',
<add> code: "console.warn('Oh no');",
<ide> errors: [
<ide> {
<del> message: `Wrap lowPriorityWarning() in an "if (__DEV__) {}" check`,
<add> message: `Wrap console.warn() in an "if (__DEV__) {}" check`,
<ide> },
<ide> ],
<ide> },
<ide> {
<del> code: 'lowPriorityWarningWithoutStack(test)',
<add> code: "console.warn('Oh no')",
<ide> errors: [
<ide> {
<del> message: `Wrap lowPriorityWarningWithoutStack() in an "if (__DEV__) {}" check`,
<add> message: `Wrap console.warn() in an "if (__DEV__) {}" check`,
<ide> },
<ide> ],
<ide> },
<ide> {
<ide> code: `
<ide> if (potato) {
<del> lowPriorityWarningWithoutStack(test);
<add> console.warn('Oh no');
<ide> }
<ide> `,
<ide> errors: [
<ide> {
<del> message: `Wrap lowPriorityWarningWithoutStack() in an "if (__DEV__) {}" check`,
<add> message: `Wrap console.warn() in an "if (__DEV__) {}" check`,
<ide> },
<ide> ],
<ide> },
<ide> {
<ide> code: `
<ide> if (__DEV__ || potato && true) {
<del> warning(test);
<add> console.error('Oh no');
<ide> }
<ide> `,
<ide> errors: [
<ide> {
<del> message: `Wrap warning() in an "if (__DEV__) {}" check`,
<add> message: `Wrap console.error() in an "if (__DEV__) {}" check`,
<ide> },
<ide> ],
<ide> },
<ide> {
<ide> code: `
<ide> if (banana && __DEV__ && potato && kitten) {
<del> warning(test);
<add> console.error('Oh no');
<ide> }
<ide> `,
<ide> // Technically this code is valid but we prefer
<ide> // explicit standalone __DEV__ blocks that stand out.
<ide> errors: [
<ide> {
<del> message: `Wrap warning() in an "if (__DEV__) {}" check`,
<add> message: `Wrap console.error() in an "if (__DEV__) {}" check`,
<ide> },
<ide> ],
<ide> },
<ide> {
<ide> code: `
<ide> if (!__DEV__) {
<del> warning(test);
<add> console.error('Oh no');
<ide> }
<ide> `,
<ide> errors: [
<ide> {
<del> message: `Wrap warning() in an "if (__DEV__) {}" check`,
<add> message: `Wrap console.error() in an "if (__DEV__) {}" check`,
<ide> },
<ide> ],
<ide> },
<ide> {
<ide> code: `
<ide> if (foo || x && __DEV__) {
<del> warning(test);
<add> console.error('Oh no');
<ide> }
<ide> `,
<ide> errors: [
<ide> {
<del> message: `Wrap warning() in an "if (__DEV__) {}" check`,
<add> message: `Wrap console.error() in an "if (__DEV__) {}" check`,
<ide> },
<ide> ],
<ide> },
<ide> {
<ide> code: `
<ide> if (__DEV__) {
<ide> } else {
<del> warning(test);
<add> console.error('Oh no');
<ide> }
<ide> `,
<ide> errors: [
<ide> {
<del> message: `Wrap warning() in an "if (__DEV__) {}" check`,
<add> message: `Wrap console.error() in an "if (__DEV__) {}" check`,
<ide> },
<ide> ],
<ide> },
<ide> ruleTester.run('no-production-logging', rule, {
<ide> } else {
<ide> if (__DEV__) {
<ide> } else {
<del> warning(test);
<add> console.error('Oh no');
<ide> }
<ide> }
<ide> `,
<ide> errors: [
<ide> {
<del> message: `Wrap warning() in an "if (__DEV__) {}" check`,
<add> message: `Wrap console.error() in an "if (__DEV__) {}" check`,
<add> },
<add> ],
<add> },
<add> {
<add> code: `
<add> if (__DEV__) {
<add> console.log('Oh no');
<add> }
<add> `,
<add> errors: [
<add> {
<add> message: 'Unexpected use of console',
<add> },
<add> ],
<add> },
<add> {
<add> code: `
<add> if (__DEV__) {
<add> console.log.apply(console, 'Oh no');
<add> }
<add> `,
<add> errors: [
<add> {
<add> message: 'Unexpected use of console',
<ide> },
<ide> ],
<ide> },
<ide><path>scripts/eslint-rules/__tests__/warning-args-test.internal.js
<ide> const ruleTester = new RuleTester();
<ide>
<ide> ruleTester.run('eslint-rules/warning-args', rule, {
<ide> valid: [
<del> "warning('hello, world');",
<del> "warning('expected %s, got %s', 42, 24);",
<add> "console.error('hello, world');",
<add> "console.error('expected %s, got %s', 42, 24);",
<ide> 'arbitraryFunction(a, b)',
<ide> ],
<ide> invalid: [
<ide> {
<del> code: 'warning(null);',
<add> code: 'console.error(null);',
<ide> errors: [
<ide> {
<del> message: 'The first argument to warning must be a string literal',
<add> message:
<add> 'The first argument to console.error must be a string literal',
<ide> },
<ide> ],
<ide> },
<ide> {
<del> code: 'var g = 5; warning(g);',
<add> code: 'console.warn(null);',
<ide> errors: [
<ide> {
<del> message: 'The first argument to warning must be a string literal',
<add> message:
<add> 'The first argument to console.warn must be a string literal',
<add> },
<add> ],
<add> },
<add> {
<add> code: 'var g = 5; console.error(g);',
<add> errors: [
<add> {
<add> message:
<add> 'The first argument to console.error must be a string literal',
<ide> },
<ide> ],
<ide> },
<ide> {
<del> code: "warning('expected %s, got %s');",
<add> code: "console.error('expected %s, got %s');",
<ide> errors: [
<ide> {
<ide> message:
<del> 'Expected 3 arguments in call to warning based on the number of ' +
<add> 'Expected 3 arguments in call to console.error based on the number of ' +
<ide> '"%s" substitutions, but got 1',
<ide> },
<ide> ],
<ide> },
<ide> {
<del> code: "warning('foo is a bar under foobar', 'junk argument');",
<add> code: "console.error('foo is a bar under foobar', 'junk argument');",
<ide> errors: [
<ide> {
<ide> message:
<del> 'Expected 1 arguments in call to warning based on the number of ' +
<add> 'Expected 1 arguments in call to console.error based on the number of ' +
<ide> '"%s" substitutions, but got 2',
<ide> },
<ide> ],
<ide> },
<ide> {
<del> code: "warning('error!');",
<add> code: "console.error('error!');",
<ide> errors: [
<ide> {
<ide> message:
<del> 'The warning format should be able to uniquely identify this ' +
<add> 'The console.error format should be able to uniquely identify this ' +
<ide> 'warning. Please, use a more descriptive format than: error!',
<ide> },
<ide> ],
<ide> },
<ide> {
<del> code: "warning('%s %s, %s %s: %s (%s)', 1, 2, 3, 4, 5, 6);",
<add> code: "console.error('%s %s, %s %s: %s (%s)', 1, 2, 3, 4, 5, 6);",
<ide> errors: [
<ide> {
<ide> message:
<del> 'The warning format should be able to uniquely identify this ' +
<add> 'The console.error format should be able to uniquely identify this ' +
<ide> 'warning. Please, use a more descriptive format than: ' +
<ide> '%s %s, %s %s: %s (%s)',
<ide> },
<ide><path>scripts/eslint-rules/no-production-logging.js
<ide>
<ide> 'use strict';
<ide>
<del>const LOGGER_FN_NAMES = [
<del> 'warning',
<del> 'warningWithoutStack',
<del> 'lowPriorityWarning',
<del> 'lowPriorityWarningWithoutStack',
<del>];
<del>
<ide> module.exports = function(context) {
<ide> function isInDEVBlock(node) {
<ide> let done = false;
<ide> module.exports = function(context) {
<ide> }
<ide> }
<ide>
<del> function report(node) {
<add> function reportWrapInDEV(node) {
<ide> context.report({
<ide> node: node,
<del> message: `Wrap {{identifier}}() in an "if (__DEV__) {}" check`,
<add> message: `Wrap console.{{identifier}}() in an "if (__DEV__) {}" check`,
<ide> data: {
<del> identifier: node.callee.name,
<add> identifier: node.property.name,
<ide> },
<ide> fix: function(fixer) {
<ide> return [
<ide> module.exports = function(context) {
<ide> });
<ide> }
<ide>
<del> const isLoggerFunctionName = name => LOGGER_FN_NAMES.includes(name);
<add> function reportUnexpectedConsole(node) {
<add> context.report({
<add> node: node,
<add> message: `Unexpected use of console`,
<add> });
<add> }
<ide>
<ide> return {
<ide> meta: {
<ide> fixable: 'code',
<ide> },
<del> CallExpression: function(node) {
<del> if (!isLoggerFunctionName(node.callee.name)) {
<del> return;
<del> }
<del> if (!isInDEVBlock(node)) {
<del> report(node);
<add> MemberExpression: function(node) {
<add> if (
<add> node.object.type === 'Identifier' &&
<add> node.object.name === 'console' &&
<add> node.property.type === 'Identifier'
<add> ) {
<add> switch (node.property.name) {
<add> case 'error':
<add> case 'warn': {
<add> if (!isInDEVBlock(node)) {
<add> reportWrapInDEV(node);
<add> }
<add> break;
<add> }
<add> default: {
<add> reportUnexpectedConsole(node);
<add> break;
<add> }
<add> }
<ide> }
<ide> },
<ide> };
<ide><path>scripts/eslint-rules/warning-args.js
<ide> module.exports = function(context) {
<ide> // This could be a little smarter by checking context.getScope() to see
<ide> // how warning/invariant was defined.
<ide> const isWarning =
<del> node.callee.type === 'Identifier' &&
<del> (node.callee.name === 'warning' ||
<del> node.callee.name === 'warningWithoutStack' ||
<del> node.callee.name === 'lowPriorityWarning' ||
<del> node.callee.name === 'lowPriorityWarningWithoutStack');
<add> node.callee.type === 'MemberExpression' &&
<add> node.callee.object.type === 'Identifier' &&
<add> node.callee.object.name === 'console' &&
<add> node.callee.property.type === 'Identifier' &&
<add> (node.callee.property.name === 'error' ||
<add> node.callee.property.name === 'warn');
<ide> if (!isWarning) {
<ide> return;
<ide> }
<add> const name = 'console.' + node.callee.property.name;
<ide> if (node.arguments.length < 1) {
<ide> context.report(node, '{{name}} takes at least one argument', {
<del> name: node.callee.name,
<add> name,
<ide> });
<ide> return;
<ide> }
<ide> module.exports = function(context) {
<ide> context.report(
<ide> node,
<ide> 'The first argument to {{name}} must be a string literal',
<del> {name: node.callee.name}
<add> {name}
<ide> );
<ide> return;
<ide> }
<ide> if (format.length < 10 || /^[s\W]*$/.test(format)) {
<ide> context.report(
<ide> node,
<ide> 'The {{name}} format should be able to uniquely identify this ' +
<del> '{{name}}. Please, use a more descriptive format than: {{format}}',
<del> {name: node.callee.name, format: format}
<add> 'warning. Please, use a more descriptive format than: {{format}}',
<add> {name, format}
<ide> );
<ide> return;
<ide> }
<ide> module.exports = function(context) {
<ide> 'the number of "%s" substitutions, but got {{length}}',
<ide> {
<ide> expectedNArgs: expectedNArgs,
<del> name: node.callee.name,
<add> name,
<ide> length: node.arguments.length,
<ide> }
<ide> );
<ide><path>scripts/jest/preprocessor.js
<ide> const pathToBabel = path.join(
<ide> const pathToBabelPluginDevWithCode = require.resolve(
<ide> '../error-codes/transform-error-messages'
<ide> );
<add>const pathToBabelPluginReplaceConsoleCalls = require.resolve(
<add> '../babel/transform-replace-console-calls'
<add>);
<ide> const pathToBabelPluginAsyncToGenerator = require.resolve(
<ide> '@babel/plugin-transform-async-to-generator'
<ide> );
<ide> module.exports = {
<ide> // for test files, we also apply the async-await transform, but we want to
<ide> // make sure we don't accidentally apply that transform to product code.
<ide> const isTestFile = !!filePath.match(/\/__tests__\//);
<add> const testOnlyPlugins = [pathToBabelPluginAsyncToGenerator];
<add> const sourceOnlyPlugins =
<add> process.env.NODE_ENV === 'development'
<add> ? [pathToBabelPluginReplaceConsoleCalls]
<add> : [];
<add> const plugins = (isTestFile ? testOnlyPlugins : sourceOnlyPlugins).concat(
<add> babelOptions.plugins
<add> );
<ide> return babel.transform(
<ide> src,
<ide> Object.assign(
<ide> {filename: path.relative(process.cwd(), filePath)},
<ide> babelOptions,
<del> isTestFile
<del> ? {
<del> plugins: [pathToBabelPluginAsyncToGenerator].concat(
<del> babelOptions.plugins
<del> ),
<del> }
<del> : {}
<add> {
<add> plugins,
<add> }
<ide> )
<ide> );
<ide> }
<ide><path>scripts/print-warnings/print-warnings.js
<ide> function transform(file, enc, cb) {
<ide> exit: function(astPath) {
<ide> const callee = astPath.get('callee');
<ide> if (
<del> callee.isIdentifier({name: 'warning'}) ||
<del> callee.isIdentifier({name: 'warningWithoutStack'}) ||
<del> callee.isIdentifier({name: 'lowPriorityWarning'}) ||
<del> callee.isIdentifier({name: 'lowPriorityWarningWithoutStack'})
<add> callee.matchesPattern('console.warn') ||
<add> callee.matchesPattern('console.error')
<ide> ) {
<ide> const node = astPath.node;
<del>
<add> if (node.callee.type !== 'MemberExpression') {
<add> return;
<add> }
<add> if (node.callee.property.type !== 'Identifier') {
<add> return;
<add> }
<ide> // warning messages can be concatenated (`+`) at runtime, so here's
<ide> // a trivial partial evaluator that interprets the literal value
<ide> try {
<ide> function transform(file, enc, cb) {
<ide>
<ide> gs([
<ide> 'packages/**/*.js',
<del> '!packages/shared/warning.js',
<del> '!packages/shared/lowPriorityWarning.js',
<add> '!packages/*/npm/**/*.js',
<add> '!packages/shared/consoleWithStackDev.js',
<ide> '!packages/react-devtools*/**/*.js',
<ide> '!**/__tests__/**/*.js',
<ide> '!**/__mocks__/**/*.js',
<ide><path>scripts/rollup/build.js
<ide> const closureOptions = {
<ide> rewrite_polyfills: false,
<ide> };
<ide>
<del>function getBabelConfig(updateBabelOptions, bundleType, filename) {
<add>function getBabelConfig(
<add> updateBabelOptions,
<add> bundleType,
<add> packageName,
<add> externals,
<add> isDevelopment
<add>) {
<add> const canAccessReactObject =
<add> packageName === 'react' || externals.indexOf('react') !== -1;
<ide> let options = {
<ide> exclude: '/**/node_modules/**',
<ide> presets: [],
<ide> plugins: [],
<ide> };
<add> if (isDevelopment) {
<add> options.plugins.push(
<add> // Turn console.error/warn() into a custom wrapper
<add> [
<add> require('../babel/transform-replace-console-calls'),
<add> {
<add> shouldError: !canAccessReactObject,
<add> },
<add> ]
<add> );
<add> }
<ide> if (updateBabelOptions) {
<ide> options = updateBabelOptions(options);
<ide> }
<ide> function getPlugins(
<ide> exclude: 'node_modules/**/*',
<ide> }),
<ide> // Compile to ES5.
<del> babel(getBabelConfig(updateBabelOptions, bundleType)),
<add> babel(
<add> getBabelConfig(
<add> updateBabelOptions,
<add> bundleType,
<add> packageName,
<add> externals,
<add> !isProduction
<add> )
<add> ),
<ide> // Remove 'use strict' from individual source files.
<ide> {
<ide> transform(source) {
<ide><path>scripts/rollup/forks.js
<ide> const forks = Object.freeze({
<ide> 'from "' +
<ide> entry +
<ide> '" because it does not declare "react" in the package ' +
<del> 'dependencies or peerDependencies. For example, this can happen if you use ' +
<del> 'warning() instead of warningWithoutStack() in a package that does not ' +
<del> 'depend on React.'
<add> 'dependencies or peerDependencies.'
<ide> );
<ide> }
<ide> return null;
<ide> const forks = Object.freeze({
<ide> return 'scheduler/src/forks/SchedulerHostConfig.default';
<ide> },
<ide>
<del> // This logic is forked on www to ignore some warnings.
<del> 'shared/lowPriorityWarningWithoutStack': (bundleType, entry) => {
<add> 'shared/consoleWithStackDev': (bundleType, entry) => {
<ide> switch (bundleType) {
<ide> case FB_WWW_DEV:
<del> case FB_WWW_PROD:
<del> case FB_WWW_PROFILING:
<del> return 'shared/forks/lowPriorityWarningWithoutStack.www.js';
<del> default:
<del> return null;
<del> }
<del> },
<del>
<del> // This logic is forked on www to ignore some warnings.
<del> 'shared/warningWithoutStack': (bundleType, entry) => {
<del> switch (bundleType) {
<del> case FB_WWW_DEV:
<del> case FB_WWW_PROD:
<del> case FB_WWW_PROFILING:
<del> return 'shared/forks/warningWithoutStack.www.js';
<add> return 'shared/forks/consoleWithStackDev.www.js';
<ide> default:
<ide> return null;
<ide> }
<ide><path>scripts/shared/evalToString.js
<ide> function evalToString(ast /* : Object */) /* : string */ {
<ide> switch (ast.type) {
<ide> case 'StringLiteral':
<add> case 'Literal': // ESLint
<ide> return ast.value;
<ide> case 'BinaryExpression': // `+`
<ide> if (ast.operator !== '+') { | 102 |
PHP | PHP | move comment to appropriate location | 0b9dd1fec3417d778aba2bcaff4436ca1fc7c754 | <ide><path>src/Illuminate/Database/Query/Builder.php
<ide> protected function ungroupedPaginate($paginator, $perPage, $columns)
<ide> */
<ide> public function getPaginationCount()
<ide> {
<add> // Because some database engines may throw errors if we leave the ordering
<add> // statements on the query, we will "back them up" and remove them from
<add> // the query. Once we have the count we will put them back onto this.
<ide> list($orders, $this->orders) = array($this->orders, null);
<ide>
<ide> $columns = $this->columns;
<ide>
<del> // Because some database engines may throw errors if we leave the ordering
<del> // statements on the query, we will "back them up" and remove them from
<del> // the query. Once we have the count we will put them back onto this.
<ide> $total = $this->count();
<ide>
<ide> $this->orders = $orders; | 1 |
Ruby | Ruby | use before_setup to set up test instance variables | fa63448420d3385dbd043aca22dba973b45b8bb2 | <ide><path>actionpack/lib/action_dispatch/testing/integration.rb
<ide> module Runner
<ide>
<ide> APP_SESSIONS = {}
<ide>
<del> def app
<del> @app ||= nil
<add> attr_reader :app, :integration_session
<add>
<add> def before_setup
<add> super
<add> @app = nil
<add> @integration_session = nil
<ide> end
<ide>
<ide> # Reset the current session. This is useful for testing multiple sessions
<ide> def method_missing(sym, *args, &block)
<ide> super
<ide> end
<ide> end
<del>
<del> private
<del> def integration_session
<del> @integration_session ||= nil
<del> end
<ide> end
<ide> end
<ide> | 1 |
Ruby | Ruby | fix dependent order bug | 888c44b238b6a5afa705ca46f6a682ac1c4bb729 | <ide><path>Library/Homebrew/cmd/uninstall.rb
<ide> def uninstall
<ide>
<ide> if !ARGV.force?
<ide> ARGV.kegs.each do |keg|
<del> dependents = keg.installed_dependents
<add> dependents = keg.installed_dependents - ARGV.kegs
<ide> if dependents.any?
<ide> dependents_output = dependents.map { |k| "#{k.name} #{k.version}" }.join(", ")
<ide> conjugation = dependents.count == 1 ? "is" : "are"
<ide><path>Library/Homebrew/test/test_uninstall.rb
<ide> require "helper/integration_command_test_case"
<ide>
<ide> class IntegrationCommandTestUninstall < IntegrationCommandTestCase
<add> def setup
<add> super
<add> @f1_path = setup_test_formula "testball_f1", <<-CONTENT
<add> def install
<add> FileUtils.touch prefix/touch("hello")
<add> end
<add> CONTENT
<add> @f2_path = setup_test_formula "testball_f2", <<-CONTENT
<add> depends_on "testball_f1"
<add>
<add> def install
<add> FileUtils.touch prefix/touch("hello")
<add> end
<add> CONTENT
<add> end
<add>
<ide> def test_uninstall
<ide> cmd("install", testball)
<ide> assert_match "Uninstalling testball", cmd("uninstall", "--force", testball)
<ide> end
<add>
<add> def test_uninstall_leaving_dependents
<add> cmd("install", "testball_f2")
<add> assert_match "Refusing to uninstall", cmd_fail("uninstall", "testball_f1")
<add> assert_match "Uninstalling #{Formulary.factory(@f2_path).rack}",
<add> cmd("uninstall", "testball_f2")
<add> end
<add>
<add> def test_uninstall_dependent_first
<add> cmd("install", "testball_f2")
<add> assert_match "Uninstalling #{Formulary.factory(@f1_path).rack}",
<add> cmd("uninstall", "testball_f2", "testball_f1")
<add> end
<add>
<add> def test_uninstall_dependent_last
<add> cmd("install", "testball_f2")
<add> assert_match "Uninstalling #{Formulary.factory(@f2_path).rack}",
<add> cmd("uninstall", "testball_f1", "testball_f2")
<add> end
<ide> end | 2 |
Ruby | Ruby | add hash support | 77f2d01739ba6738697bd834e6965023ae36eff6 | <ide><path>Library/Homebrew/extend/os/mac/software_spec.rb
<ide>
<ide> class SoftwareSpec
<ide> def uses_from_macos(deps, **args)
<add> if deps.is_a?(Hash)
<add> args = deps
<add> deps = Hash[*args.shift]
<add> end
<add>
<ide> depends_on(deps) if add_mac_dependency?(args)
<ide> end
<ide>
<ide> def add_mac_dependency?(args)
<ide>
<ide> return false if args[:before] && OS::Mac.version >= args[:before]
<ide>
<del> true
<add> args.present?
<ide> end
<ide> end | 1 |
Javascript | Javascript | clarify ngmessages docs with clearer example | 68f528aa04290609422c0d73eeef2c27c8f9a8f6 | <ide><path>src/ngMessages/messages.js
<ide> var jqLite = angular.element;
<ide> * `ngMessage` and `ngMessageExp` directives.
<ide> *
<ide> * # Usage
<del> * The `ngMessages` directive listens on a key/value collection which is set on the ngMessages attribute.
<del> * Since the {@link ngModel ngModel} directive exposes an `$error` object, this error object can be
<del> * used with `ngMessages` to display control error messages in an easier way than with just regular angular
<del> * template directives.
<add> * The `ngMessages` directive allows keys in a key/value collection to be associated with a child element
<add> * (or 'message') that will show or hide based on the truthiness of that key's value in the collection. A common use
<add> * case for `ngMessages` is to display error messages for inputs using the `$error` object exposed by the
<add> * {@link ngModel ngModel} directive.
<add> *
<add> * The child elements of the `ngMessages` directive are matched to the collection keys by a `ngMessage` or
<add> * `ngMessageExp` directive. The value of these attributes must match a key in the collection that is provided by
<add> * the `ngMessages` directive.
<add> *
<add> * Consider the following example, which illustrates a typical use case of `ngMessages`. Within the form `myForm` we
<add> * have a text input named `myField` which is bound to the scope variable `field` using the {@link ngModel ngModel}
<add> * directive.
<add> *
<add> * The `myField` field is a required input of type `email` with a maximum length of 15 characters.
<ide> *
<ide> * ```html
<ide> * <form name="myForm">
<ide> * <label>
<ide> * Enter text:
<del> * <input type="text" ng-model="field" name="myField" required minlength="5" />
<add> * <input type="email" ng-model="field" name="myField" required maxlength="15" />
<ide> * </label>
<ide> * <div ng-messages="myForm.myField.$error" role="alert">
<del> * <div ng-message="required">You did not enter a field</div>
<del> * <div ng-message="minlength, maxlength">
<del> * Your email must be between 5 and 100 characters long
<del> * </div>
<add> * <div ng-message="required">Please enter a value for this field.</div>
<add> * <div ng-message="email">This field must be a valid email address.</div>
<add> * <div ng-message="maxlength">This field can be at most 15 characters long.</div>
<ide> * </div>
<ide> * </form>
<ide> * ```
<ide> *
<del> * Now whatever key/value entries are present within the provided object (in this case `$error`) then
<del> * the ngMessages directive will render the inner first ngMessage directive (depending if the key values
<del> * match the attribute value present on each ngMessage directive). In other words, if your errors
<del> * object contains the following data:
<add> * In order to show error messages corresponding to `myField` we first create an element with an `ngMessages` attribute
<add> * set to the `$error` object owned by the `myField` input in our `myForm` form.
<add> *
<add> * Within this element we then create separate elements for each of the possible errors that `myField` could have.
<add> * The `ngMessage` attribute is used to declare which element(s) will appear for which error - for example,
<add> * setting `ng-message="required"` specifies that this particular element should be displayed when there
<add> * is no value present for the required field `myField` (because the key `required` will be `true` in the object
<add> * `myForm.myField.$error`).
<add> *
<add> * ### Message order
<add> *
<add> * By default, `ngMessages` will only display one message for a particular key/value collection at any time. If more
<add> * than one message (or error) key is currently true, then which message is shown is determined by the order of messages
<add> * in the HTML template code (messages declared first are prioritised). This mechanism means the developer does not have
<add> * to prioritise messages using custom JavaScript code.
<add> *
<add> * Given the following error object for our example (which informs us that the field `myField` currently has both the
<add> * `required` and `email` errors):
<ide> *
<ide> * ```javascript
<ide> * <!-- keep in mind that ngModel automatically sets these error flags -->
<del> * myField.$error = { minlength : true, required : true };
<add> * myField.$error = { required : true, email: true, maxlength: false };
<ide> * ```
<add> * The `required` message will be displayed to the user since it appears before the `email` message in the DOM.
<add> * Once the user types a single character, the `required` message will disappear (since the field now has a value)
<add> * but the `email` message will be visible because it is still applicable.
<ide> *
<del> * Then the `required` message will be displayed first. When required is false then the `minlength` message
<del> * will be displayed right after (since these messages are ordered this way in the template HTML code).
<del> * The prioritization of each message is determined by what order they're present in the DOM.
<del> * Therefore, instead of having custom JavaScript code determine the priority of what errors are
<del> * present before others, the presentation of the errors are handled within the template.
<add> * ### Displaying multiple messages at the same time
<ide> *
<del> * By default, ngMessages will only display one error at a time. However, if you wish to display all
<del> * messages then the `ng-messages-multiple` attribute flag can be used on the element containing the
<del> * ngMessages directive to make this happen.
<add> * While `ngMessages` will by default only display one error element at a time, the `ng-messages-multiple` attribute can
<add> * be applied to the `ngMessages` container element to cause it to display all applicable error messages at once:
<ide> *
<ide> * ```html
<ide> * <!-- attribute-style usage --> | 1 |
PHP | PHP | fix code style 6 | 587668fcf51a329fa6618a97cbb80bce2a855e10 | <ide><path>src/Illuminate/Database/Eloquent/Model.php
<ide> public function qualifyColumns($columns)
<ide>
<ide> foreach ($columns as $column) {
<ide> $qualifiedArray[] = $this->qualifyColumn($column);
<del> }
<del>
<add> }
<add>
<ide> return $qualifiedArray;
<ide> }
<ide> | 1 |
Javascript | Javascript | fix jquery.httpdata to allow forcing of text data | 05a4b784e892ea0dd56201fa1b7a77c7a453bfa7 | <ide><path>ajax/ajax.js
<ide> jQuery.httpSuccess = function(r) {
<ide> r.status == 304 ) || !r.status && location.protocol == "file:";
<ide> };
<ide>
<del>// Get the data out of an XMLHttpRequest
<add>// Get the data out of an XMLHttpRequest.
<add>// Return parsed XML if content-type header is "xml" and type is "xml" or omitted,
<add>// otherwise return plain text.
<ide> jQuery.httpData = function(r,type) {
<del> // Check the headers, or watch for a force override
<del> return r.getResponseHeader("content-type").indexOf("xml") > 0 ||
<del> type == "xml" ? r.responseXML : r.responseText;
<add> var xml = ( !type || type == "xml" ) &&
<add> r.getResponseHeader("content-type").indexOf("xml") >= 0;
<add> return xml ? r.responseXML : r.responseText;
<ide> };
<ide>
<ide> // Serialize an array of form elements or a set of | 1 |
Javascript | Javascript | use the new branch name | fc62398d62b950c6d84f5a6836a5e781a868d9f7 | <ide><path>src/git-repository-async.js
<ide> export default class GitRepositoryAsync {
<ide> refreshStatus () {
<ide> const status = this._refreshStatus()
<ide> const branch = this._refreshBranch()
<del> const aheadBehind = branch.then(branchName => this._refreshAheadBehindCount(branchName))
<add> const aheadBehind = branch.then(() => this._refreshAheadBehindCount(this.branch))
<ide>
<ide> this._refreshingPromise = this._refreshingPromise.then(_ => {
<ide> return Promise.all([status, branch, aheadBehind]) | 1 |
PHP | PHP | fix $depth being decremented by 2 | 0a182b918f2c3c61b6f0e8dc3c79bdaf0223c842 | <ide><path>lib/Cake/Test/Case/Utility/DebuggerTest.php
<ide> public function testExportVar() {
<ide> (int) 1 => 'Index one',
<ide> (int) 5 => 'Index five'
<ide> )
<add>TEXT;
<add> $this->assertTextEquals($expected, $result);
<add>
<add> $data = array(
<add> 'key' => array(
<add> 'value'
<add> )
<add> );
<add> $result = Debugger::exportVar($data, 1);
<add> $expected = <<<TEXT
<add>array(
<add> 'key' => array(
<add> [maximum depth reached]
<add> )
<add>)
<ide> TEXT;
<ide> $this->assertTextEquals($expected, $result);
<ide> }
<ide> public function testDump() {
<ide> <pre>array(
<ide> 'People' => array(
<ide> (int) 0 => array(
<add> 'name' => 'joeseph',
<add> 'coat' => 'technicolor',
<add> 'hair_color' => 'brown'
<ide> ),
<ide> (int) 1 => array(
<add> 'name' => 'Shaft',
<add> 'coat' => 'black',
<add> 'hair' => 'black'
<ide> )
<ide> )
<ide> )</pre>
<ide><path>lib/Cake/Utility/Debugger.php
<ide> protected static function _array(array $var, $depth, $indent) {
<ide> foreach ($var as $key => $val) {
<ide> $vars[] = $break . self::exportVar($key) .
<ide> ' => ' .
<del> self::_export($val, $depth - 1, $indent);
<add> self::_export($val, $depth, $indent);
<ide> }
<add> } else {
<add> $vars[] = $break . '[maximum depth reached]';
<ide> }
<ide> return $out . implode(',', $vars) . $end . ')';
<ide> } | 2 |
Text | Text | add trace category for fs sync methods | 852c4592b14db61f87b3d6b8a8f8588fee09df75 | <ide><path>doc/api/tracing.md
<ide> The available categories are:
<ide> measures and marks.
<ide> * `node.perf.timerify` - Enables capture of only Performance API timerify
<ide> measurements.
<add>* `node.fs.sync` - Enables capture of trace data for file system sync methods.
<ide> * `v8` - The [V8] events are GC, compiling, and execution related.
<ide>
<ide> By default the `node`, `node.async_hooks`, and `v8` categories are enabled. | 1 |
Javascript | Javascript | remove unreachable code | 26f8af9feba624c418be1ec270c8de30bf6ee512 | <ide><path>lib/internal/console/constructor.js
<ide> const consoleMethods = {
<ide> values.push(inspect(v));
<ide> length++;
<ide> }
<del> return final([setlike ? iterKey : indexKey, valuesKey], [
<del> getIndexArray(length),
<del> values,
<del> ]);
<add> return final([iterKey, valuesKey], [getIndexArray(length), values]);
<ide> }
<ide>
<ide> const map = {}; | 1 |
PHP | PHP | allow setting editor for whoops | 71372121752d49d47d9c0407943cfe0092c11cf0 | <ide><path>src/Illuminate/Foundation/Exceptions/Handler.php
<ide> protected function whoopsHandler()
<ide> }
<ide> }
<ide>
<add> if (config('app.debug_editor', false)) {
<add> $handler->setEditor(config('app.debug_editor');
<add> }
<add>
<ide> $handler->setApplicationPaths(
<ide> array_flip(Arr::except(
<ide> array_flip($files->directories(base_path())), [base_path('vendor')] | 1 |
Java | Java | update javadoc of flatmap() overloads | 7494a2c05cf2f02142fc3193682141826974661a | <ide><path>src/main/java/io/reactivex/Flowable.java
<ide> public final Single<T> firstOrError() {
<ide> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/flatMap.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Backpressure:</b></dt>
<del> * <dd>The operator honors backpressure from downstream. The outer {@code Publisher} is consumed
<del> * in unbounded mode (i.e., no backpressure is applied to it). The inner {@code Publisher}s are expected to honor
<del> * backpressure; if violated, the operator <em>may</em> signal {@code MissingBackpressureException}.</dd>
<add> * <dd>The operator honors backpressure from downstream. The upstream Flowable is consumed
<add> * in a bounded manner (up to {@link #bufferSize()} outstanding request amount for items).
<add> * The inner {@code Publisher}s are expected to honor backpressure; if violated,
<add> * the operator <em>may</em> signal {@code MissingBackpressureException}.</dd>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code flatMap} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> * </dl>
<ide> public final <R> Flowable<R> flatMap(Function<? super T, ? extends Publisher<? e
<ide> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/flatMap.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Backpressure:</b></dt>
<del> * <dd>The operator honors backpressure from downstream. The outer {@code Publisher} is consumed
<del> * in unbounded mode (i.e., no backpressure is applied to it). The inner {@code Publisher}s are expected to honor
<del> * backpressure; if violated, the operator <em>may</em> signal {@code MissingBackpressureException}.</dd>
<add> * <dd>The operator honors backpressure from downstream. The upstream Flowable is consumed
<add> * in a bounded manner (up to {@link #bufferSize()} outstanding request amount for items).
<add> * The inner {@code Publisher}s are expected to honor backpressure; if violated,
<add> * the operator <em>may</em> signal {@code MissingBackpressureException}.</dd>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code flatMap} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> * </dl>
<ide> public final <R> Flowable<R> flatMap(Function<? super T, ? extends Publisher<? e
<ide> * <!-- <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/flatMap.png" alt=""> -->
<ide> * <dl>
<ide> * <dt><b>Backpressure:</b></dt>
<del> * <dd>The operator honors backpressure from downstream. Both the outer and inner {@code Publisher}s are expected to honor
<del> * backpressure; if violated, the operator <em>may</em> signal {@code MissingBackpressureException}.</dd>
<add> * <dd>The operator honors backpressure from downstream. The upstream Flowable is consumed
<add> * in a bounded manner (up to {@code maxConcurrency} outstanding request amount for items).
<add> * The inner {@code Publisher}s are expected to honor backpressure; if violated,
<add> * the operator <em>may</em> signal {@code MissingBackpressureException}.</dd>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code flatMap} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> * </dl>
<ide> public final <R> Flowable<R> flatMap(Function<? super T, ? extends Publisher<? e
<ide> * <!-- <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/flatMap.png" alt=""> -->
<ide> * <dl>
<ide> * <dt><b>Backpressure:</b></dt>
<del> * <dd>The operator honors backpressure from downstream. Both the outer and inner {@code Publisher}s are expected to honor
<del> * backpressure; if violated, the operator <em>may</em> signal {@code MissingBackpressureException}.</dd>
<add> * <dd>The operator honors backpressure from downstream. The upstream Flowable is consumed
<add> * in a bounded manner (up to {@code maxConcurrency} outstanding request amount for items).
<add> * The inner {@code Publisher}s are expected to honor backpressure; if violated,
<add> * the operator <em>may</em> signal {@code MissingBackpressureException}.</dd>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code flatMap} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> * </dl>
<ide> public final <R> Flowable<R> flatMap(Function<? super T, ? extends Publisher<? e
<ide> * <!-- <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/flatMap.png" alt=""> -->
<ide> * <dl>
<ide> * <dt><b>Backpressure:</b></dt>
<del> * <dd>The operator honors backpressure from downstream. Both the outer and inner {@code Publisher}s are expected to honor
<del> * backpressure; if violated, the operator <em>may</em> signal {@code MissingBackpressureException}.</dd>
<add> * <dd>The operator honors backpressure from downstream. The upstream Flowable is consumed
<add> * in a bounded manner (up to {@code maxConcurrency} outstanding request amount for items).
<add> * The inner {@code Publisher}s are expected to honor backpressure; if violated,
<add> * the operator <em>may</em> signal {@code MissingBackpressureException}.</dd>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code flatMap} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> * </dl>
<ide> public final <R> Flowable<R> flatMap(Function<? super T, ? extends Publisher<? e
<ide> * <img width="640" height="410" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/mergeMap.nce.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Backpressure:</b></dt>
<del> * <dd>The operator honors backpressure from downstream. The outer {@code Publisher} is consumed
<del> * in unbounded mode (i.e., no backpressure is applied to it). The inner {@code Publisher}s are expected to honor
<del> * backpressure; if violated, the operator <em>may</em> signal {@code MissingBackpressureException}.</dd>
<add> * <dd>The operator honors backpressure from downstream. The upstream Flowable is consumed
<add> * in a bounded manner (up to {@link #bufferSize()} outstanding request amount for items).
<add> * The inner {@code Publisher}s are expected to honor backpressure; if violated,
<add> * the operator <em>may</em> signal {@code MissingBackpressureException}.</dd>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code flatMap} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> * </dl>
<ide> public final <R> Flowable<R> flatMap(
<ide> * <!-- <img width="640" height="410" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/mergeMap.nce.png" alt=""> -->
<ide> * <dl>
<ide> * <dt><b>Backpressure:</b></dt>
<del> * <dd>The operator honors backpressure from downstream. Both the outer and inner {@code Publisher}s are expected to honor
<del> * backpressure; if violated, the operator <em>may</em> signal {@code MissingBackpressureException}.</dd>
<add> * <dd>The operator honors backpressure from downstream. The upstream Flowable is consumed
<add> * in a bounded manner (up to {@code maxConcurrency} outstanding request amount for items).
<add> * The inner {@code Publisher}s are expected to honor backpressure; if violated,
<add> * the operator <em>may</em> signal {@code MissingBackpressureException}.</dd>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code flatMap} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> * </dl>
<ide> public final <R> Flowable<R> flatMap(
<ide> * <img width="640" height="390" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/mergeMap.r.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Backpressure:</b></dt>
<del> * <dd>The operator honors backpressure from downstream. The outer {@code Publisher} is consumed
<del> * in unbounded mode (i.e., no backpressure is applied to it). The inner {@code Publisher}s are expected to honor
<del> * backpressure; if violated, the operator <em>may</em> signal {@code MissingBackpressureException}.</dd>
<add> * <dd>The operator honors backpressure from downstream. The upstream Flowable is consumed
<add> * in a bounded manner (up to {@code maxConcurrency} outstanding request amount for items).
<add> * The inner {@code Publisher}s are expected to honor backpressure; if violated,
<add> * the operator <em>may</em> signal {@code MissingBackpressureException}.</dd>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code flatMap} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> * </dl>
<ide> *
<ide> * @param <U>
<del> * the type of items emitted by the collection Publisher
<add> * the type of items emitted by the inner Publishers
<ide> * @param <R>
<del> * the type of items emitted by the resulting Publisher
<add> * the type of items emitted by the combiner function
<ide> * @param mapper
<ide> * a function that returns a Publisher for each item emitted by the source Publisher
<del> * @param resultSelector
<add> * @param combiner
<ide> * a function that combines one item emitted by each of the source and collection Publishers and
<ide> * returns an item to be emitted by the resulting Publisher
<ide> * @return a Flowable that emits the results of applying a function to a pair of values emitted by the
<ide> public final <R> Flowable<R> flatMap(
<ide> @BackpressureSupport(BackpressureKind.FULL)
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<ide> public final <U, R> Flowable<R> flatMap(Function<? super T, ? extends Publisher<? extends U>> mapper,
<del> BiFunction<? super T, ? super U, ? extends R> resultSelector) {
<del> return flatMap(mapper, resultSelector, false, bufferSize(), bufferSize());
<add> BiFunction<? super T, ? super U, ? extends R> combiner) {
<add> return flatMap(mapper, combiner, false, bufferSize(), bufferSize());
<ide> }
<ide>
<ide> /**
<ide> public final <U, R> Flowable<R> flatMap(Function<? super T, ? extends Publisher<
<ide> * <img width="640" height="390" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/mergeMap.r.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Backpressure:</b></dt>
<del> * <dd>The operator honors backpressure from downstream. The outer {@code Publisher} is consumed
<del> * in unbounded mode (i.e., no backpressure is applied to it). The inner {@code Publisher}s are expected to honor
<del> * backpressure; if violated, the operator <em>may</em> signal {@code MissingBackpressureException}.</dd>
<add> * <dd>The operator honors backpressure from downstream. The upstream Flowable is consumed
<add> * in a bounded manner (up to {@link #bufferSize()} outstanding request amount for items).
<add> * The inner {@code Publisher}s are expected to honor backpressure; if violated,
<add> * the operator <em>may</em> signal {@code MissingBackpressureException}.</dd>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code flatMap} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> * </dl>
<ide> *
<ide> * @param <U>
<del> * the type of items emitted by the collection Publisher
<add> * the type of items emitted by the inner Publishers
<ide> * @param <R>
<del> * the type of items emitted by the resulting Publisher
<add> * the type of items emitted by the combiner functions
<ide> * @param mapper
<ide> * a function that returns a Publisher for each item emitted by the source Publisher
<ide> * @param combiner
<ide> public final <U, R> Flowable<R> flatMap(Function<? super T, ? extends Publisher<
<ide> * <!-- <img width="640" height="390" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/mergeMap.r.png" alt=""> -->
<ide> * <dl>
<ide> * <dt><b>Backpressure:</b></dt>
<del> * <dd>The operator honors backpressure from downstream. Both the outer and inner {@code Publisher}s are expected to honor
<del> * backpressure; if violated, the operator <em>may</em> signal {@code MissingBackpressureException}.</dd>
<add> * <dd>The operator honors backpressure from downstream. The upstream Flowable is consumed
<add> * in a bounded manner (up to {@code maxConcurrency} outstanding request amount for items).
<add> * The inner {@code Publisher}s are expected to honor backpressure; if violated,
<add> * the operator <em>may</em> signal {@code MissingBackpressureException}.</dd>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code flatMap} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> * </dl>
<ide> *
<ide> * @param <U>
<del> * the type of items emitted by the collection Publisher
<add> * the type of items emitted by the inner Publishers
<ide> * @param <R>
<del> * the type of items emitted by the resulting Publisher
<add> * the type of items emitted by the combiner function
<ide> * @param mapper
<ide> * a function that returns a Publisher for each item emitted by the source Publisher
<ide> * @param combiner
<ide> public final <U, R> Flowable<R> flatMap(Function<? super T, ? extends Publisher<
<ide> * <!-- <img width="640" height="390" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/mergeMap.r.png" alt=""> -->
<ide> * <dl>
<ide> * <dt><b>Backpressure:</b></dt>
<del> * <dd>The operator honors backpressure from downstream. Both the outer and inner {@code Publisher}s are expected to honor
<del> * backpressure; if violated, the operator <em>may</em> signal {@code MissingBackpressureException}.</dd>
<add> * <dd>The operator honors backpressure from downstream. The upstream Flowable is consumed
<add> * in a bounded manner (up to {@code maxConcurrency} outstanding request amount for items).
<add> * The inner {@code Publisher}s are expected to honor backpressure; if violated,
<add> * the operator <em>may</em> signal {@code MissingBackpressureException}.</dd>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code flatMap} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> * </dl>
<ide> *
<ide> * @param <U>
<del> * the type of items emitted by the collection Publisher
<add> * the type of items emitted by the inner Publishers
<ide> * @param <R>
<del> * the type of items emitted by the resulting Publisher
<add> * the type of items emitted by the combiner function
<ide> * @param mapper
<ide> * a function that returns a Publisher for each item emitted by the source Publisher
<ide> * @param combiner
<ide> public final <U, R> Flowable<R> flatMap(final Function<? super T, ? extends Publ
<ide> * <!-- <img width="640" height="390" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/mergeMap.r.png" alt=""> -->
<ide> * <dl>
<ide> * <dt><b>Backpressure:</b></dt>
<del> * <dd>The operator honors backpressure from downstream. Both the outer and inner {@code Publisher}s are expected to honor
<del> * backpressure; if violated, the operator <em>may</em> signal {@code MissingBackpressureException}.</dd>
<add> * <dd>The operator honors backpressure from downstream. The upstream Flowable is consumed
<add> * in a bounded manner (up to {@link #bufferSize()} outstanding request amount for items).
<add> * The inner {@code Publisher}s are expected to honor backpressure; if violated,
<add> * the operator <em>may</em> signal {@code MissingBackpressureException}.</dd>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code flatMap} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> * </dl>
<ide> *
<ide> * @param <U>
<del> * the type of items emitted by the collection Publisher
<add> * the type of items emitted by the inner Publishers
<ide> * @param <R>
<del> * the type of items emitted by the resulting Publisher
<add> * the type of items emitted by the combiner function
<ide> * @param mapper
<ide> * a function that returns a Publisher for each item emitted by the source Publisher
<ide> * @param combiner | 1 |
PHP | PHP | update servershell to use provided documentroot | cfa260d8c57b80c4dc262d0801f7fdcfc79d2912 | <ide><path>lib/Cake/Console/Command/ServerShell.php
<ide> public function main() {
<ide> $this->_host,
<ide> $this->_port,
<ide> $this->_documentRoot,
<del> WWW_ROOT . '/index.php'
<add> $this->_documentRoot . '/index.php'
<ide> );
<ide>
<ide> $port = ($this->_port == self::DEFAULT_PORT) ? '' : ':' . $this->_port; | 1 |
Python | Python | enable fanout_patterns for redis config template | 5ecc16f070c31f1e1fc90ac248c5405ad3a0a662 | <ide><path>funtests/stress/stress/templates.py
<ide> class redis(default):
<ide> CELERY_RESULT_BACKEND = os.environ.get(
<ide> 'CSTRESS_BACKEND', 'redis://?new_join=1',
<ide> )
<del> BROKER_TRANSPORT_OPTIONS = {'fanout_prefix': True}
<add> BROKER_TRANSPORT_OPTIONS = {
<add> 'fanout_prefix': True,
<add> 'fanout_patterns': True,
<add> }
<ide>
<ide>
<ide> @template() | 1 |
Text | Text | fix a typo in project/goverance.md | 25dbeab78e578681a05a707f6b3c97b0d1517caf | <ide><path>project/GOVERNANCE.md
<ide> the same steps:
<ide> * **Step 3**: Maintainers merge, close or reject the pull request.
<ide>
<ide> Pull requests are reviewed by the current maintainers of the moby/moby
<del>repository. Weekly meetings are organized to are organized to synchronously
<add>repository. Weekly meetings are organized to synchronously
<ide> discuss tricky PRs, as well as design and architecture decisions.. When
<ide> technical agreement cannot be reached among the maintainers of the project,
<ide> escalation or concerns can be raised by opening an issue to be handled | 1 |
Text | Text | add content to stub | ca1a7e1b774c61a0f4b8ea1c28369586712ce35f | <ide><path>guide/english/mathematics/subtracting-fractions/index.md
<ide> title: Subtracting Fractions
<ide> ---
<ide> ## Subtracting Fractions
<ide>
<del>This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/subtracting-fractions/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<del>
<del><a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<del>
<del><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
<del>
<del>#### More Information:
<del><!-- Please add any articles you think might be helpful to read before writing the article -->
<del>
<add>Subtracting fractions is a bit of a misnomer, as
<add>```
<add>(a/b) - (c/d) = (a/b) + (-c/d),
<add>```
<add>so there is nothing special going on here, it is just the usual [addition](https://github.com/freeCodeCamp/freeCodeCamp/blob/master/guide/english/mathematics/adding-fractions/index.md) of fractions. Namely,
<add>```
<add>(a/b) - (c/d) = (a/b) + (-c/d) = (a*d - b*c)/(d*b).
<add>```
<ide>
<add>For example,
<add>```
<add>1/7 - 3/8 = (1*8 - 7*3)/(7*8) = -13/56.
<add>``` | 1 |
Ruby | Ruby | remove another invalid xml character | fffba3dc7d9bdab6bbce5bed6a096e284fd78fd5 | <ide><path>Library/Homebrew/cmd/test-bot.rb
<ide> def test_bot
<ide>
<ide> if step.has_output?
<ide> # Remove invalid XML CData characters from step output.
<del> output = step.output.delete("\000\a\b\e\f")
<add> output = step.output.delete("\000\a\b\e\f\x1f")
<ide>
<ide> if output.bytesize > BYTES_IN_1_MEGABYTE
<ide> output = "truncated output to 1MB:\n" \ | 1 |
Python | Python | fix additional issue | 59ab502b4c3ef1c83fc716027e6b452cb9cd6280 | <ide><path>celery/backends/base.py
<ide> def fallback_chord_unlock(self, group_id, body, result=None,
<ide>
<ide> def apply_chord(self, header, partial_args, group_id, body,
<ide> options={}, **kwargs):
<del> result = header(*partial_args, task_id=group_id, **options or {})
<add> fixed_options = dict((k,v) for k,v in options.items() if k!='task_id')
<add> result = header(*partial_args, task_id=group_id, **fixed_options or {})
<ide> self.fallback_chord_unlock(group_id, body, **kwargs)
<ide> return result
<ide> | 1 |
Javascript | Javascript | remove fix for object element | 33be48acfdc2059368c3c8d171a1ddb94a3c9be9 | <ide><path>src/manipulation.js
<ide> function fixCloneNodeIssues( src, dest ) {
<ide>
<ide> nodeName = dest.nodeName.toLowerCase();
<ide>
<del> if ( nodeName === "object" ) {
<del> if ( dest.parentNode ) {
<del> dest.outerHTML = src.outerHTML;
<del> }
<del>
<del> // Support: IE 9
<del> // When cloning an object the outerHTML strategy above is not sufficient.
<del> // If the src has innerHTML and the destination does not,
<del> // copy the src.innerHTML into the dest.innerHTML. #10324
<del> if ( src.innerHTML && !jQuery.trim( dest.innerHTML ) ) {
<del> dest.innerHTML = src.innerHTML;
<del> }
<del>
<ide> // Support: IE >= 9
<ide> // Fails to persist the checked state of a cloned checkbox or radio button.
<del> } else if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) {
<add> if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) {
<ide> dest.checked = src.checked;
<ide>
<ide> // Support: IE >= 9 | 1 |
Python | Python | add kyrgyz to char_classes | fe3b5b8ff596117d39a9143f8d076a601e8016db | <ide><path>spacy/lang/char_classes.py
<ide> _tatar_upper = r"ӘӨҮҖҢҺ"
<ide> _tatar = r"әөүҗңһӘӨҮҖҢҺ"
<ide>
<add>_kyrgyz_lower = r"өңү"
<add>_kyrgyz_upper = r"ӨҢҮ"
<add>_kyrgyz = r"өңүӨҢҮ"
<add>
<ide> _greek_lower = r"α-ωάέίόώήύ"
<ide> _greek_upper = r"Α-ΩΆΈΊΌΏΉΎ"
<ide> _greek = r"α-ωάέίόώήύΑ-ΩΆΈΊΌΏΉΎ"
<ide> _macedonian_upper = r"ЃЅЈЉЊЌЀЍ"
<ide> _macedonian = r"ѓѕјљњќѐѝЃЅЈЉЊЌЀЍ"
<ide>
<del>_upper = LATIN_UPPER + _russian_upper + _tatar_upper + _greek_upper + _ukrainian_upper + _macedonian_upper
<del>_lower = LATIN_LOWER + _russian_lower + _tatar_lower + _greek_lower + _ukrainian_lower + _macedonian_lower
<add>_upper = LATIN_UPPER + _russian_upper + _tatar_upper + _kyrgyz_upper + _greek_upper + _ukrainian_upper + _macedonian_upper
<add>_lower = LATIN_LOWER + _russian_lower + _tatar_lower + _kyrgyz_lower + _greek_lower + _ukrainian_lower + _macedonian_lower
<ide>
<ide> _uncased = (
<ide> _ethiopic
<ide> + _cjk
<ide> )
<ide>
<del>ALPHA = group_chars(LATIN + _russian + _tatar + _greek + _ukrainian + _macedonian + _uncased)
<add>ALPHA = group_chars(LATIN + _russian + _tatar + _kyrgyz + _greek + _ukrainian + _macedonian + _uncased)
<ide> ALPHA_LOWER = group_chars(_lower + _uncased)
<ide> ALPHA_UPPER = group_chars(_upper + _uncased)
<ide> | 1 |
Go | Go | use utils.go to get error from monitor | c2b602b2ac7b5b3a67dbb7945e97a9f48b1a625e | <ide><path>container.go
<ide> func (container *Container) Start() (err error) {
<ide>
<ide> // We use a callback here instead of a goroutine and an chan for
<ide> // syncronization purposes
<del> go container.monitor(callback)
<add> cErr := utils.Go(func() error { return container.monitor(callback) })
<ide>
<ide> // Start should not return until the process is actually running
<del> <-waitLock
<del>
<add> select {
<add> case <-waitLock:
<add> case err := <-cErr:
<add> return err
<add> }
<ide> return nil
<ide> }
<ide>
<ide> func (container *Container) releaseNetwork() {
<ide> container.NetworkSettings = &NetworkSettings{}
<ide> }
<ide>
<del>func (container *Container) monitor(callback execdriver.StartCallback) {
<add>func (container *Container) monitor(callback execdriver.StartCallback) error {
<ide> var (
<ide> err error
<ide> exitCode int
<ide> func (container *Container) monitor(callback execdriver.StartCallback) {
<ide> exitCode, err = container.runtime.Run(container, callback)
<ide> }
<ide>
<del> if err != nil { //TODO: @crosbymichael @creack report error
<del> // Since non-zero exit status and signal terminations will cause err to be non-nil,
<del> // we have to actually discard it. Still, log it anyway, just in case.
<del> utils.Debugf("monitor: cmd.Wait reported exit status %s for container %s", err, container.ID)
<add> if err != nil {
<ide> if container.runtime != nil && container.runtime.srv != nil {
<ide> container.runtime.srv.LogEvent("die", container.ID, container.runtime.repositories.ImageName(container.Image))
<ide> }
<ide> func (container *Container) monitor(callback execdriver.StartCallback) {
<ide>
<ide> close(container.waitLock)
<ide>
<del> if err := container.ToDisk(); err != nil {
<del> // FIXME: there is a race condition here which causes this to fail during the unit tests.
<del> // If another goroutine was waiting for Wait() to return before removing the container's root
<del> // from the filesystem... At this point it may already have done so.
<del> // This is because State.setStopped() has already been called, and has caused Wait()
<del> // to return.
<del> // FIXME: why are we serializing running state to disk in the first place?
<del> //log.Printf("%s: Failed to dump configuration to the disk: %s", container.ID, err)
<del> }
<add> // FIXME: there is a race condition here which causes this to fail during the unit tests.
<add> // If another goroutine was waiting for Wait() to return before removing the container's root
<add> // from the filesystem... At this point it may already have done so.
<add> // This is because State.setStopped() has already been called, and has caused Wait()
<add> // to return.
<add> // FIXME: why are we serializing running state to disk in the first place?
<add> //log.Printf("%s: Failed to dump configuration to the disk: %s", container.ID, err)
<add> container.ToDisk()
<add>
<add> return err
<ide> }
<ide>
<ide> func (container *Container) cleanup() { | 1 |
Ruby | Ruby | add test for fetch with a block | b2debfb005cc6d0661b24c50983a885509f7f9c9 | <ide><path>actionpack/lib/action_dispatch/http/headers.rb
<ide> def []=(k,v); @headers[k] = v; end
<ide> def key?(k); @headers.key? k; end
<ide> alias :include? :key?
<ide>
<del> def fetch(header_name, default=nil, &block)
<del> @headers.fetch env_name(header_name), default, &block
<add> def fetch(header_name, *args, &block)
<add> @headers.fetch env_name(header_name), *args, &block
<ide> end
<ide>
<ide> def each(&block)
<ide><path>actionpack/test/dispatch/header_test.rb
<ide> def test_key?
<ide> assert @headers.include?('HTTP_CONTENT_TYPE')
<ide> end
<ide>
<add> def test_fetch_with_block
<add> assert_equal 'omg', @headers.fetch('notthere') { 'omg' }
<add> end
<add>
<ide> test "content type" do
<ide> assert_equal "text/plain", @headers["Content-Type"]
<ide> assert_equal "text/plain", @headers["content-type"] | 2 |
Python | Python | describe default in docstring | bd41739886382ec53e02045cba8a1dc2ab4dfc86 | <ide><path>numpy/lib/arraysetops.py
<ide> def in1d(ar1, ar2, assume_unique=False, invert=False, method='auto'):
<ide> to (but is faster than) ``np.invert(in1d(a, b))``.
<ide> method : {'auto', 'sort', 'dictionary'}, optional
<ide> The algorithm to use. This will not affect the final result,
<del> but will affect the speed.
<add> but will affect the speed. Default is 'auto'.
<ide>
<ide> - If 'sort', will use a sort-based approach.
<ide> - If 'dictionary', will use a key-dictionary approach similar
<ide> def isin(element, test_elements, assume_unique=False, invert=False,
<ide> than) ``np.invert(np.isin(a, b))``.
<ide> method : {'auto', 'sort', 'dictionary'}, optional
<ide> The algorithm to use. This will not affect the final result,
<del> but will affect the speed.
<add> but will affect the speed. Default is 'auto'.
<ide>
<ide> - If 'sort', will use a sort-based approach.
<ide> - If 'dictionary', will use a key-dictionary approach similar | 1 |
Ruby | Ruby | handle some todos and deprecations | 99f960a3d73b62a957988bbee0906264f35afc2e | <ide><path>actionmailer/lib/action_mailer/adv_attr_accessor.rb
<ide> module ActionMailer
<ide> module AdvAttrAccessor #:nodoc:
<ide> def adv_attr_accessor(*names)
<del>
<del> # TODO: ActiveSupport::Deprecation.warn()
<ide> names.each do |name|
<ide> ivar = "@#{name}"
<ide>
<ide><path>actionmailer/lib/action_mailer/base.rb
<ide> def mailer_name
<ide> @mailer_name ||= name.underscore
<ide> end
<ide> attr_writer :mailer_name
<del>
<ide> alias :controller_path :mailer_name
<ide>
<ide> # Receives a raw email, parses it into an email object, decodes it,
<ide> def receive(raw_mail)
<ide> end
<ide> end
<ide>
<del> def template_root
<del> self.view_paths && self.view_paths.first
<del> end
<del>
<del> # Should template root overwrite the whole view_paths?
<del> def template_root=(root)
<del> self.view_paths = ActionView::Base.process_view_paths(root)
<del> end
<del>
<ide> # TODO The delivery should happen inside the instrument block
<ide> def delivered_email(mail)
<del> ActiveSupport::Notifications.instrument("action_mailer.deliver", :mailer => self.name) do |payload|
<add> ActiveSupport::Notifications.instrument("action_mailer.deliver") do |payload|
<ide> self.set_payload_for_mail(payload, mail)
<ide> end
<ide> end
<ide>
<add> def respond_to?(method, *args) #:nodoc:
<add> super || action_methods.include?(method.to_s)
<add> end
<add>
<add> protected
<add>
<ide> def set_payload_for_mail(payload, mail) #:nodoc:
<add> payload[:mailer] = self.name
<ide> payload[:message_id] = mail.message_id
<ide> payload[:subject] = mail.subject
<ide> payload[:to] = mail.to
<ide> def set_payload_for_mail(payload, mail) #:nodoc:
<ide> payload[:mail] = mail.encoded
<ide> end
<ide>
<del> def respond_to?(method, *args)
<del> super || action_methods.include?(method.to_s)
<del> end
<del>
<del> protected
<del>
<del> def method_missing(method, *args)
<add> def method_missing(method, *args) #:nodoc:
<ide> if action_methods.include?(method.to_s)
<ide> new(method, *args).message
<ide> else
<ide> def collect_responses_and_sort_order(headers) #:nodoc:
<ide> :content_type => self.class.default_content_type.dup
<ide> }
<ide> else
<del> self.class.template_root.find_all(action_name, {}, self.class.mailer_name).each do |template|
<add> each_template do |template|
<ide> responses << {
<ide> :body => render_to_body(:_template => template),
<ide> :content_type => template.mime_type.to_s
<ide> def collect_responses_and_sort_order(headers) #:nodoc:
<ide> [responses, sort_order]
<ide> end
<ide>
<add> def each_template(&block) #:nodoc:
<add> self.class.view_paths.each do |load_paths|
<add> templates = load_paths.find_all(action_name, {}, self.class.mailer_name)
<add> unless templates.empty?
<add> templates.each(&block)
<add> return
<add> end
<add> end
<add> end
<add>
<ide> def create_parts_from_responses(m, responses, charset) #:nodoc:
<ide> if responses.size == 1 && !m.has_attachments?
<ide> m.body = responses[0][:body]
<ide><path>actionmailer/lib/action_mailer/deprecated_api.rb
<ide> def deliver(mail, show_warning=true)
<ide> mail
<ide> end
<ide>
<del> def respond_to?(method_symbol, include_private = false) #:nodoc:
<add> def template_root
<add> self.view_paths && self.view_paths.first
<add> end
<add>
<add> def template_root=(root)
<add> ActiveSupport::Deprecation.warn "template_root= is deprecated, use view_paths.unshift instead", caller[0,2]
<add> self.view_paths = ActionView::Base.process_view_paths(root)
<add> end
<add>
<add> def respond_to?(method_symbol, include_private = false)
<ide> matches_dynamic_method?(method_symbol) || super
<ide> end
<ide>
<del> def method_missing(method_symbol, *parameters) #:nodoc:
<add> def method_missing(method_symbol, *parameters)
<ide> if match = matches_dynamic_method?(method_symbol)
<ide> case match[1]
<ide> when 'create'
<ide> def method_missing(method_symbol, *parameters) #:nodoc:
<ide>
<ide> private
<ide>
<del> def matches_dynamic_method?(method_name) #:nodoc:
<add> def matches_dynamic_method?(method_name)
<ide> method_name = method_name.to_s
<ide> /^(create|deliver)_([_a-z]\w*)/.match(method_name) || /^(new)$/.match(method_name)
<ide> end
<ide> def render(*args)
<ide> if options[:body]
<ide> ActiveSupport::Deprecation.warn(':body in render deprecated. Please use instance ' <<
<ide> 'variables as assigns instead', caller[0,1])
<del>
<ide> body options.delete(:body)
<ide> end
<del>
<ide> super
<ide> end
<ide>
<ide> def render_message(*args)
<ide>
<ide> private
<ide>
<del>
<del> def create_parts #:nodoc:
<add> def create_parts
<ide> if @body.is_a?(Hash) && !@body.empty?
<ide> ActiveSupport::Deprecation.warn "Giving a hash to body is deprecated, please use instance variables instead", caller[0,2]
<ide> @body.each { |k, v| instance_variable_set(:"@#{k}", v) }
<ide> end
<del>
<ide> super
<ide> end
<ide>
<ide><path>actionmailer/lib/action_mailer/old_api.rb
<ide> module ActionMailer
<del> module OldApi
<add> module OldApi #:nodoc:
<ide> extend ActiveSupport::Concern
<ide>
<ide> included do
<ide> def normalize_file_hash(params)
<ide> :content_disposition => content_disposition }.merge(params)
<ide> end
<ide>
<del> def create_mail #:nodoc:
<add> def create_mail
<ide> m = @_message
<ide>
<ide> quote_fields!({:subject => subject, :to => recipients, :from => from,
<ide> def create_mail #:nodoc:
<ide> # Set up the default values for the various instance variables of this
<ide> # mailer. Subclasses may override this method to provide different
<ide> # defaults.
<del> def initialize_defaults(method_name) #:nodoc:
<add> def initialize_defaults(method_name)
<ide> @charset ||= self.class.default_charset.dup
<ide> @content_type ||= self.class.default_content_type.dup
<ide> @implicit_parts_order ||= self.class.default_implicit_parts_order.dup
<ide> def initialize_defaults(method_name) #:nodoc:
<ide> @body ||= {}
<ide> end
<ide>
<del> def create_parts #:nodoc:
<add> def create_parts
<ide> if String === @body
<ide> self.response_body = @body
<ide> end
<ide>
<ide> if String === response_body
<ide> @parts.unshift create_inline_part(response_body)
<ide> else
<del> self.class.template_root.find_all(@template, {}, @mailer_name).each do |template|
<add> self.class.view_paths.first.find_all(@template, {}, @mailer_name).each do |template|
<ide> @parts << create_inline_part(render_to_body(:_template => template), template.mime_type)
<ide> end
<ide>
<ide> def create_parts #:nodoc:
<ide> end
<ide> end
<ide>
<del> def create_inline_part(body, mime_type=nil) #:nodoc:
<add> def create_inline_part(body, mime_type=nil)
<ide> ct = mime_type || "text/plain"
<ide> main_type, sub_type = split_content_type(ct.to_s)
<ide>
<ide> def create_inline_part(body, mime_type=nil) #:nodoc:
<ide> )
<ide> end
<ide>
<del> def split_content_type(ct) #:nodoc:
<add> def split_content_type(ct)
<ide> ct.to_s.split("/")
<ide> end
<ide>
<del> def parse_content_type(defaults=nil) #:nodoc:
<add> def parse_content_type(defaults=nil)
<ide> if @content_type.blank?
<ide> [ nil, {} ]
<ide> else
<ide><path>actionmailer/lib/action_mailer/test_helper.rb
<ide> def assert_no_emails(&block)
<ide> end
<ide> end
<ide>
<del># TODO: Deprecate this
<ide> module Test
<ide> module Unit
<ide> class TestCase
<ide><path>actionmailer/test/mail_service_test.rb
<ide> def test_starttls_is_not_enabled
<ide> end
<ide> end
<ide>
<del>class InheritableTemplateRootTest < Test::Unit::TestCase
<add>class InheritableTemplateRootTest < ActiveSupport::TestCase
<ide> def test_attr
<ide> expected = File.expand_path("#{File.dirname(__FILE__)}/fixtures/path.with.dots")
<ide> assert_equal expected, FunkyPathMailer.template_root.to_s
<ide>
<ide> sub = Class.new(FunkyPathMailer)
<del> sub.template_root = 'test/path'
<add> assert_deprecated do
<add> sub.template_root = 'test/path'
<add> end
<ide>
<ide> assert_equal File.expand_path('test/path'), sub.template_root.to_s
<ide> assert_equal expected, FunkyPathMailer.template_root.to_s | 6 |
Python | Python | quarantine a flaky test | 92ba9ee03cb7a47ac7ee5993056816efebd20902 | <ide><path>tests/jobs/test_local_task_job.py
<ide> def task_function(ti):
<ide> (signal.SIGKILL,),
<ide> ]
<ide> )
<add> @pytest.mark.quarantined
<ide> def test_process_kill_calls_on_failure_callback(self, signal_type):
<ide> """
<ide> Test that ensures that when a task is killed with sigterm or sigkill | 1 |
Mixed | Text | add changelog entry for | 9647d4b6f4483f4fc88775020f125c61634192fd | <ide><path>activemodel/CHANGELOG.md
<ide> ## Rails 4.0.0 (unreleased) ##
<ide>
<add>* Fix `validates_presence_of` with `:allow_nil` or `:allow_blank` options.
<add> Fixes #8621.
<add>
<add> *Colin Kelley and Rafael Mendonça França*
<add>
<ide> * Add `ActiveModel::Validations::AbsenceValidator`, a validator to check the
<ide> absence of attributes.
<ide>
<ide><path>activemodel/test/cases/validations/presence_validation_test.rb
<ide> def test_validates_presence_of_for_ruby_class_with_custom_reader
<ide> assert p.valid?
<ide> end
<ide>
<del> def test_allow_nil
<add> def test_validates_presence_of_with_allow_nil_option
<ide> Topic.validates_presence_of(:title, allow_nil: true)
<ide>
<ide> t = Topic.new(title: "something")
<ide> def test_allow_nil
<ide> assert t.valid?, t.errors.full_messages
<ide> end
<ide>
<del> def test_allow_blank
<add> def test_validates_presence_of_with_allow_blank_option
<ide> Topic.validates_presence_of(:title, allow_blank: true)
<ide>
<ide> t = Topic.new(title: "something") | 2 |
Javascript | Javascript | fix ga id | 5613630567b82da517fbe30609d0ab05700453e8 | <ide><path>website/docusaurus.config.js
<ide> module.exports = {
<ide> algoliaOptions: {}
<ide> },
<ide> googleAnalytics: {
<del> trackingID: 'UA-130598673-3'
<add> trackingID: 'UA-130598673-1'
<ide> }
<ide> },
<ide> presets: [ | 1 |
Java | Java | add gethandler in reactive abstracthandlermapping | 1f6f0dc101fb425bd63786ef669b0626a6591543 | <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/config/WebReactiveConfiguration.java
<ide> protected void configureViewResolvers(ViewResolverRegistry registry) {
<ide> private static final class EmptyHandlerMapping extends AbstractHandlerMapping {
<ide>
<ide> @Override
<del> public Mono<Object> getHandler(ServerWebExchange exchange) {
<add> public Mono<Object> getHandlerInternal(ServerWebExchange exchange) {
<ide> return Mono.empty();
<ide> }
<ide> }
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/handler/AbstractHandlerMapping.java
<ide> public CorsProcessor getCorsProcessor() {
<ide> }
<ide>
<ide>
<del> protected Object processCorsRequest(ServerWebExchange exchange, Object handler) {
<del> if (CorsUtils.isCorsRequest(exchange.getRequest())) {
<del> CorsConfiguration configA = this.globalCorsConfigSource.getCorsConfiguration(exchange);
<del> CorsConfiguration configB = getCorsConfiguration(handler, exchange);
<del> CorsConfiguration config = (configA != null ? configA.combine(configB) : configB);
<del>
<del> if (!getCorsProcessor().processRequest(config, exchange) ||
<del> CorsUtils.isPreFlightRequest(exchange.getRequest())) {
<del> return REQUEST_HANDLED_HANDLER;
<add> @Override
<add> public Mono<Object> getHandler(ServerWebExchange exchange) {
<add> return getHandlerInternal(exchange).map(handler -> {
<add> if (CorsUtils.isCorsRequest(exchange.getRequest())) {
<add> CorsConfiguration configA = this.globalCorsConfigSource.getCorsConfiguration(exchange);
<add> CorsConfiguration configB = getCorsConfiguration(handler, exchange);
<add> CorsConfiguration config = (configA != null ? configA.combine(configB) : configB);
<add>
<add> if (!getCorsProcessor().processRequest(config, exchange) ||
<add> CorsUtils.isPreFlightRequest(exchange.getRequest())) {
<add> return REQUEST_HANDLED_HANDLER;
<add> }
<ide> }
<del> }
<del> return handler;
<add> return handler;
<add> });
<ide> }
<ide>
<add> /**
<add> * Look up a handler for the given request, returning an empty {@code Mono}
<add> * if no specific one is found. This method is called by {@link #getHandler}.
<add> *
<add> * <p>On CORS pre-flight requests this method should return a match not for
<add> * the pre-flight request but for the expected actual request based on the URL
<add> * path, the HTTP methods from the "Access-Control-Request-Method" header, and
<add> * the headers from the "Access-Control-Request-Headers" header thus allowing
<add> * the CORS configuration to be obtained via {@link #getCorsConfigurations},
<add> *
<add> * @param exchange current exchange
<add> * @return {@code Mono} for the matching handler, if any
<add> */
<add> protected abstract Mono<?> getHandlerInternal(ServerWebExchange exchange);
<add>
<ide> /**
<ide> * Retrieve the CORS configuration for the given handler.
<ide> * @param handler the handler to check (never {@code null}).
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/handler/AbstractUrlHandlerMapping.java
<ide> public final Map<String, Object> getHandlerMap() {
<ide>
<ide>
<ide> @Override
<del> public Mono<Object> getHandler(ServerWebExchange exchange) {
<add> public Mono<Object> getHandlerInternal(ServerWebExchange exchange) {
<ide> String lookupPath = getPathHelper().getLookupPathForRequest(exchange);
<ide> Object handler;
<ide> try {
<ide> handler = lookupHandler(lookupPath, exchange);
<del> handler = processCorsRequest(exchange, handler);
<ide> }
<ide> catch (Exception ex) {
<ide> return Mono.error(ex);
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/result/method/AbstractHandlerMethodMapping.java
<ide> protected void handlerMethodsInitialized(Map<T, HandlerMethod> handlerMethods) {
<ide> * @param exchange the current exchange
<ide> */
<ide> @Override
<del> public Mono<Object> getHandler(ServerWebExchange exchange) {
<add> public Mono<HandlerMethod> getHandlerInternal(ServerWebExchange exchange) {
<ide> String lookupPath = getPathHelper().getLookupPathForRequest(exchange);
<ide> if (logger.isDebugEnabled()) {
<ide> logger.debug("Looking up handler method for path " + lookupPath);
<ide> public Mono<Object> getHandler(ServerWebExchange exchange) {
<ide> if (handlerMethod != null) {
<ide> handlerMethod = handlerMethod.createWithResolvedBean();
<ide> }
<del> return Mono.justOrEmpty(processCorsRequest(exchange, handlerMethod));
<add> return Mono.justOrEmpty(handlerMethod);
<ide> }
<ide> finally {
<ide> this.mappingRegistry.releaseReadLock(); | 4 |
Ruby | Ruby | ignore schema queries in some habtm tests | b5c4c50aa9f93a5602b895a9931ad529cccf2048 | <ide><path>activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb
<ide> def test_habtm_collection_size_from_params
<ide>
<ide> def test_build
<ide> devel = Developer.find(1)
<del> proj = assert_no_queries { devel.projects.build("name" => "Projekt") }
<add> proj = assert_no_queries(ignore_none: false) { devel.projects.build("name" => "Projekt") }
<ide> assert !devel.projects.loaded?
<ide>
<ide> assert_equal devel.projects.last, proj
<ide> def test_build
<ide>
<ide> def test_new_aliased_to_build
<ide> devel = Developer.find(1)
<del> proj = assert_no_queries { devel.projects.new("name" => "Projekt") }
<add> proj = assert_no_queries(ignore_none: false) { devel.projects.new("name" => "Projekt") }
<ide> assert !devel.projects.loaded?
<ide>
<ide> assert_equal devel.projects.last, proj
<ide> def test_include_uses_array_include_after_loaded
<ide>
<ide> developer = project.developers.first
<ide>
<del> assert_no_queries do
<add> assert_no_queries(ignore_none: false) do
<ide> assert project.developers.loaded?
<ide> assert project.developers.include?(developer)
<ide> end
<ide> def test_destruction_does_not_error_without_primary_key
<ide>
<ide> def test_has_and_belongs_to_many_associations_on_new_records_use_null_relations
<ide> projects = Developer.new.projects
<del> assert_no_queries do
<add> assert_no_queries(ignore_none: false) do
<ide> assert_equal [], projects
<ide> assert_equal [], projects.where(title: 'omg')
<ide> assert_equal [], projects.pluck(:title) | 1 |
PHP | PHP | add missing parameter annotations | de941f5a16500a2af1cfa521a35dbfc29d29681f | <ide><path>tests/TestCase/Collection/CollectionTest.php
<ide> public function testLastWithTraversableNonIterator()
<ide> * Tests the takeLast() method
<ide> *
<ide> * @dataProvider simpleProvider
<add> * @param array $data The data to test with.
<ide> * @return void
<ide> * @covers ::takeLast
<ide> */
<ide> public function testLastN($data)
<ide> * Tests the takeLast() method with overflow
<ide> *
<ide> * @dataProvider simpleProvider
<add> * @param array $data The data to test with.
<ide> * @return void
<ide> * @covers ::takeLast
<ide> */
<ide> public function testLastNtWithOverflow($data)
<ide> * Tests the takeLast() with and odd numbers collection
<ide> *
<ide> * @dataProvider simpleProvider
<add> * @param array $data The data to test with.
<ide> * @return void
<ide> * @covers ::takeLast
<ide> */
<ide> public function testLastNtWithCountable()
<ide> * Tests the takeLast() with countable collection
<ide> *
<ide> * @dataProvider simpleProvider
<add> * @param array $data The data to test with.
<ide> * @return void
<ide> * @covers ::takeLast
<ide> */ | 1 |
Ruby | Ruby | remove unused block | 35870148b6b71b5b77c90fbbd1ac66b5882121f1 | <ide><path>activerecord/lib/active_record/database_configurations.rb
<ide> def initialize(configurations = {})
<ide> # the returned list. Most of the time we're only iterating over the write
<ide> # connection (i.e. migrations don't need to run for the write and read connection).
<ide> # Defaults to +false+.
<del> def configs_for(env_name: nil, spec_name: nil, include_replicas: false, &blk)
<add> def configs_for(env_name: nil, spec_name: nil, include_replicas: false)
<ide> configs = env_with_configs(env_name)
<ide>
<ide> unless include_replicas | 1 |
Text | Text | use better terminology for build machines | 8f5040771475ca5435b6cb78ab2ebce7447afcc1 | <ide><path>doc/changelogs/CHANGELOG_IOJS.md
<ide> will be removed at a later point. (Roman Reiss) [#1363](https://github.com/nodej
<ide>
<ide> ### Notable changes
<ide>
<del>* **tls**: A typo introduced in the TLSWrap changes in [#840](https://github.com/nodejs/node/pull/840) only encountered as a bug on Windows was not caught by the io.js CI system due to problems with the Windows build script and the Windows CI slave configuration, see Known Issues below. Fixed in [#994](https://github.com/nodejs/node/pull/994) & [#1004](https://github.com/nodejs/node/pull/1004). (Fedor Indutny)
<add>* **tls**: A typo introduced in the TLSWrap changes in [#840](https://github.com/nodejs/node/pull/840) only encountered as a bug on Windows was not caught by the io.js CI system due to problems with the Windows build script and the Windows CI configuration, see Known Issues below. Fixed in [#994](https://github.com/nodejs/node/pull/994) & [#1004](https://github.com/nodejs/node/pull/1004). (Fedor Indutny)
<ide> * **npm**: Upgrade npm to 2.6.1. See [npm CHANGELOG.md](https://github.com/npm/npm/blob/master/CHANGELOG.md#v260-2015-02-12) for details. Summary:
<ide> * [`8b98f0e`](https://github.com/npm/npm/commit/8b98f0e709d77a8616c944aebd48ab726f726f76)
<ide> [#4471](https://github.com/npm/npm/issues/4471) `npm outdated` (and only `npm
<ide> _Note: version **1.4.0** was tagged and built but not released. A libuv bug was
<ide> <a id="1.0.1"></a>
<ide> ## 2015-01-14, Version 1.0.1, @rvagg
<ide>
<del>Rebuild due to stale build slave git reflogs for 1.0.0 release
<add>Rebuild due to stale build worker git reflogs for 1.0.0 release
<ide>
<ide> * doc: improve write style consistency (Rui Marinho)
<ide> * win,msi: correct doc website link (Bert Belder)
<ide><path>doc/releases.md
<ide> The [Node.js build team](https://github.com/nodejs/build) is able to provide thi
<ide>
<ide> The _dist_ user on nodejs.org controls the assets available in <https://nodejs.org/download/>. <https://nodejs.org/dist/> is an alias for <https://nodejs.org/download/release/>.
<ide>
<del>The Jenkins release build slaves upload their artifacts to the web server as the _staging_ user. The _dist_ user has access to move these assets to public access while, for security, the _staging_ user does not.
<add>The Jenkins release build workers upload their artifacts to the web server as the _staging_ user. The _dist_ user has access to move these assets to public access while, for security, the _staging_ user does not.
<ide>
<ide> Nightly builds are promoted automatically on the server by a cron task for the _dist_ user.
<ide>
<ide> This is particularly recommended if there has been recent work relating to the m
<ide>
<ide> Use **[iojs+release](https://ci-release.nodejs.org/job/iojs+release/)** to produce release artifacts. Enter the commit that you want to build from and select "release" for "disttype".
<ide>
<del>Artifacts from each slave are uploaded to Jenkins and are available if further testing is required. Use this opportunity particularly to test macOS and Windows installers if there are any concerns. Click through to the individual slaves for a run to find the artifacts.
<add>Artifacts from each worker are uploaded to Jenkins and are available if further testing is required. Use this opportunity particularly to test macOS and Windows installers if there are any concerns. Click through to the individual workers for a run to find the artifacts.
<ide>
<del>All release slaves should achieve "SUCCESS" (and be green, not red). A release with failures should not be promoted as there are likely problems to be investigated.
<add>All release workers should achieve "SUCCESS" (and be green, not red). A release with failures should not be promoted as there are likely problems to be investigated.
<ide>
<ide> You can rebuild the release as many times as you need prior to promoting them if you encounter problems.
<ide>
<del>If you have an error on Windows and need to start again, be aware that you'll get immediate failure unless you wait up to 2 minutes for the linker to stop from previous jobs. i.e. if a build fails after having started compiling, that slave will still have a linker process that's running for another couple of minutes which will prevent Jenkins from clearing the workspace to start a new one. This isn't a big deal, it's just a hassle because it'll result in another failed build if you start again!
<add>If you have an error on Windows and need to start again, be aware that you'll get immediate failure unless you wait up to 2 minutes for the linker to stop from previous jobs. i.e. if a build fails after having started compiling, that worker will still have a linker process that's running for another couple of minutes which will prevent Jenkins from clearing the workspace to start a new one. This isn't a big deal, it's just a hassle because it'll result in another failed build if you start again!
<ide>
<ide> ARMv7 takes the longest to compile. Unfortunately ccache isn't as effective on release builds, I think it's because of the additional macro settings that go in to a release build that nullify previous builds. Also most of the release build machines are separate to the test build machines so they don't get any benefit from ongoing compiles between releases. You can expect 1.5 hours for the ARMv7 builder to complete and you should normally wait for this to finish. It is possible to rush a release out if you want and add additional builds later but we normally provide ARMv7 from initial promotion.
<ide>
<del>You do not have to wait for the ARMv6 / Raspberry PI builds if they take longer than the others. It is only necessary to have the main Linux (x64 and x86), macOS .pkg and .tar.gz, Windows (x64 and x86) .msi and .exe, source, headers and docs (both produced currently by an macOS slave). **If you promote builds _before_ ARM builds have finished, you must repeat the promotion step for the ARM builds when they are ready**.
<add>You do not have to wait for the ARMv6 / Raspberry PI builds if they take longer than the others. It is only necessary to have the main Linux (x64 and x86), macOS .pkg and .tar.gz, Windows (x64 and x86) .msi and .exe, source, headers and docs (both produced currently by an macOS worker). **If you promote builds _before_ ARM builds have finished, you must repeat the promotion step for the ARM builds when they are ready**.
<ide>
<ide> ### 9. Test the Build
<ide> | 2 |
Python | Python | implement rat in maze algorithm. | 23dae9ceabfd8135598b67ca89dc8f199879d88d | <ide><path>backtracking/rat_in_maze.py
<add>def solve_maze(maze: list) -> bool:
<add> """
<add> This method solves rat in maze algorithm.
<add> In this problem we have n by n matrix and we have start point and end point
<add> we want to go from source to distination. In this matrix 0 are block paths
<add> 1 are open paths we can use.
<add> Parameters :
<add> maze(2D matrix) : maze
<add> Returns:
<add> Return: True is maze has a solution or False if it does not.
<add> >>> maze = [[0, 1, 0, 1, 1],
<add> ... [0, 0, 0, 0, 0],
<add> ... [1, 0, 1, 0, 1],
<add> ... [0, 0, 1, 0, 0],
<add> ... [1, 0, 0, 1, 0]]
<add> >>> solve_maze(maze)
<add> [1, 0, 0, 0, 0]
<add> [1, 1, 1, 1, 0]
<add> [0, 0, 0, 1, 0]
<add> [0, 0, 0, 1, 1]
<add> [0, 0, 0, 0, 1]
<add> True
<add>
<add> >>> maze = [[0, 1, 0, 1, 1],
<add> ... [0, 0, 0, 0, 0],
<add> ... [0, 0, 0, 0, 1],
<add> ... [0, 0, 0, 0, 0],
<add> ... [0, 0, 0, 0, 0]]
<add> >>> solve_maze(maze)
<add> [1, 0, 0, 0, 0]
<add> [1, 0, 0, 0, 0]
<add> [1, 0, 0, 0, 0]
<add> [1, 0, 0, 0, 0]
<add> [1, 1, 1, 1, 1]
<add> True
<add>
<add> >>> maze = [[0, 0, 0],
<add> ... [0, 1, 0],
<add> ... [1, 0, 0]]
<add> >>> solve_maze(maze)
<add> [1, 1, 1]
<add> [0, 0, 1]
<add> [0, 0, 1]
<add> True
<add>
<add> >>> maze = [[0, 1, 0],
<add> ... [0, 1, 0],
<add> ... [1, 0, 0]]
<add> >>> solve_maze(maze)
<add> Solution does not exists!
<add> False
<add>
<add> >>> maze = [[0, 1],
<add> ... [1, 0]]
<add> >>> solve_maze(maze)
<add> Solution does not exists!
<add> False
<add> """
<add> size = len(maze)
<add> # We need to create solution object to save path.
<add> solutions = [[0 for _ in range(size)] for _ in range(size)]
<add> solved = run_maze(maze, 0, 0, solutions)
<add> if solved:
<add> print("\n".join(str(row) for row in solutions))
<add> else:
<add> print("Solution does not exists!")
<add> return solved
<add>
<add>
<add>def run_maze(maze, i, j, solutions):
<add> """
<add> This method is recursive method which starts from i and j
<add> and goes with 4 direction option up, down, left, right
<add> if path found to destination it breaks and return True
<add> otherwise False
<add> Parameters:
<add> maze(2D matrix) : maze
<add> i, j : coordinates of matrix
<add> solutions(2D matrix) : solutions
<add> Returns:
<add> Boolean if path is found True, Otherwise False.
<add> """
<add> size = len(maze)
<add> # Final check point.
<add> if i == j == (size - 1):
<add> solutions[i][j] = 1
<add> return True
<add>
<add> lower_flag = (not (i < 0)) and (not (j < 0)) # Check lower bounds
<add> upper_flag = (i < size) and (j < size) # Check upper bounds
<add>
<add> if lower_flag and upper_flag:
<add> # check for already visited and block points.
<add> block_flag = (not (solutions[i][j])) and (not (maze[i][j]))
<add> if block_flag:
<add> # check visited
<add> solutions[i][j] = 1
<add>
<add> # check for directions
<add> if (run_maze(maze, i + 1, j, solutions) or
<add> run_maze(maze, i, j + 1, solutions) or
<add> run_maze(maze, i - 1, j, solutions) or
<add> run_maze(maze, i, j - 1, solutions)):
<add> return True
<add>
<add> solutions[i][j] = 0
<add> return False
<add>
<add>
<add>if __name__ == "__main__":
<add> import doctest
<add>
<add> doctest.testmod() | 1 |
PHP | PHP | add missing classregistry import | 5c590aad0923567f8b40f8a90bfe016477f1b9e8 | <ide><path>lib/Cake/Model/Datasource/Session/DatabaseSession.php
<ide> */
<ide>
<ide> App::uses('CakeSessionHandlerInterface', 'Model/Datasource/Session');
<add>App::uses('ClassRegistry', 'Utility');
<ide>
<ide> /**
<ide> * DatabaseSession provides methods to be used with CakeSession.
<ide><path>lib/Cake/View/Helper/FormHelper.php
<ide> * @since CakePHP(tm) v 0.10.0.1076
<ide> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<ide> */
<del>
<add>App::uses('ClassRegistry', 'Utility');
<ide> App::uses('AppHelper', 'View/Helper');
<ide>
<ide> /** | 2 |
Python | Python | fix comments in min and ptp | 424d84bf6b18be1279d0bb3efefc33e637aad79b | <ide><path>numpy/ma/core.py
<ide> def min(obj, axis=None, out=None, fill_value=None):
<ide> try:
<ide> return obj.min(axis=axis, fill_value=fill_value, out=out)
<ide> except (AttributeError, TypeError):
<del> # If obj doesn't have a max method,
<add> # If obj doesn't have a min method,
<ide> # ...or if the method doesn't accept a fill_value argument
<ide> return asanyarray(obj).min(axis=axis, fill_value=fill_value, out=out)
<ide> min.__doc__ = MaskedArray.min.__doc__
<ide> def ptp(obj, axis=None, out=None, fill_value=None):
<ide> try:
<ide> return obj.ptp(axis, out=out, fill_value=fill_value)
<ide> except (AttributeError, TypeError):
<del> # If obj doesn't have a max method,
<add> # If obj doesn't have a ptp method,
<ide> # ...or if the method doesn't accept a fill_value argument
<ide> return asanyarray(obj).ptp(axis=axis, fill_value=fill_value, out=out)
<ide> ptp.__doc__ = MaskedArray.ptp.__doc__ | 1 |
Javascript | Javascript | add missing semicolon in md2loader | bfa24378d6418af7c49e519383788f9194c73875 | <ide><path>examples/js/loaders/MD2Loader.js
<ide> THREE.MD2Loader.prototype = {
<ide>
<ide> } )()
<ide>
<del>}
<add>}; | 1 |
Ruby | Ruby | avoid ajv@6.9.0 for now | 7942d675b8e63de154cfcd67cde2db5fcba880c7 | <ide><path>railties/test/isolation/abstract_unit.rb
<ide> class ActiveSupport::TestCase
<ide> Dir.chdir(app_template_path) { `yarn add webpack@4.17.1 --tilde` }
<ide> Dir.chdir(app_template_path) { `yarn add webpack-cli` }
<ide>
<add> # FIXME: Temporary fix for webpack + ajv@6.9.0 compatible issue.
<add> # See https://github.com/epoberezkin/ajv/issues/941
<add> Dir.chdir(app_template_path) do
<add> package = File.read("package.json")
<add> resolutions = <<~EOS
<add> ,
<add> "resolutions": {
<add> "ajv": "6.8.1"
<add> }
<add> }
<add> EOS
<add> if package =~ /\n}\n\z/
<add> File.open("package.json", "w") { |f| f.puts $` + resolutions + $' }
<add> end
<add> end
<add>
<ide> # Fake 'Bundler.require' -- we run using the repo's Gemfile, not an
<ide> # app-specific one: we don't want to require every gem that lists.
<ide> contents = File.read("#{app_template_path}/config/application.rb") | 1 |
Mixed | Ruby | touch parent model when an attachment is purged | 396b43a99d436d87c409a1260d55141716ab7cd3 | <ide><path>activestorage/CHANGELOG.md
<add>* Touch parent model when an attachment is purged.
<add>
<add> *Víctor Pérez Rodríguez*
<add>
<ide> * Files can now be served by proxying them from the underlying storage service
<ide> instead of redirecting to a signed service URL. Use the
<ide> `rails_storage_proxy_path` and `_url` helpers to proxy an attached file:
<ide><path>activestorage/app/models/active_storage/attachment.rb
<ide> class ActiveStorage::Attachment < ActiveRecord::Base
<ide>
<ide> # Synchronously deletes the attachment and {purges the blob}[rdoc-ref:ActiveStorage::Blob#purge].
<ide> def purge
<del> delete
<add> transaction do
<add> delete
<add> record&.touch
<add> end
<ide> blob&.purge
<ide> end
<ide>
<ide> # Deletes the attachment and {enqueues a background job}[rdoc-ref:ActiveStorage::Blob#purge_later] to purge the blob.
<ide> def purge_later
<del> delete
<add> transaction do
<add> delete
<add> record&.touch
<add> end
<ide> blob&.purge_later
<ide> end
<ide>
<ide> def purge_dependent_blob_later
<ide> blob&.purge_later if dependent == :purge_later
<ide> end
<ide>
<del>
<ide> def dependent
<ide> record.attachment_reflections[name]&.options[:dependent]
<ide> end
<ide><path>activestorage/test/database/create_users_migration.rb
<ide> def change
<ide> create_table :users do |t|
<ide> t.string :name
<ide> t.integer :group_id
<add> t.timestamps
<ide> end
<ide> end
<ide> end
<ide><path>activestorage/test/models/attached/many_test.rb
<ide> class ActiveStorage::ManyAttachedTest < ActiveSupport::TestCase
<ide> @user.highlights.attach blobs
<ide> assert @user.highlights.attached?
<ide>
<del> @user.highlights.purge
<add> assert_changes -> { @user.updated_at } do
<add> @user.highlights.purge
<add> end
<ide> assert_not @user.highlights.attached?
<ide> assert_not ActiveStorage::Blob.exists?(blobs.first.id)
<ide> assert_not ActiveStorage::Blob.exists?(blobs.second.id)
<ide> class ActiveStorage::ManyAttachedTest < ActiveSupport::TestCase
<ide> assert @user.highlights.attached?
<ide>
<ide> perform_enqueued_jobs do
<del> @user.highlights.purge_later
<add> assert_changes -> { @user.updated_at } do
<add> @user.highlights.purge_later
<add> end
<ide> end
<ide>
<ide> assert_not @user.highlights.attached?
<ide><path>activestorage/test/models/attached/one_test.rb
<ide> def upload.open
<ide> @user.avatar.attach blob
<ide> assert @user.avatar.attached?
<ide>
<del> @user.avatar.purge
<add> assert_changes -> { @user.updated_at } do
<add> @user.avatar.purge
<add> end
<ide> assert_not @user.avatar.attached?
<ide> assert_not ActiveStorage::Blob.exists?(blob.id)
<ide> assert_not ActiveStorage::Blob.service.exist?(blob.key)
<ide> def upload.open
<ide> assert @user.avatar.attached?
<ide>
<ide> perform_enqueued_jobs do
<del> @user.avatar.purge_later
<add> assert_changes -> { @user.updated_at } do
<add> @user.avatar.purge_later
<add> end
<ide> end
<ide>
<ide> assert_not @user.avatar.attached? | 5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.