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 |
|---|---|---|---|---|---|
Ruby | Ruby | fix typo in set_callback docs. [ci skip] | fc4b37c4fbbb0258f4572105cc9477b7a7bbff2e | <ide><path>activesupport/lib/active_support/callbacks.rb
<ide> def __update_callbacks(name) #:nodoc:
<ide> #
<ide> # set_callback :save, :before_meth
<ide> #
<del> # The callback can specified as a symbol naming an instance method; as a
<add> # The callback can be specified as a symbol naming an instance method; as a
<ide> # proc, lambda, or block; as a string to be instance evaluated; or as an
<ide> # object that responds to a certain method determined by the <tt>:scope</tt>
<ide> # argument to +define_callback+. | 1 |
Java | Java | make spacing.release() public | 1eddd01063d6fbc50d96ed8ae5be509ba58067ef | <ide><path>ReactAndroid/src/main/java/com/facebook/csslayout/Spacing.java
<ide> public float getRaw(int spacingType) {
<ide> * Resets the spacing instance to its default state. This method is meant to be used when
<ide> * recycling {@link Spacing} instances.
<ide> */
<del> void reset() {
<add> public void reset() {
<ide> Arrays.fill(mSpacing, CSSConstants.UNDEFINED);
<ide> mHasAliasesSet = false;
<ide> mValueFlags = 0; | 1 |
Javascript | Javascript | use new style of passing watch options | fd4c0042ed0a57212a0b89f93ea1afae73022516 | <ide><path>bin/convert-argv.js
<ide> var path = require("path");
<ide> var fs = require("fs");
<ide> fs.existsSync = fs.existsSync || path.existsSync;
<ide> var resolve = require("enhanced-resolve");
<del>var interpret = require('interpret');
<add>var interpret = require("interpret");
<ide>
<ide> module.exports = function(optimist, argv, convertOptions) {
<ide>
<ide> module.exports = function(optimist, argv, convertOptions) {
<ide> }
<ide>
<ide> if(argv.context) {
<del> options.context = path.resolve(argv.context)
<add> options.context = path.resolve(argv.context);
<ide> }
<ide> if(!options.context) {
<ide> options.context = process.cwd();
<ide> }
<ide>
<ide> if(argv["watch"]) {
<del> options.watch = true;
<add> options.doWatch = true;
<ide> }
<ide>
<ide> if(argv["watch-delay"]) {
<del> options.watchDelay = +argv["watch-delay"];
<add> options.watch = options.watch || {};
<add> options.watch.aggregateTimeout = +argv["watch-delay"];
<ide> }
<ide>
<ide> function processOptions(options) {
<ide> module.exports = function(optimist, argv, convertOptions) {
<ide> if(finalize) {
<ide> finalize();
<ide> }
<del> } else if(typeof argv[name] != "undefined") {
<add> } else if(typeof argv[name] !== "undefined") {
<ide> if(init) {
<ide> init();
<ide> }
<ide> module.exports = function(optimist, argv, convertOptions) {
<ide> if(i < 0) {
<ide> return fn(null, content, idx);
<ide> } else {
<del> return fn(content.substr(0, i), content.substr(i+1), idx);
<add> return fn(content.substr(0, i), content.substr(i + 1), idx);
<ide> }
<ide> }, init, finalize);
<ide> }
<ide> module.exports = function(optimist, argv, convertOptions) {
<ide> addTo("main", content);
<ide> }
<ide> } else {
<del> addTo(content.substr(0, i), content.substr(i+1));
<add> addTo(content.substr(0, i), content.substr(i + 1));
<ide> }
<ide> });
<ide> }
<ide><path>bin/webpack.js
<ide> try {
<ide> return require(localWebpack);
<ide> }
<ide> } catch(e) {}
<del>var fs = require("fs");
<del>var util = require("util");
<ide> var optimist = require("optimist")
<ide> .usage("webpack " + require("../package.json").version + "\n" +
<del> "Usage: http://webpack.github.io/docs/cli.html")
<add> "Usage: http://webpack.github.io/docs/cli.html");
<ide>
<ide> require("./config-optimist")(optimist);
<ide>
<ide> function ifArg(name, fn, init) {
<ide> if(Array.isArray(argv[name])) {
<ide> if(init) init();
<ide> argv[name].forEach(fn);
<del> } else if(typeof argv[name] != "undefined") {
<add> } else if(typeof argv[name] !== "undefined") {
<ide> if(init) init();
<ide> fn(argv[name], -1);
<ide> }
<ide> var webpack = require("../lib/webpack.js");
<ide>
<ide> Error.stackTrackLimit = 30;
<ide> var lastHash = null;
<del>var compiler = webpack(options, function(err, stats) {
<del> if(!options.watch) {
<add>var compiler = webpack(options);
<add>function compilerCallback(err, stats) {
<add> if(!options.doWatch) {
<ide> // Do not keep cache anymore
<ide> compiler.purgeInputFileSystem();
<ide> }
<ide> if(err) {
<ide> lastHash = null;
<ide> console.error(err.stack || err);
<ide> if(err.details) console.error(err.details);
<del> if(!options.watch) {
<add> if(!options.doWatch) {
<ide> process.on("exit", function() {
<ide> process.exit(1);
<ide> });
<ide> var compiler = webpack(options, function(err, stats) {
<ide> lastHash = stats.hash;
<ide> process.stdout.write(stats.toString(outputOptions) + "\n");
<ide> }
<del>});
<add>}
<add>if(options.doWatch)
<add> compiler.watch(options.watch, compilerCallback);
<add>else
<add> compiler.run(compilerCallback); | 2 |
Text | Text | remove redundant empty lines | a3bd06a5e6cf07854dd757dd97c5a0292f8ea0a3 | <ide><path>doc/api/addons.md
<ide> Addon developers are recommended to use to keep compatibility between past and
<ide> future releases of V8 and Node.js. See the `nan` [examples][] for an
<ide> illustration of how it can be used.
<ide>
<del>
<ide> ## N-API
<ide>
<ide> > Stability: 1 - Experimental
<ide> built using `node-gyp`:
<ide> $ node-gyp configure build
<ide> ```
<ide>
<del>
<ide> ### Function arguments
<ide>
<ide> Addons will typically expose objects and functions that can be accessed from
<ide> const addon = require('./build/Release/addon');
<ide> console.log('This should be eight:', addon.add(3, 5));
<ide> ```
<ide>
<del>
<ide> ### Callbacks
<ide>
<ide> It is common practice within Addons to pass JavaScript functions to a C++
<ide> console.log(obj1.msg, obj2.msg);
<ide> // Prints: 'hello world'
<ide> ```
<ide>
<del>
<ide> ### Function factory
<ide>
<ide> Another common scenario is creating JavaScript functions that wrap C++
<ide> console.log(fn());
<ide> // Prints: 'hello world'
<ide> ```
<ide>
<del>
<ide> ### Wrapping C++ objects
<ide>
<ide> It is also possible to wrap C++ objects/classes in a way that allows new
<ide> console.log(obj2.plusOne());
<ide> // Prints: 23
<ide> ```
<ide>
<del>
<ide> ### Passing wrapped objects around
<ide>
<ide> In addition to wrapping and returning C++ objects, it is possible to pass
<ide><path>doc/api/async_hooks.md
<ide> future. This is subject to change in the future if a comprehensive analysis is
<ide> performed to ensure an exception can follow the normal control flow without
<ide> unintentional side effects.
<ide>
<del>
<ide> ##### Printing in AsyncHooks callbacks
<ide>
<ide> Because printing to the console is an asynchronous operation, `console.log()`
<ide> the new resource to initialize and that caused `init` to call. This is different
<ide> from `async_hooks.executionAsyncId()` that only shows *when* a resource was
<ide> created, while `triggerAsyncId` shows *why* a resource was created.
<ide>
<del>
<ide> The following is a simple demonstration of `triggerAsyncId`:
<ide>
<ide> ```js
<ide> API the user's callback is placed in a `process.nextTick()`.
<ide> The graph only shows *when* a resource was created, not *why*, so to track
<ide> the *why* use `triggerAsyncId`.
<ide>
<del>
<ide> ##### before(asyncId)
<ide>
<ide> * `asyncId` {number}
<ide> asynchronous resources like a TCP server will typically call the `before`
<ide> callback multiple times, while other operations like `fs.open()` will call
<ide> it only once.
<ide>
<del>
<ide> ##### after(asyncId)
<ide>
<ide> * `asyncId` {number}
<ide> If an uncaught exception occurs during execution of the callback, then `after`
<ide> will run *after* the `'uncaughtException'` event is emitted or a `domain`'s
<ide> handler runs.
<ide>
<del>
<ide> ##### destroy(asyncId)
<ide>
<ide> * `asyncId` {number}
<ide><path>doc/api/child_process.md
<ide> ls.on('close', (code) => {
<ide> });
<ide> ```
<ide>
<del>
<ide> Example: A very elaborate way to run `ps ax | grep ssh`
<ide>
<ide> ```js
<ide> grep.on('close', (code) => {
<ide> });
<ide> ```
<ide>
<del>
<ide> Example of checking for failed `spawn`:
<ide>
<ide> ```js
<ide><path>doc/api/cli.md
<ide> debugging, multiple ways to execute scripts, and other helpful runtime options.
<ide>
<ide> To view this documentation as a manual page in a terminal, run `man node`.
<ide>
<del>
<ide> ## Synopsis
<ide>
<ide> `node [options] [V8 options] [script.js | -e "script" | -] [--] [arguments]`
<ide> Execute without arguments to start the [REPL][].
<ide>
<ide> _For more info about `node debug`, please see the [debugger][] documentation._
<ide>
<del>
<ide> ## Options
<ide>
<ide> ### `-`
<ide> Alias for stdin, analogous to the use of - in other command line utilities,
<ide> meaning that the script will be read from stdin, and the rest of the options
<ide> are passed to that script.
<ide>
<del>
<ide> ### `--`
<ide> <!-- YAML
<ide> added: v6.11.0
<ide> Indicate the end of node options. Pass the rest of the arguments to the script.
<ide> If no script filename or eval/print script is supplied prior to this, then
<ide> the next argument will be used as a script filename.
<ide>
<del>
<ide> ### `--abort-on-uncaught-exception`
<ide> <!-- YAML
<ide> added: v0.10
<ide> If this flag is passed, the behavior can still be set to not abort through
<ide> [`process.setUncaughtExceptionCaptureCallback()`][] (and through usage of the
<ide> `domain` module that uses it).
<ide>
<del>
<ide> ### `--enable-fips`
<ide> <!-- YAML
<ide> added: v6.0.0
<ide> added: v6.0.0
<ide> Enable FIPS-compliant crypto at startup. (Requires Node.js to be built with
<ide> `./configure --openssl-fips`)
<ide>
<del>
<ide> ### `--experimental-modules`
<ide> <!-- YAML
<ide> added: v8.5.0
<ide> -->
<ide>
<ide> Enable experimental ES module support and caching modules.
<ide>
<del>
<ide> ### `--experimental-repl-await`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> -->
<ide>
<ide> Enable experimental top-level `await` keyword support in REPL.
<ide>
<del>
<ide> ### `--experimental-vm-modules`
<ide> <!-- YAML
<ide> added: v9.6.0
<ide> -->
<ide>
<ide> Enable experimental ES Module support in the `vm` module.
<ide>
<del>
<ide> ### `--force-fips`
<ide> <!-- YAML
<ide> added: v6.0.0
<ide> added: v6.0.0
<ide> Force FIPS-compliant crypto on startup. (Cannot be disabled from script code.)
<ide> (Same requirements as `--enable-fips`)
<ide>
<del>
<ide> ### `--icu-data-dir=file`
<ide> <!-- YAML
<ide> added: v0.11.15
<ide> -->
<ide>
<ide> Specify ICU data load path. (overrides `NODE_ICU_DATA`)
<ide>
<del>
<ide> ### `--inspect-brk[=[host:]port]`
<ide> <!-- YAML
<ide> added: v7.6.0
<ide> added: v7.6.0
<ide> Activate inspector on host:port and break at start of user script.
<ide> Default host:port is 127.0.0.1:9229.
<ide>
<del>
<ide> ### `--inspect-port=[host:]port`
<ide> <!-- YAML
<ide> added: v7.6.0
<ide> Useful when activating the inspector by sending the `SIGUSR1` signal.
<ide>
<ide> Default host is 127.0.0.1.
<ide>
<del>
<ide> ### `--inspect[=[host:]port]`
<ide> <!-- YAML
<ide> added: v6.3.0
<ide> V8 inspector integration allows tools such as Chrome DevTools and IDEs to debug
<ide> and profile Node.js instances. The tools attach to Node.js instances via a
<ide> tcp port and communicate using the [Chrome DevTools Protocol][].
<ide>
<del>
<ide> ### `--napi-modules`
<ide> <!-- YAML
<ide> added: v7.10.0
<ide> -->
<ide>
<ide> This option is a no-op. It is kept for compatibility.
<ide>
<del>
<ide> ### `--no-deprecation`
<ide> <!-- YAML
<ide> added: v0.8.0
<ide> -->
<ide>
<ide> Silence deprecation warnings.
<ide>
<del>
<ide> ### `--no-force-async-hooks-checks`
<ide> <!-- YAML
<ide> added: v9.0.0
<ide> added: v9.0.0
<ide> Disables runtime checks for `async_hooks`. These will still be enabled
<ide> dynamically when `async_hooks` is enabled.
<ide>
<del>
<ide> ### `--no-warnings`
<ide> <!-- YAML
<ide> added: v6.0.0
<ide> -->
<ide>
<ide> Silence all process warnings (including deprecations).
<ide>
<del>
<ide> ### `--openssl-config=file`
<ide> <!-- YAML
<ide> added: v6.9.0
<ide> Load an OpenSSL configuration file on startup. Among other uses, this can be
<ide> used to enable FIPS-compliant crypto if Node.js is built with
<ide> `./configure --openssl-fips`.
<ide>
<del>
<ide> ### `--pending-deprecation`
<ide> <!-- YAML
<ide> added: v8.0.0
<ide> unless either the `--pending-deprecation` command line flag, or the
<ide> are used to provide a kind of selective "early warning" mechanism that
<ide> developers may leverage to detect deprecated API usage.
<ide>
<del>
<ide> ### `--preserve-symlinks`
<ide> <!-- YAML
<ide> added: v6.3.0
<ide> are linked from more than one location in the dependency tree (Node.js would
<ide> see those as two separate modules and would attempt to load the module multiple
<ide> times, causing an exception to be thrown).
<ide>
<del>
<ide> ### `--prof-process`
<ide> <!-- YAML
<ide> added: v5.2.0
<ide> -->
<ide>
<ide> Process V8 profiler output generated using the V8 option `--prof`.
<ide>
<del>
<ide> ### `--redirect-warnings=file`
<ide> <!-- YAML
<ide> added: v8.0.0
<ide> file will be created if it does not exist, and will be appended to if it does.
<ide> If an error occurs while attempting to write the warning to the file, the
<ide> warning will be written to stderr instead.
<ide>
<del>
<ide> ### `--throw-deprecation`
<ide> <!-- YAML
<ide> added: v0.11.14
<ide> -->
<ide>
<ide> Throw errors for deprecations.
<ide>
<del>
<ide> ### `--tls-cipher-list=list`
<ide> <!-- YAML
<ide> added: v4.0.0
<ide> added: v4.0.0
<ide> Specify an alternative default TLS cipher list. (Requires Node.js to be built
<ide> with crypto support. (Default))
<ide>
<del>
<ide> ### `--trace-deprecation`
<ide> <!-- YAML
<ide> added: v0.8.0
<ide> -->
<ide>
<ide> Print stack traces for deprecations.
<ide>
<del>
<ide> ### `--trace-event-categories`
<ide> <!-- YAML
<ide> added: v7.7.0
<ide> added: v7.7.0
<ide> A comma separated list of categories that should be traced when trace event
<ide> tracing is enabled using `--trace-events-enabled`.
<ide>
<del>
<ide> ### `--trace-event-file-pattern`
<ide> <!-- YAML
<ide> added: v9.8.0
<ide> added: v9.8.0
<ide> Template string specifying the filepath for the trace event data, it
<ide> supports `${rotation}` and `${pid}`.
<ide>
<del>
<ide> ### `--trace-events-enabled`
<ide> <!-- YAML
<ide> added: v7.7.0
<ide> -->
<ide>
<ide> Enables the collection of trace event tracing information.
<ide>
<del>
<ide> ### `--trace-sync-io`
<ide> <!-- YAML
<ide> added: v2.1.0
<ide> added: v2.1.0
<ide> Prints a stack trace whenever synchronous I/O is detected after the first turn
<ide> of the event loop.
<ide>
<del>
<ide> ### `--trace-warnings`
<ide> <!-- YAML
<ide> added: v6.0.0
<ide> -->
<ide>
<ide> Print stack traces for process warnings (including deprecations).
<ide>
<del>
<ide> ### `--track-heap-objects`
<ide> <!-- YAML
<ide> added: v2.4.0
<ide> -->
<ide>
<ide> Track heap object allocations for heap snapshots.
<ide>
<del>
<ide> ### `--use-bundled-ca`, `--use-openssl-ca`
<ide> <!-- YAML
<ide> added: v6.11.0
<ide> environment variables.
<ide>
<ide> See `SSL_CERT_DIR` and `SSL_CERT_FILE`.
<ide>
<del>
<ide> ### `--v8-options`
<ide> <!-- YAML
<ide> added: v0.1.3
<ide> underscores (`_`).
<ide>
<ide> For example, `--stack-trace-limit` is equivalent to `--stack_trace_limit`.
<ide>
<del>
<ide> ### `--v8-pool-size=num`
<ide> <!-- YAML
<ide> added: v5.10.0
<ide> on the number of online processors.
<ide> If the value provided is larger than V8's maximum, then the largest value
<ide> will be chosen.
<ide>
<del>
<ide> ### `--zero-fill-buffers`
<ide> <!-- YAML
<ide> added: v6.0.0
<ide> added: v6.0.0
<ide> Automatically zero-fills all newly allocated [`Buffer`][] and [`SlowBuffer`][]
<ide> instances.
<ide>
<del>
<ide> ### `-c`, `--check`
<ide> <!-- YAML
<ide> added:
<ide> changes:
<ide>
<ide> Syntax check the script without executing.
<ide>
<del>
<ide> ### `-e`, `--eval "script"`
<ide> <!-- YAML
<ide> added: v0.5.2
<ide> On Windows, using `cmd.exe` a single quote will not work correctly because it
<ide> only recognizes double `"` for quoting. In Powershell or Git bash, both `'`
<ide> and `"` are usable.
<ide>
<del>
<ide> ### `-h`, `--help`
<ide> <!-- YAML
<ide> added: v0.1.3
<ide> added: v0.1.3
<ide> Print node command line options.
<ide> The output of this option is less detailed than this document.
<ide>
<del>
<ide> ### `-i`, `--interactive`
<ide> <!-- YAML
<ide> added: v0.7.7
<ide> -->
<ide>
<ide> Opens the REPL even if stdin does not appear to be a terminal.
<ide>
<del>
<ide> ### `-p`, `--print "script"`
<ide> <!-- YAML
<ide> added: v0.6.4
<ide> changes:
<ide>
<ide> Identical to `-e` but prints the result.
<ide>
<del>
<ide> ### `-r`, `--require module`
<ide> <!-- YAML
<ide> added: v1.6.0
<ide> Preload the specified module at startup.
<ide> Follows `require()`'s module resolution
<ide> rules. `module` may be either a path to a file, or a node module name.
<ide>
<del>
<ide> ### `-v`, `--version`
<ide> <!-- YAML
<ide> added: v0.1.3
<ide> added: v0.1.32
<ide>
<ide> `','`-separated list of core modules that should print debug information.
<ide>
<del>
<ide> ### `NODE_DISABLE_COLORS=1`
<ide> <!-- YAML
<ide> added: v0.3.0
<ide> -->
<ide>
<ide> When set to `1` colors will not be used in the REPL.
<ide>
<del>
<ide> ### `NODE_EXTRA_CA_CERTS=file`
<ide> <!-- YAML
<ide> added: v7.3.0
<ide> malformed, but any errors are otherwise ignored.
<ide> Note that neither the well known nor extra certificates are used when the `ca`
<ide> options property is explicitly specified for a TLS or HTTPS client or server.
<ide>
<del>
<ide> ### `NODE_ICU_DATA=file`
<ide> <!-- YAML
<ide> added: v0.11.15
<ide> added: v0.11.15
<ide> Data path for ICU (Intl object) data. Will extend linked-in data when compiled
<ide> with small-icu support.
<ide>
<del>
<ide> ### `NODE_NO_WARNINGS=1`
<ide> <!-- YAML
<ide> added: v6.11.0
<ide> -->
<ide>
<ide> When set to `1`, process warnings are silenced.
<ide>
<del>
<ide> ### `NODE_OPTIONS=options...`
<ide> <!-- YAML
<ide> added: v8.0.0
<ide> V8 options that are allowed are:
<ide> - `--perf-prof`
<ide> - `--stack-trace-limit`
<ide>
<del>
<ide> ### `NODE_PATH=path[:…]`
<ide> <!-- YAML
<ide> added: v0.1.32
<ide> added: v0.1.32
<ide>
<ide> On Windows, this is a `';'`-separated list instead.
<ide>
<del>
<ide> ### `NODE_PENDING_DEPRECATION=1`
<ide> <!-- YAML
<ide> added: v8.0.0
<ide> unless either the `--pending-deprecation` command line flag, or the
<ide> are used to provide a kind of selective "early warning" mechanism that
<ide> developers may leverage to detect deprecated API usage.
<ide>
<del>
<ide> ### `NODE_PRESERVE_SYMLINKS=1`
<ide> <!-- YAML
<ide> added: v7.1.0
<ide> added: v7.1.0
<ide> When set to `1`, instructs the module loader to preserve symbolic links when
<ide> resolving and caching modules.
<ide>
<del>
<ide> ### `NODE_REDIRECT_WARNINGS=file`
<ide> <!-- YAML
<ide> added: v8.0.0
<ide> appended to if it does. If an error occurs while attempting to write the
<ide> warning to the file, the warning will be written to stderr instead. This is
<ide> equivalent to using the `--redirect-warnings=file` command-line flag.
<ide>
<del>
<ide> ### `NODE_REPL_HISTORY=file`
<ide> <!-- YAML
<ide> added: v3.0.0
<ide> Path to the file used to store the persistent REPL history. The default path is
<ide> `~/.node_repl_history`, which is overridden by this variable. Setting the value
<ide> to an empty string (`''` or `' '`) disables persistent REPL history.
<ide>
<del>
<ide> ### `OPENSSL_CONF=file`
<ide> <!-- YAML
<ide> added: v6.11.0
<ide> used to enable FIPS-compliant crypto if Node.js is built with `./configure
<ide> If the [`--openssl-config`][] command line option is used, the environment
<ide> variable is ignored.
<ide>
<del>
<ide> ### `SSL_CERT_DIR=dir`
<ide> <!-- YAML
<ide> added: v7.7.0
<ide> Be aware that unless the child environment is explicitly set, this environment
<ide> variable will be inherited by any child processes, and if they use OpenSSL, it
<ide> may cause them to trust the same CAs as node.
<ide>
<del>
<ide> ### `SSL_CERT_FILE=file`
<ide> <!-- YAML
<ide> added: v7.7.0
<ide> Be aware that unless the child environment is explicitly set, this environment
<ide> variable will be inherited by any child processes, and if they use OpenSSL, it
<ide> may cause them to trust the same CAs as node.
<ide>
<del>
<ide> ### `UV_THREADPOOL_SIZE=size`
<ide>
<ide> Set the number of threads used in libuv's threadpool to `size` threads.
<ide><path>doc/api/console.md
<ide> changes:
<ide> will now be ignored by default.
<ide> -->
<ide>
<del>
<ide> <!--type=class-->
<ide>
<ide> The `Console` class can be used to create a simple logger with configurable
<ide><path>doc/api/crypto.md
<ide> the `crypto`, `tls`, and `https` modules and are generally specific to OpenSSL.
<ide> </tr>
<ide> </table>
<ide>
<del>
<ide> [`Buffer`]: buffer.html
<ide> [`EVP_BytesToKey`]: https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html
<ide> [`UV_THREADPOOL_SIZE`]: cli.html#cli_uv_threadpool_size_size
<ide><path>doc/api/dgram.md
<ide> A socket's address family's ANY address (IPv4 `'0.0.0.0'` or IPv6 `'::'`) can be
<ide> used to return control of the sockets default outgoing interface to the system
<ide> for future multicast packets.
<ide>
<del>
<ide> ### socket.setMulticastLoopback(flag)
<ide> <!-- YAML
<ide> added: v0.3.8
<ide><path>doc/api/dns.md
<ide> Uses the DNS protocol to resolve a IPv4 addresses (`A` records) for the
<ide> will contain an array of IPv4 addresses (e.g.
<ide> `['74.125.79.104', '74.125.79.105', '74.125.79.106']`).
<ide>
<del>
<ide> ## dns.resolve6(hostname[, options], callback)
<ide> <!-- YAML
<ide> added: v0.1.16
<ide> Uses the DNS protocol to resolve a IPv6 addresses (`AAAA` records) for the
<ide> `hostname`. The `addresses` argument passed to the `callback` function
<ide> will contain an array of IPv6 addresses.
<ide>
<del>
<ide> ## dns.resolveCname(hostname, callback)
<ide> <!-- YAML
<ide> added: v0.3.2
<ide><path>doc/api/errors.md
<ide> The following properties are provided:
<ide> * `dest` {Buffer} When reporting a file system error, the `dest` will identify
<ide> the file path destination (if any).
<ide>
<del>
<ide> #### error.code
<ide>
<ide> * {string}
<ide><path>doc/api/events.md
<ide> myEmitter.emit('event');
<ide> myEmitter.emit('event');
<ide> // Prints:
<ide> // A
<del>
<ide> ```
<ide>
<ide> Because listeners are managed using an internal array, calling this will
<ide><path>doc/api/fs.md
<ide> Any specified `FileHandle` has to support writing.
<ide> It is unsafe to use `fsPromises.writeFile()` multiple times on the same file
<ide> without waiting for the `Promise` to be resolved (or rejected).
<ide>
<del>
<ide> ## FS Constants
<ide>
<ide> The following constants are exported by `fs.constants`.
<ide><path>doc/api/http.md
<ide> const contentLength = request.getHeader('Content-Length');
<ide> // contentLength is of type number
<ide> const setCookie = request.getHeader('set-cookie');
<ide> // setCookie is of type string[]
<del>
<ide> ```
<ide>
<ide> ### request.removeHeader(name)
<ide> response.end();
<ide> Attempting to set a header field name or value that contains invalid characters
<ide> will result in a [`TypeError`][] being thrown.
<ide>
<del>
<ide> ### response.connection
<ide> <!-- YAML
<ide> added: v0.3.0
<ide><path>doc/api/http2.md
<ide> following additional properties:
<ide> * `type` {string} Either `'server'` or `'client'` to identify the type of
<ide> `Http2Session`.
<ide>
<del>
<ide> [ALPN negotiation]: #http2_alpn_negotiation
<ide> [ALPN Protocol ID]: https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids
<ide> [Compatibility API]: #http2_compatibility_api
<ide><path>doc/api/https.md
<ide> changes:
<ide> - `agent` **Default:** `https.globalAgent`
<ide> - `callback` {Function}
<ide>
<del>
<ide> Makes a request to a secure web server.
<ide>
<ide> The following additional `options` from [`tls.connect()`][] are also accepted:
<ide> req.on('error', (e) => {
<ide> console.error(e.message);
<ide> });
<ide> req.end();
<del>
<ide> ```
<del> Outputs for example:
<add>
<add>Outputs for example:
<add>
<ide> ```text
<ide> Subject Common Name: github.com
<ide> Certificate SHA256 fingerprint: 25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16
<ide><path>doc/api/inspector.md
<ide> session.post('Profiler.enable', () => {
<ide> });
<ide> ```
<ide>
<del>
<ide> [`'Debugger.paused'`]: https://chromedevtools.github.io/devtools-protocol/v8/Debugger#event-paused
<ide> [`EventEmitter`]: events.html#events_class_eventemitter
<ide> [`session.connect()`]: #inspector_session_connect
<ide><path>doc/api/modules.md
<ide> a.on('ready', () => {
<ide> });
<ide> ```
<ide>
<del>
<ide> Note that assignment to `module.exports` must be done immediately. It cannot be
<ide> done in any callbacks. This does not work:
<ide>
<ide><path>doc/api/perf_hooks.md
<ide> added: v8.5.0
<ide> The high resolution millisecond timestamp at which the V8 platform was
<ide> initialized.
<ide>
<del>
<ide> ## Class: PerformanceObserver
<ide>
<ide> ### new PerformanceObserver(callback)
<ide> Returns a list of `PerformanceEntry` objects in chronological order
<ide> with respect to `performanceEntry.startTime` whose `performanceEntry.entryType`
<ide> is equal to `type`.
<ide>
<del>
<ide> ## Examples
<ide>
<ide> ### Measuring the duration of async operations
<ide><path>doc/api/process.md
<ide> that started the Node.js process.
<ide> '/usr/local/bin/node'
<ide> ```
<ide>
<del>
<ide> ## process.exit([code])
<ide> <!-- YAML
<ide> added: v0.1.13
<ide> a code.
<ide> Specifying a code to [`process.exit(code)`][`process.exit()`] will override any
<ide> previous setting of `process.exitCode`.
<ide>
<del>
<ide> ## process.getegid()
<ide> <!-- YAML
<ide> added: v2.0.0
<ide> setTimeout(() => {
<ide> }, 1000);
<ide> ```
<ide>
<del>
<ide> ## process.initgroups(user, extraGroup)
<ide> <!-- YAML
<ide> added: v0.9.4
<ide> if (process.getegid && process.setegid) {
<ide> This function is only available on POSIX platforms (i.e. not Windows or
<ide> Android).
<ide>
<del>
<ide> ## process.seteuid(id)
<ide> <!-- YAML
<ide> added: v2.0.0
<ide> console.log(
<ide> );
<ide> ```
<ide>
<del>
<ide> ## process.uptime()
<ide> <!-- YAML
<ide> added: v0.5.0
<ide> cases:
<ide> For example, signal `SIGABRT` has value `6`, so the expected exit
<ide> code will be `128` + `6`, or `134`.
<ide>
<del>
<ide> [`'exit'`]: #process_event_exit
<ide> [`'finish'`]: stream.html#stream_event_finish
<ide> [`'message'`]: child_process.html#child_process_event_message
<ide><path>doc/api/querystring.md
<ide> added: v0.1.25
<ide> -->
<ide> * `str` {string}
<ide>
<del>
<ide> The `querystring.unescape()` method performs decoding of URL percent-encoded
<ide> characters on the given `str`.
<ide>
<ide><path>doc/api/readline.md
<ide> added: v0.7.7
<ide> The `readline.clearLine()` method clears current line of given [TTY][] stream
<ide> in a specified direction identified by `dir`.
<ide>
<del>
<ide> ## readline.clearScreenDown(stream)
<ide> <!-- YAML
<ide> added: v0.7.7
<ide> added: v0.7.7
<ide> The `readline.moveCursor()` method moves the cursor *relative* to its current
<ide> position in a given [TTY][] `stream`.
<ide>
<del>
<ide> ## Example: Tiny CLI
<ide>
<ide> The following example illustrates the use of `readline.Interface` class to
<ide><path>doc/api/stream.md
<ide> In addition to new Readable streams switching into flowing mode,
<ide> pre-v0.10 style streams can be wrapped in a Readable class using the
<ide> [`readable.wrap()`][`stream.wrap()`] method.
<ide>
<del>
<ide> ### `readable.read(0)`
<ide>
<ide> There are some cases where it is necessary to trigger a refresh of the
<ide><path>doc/api/timers.md
<ide> added: v0.0.1
<ide>
<ide> Cancels a `Timeout` object created by [`setTimeout()`][].
<ide>
<del>
<ide> [`TypeError`]: errors.html#errors_class_typeerror
<ide> [`clearImmediate()`]: timers.html#timers_clearimmediate_immediate
<ide> [`clearInterval()`]: timers.html#timers_clearinterval_timeout
<ide><path>doc/api/tls.md
<ide> more information on how it is used.
<ide> Changes to the ticket keys are effective only for future server connections.
<ide> Existing or currently pending server connections will use the previous keys.
<ide>
<del>
<ide> ## Class: tls.TLSSocket
<ide> <!-- YAML
<ide> added: v0.11.4
<ide> as arguments instead of options.
<ide> A port or host option, if specified, will take precedence over any port or host
<ide> argument.
<ide>
<del>
<ide> ## tls.createSecureContext(options)
<ide> <!-- YAML
<ide> added: v0.11.13
<ide> If the 'ca' option is not given, then Node.js will use the default
<ide> publicly trusted list of CAs as given in
<ide> <https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt>.
<ide>
<del>
<ide> ## tls.createServer([options][, secureConnectionListener])
<ide> <!-- YAML
<ide> added: v0.3.2
<ide> The default curve name to use for ECDH key agreement in a tls server. The
<ide> default value is `'auto'`. See [`tls.createSecureContext()`] for further
<ide> information.
<ide>
<del>
<ide> ## Deprecated APIs
<ide>
<ide> ### Class: CryptoStream
<ide><path>doc/api/url.md
<ide> The formatting process operates as follows:
<ide> string, an [`Error`][] is thrown.
<ide> * `result` is returned.
<ide>
<del>
<ide> ### url.parse(urlString[, parseQueryString[, slashesDenoteHost]])
<ide> <!-- YAML
<ide> added: v0.1.25
<ide><path>doc/api/util.md
<ide> stream.on('data', (data) => {
<ide> console.log(`Received data: "${data}"`);
<ide> });
<ide> stream.write('With ES6');
<del>
<ide> ```
<ide>
<ide> ## util.inspect(object[, options])
<ide> const module = new WebAssembly.Module(wasmBuffer);
<ide> util.types.isWebAssemblyCompiledModule(module); // Returns true
<ide> ```
<ide>
<del>
<ide> ## Deprecated APIs
<ide>
<ide> The following APIs have been deprecated and should no longer be used. Existing
<ide><path>doc/api/vm.md
<ide> changes:
<ide> during script execution, but will continue to work after that.
<ide> If execution is terminated, an [`Error`][] will be thrown.
<ide>
<del>
<ide> Runs the compiled code contained by the `vm.Script` object within the given
<ide> `contextifiedSandbox` and returns the result. Running code does not have access
<ide> to local scope. | 26 |
Text | Text | fix errors in performance hooks doc | 38f48100eb60539346a74fd9c7f85e8c22257d76 | <ide><path>doc/api/perf_hooks.md
<ide> added: v16.7.0
<ide> * `name` {string}
<ide>
<ide> If `name` is not provided, removes all `PerformanceMeasure` objects from the
<del>Performance Timeline. If `name` is provided, removes only the named mark.
<add>Performance Timeline. If `name` is provided, removes only the named measure.
<ide>
<ide> ### `performance.clearResourceTimings([name])`
<ide>
<ide> changes:
<ide> * `options` {Object}
<ide> * `detail` {any} Additional optional detail to include with the mark.
<ide> * `startTime` {number} An optional timestamp to be used as the mark time.
<del> **Defaults**: `performance.now()`.
<add> **Default**: `performance.now()`.
<ide>
<ide> Creates a new `PerformanceMark` entry in the Performance Timeline. A
<ide> `PerformanceMark` is a subclass of `PerformanceEntry` whose
<ide> and can be queried with `performance.getEntries`,
<ide> observation is performed, the entries should be cleared from the global
<ide> Performance Timeline manually with `performance.clearMarks`.
<ide>
<del>### \`performance.markResourceTiming(timingInfo, requestedUrl, initiatorType,
<del>
<del>global, cacheMode)\`
<add>### `performance.markResourceTiming(timingInfo, requestedUrl, initiatorType, global, cacheMode)`
<ide>
<ide> <!-- YAML
<ide> added: v18.2.0 | 1 |
Text | Text | clarify event.istrusted text | 2af43f65055de2817eb7907d3a3d3b3a3de127f5 | <ide><path>doc/api/events.md
<ide> This is not used in Node.js and is provided purely for completeness.
<ide> added: v14.5.0
<ide> -->
<ide>
<del>* Type: {boolean} True for Node.js internal events, false otherwise.
<add>* Type: {boolean}
<ide>
<del>Currently only `AbortSignal`s' `"abort"` event is fired with `isTrusted`
<del>set to `true`.
<add>The {AbortSignal} `"abort"` event is emitted with `isTrusted` set to `true`. The
<add>value is `false` in all other cases.
<ide>
<ide> #### `event.preventDefault()`
<ide> <!-- YAML | 1 |
Javascript | Javascript | stop deep linking `reactproptypes` | 7263c349c7af47d1aa603aa80f8a7a9239c5f807 | <ide><path>Libraries/CameraRoll/CameraRoll.js
<ide> */
<ide> 'use strict';
<ide>
<del>var ReactPropTypes = require('react/lib/ReactPropTypes');
<add>var ReactPropTypes = require('React').PropTypes
<ide> var RCTCameraRollManager = require('NativeModules').CameraRollManager;
<ide>
<ide> var createStrictShapeTypeChecker = require('createStrictShapeTypeChecker');
<ide><path>Libraries/Components/ActivityIndicator/ActivityIndicator.js
<ide> const ColorPropType = require('ColorPropType');
<ide> const NativeMethodsMixin = require('react/lib/NativeMethodsMixin');
<ide> const Platform = require('Platform');
<del>const PropTypes = require('react/lib/ReactPropTypes');
<ide> const React = require('React');
<ide> const StyleSheet = require('StyleSheet');
<ide> const View = require('View');
<ide>
<ide> const requireNativeComponent = require('requireNativeComponent');
<ide>
<add>const PropTypes = React.PropTypes;
<add>
<ide> const GRAY = '#999999';
<ide>
<ide> type IndicatorSize = number | 'small' | 'large';
<ide><path>Libraries/Components/DatePicker/DatePickerIOS.ios.js
<ide> 'use strict';
<ide>
<ide> const NativeMethodsMixin = require('react/lib/NativeMethodsMixin');
<del>const PropTypes = require('react/lib/ReactPropTypes');
<ide> const React = require('React');
<ide> const StyleSheet = require('StyleSheet');
<ide> const View = require('View');
<ide>
<ide> const requireNativeComponent = require('requireNativeComponent');
<ide>
<add>const PropTypes = React.PropTypes;
<add>
<ide> type DefaultProps = {
<ide> mode: 'date' | 'time' | 'datetime',
<ide> };
<ide><path>Libraries/Components/DrawerAndroid/DrawerLayoutAndroid.android.js
<ide> var NativeMethodsMixin = require('react/lib/NativeMethodsMixin');
<ide> var Platform = require('Platform');
<ide> var React = require('React');
<ide> var ReactNative = require('ReactNative');
<del>var ReactPropTypes = require('react/lib/ReactPropTypes');
<ide> var StatusBar = require('StatusBar');
<ide> var StyleSheet = require('StyleSheet');
<ide> var UIManager = require('UIManager');
<ide> var DrawerConsts = UIManager.AndroidDrawerLayout.Constants;
<ide> var dismissKeyboard = require('dismissKeyboard');
<ide> var requireNativeComponent = require('requireNativeComponent');
<ide>
<add>var ReactPropTypes = React.PropTypes;
<add>
<ide> var RK_DRAWER_REF = 'drawerlayout';
<ide> var INNERVIEW_REF = 'innerView';
<ide>
<ide><path>Libraries/Components/Keyboard/KeyboardAvoidingView.js
<ide> const Keyboard = require('Keyboard');
<ide> const LayoutAnimation = require('LayoutAnimation');
<ide> const Platform = require('Platform');
<del>const PropTypes = require('react/lib/ReactPropTypes');
<ide> const React = require('React');
<ide> const TimerMixin = require('react-timer-mixin');
<ide> const View = require('View');
<ide>
<add>const PropTypes = React.PropTypes;
<add>
<ide> import type EmitterSubscription from 'EmitterSubscription';
<ide>
<ide> type Rect = {
<ide><path>Libraries/Components/Picker/PickerAndroid.android.js
<ide> var ColorPropType = require('ColorPropType');
<ide> var React = require('React');
<ide> var ReactChildren = require('react/lib/ReactChildren');
<del>var ReactPropTypes = require('react/lib/ReactPropTypes');
<ide> var StyleSheet = require('StyleSheet');
<ide> var StyleSheetPropType = require('StyleSheetPropType');
<ide> var View = require('View');
<ide> var ViewStylePropTypes = require('ViewStylePropTypes');
<ide> var processColor = require('processColor');
<ide> var requireNativeComponent = require('requireNativeComponent');
<ide>
<add>var ReactPropTypes = React.PropTypes;
<add>
<ide> var REF_PICKER = 'picker';
<del>var MODE_DIALOG = 'dialog';
<ide> var MODE_DROPDOWN = 'dropdown';
<ide>
<ide> var pickerStyleType = StyleSheetPropType({
<ide><path>Libraries/Components/ProgressBarAndroid/ProgressBarAndroid.android.js
<ide>
<ide> var NativeMethodsMixin = require('react/lib/NativeMethodsMixin');
<ide> var React = require('React');
<del>var ReactPropTypes = require('react/lib/ReactPropTypes');
<ide> var View = require('View');
<ide> var ColorPropType = require('ColorPropType');
<ide>
<ide> var requireNativeComponent = require('requireNativeComponent');
<ide>
<add>var ReactPropTypes = React.PropTypes;
<add>
<ide> var STYLE_ATTRIBUTES = [
<ide> 'Horizontal',
<ide> 'Normal',
<ide> 'Small',
<ide> 'Large',
<ide> 'Inverse',
<ide> 'SmallInverse',
<del> 'LargeInverse'
<add> 'LargeInverse',
<ide> ];
<ide>
<ide> var indeterminateType = function(props, propName, componentName) {
<ide><path>Libraries/Components/ProgressViewIOS/ProgressViewIOS.ios.js
<ide>
<ide> var Image = require('Image');
<ide> var NativeMethodsMixin = require('react/lib/NativeMethodsMixin');
<del>var PropTypes = require('react/lib/ReactPropTypes');
<ide> var React = require('React');
<ide> var StyleSheet = require('StyleSheet');
<ide> var View = require('View');
<ide>
<ide> var requireNativeComponent = require('requireNativeComponent');
<ide>
<add>var PropTypes = React.PropTypes;
<add>
<ide> /**
<ide> * Use `ProgressViewIOS` to render a UIProgressView on iOS.
<ide> */
<ide><path>Libraries/Components/SegmentedControlIOS/SegmentedControlIOS.ios.js
<ide> 'use strict';
<ide>
<ide> var NativeMethodsMixin = require('react/lib/NativeMethodsMixin');
<del>var PropTypes = require('react/lib/ReactPropTypes');
<ide> var React = require('React');
<ide> var StyleSheet = require('StyleSheet');
<ide> var View = require('View');
<ide>
<ide> var requireNativeComponent = require('requireNativeComponent');
<ide>
<add>var PropTypes = React.PropTypes;
<add>
<ide> type DefaultProps = {
<ide> values: Array<string>,
<ide> enabled: boolean,
<ide><path>Libraries/Components/Slider/Slider.js
<ide> var Image = require('Image');
<ide> var NativeMethodsMixin = require('react/lib/NativeMethodsMixin');
<ide> var ReactNativeViewAttributes = require('ReactNativeViewAttributes');
<ide> var Platform = require('Platform');
<del>var PropTypes = require('react/lib/ReactPropTypes');
<ide> var React = require('React');
<ide> var StyleSheet = require('StyleSheet');
<ide> var View = require('View');
<ide>
<ide> var requireNativeComponent = require('requireNativeComponent');
<ide>
<add>var PropTypes = React.PropTypes;
<add>
<ide> type Event = Object;
<ide>
<ide> /**
<ide><path>Libraries/Components/TextInput/TextInput.js
<ide> const DocumentSelectionState = require('DocumentSelectionState');
<ide> const EventEmitter = require('EventEmitter');
<ide> const NativeMethodsMixin = require('react/lib/NativeMethodsMixin');
<ide> const Platform = require('Platform');
<del>const PropTypes = require('react/lib/ReactPropTypes');
<ide> const React = require('React');
<ide> const ReactNative = require('ReactNative');
<ide> const ReactChildren = require('react/lib/ReactChildren');
<ide> const emptyFunction = require('fbjs/lib/emptyFunction');
<ide> const invariant = require('fbjs/lib/invariant');
<ide> const requireNativeComponent = require('requireNativeComponent');
<ide>
<add>const PropTypes = React.PropTypes;
<add>
<ide> const onlyMultiline = {
<ide> onTextInput: true,
<ide> children: true,
<ide><path>Libraries/Components/ToolbarAndroid/ToolbarAndroid.android.js
<ide> var Image = require('Image');
<ide> var NativeMethodsMixin = require('react/lib/NativeMethodsMixin');
<ide> var React = require('React');
<ide> var ReactNativeViewAttributes = require('ReactNativeViewAttributes');
<del>var ReactPropTypes = require('react/lib/ReactPropTypes');
<ide> var UIManager = require('UIManager');
<ide> var View = require('View');
<ide> var ColorPropType = require('ColorPropType');
<ide>
<ide> var requireNativeComponent = require('requireNativeComponent');
<ide> var resolveAssetSource = require('resolveAssetSource');
<ide>
<add>var ReactPropTypes = React.PropTypes;
<add>
<ide> var optionalImageSource = ReactPropTypes.oneOfType([
<ide> Image.propTypes.source,
<ide> // Image.propTypes.source is required but we want it to be optional, so we OR
<ide> // it with a nullable propType.
<del> ReactPropTypes.oneOf([])
<add> ReactPropTypes.oneOf([]),
<ide> ]);
<ide>
<ide> /**
<ide><path>Libraries/Components/Touchable/TouchableNativeFeedback.android.js
<ide> 'use strict';
<ide>
<ide> var Platform = require('Platform');
<del>var PropTypes = require('react/lib/ReactPropTypes');
<ide> var React = require('React');
<ide> var ReactNative = require('ReactNative');
<ide> var Touchable = require('Touchable');
<ide> var ensurePositiveDelayProps = require('ensurePositiveDelayProps');
<ide> var processColor = require('processColor');
<ide> var requireNativeComponent = require('requireNativeComponent');
<ide>
<add>var PropTypes = React.PropTypes;
<add>
<ide> var rippleBackgroundPropType = PropTypes.shape({
<ide> type: React.PropTypes.oneOf(['RippleAndroid']),
<ide> color: PropTypes.number,
<ide> var TouchableView = requireNativeComponent('RCTView', null, {
<ide> nativeOnly: {
<ide> nativeBackgroundAndroid: backgroundPropType,
<ide> nativeForegroundAndroid: backgroundPropType,
<del> }
<add> },
<ide> });
<ide>
<ide> type Event = Object;
<ide><path>Libraries/Components/View/ShadowPropTypesIOS.js
<ide> 'use strict';
<ide>
<ide> var ColorPropType = require('ColorPropType');
<del>var ReactPropTypes = require('react/lib/ReactPropTypes');
<add>var ReactPropTypes = require('React').PropTypes;
<ide>
<ide> var ShadowPropTypesIOS = {
<ide> /**
<ide><path>Libraries/Components/View/View.js
<ide>
<ide> const EdgeInsetsPropType = require('EdgeInsetsPropType');
<ide> const NativeMethodsMixin = require('react/lib/NativeMethodsMixin');
<del>const PropTypes = require('react/lib/ReactPropTypes');
<ide> const React = require('React');
<ide> const ReactNativeStyleAttributes = require('ReactNativeStyleAttributes');
<ide> const ReactNativeViewAttributes = require('ReactNativeViewAttributes');
<ide> const ViewStylePropTypes = require('ViewStylePropTypes');
<ide>
<ide> const requireNativeComponent = require('requireNativeComponent');
<ide>
<add>const PropTypes = React.PropTypes;
<add>
<ide> const stylePropType = StyleSheetPropType(ViewStylePropTypes);
<ide>
<ide> const AccessibilityTraits = [
<ide><path>Libraries/Components/View/ViewStylePropTypes.js
<ide> 'use strict';
<ide>
<ide> var LayoutPropTypes = require('LayoutPropTypes');
<del>var ReactPropTypes = require('react/lib/ReactPropTypes');
<add>var ReactPropTypes = require('React').PropTypes;
<ide> var ColorPropType = require('ColorPropType');
<ide> var ShadowPropTypesIOS = require('ShadowPropTypesIOS');
<ide> var TransformPropTypes = require('TransformPropTypes');
<ide><path>Libraries/Components/ViewPager/ViewPagerAndroid.android.js
<ide> var React = require('React');
<ide> var ReactNative = require('ReactNative');
<ide> var ReactElement = require('react/lib/ReactElement');
<del>var ReactPropTypes = require('react/lib/ReactPropTypes');
<ide> var UIManager = require('UIManager');
<ide> var View = require('View');
<ide>
<ide> var dismissKeyboard = require('dismissKeyboard');
<ide> var requireNativeComponent = require('requireNativeComponent');
<ide>
<add>var ReactPropTypes = React.PropTypes;
<add>
<ide> var VIEWPAGER_REF = 'viewPager';
<ide>
<ide> type Event = Object;
<ide><path>Libraries/Image/Image.android.js
<ide> var NativeModules = require('NativeModules');
<ide> var ImageResizeMode = require('ImageResizeMode');
<ide> var ImageStylePropTypes = require('ImageStylePropTypes');
<ide> var ViewStylePropTypes = require('ViewStylePropTypes');
<del>var PropTypes = require('react/lib/ReactPropTypes');
<ide> var React = require('React');
<ide> var ReactNativeViewAttributes = require('ReactNativeViewAttributes');
<ide> var StyleSheet = require('StyleSheet');
<ide> var resolveAssetSource = require('resolveAssetSource');
<ide> var Set = require('Set');
<ide> var filterObject = require('fbjs/lib/filterObject');
<ide>
<add>var PropTypes = React.PropTypes;
<ide> var {
<ide> ImageLoader,
<ide> } = NativeModules;
<ide><path>Libraries/Image/Image.ios.js
<ide> const ImageSourcePropType = require('ImageSourcePropType');
<ide> const ImageStylePropTypes = require('ImageStylePropTypes');
<ide> const NativeMethodsMixin = require('react/lib/NativeMethodsMixin');
<ide> const NativeModules = require('NativeModules');
<del>const PropTypes = require('react/lib/ReactPropTypes');
<ide> const React = require('React');
<ide> const ReactNativeViewAttributes = require('ReactNativeViewAttributes');
<ide> const StyleSheet = require('StyleSheet');
<ide> const flattenStyle = require('flattenStyle');
<ide> const requireNativeComponent = require('requireNativeComponent');
<ide> const resolveAssetSource = require('resolveAssetSource');
<ide>
<add>const PropTypes = React.PropTypes;
<add>
<ide> const ImageViewManager = NativeModules.ImageViewManager;
<ide>
<ide> /**
<ide><path>Libraries/Image/ImageSourcePropType.js
<ide> */
<ide> 'use strict';
<ide>
<del>const PropTypes = require('react/lib/ReactPropTypes');
<add>const {PropTypes} = require('React');
<ide>
<ide> const ImageURISourcePropType = PropTypes.shape({
<ide> /**
<ide><path>Libraries/Image/ImageStylePropTypes.js
<ide>
<ide> var ImageResizeMode = require('ImageResizeMode');
<ide> var LayoutPropTypes = require('LayoutPropTypes');
<del>var ReactPropTypes = require('react/lib/ReactPropTypes');
<ide> var ColorPropType = require('ColorPropType');
<ide> var ShadowPropTypesIOS = require('ShadowPropTypesIOS');
<ide> var TransformPropTypes = require('TransformPropTypes');
<ide>
<add>var ReactPropTypes = require('React').PropTypes;
<add>
<ide> var ImageStylePropTypes = {
<ide> ...LayoutPropTypes,
<ide> ...ShadowPropTypesIOS,
<ide><path>Libraries/Inspector/ElementProperties.js
<ide> 'use strict';
<ide>
<ide> var BoxInspector = require('BoxInspector');
<del>var PropTypes = require('react/lib/ReactPropTypes');
<ide> var React = require('React');
<ide> var StyleInspector = require('StyleInspector');
<ide> var StyleSheet = require('StyleSheet');
<ide> var Text = require('Text');
<ide> var TouchableHighlight = require('TouchableHighlight');
<ide> var TouchableWithoutFeedback = require('TouchableWithoutFeedback');
<ide> var View = require('View');
<del>var {fetch} = require('fetch');
<ide>
<ide> var flattenStyle = require('flattenStyle');
<ide> var mapWithSeparator = require('mapWithSeparator');
<ide> var openFileInEditor = require('openFileInEditor');
<ide>
<add>var PropTypes = React.PropTypes;
<add>
<ide> class ElementProperties extends React.Component {
<ide> props: {
<ide> hierarchy: Array<$FlowFixMe>,
<ide><path>Libraries/LayoutAnimation/LayoutAnimation.js
<ide> */
<ide> 'use strict';
<ide>
<del>var PropTypes = require('react/lib/ReactPropTypes');
<add>var {PropTypes} = require('React');
<ide> var UIManager = require('UIManager');
<ide>
<ide> var createStrictShapeTypeChecker = require('createStrictShapeTypeChecker');
<ide><path>Libraries/Modal/Modal.js
<ide> const AppContainer = require('AppContainer');
<ide> const I18nManager = require('I18nManager');
<ide> const Platform = require('Platform');
<del>const PropTypes = require('react/lib/ReactPropTypes');
<ide> const React = require('React');
<ide> const StyleSheet = require('StyleSheet');
<ide> const View = require('View');
<ide> const deprecatedPropType = require('deprecatedPropType');
<ide> const requireNativeComponent = require('requireNativeComponent');
<ide> const RCTModalHostView = requireNativeComponent('RCTModalHostView', null);
<ide>
<add>const PropTypes = React.PropTypes;
<add>
<ide> /**
<ide> * The Modal component is a simple way to present content above an enclosing view.
<ide> *
<ide><path>Libraries/StyleSheet/EdgeInsetsPropType.js
<ide> */
<ide> 'use strict';
<ide>
<del>var PropTypes = require('react/lib/ReactPropTypes');
<add>var {PropTypes} = require('React');
<ide>
<ide> var createStrictShapeTypeChecker = require('createStrictShapeTypeChecker');
<ide>
<ide><path>Libraries/StyleSheet/LayoutPropTypes.js
<ide> */
<ide> 'use strict';
<ide>
<del>var ReactPropTypes = require('react/lib/ReactPropTypes');
<add>var ReactPropTypes = require('React').PropTypes;
<ide>
<ide> /**
<ide> * React Native's layout system is based on Flexbox and is powered both
<ide><path>Libraries/StyleSheet/PointPropType.js
<ide> */
<ide> 'use strict';
<ide>
<del>var PropTypes = require('react/lib/ReactPropTypes');
<add>var PropTypes = require('React').PropTypes;
<ide>
<ide> var createStrictShapeTypeChecker = require('createStrictShapeTypeChecker');
<ide>
<ide><path>Libraries/StyleSheet/TransformPropTypes.js
<ide> */
<ide> 'use strict';
<ide>
<del>var ReactPropTypes = require('react/lib/ReactPropTypes');
<ide> var deprecatedPropType = require('deprecatedPropType');
<ide>
<del>var ArrayOfNumberPropType = ReactPropTypes.arrayOf(ReactPropTypes.number);
<add>var ReactPropTypes = require('React').PropTypes;
<ide>
<ide> var TransformMatrixPropType = function(
<ide> props : Object,
<ide><path>Libraries/Text/TextStylePropTypes.js
<ide> */
<ide> 'use strict';
<ide>
<del>var ReactPropTypes = require('react/lib/ReactPropTypes');
<add>var ReactPropTypes = require('React').PropTypes;
<ide> var ColorPropType = require('ColorPropType');
<ide> var ViewStylePropTypes = require('ViewStylePropTypes');
<ide> | 29 |
Javascript | Javascript | remove unnecessary reflective dereferencing | 3fbb25e25cc9bd1ddad8efab9f43749735e53454 | <ide><path>src/ngAnimate/animate.js
<ide> angular.module('ngAnimate', ['ng'])
<ide> function cancelAnimations(animations) {
<ide> var isCancelledFlag = true;
<ide> forEach(animations, function(animation) {
<del> if(!animations['beforeComplete']) {
<add> if(!animations.beforeComplete) {
<ide> (animation.beforeEnd || noop)(isCancelledFlag);
<ide> }
<del> if(!animations['afterComplete']) {
<add> if(!animations.afterComplete) {
<ide> (animation.afterEnd || noop)(isCancelledFlag);
<ide> }
<ide> }); | 1 |
Javascript | Javascript | convert `registry` to es6 class | d7d40fcc3a8fa4be3310bcff0c6d14eac084a422 | <ide><path>packages/container/lib/registry.js
<ide> const VALID_FULL_NAME_REGEXP = /^[^:]+:[^:]+$/;
<ide> @class Registry
<ide> @since 1.11.0
<ide> */
<del>export default function Registry(options = {}) {
<del> this.fallback = options.fallback || null;
<add>export default class Registry {
<add> constructor(options = {}) {
<add> this.fallback = options.fallback || null;
<add> this.resolver = options.resolver || null;
<ide>
<del> if (options.resolver) {
<del> this.resolver = options.resolver;
<ide> if (typeof this.resolver === 'function') {
<ide> deprecateResolverFunction(this);
<ide> }
<del> }
<ide>
<del> this.registrations = dictionary(options.registrations || null);
<add> this.registrations = dictionary(options.registrations || null);
<ide>
<del> this._typeInjections = dictionary(null);
<del> this._injections = dictionary(null);
<add> this._typeInjections = dictionary(null);
<add> this._injections = dictionary(null);
<ide>
<del> this._localLookupCache = Object.create(null);
<del> this._normalizeCache = dictionary(null);
<del> this._resolveCache = dictionary(null);
<del> this._failCache = dictionary(null);
<add> this._localLookupCache = Object.create(null);
<add> this._normalizeCache = dictionary(null);
<add> this._resolveCache = dictionary(null);
<add> this._failCache = dictionary(null);
<ide>
<del> this._options = dictionary(null);
<del> this._typeOptions = dictionary(null);
<del>}
<add> this._options = dictionary(null);
<add> this._typeOptions = dictionary(null);
<add> }
<ide>
<del>Registry.prototype = {
<ide> /**
<ide> A backup registry for resolving registrations when no matches can be found.
<ide>
<ide> @private
<ide> @property fallback
<ide> @type Registry
<ide> */
<del> fallback: null,
<ide>
<ide> /**
<ide> An object that has a `resolve` method that resolves a name.
<ide> Registry.prototype = {
<ide> @property resolver
<ide> @type Resolver
<ide> */
<del> resolver: null,
<ide>
<ide> /**
<ide> @private
<ide> @property registrations
<ide> @type InheritingDict
<ide> */
<del> registrations: null,
<ide>
<ide> /**
<ide> @private
<ide>
<ide> @property _typeInjections
<ide> @type InheritingDict
<ide> */
<del> _typeInjections: null,
<ide>
<ide> /**
<ide> @private
<ide>
<ide> @property _injections
<ide> @type InheritingDict
<ide> */
<del> _injections: null,
<ide>
<ide> /**
<ide> @private
<ide>
<ide> @property _normalizeCache
<ide> @type InheritingDict
<ide> */
<del> _normalizeCache: null,
<ide>
<ide> /**
<ide> @private
<ide>
<ide> @property _resolveCache
<ide> @type InheritingDict
<ide> */
<del> _resolveCache: null,
<ide>
<ide> /**
<ide> @private
<ide>
<ide> @property _options
<ide> @type InheritingDict
<ide> */
<del> _options: null,
<ide>
<ide> /**
<ide> @private
<ide>
<ide> @property _typeOptions
<ide> @type InheritingDict
<ide> */
<del> _typeOptions: null,
<ide>
<ide> /**
<ide> Creates a container based on this registry.
<ide> Registry.prototype = {
<ide> */
<ide> container(options) {
<ide> return new Container(this, options);
<del> },
<add> }
<ide>
<ide> /**
<ide> Registers a factory for later injection.
<ide> Registry.prototype = {
<ide> delete this._failCache[normalizedName];
<ide> this.registrations[normalizedName] = factory;
<ide> this._options[normalizedName] = options;
<del> },
<add> }
<ide>
<ide> /**
<ide> Unregister a fullName
<ide> Registry.prototype = {
<ide> delete this._resolveCache[normalizedName];
<ide> delete this._failCache[normalizedName];
<ide> delete this._options[normalizedName];
<del> },
<add> }
<ide>
<ide> /**
<ide> Given a fullName return the corresponding factory.
<ide> Registry.prototype = {
<ide> factory = this.fallback.resolve(...arguments);
<ide> }
<ide> return factory;
<del> },
<add> }
<ide>
<ide> /**
<ide> A hook that can be used to describe how the resolver will
<ide> Registry.prototype = {
<ide> } else {
<ide> return fullName;
<ide> }
<del> },
<add> }
<ide>
<ide> /**
<ide> A hook to enable custom fullName normalization behavior
<ide> Registry.prototype = {
<ide> } else {
<ide> return fullName;
<ide> }
<del> },
<add> }
<ide>
<ide> /**
<ide> Normalize a fullName based on the application's conventions
<ide> Registry.prototype = {
<ide> return this._normalizeCache[fullName] || (
<ide> (this._normalizeCache[fullName] = this.normalizeFullName(fullName))
<ide> );
<del> },
<add> }
<ide>
<ide> /**
<ide> @method makeToString
<ide> Registry.prototype = {
<ide> } else {
<ide> return factory.toString();
<ide> }
<del> },
<add> }
<ide>
<ide> /**
<ide> Given a fullName check if the container is aware of its factory
<ide> Registry.prototype = {
<ide> let source = options && options.source && this.normalize(options.source);
<ide>
<ide> return has(this, this.normalize(fullName), source);
<del> },
<add> }
<ide>
<ide> /**
<ide> Allow registering options for all factories of a type.
<ide> Registry.prototype = {
<ide> */
<ide> optionsForType(type, options) {
<ide> this._typeOptions[type] = options;
<del> },
<add> }
<ide>
<ide> getOptionsForType(type) {
<ide> let optionsForType = this._typeOptions[type];
<ide> if (optionsForType === undefined && this.fallback) {
<ide> optionsForType = this.fallback.getOptionsForType(type);
<ide> }
<ide> return optionsForType;
<del> },
<add> }
<ide>
<ide> /**
<ide> @private
<ide> Registry.prototype = {
<ide> options(fullName, options = {}) {
<ide> let normalizedName = this.normalize(fullName);
<ide> this._options[normalizedName] = options;
<del> },
<add> }
<ide>
<ide> getOptions(fullName) {
<ide> let normalizedName = this.normalize(fullName);
<ide> Registry.prototype = {
<ide> options = this.fallback.getOptions(fullName);
<ide> }
<ide> return options;
<del> },
<add> }
<ide>
<ide> getOption(fullName, optionName) {
<ide> let options = this._options[fullName];
<ide> Registry.prototype = {
<ide> } else if (this.fallback) {
<ide> return this.fallback.getOption(fullName, optionName);
<ide> }
<del> },
<add> }
<ide>
<ide> /**
<ide> Used only via `injection`.
<ide> Registry.prototype = {
<ide> (this._typeInjections[type] = []);
<ide>
<ide> injections.push({ property, fullName });
<del> },
<add> }
<ide>
<ide> /**
<ide> Defines injection rules.
<ide> Registry.prototype = {
<ide> (this._injections[normalizedName] = []);
<ide>
<ide> injections.push({ property, fullName: normalizedInjectionName });
<del> },
<add> }
<ide>
<ide> /**
<ide> @private
<ide> Registry.prototype = {
<ide> }
<ide>
<ide> return assign({}, fallbackKnown, localKnown, resolverKnown);
<del> },
<add> }
<ide>
<ide> validateFullName(fullName) {
<ide> if (!this.isValidFullName(fullName)) {
<ide> throw new TypeError(`Invalid Fullname, expected: 'type:name' got: ${fullName}`);
<ide> }
<ide>
<ide> return true;
<del> },
<add> }
<ide>
<ide> isValidFullName(fullName) {
<ide> return VALID_FULL_NAME_REGEXP.test(fullName);
<del> },
<add> }
<ide>
<ide> getInjections(fullName) {
<ide> let injections = this._injections[fullName] || [];
<ide> if (this.fallback) {
<ide> injections = injections.concat(this.fallback.getInjections(fullName));
<ide> }
<ide> return injections;
<del> },
<add> }
<ide>
<ide> getTypeInjections(type) {
<ide> let injections = this._typeInjections[type] || [];
<ide> if (this.fallback) {
<ide> injections = injections.concat(this.fallback.getTypeInjections(type));
<ide> }
<ide> return injections;
<del> },
<add> }
<ide>
<ide> resolverCacheKey(name, options) {
<ide> if (!EMBER_MODULE_UNIFICATION) {
<ide> return name;
<ide> }
<ide>
<ide> return (options && options.source) ? `${options.source}:${name}` : name;
<del> },
<add> }
<ide>
<ide> /**
<ide> Given a fullName and a source fullName returns the fully resolved
<ide> Registry.prototype = {
<ide> return null;
<ide> }
<ide> }
<del>};
<add>}
<ide>
<ide> function deprecateResolverFunction(registry) {
<del> deprecate('Passing a `resolver` function into a Registry is deprecated. Please pass in a Resolver object with a `resolve` method.',
<del> false,
<del> { id: 'ember-application.registry-resolver-as-function', until: '3.0.0', url: 'https://emberjs.com/deprecations/v2.x#toc_registry-resolver-as-function' });
<del> registry.resolver = {
<del> resolve: registry.resolver
<del> };
<add> deprecate(
<add> 'Passing a `resolver` function into a Registry is deprecated. Please pass in a Resolver object with a `resolve` method.',
<add> false,
<add> { id: 'ember-application.registry-resolver-as-function', until: '3.0.0', url: 'https://emberjs.com/deprecations/v2.x#toc_registry-resolver-as-function' }
<add> );
<add> registry.resolver = { resolve: registry.resolver };
<ide> }
<ide>
<ide> if (DEBUG) { | 1 |
Text | Text | remove outdated info in cypress/gitpod | 0823b45f5dc961fb4f236decd361d88691760d5c | <ide><path>docs/how-to-add-cypress-tests.md
<ide> To run tests against production builds, replace `dev` with `prd` below.
<ide>
<ide> ## Cypress-GitPod Setup
<ide>
<del>### 1. Ensure you are on the _Feature Preview_ of GitPod _as of 01/02/2021_
<del>
<del>- Go to [GitPod Docs - Feature Preview](https://www.gitpod.io/docs/feature-preview/) to see how to enable _Feature Preview_
<del>
<del>### 2. Ensure Development Environment is Running
<add>### 1. Ensure Development Environment is Running
<ide>
<ide> If starting the GitPod environment did not automatically develop the environment:
<ide>
<ide> npm run seed
<ide> npm run develop
<ide> ```
<ide>
<del>### 3. Install Cypress Build Tools
<add>### 2. Install Cypress Build Tools
<ide>
<ide> ```console
<ide> npm run cypress:install-build-tools | 1 |
Text | Text | explain what the virtual size means | 498f208ade18dffb7362adc37c1f11b1bff187da | <ide><path>docs/sources/reference/commandline/cli.md
<ide> decrease disk usage, and speed up `docker build` by
<ide> allowing each step to be cached. These intermediate layers are not shown
<ide> by default.
<ide>
<add>The `VIRTUAL SIZE` is the cumulative space taken up by the image and all
<add>its parent images. This is also the disk space used by the contents of the
<add>Tar file created when you `docker save` an image.
<add>
<ide> An image will be listed more than once if it has multiple repository names
<ide> or tags. This single image (identifiable by its matching `IMAGE ID`)
<ide> uses up the `VIRTUAL SIZE` listed only once. | 1 |
Python | Python | return custom error in nlp.initialize | 39de3602e0321eb2dbcfce032a8d4734162ee69d | <ide><path>spacy/errors.py
<ide> class Errors:
<ide> E880 = ("The 'wandb' library could not be found - did you install it? "
<ide> "Alternatively, specify the 'ConsoleLogger' in the 'training.logger' "
<ide> "config section, instead of the 'WandbLogger'.")
<add> E884 = ("The pipeline could not be initialized because the vectors "
<add> "could not be found at '{vectors}'. If your pipeline was already "
<add> "initialized/trained before, call 'resume_training' instead of 'initialize', "
<add> "or initialize only the components that are new.")
<ide> E885 = ("entity_linker.set_kb received an invalid 'kb_loader' argument: expected "
<ide> "a callable function, but got: {arg_type}")
<ide> E886 = ("Can't replace {name} -> {tok2vec} listeners: path '{path}' not "
<ide><path>spacy/language.py
<ide> def initialize(
<ide> before_init = I["before_init"]
<ide> if before_init is not None:
<ide> before_init(self)
<del> init_vocab(
<del> self, data=I["vocab_data"], lookups=I["lookups"], vectors=I["vectors"]
<del> )
<add> try:
<add> init_vocab(
<add> self, data=I["vocab_data"], lookups=I["lookups"], vectors=I["vectors"]
<add> )
<add> except IOError:
<add> raise IOError(Errors.E884.format(vectors=I["vectors"]))
<ide> if self.vocab.vectors.data.shape[1] >= 1:
<ide> ops = get_current_ops()
<ide> self.vocab.vectors.data = ops.asarray(self.vocab.vectors.data) | 2 |
PHP | PHP | fix lint error | 3d473576c7d3630fb522c4bd0825193246356178 | <ide><path>src/Mailer/Email.php
<ide> public function headerCharset($charset = null)
<ide> * @param string|null $encoding Encoding set.
<ide> * @return $this
<ide> */
<del> public function setTransferEncoding($encoding) {
<add> public function setTransferEncoding($encoding)
<add> {
<ide> $this->transferEncoding = $encoding;
<ide>
<ide> return $this;
<ide> public function setTransferEncoding($encoding) {
<ide> *
<ide> * @return string|null Encoding
<ide> */
<del> public function getTransferEncoding() {
<add> public function getTransferEncoding()
<add> {
<ide> return $this->transferEncoding;
<ide> }
<ide>
<ide><path>tests/TestCase/Mailer/EmailTest.php
<ide> public function render($content)
<ide> *
<ide> * @return string
<ide> */
<del> public function getContentTransferEncoding() {
<add> public function getContentTransferEncoding()
<add> {
<ide> return $this->_getContentTransferEncoding();
<ide> }
<ide>
<ide> public function testHeaderCharset()
<ide> *
<ide> * @return void
<ide> */
<del> public function testTransferEncoding(){
<add> public function testTransferEncoding()
<add> {
<ide> // Test new transfer encoding
<ide> $this->Email->setTransferEncoding('quoted-printable');
<ide> $this->assertSame($this->Email->getTransferEncoding(), 'quoted-printable'); | 2 |
Javascript | Javascript | add welcome message | fe963149f6b2b4af7ace402851dc3dfed64ca2d5 | <ide><path>lib/internal/main/repl.js
<ide> const {
<ide> evalScript
<ide> } = require('internal/process/execution');
<ide>
<add>const console = require('internal/console/global');
<add>
<ide> prepareMainThreadExecution();
<ide>
<ide> // --entry-type flag not supported in REPL
<ide> if (require('internal/options').getOptionValue('--entry-type')) {
<ide> // If we can't write to stderr, we'd like to make this a noop,
<ide> // so use console.error.
<del> const { error } = require('internal/console/global');
<del> error('Cannot specify --entry-type for REPL');
<add> console.error('Cannot specify --entry-type for REPL');
<ide> process.exit(1);
<ide> }
<ide>
<add>console.log(`Welcome to Node.js ${process.version}.\n` +
<add> 'Type ".help" for more information.');
<add>
<ide> const cliRepl = require('internal/repl');
<ide> cliRepl.createInternalRepl(process.env, (err, repl) => {
<ide> if (err) {
<ide><path>test/parallel/test-force-repl-with-eval.js
<ide> cp.stdout.setEncoding('utf8');
<ide> let output = '';
<ide> cp.stdout.on('data', function(b) {
<ide> output += b;
<del> if (output === '> 42\n') {
<add> if (output.endsWith('> 42\n')) {
<ide> gotToEnd = true;
<ide> cp.kill();
<ide> }
<ide><path>test/parallel/test-force-repl.js
<ide> const assert = require('assert');
<ide> const spawn = require('child_process').spawn;
<ide>
<ide> // Spawn a node child process in interactive mode (enabling the REPL) and
<del>// confirm the '> ' prompt is included in the output.
<add>// confirm the '> ' prompt and welcome message is included in the output.
<ide> const cp = spawn(process.execPath, ['-i']);
<ide>
<ide> cp.stdout.setEncoding('utf8');
<ide>
<del>cp.stdout.once('data', common.mustCall(function(b) {
<del> assert.strictEqual(b, '> ');
<del> cp.kill();
<add>let out = '';
<add>cp.stdout.on('data', (d) => {
<add> out += d;
<add>});
<add>
<add>cp.stdout.on('end', common.mustCall(() => {
<add> assert.strictEqual(out, `Welcome to Node.js ${process.version}.\n` +
<add> 'Type ".help" for more information.\n> ');
<ide> }));
<add>
<add>cp.stdin.end('');
<ide><path>test/parallel/test-preload.js
<ide> const replProc = childProcess.spawn(
<ide> );
<ide> replProc.stdin.end('.exit\n');
<ide> let replStdout = '';
<del>replProc.stdout.on('data', function(d) {
<add>replProc.stdout.on('data', (d) => {
<ide> replStdout += d;
<ide> });
<ide> replProc.on('close', function(code) {
<ide> assert.strictEqual(code, 0);
<ide> const output = [
<ide> 'A',
<ide> '> '
<del> ].join('\n');
<del> assert.strictEqual(replStdout, output);
<add> ];
<add> assert.ok(replStdout.startsWith(output[0]));
<add> assert.ok(replStdout.endsWith(output[1]));
<ide> });
<ide>
<ide> // Test that preload placement at other points in the cmdline
<ide> const interactive = childProcess.exec(
<ide> `"${nodeBinary}" ${preloadOption([fixtureD])}-i`,
<ide> common.mustCall(function(err, stdout, stderr) {
<ide> assert.ifError(err);
<del> assert.strictEqual(stdout, "> 'test'\n> ");
<add> assert.ok(stdout.endsWith("> 'test'\n> "));
<ide> })
<ide> );
<ide>
<ide><path>test/parallel/test-repl-harmony.js
<ide> const child = spawn(process.execPath, args);
<ide> const input = '(function(){"use strict"; const y=1;y=2})()\n';
<ide> // This message will vary based on JavaScript engine, so don't check the message
<ide> // contents beyond confirming that the `Error` is a `TypeError`.
<del>const expectOut = /^> Thrown:\nTypeError: /;
<add>const expectOut = /> Thrown:\nTypeError: /;
<ide>
<ide> child.stderr.setEncoding('utf8');
<del>child.stderr.on('data', function(c) {
<add>child.stderr.on('data', (d) => {
<ide> throw new Error('child.stderr be silent');
<ide> });
<ide>
<ide> child.stdout.setEncoding('utf8');
<ide> let out = '';
<del>child.stdout.on('data', function(c) {
<del> out += c;
<add>child.stdout.on('data', (d) => {
<add> out += d;
<ide> });
<del>child.stdout.on('end', function() {
<add>child.stdout.on('end', () => {
<ide> assert(expectOut.test(out));
<ide> console.log('ok');
<ide> });
<ide><path>test/parallel/test-repl-inspect-defaults.js
<ide> child.stdout.on('data', (data) => {
<ide> });
<ide>
<ide> child.on('exit', common.mustCall(() => {
<del> const results = output.replace(/^> /mg, '').split('\n');
<add> const results = output.replace(/^> /mg, '').split('\n').slice(2);
<ide> assert.deepStrictEqual(
<ide> results,
<ide> [
<ide><path>test/parallel/test-repl-require-after-write.js
<ide> child.stdout.on('data', (c) => {
<ide> out += c;
<ide> });
<ide> child.stdout.on('end', common.mustCall(() => {
<del> assert.strictEqual(out, '> 1\n> ');
<add> assert.ok(out.endsWith('> 1\n> '));
<ide> }));
<ide>
<ide> child.stdin.end(input);
<ide><path>test/parallel/test-repl-require-context.js
<ide> child.stdout.on('data', (data) => {
<ide> });
<ide>
<ide> child.on('exit', common.mustCall(() => {
<del> const results = output.replace(/^> /mg, '').split('\n');
<add> const results = output.replace(/^> /mg, '').split('\n').slice(2);
<ide> assert.deepStrictEqual(results, ['undefined', 'true', 'true', '']);
<ide> }));
<ide>
<ide><path>test/parallel/test-repl-unexpected-token-recoverable.js
<ide> const child = spawn(process.execPath, args);
<ide>
<ide> const input = 'var foo = "bar\\\nbaz"';
<ide> // Match '...' as well since it marks a multi-line statement
<del>const expectOut = /^> \.\.\. undefined\n/;
<add>const expectOut = /> \.\.\. undefined\n/;
<ide>
<ide> child.stderr.setEncoding('utf8');
<del>child.stderr.on('data', function(c) {
<add>child.stderr.on('data', (d) => {
<ide> throw new Error('child.stderr be silent');
<ide> });
<ide>
<ide> child.stdout.setEncoding('utf8');
<ide> let out = '';
<del>child.stdout.on('data', function(c) {
<del> out += c;
<add>child.stdout.on('data', (d) => {
<add> out += d;
<ide> });
<ide>
<del>child.stdout.on('end', function() {
<add>child.stdout.on('end', () => {
<ide> assert(expectOut.test(out));
<ide> console.log('ok');
<ide> }); | 9 |
Ruby | Ruby | use 1.9 hash style in docs/comments [ci skip] | 5a69fe724e50377f13dc107733b765a53fc0c799 | <ide><path>actionpack/lib/action_controller/metal/strong_parameters.rb
<ide> def require(key)
<ide> # You may declare that the parameter should be an array of permitted scalars
<ide> # by mapping it to an empty array:
<ide> #
<del> # params.permit(:tags => [])
<add> # params.permit(tags: [])
<ide> #
<ide> # You can also use +permit+ on nested parameters, like:
<ide> #
<ide> def hash_filter(params, filter)
<ide> return unless value
<ide>
<ide> if filter[key] == []
<del> # Declaration {:comment_ids => []}.
<add> # Declaration { comment_ids: [] }.
<ide> array_of_permitted_scalars_filter(params, key)
<ide> else
<del> # Declaration {:user => :name} or {:user => [:name, :age, {:adress => ...}]}.
<add> # Declaration { user: :name } or { user: [:name, :age, { adress: ... }] }.
<ide> params[key] = each_element(value) do |element|
<ide> if element.is_a?(Hash)
<ide> element = self.class.new(element) unless element.respond_to?(:permit) | 1 |
Python | Python | add support for atlas > 3.9.33 | dd0732e4bda8f4379b17ea479bcecc876ab50ce6 | <ide><path>numpy/distutils/system_info.py
<ide> atlas_blas_info
<ide> atlas_blas_threads_info
<ide> lapack_atlas_info
<add> lapack_atlas_threads_info
<add> atlas_3_10_info
<add> atlas_3_10_threads_info
<add> atlas_3_10_blas_info,
<add> atlas_3_10_blas_threads_info,
<add> lapack_atlas_3_10_info
<add> lapack_atlas_3_10_threads_info
<ide> blas_info
<ide> lapack_info
<ide> openblas_info
<ide> def get_info(name, notfound_action=0):
<ide> 'atlas_blas_threads': atlas_blas_threads_info,
<ide> 'lapack_atlas': lapack_atlas_info, # use lapack_opt instead
<ide> 'lapack_atlas_threads': lapack_atlas_threads_info, # ditto
<add> 'atlas_3_10': atlas_3_10_info, # use lapack_opt or blas_opt instead
<add> 'atlas_3_10_threads': atlas_3_10_threads_info, # ditto
<add> 'atlas_3_10_blas': atlas_3_10_blas_info,
<add> 'atlas_3_10_blas_threads': atlas_3_10_blas_threads_info,
<add> 'lapack_atlas_3_10': lapack_atlas_3_10_info, # use lapack_opt instead
<add> 'lapack_atlas_3_10_threads': lapack_atlas_3_10_threads_info, # ditto
<ide> 'mkl': mkl_info,
<ide> # openblas which may or may not have embedded lapack
<ide> 'openblas': openblas_info, # use blas_opt instead
<ide> class lapack_atlas_threads_info(atlas_threads_info):
<ide> _lib_names = ['lapack_atlas'] + atlas_threads_info._lib_names
<ide>
<ide>
<add>class atlas_3_10_info(atlas_info):
<add> _lib_names = ['satlas']
<add> _lib_atlas = _lib_names
<add> _lib_lapack = _lib_names
<add>
<add>
<add>class atlas_3_10_blas_info(atlas_3_10_info):
<add> _lib_names = ['satlas']
<add>
<add> def calc_info(self):
<add> lib_dirs = self.get_lib_dirs()
<add> info = {}
<add> atlas_libs = self.get_libs('atlas_libs',
<add> self._lib_names)
<add> atlas = self.check_libs2(lib_dirs, atlas_libs, [])
<add> if atlas is None:
<add> return
<add> include_dirs = self.get_include_dirs()
<add> h = (self.combine_paths(lib_dirs + include_dirs, 'cblas.h') or [None])
<add> h = h[0]
<add> if h:
<add> h = os.path.dirname(h)
<add> dict_append(info, include_dirs=[h])
<add> info['language'] = 'c'
<add> info['define_macros'] = [('HAVE_CBLAS', None)]
<add>
<add> atlas_version, atlas_extra_info = get_atlas_version(**atlas)
<add> dict_append(atlas, **atlas_extra_info)
<add>
<add> dict_append(info, **atlas)
<add>
<add> self.set_info(**info)
<add> return
<add>
<add>
<add>class atlas_3_10_threads_info(atlas_3_10_info):
<add> dir_env_var = ['PTATLAS', 'ATLAS']
<add> _lib_names = ['tatlas']
<add> #if sys.platfcorm[:7] == 'freebsd':
<add> ## I don't think freebsd supports 3.10 at this time - 2014
<add> _lib_atlas = _lib_names
<add> _lib_lapack = _lib_names
<add>
<add>
<add>class atlas_3_10_blas_threads_info(atlas_3_10_blas_info):
<add> dir_env_var = ['PTATLAS', 'ATLAS']
<add> _lib_names = ['tatlas']
<add>
<add>
<add>class lapack_atlas_3_10_info(atlas_3_10_info):
<add> pass
<add>
<add>
<add>class lapack_atlas_3_10_threads_info(atlas_3_10_threads_info):
<add> pass
<add>
<add>
<ide> class lapack_info(system_info):
<ide> section = 'lapack'
<ide> dir_env_var = 'LAPACK'
<ide> def get_atlas_version(**config):
<ide> return result
<ide>
<ide>
<del>
<ide> class lapack_opt_info(system_info):
<ide>
<ide> notfounderror = LapackNotFoundError
<ide> def calc_info(self):
<ide> self.set_info(**lapack_mkl_info)
<ide> return
<ide>
<del> atlas_info = get_info('atlas_threads')
<add> atlas_info = get_info('atlas_3_10_threads')
<add> if not atlas_info:
<add> atlas_info = get_info('atlas_3_10')
<add> if not atlas_info:
<add> atlas_info = get_info('atlas_threads')
<ide> if not atlas_info:
<ide> atlas_info = get_info('atlas')
<ide>
<ide> def calc_info(self):
<ide> self.set_info(**openblas_info)
<ide> return
<ide>
<del> atlas_info = get_info('atlas_blas_threads')
<add> atlas_info = get_info('atlas_3_10_blas_threads')
<add> if not atlas_info:
<add> atlas_info = get_info('atlas_3_10_blas')
<add> if not atlas_info:
<add> atlas_info = get_info('atlas_blas_threads')
<ide> if not atlas_info:
<ide> atlas_info = get_info('atlas_blas')
<ide> | 1 |
Python | Python | resolve mypy issue in athena example dag | a9b7dd69008710f1e5b188e4f8bc2d09a5136776 | <ide><path>airflow/providers/amazon/aws/example_dags/example_athena.py
<ide> def read_results_from_s3(query_execution_id):
<ide> remove_sample_data_from_s3 = remove_sample_data_from_s3()
<ide>
<ide> (
<del> add_sample_data_to_s3
<add> add_sample_data_to_s3 # type: ignore
<ide> >> create_table
<ide> >> read_table
<ide> >> get_read_state | 1 |
Ruby | Ruby | use more https in urls and updated some lost links | fc2818b7a54dadcf0c35965ef1f07219da3fc4a7 | <ide><path>Library/Homebrew/blacklist.rb
<ide> def blacklisted? name
<ide> Installing TeX from source is weird and gross, requires a lot of patches,
<ide> and only builds 32-bit (and thus can't use Homebrew deps on Snow Leopard.)
<ide>
<del> We recommend using a MacTeX distribution: http://www.tug.org/mactex/
<add> We recommend using a MacTeX distribution: https://www.tug.org/mactex/
<ide> EOS
<ide> when 'pip' then <<-EOS.undent
<ide> Homebrew provides pip via: `brew install python`. However you will then
<ide> def blacklisted? name
<ide> brew install typesafe-activator
<ide>
<ide> You can read more about this change at:
<del> http://www.playframework.com/documentation/2.3.x/Migration23
<del> http://www.playframework.com/documentation/2.3.x/Highlights23
<add> https://www.playframework.com/documentation/2.3.x/Migration23
<add> https://www.playframework.com/documentation/2.3.x/Highlights23
<ide> EOS
<ide> when 'haskell-platform' then <<-EOS.undent
<ide> We no longer package haskell-platform. Consider installing ghc
<ide><path>Library/Homebrew/cmd/aspell-dictionaries.rb
<ide> module Homebrew
<ide> def aspell_dictionaries
<ide> dict_url = "http://ftpmirror.gnu.org/aspell/dict"
<del> dict_mirror = "http://ftp.gnu.org/gnu/aspell/dict"
<add> dict_mirror = "https://ftp.gnu.org/gnu/aspell/dict"
<ide> languages = {}
<ide>
<ide> open("#{dict_url}/0index.html") do |content|
<ide><path>Library/Homebrew/cmd/create.rb
<ide> def create
<ide>
<ide> # Allow searching MacPorts or Fink.
<ide> if ARGV.include? '--macports'
<del> exec_browser "http://www.macports.org/ports.php?by=name&substr=#{ARGV.next}"
<add> exec_browser "https://www.macports.org/ports.php?by=name&substr=#{ARGV.next}"
<ide> elsif ARGV.include? '--fink'
<ide> exec_browser "http://pdb.finkproject.org/pdb/browse.php?summary=#{ARGV.next}"
<ide> end
<ide><path>Library/Homebrew/cmd/doctor.rb
<ide> def check_path_for_trailing_slashes
<ide> end
<ide>
<ide> # Installing MacGPG2 interferes with Homebrew in a big way
<del># http://sourceforge.net/projects/macgpg2/files/
<add># https://github.com/GPGTools/MacGPG2
<ide> def check_for_macgpg2
<ide> return if File.exist? '/usr/local/MacGPG2/share/gnupg/VERSION'
<ide>
<ide> def check_for_pydistutils_cfg_in_home
<ide> if File.exist? "#{ENV['HOME']}/.pydistutils.cfg" then <<-EOS.undent
<ide> A .pydistutils.cfg file was found in $HOME, which may cause Python
<ide> builds to fail. See:
<del> http://bugs.python.org/issue6138
<del> http://bugs.python.org/issue4655
<add> https://bugs.python.org/issue6138
<add> https://bugs.python.org/issue4655
<ide> EOS
<ide> end
<ide> end
<ide><path>Library/Homebrew/cmd/search.rb
<ide> module Homebrew
<ide>
<ide> def search
<ide> if ARGV.include? '--macports'
<del> exec_browser "http://www.macports.org/ports.php?by=name&substr=#{ARGV.next}"
<add> exec_browser "https://www.macports.org/ports.php?by=name&substr=#{ARGV.next}"
<ide> elsif ARGV.include? '--fink'
<ide> exec_browser "http://pdb.finkproject.org/pdb/browse.php?summary=#{ARGV.next}"
<ide> elsif ARGV.include? '--debian'
<del> exec_browser "http://packages.debian.org/search?keywords=#{ARGV.next}&searchon=names&suite=all§ion=all"
<add> exec_browser "https://packages.debian.org/search?keywords=#{ARGV.next}&searchon=names&suite=all§ion=all"
<ide> elsif ARGV.include? '--opensuse'
<ide> exec_browser "http://software.opensuse.org/search?q=#{ARGV.next}"
<ide> elsif ARGV.include? '--fedora'
<ide><path>Library/Homebrew/download_strategy.rb
<ide> def ext
<ide> # We need a Pathname because we've monkeypatched extname to support double
<ide> # extensions (e.g. tar.gz).
<ide> # We can't use basename_without_params, because given a URL like
<del> # http://example.com/download.php?file=foo-1.0.tar.gz
<add> # https://example.com/download.php?file=foo-1.0.tar.gz
<ide> # the extension we want is ".tar.gz", not ".php".
<ide> Pathname.new(@url).extname[/[^?]+/]
<ide> end
<ide> def stage
<ide>
<ide> dst = Dir.getwd
<ide> cached_location.cd do
<del> # http://stackoverflow.com/questions/160608/how-to-do-a-git-export-like-svn-export
<add> # https://stackoverflow.com/questions/160608/how-to-do-a-git-export-like-svn-export
<ide> safe_system 'git', 'checkout-index', '-a', '-f', "--prefix=#{dst}/"
<ide> checkout_submodules(dst) if submodules?
<ide> end
<ide><path>Library/Homebrew/extend/ENV/shared.rb
<ide> def determine_cc
<ide> end
<ide>
<ide> # Snow Leopard defines an NCURSES value the opposite of most distros
<del> # See: http://bugs.python.org/issue6848
<add> # See: https://bugs.python.org/issue6848
<ide> # Currently only used by aalib in core
<ide> def ncurses_define
<ide> append 'CPPFLAGS', "-DNCURSES_OPAQUE=0"
<ide><path>Library/Homebrew/os/mac.rb
<ide> def clear_version_cache
<ide> end
<ide>
<ide> # See these issues for some history:
<del> # http://github.com/Homebrew/homebrew/issues/13
<del> # http://github.com/Homebrew/homebrew/issues/41
<del> # http://github.com/Homebrew/homebrew/issues/48
<add> # https://github.com/Homebrew/homebrew/issues/13
<add> # https://github.com/Homebrew/homebrew/issues/41
<add> # https://github.com/Homebrew/homebrew/issues/48
<ide> def macports_or_fink
<ide> paths = []
<ide>
<ide><path>Library/Homebrew/os/mac/xcode.rb
<ide> def toolchain_path
<ide>
<ide> # Ask Spotlight where Xcode is. If the user didn't install the
<ide> # helper tools and installed Xcode in a non-conventional place, this
<del> # is our only option. See: http://superuser.com/questions/390757
<add> # is our only option. See: https://superuser.com/questions/390757
<ide> def bundle_path
<ide> MacOS.app_with_bundle_id(V4_BUNDLE_ID, V3_BUNDLE_ID)
<ide> end
<ide><path>Library/Homebrew/os/mac/xquartz.rb
<ide> def detect_version
<ide> end
<ide> end
<ide>
<del> # http://xquartz.macosforge.org/trac/wiki
<del> # http://xquartz.macosforge.org/trac/wiki/Releases
<add> # https://xquartz.macosforge.org/trac/wiki
<add> # https://xquartz.macosforge.org/trac/wiki/Releases
<ide> def latest_version
<ide> case MacOS.version
<ide> when "10.5"
<ide><path>Library/Homebrew/requirements.rb
<ide> class PostgresqlDependency < Requirement
<ide> class TeXDependency < Requirement
<ide> fatal true
<ide> cask "mactex"
<del> download "http://www.tug.org/mactex/"
<add> download "https://www.tug.org/mactex/"
<ide>
<ide> satisfy { which('tex') || which('latex') }
<ide>
<ide><path>Library/Homebrew/requirements/mpi_dependency.rb
<ide> def mpi_wrapper_works? compiler
<ide> env do
<ide> # Set environment variables to help configure scripts find MPI compilers.
<ide> # Variable names taken from:
<del> # http://www.gnu.org/software/autoconf-archive/ax_mpi.html
<add> # https://www.gnu.org/software/autoconf-archive/ax_mpi.html
<ide> @lang_list.each do |lang|
<ide> compiler = 'mpi' + lang.to_s
<ide> mpi_path = which compiler
<ide><path>Library/Homebrew/version.rb
<ide> def self._parse spec
<ide> m = /_((?:\d+\.)+\d+[abc]?)[.]orig$/.match(stem)
<ide> return m.captures.first unless m.nil?
<ide>
<del> # e.g. http://www.openssl.org/source/openssl-0.9.8s.tar.gz
<add> # e.g. https://www.openssl.org/source/openssl-0.9.8s.tar.gz
<ide> m = /-v?([^-]+)/.match(stem)
<ide> return m.captures.first unless m.nil?
<ide> | 13 |
Python | Python | update failure message | 06b5318a09b6173ea281f47f3d7eb584168f4e4e | <ide><path>numpy/ma/tests/test_core.py
<ide> def test_varstd(self):
<ide> mX[:, k].compressed().std())
<ide>
<ide> @dec.knownfailureif(sys.platform=='win32' and sys.version_info < (3, 6),
<del> msg='Fails on Python < 3.6')
<add> msg='Fails on Python < 3.6 (Issue #9671)')
<ide> @suppress_copy_mask_on_assignment
<ide> def test_varstd_specialcases(self):
<ide> # Test a special case for var | 1 |
Javascript | Javascript | remove unused deps | 541bedd1a9692208deae0cd2a93171e87fb7d1ba | <ide><path>src/directive/ngController.js
<ide> </doc:scenario>
<ide> </doc:example>
<ide> */
<del>var ngControllerDirective = ['$controller', '$window', function($controller, $window) {
<add>var ngControllerDirective = [function() {
<ide> return {
<ide> scope: true,
<ide> controller: '@'
<del> }
<add> };
<ide> }]; | 1 |
Javascript | Javascript | add "mustcall" for test-net-buffersize | 7cbbd51479a9637694ab14e985880758ee24c656 | <ide><path>test/parallel/test-net-buffersize.js
<ide> // USE OR OTHER DEALINGS IN THE SOFTWARE.
<ide>
<ide> 'use strict';
<del>require('../common');
<add>const common = require('../common');
<ide> const assert = require('assert');
<ide> const net = require('net');
<ide>
<ide> const server = net.createServer(function(socket) {
<ide> });
<ide> });
<ide>
<del>server.listen(0, function() {
<add>server.listen(0, common.mustCall(function() {
<ide> const client = net.connect(this.address().port);
<ide>
<del> client.on('finish', function() {
<add> client.on('finish', common.mustCall(() => {
<ide> assert.strictEqual(client.bufferSize, 0);
<del> });
<add> }));
<ide>
<ide> for (let i = 1; i < iter; i++) {
<ide> client.write('a');
<ide> assert.strictEqual(client.bufferSize, i);
<ide> }
<ide>
<ide> client.end();
<del>});
<add>})); | 1 |
Javascript | Javascript | add some new (failing) tests for component bugs | a668299bc8dcc922617718d9dc4b63152413cef2 | <ide><path>packages/ember-htmlbars/tests/integration/component_invocation_test.js
<ide> if (isEnabled('ember-htmlbars-component-generation')) {
<ide> equal(view.$('div').attr('class'), 'inner-class new-outer ember-view', 'the classes are merged');
<ide> });
<ide>
<del> QUnit.test('non-block with class replaced with a identity element merges classes', function() {
<add> QUnit.test('non-block with class replaced with identity element merges classes', function() {
<ide> registry.register('template:components/non-block', compile('<non-block class="inner-class" />'));
<ide>
<ide> view = appendViewFor('<non-block class="{{view.outer}}" />', {
<ide> if (isEnabled('ember-htmlbars-component-generation')) {
<ide> equal(view.$('non-block').attr('class'), 'inner-class new-outer ember-view', 'the classes are merged');
<ide> });
<ide>
<add> QUnit.test('non-block with outer attributes replaced with a div shadows inner attributes', function() {
<add> registry.register('template:components/non-block', compile('<div data-static="static" data-dynamic="{{internal}}" />'));
<add>
<add> view = appendViewFor('<non-block data-static="outer" data-dynamic="outer" />');
<add>
<add> equal(view.$('div').attr('data-static'), 'outer', 'the outer attribute wins');
<add> equal(view.$('div').attr('data-dynamic'), 'outer', 'the outer attribute wins');
<add>
<add> let component = view.childViews[0]; // HAX
<add>
<add> run(() => component.set('internal', 'changed'));
<add>
<add> equal(view.$('div').attr('data-static'), 'outer', 'the outer attribute wins');
<add> equal(view.$('div').attr('data-dynamic'), 'outer', 'the outer attribute wins');
<add> });
<add>
<add> QUnit.test('non-block with outer attributes replaced with identity element shadows inner attributes', function() {
<add> registry.register('template:components/non-block', compile('<non-block data-static="static" data-dynamic="{{internal}}" />'));
<add>
<add> view = appendViewFor('<non-block data-static="outer" data-dynamic="outer" />');
<add>
<add> equal(view.$('non-block').attr('data-static'), 'outer', 'the outer attribute wins');
<add> equal(view.$('non-block').attr('data-dynamic'), 'outer', 'the outer attribute wins');
<add>
<add> let component = view.childViews[0]; // HAX
<add>
<add> run(() => component.set('internal', 'changed'));
<add>
<add> equal(view.$('non-block').attr('data-static'), 'outer', 'the outer attribute wins');
<add> equal(view.$('non-block').attr('data-dynamic'), 'outer', 'the outer attribute wins');
<add> });
<add>
<add> QUnit.test('non-block recurrsive invocations with outer attributes replaced with a div shadows inner attributes', function() {
<add> registry.register('template:components/non-block-wrapper', compile('<non-block />'));
<add> registry.register('template:components/non-block', compile('<div data-static="static" data-dynamic="{{internal}}" />'));
<add>
<add> view = appendViewFor('<non-block-wrapper data-static="outer" data-dynamic="outer" />');
<add>
<add> equal(view.$('div').attr('data-static'), 'outer', 'the outer-most attribute wins');
<add> equal(view.$('div').attr('data-dynamic'), 'outer', 'the outer-most attribute wins');
<add>
<add> let component = view.childViews[0].childViews[0]; // HAX
<add>
<add> run(() => component.set('internal', 'changed'));
<add>
<add> equal(view.$('div').attr('data-static'), 'outer', 'the outer-most attribute wins');
<add> equal(view.$('div').attr('data-dynamic'), 'outer', 'the outer-most attribute wins');
<add> });
<add>
<add> QUnit.test('non-block recurrsive invocations with outer attributes replaced with identity element shadows inner attributes', function() {
<add> registry.register('template:components/non-block-wrapper', compile('<non-block />'));
<add> registry.register('template:components/non-block', compile('<non-block data-static="static" data-dynamic="{{internal}}" />'));
<add>
<add> view = appendViewFor('<non-block-wrapper data-static="outer" data-dynamic="outer" />');
<add>
<add> equal(view.$('div').attr('data-static'), 'outer', 'the outer-most attribute wins');
<add> equal(view.$('div').attr('data-dynamic'), 'outer', 'the outer-most attribute wins');
<add>
<add> let component = view.childViews[0].childViews[0]; // HAX
<add>
<add> run(() => component.set('internal', 'changed'));
<add>
<add> equal(view.$('div').attr('data-static'), 'outer', 'the outer-most attribute wins');
<add> equal(view.$('div').attr('data-dynamic'), 'outer', 'the outer-most attribute wins');
<add> });
<add>
<add> QUnit.test('non-block replaced with a div should have correct scope', function() {
<add> registry.register('template:components/non-block', compile('<div>{{internal}}</div>'));
<add>
<add> registry.register('component:non-block', GlimmerComponent.extend({
<add> init() {
<add> this._super(...arguments);
<add> this.set('internal', 'stuff');
<add> }
<add> }));
<add>
<add> view = appendViewFor('<non-block />');
<add>
<add> equal(view.$().text(), 'stuff');
<add> });
<add>
<add> QUnit.test('non-block replaced with identity element should have correct scope', function() {
<add> registry.register('template:components/non-block', compile('<non-block>{{internal}}</non-block>'));
<add>
<add> registry.register('component:non-block', GlimmerComponent.extend({
<add> init() {
<add> this._super(...arguments);
<add> this.set('internal', 'stuff');
<add> }
<add> }));
<add>
<add> view = appendViewFor('<non-block />');
<add>
<add> equal(view.$().text(), 'stuff');
<add> });
<add>
<add> QUnit.test('non-block replaced with a div should have inner attributes', function() {
<add> registry.register('template:components/non-block', compile('<div data-static="static" data-dynamic="{{internal}}" />'));
<add>
<add> registry.register('component:non-block', GlimmerComponent.extend({
<add> init() {
<add> this._super(...arguments);
<add> this.set('internal', 'stuff');
<add> }
<add> }));
<add>
<add> view = appendViewFor('<non-block />');
<add>
<add> equal(view.$('div').attr('data-static'), 'static');
<add> equal(view.$('div').attr('data-dynamic'), 'stuff');
<add> });
<add>
<add> QUnit.test('non-block replaced with identity element should have inner attributes', function() {
<add> registry.register('template:components/non-block', compile('<non-block data-static="static" data-dynamic="{{internal}}" />'));
<add>
<add> registry.register('component:non-block', GlimmerComponent.extend({
<add> init() {
<add> this._super(...arguments);
<add> this.set('internal', 'stuff');
<add> }
<add> }));
<add>
<add> view = appendViewFor('<non-block />');
<add>
<add> equal(view.$('non-block').attr('data-static'), 'static');
<add> equal(view.$('non-block').attr('data-dynamic'), 'stuff');
<add> });
<add>
<ide> QUnit.test('non-block rendering a fragment', function() {
<ide> registry.register('template:components/non-block', compile('<p>{{attrs.first}}</p><p>{{attrs.second}}</p>'));
<ide>
<ide> if (isEnabled('ember-htmlbars-component-generation')) {
<ide> equal(view.$('with-block.ember-view').text(), 'In layout - In template', 'Both the layout and template are rendered');
<ide> });
<ide>
<del> QUnit.test('non-block with properties on attrs', function() {
<add> QUnit.test('non-block with properties on attrs', function() {
<ide> registry.register('template:components/non-block', compile('<non-block>In layout</non-block>'));
<ide>
<ide> view = appendViewFor('<non-block static-prop="static text" concat-prop="{{view.dynamic}} text" dynamic-prop={{view.dynamic}} />', { | 1 |
Javascript | Javascript | use setimmediate() in test of stream2 | 99277952b4881fbb65d9a7dc03fc9a3c5cc0290e | <ide><path>test/parallel/test-stream2-push.js
<ide> function end() {
<ide> source.emit('end');
<ide> assert(!reading);
<ide> writer.end(stream.read());
<del> setTimeout(function() {
<add> setImmediate(function() {
<ide> assert(ended);
<ide> });
<ide> } | 1 |
Javascript | Javascript | set ng-valid/ng-invalid correctly | 08bfea183a850b29da270eac47f80b598cbe600f | <ide><path>src/directive/input.js
<ide> var NgModelController = ['$scope', '$exceptionHandler', '$attrs', 'ngModel', '$e
<ide>
<ide> if (isValid) {
<ide> if ($error[validationErrorKey]) invalidCount--;
<del> $error[validationErrorKey] = false;
<del> toggleValidCss(isValid);
<ide> if (!invalidCount) {
<del> toggleValidCss(isValid, validationErrorKey);
<add> toggleValidCss(true);
<ide> this.$valid = true;
<ide> this.$invalid = false;
<ide> }
<ide> } else {
<del> if (!$error[validationErrorKey]) invalidCount++;
<del> $error[validationErrorKey] = true;
<del> toggleValidCss(isValid)
<del> toggleValidCss(isValid, validationErrorKey);
<add> toggleValidCss(false)
<ide> this.$invalid = true;
<ide> this.$valid = false;
<add> invalidCount++;
<ide> }
<ide>
<add> $error[validationErrorKey] = !isValid;
<add> toggleValidCss(isValid, validationErrorKey);
<add>
<ide> parentForm.$setValidity(validationErrorKey, isValid, this);
<ide> };
<ide>
<ide><path>test/directive/inputSpec.js
<ide> describe('ng-model', function() {
<ide>
<ide> dealoc(element);
<ide> }));
<add>
<add>
<add> it('should set invalid classes on init', inject(function($compile, $rootScope) {
<add> var element = $compile('<input type="email" ng-model="value" required />')($rootScope);
<add> $rootScope.$digest();
<add>
<add> expect(element).toBeInvalid();
<add> expect(element).toHaveClass('ng-invalid-required');
<add> }));
<ide> });
<ide>
<ide> | 2 |
Javascript | Javascript | add usenativedriver toggle ui | 63e0f7d76765e6e711b47dc64b04a6065193cab1 | <ide><path>packages/rn-tester/js/components/RNTConfigurationBlock.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> * @format
<add> * @flow strict-local
<add> */
<add>
<add>'use strict';
<add>
<add>import * as React from 'react';
<add>import {StyleSheet, View} from 'react-native';
<add>import {RNTesterThemeContext} from './RNTesterTheme';
<add>
<add>type Props = $ReadOnly<{|
<add> children?: ?React.Node,
<add> testID?: string,
<add>|}>;
<add>
<add>/**
<add> * Container view for a block of configuration options for an example.
<add> */
<add>export default function RNTConfigurationBlock(props: Props): React.Node {
<add> const theme = React.useContext(RNTesterThemeContext);
<add> return (
<add> <View
<add> style={StyleSheet.compose(styles.container, {
<add> borderColor: theme.SeparatorColor,
<add> })}
<add> testID={props.testID}>
<add> {props.children}
<add> </View>
<add> );
<add>}
<add>
<add>const styles = StyleSheet.create({
<add> container: {
<add> padding: 10,
<add> borderBottomWidth: 1,
<add> },
<add>});
<ide><path>packages/rn-tester/js/components/RNTTestDetails.js
<ide> * LICENSE file in the root directory of this source tree.
<ide> *
<ide> * @format
<del> * @flow
<add> * @flow strict-local
<ide> */
<ide>
<ide> import * as React from 'react';
<ide> import {View, Text, StyleSheet, Button} from 'react-native';
<ide> import {type RNTesterTheme} from './RNTesterTheme';
<ide>
<ide> function RNTTestDetails({
<del> test,
<ide> description,
<ide> expect,
<ide> title,
<ide> theme,
<ide> }: {
<del> test?: string,
<ide> description?: string,
<ide> expect?: string,
<ide> title: string,
<ide> theme: RNTesterTheme,
<ide> }): React.Node {
<ide> const [collapsed, setCollapsed] = React.useState(false);
<ide>
<del> const content =
<del> test != null ? (
<del> <>
<add> const content = (
<add> <>
<add> {description == null ? null : (
<ide> <View style={styles.section}>
<del> <Text style={styles.heading}>How to Test</Text>
<del> <Text style={styles.paragraph}>{test}</Text>
<add> <Text style={styles.heading}>Description</Text>
<add> <Text style={styles.paragraph}>{description}</Text>
<ide> </View>
<del> {expect != null && (
<del> <View style={styles.section}>
<del> <Text style={styles.heading}>Expectation</Text>
<del> <Text style={styles.paragraph}>{expect}</Text>
<del> </View>
<del> )}
<del> </>
<del> ) : description != null ? (
<del> <View style={styles.section}>
<del> <Text style={styles.heading}>Description</Text>
<del> <Text style={styles.paragraph}>{description}</Text>
<del> </View>
<del> ) : null;
<del>
<add> )}
<add> {expect == null ? null : (
<add> <View style={styles.section}>
<add> <Text style={styles.heading}>Expectation</Text>
<add> <Text style={styles.paragraph}>{expect}</Text>
<add> </View>
<add> )}
<add> </>
<add> );
<ide> return (
<ide> <View
<ide> style={StyleSheet.compose(styles.container, {
<ide><path>packages/rn-tester/js/examples/Animated/ComposeAnimationsWithEasingExample.js
<ide> import type {RNTesterModuleExample} from '../../types/RNTesterTypes';
<ide> import * as React from 'react';
<ide> import RNTesterButton from '../../components/RNTesterButton';
<ide> import {Text, Easing, StyleSheet, View, Animated} from 'react-native';
<add>import RNTConfigurationBlock from '../../components/RNTConfigurationBlock';
<ide>
<ide> const styles = StyleSheet.create({
<ide> content: {
<ide> const styles = StyleSheet.create({
<ide> },
<ide> });
<ide>
<del>export default ({
<del> title: 'Composite Animations with Easing',
<del> name: 'compositeAnimationsWithEasing',
<del> description: ('Sequence, parallel, delay, and ' +
<del> 'stagger with different easing functions.': string),
<del> render: function(): React.Node {
<del> const anims = [1, 2, 3].map(() => new Animated.Value(0));
<del> return (
<del> <View>
<del> <RNTesterButton
<del> onPress={() => {
<del> Animated.sequence([
<del> // One after the other
<del> Animated.timing(anims[0], {
<del> toValue: 200,
<del> // $FlowFixMe[method-unbinding]
<del> easing: Easing.linear,
<del> useNativeDriver: false,
<del> }),
<del> Animated.delay(400), // Use with sequence
<del> Animated.timing(anims[0], {
<del> toValue: 0,
<add>function CompositeAnimationsWithEasingExample(): React.Node {
<add> const anims = [1, 2, 3].map(() => new Animated.Value(0));
<add>
<add> return (
<add> <View>
<add> <RNTConfigurationBlock>
<add> <Text>Note you cannot `useNativeDriver` for layout properties.</Text>
<add> </RNTConfigurationBlock>
<add> <RNTesterButton
<add> onPress={() => {
<add> Animated.sequence([
<add> // One after the other
<add> Animated.timing(anims[0], {
<add> toValue: 200,
<add> // $FlowFixMe[method-unbinding]
<add> easing: Easing.linear,
<add> useNativeDriver: false,
<add> }),
<add> Animated.delay(400), // Use with sequence
<add> Animated.timing(anims[0], {
<add> toValue: 0,
<ide>
<del> // Springy
<del> easing: Easing.elastic(2),
<add> // Springy
<add> easing: Easing.elastic(2),
<ide>
<del> useNativeDriver: false,
<del> }),
<del> Animated.delay(400),
<del> Animated.stagger(
<del> 200,
<del> anims
<del> .map(anim =>
<add> useNativeDriver: false,
<add> }),
<add> Animated.delay(400),
<add> Animated.stagger(
<add> 200,
<add> anims
<add> .map(anim =>
<add> Animated.timing(anim, {
<add> toValue: 200,
<add> useNativeDriver: false,
<add> }),
<add> )
<add> .concat(
<add> anims.map(anim =>
<ide> Animated.timing(anim, {
<del> toValue: 200,
<add> toValue: 0,
<ide> useNativeDriver: false,
<ide> }),
<del> )
<del> .concat(
<del> anims.map(anim =>
<del> Animated.timing(anim, {
<del> toValue: 0,
<del> useNativeDriver: false,
<del> }),
<del> ),
<ide> ),
<del> ),
<del> Animated.delay(400),
<del> Animated.parallel(
<del> [
<del> // $FlowFixMe[method-unbinding]
<del> Easing.inOut(Easing.quad), // Symmetric
<del> Easing.back(1.5), // Goes backwards first
<del> Easing.ease, // Default bezier
<del> ].map((easing, ii) =>
<del> Animated.timing(anims[ii], {
<del> toValue: 320,
<del> // $FlowFixMe[method-unbinding]
<del> easing,
<del> duration: 3000,
<del> useNativeDriver: false,
<del> }),
<ide> ),
<add> ),
<add> Animated.delay(400),
<add> Animated.parallel(
<add> [
<add> // $FlowFixMe[method-unbinding]
<add> Easing.inOut(Easing.quad), // Symmetric
<add> Easing.back(1.5), // Goes backwards first
<add> Easing.ease, // Default bezier
<add> ].map((easing, ii) =>
<add> Animated.timing(anims[ii], {
<add> toValue: 320,
<add> // $FlowFixMe[method-unbinding]
<add> easing,
<add> duration: 3000,
<add> useNativeDriver: false,
<add> }),
<ide> ),
<del> Animated.delay(400),
<del> Animated.stagger(
<del> 200,
<del> anims.map(anim =>
<del> Animated.timing(anim, {
<del> toValue: 0,
<add> ),
<add> Animated.delay(400),
<add> Animated.stagger(
<add> 200,
<add> anims.map(anim =>
<add> Animated.timing(anim, {
<add> toValue: 0,
<ide>
<del> // Like a ball
<del> // $FlowFixMe[method-unbinding]
<del> easing: Easing.bounce,
<add> // Like a ball
<add> // $FlowFixMe[method-unbinding]
<add> easing: Easing.bounce,
<ide>
<del> duration: 2000,
<del> useNativeDriver: false,
<del> }),
<del> ),
<add> duration: 2000,
<add> useNativeDriver: false,
<add> }),
<ide> ),
<del> ]).start();
<del> }}>
<del> Press to Animate
<del> </RNTesterButton>
<del> {['Composite', 'Easing', 'Animations!'].map((text, ii) => (
<del> <Animated.View
<del> key={text}
<del> style={[
<del> styles.content,
<del> {
<del> left: anims[ii],
<del> },
<del> ]}>
<del> <Text>{text}</Text>
<del> </Animated.View>
<del> ))}
<del> </View>
<del> );
<del> },
<add> ),
<add> ]).start();
<add> }}>
<add> Press to Animate
<add> </RNTesterButton>
<add> {['Composite', 'Easing', 'Animations!'].map((text, ii) => (
<add> <Animated.View
<add> key={text}
<add> style={[
<add> styles.content,
<add> {
<add> left: anims[ii],
<add> },
<add> ]}>
<add> <Text>{text}</Text>
<add> </Animated.View>
<add> ))}
<add> </View>
<add> );
<add>}
<add>
<add>export default ({
<add> title: 'Composite Animations with Easing',
<add> name: 'compositeAnimationsWithEasing',
<add> description: ('Sequence, parallel, delay, and ' +
<add> 'stagger with different easing functions.': string),
<add> expect:
<add> 'The 3 views will animate their `left` position based on their animation configurations.',
<add> render: () => <CompositeAnimationsWithEasingExample />,
<ide> }: RNTesterModuleExample);
<ide><path>packages/rn-tester/js/examples/Animated/ComposingExample.js
<ide> import type {RNTesterModuleExample} from '../../types/RNTesterTypes';
<ide> import type {CompositeAnimation} from 'react-native/Libraries/Animated/AnimatedMock';
<ide> import * as React from 'react';
<ide> import RNTesterButton from '../../components/RNTesterButton';
<add>import RNTConfigurationBlock from '../../components/RNTConfigurationBlock';
<add>import ToggleNativeDriver from './utils/ToggleNativeDriver';
<ide> import {Text, StyleSheet, View, Animated, FlatList} from 'react-native';
<ide>
<ide> type Props = $ReadOnly<{||}>;
<ide>
<del>const leftToRightTimingConfig = {
<add>const leftToRightTimingConfig = useNativeDriver => ({
<ide> toValue: 200,
<del> useNativeDriver: true,
<del>};
<del>const rightToLeftTimingConfig = {
<add> useNativeDriver,
<add>});
<add>const rightToLeftTimingConfig = useNativeDriver => ({
<ide> toValue: 0,
<del> useNativeDriver: true,
<del>};
<add> useNativeDriver,
<add>});
<ide> const items = [
<ide> {
<ide> title: 'Parallel',
<del> compositeAnimation: values =>
<add> compositeAnimation: (values, useNativeDriver) =>
<ide> Animated.sequence([
<ide> Animated.parallel(
<del> values.map(value => Animated.timing(value, leftToRightTimingConfig)),
<add> values.map(value =>
<add> Animated.timing(value, leftToRightTimingConfig(useNativeDriver)),
<add> ),
<ide> ),
<ide> Animated.parallel(
<del> values.map(value => Animated.timing(value, rightToLeftTimingConfig)),
<add> values.map(value =>
<add> Animated.timing(value, rightToLeftTimingConfig(useNativeDriver)),
<add> ),
<ide> ),
<ide> ]),
<ide> },
<ide> {
<ide> title: 'Sequence',
<del> compositeAnimation: values =>
<add> compositeAnimation: (values, useNativeDriver) =>
<ide> Animated.sequence([
<ide> Animated.sequence(
<del> values.map(value => Animated.timing(value, leftToRightTimingConfig)),
<add> values.map(value =>
<add> Animated.timing(value, leftToRightTimingConfig(useNativeDriver)),
<add> ),
<ide> ),
<ide> Animated.sequence(
<del> values.map(value => Animated.timing(value, rightToLeftTimingConfig)),
<add> values.map(value =>
<add> Animated.timing(value, rightToLeftTimingConfig(useNativeDriver)),
<add> ),
<ide> ),
<ide> ]),
<ide> },
<ide> {
<ide> title: 'Stagger',
<del> compositeAnimation: values =>
<add> compositeAnimation: (values, useNativeDriver) =>
<ide> Animated.sequence([
<ide> Animated.stagger(
<ide> 150,
<del> values.map(value => Animated.timing(value, leftToRightTimingConfig)),
<add> values.map(value =>
<add> Animated.timing(value, leftToRightTimingConfig(useNativeDriver)),
<add> ),
<ide> ),
<ide> Animated.stagger(
<ide> 150,
<del> values.map(value => Animated.timing(value, rightToLeftTimingConfig)),
<add> values.map(value =>
<add> Animated.timing(value, rightToLeftTimingConfig(useNativeDriver)),
<add> ),
<ide> ),
<ide> ]),
<ide> },
<ide> {
<ide> title: 'Delay',
<del> compositeAnimation: values =>
<add> compositeAnimation: (values, useNativeDriver) =>
<ide> Animated.sequence([
<ide> Animated.delay(2000),
<ide> Animated.parallel(
<del> values.map(value => Animated.timing(value, leftToRightTimingConfig)),
<add> values.map(value =>
<add> Animated.timing(value, leftToRightTimingConfig(useNativeDriver)),
<add> ),
<ide> ),
<ide> Animated.delay(2000),
<ide> Animated.parallel(
<del> values.map(value => Animated.timing(value, rightToLeftTimingConfig)),
<add> values.map(value =>
<add> Animated.timing(value, rightToLeftTimingConfig(useNativeDriver)),
<add> ),
<ide> ),
<ide> ]),
<ide> },
<ide> const items = [
<ide> function ComposingExampleItem({
<ide> title,
<ide> compositeAnimation,
<add> useNativeDriver,
<ide> }: {
<ide> title: string,
<del> compositeAnimation: (values: Animated.Value[]) => CompositeAnimation,
<add> compositeAnimation: (
<add> values: Animated.Value[],
<add> useNativeDriver: boolean,
<add> ) => CompositeAnimation,
<add> useNativeDriver: boolean,
<ide> }): React.Node {
<ide> const boxes = [0, 1, 2, 3, 4];
<ide> const xTranslations = React.useRef(boxes.map(() => new Animated.Value(0)))
<ide> function ComposingExampleItem({
<ide> <Text style={styles.itemTitle}>{title}</Text>
<ide> <RNTesterButton
<ide> onPress={() => {
<del> compositeAnimation(xTranslations).start();
<add> compositeAnimation(xTranslations, useNativeDriver).start();
<ide> }}>
<ide> Animate
<ide> </RNTesterButton>
<ide> function ComposingExampleItem({
<ide> }
<ide>
<ide> function ComposingExample(props: Props): React.Node {
<add> const [useNativeDriver, setUseNativeDriver] = React.useState(false);
<ide> return (
<del> <FlatList
<del> data={items}
<del> renderItem={({item}) => (
<del> <ComposingExampleItem
<del> key={item.title}
<del> title={item.title}
<del> compositeAnimation={item.compositeAnimation}
<add> <>
<add> <RNTConfigurationBlock>
<add> <ToggleNativeDriver
<add> value={useNativeDriver}
<add> onValueChange={setUseNativeDriver}
<ide> />
<del> )}
<del> />
<add> </RNTConfigurationBlock>
<add> <FlatList
<add> data={items}
<add> renderItem={({item}) => (
<add> <ComposingExampleItem
<add> key={item.title}
<add> title={item.title}
<add> compositeAnimation={item.compositeAnimation}
<add> useNativeDriver={useNativeDriver}
<add> />
<add> )}
<add> />
<add> </>
<ide> );
<ide> }
<ide>
<ide><path>packages/rn-tester/js/examples/Animated/FadeInViewExample.js
<ide> import type {RNTesterModuleExample} from '../../types/RNTesterTypes';
<ide> import * as React from 'react';
<ide> import RNTesterButton from '../../components/RNTesterButton';
<add>import ToggleNativeDriver from './utils/ToggleNativeDriver';
<ide> import {Text, StyleSheet, View, Animated} from 'react-native';
<add>import RNTConfigurationBlock from '../../components/RNTConfigurationBlock';
<ide>
<ide> const styles = StyleSheet.create({
<ide> content: {
<ide> const styles = StyleSheet.create({
<ide> },
<ide> });
<ide>
<del>function FadeInView({children}: {children: React.Node}) {
<add>function FadeInView({
<add> useNativeDriver,
<add> children,
<add>}: {
<add> useNativeDriver: boolean,
<add> children: React.Node,
<add>}) {
<ide> //opacity 0
<ide> const [fadeAnim, setFadeAnim] = React.useState(() => new Animated.Value(0));
<ide> React.useEffect(() => {
<ide> function FadeInView({children}: {children: React.Node}) {
<ide> // Configuration
<ide> duration: 2000,
<ide>
<del> useNativeDriver: false,
<add> useNativeDriver,
<ide> },
<ide> ).start(); // Don't forget start!
<del> }, [fadeAnim]);
<add> }, [fadeAnim, useNativeDriver]);
<ide>
<ide> return (
<ide> <Animated.View // Special animatable View
<ide> function FadeInView({children}: {children: React.Node}) {
<ide>
<ide> function FadeInExample(): React.Node {
<ide> const [show, setShow] = React.useState(true);
<add> const [useNativeDriver, setUseNativeDriver] = React.useState(false);
<ide> return (
<ide> <View>
<add> <RNTConfigurationBlock>
<add> <ToggleNativeDriver
<add> value={useNativeDriver}
<add> onValueChange={setUseNativeDriver}
<add> />
<add> </RNTConfigurationBlock>
<ide> <RNTesterButton testID="toggle-button" onPress={() => setShow(!show)}>
<ide> Press to {show ? 'Hide' : 'Show'}
<ide> </RNTesterButton>
<ide> {show && (
<del> <FadeInView>
<add> <FadeInView useNativeDriver={useNativeDriver}>
<ide> <View testID="fade-in-view" style={styles.content}>
<ide> <Text>FadeInView</Text>
<ide> </View>
<ide><path>packages/rn-tester/js/examples/Animated/LoopingExample.js
<ide> import RNTesterButton from '../../components/RNTesterButton';
<ide> import type {RNTesterModuleExample} from '../../types/RNTesterTypes';
<ide> import {Animated, StyleSheet, Text, View} from 'react-native';
<ide> import * as React from 'react';
<del>import {useEffect, useState} from 'react';
<add>import {useEffect} from 'react';
<add>import ToggleNativeDriver from './utils/ToggleNativeDriver';
<add>import RNTConfigurationBlock from '../../components/RNTConfigurationBlock';
<ide>
<ide> export default ({
<ide> title: 'Looping Example',
<ide> export default ({
<ide> render: () => <LoopingExample />,
<ide> }: RNTesterModuleExample);
<ide>
<del>function LoopingExample(props: {}): React.Node {
<del> const [running, setRunning] = useState(false);
<del> const [opacity] = useState(() => new Animated.Value(1));
<del> const [scale] = useState(() => new Animated.Value(1));
<add>function LoopingView({
<add> useNativeDriver,
<add> running,
<add>}: {
<add> useNativeDriver: boolean,
<add> running: boolean,
<add>}) {
<add> const opacity = React.useMemo(() => new Animated.Value(1), []);
<add> const scale = React.useMemo(() => new Animated.Value(1), []);
<ide>
<ide> useEffect(() => {
<ide> if (!running) {
<ide> return;
<ide> }
<add>
<ide> const options = {
<ide> duration: 1000,
<ide> toValue: 0,
<del> useNativeDriver: true,
<add> useNativeDriver,
<ide> };
<ide> const animation = Animated.loop(
<ide> Animated.parallel([
<ide> function LoopingExample(props: {}): React.Node {
<ide> ]),
<ide> );
<ide> animation.start();
<add>
<ide> return () => {
<ide> animation.reset();
<ide> };
<del> }, [opacity, running, scale]);
<add> }, [opacity, scale, running, useNativeDriver]);
<add>
<add> return (
<add> <Animated.View style={[styles.view, {opacity, transform: [{scale}]}]}>
<add> <Text>Looping!</Text>
<add> </Animated.View>
<add> );
<add>}
<add>
<add>function LoopingExample(props: {}): React.Node {
<add> const [running, setRunning] = React.useState(false);
<add> const [useNativeDriver, setUseNativeDriver] = React.useState(false);
<ide>
<ide> return (
<ide> <View>
<add> <RNTConfigurationBlock>
<add> <ToggleNativeDriver
<add> value={useNativeDriver}
<add> onValueChange={value => {
<add> setRunning(false);
<add> setUseNativeDriver(value);
<add> }}
<add> />
<add> </RNTConfigurationBlock>
<ide> <RNTesterButton onPress={() => setRunning(!running)}>
<ide> Press to {running ? 'Reset' : 'Start'}
<ide> </RNTesterButton>
<del> <Animated.View style={[styles.view, {opacity, transform: [{scale}]}]}>
<del> <Text>Looping!</Text>
<del> </Animated.View>
<add> <LoopingView
<add> key={`looping-view-${useNativeDriver ? 'native' : 'js'}-driver`}
<add> useNativeDriver={useNativeDriver}
<add> running={running}
<add> />
<ide> </View>
<ide> );
<ide> }
<ide><path>packages/rn-tester/js/examples/Animated/MovingBoxExample.js
<ide> import type {RNTesterModuleExample} from '../../types/RNTesterTypes';
<ide> import * as React from 'react';
<ide> import RNTesterButton from '../../components/RNTesterButton';
<ide> import {Text, StyleSheet, View, Animated} from 'react-native';
<add>import RNTConfigurationBlock from '../../components/RNTConfigurationBlock';
<add>import ToggleNativeDriver from './utils/ToggleNativeDriver';
<ide> const containerWidth = 200;
<ide> const boxSize = 50;
<ide>
<ide> const styles = StyleSheet.create({
<ide>
<ide> type Props = $ReadOnly<{||}>;
<ide>
<del>function MovingBoxExample(props: Props): React.Node {
<add>function MovingBoxView({useNativeDriver}: {useNativeDriver: boolean}) {
<ide> const x = React.useRef(new Animated.Value(0));
<add> const [update, setUpdate] = React.useState(0);
<ide> const [boxVisible, setBoxVisible] = React.useState(true);
<ide>
<ide> const moveTo = (pos: number) => {
<ide> Animated.timing(x.current, {
<ide> toValue: pos,
<ide> duration: 1000,
<del> useNativeDriver: true,
<add> useNativeDriver,
<ide> }).start();
<ide> };
<ide>
<ide> function MovingBoxExample(props: Props): React.Node {
<ide> const toggleText = boxVisible ? 'Hide' : 'Show';
<ide> const onReset = () => {
<ide> x.current.resetAnimation();
<add> setUpdate(update + 1);
<ide> };
<del>
<ide> return (
<ide> <View style={styles.container}>
<del> {boxVisible ? (
<del> <View style={styles.boxContainer}>
<add> <View style={styles.boxContainer}>
<add> {boxVisible ? (
<ide> <Animated.View
<ide> testID="moving-view"
<ide> style={[
<ide> function MovingBoxExample(props: Props): React.Node {
<ide> {transform: [{translateX: x.current}]},
<ide> ]}
<ide> />
<del> </View>
<del> ) : (
<del> <View style={styles.boxContainer}>
<add> ) : (
<ide> <Text>The box view is not being rendered</Text>
<del> </View>
<del> )}
<add> )}
<add> </View>
<ide> <View style={styles.buttonsContainer}>
<ide> <RNTesterButton testID="move-left-button" onPress={() => moveTo(0)}>
<ide> {'<-'}
<ide> function MovingBoxExample(props: Props): React.Node {
<ide> );
<ide> }
<ide>
<add>function MovingBoxExample(props: Props): React.Node {
<add> const [useNativeDriver, setUseNativeDriver] = React.useState(false);
<add>
<add> return (
<add> <>
<add> <RNTConfigurationBlock>
<add> <ToggleNativeDriver
<add> value={useNativeDriver}
<add> onValueChange={setUseNativeDriver}
<add> />
<add> </RNTConfigurationBlock>
<add> <MovingBoxView
<add> key={`moving-box-view-${useNativeDriver ? 'native' : 'js'}-driver`}
<add> useNativeDriver={useNativeDriver}
<add> />
<add> </>
<add> );
<add>}
<add>
<ide> export default ({
<ide> title: 'Moving box example',
<ide> name: 'movingView',
<ide> description:
<del> 'Click arrow buttons to move the box. Then hide the box and reveal it again. The box will stay its last position. Reset will reset the animation to its starting position',
<add> 'Click arrow buttons to move the box. Hide will remove the box from layout.',
<add> expect:
<add> 'During animation, removing box from layout will stop the animation and box will stay in its current position.\nStarting animation when box is not rendered and rendering mid-way does not affect animation.\nReset will reset the animation to its starting position.',
<ide> render: (): React.Node => <MovingBoxExample />,
<ide> }: RNTesterModuleExample);
<ide><path>packages/rn-tester/js/examples/Animated/RotatingImagesExample.js
<ide> import * as React from 'react';
<ide> import RNTesterButton from '../../components/RNTesterButton';
<ide> import {Animated, View, StyleSheet} from 'react-native';
<ide> import type {RNTesterModuleExample} from '../../types/RNTesterTypes';
<add>import RNTConfigurationBlock from '../../components/RNTConfigurationBlock';
<add>import ToggleNativeDriver from './utils/ToggleNativeDriver';
<ide>
<ide> const styles = StyleSheet.create({
<ide> rotatingImage: {
<ide> const styles = StyleSheet.create({
<ide> },
<ide> });
<ide>
<del>function RotatingImagesExample(): React.Node {
<del> const anim = React.useRef(new Animated.Value(0));
<del> return (
<del> <View>
<del> <RNTesterButton
<del> onPress={() => {
<del> Animated.spring(anim.current, {
<del> // Returns to the start
<del> toValue: 0,
<add>function RotatingImagesView({useNativeDriver}: {useNativeDriver: boolean}) {
<add> const anim = new Animated.Value(0);
<add> const rotatingAnimation = Animated.spring(anim, {
<add> // Returns to the start
<add> toValue: 0,
<ide>
<del> // Velocity makes it move
<del> velocity: 3,
<add> // Velocity makes it move
<add> velocity: 3,
<ide>
<del> // Slow
<del> tension: -10,
<add> // Slow
<add> tension: -10,
<ide>
<del> // Oscillate a lot
<del> friction: 1,
<add> // Oscillate a lot
<add> friction: 1,
<add> useNativeDriver,
<add> });
<ide>
<del> useNativeDriver: false,
<del> }).start();
<add> return (
<add> <>
<add> <RNTesterButton
<add> onPress={() => {
<add> rotatingAnimation.start();
<ide> }}>
<ide> Press to Spin it!
<ide> </RNTesterButton>
<ide> function RotatingImagesExample(): React.Node {
<ide> {
<ide> transform: [
<ide> {
<del> scale: anim.current.interpolate({
<add> scale: anim.interpolate({
<ide> inputRange: [0, 1],
<ide> outputRange: ([1, 10]: $ReadOnlyArray<number>),
<ide> }),
<ide> },
<ide> {
<del> translateX: anim.current.interpolate({
<add> translateX: anim.interpolate({
<ide> inputRange: [0, 1],
<ide> outputRange: ([0, 100]: $ReadOnlyArray<number>),
<ide> }),
<ide> },
<ide> {
<del> rotate: anim.current.interpolate({
<add> rotate: anim.interpolate({
<ide> inputRange: [0, 1],
<ide> outputRange: ([
<ide> '0deg',
<ide> function RotatingImagesExample(): React.Node {
<ide> },
<ide> ]}
<ide> />
<add> </>
<add> );
<add>}
<add>
<add>function RotatingImagesExample(): React.Node {
<add> const [useNativeDriver, setUseNativeDriver] = React.useState(false);
<add>
<add> return (
<add> <View>
<add> <RNTConfigurationBlock>
<add> <ToggleNativeDriver
<add> value={useNativeDriver}
<add> onValueChange={setUseNativeDriver}
<add> />
<add> </RNTConfigurationBlock>
<add> <RotatingImagesView
<add> key={`rotating-images-view-${useNativeDriver ? 'native' : 'js'}-driver`}
<add> useNativeDriver={useNativeDriver}
<add> />
<ide> </View>
<ide> );
<ide> }
<ide> export default ({
<ide> title: 'Rotating Images',
<ide> name: 'rotatingImages',
<ide> description: 'Simple Animated.Image rotation.',
<add> expect:
<add> 'Transform animation on image in scale, rotation, and translation. JS driver will ignore any calls to `start` on running animation. Native driver will re-start the animation.',
<ide> render: RotatingImagesExample,
<ide> }: RNTesterModuleExample);
<ide><path>packages/rn-tester/js/examples/Animated/TransformBounceExample.js
<ide> import * as React from 'react';
<ide> import RNTesterButton from '../../components/RNTesterButton';
<ide> import {Text, StyleSheet, View, Animated} from 'react-native';
<ide> import type {RNTesterModuleExample} from '../../types/RNTesterTypes';
<add>import RNTConfigurationBlock from '../../components/RNTConfigurationBlock';
<add>import ToggleNativeDriver from './utils/ToggleNativeDriver';
<ide>
<ide> const styles = StyleSheet.create({
<ide> content: {
<ide> const styles = StyleSheet.create({
<ide> },
<ide> });
<ide>
<add>function TransformBounceView({useNativeDriver}: {useNativeDriver: boolean}) {
<add> const anim = new Animated.Value(0);
<add> const bounceAnimation = Animated.spring(anim, {
<add> // Returns to the start
<add> toValue: 0,
<add>
<add> // Velocity makes it move
<add> velocity: 3,
<add>
<add> // Slow
<add> tension: -10,
<add>
<add> // Oscillate a lot
<add> friction: 1,
<add>
<add> useNativeDriver,
<add> });
<add>
<add> return (
<add> <>
<add> <RNTesterButton
<add> onPress={() => {
<add> bounceAnimation.start();
<add> }}>
<add> Press to Fling it!
<add> </RNTesterButton>
<add> <Animated.View
<add> style={[
<add> styles.content,
<add> {
<add> transform: [
<add> // Array order matters
<add> {
<add> scale: anim.interpolate({
<add> inputRange: [0, 1],
<add> outputRange: ([1, 4]: $ReadOnlyArray<number>),
<add> }),
<add> },
<add> {
<add> translateX: anim.interpolate({
<add> inputRange: [0, 1],
<add> outputRange: ([0, 500]: $ReadOnlyArray<number>),
<add> }),
<add> },
<add> {
<add> rotate: anim.interpolate({
<add> inputRange: [0, 1],
<add> outputRange: ([
<add> '0deg',
<add> '360deg', // 'deg' or 'rad'
<add> ]: $ReadOnlyArray<string>),
<add> }),
<add> },
<add> ],
<add> },
<add> ]}>
<add> <Text>Transforms!</Text>
<add> </Animated.View>
<add> </>
<add> );
<add>}
<add>
<add>function TransformBounceExample(): React.Node {
<add> const [useNativeDriver, setUseNativeDriver] = React.useState(false);
<add>
<add> return (
<add> <View>
<add> <RNTConfigurationBlock>
<add> <ToggleNativeDriver
<add> value={useNativeDriver}
<add> onValueChange={setUseNativeDriver}
<add> />
<add> </RNTConfigurationBlock>
<add> <TransformBounceView
<add> key={`transform-bounce-view-${
<add> useNativeDriver ? 'native' : 'js'
<add> }-driver`}
<add> useNativeDriver={useNativeDriver}
<add> />
<add> </View>
<add> );
<add>}
<add>
<ide> export default ({
<ide> title: 'Transform Bounce',
<ide> name: 'transformBounce',
<add> expect: 'Transform animation on rotation, translation, scale of View',
<ide> description: ('One `Animated.Value` is driven by a ' +
<ide> 'spring with custom constants and mapped to an ' +
<ide> 'ordered set of transforms. Each transform has ' +
<ide> 'an interpolation to convert the value into the ' +
<ide> 'right range and units.': string),
<del> render: function(): React.Node {
<del> const anim = new Animated.Value(0);
<del> return (
<del> <View>
<del> <RNTesterButton
<del> onPress={() => {
<del> Animated.spring(anim, {
<del> // Returns to the start
<del> toValue: 0,
<del>
<del> // Velocity makes it move
<del> velocity: 3,
<del>
<del> // Slow
<del> tension: -10,
<del>
<del> // Oscillate a lot
<del> friction: 1,
<del>
<del> useNativeDriver: false,
<del> }).start();
<del> }}>
<del> Press to Fling it!
<del> </RNTesterButton>
<del> <Animated.View
<del> style={[
<del> styles.content,
<del> {
<del> transform: [
<del> // Array order matters
<del> {
<del> scale: anim.interpolate({
<del> inputRange: [0, 1],
<del> outputRange: ([1, 4]: $ReadOnlyArray<number>),
<del> }),
<del> },
<del> {
<del> translateX: anim.interpolate({
<del> inputRange: [0, 1],
<del> outputRange: ([0, 500]: $ReadOnlyArray<number>),
<del> }),
<del> },
<del> {
<del> rotate: anim.interpolate({
<del> inputRange: [0, 1],
<del> outputRange: ([
<del> '0deg',
<del> '360deg', // 'deg' or 'rad'
<del> ]: $ReadOnlyArray<string>),
<del> }),
<del> },
<del> ],
<del> },
<del> ]}>
<del> <Text>Transforms!</Text>
<del> </Animated.View>
<del> </View>
<del> );
<del> },
<add> render: () => <TransformBounceExample />,
<ide> }: RNTesterModuleExample);
<ide><path>packages/rn-tester/js/examples/Animated/utils/ToggleNativeDriver.js
<add>/**
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> *
<add> * @flow strict-local
<add> * @format
<add> */
<add>
<add>import {View, Text, StyleSheet, Switch} from 'react-native';
<add>import * as React from 'react';
<add>
<add>type Props = {
<add> value: boolean,
<add> onValueChange: $ElementType<
<add> React.ElementConfig<typeof Switch>,
<add> 'onValueChange',
<add> >,
<add>};
<add>
<add>export default function ToggleNativeDriver({
<add> value,
<add> onValueChange,
<add>}: Props): React.Node {
<add> return (
<add> <View style={styles.row}>
<add> <Text>Use Native Driver</Text>
<add> <Switch
<add> testID="toggle-use-native-driver"
<add> onValueChange={onValueChange}
<add> value={value}
<add> />
<add> </View>
<add> );
<add>}
<add>
<add>const styles = StyleSheet.create({
<add> row: {
<add> flexDirection: 'row',
<add> justifyContent: 'space-between',
<add> alignItems: 'center',
<add> },
<add>}); | 10 |
Javascript | Javascript | use empty object | 714f0b8b7d4c95d18b561845493cc031d182eec7 | <ide><path>packages/ember-metal/lib/meta.js
<ide>
<ide> import isEnabled from 'ember-metal/features';
<ide> import { protoMethods as listenerMethods } from 'ember-metal/meta_listeners';
<add>import EmptyObject from 'ember-metal/empty_object';
<ide>
<ide> /**
<ide> @module ember-metal
<ide> function ownMap(name, Meta) {
<ide> Meta.prototype._getOrCreateOwnMap = function(key) {
<ide> let ret = this[key];
<ide> if (!ret) {
<del> ret = this[key] = {};
<add> ret = this[key] = new EmptyObject();
<ide> }
<ide> return ret;
<ide> };
<ide> function inheritedMap(name, Meta) {
<ide> };
<ide>
<ide> Meta.prototype['clear' + capitalized] = function() {
<del> this[key] = {};
<add> this[key] = new EmptyObject();
<ide> };
<ide> }
<ide>
<ide> Meta.prototype._getOrCreateInheritedMap = function(key) {
<ide> if (this.parent) {
<ide> ret = this[key] = Object.create(this.parent._getOrCreateInheritedMap(key));
<ide> } else {
<del> ret = this[key] = {};
<add> ret = this[key] = new EmptyObject();
<ide> }
<ide> }
<ide> return ret;
<ide> function inheritedMapOfMaps(name, Meta) {
<ide> let outerMap = this._getOrCreateInheritedMap(key);
<ide> let innerMap = outerMap[subkey];
<ide> if (!innerMap) {
<del> innerMap = outerMap[subkey] = {};
<add> innerMap = outerMap[subkey] = new EmptyObject();
<ide> } else if (!Object.hasOwnProperty.call(outerMap, subkey)) {
<ide> innerMap = outerMap[subkey] = Object.create(innerMap);
<ide> } | 1 |
Javascript | Javascript | fix negative zoomscale in rtl | 82b268f884c2b46cb1ef55d97839614ba22a3460 | <ide><path>Libraries/Lists/VirtualizedList.js
<ide> class VirtualizedList extends React.PureComponent<Props, State> {
<ide> this._hasWarned.perf = true;
<ide> }
<ide>
<del> // e.nativeEvent.zoomScale is -1 in RTL so take absolute
<del> const zoomScale = Math.abs(e.nativeEvent.zoomScale);
<add> const zoomScale = e.nativeEvent.zoomScale;
<ide>
<ide> this._scrollMetrics = {
<ide> contentLength, | 1 |
Text | Text | improve example formatting | 574013f8dad86b5a01b25a19a8eb9abed8da6f87 | <ide><path>docs/usage/WritingTests.md
<ide> Because most of the Redux code you write are functions, and many of them are pur
<ide>
<ide> Our general advice for testing an app using Redux is:
<ide>
<del>- **Prefer writing integration tests with everything working together**. For a React app using Redux, render a `<Provider>` with a real store instance wrapping the component/s being tested. Interactions with the page being tested should use real Redux logic, with API calls mocked out so app code doesn't have to change, and assert that the UI is updated appropriately.
<add>- **Prefer writing integration tests with everything working together**. For a React app using Redux, render a `<Provider>` with a real store instance wrapping the components being tested. Interactions with the page being tested should use real Redux logic, with API calls mocked out so app code doesn't have to change, and assert that the UI is updated appropriately.
<ide> - _If_ needed, use basic unit tests for pure functions such as particularly complex reducers or selectors. However, in many cases, these are just implementation details that are covered by integration tests instead.
<ide> - **Do _not_ try to mock selector functions or the React-Redux hooks!** Mocking imports from libraries is fragile, and doesn't give you confidence that your actual app code is working.
<ide>
<ide> Because reducers are pure functions, so testing them should be straightforward.
<ide> ```js
<ide> import { createSlice } from '@reduxjs/toolkit'
<ide>
<del>const initialState = [
<del> {
<del> text: 'Use Redux',
<del> completed: false,
<del> id: 0
<del> }
<del>]
<add>const initialState = [{ text: 'Use Redux', completed: false, id: 0 }]
<ide>
<ide> const todosSlice = createSlice({
<ide> name: 'todos',
<ide> import reducer, { todoAdded } from './todosSlice'
<ide>
<ide> test('should return the initial state', () => {
<ide> expect(reducer(undefined, {})).toEqual([
<del> {
<del> text: 'Use Redux',
<del> completed: false,
<del> id: 0
<del> }
<add> { text: 'Use Redux', completed: false, id: 0 }
<ide> ])
<ide> })
<ide>
<ide> test('should handle a todo being added to an empty list', () => {
<ide> const previousState = []
<add>
<ide> expect(reducer(previousState, todoAdded('Run the tests'))).toEqual([
<del> {
<del> text: 'Run the tests',
<del> completed: false,
<del> id: 0
<del> }
<add> { text: 'Run the tests', completed: false, id: 0 }
<ide> ])
<ide> })
<ide>
<ide> test('should handle a todo being added to an existing list', () => {
<del> const previousState = [
<del> {
<del> text: 'Run the tests',
<del> completed: true,
<del> id: 0
<del> }
<del> ]
<add> const previousState = [{ text: 'Run the tests', completed: true, id: 0 }]
<add>
<ide> expect(reducer(previousState, todoAdded('Use Redux'))).toEqual([
<del> {
<del> text: 'Run the tests',
<del> completed: true,
<del> id: 0
<del> },
<del> {
<del> text: 'Use Redux',
<del> completed: false,
<del> id: 1
<del> }
<add> { text: 'Run the tests', completed: true, id: 0 },
<add> { text: 'Use Redux', completed: false, id: 1 }
<ide> ])
<ide> })
<ide> ```
<ide>
<ide> ### Selectors
<ide>
<del>Selectors are also generally pure functions, and thus can be tested using the same basic `const actual = selectSomeValue(inputValue)` approach as reducers.
<add>Selectors are also generally pure functions, and thus can be tested using the same basic approach as reducers: set up an initial value, call the selector function with those inputs, and assert that the result matches the expected output.
<ide>
<ide> However, since [most selectors are memoized to remember their last inputs](./deriving-data-selectors.md), you may need to watch for cases where a selector is returning a cached value when you expected it to generate a new one depending on where it's being used in the test.
<ide>
<ide> Middleware functions wrap behavior of `dispatch` calls in Redux, so to test this
<ide> First, we'll need a middleware function. This is similar to the real [redux-thunk](https://github.com/reduxjs/redux-thunk/blob/master/src/index.ts).
<ide>
<ide> ```js
<del>const thunk =
<add>const thunkMiddleware =
<ide> ({ dispatch, getState }) =>
<ide> next =>
<ide> action => {
<ide> const create = () => {
<ide> }
<ide> const next = jest.fn()
<ide>
<del> const invoke = action => thunk(store)(next)(action)
<add> const invoke = action => thunkMiddleware(store)(next)(action)
<ide>
<ide> return { store, next, invoke }
<ide> } | 1 |
Javascript | Javascript | remove unreachable code | 9b0246b179694d2d13298c8ff6c701b806e68aa6 | <ide><path>lib/timers.js
<ide> exports.setTimeout = function(callback, after) {
<ide> var ontimeout = callback;
<ide> switch (length) {
<ide> // fast cases
<del> case 0:
<ide> case 1:
<ide> case 2:
<ide> break;
<ide> exports.setInterval = function(callback, repeat) {
<ide> var length = arguments.length;
<ide> var ontimeout = callback;
<ide> switch (length) {
<del> case 0:
<ide> case 1:
<ide> case 2:
<ide> break;
<ide> exports.setImmediate = function(callback, arg1, arg2, arg3) {
<ide>
<ide> switch (arguments.length) {
<ide> // fast cases
<del> case 0:
<ide> case 1:
<ide> break;
<ide> case 2: | 1 |
Mixed | Javascript | add stream utilities to `filehandle` | 026bd82e3083e426bc8613be8b2285a3edd92336 | <ide><path>doc/api/fs.md
<ide> try {
<ide> }
<ide> ```
<ide>
<add>#### `filehandle.createReadStream([options])`
<add><!-- YAML
<add>added: REPLACEME
<add>-->
<add>
<add>* `options` {Object}
<add> * `encoding` {string} **Default:** `null`
<add> * `autoClose` {boolean} **Default:** `true`
<add> * `emitClose` {boolean} **Default:** `true`
<add> * `start` {integer}
<add> * `end` {integer} **Default:** `Infinity`
<add> * `highWaterMark` {integer} **Default:** `64 * 1024`
<add>* Returns: {fs.ReadStream}
<add>
<add>Unlike the 16 kb default `highWaterMark` for a {stream.Readable}, the stream
<add>returned by this method has a default `highWaterMark` of 64 kb.
<add>
<add>`options` can include `start` and `end` values to read a range of bytes from
<add>the file instead of the entire file. Both `start` and `end` are inclusive and
<add>start counting at 0, allowed values are in the
<add>[0, [`Number.MAX_SAFE_INTEGER`][]] range. If `start` is
<add>omitted or `undefined`, `filehandle.createReadStream()` reads sequentially from
<add>the current file position. The `encoding` can be any one of those accepted by
<add>{Buffer}.
<add>
<add>If the `FileHandle` points to a character device that only supports blocking
<add>reads (such as keyboard or sound card), read operations do not finish until data
<add>is available. This can prevent the process from exiting and the stream from
<add>closing naturally.
<add>
<add>By default, the stream will emit a `'close'` event after it has been
<add>destroyed. Set the `emitClose` option to `false` to change this behavior.
<add>
<add>```mjs
<add>import { open } from 'fs/promises';
<add>
<add>const fd = await open('/dev/input/event0');
<add>// Create a stream from some character device.
<add>const stream = fd.createReadStream();
<add>setTimeout(() => {
<add> stream.close(); // This may not close the stream.
<add> // Artificially marking end-of-stream, as if the underlying resource had
<add> // indicated end-of-file by itself, allows the stream to close.
<add> // This does not cancel pending read operations, and if there is such an
<add> // operation, the process may still not be able to exit successfully
<add> // until it finishes.
<add> stream.push(null);
<add> stream.read(0);
<add>}, 100);
<add>```
<add>
<add>If `autoClose` is false, then the file descriptor won't be closed, even if
<add>there's an error. It is the application's responsibility to close it and make
<add>sure there's no file descriptor leak. If `autoClose` is set to true (default
<add>behavior), on `'error'` or `'end'` the file descriptor will be closed
<add>automatically.
<add>
<add>An example to read the last 10 bytes of a file which is 100 bytes long:
<add>
<add>```mjs
<add>import { open } from 'fs/promises';
<add>
<add>const fd = await open('sample.txt');
<add>fd.createReadStream({ start: 90, end: 99 });
<add>```
<add>
<add>#### `filehandle.createWriteStream([options])`
<add><!-- YAML
<add>added: REPLACEME
<add>-->
<add>
<add>* `options` {Object}
<add> * `encoding` {string} **Default:** `'utf8'`
<add> * `autoClose` {boolean} **Default:** `true`
<add> * `emitClose` {boolean} **Default:** `true`
<add> * `start` {integer}
<add>* Returns: {fs.WriteStream}
<add>
<add>`options` may also include a `start` option to allow writing data at some
<add>position past the beginning of the file, allowed values are in the
<add>[0, [`Number.MAX_SAFE_INTEGER`][]] range. Modifying a file rather than replacing
<add>it may require the `flags` `open` option to be set to `r+` rather than the
<add>default `r`. The `encoding` can be any one of those accepted by {Buffer}.
<add>
<add>If `autoClose` is set to true (default behavior) on `'error'` or `'finish'`
<add>the file descriptor will be closed automatically. If `autoClose` is false,
<add>then the file descriptor won't be closed, even if there's an error.
<add>It is the application's responsibility to close it and make sure there's no
<add>file descriptor leak.
<add>
<add>By default, the stream will emit a `'close'` event after it has been
<add>destroyed. Set the `emitClose` option to `false` to change this behavior.
<add>
<ide> #### `filehandle.datasync()`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> changes:
<ide> * `end` {integer} **Default:** `Infinity`
<ide> * `highWaterMark` {integer} **Default:** `64 * 1024`
<ide> * `fs` {Object|null} **Default:** `null`
<del>* Returns: {fs.ReadStream} See [Readable Stream][].
<add>* Returns: {fs.ReadStream}
<ide>
<del>Unlike the 16 kb default `highWaterMark` for a readable stream, the stream
<add>Unlike the 16 kb default `highWaterMark` for a {stream.Readable}, the stream
<ide> returned by this method has a default `highWaterMark` of 64 kb.
<ide>
<ide> `options` can include `start` and `end` values to read a range of bytes from
<ide> available. This can prevent the process from exiting and the stream from
<ide> closing naturally.
<ide>
<ide> By default, the stream will emit a `'close'` event after it has been
<del>destroyed, like most `Readable` streams. Set the `emitClose` option to
<del>`false` to change this behavior.
<add>destroyed. Set the `emitClose` option to `false` to change this behavior.
<ide>
<ide> By providing the `fs` option, it is possible to override the corresponding `fs`
<ide> implementations for `open`, `read`, and `close`. When providing the `fs` option,
<ide> changes:
<ide> * `emitClose` {boolean} **Default:** `true`
<ide> * `start` {integer}
<ide> * `fs` {Object|null} **Default:** `null`
<del>* Returns: {fs.WriteStream} See [Writable Stream][].
<add>* Returns: {fs.WriteStream}
<ide>
<ide> `options` may also include a `start` option to allow writing data at some
<ide> position past the beginning of the file, allowed values are in the
<ide> It is the application's responsibility to close it and make sure there's no
<ide> file descriptor leak.
<ide>
<ide> By default, the stream will emit a `'close'` event after it has been
<del>destroyed, like most `Writable` streams. Set the `emitClose` option to
<del>`false` to change this behavior.
<add>destroyed. Set the `emitClose` option to `false` to change this behavior.
<ide>
<ide> By providing the `fs` option it is possible to override the corresponding `fs`
<ide> implementations for `open`, `write`, `writev` and `close`. Overriding `write()`
<ide> the file contents.
<ide> [MSDN-Rel-Path]: https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#fully-qualified-vs-relative-paths
<ide> [MSDN-Using-Streams]: https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams
<ide> [Naming Files, Paths, and Namespaces]: https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file
<del>[Readable Stream]: stream.md#class-streamreadable
<del>[Writable Stream]: stream.md#class-streamwritable
<ide> [`AHAFS`]: https://developer.ibm.com/articles/au-aix_event_infrastructure/
<ide> [`Buffer.byteLength`]: buffer.md#static-method-bufferbytelengthstring-encoding
<ide> [`FSEvents`]: https://developer.apple.com/documentation/coreservices/file_system_events
<ide><path>lib/internal/fs/promises.js
<ide> function lazyLoadCpPromises() {
<ide> return cpPromises ??= require('internal/fs/cp/cp').cpFn;
<ide> }
<ide>
<add>// Lazy loaded to avoid circular dependency.
<add>let fsStreams;
<add>function lazyFsStreams() {
<add> return fsStreams ??= require('internal/fs/streams');
<add>}
<add>
<ide> class FileHandle extends EventEmitterMixin(JSTransferable) {
<ide> /**
<ide> * @param {InternalFSBinding.FileHandle | undefined} filehandle
<ide> class FileHandle extends EventEmitterMixin(JSTransferable) {
<ide> return readable;
<ide> }
<ide>
<add> /**
<add> * @typedef {import('./streams').ReadStream
<add> * } ReadStream
<add> * @param {{
<add> * encoding?: string;
<add> * autoClose?: boolean;
<add> * emitClose?: boolean;
<add> * start: number;
<add> * end?: number;
<add> * highWaterMark?: number;
<add> * }} [options]
<add> * @returns {ReadStream}
<add> */
<add> createReadStream(options = undefined) {
<add> const { ReadStream } = lazyFsStreams();
<add> return new ReadStream(undefined, { ...options, fd: this });
<add> }
<add>
<add> /**
<add> * @typedef {import('./streams').WriteStream
<add> * } WriteStream
<add> * @param {{
<add> * encoding?: string;
<add> * autoClose?: boolean;
<add> * emitClose?: boolean;
<add> * start: number;
<add> * }} [options]
<add> * @returns {WriteStream}
<add> */
<add> createWriteStream(options = undefined) {
<add> const { WriteStream } = lazyFsStreams();
<add> return new WriteStream(undefined, { ...options, fd: this });
<add> }
<add>
<ide> [kTransfer]() {
<ide> if (this[kClosePromise] || this[kRefs] > 1) {
<ide> throw lazyDOMException('Cannot transfer FileHandle while in use',
<ide><path>test/parallel/test-fs-promises-file-handle-stream.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>
<add>// The following tests validate base functionality for the fs.promises
<add>// FileHandle.write method.
<add>
<add>const fs = require('fs');
<add>const { open } = fs.promises;
<add>const path = require('path');
<add>const tmpdir = require('../common/tmpdir');
<add>const assert = require('assert');
<add>const { finished } = require('stream/promises');
<add>const { buffer } = require('stream/consumers');
<add>const tmpDir = tmpdir.path;
<add>
<add>tmpdir.refresh();
<add>
<add>async function validateWrite() {
<add> const filePathForHandle = path.resolve(tmpDir, 'tmp-write.txt');
<add> const fileHandle = await open(filePathForHandle, 'w');
<add> const buffer = Buffer.from('Hello world'.repeat(100), 'utf8');
<add>
<add> const stream = fileHandle.createWriteStream();
<add> stream.end(buffer);
<add> await finished(stream);
<add>
<add> const readFileData = fs.readFileSync(filePathForHandle);
<add> assert.deepStrictEqual(buffer, readFileData);
<add>}
<add>
<add>async function validateRead() {
<add> const filePathForHandle = path.resolve(tmpDir, 'tmp-read.txt');
<add> const buf = Buffer.from('Hello world'.repeat(100), 'utf8');
<add>
<add> fs.writeFileSync(filePathForHandle, buf);
<add>
<add> const fileHandle = await open(filePathForHandle);
<add> assert.deepStrictEqual(
<add> await buffer(fileHandle.createReadStream()),
<add> buf
<add> );
<add>}
<add>
<add>Promise.all([
<add> validateWrite(),
<add> validateRead(),
<add>]).then(common.mustCall()); | 3 |
Python | Python | fix one more issue related to build dir | f0e69ab361b29daae801aa514c78d2097412691a | <ide><path>numpy/distutils/command/scons.py
<ide> def get_scons_local_path():
<ide> from numscons import get_scons_path
<ide> return get_scons_path()
<ide>
<del>def get_distutils_libdir(cmd, sconscript_path):
<add>def get_distutils_libdir(cmd, pkg):
<ide> """Returns the path where distutils install libraries, relatively to the
<ide> scons build directory."""
<ide> from numscons import get_scons_build_dir
<del> scdir = pjoin(get_scons_build_dir(), pdirname(sconscript_path))
<add> from numscons.core.utils import pkg_to_path
<add> scdir = pjoin(get_scons_build_dir(), pkg_to_path(pkg))
<ide> n = scdir.count(os.sep)
<ide> return pjoin(os.sep.join([os.pardir for i in range(n+1)]), cmd.build_lib)
<ide>
<ide> def run(self):
<ide> #cmd.append('distutils_libdir=%s' % protect_path(pjoin(self.build_lib,
<ide> # pdirname(sconscript))))
<ide> cmd.append('distutils_libdir=%s' %
<del> protect_path(get_distutils_libdir(self, sconscript)))
<add> protect_path(get_distutils_libdir(self, pkg_name)))
<ide>
<ide> if not self._bypass_distutils_cc:
<ide> cmd.append('cc_opt=%s' % self.scons_compiler) | 1 |
PHP | PHP | add tests for belongsto and null property values | 9dfe876de0fed2c35019b52f1a8f174878d3fa37 | <ide><path>tests/TestCase/ORM/Association/BelongsToTest.php
<ide> */
<ide> class BelongsToTest extends \Cake\TestSuite\TestCase {
<ide>
<add>/**
<add> * Fixtures to use.
<add> *
<add> * @var array
<add> */
<add> public $fixtures = ['core.article', 'core.comment'];
<add>
<add>/**
<add> * Don't autoload fixtures as most tests uses mocks.
<add> *
<add> * @var bool
<add> */
<add> public $autoFixture = false;
<add>
<ide> /**
<ide> * Set up
<ide> *
<ide> public function testAttachToBeforeFindExtraOptions() {
<ide> }]);
<ide> }
<ide>
<add>/**
<add> * Test that eagerLoader leaves empty associations unpopulated.
<add> *
<add> * @return void
<add> */
<add> public function testEagerLoaderLeavesEmptyAssocation() {
<add> $this->loadFixtures('Article', 'Comment');
<add> $comments = TableRegistry::get('Comments');
<add> $comments->belongsTo('Articles');
<add>
<add> // Clear the articles table so we can trigger an empty belongsTo
<add> $articles = TableRegistry::get('Articles');
<add> $articles->deleteAll([]);
<add>
<add> $comment = $comments->get(1, ['contain' => ['Articles']]);
<add> $this->assertNull($comment->article);
<add> }
<add>
<ide> } | 1 |
Python | Python | set version to 2.1.0a6.dev1 | 246538be2e55a48a674ba3ff66025205ba3de020 | <ide><path>spacy/about.py
<ide> # fmt: off
<ide>
<ide> __title__ = "spacy-nightly"
<del>__version__ = "2.1.0a6.dev0"
<add>__version__ = "2.1.0a6.dev1"
<ide> __summary__ = "Industrial-strength Natural Language Processing (NLP) with Python and Cython"
<ide> __uri__ = "https://spacy.io"
<ide> __author__ = "Explosion AI" | 1 |
Javascript | Javascript | remove picker from modal example | b22a6d6e9d9e4bd28fbd3b63c7c90d86a5f99a1e | <ide><path>packages/rn-tester/js/components/RNTOption.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> * @format
<add> * @flow strict-local
<add> */
<add>
<add>'use strict';
<add>
<add>import * as React from 'react';
<add>import {Text, Pressable, StyleSheet, View} from 'react-native';
<add>import type {PressEvent} from 'react-native/Libraries/Types/CoreEventTypes';
<add>import type {ViewStyleProp} from 'react-native/Libraries/StyleSheet/StyleSheet';
<add>
<add>type Props = $ReadOnly<{|
<add> testID?: string,
<add> label: string,
<add> onPress?: ?(event: PressEvent) => mixed,
<add> selected?: boolean,
<add> style?: ViewStyleProp,
<add>|}>;
<add>
<add>/**
<add> * A reusable toggle button component for RNTester. Highlights when selected.
<add> */
<add>export default function RNTOption(props: Props): React.Node {
<add> const [pressed, setPressed] = React.useState(false);
<add>
<add> return (
<add> <Pressable
<add> accessibilityState={{selected: !!props.selected}}
<add> disabled={props.selected}
<add> hitSlop={4}
<add> onPress={props.onPress}
<add> onPressIn={() => setPressed(true)}
<add> onPressOut={() => setPressed(false)}
<add> testID={props.testID}>
<add> <View
<add> style={[
<add> styles.container,
<add> props.selected === true ? styles.selected : null,
<add> pressed && props.selected !== true ? styles.pressed : null,
<add> props.style,
<add> ]}>
<add> <Text style={styles.label}>{props.label}</Text>
<add> </View>
<add> </Pressable>
<add> );
<add>}
<add>
<add>const styles = StyleSheet.create({
<add> pressed: {
<add> backgroundColor: 'rgba(100,215,255,.3)',
<add> },
<add> label: {
<add> color: 'black',
<add> },
<add> selected: {
<add> backgroundColor: 'rgba(100,215,255,.3)',
<add> borderColor: 'rgba(100,215,255,.3)',
<add> },
<add> container: {
<add> borderColor: 'rgba(0,0,0, 0.1)',
<add> borderWidth: 1,
<add> borderRadius: 16,
<add> padding: 6,
<add> paddingHorizontal: 10,
<add> alignItems: 'center',
<add> },
<add>});
<ide><path>packages/rn-tester/js/examples/Modal/ModalCustomizable.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> * @flow strict-local
<del> * @format
<del> */
<del>
<del>import * as React from 'react';
<del>import {
<del> Modal,
<del> Picker,
<del> Platform,
<del> StyleSheet,
<del> Switch,
<del> Text,
<del> TouchableHighlight,
<del> View,
<del> ScrollView,
<del>} from 'react-native';
<del>import type {RNTesterExampleModuleItem} from '../../types/RNTesterTypes';
<del>
<del>const Item = Picker.Item;
<del>
<del>class Button extends React.Component<$FlowFixMeProps, $FlowFixMeState> {
<del> state = {
<del> active: false,
<del> };
<del>
<del> _onHighlight = () => {
<del> this.setState({active: true});
<del> };
<del>
<del> _onUnhighlight = () => {
<del> this.setState({active: false});
<del> };
<del>
<del> render() {
<del> const colorStyle = {
<del> color: this.state.active ? '#fff' : '#000',
<del> };
<del> return (
<del> <TouchableHighlight
<del> onHideUnderlay={this._onUnhighlight}
<del> onPress={this.props.onPress}
<del> onShowUnderlay={this._onHighlight}
<del> style={[styles.button, this.props.style]}
<del> underlayColor="#a9d9d4">
<del> <Text style={[styles.buttonText, colorStyle]}>
<del> {this.props.children}
<del> </Text>
<del> </TouchableHighlight>
<del> );
<del> }
<del>}
<del>
<del>const supportedOrientationsPickerValues = [
<del> ['portrait'],
<del> ['landscape'],
<del> ['landscape-left'],
<del> ['portrait', 'landscape-right'],
<del> ['portrait', 'landscape'],
<del> [],
<del>];
<del>
<del>class ModalExample extends React.Component<{...}, $FlowFixMe> {
<del> state: $FlowFixMe = {
<del> animationType: 'none',
<del> modalVisible: false,
<del> transparent: false,
<del> hardwareAccelerated: false,
<del> statusBarTranslucent: false,
<del> presentationStyle: 'fullScreen',
<del> selectedSupportedOrientation: '0',
<del> currentOrientation: 'unknown',
<del> action: '',
<del> };
<del>
<del> _setModalVisible = visible => {
<del> this.setState({modalVisible: visible});
<del> };
<del>
<del> _setAnimationType = type => {
<del> this.setState({animationType: type});
<del> };
<del>
<del> _toggleTransparent = () => {
<del> this.setState({transparent: !this.state.transparent});
<del> };
<del>
<del> _toggleHardwareAccelerated = () => {
<del> this.setState({hardwareAccelerated: !this.state.hardwareAccelerated});
<del> };
<del>
<del> _toggleStatusBarTranslucent = () => {
<del> this.setState({statusBarTranslucent: !this.state.statusBarTranslucent});
<del> };
<del>
<del> renderSwitch(): React.Node {
<del> if (Platform.isTV) {
<del> return null;
<del> }
<del> if (Platform.OS === 'android') {
<del> return (
<del> <>
<del> <Text style={styles.rowTitle}>Hardware Accelerated</Text>
<del> <Switch
<del> value={this.state.hardwareAccelerated}
<del> onValueChange={this._toggleHardwareAccelerated}
<del> />
<del> <Text style={styles.rowTitle}>Status Bar Translucent</Text>
<del> <Switch
<del> value={this.state.statusBarTranslucent}
<del> onValueChange={this._toggleStatusBarTranslucent}
<del> />
<del> <Text style={styles.rowTitle}>Transparent</Text>
<del> <Switch
<del> value={this.state.transparent}
<del> onValueChange={this._toggleTransparent}
<del> />
<del> </>
<del> );
<del> }
<del> return (
<del> <>
<del> <Text style={styles.rowTitle}>Transparent</Text>
<del> <Switch
<del> value={this.state.transparent}
<del> onValueChange={this._toggleTransparent}
<del> />
<del> </>
<del> );
<del> }
<del>
<del> render(): React.Node {
<del> const modalBackgroundStyle = {
<del> backgroundColor: this.state.transparent
<del> ? 'rgba(0, 0, 0, 0.5)'
<del> : '#f5fcff',
<del> };
<del> const innerContainerTransparentStyle = this.state.transparent
<del> ? {backgroundColor: '#fff', padding: 20}
<del> : null;
<del> const activeButtonStyle = {
<del> backgroundColor: '#ddd',
<del> };
<del>
<del> return (
<del> <ScrollView contentContainerStyle={styles.ScrollView}>
<del> <Modal
<del> animationType={this.state.animationType}
<del> presentationStyle={this.state.presentationStyle}
<del> transparent={this.state.transparent}
<del> hardwareAccelerated={this.state.hardwareAccelerated}
<del> statusBarTranslucent={this.state.statusBarTranslucent}
<del> visible={this.state.modalVisible}
<del> onRequestClose={() => this._setModalVisible(false)}
<del> supportedOrientations={
<del> supportedOrientationsPickerValues[
<del> Number(this.state.selectedSupportedOrientation)
<del> ]
<del> }
<del> onOrientationChange={evt =>
<del> this.setState({currentOrientation: evt.nativeEvent.orientation})
<del> }
<del> onDismiss={() => {
<del> if (this.state.action === 'onDismiss') {
<del> alert(this.state.action);
<del> }
<del> }}
<del> onShow={() => {
<del> if (this.state.action === 'onShow') {
<del> alert(this.state.action);
<del> }
<del> }}>
<del> <View style={[styles.container, modalBackgroundStyle]}>
<del> <View
<del> style={[styles.innerContainer, innerContainerTransparentStyle]}>
<del> <Text>
<del> This modal was presented{' '}
<del> {this.state.animationType === 'none' ? 'without' : 'with'}{' '}
<del> animation.
<del> </Text>
<del> <Text>
<del> It is currently displayed in {this.state.currentOrientation}{' '}
<del> mode.
<del> </Text>
<del> <Button
<del> onPress={this._setModalVisible.bind(this, false)}
<del> style={styles.modalButton}>
<del> Close
<del> </Button>
<del> </View>
<del> </View>
<del> </Modal>
<del> <View style={styles.row}>
<del> <Text style={styles.rowTitle}>Animation Type</Text>
<del> <Button
<del> onPress={this._setAnimationType.bind(this, 'none')}
<del> style={
<del> this.state.animationType === 'none' ? activeButtonStyle : {}
<del> }>
<del> none
<del> </Button>
<del> <Button
<del> onPress={this._setAnimationType.bind(this, 'slide')}
<del> style={
<del> this.state.animationType === 'slide' ? activeButtonStyle : {}
<del> }>
<del> slide
<del> </Button>
<del> <Button
<del> onPress={this._setAnimationType.bind(this, 'fade')}
<del> style={
<del> this.state.animationType === 'fade' ? activeButtonStyle : {}
<del> }>
<del> fade
<del> </Button>
<del> </View>
<del>
<del> <View style={styles.row}>{this.renderSwitch()}</View>
<del> {this.renderPickers()}
<del> <Button onPress={this._setModalVisible.bind(this, true)}>
<del> Present
<del> </Button>
<del> </ScrollView>
<del> );
<del> }
<del> renderPickers(): React.Node {
<del> if (Platform.isTV) {
<del> return null;
<del> }
<del> return (
<del> <View>
<del> <View>
<del> <Text style={styles.rowTitle}>Presentation style</Text>
<del> <Picker
<del> selectedValue={this.state.presentationStyle}
<del> onValueChange={presentationStyle =>
<del> this.setState({presentationStyle})
<del> }
<del> itemStyle={styles.pickerItem}>
<del> <Item label="Full Screen" value="fullScreen" />
<del> <Item label="Page Sheet" value="pageSheet" />
<del> <Item label="Form Sheet" value="formSheet" />
<del> <Item label="Over Full Screen" value="overFullScreen" />
<del> <Item label="Default presentationStyle" value="" />
<del> </Picker>
<del> </View>
<del>
<del> <View>
<del> <Text style={styles.rowTitle}>Supported orientations</Text>
<del> <Picker
<del> selectedValue={this.state.selectedSupportedOrientation}
<del> onValueChange={(_, i) =>
<del> this.setState({selectedSupportedOrientation: i.toString()})
<del> }
<del> itemStyle={styles.pickerItem}>
<del> <Item label="Portrait" value={'0'} />
<del> <Item label="Landscape" value={'1'} />
<del> <Item label="Landscape left" value={'2'} />
<del> <Item label="Portrait and landscape right" value={'3'} />
<del> <Item label="Portrait and landscape" value={'4'} />
<del> <Item label="Default supportedOrientations" value={'5'} />
<del> </Picker>
<del> </View>
<del>
<del> <View>
<del> <Text style={styles.rowTitle}>Actions</Text>
<del> {Platform.OS === 'ios' ? (
<del> <Picker
<del> selectedValue={this.state.action}
<del> onValueChange={action => this.setState({action})}
<del> itemStyle={styles.pickerItem}>
<del> <Item label="None" value="" />
<del> <Item label="On Dismiss" value="onDismiss" />
<del> <Item label="On Show" value="onShow" />
<del> </Picker>
<del> ) : (
<del> <Picker
<del> selectedValue={this.state.action}
<del> onValueChange={action => this.setState({action})}
<del> itemStyle={styles.pickerItem}>
<del> <Item label="None" value="" />
<del> <Item label="On Show" value="onShow" />
<del> </Picker>
<del> )}
<del> </View>
<del> </View>
<del> );
<del> }
<del>}
<del>
<del>const styles = StyleSheet.create({
<del> container: {
<del> flex: 1,
<del> justifyContent: 'center',
<del> padding: 20,
<del> },
<del> innerContainer: {
<del> borderRadius: 10,
<del> alignItems: 'center',
<del> },
<del> row: {
<del> alignItems: 'center',
<del> flex: 1,
<del> flexDirection: 'row',
<del> marginBottom: 20,
<del> },
<del> rowTitle: {
<del> flex: 1,
<del> fontWeight: 'bold',
<del> },
<del> button: {
<del> borderRadius: 5,
<del> flexGrow: 1,
<del> height: 44,
<del> alignSelf: 'stretch',
<del> justifyContent: 'center',
<del> overflow: 'hidden',
<del> },
<del> buttonText: {
<del> fontSize: 18,
<del> margin: 5,
<del> textAlign: 'center',
<del> },
<del> modalButton: {
<del> marginTop: 10,
<del> },
<del> pickerItem: {
<del> fontSize: 16,
<del> },
<del> ScrollView: {
<del> paddingTop: 10,
<del> paddingBottom: 100,
<del> },
<del>});
<del>
<del>export default ({
<del> title: 'Modal Presentation',
<del> name: 'basic',
<del> description: 'Modals can be presented with or without animation',
<del> render: (): React.Node => <ModalExample />,
<del>}: RNTesterExampleModuleItem);
<ide><path>packages/rn-tester/js/examples/Modal/ModalExample.js
<ide> * @format
<ide> */
<ide>
<del>import ModalCustomizable from './ModalCustomizable';
<add>import ModalPresentation from './ModalPresentation';
<ide> import ModalOnShow from './ModalOnShow';
<ide> import type {RNTesterExampleModuleItem} from '../../types/RNTesterTypes';
<ide>
<ide> export const category = 'UI';
<ide> export const documentationURL = 'https://reactnative.dev/docs/modal';
<ide> export const description = 'Component for presenting modal views.';
<ide> export const examples = ([
<del> ModalCustomizable,
<add> ModalPresentation,
<ide> ModalOnShow,
<ide> ]: Array<RNTesterExampleModuleItem>);
<ide><path>packages/rn-tester/js/examples/Modal/ModalPresentation.js
<add>/**
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> *
<add> * @flow strict-local
<add> * @format
<add> */
<add>
<add>import * as React from 'react';
<add>import {Modal, Platform, StyleSheet, Switch, Text, View} from 'react-native';
<add>import type {RNTesterExampleModuleItem} from '../../types/RNTesterTypes';
<add>import RNTOption from '../../components/RNTOption';
<add>const RNTesterButton = require('../../components/RNTesterButton');
<add>
<add>const supportedOrientations = {
<add> Portrait: ['portrait'],
<add> Landscape: ['landscape'],
<add> 'Landscape Left': ['landscape-left'],
<add> 'Portrait and Landscape Right': ['portrait', 'landscape-right'],
<add> 'Portrait and Landscape': ['portrait', 'landscape'],
<add> Default: [],
<add>};
<add>
<add>const animationTypes = ['slide', 'none', 'fade'];
<add>const presentationStyles = [
<add> 'fullScreen',
<add> 'pageSheet',
<add> 'formSheet',
<add> 'overFullScreen',
<add>];
<add>const iOSActions = ['None', 'On Dismiss', 'On Show'];
<add>const noniOSActions = ['None', 'On Show'];
<add>
<add>function ModalPresentation() {
<add> const [animationType, setAnimationType] = React.useState('none');
<add> const [transparent, setTransparent] = React.useState(false);
<add> const [visible, setVisible] = React.useState(false);
<add> const [hardwareAccelerated, setHardwareAccelerated] = React.useState(false);
<add> const [statusBarTranslucent, setStatusBarTranslucent] = React.useState(false);
<add> const [presentationStyle, setPresentationStyle] = React.useState(
<add> 'fullScreen',
<add> );
<add> const [supportedOrientationKey, setSupportedOrientationKey] = React.useState(
<add> 'Portrait',
<add> );
<add> const [currentOrientation, setCurrentOrientation] = React.useState('unknown');
<add> const [action, setAction] = React.useState('None');
<add> const actions = Platform.OS === 'ios' ? iOSActions : noniOSActions;
<add> const onDismiss = () => {
<add> setVisible(false);
<add> if (action === 'onDismiss') {
<add> alert('onDismiss');
<add> }
<add> };
<add>
<add> const onShow = () => {
<add> if (action === 'onShow') {
<add> alert('onShow');
<add> }
<add> };
<add> const onOrientationChange = event =>
<add> setCurrentOrientation(event.nativeEvent.orientation);
<add> const modalBackgroundStyle = {
<add> backgroundColor: transparent ? 'rgba(0, 0, 0, 0.5)' : '#f5fcff',
<add> };
<add> const innerContainerTransparentStyle = transparent
<add> ? {backgroundColor: '#fff', padding: 20}
<add> : null;
<add> return (
<add> <View>
<add> <RNTesterButton onPress={() => setVisible(true)}>
<add> Show Modal
<add> </RNTesterButton>
<add> <Modal
<add> animationType={animationType}
<add> presentationStyle={presentationStyle}
<add> transparent={transparent}
<add> hardwareAccelerated={hardwareAccelerated}
<add> statusBarTranslucent={statusBarTranslucent}
<add> visible={visible}
<add> onRequestClose={onDismiss}
<add> supportedOrientations={supportedOrientations[supportedOrientationKey]}
<add> onOrientationChange={onOrientationChange}
<add> onDismiss={onDismiss}
<add> onShow={onShow}>
<add> <View style={[styles.modalContainer, modalBackgroundStyle]}>
<add> <View
<add> style={[
<add> styles.modalInnerContainer,
<add> innerContainerTransparentStyle,
<add> ]}>
<add> <Text>
<add> This modal was presented with animationType: '{animationType}'
<add> </Text>
<add> {Platform.OS === 'ios' ? (
<add> <Text>
<add> It is currently displayed in {currentOrientation} mode.
<add> </Text>
<add> ) : null}
<add> <RNTesterButton onPress={onDismiss}>Close</RNTesterButton>
<add> </View>
<add> </View>
<add> </Modal>
<add> <View style={styles.block}>
<add> <Text style={styles.title}>Animation Type</Text>
<add> <View style={styles.row}>
<add> {animationTypes.map(type => (
<add> <RNTOption
<add> key={type}
<add> style={styles.option}
<add> label={type}
<add> onPress={() => setAnimationType(type)}
<add> selected={type === animationType}
<add> />
<add> ))}
<add> </View>
<add> </View>
<add> {Platform.OS === 'android' && Platform.isTV !== true ? (
<add> <>
<add> <View style={styles.inlineBlock}>
<add> <Text style={styles.title}>Status Bar Translucent</Text>
<add> <Switch
<add> value={statusBarTranslucent}
<add> onValueChange={() =>
<add> setStatusBarTranslucent(!statusBarTranslucent)
<add> }
<add> />
<add> </View>
<add> <View style={styles.inlineBlock}>
<add> <Text style={styles.title}>Hardware Acceleration</Text>
<add> <Switch
<add> value={hardwareAccelerated}
<add> onValueChange={() => setHardwareAccelerated(!hardwareAccelerated)}
<add> />
<add> </View>
<add> </>
<add> ) : null}
<add> {Platform.isTV !== true ? (
<add> <>
<add> <View>
<add> {Platform.OS === 'ios' && presentationStyle !== 'overFullScreen' ? (
<add> <Text style={styles.warning}>
<add> Modal can only be transparent with overFullScreen
<add> presentationStyle
<add> </Text>
<add> ) : null}
<add> <View style={styles.inlineBlock}>
<add> <Text style={styles.title}>Transparent</Text>
<add> <Switch
<add> value={transparent}
<add> disabled={presentationStyle !== 'overFullScreen'}
<add> onValueChange={() => setTransparent(!transparent)}
<add> />
<add> </View>
<add> </View>
<add> {Platform.OS === 'ios' ? (
<add> <View style={styles.block}>
<add> <Text style={styles.title}>Presentation Style</Text>
<add> <View style={styles.row}>
<add> {presentationStyles.map(type => (
<add> <RNTOption
<add> key={type}
<add> style={styles.option}
<add> label={type}
<add> onPress={() => {
<add> if (type !== 'overFullScreen' && transparent) {
<add> setTransparent(false);
<add> }
<add> setPresentationStyle(type);
<add> }}
<add> selected={type === presentationStyle}
<add> />
<add> ))}
<add> </View>
<add> </View>
<add> ) : null}
<add> <View style={styles.block}>
<add> <Text style={styles.title}>Supported Orientation</Text>
<add> <View style={styles.row}>
<add> {Object.keys(supportedOrientations).map(label => (
<add> <RNTOption
<add> key={label}
<add> style={styles.option}
<add> label={label}
<add> onPress={() => setSupportedOrientationKey(label)}
<add> selected={label === supportedOrientationKey}
<add> />
<add> ))}
<add> </View>
<add> </View>
<add> <View style={styles.block}>
<add> <Text style={styles.title}>Actions</Text>
<add> <View style={styles.row}>
<add> {actions.map(value => (
<add> <RNTOption
<add> key={value}
<add> style={styles.option}
<add> label={value}
<add> onPress={() => setAction(value)}
<add> selected={value === action}
<add> />
<add> ))}
<add> </View>
<add> </View>
<add> </>
<add> ) : null}
<add> </View>
<add> );
<add>}
<add>
<add>const styles = StyleSheet.create({
<add> row: {
<add> flex: 1,
<add> flexWrap: 'wrap',
<add> flexDirection: 'row',
<add> },
<add> block: {
<add> borderColor: 'rgba(0,0,0, 0.1)',
<add> borderBottomWidth: 1,
<add> padding: 6,
<add> },
<add> inlineBlock: {
<add> padding: 6,
<add> flexDirection: 'row',
<add> justifyContent: 'space-between',
<add> alignItems: 'center',
<add> borderColor: 'rgba(0,0,0, 0.1)',
<add> borderBottomWidth: 1,
<add> },
<add> title: {
<add> margin: 3,
<add> fontWeight: 'bold',
<add> },
<add> option: {
<add> marginRight: 8,
<add> marginTop: 6,
<add> },
<add> modalContainer: {
<add> flex: 1,
<add> justifyContent: 'center',
<add> padding: 20,
<add> },
<add> modalInnerContainer: {
<add> borderRadius: 10,
<add> alignItems: 'center',
<add> },
<add> warning: {
<add> fontSize: 12,
<add> color: 'red',
<add> alignSelf: 'center',
<add> },
<add>});
<add>
<add>export default ({
<add> title: 'Modal Presentation',
<add> name: 'basic',
<add> description: 'Modals can be presented with or without animation',
<add> render: (): React.Node => <ModalPresentation />,
<add>}: RNTesterExampleModuleItem); | 4 |
Javascript | Javascript | add flow types for `platform.select` [5/5] | deb2a94568a4b62812cc538960fa1b25e4344dfa | <ide><path>Libraries/Utilities/Platform.android.js
<ide>
<ide> const NativeModules = require('NativeModules');
<ide>
<add>export type PlatformSelectSpec<A, D> = {
<add> android?: A,
<add> default?: D,
<add>};
<add>
<ide> const Platform = {
<ide> OS: 'android',
<ide> get Version() {
<ide> const Platform = {
<ide> const constants = NativeModules.PlatformConstants;
<ide> return constants && constants.uiMode === 'tv';
<ide> },
<del> select: (obj: Object) => ('android' in obj ? obj.android : obj.default),
<add> select: <A, D>(spec: PlatformSelectSpec<A, D>): A | D =>
<add> 'android' in spec ? spec.android : spec.default,
<ide> };
<ide>
<ide> module.exports = Platform;
<ide><path>Libraries/Utilities/Platform.ios.js
<ide>
<ide> const NativeModules = require('NativeModules');
<ide>
<add>export type PlatformSelectSpec<D, I> = {
<add> default?: D,
<add> ios?: I,
<add>};
<add>
<ide> const Platform = {
<ide> OS: 'ios',
<ide> get Version() {
<ide> const Platform = {
<ide> }
<ide> return false;
<ide> },
<del> select: (obj: Object) => ('ios' in obj ? obj.ios : obj.default),
<add> select: <D, I>(spec: PlatformSelectSpec<D, I>): D | I =>
<add> 'ios' in spec ? spec.ios : spec.default,
<ide> };
<ide>
<ide> module.exports = Platform;
<ide><path>Libraries/Utilities/PlatformOS.android.js
<ide> * LICENSE file in the root directory of this source tree.
<ide> *
<ide> * @format
<del> * @flow
<add> * @flow strict
<ide> */
<ide>
<ide> 'use strict'; | 3 |
Python | Python | fix inconsistencies in generate_specials.py | 85485f5c2ba9bc19356c1940ee4304f0c44517c6 | <ide><path>lang_data/en/generate_specials.py
<ide> "are": {"L": "be", "pos": "VBP", "number": 2},
<ide> "ca": {"L": "can", "pos": "MD"},
<ide> "can": {"L": "can", "pos": "MD"},
<del> "could": {"pos": "MD"}, # no lemma for could?
<add> "could": {"pos": "MD", "L": "could"},
<ide> "'d": {"L": "would", "pos": "MD"},
<ide> "did": {"L": "do", "pos": "VBD"},
<del> "do": {"L": "do"}, # no POS for do?
<add> "do": {"L": "do"},
<ide> "does": {"L": "do", "pos": "VBZ"},
<ide> "had": {"L": "have", "pos": "VBD"},
<del> "has": {}, # no POS or lemma for has?
<del> "have": {"pos": "VB"}, # no lemma for have?
<del> "he": {"L": "-PRON-"}, # no POS for he?
<del> "how": {}, # no POS or lemma for how?
<del> "i": {"L": "-PRON-"}, # no POS for i?
<add> "has": {"L": "have", "pos": "VBZ"},
<add> "have": {"pos": "VB"},
<add> "he": {"L": "-PRON-", "pos": "PRP"},
<add> "how": {},
<add> "i": {"L": "-PRON-", "pos": "PRP"},
<ide> "is": {"L": "be", "pos": "VBZ"},
<del> "it": {"L": "-PRON-"}, # no POS for it?
<add> "it": {"L": "-PRON-", "pos": "PRP"},
<ide> "'ll": {"L": "will", "pos": "MD"},
<ide> "'m": {"L": "be", "pos": "VBP", "number": 1, "tenspect": 1},
<del> "'ma": {}, # no POS or lemma for ma?
<del> "might": {}, # no POS or lemma for might?
<del> "must": {}, # no POS or lemma for must?
<del> "need": {}, # no POS or lemma for need?
<add> "'ma": {},
<add> "might": {},
<add> "must": {},
<add> "need": {},
<ide> "not": {"L": "not", "pos": "RB"},
<ide> "'nt": {"L": "not", "pos": "RB"},
<ide> "n't": {"L": "not", "pos": "RB"},
<del> "'re": {}, # no POS or lemma for re?
<add> "'re": {"L": "be", "pos": "VBZ"},
<ide> "'s": {}, # no POS or lemma for s?
<del> "sha": {}, # no POS or lemma for sha?
<del> "she": {"L": "-PRON-"}, # no POS for she?
<del> "should": {}, # no POS or lemma for should?
<del> "that": {}, # no POS or lemma for that?
<del> "there": {}, # no POS or lemma for there?
<del> "they": {"L": "-PRON-"}, # no POS for they?
<del> "was": {}, # no POS or lemma for was?
<del> "we": {}, # no POS or lemma for we?
<del> "were": {}, # no POS or lemma for were?
<del> "what": {}, # no POS or lemma for what?
<del> "when": {}, # no POS or lemma for when?
<del> "where": {}, # no POS or lemma for where?
<del> "who": {}, # no POS or lemma for who?
<del> "why": {}, # no POS or lemma for why?
<del> "wo": {}, # no POS or lemma for wo?
<del> "would": {}, # no POS or lemma for would?
<del> "you": {"L": "-PRON-"}, # no POS or lemma for you?
<add> "sha": {"L": "shall", "pos": "MD"},
<add> "she": {"L": "-PRON-", "pos": "PRP"},
<add> "should": {},
<add> "that": {},
<add> "there": {},
<add> "they": {"L": "-PRON-", "pos": "PRP"},
<add> "was": {},
<add> "we": {"L": "-PRON-", "pos": "PRP"},
<add> "were": {},
<add> "what": {},
<add> "when": {},
<add> "where": {},
<add> "who": {},
<add> "why": {},
<add> "wo": {},
<add> "would": {},
<add> "you": {"L": "-PRON-", "pos": "PRP"},
<ide> "'ve": {"L": "have", "pos": "VB"}
<del>
<ide> }
<ide>
<ide> # contains starting tokens with their potential contractions | 1 |
Go | Go | fix flaky test testrunattachfailednoleak in | 1a9f5f4c69451c580595d67844f41937b3293069 | <ide><path>integration-cli/docker_cli_run_test.go
<ide> func (s *DockerSuite) TestRunAttachFailedNoLeak(c *check.C) {
<ide>
<ide> runSleepingContainer(c, "--name=test", "-p", "8000:8000")
<ide>
<add> // Wait until container is fully up and running
<add> c.Assert(waitRun("test"), check.IsNil)
<add>
<ide> out, _, err := dockerCmdWithError("run", "-p", "8000:8000", "busybox", "true")
<ide> c.Assert(err, checker.NotNil)
<ide> // check for windows error as well | 1 |
Javascript | Javascript | fix macedonian locale | 3467900690dcb0e22cdf51c4ea293c8b3d563158 | <ide><path>src/locale/mk.js
<ide> export default moment.defineLocale('mk', {
<ide> calendar : {
<ide> sameDay : '[Денес во] LT',
<ide> nextDay : '[Утре во] LT',
<del> nextWeek : 'dddd [во] LT',
<add> nextWeek : '[Во] dddd [во] LT',
<ide> lastDay : '[Вчера во] LT',
<ide> lastWeek : function () {
<ide> switch (this.day()) {
<ide> case 0:
<ide> case 3:
<ide> case 6:
<del> return '[Во изминатата] dddd [во] LT';
<add> return '[Изминатата] dddd [во] LT';
<ide> case 1:
<ide> case 2:
<ide> case 4:
<ide> case 5:
<del> return '[Во изминатиот] dddd [во] LT';
<add> return '[Изминатиот] dddd [во] LT';
<ide> }
<ide> },
<ide> sameElse : 'L' | 1 |
Python | Python | fix linting errors in in1d tests | 179d1575ebdf850add391db87da6b1f4d3209e3c | <ide><path>numpy/lib/arraysetops.py
<ide> def in1d(ar1, ar2, assume_unique=False, invert=False, _slow_integer=None):
<ide> ar2_range = ar2_max - ar2_min
<ide>
<ide> # Optimal performance is for approximately
<del> # log10(size) > (log10(range) - 2.27) / 0.927, see discussion on
<add> # log10(size) > (log10(range) - 2.27) / 0.927.
<add> # See discussion on
<ide> # https://github.com/numpy/numpy/pull/12065
<ide> optimal_parameters = (
<ide> np.log10(ar2_size) >
<ide><path>numpy/lib/tests/test_arraysetops.py
<ide> def test_in1d_ravel(self):
<ide> assert_array_equal(in1d(a, b, assume_unique=False), ec)
<ide> assert_array_equal(in1d(a, long_b, assume_unique=True), ec)
<ide> assert_array_equal(in1d(a, long_b, assume_unique=False), ec)
<del> assert_array_equal(in1d(a, b, assume_unique=True, _slow_integer=True), ec)
<del> assert_array_equal(in1d(a, b, assume_unique=False, _slow_integer=True), ec)
<del> assert_array_equal(in1d(a, long_b, assume_unique=True, _slow_integer=True), ec)
<del> assert_array_equal(in1d(a, long_b, assume_unique=False, _slow_integer=True), ec)
<add> assert_array_equal(in1d(a, b, assume_unique=True, _slow_integer=True),
<add> ec)
<add> assert_array_equal(in1d(a, b, assume_unique=False, _slow_integer=True),
<add> ec)
<add> assert_array_equal(in1d(a, long_b, assume_unique=True,
<add> _slow_integer=True),
<add> ec)
<add> assert_array_equal(in1d(a, long_b, assume_unique=False,
<add> _slow_integer=True),
<add> ec)
<ide>
<ide> def test_in1d_hit_alternate_algorithm(self):
<ide> """Hit the standard isin code with integers"""
<ide> def test_in1d_boolean(self):
<ide> a = np.array([True, False])
<ide> b = np.array([False, False, False])
<ide> expected = np.array([False, True])
<del> assert_array_equal(expected, in1d(a, b))
<del> assert_array_equal(expected, in1d(a, b, _slow_integer=True))
<del> assert_array_equal(np.invert(expected), in1d(a, b, invert=True))
<del> assert_array_equal(np.invert(expected), in1d(a, b, invert=True, _slow_integer=True))
<add> assert_array_equal(expected,
<add> in1d(a, b))
<add> assert_array_equal(expected,
<add> in1d(a, b, _slow_integer=True))
<add> assert_array_equal(np.invert(expected),
<add> in1d(a, b, invert=True))
<add> assert_array_equal(np.invert(expected),
<add> in1d(a, b, invert=True, _slow_integer=True))
<ide>
<ide> def test_in1d_first_array_is_object(self):
<ide> ar1 = [None] | 2 |
Python | Python | save config file | 744295636116eac1c0b84e23e9b3cab90886a45d | <ide><path>pytorch_transformers/modeling_utils.py
<ide> def __init__(self, **kwargs):
<ide> self.output_hidden_states = kwargs.pop('output_hidden_states', False)
<ide> self.torchscript = kwargs.pop('torchscript', False)
<ide>
<add> def save_pretrained(self, save_directory):
<add> """ Save a configuration file to a directory, so that it
<add> can be re-loaded using the `from_pretrained(save_directory)` class method.
<add> """
<add> assert os.path.isdir(save_directory), "Saving path should be a directory where the model and configuration can be saved"
<add>
<add> # If we save using the predefined names, we can load using `from_pretrained`
<add> output_config_file = os.path.join(save_directory, CONFIG_NAME)
<add>
<add> self.to_json_file(output_config_file)
<add>
<ide> @classmethod
<ide> def from_pretrained(cls, pretrained_model_name_or_path, *input, **kwargs):
<ide> """
<ide> def save_pretrained(self, save_directory):
<ide> # Only save the model it-self if we are using distributed training
<ide> model_to_save = self.module if hasattr(self, 'module') else self
<ide>
<add> # Save configuration file
<add> model_to_save.config.save_pretrained(save_directory)
<add>
<ide> # If we save using the predefined names, we can load using `from_pretrained`
<ide> output_model_file = os.path.join(save_directory, WEIGHTS_NAME)
<del> output_config_file = os.path.join(save_directory, CONFIG_NAME)
<ide>
<ide> torch.save(model_to_save.state_dict(), output_model_file)
<del> model_to_save.config.to_json_file(output_config_file)
<ide>
<ide> @classmethod
<ide> def from_pretrained(cls, pretrained_model_name_or_path, *inputs, **kwargs): | 1 |
Javascript | Javascript | add missing types on chunk related classes | de41d1fe8bb2c379c4bd558f7ee23977bf7511b5 | <ide><path>lib/Chunk.js
<ide> const SortableSet = require("./util/SortableSet");
<ide> const { compareModulesById } = require("./util/comparators");
<ide>
<ide> /** @typedef {import("webpack-sources").Source} Source */
<add>/** @typedef {import("./ChunkGraph").ChunkFilterPredicate} ChunkFilterPredicate */
<add>/** @typedef {import("./ChunkGraph").ChunkModuleMaps} ChunkModuleMaps */
<add>/** @typedef {import("./ChunkGraph").ChunkSizeOptions} ChunkSizeOptions */
<add>/** @typedef {import("./ChunkGraph").ModuleFilterPredicate} ModuleFilterPredicate */
<ide> /** @typedef {import("./ChunkGroup")} ChunkGroup */
<ide> /** @typedef {import("./Compilation")} Compilation */
<ide> /** @typedef {import("./Module")} Module */
<ide> const { compareModulesById } = require("./util/comparators");
<ide> * @returns {-1|0|1} sort value
<ide> */
<ide>
<del>// TODO use @callback
<del>/** @typedef {(a: Module, b: Module) => -1|0|1} ModuleSortPredicate */
<del>/** @typedef {(c: Chunk) => boolean} ChunkFilterPredicate */
<del>
<ide> let debugId = 1000;
<ide>
<ide> /**
<ide> class Chunk {
<ide> }
<ide> }
<ide>
<add> /**
<add> * @returns {boolean} true, if the chunk contains an entry module
<add> */
<ide> hasEntryModule() {
<ide> return (
<ide> ChunkGraph.getChunkGraphForChunk(
<ide> class Chunk {
<ide> );
<ide> }
<ide>
<add> /**
<add> * @param {Module} module the module
<add> * @returns {boolean} true, if the chunk could be added
<add> */
<ide> addModule(module) {
<ide> return ChunkGraph.getChunkGraphForChunk(
<ide> this,
<ide> "Chunk.addModule"
<ide> ).connectChunkAndModule(this, module);
<ide> }
<ide>
<add> /**
<add> * @param {Module} module the module
<add> * @returns {void}
<add> */
<ide> removeModule(module) {
<del> return ChunkGraph.getChunkGraphForChunk(
<add> ChunkGraph.getChunkGraphForChunk(
<ide> this,
<ide> "Chunk.removeModule"
<ide> ).disconnectChunkAndModule(this, module);
<ide> }
<ide>
<add> /**
<add> * @returns {number} the number of module which are contained in this chunk
<add> */
<ide> getNumberOfModules() {
<ide> return ChunkGraph.getChunkGraphForChunk(
<ide> this,
<ide> class Chunk {
<ide> );
<ide> }
<ide>
<add> /**
<add> * @param {Chunk} otherChunk the chunk to compare with
<add> * @returns {-1|0|1} the comparison result
<add> */
<ide> compareTo(otherChunk) {
<ide> const chunkGraph = ChunkGraph.getChunkGraphForChunk(
<ide> this,
<ide> class Chunk {
<ide> return chunkGraph.compareChunks(this, otherChunk);
<ide> }
<ide>
<add> /**
<add> * @param {Module} module the module
<add> * @returns {boolean} true, if the chunk contains the module
<add> */
<ide> containsModule(module) {
<ide> return ChunkGraph.getChunkGraphForChunk(
<ide> this,
<ide> "Chunk.containsModule"
<ide> ).isModuleInChunk(module, this);
<ide> }
<ide>
<add> /**
<add> * @returns {Module[]} the modules for this chunk
<add> */
<ide> getModules() {
<ide> return ChunkGraph.getChunkGraphForChunk(
<ide> this,
<ide> "Chunk.getModules"
<ide> ).getChunkModules(this);
<ide> }
<ide>
<add> /**
<add> * @returns {void}
<add> */
<ide> remove() {
<ide> const chunkGraph = ChunkGraph.getChunkGraphForChunk(this, "Chunk.remove");
<ide> chunkGraph.disconnectChunk(this);
<ide> this.disconnectFromGroups();
<ide> }
<ide>
<add> /**
<add> * @param {Module} module the module
<add> * @param {Chunk} otherChunk the target chunk
<add> * @returns {void}
<add> */
<ide> moveModule(module, otherChunk) {
<ide> const chunkGraph = ChunkGraph.getChunkGraphForChunk(
<ide> this,
<ide> class Chunk {
<ide> chunkGraph.connectChunkAndModule(otherChunk, module);
<ide> }
<ide>
<add> /**
<add> * @param {Chunk} otherChunk the other chunk
<add> * @returns {boolean} true, if the specified chunk has been integrated
<add> */
<ide> integrate(otherChunk) {
<ide> const chunkGraph = ChunkGraph.getChunkGraphForChunk(
<ide> this,
<ide> "Chunk.integrate"
<ide> );
<del> if (!chunkGraph.canChunksBeIntegrated(this, otherChunk)) return false;
<del> chunkGraph.integrateChunks(this, otherChunk);
<del> return true;
<add> if (chunkGraph.canChunksBeIntegrated(this, otherChunk)) {
<add> chunkGraph.integrateChunks(this, otherChunk);
<add> return true;
<add> } else {
<add> return false;
<add> }
<ide> }
<ide>
<add> /**
<add> * @param {Chunk} otherChunk the other chunk
<add> * @returns {boolean} true, if chunks could be integrated
<add> */
<ide> canBeIntegrated(otherChunk) {
<ide> const chunkGraph = ChunkGraph.getChunkGraphForChunk(
<ide> this,
<ide> class Chunk {
<ide> return chunkGraph.canChunksBeIntegrated(this, otherChunk);
<ide> }
<ide>
<add> /**
<add> * @returns {boolean} true, if this chunk contains no module
<add> */
<ide> isEmpty() {
<ide> const chunkGraph = ChunkGraph.getChunkGraphForChunk(this, "Chunk.isEmpty");
<ide> return chunkGraph.getNumberOfChunkModules(this) === 0;
<ide> }
<ide>
<add> /**
<add> * @returns {number} total size of all modules in this chunk
<add> */
<ide> modulesSize() {
<ide> const chunkGraph = ChunkGraph.getChunkGraphForChunk(
<ide> this,
<ide> class Chunk {
<ide> return chunkGraph.getChunkModulesSize(this);
<ide> }
<ide>
<add> /**
<add> * @param {ChunkSizeOptions} options options object
<add> * @returns {number} total size of this chunk
<add> */
<ide> size(options) {
<ide> const chunkGraph = ChunkGraph.getChunkGraphForChunk(this, "Chunk.size");
<ide> return chunkGraph.getChunkSize(this, options);
<ide> }
<ide>
<add> /**
<add> * @param {Chunk} otherChunk the other chunk
<add> * @param {ChunkSizeOptions} options options object
<add> * @returns {number} total size of the chunk or false if the chunk can't be integrated
<add> */
<ide> integratedSize(otherChunk, options) {
<ide> const chunkGraph = ChunkGraph.getChunkGraphForChunk(
<ide> this,
<ide> class Chunk {
<ide> return chunkGraph.getIntegratedChunksSize(this, otherChunk, options);
<ide> }
<ide>
<add> /**
<add> * @param {ModuleFilterPredicate} filterFn function used to filter modules
<add> * @returns {ChunkModuleMaps} module map information
<add> */
<ide> getChunkModuleMaps(filterFn) {
<ide> const chunkGraph = ChunkGraph.getChunkGraphForChunk(
<ide> this,
<ide> class Chunk {
<ide> return chunkGraph.getChunkModuleMaps(this, filterFn);
<ide> }
<ide>
<add> /**
<add> * @param {ModuleFilterPredicate} filterFn predicate function used to filter modules
<add> * @param {ChunkFilterPredicate=} filterChunkFn predicate function used to filter chunks
<add> * @returns {boolean} return true if module exists in graph
<add> */
<ide> hasModuleInGraph(filterFn, filterChunkFn) {
<ide> const chunkGraph = ChunkGraph.getChunkGraphForChunk(
<ide> this,
<ide><path>lib/ChunkGraph.js
<ide> const {
<ide>
<ide> const compareModuleIterables = compareIterables(compareModulesByIdentifier);
<ide>
<add>/** @typedef {(c: Chunk) => boolean} ChunkFilterPredicate */
<ide> /** @typedef {(m: Module) => boolean} ModuleFilterPredicate */
<ide>
<add>/**
<add> * @typedef {Object} ChunkSizeOptions
<add> * @property {number=} chunkOverhead constant overhead for a chunk
<add> * @property {number=} entryChunkMultiplicator multiplicator for initial chunks
<add> */
<add>
<add>/**
<add> * @typedef {Object} ChunkModuleMaps
<add> * @property {Record<string|number, (string|number)[]>} id
<add> * @property {Record<string|number, string>} hash
<add> */
<add>
<ide> /**
<ide> * @param {Chunk} a chunk
<ide> * @param {Chunk} b chunk
<ide> class ChunkGraph {
<ide> return cgc.modules.getFromUnorderedCache(arrayFunction);
<ide> }
<ide>
<del> /**
<del> * @typedef {Object} ChunkModuleMaps
<del> * @property {Record<string|number, (string|number)[]>} id
<del> * @property {Record<string|number, string>} hash
<del> */
<del>
<ide> /**
<ide> * @param {Chunk} chunk the chunk
<ide> * @param {ModuleFilterPredicate} filterFn function used to filter modules
<ide> class ChunkGraph {
<ide>
<ide> /**
<ide> * @param {Chunk} chunk the chunk
<del> * @param {function(Module): boolean} filterFn predicate function used to filter modules
<del> * @param {(function(Chunk): boolean)=} filterChunkFn predicate function used to filter chunks
<add> * @param {ModuleFilterPredicate} filterFn predicate function used to filter modules
<add> * @param {ChunkFilterPredicate=} filterChunkFn predicate function used to filter chunks
<ide> * @returns {boolean} return true if module exists in graph
<ide> */
<ide> hasModuleInGraph(chunk, filterFn, filterChunkFn) {
<ide> class ChunkGraph {
<ide> /**
<ide> * @param {Chunk} chunkA first chunk
<ide> * @param {Chunk} chunkB second chunk
<del> * @returns {-1|0|1} this is a comparitor function like sort and returns -1, 0, or 1 based on sort order
<add> * @returns {-1|0|1} this is a comparator function like sort and returns -1, 0, or 1 based on sort order
<ide> */
<ide> compareChunks(chunkA, chunkB) {
<ide> const cgcA = this._getChunkGraphChunk(chunkA);
<ide> class ChunkGraph {
<ide> return cgc.modules.getFromUnorderedCache(getModulesSize);
<ide> }
<ide>
<del> /**
<del> * @typedef {Object} ChunkSizeOptions
<del> * @property {number=} chunkOverhead constant overhead for a chunk
<del> * @property {number=} entryChunkMultiplicator multiplicator for initial chunks
<del> */
<del>
<ide> /**
<ide> * @param {Chunk} chunk the chunk
<ide> * @param {ChunkSizeOptions} options options object
<ide><path>lib/ChunkGroup.js
<ide> class ChunkGroup {
<ide>
<ide> /**
<ide> * @param {Chunk} oldChunk chunk to be replaced
<del> * @param {Chunk} newChunk New chunkt that will be replaced
<del> * @returns {boolean} rerturns true for
<add> * @param {Chunk} newChunk new chunk that will be replaced
<add> * @returns {boolean} returns true if the chunk has been replaced
<ide> */
<ide> replaceChunk(oldChunk, newChunk) {
<ide> const oldIdx = this.chunks.indexOf(oldChunk);
<ide> class ChunkGroup {
<ide> }
<ide> }
<ide>
<add> /**
<add> * @param {Chunk} chunk chunk to remove
<add> * @returns {boolean} returns true if chunk was removed
<add> */
<ide> removeChunk(chunk) {
<ide> const idx = this.chunks.indexOf(chunk);
<ide> if (idx >= 0) {
<ide> class ChunkGroup {
<ide> return false;
<ide> }
<ide>
<del> addChild(chunk) {
<del> if (this._children.has(chunk)) {
<add> /**
<add> * @param {ChunkGroup} group chunk ground to add
<add> * @returns {boolean} returns true if chunk ground was added
<add> */
<add> addChild(group) {
<add> if (this._children.has(group)) {
<ide> return false;
<ide> }
<del> this._children.add(chunk);
<add> this._children.add(group);
<ide> return true;
<ide> }
<ide>
<add> /**
<add> * @returns {ChunkGroup[]} returns the children of this group
<add> */
<ide> getChildren() {
<ide> return this._children.getFromCache(getArray);
<ide> }
<ide> class ChunkGroup {
<ide> return this._children;
<ide> }
<ide>
<del> removeChild(chunk) {
<del> if (!this._children.has(chunk)) {
<add> /**
<add> * @param {ChunkGroup} group the chunk group to remove
<add> * @returns {boolean} returns true if the chunk group was removed
<add> */
<add> removeChild(group) {
<add> if (!this._children.has(group)) {
<ide> return false;
<ide> }
<ide>
<del> this._children.delete(chunk);
<del> chunk.removeParent(this);
<add> this._children.delete(group);
<add> group.removeParent(this);
<ide> return true;
<ide> }
<ide>
<add> /**
<add> * @param {ChunkGroup} parentChunk the parent group to be added into
<add> * @returns {boolean} returns true if this chunk group was added to the parent group
<add> */
<ide> addParent(parentChunk) {
<ide> if (!this._parents.has(parentChunk)) {
<ide> this._parents.add(parentChunk);
<ide> class ChunkGroup {
<ide> return false;
<ide> }
<ide>
<add> /**
<add> * @returns {ChunkGroup[]} returns the parents of this group
<add> */
<ide> getParents() {
<ide> return this._parents.getFromCache(getArray);
<ide> }
<ide>
<add> /**
<add> * @param {Iterable<ChunkGroup>} newParents the parent groups to be added into
<add> * @returns {void}
<add> */
<ide> setParents(newParents) {
<ide> this._parents.clear();
<ide> for (const p of newParents) {
<ide> class ChunkGroup {
<ide> return this._parents.size;
<ide> }
<ide>
<add> /**
<add> * @param {ChunkGroup} parent the parent group
<add> * @returns {boolean} returns true if the parent group contains this group
<add> */
<ide> hasParent(parent) {
<ide> return this._parents.has(parent);
<ide> }
<ide> class ChunkGroup {
<ide> return this._parents;
<ide> }
<ide>
<add> /**
<add> * @param {ChunkGroup} chunkGroup the parent group
<add> * @returns {boolean} returns true if this group has been removed from the parent
<add> */
<ide> removeParent(chunkGroup) {
<ide> if (this._parents.delete(chunkGroup)) {
<del> chunkGroup.removeChunk(this);
<add> chunkGroup.removeChild(this);
<ide> return true;
<ide> }
<ide> return false;
<ide> }
<ide>
<ide> /**
<del> * @returns {Array} - an array containing the blocks
<add> * @returns {Array} an array containing the blocks
<ide> */
<ide> getBlocks() {
<ide> return this._blocks.getFromCache(getArray);
<ide> class ChunkGroup {
<ide> });
<ide> }
<ide>
<add> /**
<add> * @returns {string[]} the files contained this chunk group
<add> */
<ide> getFiles() {
<ide> const files = new Set();
<ide>
<ide><path>lib/Compilation.js
<ide> class Compilation {
<ide> for (let indexChunk = 0; indexChunk < chunks.length; indexChunk++) {
<ide> const iteratedChunk = chunks[indexChunk];
<ide> chunkGroup.removeChunk(iteratedChunk);
<del> chunkGroup.removeParent(iteratedChunk);
<ide> // Recurse
<ide> this.removeChunkFromDependencies(block, iteratedChunk);
<ide> }
<ide><path>lib/Entrypoint.js
<ide> class Entrypoint extends ChunkGroup {
<ide>
<ide> /**
<ide> * @param {Chunk} oldChunk chunk to be replaced
<del> * @param {Chunk} newChunk New chunkt that will be replaced
<del> * @returns {boolean} rerturns true for
<add> * @param {Chunk} newChunk new chunk that will be replaced
<add> * @returns {boolean} returns true if the chunk has been replaced
<ide> */
<ide> replaceChunk(oldChunk, newChunk) {
<ide> if (this.runtimeChunk === oldChunk) this.runtimeChunk = newChunk; | 5 |
Ruby | Ruby | add missing require | 05f29e7463e793ec3c77d5b1b1d2264a44887810 | <ide><path>Library/Contributions/cmds/brew-pull.rb
<ide> # Optionally, installs it too.
<ide>
<ide> require 'utils'
<add>require 'formula'
<ide>
<ide> def tap arg
<ide> match = arg.match(%r[homebrew-(\w+)/]) | 1 |
Javascript | Javascript | clarify doc for "args" in $broadcast and $emit | caed2dfe4feeac5d19ecea2dbb1456b7fde21e6d | <ide><path>src/ng/rootScope.js
<ide> function $RootScopeProvider(){
<ide> * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
<ide> *
<ide> * @param {string} name Event name to emit.
<del> * @param {...*} args Optional set of arguments which will be passed onto the event listeners.
<add> * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
<ide> * @return {Object} Event object (see {@link ng.$rootScope.Scope#methods_$on}).
<ide> */
<ide> $emit: function(name, args) {
<ide> function $RootScopeProvider(){
<ide> * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
<ide> *
<ide> * @param {string} name Event name to broadcast.
<del> * @param {...*} args Optional set of arguments which will be passed onto the event listeners.
<add> * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
<ide> * @return {Object} Event object, see {@link ng.$rootScope.Scope#methods_$on}
<ide> */
<ide> $broadcast: function(name, args) { | 1 |
Text | Text | improve function parameter descriptions | ac570899607b9dab4f139e684f5fe4784af1af01 | <ide><path>doc/api/buffer.md
<ide> deprecated: v6.0.0
<ide>
<ide> Stability: 0 - Deprecated: Use [`Buffer.from(array)`] instead.
<ide>
<del>* `array` {Array}
<add>* `array` {Array} An array of bytes to copy from
<ide>
<ide> Allocates a new `Buffer` using an `array` of octets.
<ide>
<ide> deprecated: v6.0.0
<ide>
<ide> Stability: 0 - Deprecated: Use [`Buffer.from(buffer)`] instead.
<ide>
<del>* `buffer` {Buffer}
<add>* `buffer` {Buffer} An existing `Buffer` to copy data from
<ide>
<ide> Copies the passed `buffer` data onto a new `Buffer` instance.
<ide>
<ide> deprecated: v6.0.0
<ide> [`Buffer.from(arrayBuffer[, byteOffset [, length]])`][`Buffer.from(arrayBuffer)`]
<ide> instead.
<ide>
<del>* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or a
<del> `new ArrayBuffer()`
<del>* `byteOffset` {Number} Default: `0`
<del>* `length` {Number} Default: `arrayBuffer.length - byteOffset`
<add>* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a [`TypedArray`] or
<add> [`ArrayBuffer`]
<add>* `byteOffset` {Integer} Where to start copying from `arrayBuffer`. **Default:** `0`
<add>* `length` {Integer} How many bytes to copy from `arrayBuffer`.
<add> **Default:** `arrayBuffer.length - byteOffset`
<ide>
<ide> When passed a reference to the `.buffer` property of a [`TypedArray`] instance,
<ide> the newly created `Buffer` will share the same allocated memory as the
<ide> deprecated: v6.0.0
<ide> Stability: 0 - Deprecated: Use [`Buffer.alloc()`] instead (also see
<ide> [`Buffer.allocUnsafe()`]).
<ide>
<del>* `size` {Number}
<add>* `size` {Integer} The desired length of the new `Buffer`
<ide>
<ide> Allocates a new `Buffer` of `size` bytes. The `size` must be less than or equal
<ide> to the value of [`buffer.kMaxLength`]. Otherwise, a [`RangeError`] is thrown.
<ide> buf.fill(0);
<ide> console.log(buf);
<ide> ```
<ide>
<del>### new Buffer(str[, encoding])
<add>### new Buffer(string[, encoding])
<ide> <!-- YAML
<ide> deprecated: v6.0.0
<ide> -->
<ide>
<ide> Stability: 0 - Deprecated:
<del> Use [`Buffer.from(str[, encoding])`][buffer_from_string] instead.
<add> Use [`Buffer.from(string[, encoding])`][`Buffer.from(string)`] instead.
<ide>
<del>* `str` {String} string to encode.
<del>* `encoding` {String} Default: `'utf8'`
<add>* `string` {String} String to encode
<add>* `encoding` {String} The encoding of `string`. **Default:** `'utf8'`
<ide>
<del>Creates a new Buffer containing the given JavaScript string `str`. If
<del>provided, the `encoding` parameter identifies the strings character encoding.
<add>Creates a new `Buffer` containing the given JavaScript string `string`. If
<add>provided, the `encoding` parameter identifies the character encoding of `string`.
<ide>
<ide> Examples:
<ide>
<ide> console.log(buf2.toString());
<ide> added: v5.10.0
<ide> -->
<ide>
<del>* `size` {Number}
<del>* `fill` {Value} Default: `undefined`
<del>* `encoding` {String} Default: `utf8`
<add>* `size` {Integer} The desired length of the new `Buffer`
<add>* `fill` {String | Buffer | Integer} A value to pre-fill the new `Buffer` with.
<add> **Default:** `0`
<add>* `encoding` {String} If `fill` is a string, this is its encoding.
<add> **Default:** `'utf8'`
<ide>
<ide> Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the
<ide> `Buffer` will be *zero-filled*.
<ide> A `TypeError` will be thrown if `size` is not a number.
<ide> added: v5.10.0
<ide> -->
<ide>
<del>* `size` {Number}
<add>* `size` {Integer} The desired length of the new `Buffer`
<ide>
<ide> Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must
<ide> be less than or equal to the value of [`buffer.kMaxLength`]. Otherwise, a
<ide> additional performance that [`Buffer.allocUnsafe()`] provides.
<ide> added: v5.10.0
<ide> -->
<ide>
<del>* `size` {Number}
<add>* `size` {Integer} The desired length of the new `Buffer`
<ide>
<ide> Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The
<ide> `size` must be less than or equal to the value of [`buffer.kMaxLength`].
<ide> A `TypeError` will be thrown if `size` is not a number.
<ide>
<ide> ### Class Method: Buffer.byteLength(string[, encoding])
<ide>
<del>* `string` {String | Buffer | TypedArray | DataView | ArrayBuffer}
<del>* `encoding` {String} Default: `'utf8'`
<del>* Return: {Number}
<add>* `string` {String | Buffer | TypedArray | DataView | ArrayBuffer} A value to
<add> calculate the length of
<add>* `encoding` {String} If `string` is a string, this is its encoding.
<add> **Default:** `'utf8'`
<add>* Return: {Integer} The number of bytes contained within `string`
<ide>
<ide> Returns the actual byte length of a string. This is not the same as
<ide> [`String.prototype.length`] since that returns the number of *characters* in
<ide> added: v0.11.13
<ide>
<ide> * `buf1` {Buffer}
<ide> * `buf2` {Buffer}
<del>* Return: {Number}
<add>* Return: {Integer}
<ide>
<ide> Compares `buf1` to `buf2` typically for the purpose of sorting arrays of
<ide> `Buffer` instances. This is equivalent to calling
<ide> console.log(arr.sort(Buffer.compare));
<ide> added: v0.7.11
<ide> -->
<ide>
<del>* `list` {Array} List of Buffer objects to concat
<del>* `totalLength` {Number} Total length of the Buffers in the list
<add>* `list` {Array} List of `Buffer` instances to concat
<add>* `totalLength` {Integer} Total length of the `Buffer` instances in `list`
<ide> when concatenated
<ide> * Return: {Buffer}
<ide>
<ide> A `TypeError` will be thrown if `array` is not an `Array`.
<ide> added: v5.10.0
<ide> -->
<ide>
<del>* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or
<del> a `new ArrayBuffer()`
<del>* `byteOffset` {Number} Default: `0`
<del>* `length` {Number} Default: `arrayBuffer.length - byteOffset`
<add>* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a [`TypedArray`] or
<add> [`ArrayBuffer`]
<add>* `byteOffset` {Integer} Where to start copying from `arrayBuffer`. **Default:** `0`
<add>* `length` {Integer} How many bytes to copy from `arrayBuffer`.
<add> **Default:** `arrayBuffer.length - byteOffset`
<ide>
<ide> When passed a reference to the `.buffer` property of a [`TypedArray`] instance,
<ide> the newly created `Buffer` will share the same allocated memory as the
<ide> A `TypeError` will be thrown if `arrayBuffer` is not an [`ArrayBuffer`].
<ide> added: v3.0.0
<ide> -->
<ide>
<del>* `buffer` {Buffer}
<add>* `buffer` {Buffer} An existing `Buffer` to copy data from
<ide>
<ide> Copies the passed `buffer` data onto a new `Buffer` instance.
<ide>
<ide> console.log(buf2.toString());
<ide>
<ide> A `TypeError` will be thrown if `buffer` is not a `Buffer`.
<ide>
<del>### Class Method: Buffer.from(str[, encoding])
<add>### Class Method: Buffer.from(string[, encoding])
<ide> <!-- YAML
<ide> added: v5.10.0
<ide> -->
<ide>
<del>* `str` {String} String to encode.
<del>* `encoding` {String} Encoding to use, Default: `'utf8'`
<add>* `string` {String} A string to encode.
<add>* `encoding` {String} The encoding of `string`. **Default:** `'utf8'`
<ide>
<del>Creates a new `Buffer` containing the given JavaScript string `str`. If
<del>provided, the `encoding` parameter identifies the character encoding.
<del>If not provided, `encoding` defaults to `'utf8'`.
<add>Creates a new `Buffer` containing the given JavaScript string `string`. If
<add>provided, the `encoding` parameter identifies the character encoding of `string`.
<ide>
<ide> Examples:
<ide>
<ide> Returns `true` if `obj` is a `Buffer`, `false` otherwise.
<ide> added: v0.9.1
<ide> -->
<ide>
<del>* `encoding` {String} The encoding string to test
<add>* `encoding` {String} A character encoding name to check
<ide> * Return: {Boolean}
<ide>
<ide> Returns `true` if `encoding` contains a supported character encoding, or `false`
<ide> otherwise.
<ide> added: v0.11.3
<ide> -->
<ide>
<del>* {Number} **Default:** `8192`
<add>* {Integer} **Default:** `8192`
<ide>
<ide> This is the number of bytes used to determine the size of pre-allocated, internal
<ide> `Buffer` instances used for pooling. This value may be modified.
<ide> console.log(buf.toString('ascii'));
<ide> added: v0.11.13
<ide> -->
<ide>
<del>* `target` {Buffer}
<add>* `target` {Buffer} A `Buffer` to compare to
<ide> * `targetStart` {Integer} The offset within `target` at which to begin
<del> comparison. default = `0`.
<del>* `targetEnd` {Integer} The offset with `target` at which to end comparison.
<del> Ignored when `targetStart` is `undefined`. default = `target.byteLength`.
<add> comparison. **Default:** `0`
<add>* `targetEnd` {Integer} The offset with `target` at which to end comparison
<add> (not inclusive). Ignored when `targetStart` is `undefined`.
<add> **Default:** `target.length`
<ide> * `sourceStart` {Integer} The offset within `buf` at which to begin comparison.
<del> Ignored when `targetStart` is `undefined`. default = `0`
<del>* `sourceEnd` {Integer} The offset within `buf` at which to end comparison.
<del> Ignored when `targetStart` is `undefined`. default = `buf.byteLength`.
<del>* Return: {Number}
<add> Ignored when `targetStart` is `undefined`. **Default:** `0`
<add>* `sourceEnd` {Integer} The offset within `buf` at which to end comparison
<add> (not inclusive). Ignored when `targetStart` is `undefined`.
<add> **Default:** [`buf.length`]
<add>* Return: {Integer}
<ide>
<ide> Compares `buf` with `target` and returns a number indicating whether `buf`
<ide> comes before, after, or is the same as `target` in sort order.
<ide> console.log(buf1.compare(buf2, 5, 6, 5));
<ide> A `RangeError` will be thrown if: `targetStart < 0`, `sourceStart < 0`,
<ide> `targetEnd > target.byteLength` or `sourceEnd > source.byteLength`.
<ide>
<del>### buf.copy(targetBuffer[, targetStart[, sourceStart[, sourceEnd]]])
<add>### buf.copy(target[, targetStart[, sourceStart[, sourceEnd]]])
<ide>
<del>* `targetBuffer` {Buffer} Buffer to copy into
<del>* `targetStart` {Number} Default: 0
<del>* `sourceStart` {Number} Default: 0
<del>* `sourceEnd` {Number} Default: `buffer.length`
<del>* Return: {Number} The number of bytes copied.
<add>* `target` {Buffer} A `Buffer` to copy into.
<add>* `targetStart` {Integer} The offset within `target` at which to begin
<add> copying to. **Default:** `0`
<add>* `sourceStart` {Integer} The offset within `buf` at which to begin copying from.
<add> Ignored when `targetStart` is `undefined`. **Default:** `0`
<add>* `sourceEnd` {Integer} The offset within `buf` at which to stop copying (not
<add> inclusive). Ignored when `sourceStart` is `undefined`. **Default:** [`buf.length`]
<add>* Return: {Integer} The number of bytes copied.
<ide>
<ide> Copies data from a region of `buf` to a region in `target` even if the `target`
<ide> memory region overlaps with `buf`.
<ide> for (var pair of buf.entries()) {
<ide> added: v1.0.0
<ide> -->
<ide>
<del>* `otherBuffer` {Buffer}
<add>* `otherBuffer` {Buffer} A `Buffer` to compare to
<ide> * Return: {Boolean}
<ide>
<ide> Returns `true` if both `buf` and `otherBuffer` have exactly the same bytes,
<ide> console.log(buf1.equals(buf3));
<ide> added: v0.5.0
<ide> -->
<ide>
<del>* `value` {String|Buffer|Number}
<del>* `offset` {Number} Default: 0
<del>* `end` {Number} Default: `buf.length`
<del>* `encoding` {String} Default: `'utf8'`
<del>* Return: {Buffer}
<add>* `value` {String | Buffer | Integer} The value to fill `buf` with
<add>* `offset` {Integer} Where to start filling `buf`. **Default:** `0`
<add>* `end` {Integer} Where to stop filling `buf` (not inclusive). **Default:** [`buf.length`]
<add>* `encoding` {String} If `value` is a string, this is its encoding.
<add> **Default:** `'utf8'`
<add>* Return: {Buffer} A reference to `buf`
<ide>
<ide> Fills `buf` with the specified `value`. If the `offset` and `end` are not given,
<ide> the entire `buf` will be filled. This is meant to be a small simplification to
<ide> const b = Buffer.allocUnsafe(50).fill('h');
<ide> console.log(b.toString());
<ide> ```
<ide>
<del>`encoding` is only relevant if `value` is a string. Otherwise it is ignored.
<del>`value` is coerced to a `uint32` value if it is not a String or Number.
<add>`value` is coerced to a `uint32` value if it is not a String or Integer.
<ide>
<ide> If the final write of a `fill()` operation falls on a multi-byte character,
<ide> then only the first bytes of that character that fit into `buf` are written.
<ide> console.log(Buffer.allocUnsafe(3).fill('\u0222'));
<ide> added: v1.5.0
<ide> -->
<ide>
<del>* `value` {String|Buffer|Number}
<del>* `byteOffset` {Number} Default: 0
<del>* `encoding` {String} Default: `'utf8'`
<del>* Return: {Number}
<add>* `value` {String | Buffer | Integer} What to search for
<add>* `byteOffset` {Integer} Where to begin searching in `buf`. **Default:** `0`
<add>* `encoding` {String} If `value` is a string, this is its encoding.
<add> **Default:** `'utf8'`
<add>* Return: {Integer} The index of the first occurrence of `value` in `buf` or `-1`
<add> if `buf` does not contain `value`
<ide>
<ide> If `value` is:
<ide>
<ide> console.log(utf16Buffer.indexOf('\u03a3', -4, 'ucs2'));
<ide> added: v5.3.0
<ide> -->
<ide>
<del>* `value` {String|Buffer|Number}
<del>* `byteOffset` {Number} Default: 0
<del>* `encoding` {String} Default: `'utf8'`
<del>* Return: {Boolean}
<add>* `value` {String | Buffer | Integer} What to search for
<add>* `byteOffset` {Integer} Where to begin searching in `buf`. **Default:** `0`
<add>* `encoding` {String} If `value` is a string, this is its encoding.
<add> **Default:** `'utf8'`
<add>* Return: {Boolean} `true` if `value` was found in `buf`, `false` otherwise
<ide>
<ide> Equivalent to [`buf.indexOf() !== -1`][`buf.indexOf()`].
<ide>
<ide> for (var key of buf.keys()) {
<ide> added: v6.0.0
<ide> -->
<ide>
<del>* `value` {String|Buffer|Number}
<del>* `byteOffset` {Number} Default: `buf.length`
<del>* `encoding` {String} Default: `'utf8'`
<del>* Return: {Number}
<add>* `value` {String | Buffer | Integer} What to search for
<add>* `byteOffset` {Integer} Where to begin searching in `buf` (not inclusive).
<add> **Default:** [`buf.length`]
<add>* `encoding` {String} If `value` is a string, this is its encoding.
<add> **Default:** `'utf8'`
<add>* Return: {Integer} The index of the last occurrence of `value` in `buf` or `-1`
<add> if `buf` does not contain `value`
<ide>
<ide> Identical to [`buf.indexOf()`], except `buf` is searched from back to front
<ide> instead of front to back.
<ide> console.log(utf16Buffer.lastIndexOf('\u03a3', -5, 'ucs2'));
<ide>
<ide> ### buf.length
<ide>
<del>* {Number}
<add>* {Integer}
<ide>
<ide> Returns the amount of memory allocated for `buf` in bytes. Note that this
<ide> does not necessarily reflect the amount of "usable" data within `buf`.
<ide> console.log(buf.length);
<ide> ### buf.readDoubleBE(offset[, noAssert])
<ide> ### buf.readDoubleLE(offset[, noAssert])
<ide>
<del>* `offset` {Number} `0 <= offset <= buf.length - 8`
<del>* `noAssert` {Boolean} Default: false
<add>* `offset` {Integer} Where to start reading. Must satisfy: `0 <= offset <= buf.length - 8`
<add>* `noAssert` {Boolean} Skip `offset` validation? **Default:** `false`
<ide> * Return: {Number}
<ide>
<ide> Reads a 64-bit double from `buf` at the specified `offset` with specified
<ide> console.log(buf.readDoubleLE(1, true));
<ide> ### buf.readFloatBE(offset[, noAssert])
<ide> ### buf.readFloatLE(offset[, noAssert])
<ide>
<del>* `offset` {Number} `0 <= offset <= buf.length - 4`
<del>* `noAssert` {Boolean} Default: false
<add>* `offset` {Integer} Where to start reading. Must satisfy: `0 <= offset <= buf.length - 4`
<add>* `noAssert` {Boolean} Skip `offset` validation? **Default:** `false`
<ide> * Return: {Number}
<ide>
<ide> Reads a 32-bit float from `buf` at the specified `offset` with specified
<ide> console.log(buf.readFloatLE(1, true));
<ide>
<ide> ### buf.readInt8(offset[, noAssert])
<ide>
<del>* `offset` {Number} `0 <= offset <= buf.length - 1`
<del>* `noAssert` {Boolean} Default: false
<del>* Return: {Number}
<add>* `offset` {Integer} Where to start reading. Must satisfy: `0 <= offset <= buf.length - 1`
<add>* `noAssert` {Boolean} Skip `offset` validation? **Default:** `false`
<add>* Return: {Integer}
<ide>
<ide> Reads a signed 8-bit integer from `buf` at the specified `offset`.
<ide>
<ide> console.log(buf.readInt8(2));
<ide> ### buf.readInt16BE(offset[, noAssert])
<ide> ### buf.readInt16LE(offset[, noAssert])
<ide>
<del>* `offset` {Number} `0 <= offset <= buf.length - 2`
<del>* `noAssert` {Boolean} Default: false
<del>* Return: {Number}
<add>* `offset` {Integer} Where to start reading. Must satisfy: `0 <= offset <= buf.length - 2`
<add>* `noAssert` {Boolean} Skip `offset` validation? **Default:** `false`
<add>* Return: {Integer}
<ide>
<ide> Reads a signed 16-bit integer from `buf` at the specified `offset` with
<ide> the specified endian format (`readInt16BE()` returns big endian,
<ide> console.log(buf.readInt16LE(1));
<ide> ### buf.readInt32BE(offset[, noAssert])
<ide> ### buf.readInt32LE(offset[, noAssert])
<ide>
<del>* `offset` {Number} `0 <= offset <= buf.length - 4`
<del>* `noAssert` {Boolean} Default: false
<del>* Return: {Number}
<add>* `offset` {Integer} Where to start reading. Must satisfy: `0 <= offset <= buf.length - 4`
<add>* `noAssert` {Boolean} Skip `offset` validation? **Default:** `false`
<add>* Return: {Integer}
<ide>
<ide> Reads a signed 32-bit integer from `buf` at the specified `offset` with
<ide> the specified endian format (`readInt32BE()` returns big endian,
<ide> console.log(buf.readInt32LE(1));
<ide> added: v1.0.0
<ide> -->
<ide>
<del>* `offset` {Number} `0 <= offset <= buf.length - byteLength`
<del>* `byteLength` {Number} `0 < byteLength <= 6`
<del>* `noAssert` {Boolean} Default: false
<del>* Return: {Number}
<add>* `offset` {Integer} Where to start reading. Must satisfy: `0 <= offset <= buf.length - byteLength`
<add>* `byteLength` {Integer} How many bytes to read. Must satisfy: `0 < byteLength <= 6`
<add>* `noAssert` {Boolean} Skip `offset` and `byteLength` validation? **Default:** `false`
<add>* Return: {Integer}
<ide>
<ide> Reads `byteLength` number of bytes from `buf` at the specified `offset`
<ide> and interprets the result as a two's complement signed value. Supports up to 48
<ide> console.log(buf.readIntBE(1, 6).toString(16));
<ide>
<ide> ### buf.readUInt8(offset[, noAssert])
<ide>
<del>* `offset` {Number} `0 <= offset <= buf.length - 1`
<del>* `noAssert` {Boolean} Default: false
<del>* Return: {Number}
<add>* `offset` {Integer} Where to start reading. Must satisfy: `0 <= offset <= buf.length - 1`
<add>* `noAssert` {Boolean} Skip `offset` validation? **Default:** `false`
<add>* Return: {Integer}
<ide>
<ide> Reads an unsigned 8-bit integer from `buf` at the specified `offset`.
<ide>
<ide> console.log(buf.readUInt8(2));
<ide> ### buf.readUInt16BE(offset[, noAssert])
<ide> ### buf.readUInt16LE(offset[, noAssert])
<ide>
<del>* `offset` {Number} `0 <= offset <= buf.length - 2`
<del>* `noAssert` {Boolean} Default: false
<del>* Return: {Number}
<add>* `offset` {Integer} Where to start reading. Must satisfy: `0 <= offset <= buf.length - 2`
<add>* `noAssert` {Boolean} Skip `offset` validation? **Default:** `false`
<add>* Return: {Integer}
<ide>
<ide> Reads an unsigned 16-bit integer from `buf` at the specified `offset` with
<ide> specified endian format (`readUInt16BE()` returns big endian, `readUInt16LE()`
<ide> console.log(buf.readUInt16LE(2).toString(16));
<ide> ### buf.readUInt32BE(offset[, noAssert])
<ide> ### buf.readUInt32LE(offset[, noAssert])
<ide>
<del>* `offset` {Number} `0 <= offset <= buf.length - 4`
<del>* `noAssert` {Boolean} Default: false
<del>* Return: {Number}
<add>* `offset` {Integer} Where to start reading. Must satisfy: `0 <= offset <= buf.length - 4`
<add>* `noAssert` {Boolean} Skip `offset` validation? **Default:** `false`
<add>* Return: {Integer}
<ide>
<ide> Reads an unsigned 32-bit integer from `buf` at the specified `offset` with
<ide> specified endian format (`readUInt32BE()` returns big endian,
<ide> console.log(buf.readUInt32LE(1).toString(16));
<ide> added: v1.0.0
<ide> -->
<ide>
<del>* `offset` {Number} `0 <= offset <= buf.length - byteLength`
<del>* `byteLength` {Number} `0 < byteLength <= 6`
<del>* `noAssert` {Boolean} Default: false
<del>* Return: {Number}
<add>* `offset` {Integer} Where to start reading. Must satisfy: `0 <= offset <= buf.length - byteLength`
<add>* `byteLength` {Integer} How many bytes to read. Must satisfy: `0 < byteLength <= 6`
<add>* `noAssert` {Boolean} Skip `offset` and `byteLength` validation? **Default:** `false`
<add>* Return: {Integer}
<ide>
<ide> Reads `byteLength` number of bytes from `buf` at the specified `offset`
<ide> and interprets the result as an unsigned integer. Supports up to 48
<ide> console.log(buf.readUIntBE(1, 6).toString(16));
<ide>
<ide> ### buf.slice([start[, end]])
<ide>
<del>* `start` {Number} Default: 0
<del>* `end` {Number} Default: `buffer.length`
<add>* `start` {Integer} Where the new `Buffer` will start. **Default:** `0`
<add>* `end` {Integer} Where the new `Buffer` will end (not inclusive).
<add> **Default:** [`buf.length`]
<ide> * Return: {Buffer}
<ide>
<ide> Returns a new `Buffer` that references the same memory as the original, but
<ide> console.log(buf.slice(-5, -2).toString());
<ide> added: v5.10.0
<ide> -->
<ide>
<del>* Return: {Buffer}
<add>* Return: {Buffer} A reference to `buf`
<ide>
<ide> Interprets `buf` as an array of unsigned 16-bit integers and swaps the byte-order
<ide> *in-place*. Throws a `RangeError` if [`buf.length`] is not a multiple of 2.
<ide> buf2.swap32();
<ide> added: v5.10.0
<ide> -->
<ide>
<del>* Return: {Buffer}
<add>* Return: {Buffer} A reference to `buf`
<ide>
<ide> Interprets `buf` as an array of unsigned 32-bit integers and swaps the byte-order
<ide> *in-place*. Throws a `RangeError` if [`buf.length`] is not a multiple of 4.
<ide> buf2.swap32();
<ide> added: v6.3.0
<ide> -->
<ide>
<del>* Return: {Buffer}
<add>* Return: {Buffer} A reference to `buf`
<ide>
<ide> Interprets `buf` as an array of 64-bit numbers and swaps the byte-order *in-place*.
<ide> Throws a `RangeError` if [`buf.length`] is not a multiple of 8.
<ide> for working with 64-bit floats.
<ide>
<ide> ### buf.toString([encoding[, start[, end]]])
<ide>
<del>* `encoding` {String} Default: `'utf8'`
<del>* `start` {Number} Default: 0
<del>* `end` {Number} Default: `buffer.length`
<add>* `encoding` {String} The character encoding to decode to. **Default:** `'utf8'`
<add>* `start` {Integer} Where to start decoding. **Default:** `0`
<add>* `end` {Integer} Where to stop decoding (not inclusive). **Default:** [`buf.length`]
<ide> * Return: {String}
<ide>
<ide> Decodes `buf` to a string according to the specified character encoding in `encoding`.
<ide> for (var value of buf) {
<ide>
<ide> ### buf.write(string[, offset[, length]][, encoding])
<ide>
<del>* `string` {String} Bytes to be written to buffer
<del>* `offset` {Number} Default: 0
<del>* `length` {Number} Default: `buffer.length - offset`
<del>* `encoding` {String} Default: `'utf8'`
<del>* Return: {Number} Numbers of bytes written
<add>* `string` {String} String to be written to `buf`
<add>* `offset` {Integer} Where to start writing `string`. **Default:** `0`
<add>* `length` {Integer} How many bytes to write. **Default:** `buf.length - offset`
<add>* `encoding` {String} The character encoding of `string`. **Default:** `'utf8'`
<add>* Return: {Integer} Number of bytes written
<ide>
<ide> Writes `string` to `buf` at `offset` according to the character encoding in `encoding`.
<ide> The `length` parameter is the number of bytes to write. If `buf` did not contain
<ide> console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`);
<ide> ### buf.writeDoubleBE(value, offset[, noAssert])
<ide> ### buf.writeDoubleLE(value, offset[, noAssert])
<ide>
<del>* `value` {Number} Bytes to be written to Buffer
<del>* `offset` {Number} `0 <= offset <= buf.length - 8`
<del>* `noAssert` {Boolean} Default: false
<del>* Return: {Number} The offset plus the number of written bytes
<add>* `value` {Number} Number to be written to `buf`
<add>* `offset` {Integer} Where to start writing. Must satisfy: `0 <= offset <= buf.length - 8`
<add>* `noAssert` {Boolean} Skip `value` and `offset` validation? **Default:** `false`
<add>* Return: {Integer} `offset` plus the number of bytes written
<ide>
<ide> Writes `value` to `buf` at the specified `offset` with specified endian
<ide> format (`writeDoubleBE()` writes big endian, `writeDoubleLE()` writes little
<ide> console.log(buf);
<ide> ### buf.writeFloatBE(value, offset[, noAssert])
<ide> ### buf.writeFloatLE(value, offset[, noAssert])
<ide>
<del>* `value` {Number} Bytes to be written to Buffer
<del>* `offset` {Number} `0 <= offset <= buf.length - 4`
<del>* `noAssert` {Boolean} Default: false
<del>* Return: {Number} The offset plus the number of written bytes
<add>* `value` {Number} Number to be written to `buf`
<add>* `offset` {Integer} Where to start writing. Must satisfy: `0 <= offset <= buf.length - 4`
<add>* `noAssert` {Boolean} Skip `value` and `offset` validation? **Default:** `false`
<add>* Return: {Integer} `offset` plus the number of bytes written
<ide>
<ide> Writes `value` to `buf` at the specified `offset` with specified endian
<ide> format (`writeFloatBE()` writes big endian, `writeFloatLE()` writes little
<ide> console.log(buf);
<ide>
<ide> ### buf.writeInt8(value, offset[, noAssert])
<ide>
<del>* `value` {Number} Bytes to be written to Buffer
<del>* `offset` {Number} `0 <= offset <= buf.length - 1`
<del>* `noAssert` {Boolean} Default: false
<del>* Return: {Number} The offset plus the number of written bytes
<add>* `value` {Integer} Number to be written to `buf`
<add>* `offset` {Integer} Where to start writing. Must satisfy: `0 <= offset <= buf.length - 1`
<add>* `noAssert` {Boolean} Skip `value` and `offset` validation? **Default:** `false`
<add>* Return: {Integer} `offset` plus the number of bytes written
<ide>
<ide> Writes `value` to `buf` at the specified `offset`. `value` *should* be a valid
<ide> signed 8-bit integer. Behavior is undefined when `value` is anything other than
<ide> console.log(buf);
<ide> ### buf.writeInt16BE(value, offset[, noAssert])
<ide> ### buf.writeInt16LE(value, offset[, noAssert])
<ide>
<del>* `value` {Number} Bytes to be written to Buffer
<del>* `offset` {Number} `0 <= offset <= buf.length - 2`
<del>* `noAssert` {Boolean} Default: false
<del>* Return: {Number} The offset plus the number of written bytes
<add>* `value` {Integer} Number to be written to `buf`
<add>* `offset` {Integer} Where to start writing. Must satisfy: `0 <= offset <= buf.length - 2`
<add>* `noAssert` {Boolean} Skip `value` and `offset` validation? **Default:** `false`
<add>* Return: {Integer} `offset` plus the number of bytes written
<ide>
<ide> Writes `value` to `buf` at the specified `offset` with specified endian
<ide> format (`writeInt16BE()` writes big endian, `writeInt16LE()` writes little
<ide> console.log(buf);
<ide> ### buf.writeInt32BE(value, offset[, noAssert])
<ide> ### buf.writeInt32LE(value, offset[, noAssert])
<ide>
<del>* `value` {Number} Bytes to be written to Buffer
<del>* `offset` {Number} `0 <= offset <= buf.length - 4`
<del>* `noAssert` {Boolean} Default: false
<del>* Return: {Number} The offset plus the number of written bytes
<add>* `value` {Integer} Number to be written to `buf`
<add>* `offset` {Integer} Where to start writing. Must satisfy: `0 <= offset <= buf.length - 4`
<add>* `noAssert` {Boolean} Skip `value` and `offset` validation? **Default:** `false`
<add>* Return: {Integer} `offset` plus the number of bytes written
<ide>
<ide> Writes `value` to `buf` at the specified `offset` with specified endian
<ide> format (`writeInt32BE()` writes big endian, `writeInt32LE()` writes little
<ide> console.log(buf);
<ide> added: v1.0.0
<ide> -->
<ide>
<del>* `value` {Number} Bytes to be written to Buffer
<del>* `offset` {Number} `0 <= offset <= buf.length - byteLength`
<del>* `byteLength` {Number} `0 < byteLength <= 6`
<del>* `noAssert` {Boolean} Default: false
<del>* Return: {Number} The offset plus the number of written bytes
<add>* `value` {Integer} Number to be written to `buf`
<add>* `offset` {Integer} Where to start writing. Must satisfy: `0 <= offset <= buf.length - byteLength`
<add>* `byteLength` {Integer} How many bytes to write. Must satisfy: `0 < byteLength <= 6`
<add>* `noAssert` {Boolean} Skip `value`, `offset`, and `byteLength` validation?
<add> **Default:** `false`
<add>* Return: {Integer} `offset` plus the number of bytes written
<ide>
<ide> Writes `byteLength` bytes of `value` to `buf` at the specified `offset`.
<ide> Supports up to 48 bits of accuracy. Behavior is undefined when `value` is
<ide> console.log(buf);
<ide>
<ide> ### buf.writeUInt8(value, offset[, noAssert])
<ide>
<del>* `value` {Number} Bytes to be written to Buffer
<del>* `offset` {Number} `0 <= offset <= buf.length - 1`
<del>* `noAssert` {Boolean} Default: false
<del>* Return: {Number} The offset plus the number of written bytes
<add>* `value` {Integer} Number to be written to `buf`
<add>* `offset` {Integer} Where to start writing. Must satisfy: `0 <= offset <= buf.length - 1`
<add>* `noAssert` {Boolean} Skip `value` and `offset` validation? **Default:** `false`
<add>* Return: {Integer} `offset` plus the number of bytes written
<ide>
<ide> Writes `value` to `buf` at the specified `offset`. `value` *should* be a
<ide> valid unsigned 8-bit integer. Behavior is undefined when `value` is anything
<ide> console.log(buf);
<ide> ### buf.writeUInt16BE(value, offset[, noAssert])
<ide> ### buf.writeUInt16LE(value, offset[, noAssert])
<ide>
<del>* `value` {Number} Bytes to be written to Buffer
<del>* `offset` {Number} `0 <= offset <= buf.length - 2`
<del>* `noAssert` {Boolean} Default: false
<del>* Return: {Number} The offset plus the number of written bytes
<add>* `value` {Integer} Number to be written to `buf`
<add>* `offset` {Integer} Where to start writing. Must satisfy: `0 <= offset <= buf.length - 2`
<add>* `noAssert` {Boolean} Skip `value` and `offset` validation? **Default:** `false`
<add>* Return: {Integer} `offset` plus the number of bytes written
<ide>
<ide> Writes `value` to `buf` at the specified `offset` with specified endian
<ide> format (`writeUInt16BE()` writes big endian, `writeUInt16LE()` writes little
<ide> console.log(buf);
<ide> ### buf.writeUInt32BE(value, offset[, noAssert])
<ide> ### buf.writeUInt32LE(value, offset[, noAssert])
<ide>
<del>* `value` {Number} Bytes to be written to Buffer
<del>* `offset` {Number} `0 <= offset <= buf.length - 4`
<del>* `noAssert` {Boolean} Default: false
<del>* Return: {Number} The offset plus the number of written bytes
<add>* `value` {Integer} Number to be written to `buf`
<add>* `offset` {Integer} Where to start writing. Must satisfy: `0 <= offset <= buf.length - 4`
<add>* `noAssert` {Boolean} Skip `value` and `offset` validation? **Default:** `false`
<add>* Return: {Integer} `offset` plus the number of bytes written
<ide>
<ide> Writes `value` to `buf` at the specified `offset` with specified endian
<ide> format (`writeUInt32BE()` writes big endian, `writeUInt32LE()` writes little
<ide> console.log(buf);
<ide> ### buf.writeUIntBE(value, offset, byteLength[, noAssert])
<ide> ### buf.writeUIntLE(value, offset, byteLength[, noAssert])
<ide>
<del>* `value` {Number} Bytes to be written to Buffer
<del>* `offset` {Number} `0 <= offset <= buf.length - byteLength`
<del>* `byteLength` {Number} `0 < byteLength <= 6`
<del>* `noAssert` {Boolean} Default: false
<del>* Return: {Number} The offset plus the number of written bytes
<add>* `value` {Integer} Number to be written to `buf`
<add>* `offset` {Integer} Where to start writing. Must satisfy: `0 <= offset <= buf.length - byteLength`
<add>* `byteLength` {Integer} How many bytes to write. Must satisfy: `0 < byteLength <= 6`
<add>* `noAssert` {Boolean} Skip `value`, `offset`, and `byteLength` validation?
<add> **Default:** `false`
<add>* Return: {Integer} `offset` plus the number of bytes written
<ide>
<ide> Writes `byteLength` bytes of `value` to `buf` at the specified `offset`.
<ide> Supports up to 48 bits of accuracy. Behavior is undefined when `value` is
<ide> console.log(buf);
<ide>
<ide> ## buffer.INSPECT_MAX_BYTES
<ide>
<del>* {Number} Default: 50
<add>* {Integer} **Default:** `50`
<ide>
<ide> Returns the maximum number of bytes that will be returned when
<ide> `buf.inspect()` is called. This can be overridden by user modules. See
<ide> Note that this is a property on the `buffer` module as returned by
<ide> added: v3.0.0
<ide> -->
<ide>
<del>* {Number} The largest size allowed for a single `Buffer` instance
<add>* {Integer} The largest size allowed for a single `Buffer` instance
<ide>
<ide> On 32-bit architectures, this value is `(2^30)-1` (~1GB).
<ide> On 64-bit architectures, this value is `(2^31)-1` (~2GB).
<ide> deprecated: v6.0.0
<ide>
<ide> Stability: 0 - Deprecated: Use [`Buffer.allocUnsafeSlow()`] instead.
<ide>
<del>* `size` Number
<add>* `size` {Integer} The desired length of the new `SlowBuffer`
<ide>
<ide> Allocates a new `SlowBuffer` of `size` bytes. The `size` must be less than
<ide> or equal to the value of [`buffer.kMaxLength`]. Otherwise, a [`RangeError`] is | 1 |
Ruby | Ruby | remove unused variable | 9cd95bc0b7ff44fd13894e17318cb33abbdea280 | <ide><path>Library/Homebrew/cmd/tap.rb
<ide> def tap_args
<ide>
<ide> def private_tap?(user, repo)
<ide> GitHub.private_repo?(user, "homebrew-#{repo}")
<del> rescue GitHub::HTTPNotFoundError => e
<add> rescue GitHub::HTTPNotFoundError
<ide> true
<ide> rescue GitHub::Error
<ide> false | 1 |
PHP | PHP | use new route syntax | 99bb07502c18ce73d64970e3237fec6152527bd9 | <ide><path>routes/api.php
<ide> |
<ide> */
<ide>
<del>Route::get('/user', function (Request $request) {
<add>Route::middleware('auth:api')->get('/user', function (Request $request) {
<ide> return $request->user();
<del>})->middleware('auth:api');
<add>}); | 1 |
Javascript | Javascript | remove unnecessary `resolvemodulesource()` call | b1f34f0cf75dac6a869dffff1a4a463a14f8b7f1 | <ide><path>broccoli/transforms/inject-node-globals.js
<ide> function injectNodeGlobals({ types: t }) {
<ide>
<ide> if (requireId || moduleId) {
<ide> let specifiers = [];
<del> let source = t.stringLiteral(this.file.resolveModuleSource('node-module'));
<add> let source = t.stringLiteral('node-module');
<ide>
<ide> if (requireId) {
<ide> delete path.scope.globals.require; | 1 |
Ruby | Ruby | fix links in csp documentation [ci-skip] | 0b851183e0f88267a5bcd9431437397122a498bd | <ide><path>actionpack/lib/action_dispatch/http/content_security_policy.rb
<ide>
<ide> module ActionDispatch # :nodoc:
<ide> # Allows configuring a
<del> # {Content-Security-Policy}(https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy)
<add> # {Content-Security-Policy}[https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy]
<ide> # to help protect against XSS and injection attacks.
<ide> #
<ide> # Example global policy:
<ide> def plugin_types(*types)
<ide> end
<ide> end
<ide>
<del> # Enable the {report-uri}(https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/report-uri)
<add> # Enable the {report-uri}[https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/report-uri]
<ide> # directive. Violation reports will be sent to the specified URI:
<ide> #
<ide> # policy.report_uri "/csp-violation-report-endpoint"
<ide> def report_uri(uri)
<ide> @directives["report-uri"] = [uri]
<ide> end
<ide>
<del> # Specify asset types for which {Subresource Integrity}(https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity)
<add> # Specify asset types for which {Subresource Integrity}[https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity]
<ide> # is required:
<ide> #
<ide> # policy.require_sri_for :script, :style
<ide> def require_sri_for(*types)
<ide> end
<ide> end
<ide>
<del> # Specify whether a {sandbox}(https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/sandbox)
<add> # Specify whether a {sandbox}[https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/sandbox]
<ide> # should be enabled for the requested resource:
<ide> #
<ide> # policy.sandbox | 1 |
Go | Go | move "image_history" to graph/history.go | 55235e121eb2924488508f70b8f30e0e9905d85e | <ide><path>graph/history.go
<add>package graph
<add>
<add>import (
<add> "strings"
<add>
<add> "github.com/docker/docker/engine"
<add> "github.com/docker/docker/image"
<add>)
<add>
<add>func (s *TagStore) CmdHistory(job *engine.Job) engine.Status {
<add> if n := len(job.Args); n != 1 {
<add> return job.Errorf("Usage: %s IMAGE", job.Name)
<add> }
<add> name := job.Args[0]
<add> foundImage, err := s.LookupImage(name)
<add> if err != nil {
<add> return job.Error(err)
<add> }
<add>
<add> lookupMap := make(map[string][]string)
<add> for name, repository := range s.Repositories {
<add> for tag, id := range repository {
<add> // If the ID already has a reverse lookup, do not update it unless for "latest"
<add> if _, exists := lookupMap[id]; !exists {
<add> lookupMap[id] = []string{}
<add> }
<add> lookupMap[id] = append(lookupMap[id], name+":"+tag)
<add> }
<add> }
<add>
<add> outs := engine.NewTable("Created", 0)
<add> err = foundImage.WalkHistory(func(img *image.Image) error {
<add> out := &engine.Env{}
<add> out.Set("Id", img.ID)
<add> out.SetInt64("Created", img.Created.Unix())
<add> out.Set("CreatedBy", strings.Join(img.ContainerConfig.Cmd, " "))
<add> out.SetList("Tags", lookupMap[img.ID])
<add> out.SetInt64("Size", img.Size)
<add> outs.Add(out)
<add> return nil
<add> })
<add> if _, err := outs.WriteListTo(job.Stdout); err != nil {
<add> return job.Error(err)
<add> }
<add> return engine.StatusOK
<add>}
<ide><path>graph/service.go
<ide> func (s *TagStore) Install(eng *engine.Engine) error {
<ide> eng.Register("image_inspect", s.CmdLookup)
<ide> eng.Register("image_tarlayer", s.CmdTarLayer)
<ide> eng.Register("image_export", s.CmdImageExport)
<add> eng.Register("history", s.CmdHistory)
<ide> return nil
<ide> }
<ide>
<ide><path>server/image.go
<ide> func (srv *Server) Images(job *engine.Job) engine.Status {
<ide> return engine.StatusOK
<ide> }
<ide>
<del>func (srv *Server) ImageHistory(job *engine.Job) engine.Status {
<del> if n := len(job.Args); n != 1 {
<del> return job.Errorf("Usage: %s IMAGE", job.Name)
<del> }
<del> name := job.Args[0]
<del> foundImage, err := srv.daemon.Repositories().LookupImage(name)
<del> if err != nil {
<del> return job.Error(err)
<del> }
<del>
<del> lookupMap := make(map[string][]string)
<del> for name, repository := range srv.daemon.Repositories().Repositories {
<del> for tag, id := range repository {
<del> // If the ID already has a reverse lookup, do not update it unless for "latest"
<del> if _, exists := lookupMap[id]; !exists {
<del> lookupMap[id] = []string{}
<del> }
<del> lookupMap[id] = append(lookupMap[id], name+":"+tag)
<del> }
<del> }
<del>
<del> outs := engine.NewTable("Created", 0)
<del> err = foundImage.WalkHistory(func(img *image.Image) error {
<del> out := &engine.Env{}
<del> out.Set("Id", img.ID)
<del> out.SetInt64("Created", img.Created.Unix())
<del> out.Set("CreatedBy", strings.Join(img.ContainerConfig.Cmd, " "))
<del> out.SetList("Tags", lookupMap[img.ID])
<del> out.SetInt64("Size", img.Size)
<del> outs.Add(out)
<del> return nil
<del> })
<del> if _, err := outs.WriteListTo(job.Stdout); err != nil {
<del> return job.Error(err)
<del> }
<del> return engine.StatusOK
<del>}
<ide> func (srv *Server) ImageTag(job *engine.Job) engine.Status {
<ide> if len(job.Args) != 2 && len(job.Args) != 3 {
<ide> return job.Errorf("Usage: %s IMAGE REPOSITORY [TAG]\n", job.Name)
<ide><path>server/init.go
<ide> func InitServer(job *engine.Job) engine.Status {
<ide> "tag": srv.ImageTag, // FIXME merge with "image_tag"
<ide> "info": srv.DockerInfo,
<ide> "images": srv.Images,
<del> "history": srv.ImageHistory,
<ide> "viz": srv.ImagesViz,
<ide> "log": srv.Log,
<ide> "load": srv.ImageLoad, | 4 |
Ruby | Ruby | fix response_body warning in ac | 70c3e825fc184c7267d226c7b365af4db17f58b7 | <ide><path>actionpack/lib/abstract_controller/base.rb
<ide> def process(action)
<ide> raise ActionNotFound, "The action '#{action}' could not be found"
<ide> end
<ide>
<add> @_response_body = nil
<add>
<ide> process_action(action_name)
<ide> end
<ide> | 1 |
PHP | PHP | apply fixes from styleci | d35e24c409598c231371369dabc8cdc8c92a11d6 | <ide><path>src/Illuminate/Foundation/Console/ExceptionMakeCommand.php
<ide> protected function getStub()
<ide> return $this->option('report')
<ide> ? __DIR__.'/stubs/exception-report.stub'
<ide> : __DIR__.'/stubs/exception.stub';
<del>
<ide> }
<ide>
<ide> /** | 1 |
Go | Go | use strconv instead of fmt.sprintf | 7fbf321c2a1628e149ebe6838c9809d4c52cf37d | <ide><path>daemon/graphdriver/aufs/aufs.go
<ide> import (
<ide> "os/exec"
<ide> "path"
<ide> "path/filepath"
<add> "strconv"
<ide> "strings"
<ide> "sync"
<ide>
<ide> func (a *Driver) Status() [][2]string {
<ide> return [][2]string{
<ide> {"Root Dir", a.rootPath()},
<ide> {"Backing Filesystem", backingFs},
<del> {"Dirs", fmt.Sprintf("%d", len(ids))},
<del> {"Dirperm1 Supported", fmt.Sprintf("%v", useDirperm())},
<add> {"Dirs", strconv.Itoa(len(ids))},
<add> {"Dirperm1 Supported", strconv.FormatBool(useDirperm())},
<ide> }
<ide> }
<ide>
<ide><path>daemon/graphdriver/aufs/aufs_test.go
<ide> import (
<ide> "os"
<ide> "path"
<ide> "path/filepath"
<add> "strconv"
<ide> "sync"
<ide> "testing"
<ide>
<ide> func testMountMoreThan42Layers(t *testing.T, mountPath string) {
<ide> for i := 1; i < 127; i++ {
<ide> expected++
<ide> var (
<del> parent = fmt.Sprintf("%d", i-1)
<del> current = fmt.Sprintf("%d", i)
<add> parent = strconv.Itoa(i - 1)
<add> current = strconv.Itoa(i)
<ide> )
<ide>
<ide> if parent == "0" {
<ide><path>daemon/graphdriver/btrfs/btrfs.go
<ide> func (d *Driver) Status() [][2]string {
<ide> status = append(status, [2]string{"Build Version", bv})
<ide> }
<ide> if lv := btrfsLibVersion(); lv != -1 {
<del> status = append(status, [2]string{"Library Version", fmt.Sprintf("%d", lv)})
<add> status = append(status, [2]string{"Library Version", strconv.Itoa(lv)})
<ide> }
<ide> return status
<ide> }
<ide><path>daemon/graphdriver/zfs/zfs.go
<ide> func (d *Driver) GetMetadata(id string) (map[string]string, error) {
<ide> }
<ide>
<ide> func (d *Driver) cloneFilesystem(name, parentName string) error {
<del> snapshotName := fmt.Sprintf("%d", time.Now().Nanosecond())
<add> snapshotName := strconv.Itoa(time.Now().Nanosecond())
<ide> parentDataset := zfs.Dataset{Name: parentName}
<ide> snapshot, err := parentDataset.Snapshot(snapshotName /*recursive */, false)
<ide> if err != nil { | 4 |
Text | Text | add v4.0.1 to changelog | 7e411fd2205af318492a948a23ed3cc4da99aacb | <ide><path>CHANGELOG.md
<ide> - [#18269](https://github.com/emberjs/ember.js/pull/18269) [BUGFIX] Fix for when query params are using a nested value
<ide> - [#19787](https://github.com/emberjs/ember.js/pull/19787) Setup basic infrastructure to ensure destroyables destroyed
<ide>
<add>### v4.0.1 (December 1, 2021)
<add>
<add>- [#19858](https://github.com/emberjs/ember.js/pull/19858) [BUGFIX] Improve assert message in default store for when routes have dynamic segments but no model hook
<add>- [#19860](https://github.com/emberjs/ember.js/pull/19860) [BUGFIX] Add model hook in route blueprint for routes with dynamic segments
<add>
<ide> ### v4.0.0 (November 15, 2021)
<ide>
<ide> - [#19761](https://github.com/emberjs/ember.js/pull/19761) [BREAKING] Require ember-auto-import >= 2 or higher to enable ember-source to become a v2 addon in the 4.x cycle | 1 |
Javascript | Javascript | add vm context global proxy benchmark | b3531bf735afcd87db718095681d04ef8269f70f | <ide><path>benchmark/vm/context-global-proxy.js
<add>'use strict';
<add>
<add>const common = require('../common.js');
<add>
<add>const bench = common.createBenchmark(main, {
<add> n: [100000],
<add>});
<add>
<add>const vm = require('vm');
<add>const script = new vm.Script(`
<add> globalThis.foo++;
<add>`);
<add>const context = vm.createContext({ foo: 1 });
<add>
<add>function main({ n }) {
<add> bench.start();
<add> for (let i = 0; i < n; i++) {
<add> script.runInContext(context);
<add> }
<add> bench.end(n);
<add>} | 1 |
Python | Python | replace calls to unittest.testcase.fail | 88cbd3d857db84cf820a6210fde14814f1d1d92b | <ide><path>numpy/core/tests/test_defchararray.py
<ide> from numpy.core.multiarray import _vec_string
<ide> from numpy.testing import (
<ide> assert_, assert_equal, assert_array_equal, assert_raises,
<del> suppress_warnings,
<add> assert_raises_regex, suppress_warnings,
<ide> )
<ide>
<ide> kw_unicode_true = {'unicode': True} # make 2to3 work properly
<ide> def test_mul(self):
<ide> assert_array_equal(Ar, (self.A * r))
<ide>
<ide> for ob in [object(), 'qrs']:
<del> try:
<del> A * ob
<del> except ValueError:
<del> pass
<del> else:
<del> self.fail("chararray can only be multiplied by integers")
<add> with assert_raises_regex(ValueError,
<add> 'Can only multiply by integers'):
<add> A*ob
<ide>
<ide> def test_rmul(self):
<ide> A = self.A
<ide> def test_rmul(self):
<ide> assert_array_equal(Ar, (r * self.A))
<ide>
<ide> for ob in [object(), 'qrs']:
<del> try:
<add> with assert_raises_regex(ValueError,
<add> 'Can only multiply by integers'):
<ide> ob * A
<del> except ValueError:
<del> pass
<del> else:
<del> self.fail("chararray can only be multiplied by integers")
<ide>
<ide> def test_mod(self):
<ide> """Ticket #856"""
<ide> def test_rmod(self):
<ide> assert_(("%r" % self.A) == repr(self.A))
<ide>
<ide> for ob in [42, object()]:
<del> try:
<add> with assert_raises_regex(
<add> TypeError, "unsupported operand type.* and 'chararray'"):
<ide> ob % self.A
<del> except TypeError:
<del> pass
<del> else:
<del> self.fail("chararray __rmod__ should fail with "
<del> "non-string objects")
<ide>
<ide> def test_slice(self):
<ide> """Regression test for https://github.com/numpy/numpy/issues/5982"""
<ide><path>numpy/core/tests/test_errstate.py
<ide> import pytest
<ide>
<ide> import numpy as np
<del>from numpy.testing import assert_
<add>from numpy.testing import assert_, assert_raises
<ide>
<ide>
<ide> class TestErrstate(object):
<ide> def test_invalid(self):
<ide> with np.errstate(invalid='ignore'):
<ide> np.sqrt(a)
<ide> # While this should fail!
<del> try:
<add> with assert_raises(FloatingPointError):
<ide> np.sqrt(a)
<del> except FloatingPointError:
<del> pass
<del> else:
<del> self.fail("Did not raise an invalid error")
<ide>
<ide> def test_divide(self):
<ide> with np.errstate(all='raise', under='ignore'):
<ide> def test_divide(self):
<ide> with np.errstate(divide='ignore'):
<ide> a // 0
<ide> # While this should fail!
<del> try:
<add> with assert_raises(FloatingPointError):
<ide> a // 0
<del> except FloatingPointError:
<del> pass
<del> else:
<del> self.fail("Did not raise divide by zero error")
<ide>
<ide> def test_errcall(self):
<ide> def foo(*args):
<ide><path>numpy/core/tests/test_numeric.py
<ide> from numpy.testing import (
<ide> assert_, assert_equal, assert_raises, assert_raises_regex,
<ide> assert_array_equal, assert_almost_equal, assert_array_almost_equal,
<del> suppress_warnings, HAS_REFCOUNT
<add> assert_raises, suppress_warnings, HAS_REFCOUNT
<ide> )
<ide>
<ide>
<ide> def test_set(self):
<ide> @pytest.mark.skipif(platform.machine() == "armv5tel", reason="See gh-413.")
<ide> def test_divide_err(self):
<ide> with np.errstate(divide='raise'):
<del> try:
<add> with assert_raises(FloatingPointError):
<ide> np.array([1.]) / np.array([0.])
<del> except FloatingPointError:
<del> pass
<del> else:
<del> self.fail()
<add>
<ide> np.seterr(divide='ignore')
<ide> np.array([1.]) / np.array([0.])
<ide>
<ide><path>numpy/core/tests/test_regression.py
<ide> from numpy.testing import (
<ide> assert_, assert_equal, IS_PYPY, assert_almost_equal,
<ide> assert_array_equal, assert_array_almost_equal, assert_raises,
<del> assert_warns, suppress_warnings, _assert_valid_refcount, HAS_REFCOUNT,
<add> assert_raises_regex, assert_warns, suppress_warnings,
<add> _assert_valid_refcount, HAS_REFCOUNT,
<ide> )
<ide> from numpy.compat import asbytes, asunicode, long
<ide>
<ide> def test_zeros(self):
<ide> # Regression test for #1061.
<ide> # Set a size which cannot fit into a 64 bits signed integer
<ide> sz = 2 ** 64
<del> good = 'Maximum allowed dimension exceeded'
<del> try:
<add> with assert_raises_regex(ValueError,
<add> 'Maximum allowed dimension exceeded'):
<ide> np.empty(sz)
<del> except ValueError as e:
<del> if not str(e) == good:
<del> self.fail("Got msg '%s', expected '%s'" % (e, good))
<del> except Exception as e:
<del> self.fail("Got exception of type %s instead of ValueError" % type(e))
<ide>
<ide> def test_huge_arange(self):
<ide> # Regression test for #1062.
<ide> # Set a size which cannot fit into a 64 bits signed integer
<ide> sz = 2 ** 64
<del> good = 'Maximum allowed size exceeded'
<del> try:
<add> with assert_raises_regex(ValueError,
<add> 'Maximum allowed size exceeded'):
<ide> np.arange(sz)
<ide> assert_(np.size == sz)
<del> except ValueError as e:
<del> if not str(e) == good:
<del> self.fail("Got msg '%s', expected '%s'" % (e, good))
<del> except Exception as e:
<del> self.fail("Got exception of type %s instead of ValueError" % type(e))
<ide>
<ide> def test_fromiter_bytes(self):
<ide> # Ticket #1058
<ide><path>numpy/lib/tests/test_format.py
<ide>
<ide> import numpy as np
<ide> from numpy.testing import (
<del> assert_, assert_array_equal, assert_raises, raises, SkipTest
<add> assert_, assert_array_equal, assert_raises, assert_raises_regex,
<add> raises, SkipTest
<ide> )
<ide> from numpy.lib import format
<ide>
<ide> def test_write_version():
<ide> (255, 255),
<ide> ]
<ide> for version in bad_versions:
<del> try:
<add> with assert_raises_regex(ValueError,
<add> 'we only support format version.*'):
<ide> format.write_array(f, arr, version=version)
<del> except ValueError:
<del> pass
<del> else:
<del> raise AssertionError("we should have raised a ValueError for the bad version %r" % (version,))
<ide>
<ide>
<ide> bad_version_magic = [
<ide><path>numpy/lib/tests/test_io.py
<ide> def test_dtype_with_object(self):
<ide> assert_equal(test, control)
<ide>
<ide> ndtype = [('nest', [('idx', int), ('code', object)])]
<del> try:
<add> with assert_raises_regex(NotImplementedError,
<add> 'Nested fields.* not supported.*'):
<ide> test = np.genfromtxt(TextIO(data), delimiter=";",
<ide> dtype=ndtype, converters=converters)
<del> except NotImplementedError:
<del> pass
<del> else:
<del> errmsg = "Nested dtype involving objects should be supported."
<del> raise AssertionError(errmsg)
<ide>
<ide> def test_userconverters_with_explicit_dtype(self):
<ide> # Test user_converters w/ explicit (standard) dtype
<ide><path>numpy/lib/tests/test_recfunctions.py
<ide> def test_autoconversion(self):
<ide> test = stack_arrays((a, b), autoconvert=True)
<ide> assert_equal(test, control)
<ide> assert_equal(test.mask, control.mask)
<del> try:
<del> test = stack_arrays((a, b), autoconvert=False)
<del> except TypeError:
<del> pass
<del> else:
<del> raise AssertionError
<add> with assert_raises(TypeError):
<add> stack_arrays((a, b), autoconvert=False)
<ide>
<ide> def test_checktitles(self):
<ide> # Test using titles in the field names
<ide><path>numpy/ma/tests/test_core.py
<ide> def test_masked_where_oddities(self):
<ide>
<ide> def test_masked_where_shape_constraint(self):
<ide> a = arange(10)
<del> try:
<del> test = masked_equal(1, a)
<del> except IndexError:
<del> pass
<del> else:
<del> raise AssertionError("Should have failed...")
<add> with assert_raises(IndexError):
<add> masked_equal(1, a)
<ide> test = masked_equal(a, 1)
<ide> assert_equal(test.mask, [0, 1, 0, 0, 0, 0, 0, 0, 0, 0])
<ide>
<ide><path>numpy/matrixlib/tests/test_defmatrix.py
<ide> def test_notimplemented(self):
<ide> [3., 4.]])
<ide>
<ide> # __rpow__
<del> try:
<add> with assert_raises(TypeError):
<ide> 1.0**A
<del> except TypeError:
<del> pass
<del> else:
<del> self.fail("matrix.__rpow__ doesn't raise a TypeError")
<ide>
<ide> # __mul__ with something not a list, ndarray, tuple, or scalar
<del> try:
<add> with assert_raises(TypeError):
<ide> A*object()
<del> except TypeError:
<del> pass
<del> else:
<del> self.fail("matrix.__mul__ with non-numeric object doesn't raise"
<del> "a TypeError")
<add>
<ide>
<ide> class TestMatrixReturn(object):
<ide> def test_instance_methods(self):
<ide><path>numpy/testing/tests/test_utils.py
<ide> def _test_equal(self, a, b):
<ide> self._assert_func(a, b)
<ide>
<ide> def _test_not_equal(self, a, b):
<del> try:
<add> with assert_raises(AssertionError):
<ide> self._assert_func(a, b)
<del> except AssertionError:
<del> pass
<del> else:
<del> raise AssertionError("a and b are found equal but are not")
<ide>
<ide> def test_array_rank1_eq(self):
<ide> """Test two equal array of rank 1 are found equal.""" | 10 |
PHP | PHP | update routelistcommand.php | b71144ac57865b7e4a53fb23c7a901fc28362cbe | <ide><path>src/Illuminate/Foundation/Console/RouteListCommand.php
<ide> protected function getOptions()
<ide> ['path', null, InputOption::VALUE_OPTIONAL, 'Only show routes matching the given path pattern'],
<ide> ['except-path', null, InputOption::VALUE_OPTIONAL, 'Do not display the routes matching the given path pattern'],
<ide> ['reverse', 'r', InputOption::VALUE_NONE, 'Reverse the ordering of the routes'],
<del> ['sort', null, InputOption::VALUE_OPTIONAL, 'The column (precedence, domain, method, uri, name, action, middleware) to sort by', 'uri'],
<add> ['sort', null, InputOption::VALUE_OPTIONAL, 'The column (domain, method, uri, name, action, middleware) to sort by', 'uri'],
<ide> ['except-vendor', null, InputOption::VALUE_NONE, 'Do not display routes defined by vendor packages'],
<ide> ];
<ide> } | 1 |
Python | Python | fix autotokenizer with subfolder passed | fb1c8db78a35d3e1f77410b6a5e5845b04d91e30 | <ide><path>src/transformers/models/auto/tokenization_auto.py
<ide> def get_tokenizer_config(
<ide> use_auth_token: Optional[Union[bool, str]] = None,
<ide> revision: Optional[str] = None,
<ide> local_files_only: bool = False,
<add> subfolder: str = "",
<ide> **kwargs,
<ide> ):
<ide> """
<ide> def get_tokenizer_config(
<ide> identifier allowed by git.
<ide> local_files_only (`bool`, *optional*, defaults to `False`):
<ide> If `True`, will only try to load the tokenizer configuration from local files.
<add> subfolder (`str`, *optional*, defaults to `""`):
<add> In case the tokenizer config is located inside a subfolder of the model repo on huggingface.co, you can
<add> specify the folder name here.
<ide>
<ide> <Tip>
<ide>
<ide> def get_tokenizer_config(
<ide> use_auth_token=use_auth_token,
<ide> revision=revision,
<ide> local_files_only=local_files_only,
<add> subfolder=subfolder,
<ide> _raise_exceptions_for_missing_entries=False,
<ide> _raise_exceptions_for_connection_errors=False,
<ide> _commit_hash=commit_hash, | 1 |
Python | Python | set version to v3.0.0a4 | 743f7fb73aaceec752bfd74fe903b9c12e69f8c6 | <ide><path>spacy/about.py
<ide> # fmt: off
<ide> __title__ = "spacy-nightly"
<del>__version__ = "3.0.0a3"
<add>__version__ = "3.0.0a4"
<ide> __release__ = True
<ide> __download_url__ = "https://github.com/explosion/spacy-models/releases/download"
<ide> __compatibility__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json" | 1 |
Python | Python | fix dimention misspellings. | 4670b57ce984dae754a7664629b1ade2cdcfe9ca | <ide><path>src/transformers/models/gpt_neo/modeling_gpt_neo.py
<ide> def _get_block_length_and_num_blocks(seq_length, window_size):
<ide> def _look_back(tensor, block_length, window_size, pad_value=0, is_key_value=True):
<ide> """
<ide> Used to implement attention between consecutive blocks. This method assumes that dim 1 of :obj:`tensor`
<del> represents the :obj:`seq_length` dimention. It splits :obj:`seq_length` dimention into :obj:`num_blocks` and
<del> :obj:`window_size` + :obj:`block_length`. It pads the :obj:`seq_length` dimention if necessary.
<add> represents the :obj:`seq_length` dimension. It splits :obj:`seq_length` dimension into :obj:`num_blocks` and
<add> :obj:`window_size` + :obj:`block_length`. It pads the :obj:`seq_length` dimension if necessary.
<ide>
<ide> Example::
<ide>
<ide> def _create_attention_mask(self, batch_size, seq_length, num_blocks, block_lengt
<ide> # look back into the attention_block such that it will also get padded the same way
<ide> # and have 0s in the padded position
<ide> attention_mask = self._look_back(attention_mask, block_length, self.window_size, is_key_value=False)
<del> attention_mask = attention_mask.unsqueeze(-2) # Add an extra dimention to account for hidden_dim
<add> attention_mask = attention_mask.unsqueeze(-2) # Add an extra dimension to account for hidden_dim
<ide>
<ide> # Multiply the causal_mask with attention_mask so the padded positions (by _look_back operation)
<ide> # will contain 0s.
<ide> def _create_attention_mask(self, batch_size, seq_length, num_blocks, block_lengt
<ide> visible = torch.gt(relative_position, -self.window_size)
<ide>
<ide> causal_mask = causal_mask * visible
<del> causal_mask = causal_mask.unsqueeze(-3).bool() # Add an extra dimention to account for num_heads
<add> causal_mask = causal_mask.unsqueeze(-3).bool() # Add an extra dimension to account for num_heads
<ide>
<ide> return causal_mask
<ide>
<ide><path>src/transformers/models/speech_to_text/configuration_speech_to_text.py
<ide> class Speech2TextConfig(PretrainedConfig):
<ide> An integer defining the number of output channels of each convolution layers except the final one in the
<ide> conv module.
<ide> input_feat_per_channel (:obj:`int`, `optional`, defaults to 80):
<del> An integer specifying the size of feature vector. This is also the dimentions of log-mel filter-bank
<add> An integer specifying the size of feature vector. This is also the dimensions of log-mel filter-bank
<ide> features.
<ide> input_channels (:obj:`int`, `optional`, defaults to 1):
<ide> An integer specifying number of input channels of the input feature vector. | 2 |
Python | Python | decrease memory usage of lstm text gen example | be22591e326028b5642b1b7d2cecb58137dcb921 | <ide><path>examples/lstm_text_generation.py
<ide> print('nb sequences:', len(sentences))
<ide>
<ide> print('Vectorization...')
<del>X = np.zeros((len(sentences), maxlen, len(chars)))
<del>y = np.zeros((len(sentences), len(chars)))
<add>X = np.zeros((len(sentences), maxlen, len(chars)), dtype=np.bool)
<add>y = np.zeros((len(sentences), len(chars)), dtype=np.bool)
<ide> for i, sentence in enumerate(sentences):
<ide> for t, char in enumerate(sentence):
<del> X[i, t, char_indices[char]] = 1.
<del> y[i, char_indices[next_chars[i]]] = 1.
<add> X[i, t, char_indices[char]] = 1
<add> y[i, char_indices[next_chars[i]]] = 1
<ide>
<ide>
<ide> # build the model: 2 stacked LSTM | 1 |
Javascript | Javascript | remove filter pills from example page | 5cf4ab8dd28b5a336d7af29d295ede51f0d19587 | <ide><path>packages/rn-tester/js/components/RNTesterExampleList.js
<ide> const RNTesterExampleList: React$AbstractComponent<any, void> = React.memo(
<ide> page="components_page"
<ide> sections={sections}
<ide> filter={filter}
<add> hideFilterPills={true}
<ide> render={({filteredSections}) => (
<ide> <SectionList
<ide> sections={filteredSections} | 1 |
Text | Text | rearrange v1.5.1 to be right below v1.5.2 | 3e9015019f3918db444bf0bdf557361d6a9781df | <ide><path>CHANGELOG.md
<ide> <a name="1.5.2"></a>
<ide> # 1.5.2 differential-recovery (2016-03-18)
<ide>
<del>This release reverts a breaking change that accidentally made it into the 1.5.1 release. See [fee7bac3](https://github.com/angular/angular.js/commit/fee7bac392db24b6006d6a57ba71526f3afa102c) for more info.
<add>This release reverts a breaking change that accidentally made it into the 1.5.1 release. See
<add>[fee7bac3](https://github.com/angular/angular.js/commit/fee7bac392db24b6006d6a57ba71526f3afa102c)
<add>for more info.
<ide>
<ide>
<ide> ## Bug Fixes
<ide> This release reverts a breaking change that accidentally made it into the 1.5.1
<ide> ([ce7f4000](https://github.com/angular/angular.js/commit/ce7f400011e1e2e1b9316f18ce87b87b79d878b4))
<ide>
<ide>
<del>## Breaking Changes
<add><a name="1.5.1"></a>
<add># 1.5.1 equivocal-sophistication (2016-03-16)
<ide>
<ide>
<add>## Bug Fixes
<add>
<add>- **core:** only call `console.log` when `window.console` exists
<add> ([ce138f3c](https://github.com/angular/angular.js/commit/ce138f3c552f8bf741721ab8d10994ed35a4b2f5),
<add> [#14006](https://github.com/angular/angular.js/issues/14006), [#14007](https://github.com/angular/angular.js/issues/14007), [#14047](https://github.com/angular/angular.js/issues/14047))
<add>- **$compile:** allow directives to have decorators
<add> ([0728cc2f](https://github.com/angular/angular.js/commit/0728cc2f2bb04d5dbdfca41f3afacea16c75ee07))
<add>- **$resource:** fix parse errors on older Android WebViews
<add> ([df8db7b4](https://github.com/angular/angular.js/commit/df8db7b446b5bae83afef457d706d2805e597f29),
<add> [#13989](https://github.com/angular/angular.js/issues/13989))
<add>- **$routeProvider:** properly handle optional eager path named groups
<add> ([c0797c68](https://github.com/angular/angular.js/commit/c0797c68866c9ef8ff3c2f6985e6eb9374346151),
<add> [#14011](https://github.com/angular/angular.js/issues/14011))
<add>- **copy:** add support for copying `Blob` objects
<add> ([e9d579b6](https://github.com/angular/angular.js/commit/e9d579b608c2be8fdcf0326d0679a76bb9ae5b6e),
<add> [#9669](https://github.com/angular/angular.js/issues/9669), [#14064](https://github.com/angular/angular.js/issues/14064))
<add>- **dateFilter:** correctly format BC years
<add> ([e36205f5](https://github.com/angular/angular.js/commit/e36205f5af82b69362def7d2b6eeeb038f592311))
<add>- **formatNumber:** allow negative fraction size
<add> ([e046c170](https://github.com/angular/angular.js/commit/e046c170bcf677f26e61af6470cb5fd2f751c969),
<add> [#13913](https://github.com/angular/angular.js/issues/13913))
<add>- **input:** re-validate when partially editing date-family inputs
<add> ([e383804c](https://github.com/angular/angular.js/commit/e383804c4ab62278fbaf4fdfaa03caeacff77fc4),
<add> [#12207](https://github.com/angular/angular.js/issues/12207), [#13886](https://github.com/angular/angular.js/issues/13886))
<add>- **input\[date\]:** support years with more than 4 digits
<add> ([d76951f1](https://github.com/angular/angular.js/commit/d76951f1747abd2da6e320d4ff9019f170d9793f),
<add> [#13735](https://github.com/angular/angular.js/issues/13735), [#13905](https://github.com/angular/angular.js/issues/13905))
<add>- **ngOptions:** always set the 'selected' attribute for selected options
<add> ([9f5a1722](https://github.com/angular/angular.js/commit/9f5a172291ff6926dcd246f0972288916a4c9bf6),
<add> [#14115](https://github.com/angular/angular.js/issues/14115))
<add>- **ngRoute:** allow `ngView` to be included in an asynchronously loaded template
<add> ([8237482d](https://github.com/angular/angular.js/commit/8237482d49e76e2c4994fe6207e3c9799ef04163),
<add> [#1213](https://github.com/angular/angular.js/issues/1213), [#6812](https://github.com/angular/angular.js/issues/6812), [#14088](https://github.com/angular/angular.js/issues/14088))
<add>- **ngMock:**
<add> - attach `$injector` to `$rootElement` and prevent memory leak due to attached data
<add> ([75373dd4](https://github.com/angular/angular.js/commit/75373dd4bdae6c6035272942c69444c386f824cd),
<add> [#14022](https://github.com/angular/angular.js/issues/14022), [#14094](https://github.com/angular/angular.js/issues/14094), [#14098](https://github.com/angular/angular.js/issues/14098))
<add> - don't break if `$rootScope.$destroy()` is not a function
<add> ([50ed8712](https://github.com/angular/angular.js/commit/50ed8712566d601c9fb76b71f7b534b5bc803a36),
<add> [#14106](https://github.com/angular/angular.js/issues/14106), [#14107](https://github.com/angular/angular.js/issues/14107))
<add>- **ngMockE2E:** pass `responseType` to `$delegate` when using `passThrough`
<add> ([d16faf9f](https://github.com/angular/angular.js/commit/d16faf9f2b9bd2b85d95e71d902cec0269282f2c),
<add> [#5415](https://github.com/angular/angular.js/issues/5415), [#5783](https://github.com/angular/angular.js/issues/5783))
<add>
<add>
<add>## Features
<add>
<add>- **$compile:** add custom annotations to the controller
<add> ([0c800930](https://github.com/angular/angular.js/commit/0c8009300b819c39c5e4892856724a731a8dcda6),
<add> [#14114](https://github.com/angular/angular.js/issues/14114))
<add>- **$controllerProvider:** add a `has()` method for checking the existence of a controller
<add> ([bb9575db](https://github.com/angular/angular.js/commit/bb9575dbd3428176216355df7b2933d2a72783cd),
<add> [#13951](https://github.com/angular/angular.js/issues/13951), [#14109](https://github.com/angular/angular.js/issues/14109))
<add>- **dateFilter:** add support for STANDALONEMONTH in format (`LLLL`)
<add> ([3e5b25b3](https://github.com/angular/angular.js/commit/3e5b25b33f278376def432698c704b1807fdb8c0),
<add> [#13999](https://github.com/angular/angular.js/issues/13999), [#14013](https://github.com/angular/angular.js/issues/14013))
<add>- **ngMock:** add `sharedInjector()` to `angular.mock.module`
<add> ([a46ab60f](https://github.com/angular/angular.js/commit/a46ab60fd5bf94896f0761e858ef38b998eb0f80),
<add> [#14093](https://github.com/angular/angular.js/issues/14093), [#10238](https://github.com/angular/angular.js/issues/10238))
<add>
<add>
<add>## Performance Improvements
<add>
<add>- **ngRepeat:** avoid duplicate jqLite wrappers
<add> ([632e15a3](https://github.com/angular/angular.js/commit/632e15a3afdcd30168700cec1367bd81966400d4))
<add>- **ngAnimate:**
<add> - avoid jqLite/jQuery for upward DOM traversal
<add> ([35251bd4](https://github.com/angular/angular.js/commit/35251bd4ce23251b5e9a2860cf414726c194721e))
<add> - avoid `$.fn.data` overhead with jQuery
<add> ([15915e60](https://github.com/angular/angular.js/commit/15915e606fdf5114592db1a0a5e3f12e639d7cdb))
<add>
<ide>
<ide> <a name="1.4.10"></a>
<ide> # 1.4.10 benignant-oscillation (2016-03-16)
<ide> This release reverts a breaking change that accidentally made it into the 1.5.1
<ide> ([86416bcb](https://github.com/angular/angular.js/commit/86416bcbee2192fa31c017163c5d856763182ade))
<ide>
<ide>
<del><a name="1.5.1"></a>
<del># 1.5.1 equivocal-sophistication (2016-03-16)
<del>
<del>
<del>## Bug Fixes
<del>
<del>- **core:** only call `console.log` when `window.console` exists
<del> ([ce138f3c](https://github.com/angular/angular.js/commit/ce138f3c552f8bf741721ab8d10994ed35a4b2f5),
<del> [#14006](https://github.com/angular/angular.js/issues/14006), [#14007](https://github.com/angular/angular.js/issues/14007), [#14047](https://github.com/angular/angular.js/issues/14047))
<del>- **$compile:** allow directives to have decorators
<del> ([0728cc2f](https://github.com/angular/angular.js/commit/0728cc2f2bb04d5dbdfca41f3afacea16c75ee07))
<del>- **$resource:** fix parse errors on older Android WebViews
<del> ([df8db7b4](https://github.com/angular/angular.js/commit/df8db7b446b5bae83afef457d706d2805e597f29),
<del> [#13989](https://github.com/angular/angular.js/issues/13989))
<del>- **$routeProvider:** properly handle optional eager path named groups
<del> ([c0797c68](https://github.com/angular/angular.js/commit/c0797c68866c9ef8ff3c2f6985e6eb9374346151),
<del> [#14011](https://github.com/angular/angular.js/issues/14011))
<del>- **copy:** add support for copying `Blob` objects
<del> ([e9d579b6](https://github.com/angular/angular.js/commit/e9d579b608c2be8fdcf0326d0679a76bb9ae5b6e),
<del> [#9669](https://github.com/angular/angular.js/issues/9669), [#14064](https://github.com/angular/angular.js/issues/14064))
<del>- **dateFilter:** correctly format BC years
<del> ([e36205f5](https://github.com/angular/angular.js/commit/e36205f5af82b69362def7d2b6eeeb038f592311))
<del>- **formatNumber:** allow negative fraction size
<del> ([e046c170](https://github.com/angular/angular.js/commit/e046c170bcf677f26e61af6470cb5fd2f751c969),
<del> [#13913](https://github.com/angular/angular.js/issues/13913))
<del>- **input:** re-validate when partially editing date-family inputs
<del> ([e383804c](https://github.com/angular/angular.js/commit/e383804c4ab62278fbaf4fdfaa03caeacff77fc4),
<del> [#12207](https://github.com/angular/angular.js/issues/12207), [#13886](https://github.com/angular/angular.js/issues/13886))
<del>- **input\[date\]:** support years with more than 4 digits
<del> ([d76951f1](https://github.com/angular/angular.js/commit/d76951f1747abd2da6e320d4ff9019f170d9793f),
<del> [#13735](https://github.com/angular/angular.js/issues/13735), [#13905](https://github.com/angular/angular.js/issues/13905))
<del>- **ngOptions:** always set the 'selected' attribute for selected options
<del> ([9f5a1722](https://github.com/angular/angular.js/commit/9f5a172291ff6926dcd246f0972288916a4c9bf6),
<del> [#14115](https://github.com/angular/angular.js/issues/14115))
<del>- **ngRoute:** allow `ngView` to be included in an asynchronously loaded template
<del> ([8237482d](https://github.com/angular/angular.js/commit/8237482d49e76e2c4994fe6207e3c9799ef04163),
<del> [#1213](https://github.com/angular/angular.js/issues/1213), [#6812](https://github.com/angular/angular.js/issues/6812), [#14088](https://github.com/angular/angular.js/issues/14088))
<del>- **ngMock:**
<del> - attach `$injector` to `$rootElement` and prevent memory leak due to attached data
<del> ([75373dd4](https://github.com/angular/angular.js/commit/75373dd4bdae6c6035272942c69444c386f824cd),
<del> [#14022](https://github.com/angular/angular.js/issues/14022), [#14094](https://github.com/angular/angular.js/issues/14094), [#14098](https://github.com/angular/angular.js/issues/14098))
<del> - don't break if `$rootScope.$destroy()` is not a function
<del> ([50ed8712](https://github.com/angular/angular.js/commit/50ed8712566d601c9fb76b71f7b534b5bc803a36),
<del> [#14106](https://github.com/angular/angular.js/issues/14106), [#14107](https://github.com/angular/angular.js/issues/14107))
<del>- **ngMockE2E:** pass `responseType` to `$delegate` when using `passThrough`
<del> ([d16faf9f](https://github.com/angular/angular.js/commit/d16faf9f2b9bd2b85d95e71d902cec0269282f2c),
<del> [#5415](https://github.com/angular/angular.js/issues/5415), [#5783](https://github.com/angular/angular.js/issues/5783))
<del>
<del>
<del>## Features
<del>
<del>- **$compile:** add custom annotations to the controller
<del> ([0c800930](https://github.com/angular/angular.js/commit/0c8009300b819c39c5e4892856724a731a8dcda6),
<del> [#14114](https://github.com/angular/angular.js/issues/14114))
<del>- **$controllerProvider:** add a `has()` method for checking the existence of a controller
<del> ([bb9575db](https://github.com/angular/angular.js/commit/bb9575dbd3428176216355df7b2933d2a72783cd),
<del> [#13951](https://github.com/angular/angular.js/issues/13951), [#14109](https://github.com/angular/angular.js/issues/14109))
<del>- **dateFilter:** add support for STANDALONEMONTH in format (`LLLL`)
<del> ([3e5b25b3](https://github.com/angular/angular.js/commit/3e5b25b33f278376def432698c704b1807fdb8c0),
<del> [#13999](https://github.com/angular/angular.js/issues/13999), [#14013](https://github.com/angular/angular.js/issues/14013))
<del>- **ngMock:** add `sharedInjector()` to `angular.mock.module`
<del> ([a46ab60f](https://github.com/angular/angular.js/commit/a46ab60fd5bf94896f0761e858ef38b998eb0f80),
<del> [#14093](https://github.com/angular/angular.js/issues/14093), [#10238](https://github.com/angular/angular.js/issues/10238))
<del>
<del>
<del>## Performance Improvements
<del>
<del>- **ngRepeat:** avoid duplicate jqLite wrappers
<del> ([632e15a3](https://github.com/angular/angular.js/commit/632e15a3afdcd30168700cec1367bd81966400d4))
<del>- **ngAnimate:**
<del> - avoid jqLite/jQuery for upward DOM traversal
<del> ([35251bd4](https://github.com/angular/angular.js/commit/35251bd4ce23251b5e9a2860cf414726c194721e))
<del> - avoid `$.fn.data` overhead with jQuery
<del> ([15915e60](https://github.com/angular/angular.js/commit/15915e606fdf5114592db1a0a5e3f12e639d7cdb))
<del>
<del>
<ide> <a name="1.5.0"></a>
<ide> # 1.5.0 ennoblement-facilitation (2016-02-05)
<ide> | 1 |
Javascript | Javascript | return the setter values instead of this | 796aff2146d0573f4240bec294201b33ab9a9ad9 | <ide><path>packages/ember-metal/lib/set_properties.js
<ide> import keys from "ember-metal/keys";
<ide> @method setProperties
<ide> @param obj
<ide> @param {Object} properties
<del> @return obj
<add> @return properties
<ide> @public
<ide> */
<ide> export default function setProperties(obj, properties) {
<del> if (!properties || typeof properties !== "object") { return obj; }
<add> if (!properties || typeof properties !== "object") { return properties; }
<ide> changeProperties(function() {
<ide> var props = keys(properties);
<ide> var propertyName;
<ide> export default function setProperties(obj, properties) {
<ide> set(obj, propertyName, properties[propertyName]);
<ide> }
<ide> });
<del> return obj;
<add> return properties;
<ide> }
<ide><path>packages/ember-runtime/lib/mixins/observable.js
<ide> export default Mixin.create({
<ide> incrementProperty(keyName, increment) {
<ide> if (isNone(increment)) { increment = 1; }
<ide> Ember.assert("Must pass a numeric value to incrementProperty", (!isNaN(parseFloat(increment)) && isFinite(increment)));
<del> set(this, keyName, (parseFloat(get(this, keyName)) || 0) + increment);
<del> return get(this, keyName);
<add> return set(this, keyName, (parseFloat(get(this, keyName)) || 0) + increment);
<ide> },
<ide>
<ide> /**
<ide> export default Mixin.create({
<ide> decrementProperty(keyName, decrement) {
<ide> if (isNone(decrement)) { decrement = 1; }
<ide> Ember.assert("Must pass a numeric value to decrementProperty", (!isNaN(parseFloat(decrement)) && isFinite(decrement)));
<del> set(this, keyName, (get(this, keyName) || 0) - decrement);
<del> return get(this, keyName);
<add> return set(this, keyName, (get(this, keyName) || 0) - decrement);
<ide> },
<ide>
<ide> /**
<ide> export default Mixin.create({
<ide> @public
<ide> */
<ide> toggleProperty(keyName) {
<del> set(this, keyName, !get(this, keyName));
<del> return get(this, keyName);
<add> return set(this, keyName, !get(this, keyName));
<ide> },
<ide>
<ide> /** | 2 |
Text | Text | add v3.4.0-beta.1 to changelog | 1cbd034ce0c7f0c26970b9923d17b51c00c9ea53 | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### v3.4.0-beta.1 (July 16, 2018)
<add>
<add>- [#16773](https://github.com/emberjs/ember.js/pull/16773) [FEATURE] Custom component manager (see [emberjs/rfcs#213](https://github.com/emberjs/rfcs/blob/master/text/0213-custom-components.md) for more details)
<add>- [#16708](https://github.com/emberjs/ember.js/pull/16708) [FEATURE] Angle bracket component invocation (see [emberjs/rfcs#311](https://github.com/emberjs/rfcs/blob/master/text/0311-angle-bracket-invocation.md) for more details)
<add>- [#16744](https://github.com/emberjs/ember.js/pull/16744) [DEPRECATION] Deprecate `component#sendAction` (see [emberjs/rfcs#335](https://github.com/emberjs/rfcs/blob/master/text/0335-deprecate-send-action.md) for more details)
<add>- [#16720](https://github.com/emberjs/ember.js/pull/16720) Upgrade `backburner.js` to 2.3.0
<add>- [#16783](https://github.com/emberjs/ember.js/pull/16783) [BUGFIX] Allow setting length on ArrayProxy.
<add>- [#16785](https://github.com/emberjs/ember.js/pull/16785) [BUGFIX] Ensure `ArrayMixin#invoke` returns an Ember.A.
<add>- [#16784](https://github.com/emberjs/ember.js/pull/16784) [BUGFIX] Setting ArrayProxy#content in willDestroy resets length.
<add>- [#16794](https://github.com/emberjs/ember.js/pull/16794) [BUGFIX] Fix instance-initializer-test blueprint for new QUnit testing API ([emberjs/rfcs#232](https://github.com/emberjs/rfcs/pull/232))
<add>- [#16797](https://github.com/emberjs/ember.js/pull/16797) [BUGFIX] Drop autorun assertion
<add>
<ide> ### v3.3.0 (July 16, 2018)
<ide>
<ide> - [#16687](https://github.com/emberjs/ember.js/pull/16687) [FEATURE] Implement optional jQuery integration (see [emberjs/rfcs#294](https://github.com/emberjs/rfcs/blob/master/text/0294-optional-jquery.md) for more details). | 1 |
Go | Go | fix the lookup method | 5e6355d1828441fe6d5ff4cd814825e05213b2c9 | <ide><path>registry.go
<ide> func (graph *Graph) getRemoteHistory(imgId string, authConfig *auth.AuthConfig)
<ide>
<ide> // Check if an image exists in the Registry
<ide> func (graph *Graph) LookupRemoteImage(imgId string, authConfig *auth.AuthConfig) bool {
<del> client := &http.Client{}
<add> rt := &http.Transport{Proxy: http.ProxyFromEnvironment}
<ide>
<ide> req, err := http.NewRequest("GET", REGISTRY_ENDPOINT+"/images/"+imgId+"/json", nil)
<ide> if err != nil {
<ide> return false
<ide> }
<ide> req.SetBasicAuth(authConfig.Username, authConfig.Password)
<del> res, err := client.Do(req)
<add> res, err := rt.RoundTrip(req)
<ide> if err != nil || res.StatusCode != 307 {
<ide> return false
<ide> } | 1 |
PHP | PHP | fix typeerror on php 8 | fb875af10e533faef59200d3e8ee5758d614a6be | <ide><path>src/Utility/Text.php
<ide> public static function insert(string $str, array $data, array $options = []): st
<ide> /** @var array<string, mixed> $dataReplacements */
<ide> $dataReplacements = array_combine($hashKeys, array_values($data));
<ide> foreach ($dataReplacements as $tmpHash => $tmpValue) {
<del> $tmpValue = is_array($tmpValue) ? '' : $tmpValue;
<add> $tmpValue = is_array($tmpValue) ? '' : (string)$tmpValue;
<ide> $str = str_replace($tmpHash, $tmpValue, $str);
<ide> }
<ide> | 1 |
PHP | PHP | add test coverage | cea3c049780b12a9af57f9d33ef02ec5316c7b32 | <ide><path>tests/TestCase/Core/FunctionsTest.php
<ide> public function testEnv()
<ide> $_ENV['ZERO'] = '0';
<ide> $this->assertSame('0', env('ZERO'));
<ide> $this->assertSame('0', env('ZERO', '1'));
<add>
<add> $this->assertSame('', env('DOCUMENT_ROOT'));
<add> $this->assertSame('vendor/bin/phpunit', env('PHP_SELF'));
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/Database/Driver/MysqlTest.php
<ide> public function testConnectionConfigCustom()
<ide> $driver->connect($config);
<ide> }
<ide>
<add> /**
<add> * Test schema
<add> *
<add> * @return void
<add> */
<add> public function testSchema()
<add> {
<add> $connection = ConnectionManager::get('test');
<add> $config = ConnectionManager::getConfig('test');
<add> $this->assertEquals($config['database'], $connection->getDriver()->schema());
<add> }
<add>
<ide> /**
<ide> * Test isConnected
<ide> *
<ide><path>tests/TestCase/Network/SocketTest.php
<ide> public function testConstruct()
<ide> $this->assertSame($this->Socket->getConfig(), $config);
<ide> }
<ide>
<add> /**
<add> * test host() method
<add> *
<add> * @return void
<add> */
<add> public function testHost()
<add> {
<add> $this->Socket = new Socket();
<add> $this->assertSame('localhost', $this->Socket->host());
<add>
<add> $this->Socket = new Socket(['host' => '8.8.8.8']);
<add> $this->assertSame('dns.google', $this->Socket->host());
<add> }
<add>
<add> /**
<add> * test addresses() method
<add> *
<add> * @return void
<add> */
<add> public function testAddreses()
<add> {
<add> $this->Socket = new Socket();
<add> $this->assertSame(['127.0.0.1'], $this->Socket->addresses());
<add>
<add> $this->Socket = new Socket(['host' => '8.8.8.8']);
<add> $this->assertSame(['8.8.8.8'], $this->Socket->addresses());
<add> }
<add>
<ide> /**
<ide> * testSocketConnection method
<ide> * | 3 |
Text | Text | add es6 code example in util.md | 9a91ffbbdeca0f82e496c5f6b095c863ca778c8a | <ide><path>doc/api/util.md
<ide> stream.on('data', (data) => {
<ide> stream.write('It works!'); // Received data: "It works!"
<ide> ```
<ide>
<add>ES6 example using `class` and `extends`
<add>
<add>```js
<add>const util = require('util');
<add>const EventEmitter = require('events');
<add>
<add>class MyStream extends EventEmitter {
<add> constructor() {
<add> super();
<add> }
<add> write(data) {
<add> this.emit('data', data);
<add> }
<add>}
<add>
<add>const stream = new MyStream();
<add>
<add>stream.on('data', (data) => {
<add> console.log(`Received data: "${data}"`);
<add>});
<add>stream.write('With ES6');
<add>
<add>```
<add>
<ide> ## util.inspect(object[, options])
<ide>
<ide> * `object` {any} Any JavaScript primitive or Object. | 1 |
Python | Python | fix crash when python interpreter not on path. | e4ab5a8608553787154d2e5c4916c00a582c47ba | <ide><path>official/recommendation/popen_helper.py
<ide> """Helper file for running the async data generation process in OSS."""
<ide>
<ide> import os
<del>import six
<add>import sys
<ide>
<ide>
<del>_PYTHON = "python3" if six.PY3 else "python2"
<add>_PYTHON = sys.executable
<add>if not _PYTHON:
<add> raise RuntimeError("Could not find path to Python interpreter in order to "
<add> "spawn subprocesses.")
<ide>
<ide> _ASYNC_GEN_PATH = os.path.join(os.path.dirname(__file__),
<ide> "data_async_generation.py") | 1 |
PHP | PHP | tokenize bug for a single enclosed item, closes | 6f64efb3424d83e98ae4073cf90723686d11eb4a | <ide><path>cake/libs/string.php
<ide> function tokenize($data, $separator = ',', $leftBound = '(', $rightBound = ')')
<ide> }
<ide> if ($data{$tmpOffset} == $leftBound) {
<ide> $depth++;
<del> }
<del> if ($data{$tmpOffset} == $rightBound) {
<add> } elseif ($data{$tmpOffset} == $rightBound) {
<ide> $depth--;
<ide> }
<ide> $offset = ++$tmpOffset;
<ide><path>cake/tests/cases/libs/string.test.php
<ide> function testInsert() {
<ide> $result = String::insert($string, array('b' => 2, 'c' => 3), array('clean' => true));
<ide> $this->assertEqual($result, $expected);
<ide> }
<add>
<add> function testTokenize() {
<add> $result = String::tokenize('A,(short,boring test)');
<add> $expected = array('A', '(short,boring test)');
<add> $this->assertEqual($result, $expected);
<add>
<add> $result = String::tokenize('A,(short,more interesting( test)');
<add> $expected = array('A', '(short,more interesting( test)');
<add> $this->assertEqual($result, $expected);
<add>
<add> $result = String::tokenize('A,(short,very interesting( test))');
<add> $expected = array('A', '(short,very interesting( test))');
<add> $this->assertEqual($result, $expected);
<add>
<add> $result = String::tokenize('"single tag"', ' ', '"', '"');
<add> $expected = array('"single tag"');
<add> $this->assertEqual($expected, $result);
<add> }
<ide> }
<ide> ?>
<ide>\ No newline at end of file | 2 |
Java | Java | add error customizer for react native android | 0c234c90a2b831eb0f3e054de17fa26a4cee7934 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/devsupport/DevSupportManagerImpl.java
<ide> import android.hardware.SensorManager;
<ide> import android.net.Uri;
<ide> import android.os.AsyncTask;
<add>import android.util.Pair;
<ide> import android.widget.Toast;
<ide> import com.facebook.common.logging.FLog;
<ide> import com.facebook.debug.holder.PrinterHolder;
<ide> import com.facebook.react.devsupport.interfaces.DevBundleDownloadListener;
<ide> import com.facebook.react.devsupport.interfaces.DevOptionHandler;
<ide> import com.facebook.react.devsupport.interfaces.DevSupportManager;
<add>import com.facebook.react.devsupport.interfaces.ErrorCustomizer;
<ide> import com.facebook.react.devsupport.interfaces.PackagerStatusCallback;
<ide> import com.facebook.react.devsupport.interfaces.StackFrame;
<ide> import com.facebook.react.modules.debug.interfaces.DeveloperSettings;
<ide> import java.io.IOException;
<ide> import java.net.MalformedURLException;
<ide> import java.net.URL;
<add>import java.util.ArrayList;
<ide> import java.util.LinkedHashMap;
<ide> import java.util.List;
<ide> import java.util.Locale;
<ide> private static enum ErrorType {
<ide> private int mLastErrorCookie = 0;
<ide> private @Nullable ErrorType mLastErrorType;
<ide> private @Nullable DevBundleDownloadListener mBundleDownloadListener;
<add> private @Nullable List<ErrorCustomizer> mErrorCustomizers;
<ide>
<ide> private static class JscProfileTask extends AsyncTask<String, Void, Void> {
<ide> private static final MediaType JSON =
<ide> public void showNewJSError(String message, ReadableArray details, int errorCooki
<ide> showNewError(message, StackTraceHelper.convertJsStackTrace(details), errorCookie, ErrorType.JS);
<ide> }
<ide>
<add> @Override
<add> public void registerErrorCustomizer(ErrorCustomizer errorCustomizer){
<add> if (mErrorCustomizers == null){
<add> mErrorCustomizers = new ArrayList<>();
<add> }
<add> mErrorCustomizers.add(errorCustomizer);
<add> }
<add>
<add> private Pair<String, StackFrame[]> processErrorCustomizers(
<add> Pair<String, StackFrame[]> errorInfo) {
<add> if (mErrorCustomizers == null) {
<add> return errorInfo;
<add> } else {
<add> for (ErrorCustomizer errorCustomizer : mErrorCustomizers) {
<add> Pair<String, StackFrame[]> result = errorCustomizer.customizeErrorInfo(errorInfo);
<add> if (result != null) {
<add> errorInfo = result;
<add> }
<add> }
<add> return errorInfo;
<add> }
<add> }
<add>
<ide> @Override
<ide> public void updateJSError(
<ide> final String message,
<ide> public void run() {
<ide> return;
<ide> }
<ide> StackFrame[] stack = StackTraceHelper.convertJsStackTrace(details);
<del> mRedBoxDialog.setExceptionDetails(message, stack);
<add> Pair<String, StackFrame[]> errorInfo =
<add> processErrorCustomizers(Pair.create(message, stack));
<add> mRedBoxDialog.setExceptionDetails(errorInfo.first, errorInfo.second);
<ide> updateLastErrorInfo(message, stack, errorCookie, ErrorType.JS);
<ide> // JS errors are reported here after source mapping.
<ide> if (mRedBoxHandler != null) {
<ide> public void run() {
<ide> // show the first and most actionable one.
<ide> return;
<ide> }
<del> mRedBoxDialog.setExceptionDetails(message, stack);
<add> Pair<String, StackFrame[]> errorInfo = processErrorCustomizers(Pair.create(message, stack));
<add> mRedBoxDialog.setExceptionDetails(errorInfo.first, errorInfo.second);
<ide> updateLastErrorInfo(message, stack, errorCookie, errorType);
<ide> // Only report native errors here. JS errors are reported
<ide> // inside {@link #updateJSError} after source mapping.
<ide><path>ReactAndroid/src/main/java/com/facebook/react/devsupport/DisabledDevSupportManager.java
<ide>
<ide> package com.facebook.react.devsupport;
<ide>
<add>import com.facebook.react.devsupport.interfaces.ErrorCustomizer;
<ide> import javax.annotation.Nullable;
<ide>
<ide> import java.io.File;
<ide> public void isPackagerRunning(PackagerStatusCallback callback) {
<ide> return null;
<ide> }
<ide>
<add> @Override
<add> public void registerErrorCustomizer(ErrorCustomizer errorCustomizer) {
<add>
<add> }
<add>
<ide> @Override
<ide> public void handleException(Exception e) {
<ide> mDefaultNativeModuleCallExceptionHandler.handleException(e);
<ide><path>ReactAndroid/src/main/java/com/facebook/react/devsupport/interfaces/DevSupportManager.java
<ide> public interface DevSupportManager extends NativeModuleCallExceptionHandler {
<ide> final File outputFile);
<ide> @Nullable String getLastErrorTitle();
<ide> @Nullable StackFrame[] getLastErrorStack();
<add> void registerErrorCustomizer(ErrorCustomizer errorCustomizer);
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/devsupport/interfaces/ErrorCustomizer.java
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc. All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>package com.facebook.react.devsupport.interfaces;
<add>
<add>import android.util.Pair;
<add>
<add>/**
<add> * Interface that lets parts of the app process the errors before showing the redbox
<add> */
<add>public interface ErrorCustomizer {
<add>
<add> /**
<add> * The function that need to be registered using {@link DevSupportManager}.registerErrorCustomizer
<add> * and is called before passing the error to the RedBox.
<add> */
<add> Pair<String, StackFrame[]> customizeErrorInfo(Pair<String, StackFrame[]> errorInfo);
<add>} | 4 |
Java | Java | improve cors handling | d27b5d0ab6e8b91a77e272ad57ae83c7d81d810b | <ide><path>spring-web/src/main/java/org/springframework/web/cors/CorsUtils.java
<ide> /*
<del> * Copyright 2002-2015 the original author or authors.
<add> * Copyright 2002-2019 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> import org.springframework.http.HttpHeaders;
<ide> import org.springframework.http.HttpMethod;
<add>import org.springframework.lang.Nullable;
<add>import org.springframework.util.ObjectUtils;
<add>import org.springframework.web.util.UriComponents;
<add>import org.springframework.web.util.UriComponentsBuilder;
<ide>
<ide> /**
<ide> * Utility class for CORS request handling based on the
<ide> public abstract class CorsUtils {
<ide>
<ide> /**
<del> * Returns {@code true} if the request is a valid CORS one.
<add> * Returns {@code true} if the request is a valid CORS one by checking {@code Origin}
<add> * header presence and ensuring that origins are different.
<ide> */
<ide> public static boolean isCorsRequest(HttpServletRequest request) {
<del> return (request.getHeader(HttpHeaders.ORIGIN) != null);
<add> String origin = request.getHeader(HttpHeaders.ORIGIN);
<add> if (origin == null) {
<add> return false;
<add> }
<add> UriComponents originUrl = UriComponentsBuilder.fromOriginHeader(origin).build();
<add> String scheme = request.getScheme();
<add> String host = request.getServerName();
<add> int port = request.getServerPort();
<add> return !(ObjectUtils.nullSafeEquals(scheme, originUrl.getScheme()) &&
<add> ObjectUtils.nullSafeEquals(host, originUrl.getHost()) &&
<add> getPort(scheme, port) == getPort(originUrl.getScheme(), originUrl.getPort()));
<add>
<add> }
<add>
<add> private static int getPort(@Nullable String scheme, int port) {
<add> if (port == -1) {
<add> if ("http".equals(scheme) || "ws".equals(scheme)) {
<add> port = 80;
<add> }
<add> else if ("https".equals(scheme) || "wss".equals(scheme)) {
<add> port = 443;
<add> }
<add> }
<add> return port;
<ide> }
<ide>
<ide> /**
<ide> * Returns {@code true} if the request is a valid CORS pre-flight one.
<add> * To be used in combination with {@link #isCorsRequest(HttpServletRequest)} since
<add> * regular CORS checks are not invoked here for performance reasons.
<ide> */
<ide> public static boolean isPreFlightRequest(HttpServletRequest request) {
<del> return (isCorsRequest(request) && HttpMethod.OPTIONS.matches(request.getMethod()) &&
<add> return (HttpMethod.OPTIONS.matches(request.getMethod()) &&
<ide> request.getHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD) != null);
<ide> }
<ide>
<ide><path>spring-web/src/main/java/org/springframework/web/cors/DefaultCorsProcessor.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2019 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import java.io.IOException;
<ide> import java.nio.charset.StandardCharsets;
<ide> import java.util.ArrayList;
<del>import java.util.Arrays;
<ide> import java.util.List;
<ide> import javax.servlet.http.HttpServletRequest;
<ide> import javax.servlet.http.HttpServletResponse;
<ide> import org.springframework.http.server.ServletServerHttpResponse;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.CollectionUtils;
<del>import org.springframework.web.util.WebUtils;
<ide>
<ide> /**
<ide> * The default implementation of {@link CorsProcessor}, as defined by the
<ide> * <p>Note that when input {@link CorsConfiguration} is {@code null}, this
<ide> * implementation does not reject simple or actual requests outright but simply
<ide> * avoid adding CORS headers to the response. CORS processing is also skipped
<del> * if the response already contains CORS headers, or if the request is detected
<del> * as a same-origin one.
<add> * if the response already contains CORS headers.
<ide> *
<ide> * @author Sebastien Deleuze
<ide> * @author Rossen Stoyanchev
<ide> public class DefaultCorsProcessor implements CorsProcessor {
<ide> public boolean processRequest(@Nullable CorsConfiguration config, HttpServletRequest request,
<ide> HttpServletResponse response) throws IOException {
<ide>
<add> response.addHeader(HttpHeaders.VARY, HttpHeaders.ORIGIN);
<add> response.addHeader(HttpHeaders.VARY, HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD);
<add> response.addHeader(HttpHeaders.VARY, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS);
<add>
<ide> if (!CorsUtils.isCorsRequest(request)) {
<ide> return true;
<ide> }
<ide>
<del> ServletServerHttpResponse serverResponse = new ServletServerHttpResponse(response);
<del> if (responseHasCors(serverResponse)) {
<add> if (response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN) != null) {
<ide> logger.trace("Skip: response already contains \"Access-Control-Allow-Origin\"");
<ide> return true;
<ide> }
<ide>
<del> ServletServerHttpRequest serverRequest = new ServletServerHttpRequest(request);
<del> if (WebUtils.isSameOrigin(serverRequest)) {
<del> logger.trace("Skip: request is from same origin");
<del> return true;
<del> }
<del>
<ide> boolean preFlightRequest = CorsUtils.isPreFlightRequest(request);
<ide> if (config == null) {
<ide> if (preFlightRequest) {
<del> rejectRequest(serverResponse);
<add> rejectRequest(new ServletServerHttpResponse(response));
<ide> return false;
<ide> }
<ide> else {
<ide> return true;
<ide> }
<ide> }
<ide>
<del> return handleInternal(serverRequest, serverResponse, config, preFlightRequest);
<del> }
<del>
<del> private boolean responseHasCors(ServerHttpResponse response) {
<del> try {
<del> return (response.getHeaders().getAccessControlAllowOrigin() != null);
<del> }
<del> catch (NullPointerException npe) {
<del> // SPR-11919 and https://issues.jboss.org/browse/WFLY-3474
<del> return false;
<del> }
<add> return handleInternal(new ServletServerHttpRequest(request), new ServletServerHttpResponse(response), config, preFlightRequest);
<ide> }
<ide>
<ide> /**
<ide> private boolean responseHasCors(ServerHttpResponse response) {
<ide> protected void rejectRequest(ServerHttpResponse response) throws IOException {
<ide> response.setStatusCode(HttpStatus.FORBIDDEN);
<ide> response.getBody().write("Invalid CORS request".getBytes(StandardCharsets.UTF_8));
<add> response.flush();
<ide> }
<ide>
<ide> /**
<ide> protected boolean handleInternal(ServerHttpRequest request, ServerHttpResponse r
<ide> String allowOrigin = checkOrigin(config, requestOrigin);
<ide> HttpHeaders responseHeaders = response.getHeaders();
<ide>
<del> responseHeaders.addAll(HttpHeaders.VARY, Arrays.asList(HttpHeaders.ORIGIN,
<del> HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS));
<del>
<ide> if (allowOrigin == null) {
<ide> logger.debug("Reject: '" + requestOrigin + "' origin is not allowed");
<ide> rejectRequest(response);
<ide><path>spring-web/src/main/java/org/springframework/web/cors/reactive/CorsUtils.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2019 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public abstract class CorsUtils {
<ide>
<ide> /**
<del> * Returns {@code true} if the request is a valid CORS one.
<add> * Returns {@code true} if the request is a valid CORS one by checking {@code Origin}
<add> * header presence and ensuring that origins are different via {@link #isSameOrigin}.
<ide> */
<add> @SuppressWarnings("deprecation")
<ide> public static boolean isCorsRequest(ServerHttpRequest request) {
<del> return (request.getHeaders().get(HttpHeaders.ORIGIN) != null);
<add> return request.getHeaders().containsKey(HttpHeaders.ORIGIN) && !isSameOrigin(request);
<ide> }
<ide>
<ide> /**
<ide> * Returns {@code true} if the request is a valid CORS pre-flight one.
<add> * To be used in combination with {@link #isCorsRequest(ServerHttpRequest)} since
<add> * regular CORS checks are not invoked here for performance reasons.
<ide> */
<ide> public static boolean isPreFlightRequest(ServerHttpRequest request) {
<del> return (request.getMethod() == HttpMethod.OPTIONS && isCorsRequest(request) &&
<del> request.getHeaders().get(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD) != null);
<add> return (request.getMethod() == HttpMethod.OPTIONS && request.getHeaders().containsKey(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD));
<ide> }
<ide>
<ide> /**
<ide> public static boolean isPreFlightRequest(ServerHttpRequest request) {
<ide> *
<ide> * @return {@code true} if the request is a same-origin one, {@code false} in case
<ide> * of a cross-origin request
<add> * @deprecated as of 5.2, same-origin checks are performed directly by {@link #isCorsRequest}
<ide> */
<add> @Deprecated
<ide> public static boolean isSameOrigin(ServerHttpRequest request) {
<ide> String origin = request.getHeaders().getOrigin();
<ide> if (origin == null) {
<ide><path>spring-web/src/main/java/org/springframework/web/cors/reactive/CorsWebFilter.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2019 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public CorsWebFilter(CorsConfigurationSource configSource, CorsProcessor process
<ide> @Override
<ide> public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
<ide> ServerHttpRequest request = exchange.getRequest();
<del> if (CorsUtils.isCorsRequest(request)) {
<del> CorsConfiguration corsConfiguration = this.configSource.getCorsConfiguration(exchange);
<del> if (corsConfiguration != null) {
<del> boolean isValid = this.processor.process(corsConfiguration, exchange);
<del> if (!isValid || CorsUtils.isPreFlightRequest(request)) {
<del> return Mono.empty();
<del> }
<del> }
<add> CorsConfiguration corsConfiguration = this.configSource.getCorsConfiguration(exchange);
<add> boolean isValid = this.processor.process(corsConfiguration, exchange);
<add> if (!isValid || CorsUtils.isPreFlightRequest(request)) {
<add> return Mono.empty();
<ide> }
<ide> return chain.filter(exchange);
<ide> }
<ide><path>spring-web/src/main/java/org/springframework/web/cors/reactive/DefaultCorsProcessor.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2019 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> * <p>Note that when input {@link CorsConfiguration} is {@code null}, this
<ide> * implementation does not reject simple or actual requests outright but simply
<ide> * avoid adding CORS headers to the response. CORS processing is also skipped
<del> * if the response already contains CORS headers, or if the request is detected
<del> * as a same-origin one.
<add> * if the response already contains CORS headers.
<ide> *
<ide> * @author Sebastien Deleuze
<ide> * @author Rossen Stoyanchev
<ide> public class DefaultCorsProcessor implements CorsProcessor {
<ide>
<ide> private static final Log logger = LogFactory.getLog(DefaultCorsProcessor.class);
<ide>
<add> private static final List<String> VARY_HEADERS = Arrays.asList(
<add> HttpHeaders.ORIGIN, HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS);
<add>
<ide>
<ide> @Override
<ide> public boolean process(@Nullable CorsConfiguration config, ServerWebExchange exchange) {
<ide>
<ide> ServerHttpRequest request = exchange.getRequest();
<ide> ServerHttpResponse response = exchange.getResponse();
<add> response.getHeaders().addAll(HttpHeaders.VARY, VARY_HEADERS);
<ide>
<ide> if (!CorsUtils.isCorsRequest(request)) {
<ide> return true;
<ide> }
<ide>
<del> if (responseHasCors(response)) {
<add> if (response.getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN) != null) {
<ide> logger.trace("Skip: response already contains \"Access-Control-Allow-Origin\"");
<ide> return true;
<ide> }
<ide>
<del> if (CorsUtils.isSameOrigin(request)) {
<del> logger.trace("Skip: request is from same origin");
<del> return true;
<del> }
<del>
<ide> boolean preFlightRequest = CorsUtils.isPreFlightRequest(request);
<ide> if (config == null) {
<ide> if (preFlightRequest) {
<ide> public boolean process(@Nullable CorsConfiguration config, ServerWebExchange exc
<ide> return handleInternal(exchange, config, preFlightRequest);
<ide> }
<ide>
<del> private boolean responseHasCors(ServerHttpResponse response) {
<del> return response.getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN) != null;
<del> }
<del>
<ide> /**
<ide> * Invoked when one of the CORS checks failed.
<ide> */
<ide> protected boolean handleInternal(ServerWebExchange exchange,
<ide> ServerHttpResponse response = exchange.getResponse();
<ide> HttpHeaders responseHeaders = response.getHeaders();
<ide>
<del> response.getHeaders().addAll(HttpHeaders.VARY, Arrays.asList(HttpHeaders.ORIGIN,
<del> HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS));
<del>
<ide> String requestOrigin = request.getHeaders().getOrigin();
<ide> String allowOrigin = checkOrigin(config, requestOrigin);
<ide> if (allowOrigin == null) {
<ide><path>spring-web/src/main/java/org/springframework/web/filter/CorsFilter.java
<ide> /*
<del> * Copyright 2002-2016 the original author or authors.
<add> * Copyright 2002-2019 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public void setCorsProcessor(CorsProcessor processor) {
<ide> protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
<ide> FilterChain filterChain) throws ServletException, IOException {
<ide>
<del> if (CorsUtils.isCorsRequest(request)) {
<del> CorsConfiguration corsConfiguration = this.configSource.getCorsConfiguration(request);
<del> if (corsConfiguration != null) {
<del> boolean isValid = this.processor.processRequest(corsConfiguration, request, response);
<del> if (!isValid || CorsUtils.isPreFlightRequest(request)) {
<del> return;
<del> }
<del> }
<add> CorsConfiguration corsConfiguration = this.configSource.getCorsConfiguration(request);
<add> boolean isValid = this.processor.processRequest(corsConfiguration, request, response);
<add> if (!isValid || CorsUtils.isPreFlightRequest(request)) {
<add> return;
<ide> }
<del>
<ide> filterChain.doFilter(request, response);
<ide> }
<ide>
<ide><path>spring-web/src/test/java/org/springframework/web/cors/CorsUtilsTests.java
<ide> /*
<del> * Copyright 2002-2015 the original author or authors.
<add> * Copyright 2002-2019 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public void isNotPreFlightRequest() {
<ide> request.setMethod(HttpMethod.OPTIONS.name());
<ide> request.addHeader(HttpHeaders.ORIGIN, "https://domain.com");
<ide> assertFalse(CorsUtils.isPreFlightRequest(request));
<del>
<del> request = new MockHttpServletRequest();
<del> request.setMethod(HttpMethod.OPTIONS.name());
<del> request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET");
<del> assertFalse(CorsUtils.isPreFlightRequest(request));
<ide> }
<ide>
<ide> }
<ide><path>spring-web/src/test/java/org/springframework/web/cors/DefaultCorsProcessorTests.java
<ide> public class DefaultCorsProcessorTests {
<ide> public void setup() {
<ide> this.request = new MockHttpServletRequest();
<ide> this.request.setRequestURI("/test.html");
<del> this.request.setRemoteHost("domain1.com");
<add> this.request.setServerName("domain1.com");
<ide> this.conf = new CorsConfiguration();
<ide> this.response = new MockHttpServletResponse();
<ide> this.response.setStatus(HttpServletResponse.SC_OK);
<ide> this.processor = new DefaultCorsProcessor();
<ide> }
<ide>
<add> @Test
<add> public void requestWithoutOriginHeader() throws Exception {
<add> this.request.setMethod(HttpMethod.GET.name());
<add>
<add> this.processor.processRequest(this.conf, this.request, this.response);
<add> assertFalse(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
<add> assertThat(this.response.getHeaders(HttpHeaders.VARY), contains(HttpHeaders.ORIGIN,
<add> HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS));
<add> assertEquals(HttpServletResponse.SC_OK, this.response.getStatus());
<add> }
<add>
<add> @Test
<add> public void sameOriginRequest() throws Exception {
<add> this.request.setMethod(HttpMethod.GET.name());
<add> this.request.addHeader(HttpHeaders.ORIGIN, "http://domain1.com");
<add>
<add> this.processor.processRequest(this.conf, this.request, this.response);
<add> assertFalse(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
<add> assertThat(this.response.getHeaders(HttpHeaders.VARY), contains(HttpHeaders.ORIGIN,
<add> HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS));
<add> assertEquals(HttpServletResponse.SC_OK, this.response.getStatus());
<add> }
<ide>
<ide> @Test
<ide> public void actualRequestWithOriginHeader() throws Exception {
<ide><path>spring-web/src/test/java/org/springframework/web/cors/reactive/CorsUtilsTests.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2019 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public class CorsUtilsTests {
<ide>
<ide> @Test
<ide> public void isCorsRequest() {
<del> ServerHttpRequest request = get("/").header(HttpHeaders.ORIGIN, "https://domain.com").build();
<add> ServerHttpRequest request = get("http://domain.com/").header(HttpHeaders.ORIGIN, "https://domain.com").build();
<ide> assertTrue(CorsUtils.isCorsRequest(request));
<ide> }
<ide>
<ide> public void isNotPreFlightRequest() {
<ide>
<ide> request = options("/").header(HttpHeaders.ORIGIN, "https://domain.com").build();
<ide> assertFalse(CorsUtils.isPreFlightRequest(request));
<del>
<del> request = options("/").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET").build();
<del> assertFalse(CorsUtils.isPreFlightRequest(request));
<ide> }
<ide>
<ide> @Test // SPR-16262
<ide><path>spring-web/src/test/java/org/springframework/web/cors/reactive/CorsWebFilterTests.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2019 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public void setup() throws Exception {
<ide> filter = new CorsWebFilter(r -> config);
<ide> }
<ide>
<add> @Test
<add> public void nonCorsRequest() {
<add> WebFilterChain filterChain = (filterExchange) -> {
<add> try {
<add> HttpHeaders headers = filterExchange.getResponse().getHeaders();
<add> assertNull(headers.getFirst(ACCESS_CONTROL_ALLOW_ORIGIN));
<add> assertNull(headers.getFirst(ACCESS_CONTROL_EXPOSE_HEADERS));
<add> } catch (AssertionError ex) {
<add> return Mono.error(ex);
<add> }
<add> return Mono.empty();
<add>
<add> };
<add> MockServerWebExchange exchange = MockServerWebExchange.from(
<add> MockServerHttpRequest
<add> .get("https://domain1.com/test.html")
<add> .header(HOST, "domain1.com"));
<add> this.filter.filter(exchange, filterChain).block();
<add> }
<add>
<add> @Test
<add> public void sameOriginRequest() {
<add> WebFilterChain filterChain = (filterExchange) -> {
<add> try {
<add> HttpHeaders headers = filterExchange.getResponse().getHeaders();
<add> assertNull(headers.getFirst(ACCESS_CONTROL_ALLOW_ORIGIN));
<add> assertNull(headers.getFirst(ACCESS_CONTROL_EXPOSE_HEADERS));
<add> } catch (AssertionError ex) {
<add> return Mono.error(ex);
<add> }
<add> return Mono.empty();
<add>
<add> };
<add> MockServerWebExchange exchange = MockServerWebExchange.from(
<add> MockServerHttpRequest
<add> .get("https://domain1.com/test.html")
<add> .header(ORIGIN, "https://domain1.com"));
<add> this.filter.filter(exchange, filterChain).block();
<add> }
<add>
<ide> @Test
<ide> public void validActualRequest() {
<ide> WebFilterChain filterChain = (filterExchange) -> {
<ide> public void validActualRequest() {
<ide> .header(HOST, "domain1.com")
<ide> .header(ORIGIN, "https://domain2.com")
<ide> .header("header2", "foo"));
<del> this.filter.filter(exchange, filterChain);
<add> this.filter.filter(exchange, filterChain).block();
<ide> }
<ide>
<ide> @Test
<ide> public void invalidActualRequest() throws ServletException, IOException {
<ide>
<ide> WebFilterChain filterChain = (filterExchange) -> Mono.error(
<ide> new AssertionError("Invalid requests must not be forwarded to the filter chain"));
<del> filter.filter(exchange, filterChain);
<del>
<add> filter.filter(exchange, filterChain).block();
<ide> assertNull(exchange.getResponse().getHeaders().getFirst(ACCESS_CONTROL_ALLOW_ORIGIN));
<ide> }
<ide>
<ide> public void validPreFlightRequest() throws ServletException, IOException {
<ide>
<ide> WebFilterChain filterChain = (filterExchange) -> Mono.error(
<ide> new AssertionError("Preflight requests must not be forwarded to the filter chain"));
<del> filter.filter(exchange, filterChain);
<add> filter.filter(exchange, filterChain).block();
<ide>
<ide> HttpHeaders headers = exchange.getResponse().getHeaders();
<ide> assertEquals("https://domain2.com", headers.getFirst(ACCESS_CONTROL_ALLOW_ORIGIN));
<ide> public void invalidPreFlightRequest() throws ServletException, IOException {
<ide> WebFilterChain filterChain = (filterExchange) -> Mono.error(
<ide> new AssertionError("Preflight requests must not be forwarded to the filter chain"));
<ide>
<del> filter.filter(exchange, filterChain);
<add> filter.filter(exchange, filterChain).block();
<ide>
<ide> assertNull(exchange.getResponse().getHeaders().getFirst(ACCESS_CONTROL_ALLOW_ORIGIN));
<ide> }
<ide><path>spring-web/src/test/java/org/springframework/web/cors/reactive/DefaultCorsProcessorTests.java
<ide> public void setup() {
<ide> }
<ide>
<ide>
<add> @Test
<add> public void requestWithoutOriginHeader() throws Exception {
<add> MockServerHttpRequest request = MockServerHttpRequest
<add> .method(HttpMethod.GET, "http://domain1.com/test.html")
<add> .build();
<add> ServerWebExchange exchange = MockServerWebExchange.from(request);
<add> this.processor.process(this.conf, exchange);
<add>
<add> ServerHttpResponse response = exchange.getResponse();
<add> assertFalse(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN));
<add> assertThat(response.getHeaders().get(VARY), contains(ORIGIN,
<add> ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS));
<add> assertNull(response.getStatusCode());
<add> }
<add>
<add> @Test
<add> public void sameOriginRequest() throws Exception {
<add> MockServerHttpRequest request = MockServerHttpRequest
<add> .method(HttpMethod.GET, "http://domain1.com/test.html")
<add> .header(HttpHeaders.ORIGIN, "http://domain1.com")
<add> .build();
<add> ServerWebExchange exchange = MockServerWebExchange.from(request);
<add> this.processor.process(this.conf, exchange);
<add>
<add> ServerHttpResponse response = exchange.getResponse();
<add> assertFalse(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN));
<add> assertThat(response.getHeaders().get(VARY), contains(ORIGIN,
<add> ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS));
<add> assertNull(response.getStatusCode());
<add> }
<add>
<ide> @Test
<ide> public void actualRequestWithOriginHeader() throws Exception {
<ide> ServerWebExchange exchange = actualRequest();
<ide><path>spring-web/src/test/java/org/springframework/web/filter/CorsFilterTests.java
<ide> /*
<del> * Copyright 2002-2015 the original author or authors.
<add> * Copyright 2002-2019 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public void setup() throws Exception {
<ide> filter = new CorsFilter(r -> config);
<ide> }
<ide>
<add> @Test
<add> public void nonCorsRequest() throws ServletException, IOException {
<add>
<add> MockHttpServletRequest request = new MockHttpServletRequest(HttpMethod.GET.name(), "/test.html");
<add> MockHttpServletResponse response = new MockHttpServletResponse();
<add>
<add> FilterChain filterChain = (filterRequest, filterResponse) -> {
<add> assertNull(response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
<add> assertNull(response.getHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS));
<add> };
<add> filter.doFilter(request, response, filterChain);
<add> }
<add>
<add> @Test
<add> public void sameOriginRequest() throws ServletException, IOException {
<add>
<add> MockHttpServletRequest request = new MockHttpServletRequest(HttpMethod.GET.name(), "https://domain1.com/test.html");
<add> request.addHeader(HttpHeaders.ORIGIN, "https://domain1.com");
<add> request.setScheme("https");
<add> request.setServerName("domain1.com");
<add> request.setServerPort(443);
<add> MockHttpServletResponse response = new MockHttpServletResponse();
<add>
<add> FilterChain filterChain = (filterRequest, filterResponse) -> {
<add> assertNull(response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
<add> assertNull(response.getHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS));
<add> };
<add> filter.doFilter(request, response, filterChain);
<add> }
<add>
<ide> @Test
<ide> public void validActualRequest() throws ServletException, IOException {
<ide>
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/handler/AbstractHandlerMapping.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2019 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import org.springframework.beans.factory.BeanNameAware;
<ide> import org.springframework.context.support.ApplicationObjectSupport;
<ide> import org.springframework.core.Ordered;
<add>import org.springframework.http.server.reactive.ServerHttpRequest;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.web.cors.CorsConfiguration;
<ide> public abstract class AbstractHandlerMapping extends ApplicationObjectSupport
<ide>
<ide> private final PathPatternParser patternParser;
<ide>
<add> @Nullable
<ide> private CorsConfigurationSource corsConfigurationSource;
<ide>
<ide> private CorsProcessor corsProcessor = new DefaultCorsProcessor();
<ide> public abstract class AbstractHandlerMapping extends ApplicationObjectSupport
<ide>
<ide> public AbstractHandlerMapping() {
<ide> this.patternParser = new PathPatternParser();
<del> this.corsConfigurationSource = new UrlBasedCorsConfigurationSource(this.patternParser);
<ide> }
<ide>
<ide>
<ide> public PathPatternParser getPathPatternParser() {
<ide> */
<ide> public void setCorsConfigurations(Map<String, CorsConfiguration> corsConfigurations) {
<ide> Assert.notNull(corsConfigurations, "corsConfigurations must not be null");
<del> this.corsConfigurationSource = new UrlBasedCorsConfigurationSource(this.patternParser);
<del> ((UrlBasedCorsConfigurationSource) this.corsConfigurationSource).setCorsConfigurations(corsConfigurations);
<add> if (!corsConfigurations.isEmpty()) {
<add> UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(this.patternParser);
<add> source.setCorsConfigurations(corsConfigurations);
<add> this.corsConfigurationSource = source;
<add> }
<add> else {
<add> this.corsConfigurationSource = null;
<add> }
<ide> }
<ide>
<ide> /**
<ide> public Mono<Object> getHandler(ServerWebExchange exchange) {
<ide> if (logger.isDebugEnabled()) {
<ide> logger.debug(exchange.getLogPrefix() + "Mapped to " + handler);
<ide> }
<del> if (CorsUtils.isCorsRequest(exchange.getRequest())) {
<del> CorsConfiguration configA = this.corsConfigurationSource.getCorsConfiguration(exchange);
<del> CorsConfiguration configB = getCorsConfiguration(handler, exchange);
<del> CorsConfiguration config = (configA != null ? configA.combine(configB) : configB);
<del> if (!getCorsProcessor().process(config, exchange) ||
<del> CorsUtils.isPreFlightRequest(exchange.getRequest())) {
<add> if (hasCorsConfigurationSource(handler)) {
<add> ServerHttpRequest request = exchange.getRequest();
<add> CorsConfiguration config = (this.corsConfigurationSource != null ? this.corsConfigurationSource.getCorsConfiguration(exchange) : null);
<add> CorsConfiguration handlerConfig = getCorsConfiguration(handler, exchange);
<add> config = (config != null ? config.combine(handlerConfig) : handlerConfig);
<add> if (!this.corsProcessor.process(config, exchange) || CorsUtils.isPreFlightRequest(request)) {
<ide> return REQUEST_HANDLED_HANDLER;
<ide> }
<ide> }
<ide> public Mono<Object> getHandler(ServerWebExchange exchange) {
<ide> */
<ide> protected abstract Mono<?> getHandlerInternal(ServerWebExchange exchange);
<ide>
<add> /**
<add> * Return {@code true} if there is a {@link CorsConfigurationSource} for this handler.
<add> * @since 5.2
<add> */
<add> protected boolean hasCorsConfigurationSource(Object handler) {
<add> return handler instanceof CorsConfigurationSource || this.corsConfigurationSource != null;
<add> }
<add>
<ide> /**
<ide> * Retrieve the CORS configuration for the given handler.
<ide> * @param handler the handler to check (never {@code null})
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/method/AbstractHandlerMethodMapping.java
<ide> protected HandlerMethod handleNoMatch(Set<T> mappings, ServerWebExchange exchang
<ide> return null;
<ide> }
<ide>
<add> @Override
<add> protected boolean hasCorsConfigurationSource(Object handler) {
<add> return super.hasCorsConfigurationSource(handler) ||
<add> (handler instanceof HandlerMethod && this.mappingRegistry.getCorsConfiguration((HandlerMethod) handler) != null) ||
<add> handler.equals(PREFLIGHT_AMBIGUOUS_MATCH);
<add> }
<add>
<ide> @Override
<ide> protected CorsConfiguration getCorsConfiguration(Object handler, ServerWebExchange exchange) {
<ide> CorsConfiguration corsConfig = super.getCorsConfiguration(handler, exchange);
<ide> public Map<T, HandlerMethod> getMappings() {
<ide> /**
<ide> * Return CORS configuration. Thread-safe for concurrent use.
<ide> */
<add> @Nullable
<ide> public CorsConfiguration getCorsConfiguration(HandlerMethod handlerMethod) {
<ide> HandlerMethod original = handlerMethod.getResolvedFromHandlerMethod();
<ide> return this.corsLookup.get(original != null ? original : handlerMethod);
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/handler/CorsUrlHandlerMappingTests.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2019 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import static org.junit.Assert.assertEquals;
<ide> import static org.junit.Assert.assertNotNull;
<ide> import static org.junit.Assert.assertNotSame;
<del>import static org.junit.Assert.assertNull;
<ide> import static org.junit.Assert.assertSame;
<ide>
<ide> /**
<ide> public void preflightRequestWithoutCorsConfigurationProvider() throws Exception
<ide> Object actual = this.handlerMapping.getHandler(exchange).block();
<ide>
<ide> assertNotNull(actual);
<del> assertNotSame(this.welcomeController, actual);
<del> assertNull(exchange.getResponse().getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
<add> assertSame(this.welcomeController, actual);
<ide> }
<ide>
<ide> @Test
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMapping.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2019 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public abstract class AbstractHandlerMapping extends WebApplicationObjectSupport
<ide>
<ide> private final List<HandlerInterceptor> adaptedInterceptors = new ArrayList<>();
<ide>
<del> private CorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
<add> @Nullable
<add> private CorsConfigurationSource corsConfigurationSource;
<ide>
<ide> private CorsProcessor corsProcessor = new DefaultCorsProcessor();
<ide>
<ide> public void setInterceptors(Object... interceptors) {
<ide> */
<ide> public void setCorsConfigurations(Map<String, CorsConfiguration> corsConfigurations) {
<ide> Assert.notNull(corsConfigurations, "corsConfigurations must not be null");
<del> UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
<del> source.setCorsConfigurations(corsConfigurations);
<del> source.setPathMatcher(this.pathMatcher);
<del> source.setUrlPathHelper(this.urlPathHelper);
<del> this.corsConfigurationSource = source;
<add> if (!corsConfigurations.isEmpty()) {
<add> UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
<add> source.setCorsConfigurations(corsConfigurations);
<add> source.setPathMatcher(this.pathMatcher);
<add> source.setUrlPathHelper(this.urlPathHelper);
<add> this.corsConfigurationSource = source;
<add> }
<add> else {
<add> this.corsConfigurationSource = null;
<add> }
<ide> }
<ide>
<ide> /**
<ide> else if (logger.isDebugEnabled() && !request.getDispatcherType().equals(Dispatch
<ide> logger.debug("Mapped to " + executionChain.getHandler());
<ide> }
<ide>
<del> if (CorsUtils.isCorsRequest(request)) {
<del> CorsConfiguration globalConfig = this.corsConfigurationSource.getCorsConfiguration(request);
<add> if (hasCorsConfigurationSource(handler)) {
<add> CorsConfiguration config = (this.corsConfigurationSource != null ? this.corsConfigurationSource.getCorsConfiguration(request) : null);
<ide> CorsConfiguration handlerConfig = getCorsConfiguration(handler, request);
<del> CorsConfiguration config = (globalConfig != null ? globalConfig.combine(handlerConfig) : handlerConfig);
<add> config = (config != null ? config.combine(handlerConfig) : handlerConfig);
<ide> executionChain = getCorsHandlerExecutionChain(request, executionChain, config);
<ide> }
<ide>
<ide> protected HandlerExecutionChain getHandlerExecutionChain(Object handler, HttpSer
<ide> return chain;
<ide> }
<ide>
<add> /**
<add> * Return {@code true} if there is a {@link CorsConfigurationSource} for this handler.
<add> * @since 5.2
<add> */
<add> protected boolean hasCorsConfigurationSource(Object handler) {
<add> return handler instanceof CorsConfigurationSource || this.corsConfigurationSource != null;
<add> }
<add>
<ide> /**
<ide> * Retrieve the CORS configuration for the given handler.
<ide> * @param handler the handler to check (never {@code null}).
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMethodMapping.java
<ide> protected HandlerMethod handleNoMatch(Set<T> mappings, String lookupPath, HttpSe
<ide> return null;
<ide> }
<ide>
<add> @Override
<add> protected boolean hasCorsConfigurationSource(Object handler) {
<add> return super.hasCorsConfigurationSource(handler) ||
<add> (handler instanceof HandlerMethod && this.mappingRegistry.getCorsConfiguration((HandlerMethod) handler) != null) ||
<add> handler.equals(PREFLIGHT_AMBIGUOUS_MATCH);
<add> }
<add>
<ide> @Override
<ide> protected CorsConfiguration getCorsConfiguration(Object handler, HttpServletRequest request) {
<ide> CorsConfiguration corsConfig = super.getCorsConfiguration(handler, request);
<ide> public List<HandlerMethod> getHandlerMethodsByMappingName(String mappingName) {
<ide> /**
<ide> * Return CORS configuration. Thread-safe for concurrent use.
<ide> */
<add> @Nullable
<ide> public CorsConfiguration getCorsConfiguration(HandlerMethod handlerMethod) {
<ide> HandlerMethod original = handlerMethod.getResolvedFromHandlerMethod();
<ide> return this.corsLookup.get(original != null ? original : handlerMethod);
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupportExtensionTests.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2019 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public void handlerMappings() throws Exception {
<ide> HandlerExecutionChain chain = rmHandlerMapping.getHandler(new MockHttpServletRequest("GET", "/"));
<ide> assertNotNull(chain);
<ide> assertNotNull(chain.getInterceptors());
<del> assertEquals(3, chain.getInterceptors().length);
<add> assertEquals(4, chain.getInterceptors().length);
<ide> assertEquals(LocaleChangeInterceptor.class, chain.getInterceptors()[0].getClass());
<ide> assertEquals(ConversionServiceExposingInterceptor.class, chain.getInterceptors()[1].getClass());
<ide> assertEquals(ResourceUrlProviderExposingInterceptor.class, chain.getInterceptors()[2].getClass());
<ide> public void handlerMappings() throws Exception {
<ide> chain = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/resources/foo.gif"));
<ide> assertNotNull(chain);
<ide> assertNotNull(chain.getHandler());
<del> assertEquals(Arrays.toString(chain.getInterceptors()), 4, chain.getInterceptors().length);
<add> assertEquals(Arrays.toString(chain.getInterceptors()), 5, chain.getInterceptors().length);
<ide> // PathExposingHandlerInterceptor at chain.getInterceptors()[0]
<ide> assertEquals(LocaleChangeInterceptor.class, chain.getInterceptors()[1].getClass());
<ide> assertEquals(ConversionServiceExposingInterceptor.class, chain.getInterceptors()[2].getClass());
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/handler/CorsAbstractHandlerMappingTests.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2019 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public void preflightRequestWithoutCorsConfigurationProvider() throws Exception
<ide> this.request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET");
<ide> HandlerExecutionChain chain = handlerMapping.getHandler(this.request);
<ide> assertNotNull(chain);
<del> assertNotNull(chain.getHandler());
<del> assertTrue(chain.getHandler().getClass().getSimpleName().equals("PreFlightHandler"));
<add> assertTrue(chain.getHandler() instanceof SimpleHandler);
<ide> }
<ide>
<ide> @Test
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/support/AbstractSockJsService.java
<ide> import org.apache.commons.logging.Log;
<ide> import org.apache.commons.logging.LogFactory;
<ide>
<add>import org.springframework.http.HttpHeaders;
<ide> import org.springframework.http.HttpMethod;
<ide> import org.springframework.http.HttpStatus;
<ide> import org.springframework.http.InvalidMediaTypeException;
<ide> import org.springframework.util.StringUtils;
<ide> import org.springframework.web.cors.CorsConfiguration;
<ide> import org.springframework.web.cors.CorsConfigurationSource;
<del>import org.springframework.web.cors.CorsUtils;
<ide> import org.springframework.web.socket.WebSocketHandler;
<ide> import org.springframework.web.socket.sockjs.SockJsException;
<ide> import org.springframework.web.socket.sockjs.SockJsService;
<ide> protected boolean checkOrigin(ServerHttpRequest request, ServerHttpResponse resp
<ide> @Override
<ide> @Nullable
<ide> public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
<del> if (!this.suppressCors && CorsUtils.isCorsRequest(request)) {
<add> if (!this.suppressCors && (request.getHeader(HttpHeaders.ORIGIN) != null)) {
<ide> CorsConfiguration config = new CorsConfiguration();
<ide> config.setAllowedOrigins(new ArrayList<>(this.allowedOrigins));
<ide> config.addAllowedMethod("*"); | 20 |
Javascript | Javascript | convert root to hoc and add root decorator | e0a00cdba5e5946549293278006f5e014aa8a5a6 | <ide><path>examples/counter/App.js
<ide> import { increment, decrement } from './actions/CounterActions';
<ide> import counterStore from './stores/counterStore';
<ide> import Counter from './Counter';
<ide>
<del>@Root
<del>export default class App extends Component {
<add>export default class CounterApp extends Component {
<ide> render() {
<ide> return (
<del> <Container stores={counterStore}
<del> actions={{ increment, decrement }}>
<del> {props => <Counter {...props} />}
<del> </Container>
<add> <Root>
<add> {() =>
<add> <Container stores={counterStore} actions={{ increment, decrement }}>
<add> {props => <Counter {...props} />}
<add> </Container>
<add> }
<add> </Root>
<ide> );
<ide> }
<ide> }
<ide><path>examples/todo/App.js
<ide> import { Root, Container } from 'redux';
<ide> import { todoStore } from './stores/index';
<ide> import { addTodo } from './actions/index';
<ide>
<del>@Root
<del>export default class App {
<add>export default class TodoApp {
<ide> render() {
<ide> return (
<del> <Container stores={todoStore}
<del> actions={{ addTodo }}>
<del> {props =>
<del> <div>
<del> <Header addTodo={props.addTodo} />
<del> <Body todos={props.todos} />
<del> </div>
<add> <Root>
<add> {() =>
<add> <Container stores={todoStore} actions={{ addTodo }}>
<add> {props =>
<add> <div>
<add> <Header addTodo={props.addTodo} />
<add> <Body todos={props.todos} />
<add> </div>
<add> }
<add> </Container>
<ide> }
<del> </Container>
<add> </Root>
<ide> );
<ide> }
<ide> }
<ide><path>src/Root.js
<del>import React, { Component, PropTypes } from 'react';
<add>import React, { PropTypes } from 'react';
<ide> import createDispatcher from './createDispatcher';
<ide>
<del>export default function root(DecoratedComponent) {
<del> return class ReduxRoot extends Component {
<del> static childContextTypes = {
<del> redux: PropTypes.object.isRequired
<del> };
<add>export default class ReduxRoot {
<add> static propTypes = {
<add> children: PropTypes.func.isRequired
<add> };
<add>
<add> static childContextTypes = {
<add> redux: PropTypes.object.isRequired
<add> };
<ide>
<del> getChildContext() {
<del> return { redux: this.dispatcher };
<del> }
<add> constructor() {
<add> this.dispatcher = createDispatcher();
<add> }
<ide>
<del> constructor(props, context) {
<del> super(props, context);
<del> this.dispatcher = createDispatcher();
<del> }
<add> getChildContext() {
<add> const { observeStores, wrapActionCreator } = this.dispatcher
<add> return {
<add> redux: {
<add> observeStores,
<add> wrapActionCreator
<add> }
<add> };
<add> }
<ide>
<del> render() {
<del> return <DecoratedComponent {...this.props} />;
<del> }
<del> };
<add> render() {
<add> return this.props.children({
<add> ...this.props
<add> });
<add> }
<ide> }
<ide><path>src/decorators/container.js
<add>import React from 'react';
<add>import Container from '../Container';
<add>
<add>export default function container({ actions = {}, stores = [] }) {
<add> return (DecoratedComponent) => {
<add> return class ReduxContainerDecorator {
<add> render() {
<add> return (
<add> <Container actions={actions} stores={stores}>
<add> {props => <DecoratedComponent {...this.props} {...props} />}
<add> </Container>
<add> );
<add> }
<add> };
<add> };
<add>}
<ide><path>src/decorators/root.js
<add>import React from 'react';
<add>import Root from '../Root';
<add>
<add>export default function root(DecoratedComponent) {
<add> return class ReduxRootDecorator {
<add> render() {
<add> return (
<add> <Root>
<add> {props => <DecoratedComponent {...props} />}
<add> </Root>
<add> );
<add> }
<add> }
<add>}
<ide><path>src/index.js
<add>// Higher-order components
<ide> export Root from './Root';
<ide> export Container from './Container';
<add>
<add>// Decorators
<add>export root from './decorators/root';
<add>export container from './decorators/container'; | 6 |
Javascript | Javascript | fix code style | 6bf1339341e99672c37e8b2ba0257d6f47634ec7 | <ide><path>src/objects/InstancedMesh.js
<ide> InstancedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
<ide> },
<ide>
<ide> // updateMorphTargets: function () {
<del> //
<add> //
<ide> // }
<ide>
<ide> } ); | 1 |
Javascript | Javascript | remove unused path from normalmodulefactory | ce5e3e1e8d90c1c8309421b7a89aa7c3ede98ac2 | <ide><path>lib/NormalModuleFactory.js
<ide> Author Tobias Koppers @sokra
<ide> */
<ide> var async = require("async");
<del>var path = require("path");
<ide> var Tapable = require("tapable");
<ide> var NormalModule = require("./NormalModule");
<ide> var RawModule = require("./RawModule"); | 1 |
Javascript | Javascript | remove lodash dependency | 7003366e99ba6b7be80444f70d35abb915634a01 | <ide><path>resources/js/app.js
<ide> Vue.component('example-component', require('./components/ExampleComponent.vue'))
<ide> // const files = require.context('./', true, /\.vue$/i)
<ide>
<ide> // files.keys().map(key => {
<del>// return Vue.component(_.last(key.split('/')).split('.')[0], files(key))
<add>// return Vue.component(key.split('/').pop().split('.')[0], files(key))
<ide> // })
<ide>
<ide> /** | 1 |
Go | Go | fix use of bufio.scanner.err | 745ed9686b7bf09399aa013236b8112e63722dfe | <ide><path>pkg/idtools/idtools.go
<ide> func parseSubidFile(path, username string) (ranges, error) {
<ide>
<ide> s := bufio.NewScanner(subidFile)
<ide> for s.Scan() {
<del> if err := s.Err(); err != nil {
<del> return rangeList, err
<del> }
<del>
<ide> text := strings.TrimSpace(s.Text())
<ide> if text == "" || strings.HasPrefix(text, "#") {
<ide> continue
<ide> func parseSubidFile(path, username string) (ranges, error) {
<ide> rangeList = append(rangeList, subIDRange{startid, length})
<ide> }
<ide> }
<del> return rangeList, nil
<add>
<add> return rangeList, s.Err()
<ide> } | 1 |
Text | Text | add missing permission import in viewsets | ed7f3c55f7647b19ce2358ebce861a0cee8944d5 | <ide><path>docs/tutorial/6-viewsets-and-routers.md
<ide> Next we're going to replace the `SnippetList`, `SnippetDetail` and `SnippetHighl
<ide>
<ide> from rest_framework.decorators import action
<ide> from rest_framework.response import Response
<add> from rest_framework import permissions
<ide>
<ide> class SnippetViewSet(viewsets.ModelViewSet):
<ide> """ | 1 |
Ruby | Ruby | apply suggestions from code review | 3dcfc7e26e663f8378d48aa6a6d48541aea31d9d | <ide><path>Library/Homebrew/tap.rb
<ide> def link_completions_and_manpages
<ide> end
<ide>
<ide> def fix_remote_configuration(requested_remote: nil, quiet: false)
<del> unless requested_remote.nil?
<add> if requested_remote.present?
<ide> path.cd do
<ide> safe_system "git", "remote", "set-url", "origin", requested_remote
<ide> safe_system "git", "config", "remote.origin.fetch", "+refs/heads/*:refs/remotes/origin/*"
<ide> def fix_remote_configuration(requested_remote: nil, quiet: false)
<ide> end
<ide>
<ide> current_upstream_head = path.git_origin_branch
<del> return if requested_remote.nil? && path.git_origin_has_branch?(current_upstream_head)
<add> return if requested_remote.blank? && path.git_origin_has_branch?(current_upstream_head)
<ide>
<ide> args = %w[fetch]
<del> args << "-q" if quiet
<add> args << "--quiet" if quiet
<ide> args << "origin"
<ide> safe_system "git", "-C", path, *args
<ide> path.git_origin_set_head_auto | 1 |
Text | Text | add changelog entry for [ci skip] | 7765ee0e4714b82150e525f9fee80f5b23e91662 | <ide><path>railties/CHANGELOG.md
<ide> ## Rails 4.0.0 (unreleased) ##
<ide>
<del>* Added notice message for destroy action in scaffold generator
<add>* Add notice message for destroy action in scaffold generator.
<ide>
<ide> *Rahul P. Chaudhari*
<ide>
<del>* Add --rc option to support the load of a custom rc file during the generation of a new app.
<add>* Add two new test rake tasks to speed up full test runs.
<add>
<add> * `test:all`: run tests quickly by merging all types and not resetting db.
<add> * `test:all:db`: run tests quickly, but also reset db.
<add>
<add> *Ryan Davis*
<add>
<add>* Add `--rc` option to support the load of a custom rc file during the generation of a new app.
<ide>
<ide> *Amparo Luna*
<ide>
<del>* Add --no-rc option to skip the loading of railsrc file during the generation of a new app.
<del>
<add>* Add `--no-rc` option to skip the loading of railsrc file during the generation of a new app.
<add>
<ide> *Amparo Luna*
<ide>
<ide> * Fixes database.yml when creating a new rails application with '.' | 1 |
Javascript | Javascript | apply pr comments | 1159e247d0c99611b538a3291b52409c6007878c | <ide><path>src/lib/units/year.js
<ide> import toInt from '../utils/to-int';
<ide>
<ide> addFormatToken('Y', 0, 0, function () {
<ide> var y = this.year();
<del> if (y < 0) {
<del> return y;
<del> } else if (y <= 9999) {
<del> return y;
<del> } else {
<del> // force plus for longer years.
<del> return '+' + y;
<del> }
<add> return y <= 9999 ? '' + y : '+' + y;
<ide> });
<ide>
<ide> addFormatToken(0, ['YY', 2], 0, function () {
<ide><path>src/test/moment/format.js
<ide> test('Y token', function (assert) {
<ide> assert.equal(moment('2010-01-01', 'YYYY-MM-DD', true).format('Y'), '2010', 'format 2010 with Y');
<ide> assert.equal(moment('-123-01-01', 'Y-MM-DD', true).format('Y'), '-123', 'format -123 with Y');
<ide> assert.equal(moment('12345-01-01', 'Y-MM-DD', true).format('Y'), '+12345', 'format 12345 with Y');
<add> assert.equal(moment('0-01-01', 'Y-MM-DD', true).format('Y'), '0', 'format 0 with Y');
<add> assert.equal(moment('1-01-01', 'Y-MM-DD', true).format('Y'), '1', 'format 1 with Y');
<add> assert.equal(moment('9999-01-01', 'Y-MM-DD', true).format('Y'), '9999', 'format 9999 with Y');
<add> assert.equal(moment('10000-01-01', 'Y-MM-DD', true).format('Y'), '+10000', 'format 10000 with Y');
<ide> }); | 2 |
Javascript | Javascript | add pointer events to text view config | 01492296d2643e8d8440b08a629a94a2d7905c9a | <ide><path>Libraries/Text/TextNativeComponent.js
<ide> * @format
<ide> */
<ide>
<del>import ReactNativeViewAttributes from '../Components/View/ReactNativeViewAttributes';
<ide> import UIManager from '../ReactNative/UIManager';
<ide> import {type HostComponent} from '../Renderer/shims/ReactNativeTypes';
<ide> import createReactNativeComponentClass from '../Renderer/shims/createReactNativeComponentClass';
<ide> import {type ProcessedColorValue} from '../StyleSheet/processColor';
<ide> import {type TextProps} from './TextProps';
<ide> import {type PressEvent} from '../Types/CoreEventTypes';
<add>import {createViewConfig} from '../NativeComponent/ViewConfig';
<ide>
<ide> type NativeTextProps = $ReadOnly<{
<ide> ...TextProps,
<ide> type NativeTextProps = $ReadOnly<{
<ide> isPressable?: ?boolean,
<ide> }>;
<ide>
<del>export const NativeText: HostComponent<NativeTextProps> =
<del> (createReactNativeComponentClass('RCTText', () => ({
<del> validAttributes: {
<del> ...ReactNativeViewAttributes.UIView,
<del> isHighlighted: true,
<del> isPressable: true,
<del> numberOfLines: true,
<del> ellipsizeMode: true,
<del> allowFontScaling: true,
<del> maxFontSizeMultiplier: true,
<del> disabled: true,
<del> selectable: true,
<del> selectionColor: true,
<del> adjustsFontSizeToFit: true,
<del> minimumFontScale: true,
<del> textBreakStrategy: true,
<del> onTextLayout: true,
<del> onInlineViewLayout: true,
<del> dataDetectorType: true,
<del> android_hyphenationFrequency: true,
<add>const textViewConfig = {
<add> validAttributes: {
<add> isHighlighted: true,
<add> isPressable: true,
<add> numberOfLines: true,
<add> ellipsizeMode: true,
<add> allowFontScaling: true,
<add> maxFontSizeMultiplier: true,
<add> disabled: true,
<add> selectable: true,
<add> selectionColor: true,
<add> adjustsFontSizeToFit: true,
<add> minimumFontScale: true,
<add> textBreakStrategy: true,
<add> onTextLayout: true,
<add> onInlineViewLayout: true,
<add> dataDetectorType: true,
<add> android_hyphenationFrequency: true,
<add> },
<add> directEventTypes: {
<add> topTextLayout: {
<add> registrationName: 'onTextLayout',
<ide> },
<del> directEventTypes: {
<del> topTextLayout: {
<del> registrationName: 'onTextLayout',
<del> },
<del> topInlineViewLayout: {
<del> registrationName: 'onInlineViewLayout',
<del> },
<add> topInlineViewLayout: {
<add> registrationName: 'onInlineViewLayout',
<ide> },
<del> uiViewClassName: 'RCTText',
<del> })): any);
<add> },
<add> uiViewClassName: 'RCTText',
<add>};
<add>
<add>const virtualTextViewConfig = {
<add> validAttributes: {
<add> isHighlighted: true,
<add> isPressable: true,
<add> maxFontSizeMultiplier: true,
<add> },
<add> uiViewClassName: 'RCTVirtualText',
<add>};
<add>
<add>export const NativeText: HostComponent<NativeTextProps> =
<add> (createReactNativeComponentClass('RCTText', () =>
<add> createViewConfig(textViewConfig),
<add> ): any);
<ide>
<ide> export const NativeVirtualText: HostComponent<NativeTextProps> =
<ide> !global.RN$Bridgeless && !UIManager.hasViewManagerConfig('RCTVirtualText')
<ide> ? NativeText
<del> : (createReactNativeComponentClass('RCTVirtualText', () => ({
<del> validAttributes: {
<del> ...ReactNativeViewAttributes.UIView,
<del> isHighlighted: true,
<del> isPressable: true,
<del> maxFontSizeMultiplier: true,
<del> },
<del> uiViewClassName: 'RCTVirtualText',
<del> })): any);
<add> : (createReactNativeComponentClass('RCTVirtualText', () =>
<add> createViewConfig(virtualTextViewConfig),
<add> ): any); | 1 |
Javascript | Javascript | remove extra shallow copy | 77b9ce57e209c82b43d39caa50dc301f00a8abdb | <ide><path>lib/child_process.js
<ide> function spawnSync(file, args, options) {
<ide> maxBuffer: MAX_BUFFER,
<ide> ...opts.options
<ide> };
<del> options = opts.options = Object.assign(defaults, opts.options);
<add> options = opts.options = defaults;
<ide>
<ide> debug('spawnSync', opts.args, options);
<ide> | 1 |
Go | Go | add systemd implementation of cgroups | 6c7835050e53b733181ddfca6152c358fd625400 | <ide><path>pkg/cgroups/apply_nosystemd.go
<add>// +build !linux
<add>
<add>package cgroups
<add>
<add>import (
<add> "fmt"
<add>)
<add>
<add>func useSystemd() bool {
<add> return false
<add>}
<add>
<add>func systemdApply(c *Cgroup, pid int) (ActiveCgroup, error) {
<add> return nil, fmt.Errorf("Systemd not supported")
<add>}
<ide><path>pkg/cgroups/apply_systemd.go
<add>// +build linux
<add>
<add>package cgroups
<add>
<add>import (
<add> "fmt"
<add> systemd1 "github.com/coreos/go-systemd/dbus"
<add> "github.com/dotcloud/docker/pkg/systemd"
<add> "github.com/godbus/dbus"
<add> "path/filepath"
<add> "strings"
<add> "sync"
<add>)
<add>
<add>type systemdCgroup struct {
<add>}
<add>
<add>var (
<add> connLock sync.Mutex
<add> theConn *systemd1.Conn
<add> hasStartTransientUnit bool
<add>)
<add>
<add>func useSystemd() bool {
<add> if !systemd.SdBooted() {
<add> return false
<add> }
<add>
<add> connLock.Lock()
<add> defer connLock.Unlock()
<add>
<add> if theConn == nil {
<add> var err error
<add> theConn, err = systemd1.New()
<add> if err != nil {
<add> return false
<add> }
<add>
<add> // Assume we have StartTransientUnit
<add> hasStartTransientUnit = true
<add>
<add> // But if we get UnknownMethod error we don't
<add> if _, err := theConn.StartTransientUnit("test.scope", "invalid"); err != nil {
<add> if dbusError, ok := err.(dbus.Error); ok {
<add> if dbusError.Name == "org.freedesktop.DBus.Error.UnknownMethod" {
<add> hasStartTransientUnit = false
<add> }
<add> }
<add> }
<add> }
<add>
<add> return hasStartTransientUnit
<add>}
<add>
<add>type DeviceAllow struct {
<add> Node string
<add> Permissions string
<add>}
<add>
<add>func getIfaceForUnit(unitName string) string {
<add> if strings.HasSuffix(unitName, ".scope") {
<add> return "Scope"
<add> }
<add> if strings.HasSuffix(unitName, ".service") {
<add> return "Service"
<add> }
<add> return "Unit"
<add>}
<add>
<add>func systemdApply(c *Cgroup, pid int) (ActiveCgroup, error) {
<add> unitName := c.Parent + "-" + c.Name + ".scope"
<add> slice := "system.slice"
<add>
<add> var properties []systemd1.Property
<add>
<add> for _, v := range c.UnitProperties {
<add> switch v[0] {
<add> case "Slice":
<add> slice = v[1]
<add> default:
<add> return nil, fmt.Errorf("Unknown unit propery %s", v[0])
<add> }
<add> }
<add>
<add> properties = append(properties,
<add> systemd1.Property{"Slice", dbus.MakeVariant(slice)},
<add> systemd1.Property{"Description", dbus.MakeVariant("docker container " + c.Name)},
<add> systemd1.Property{"PIDs", dbus.MakeVariant([]uint32{uint32(pid)})})
<add>
<add> if !c.DeviceAccess {
<add> properties = append(properties,
<add> systemd1.Property{"DevicePolicy", dbus.MakeVariant("strict")},
<add> systemd1.Property{"DeviceAllow", dbus.MakeVariant([]DeviceAllow{
<add> {"/dev/null", "rwm"},
<add> {"/dev/zero", "rwm"},
<add> {"/dev/full", "rwm"},
<add> {"/dev/random", "rwm"},
<add> {"/dev/urandom", "rwm"},
<add> {"/dev/tty", "rwm"},
<add> {"/dev/console", "rwm"},
<add> {"/dev/tty0", "rwm"},
<add> {"/dev/tty1", "rwm"},
<add> {"/dev/pts/ptmx", "rwm"},
<add> // There is no way to add /dev/pts/* here atm, so we hack this manually below
<add> // /dev/pts/* (how to add this?)
<add> // Same with tuntap, which doesn't exist as a node most of the time
<add> })})
<add> }
<add>
<add> if c.Memory != 0 {
<add> properties = append(properties,
<add> systemd1.Property{"MemoryLimit", dbus.MakeVariant(uint64(c.Memory))})
<add> }
<add> // TODO: MemorySwap not available in systemd
<add>
<add> if c.CpuShares != 0 {
<add> properties = append(properties,
<add> systemd1.Property{"CPUShares", dbus.MakeVariant(uint64(c.CpuShares))})
<add> }
<add>
<add> if _, err := theConn.StartTransientUnit(unitName, "replace", properties...); err != nil {
<add> return nil, err
<add> }
<add>
<add> // To work around the lack of /dev/pts/* support above we need to manually add these
<add> // so, ask systemd for the cgroup used
<add> props, err := theConn.GetUnitTypeProperties(unitName, getIfaceForUnit(unitName))
<add> if err != nil {
<add> return nil, err
<add> }
<add>
<add> cgroup := props["ControlGroup"].(string)
<add>
<add> if !c.DeviceAccess {
<add> mountpoint, err := FindCgroupMountpoint("devices")
<add> if err != nil {
<add> return nil, err
<add> }
<add>
<add> path := filepath.Join(mountpoint, cgroup)
<add>
<add> // /dev/pts/*
<add> if err := writeFile(path, "devices.allow", "c 136:* rwm"); err != nil {
<add> return nil, err
<add> }
<add> // tuntap
<add> if err := writeFile(path, "devices.allow", "c 10:200 rwm"); err != nil {
<add> return nil, err
<add> }
<add> }
<add>
<add> return &systemdCgroup{}, nil
<add>}
<add>
<add>func (c *systemdCgroup) Cleanup() error {
<add> // systemd cleans up, we don't need to do anything
<add> return nil
<add>}
<ide><path>pkg/cgroups/cgroups.go
<ide> type Cgroup struct {
<ide> Memory int64 `json:"memory,omitempty"` // Memory limit (in bytes)
<ide> MemorySwap int64 `json:"memory_swap,omitempty"` // Total memory usage (memory + swap); set `-1' to disable swap
<ide> CpuShares int64 `json:"cpu_shares,omitempty"` // CPU shares (relative weight vs. other containers)
<add>
<add> UnitProperties [][2]string `json:"unit_properties,omitempty"` // systemd unit properties
<ide> }
<ide>
<ide> type ActiveCgroup interface {
<ide> func writeFile(dir, file, data string) error {
<ide> }
<ide>
<ide> func (c *Cgroup) Apply(pid int) (ActiveCgroup, error) {
<del> return rawApply(c, pid)
<add> // We have two implementation of cgroups support, one is based on
<add> // systemd and the dbus api, and one is based on raw cgroup fs operations
<add> // following the pre-single-writer model docs at:
<add> // http://www.freedesktop.org/wiki/Software/systemd/PaxControlGroups/
<add>
<add> if useSystemd() {
<add> return systemdApply(c, pid)
<add> } else {
<add> return rawApply(c, pid)
<add> }
<ide> }
<ide><path>runtime/execdriver/native/default_template.go
<ide> import (
<ide> "github.com/dotcloud/docker/pkg/cgroups"
<ide> "github.com/dotcloud/docker/pkg/libcontainer"
<ide> "github.com/dotcloud/docker/runtime/execdriver"
<add> "github.com/dotcloud/docker/utils"
<ide> "os"
<ide> )
<ide>
<ide> func createContainer(c *execdriver.Command) *libcontainer.Container {
<ide> container.Cgroups.MemorySwap = c.Resources.MemorySwap
<ide> }
<ide>
<add> if opts, ok := c.Config["unit"]; ok {
<add> props := [][2]string{}
<add> for _, opt := range opts {
<add> key, value, err := utils.ParseKeyValueOpt(opt)
<add> if err == nil {
<add> props = append(props, [2]string{key, value})
<add> } else {
<add> props = append(props, [2]string{opt, ""})
<add> }
<add> }
<add> container.Cgroups.UnitProperties = props
<add> }
<add>
<ide> // check to see if we are running in ramdisk to disable pivot root
<ide> container.NoPivotRoot = os.Getenv("DOCKER_RAMDISK") != ""
<ide> | 4 |
Go | Go | update code for latest engine-api | 7534f17261d0bb74557ca2f7cd893d5b7b531d49 | <ide><path>api/client/cli.go
<ide> func NewDockerCli(in io.ReadCloser, out, err io.Writer, clientFlags *cli.ClientF
<ide> }
<ide> customHeaders["User-Agent"] = clientUserAgent()
<ide>
<del> verStr := api.DefaultVersion.String()
<add> verStr := api.DefaultVersion
<ide> if tmpStr := os.Getenv("DOCKER_API_VERSION"); tmpStr != "" {
<ide> verStr = tmpStr
<ide> }
<ide><path>api/client/cp.go
<ide> func (cli *DockerCli) copyToContainer(srcPath, dstContainer, dstPath string, cpP
<ide> }
<ide>
<ide> options := types.CopyToContainerOptions{
<del> ContainerID: dstContainer,
<del> Path: resolvedDstPath,
<del> Content: content,
<ide> AllowOverwriteDirWithFile: false,
<ide> }
<ide>
<del> return cli.client.CopyToContainer(context.Background(), options)
<add> return cli.client.CopyToContainer(context.Background(), dstContainer, resolvedDstPath, content, options)
<ide> }
<ide><path>api/common.go
<ide> import (
<ide>
<ide> "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/pkg/system"
<del> "github.com/docker/docker/pkg/version"
<ide> "github.com/docker/engine-api/types"
<ide> "github.com/docker/libtrust"
<ide> )
<ide>
<ide> // Common constants for daemon and client.
<ide> const (
<ide> // Version of Current REST API
<del> DefaultVersion version.Version = "1.24"
<add> DefaultVersion string = "1.24"
<ide>
<ide> // MinVersion represents Minimum REST API version supported
<del> MinVersion version.Version = "1.12"
<add> MinVersion string = "1.12"
<ide>
<ide> // NoBaseImageSpecifier is the symbol used by the FROM
<ide> // command to specify that no base image is to be used.
<ide><path>api/server/httputils/httputils.go
<ide> import (
<ide> "golang.org/x/net/context"
<ide>
<ide> "github.com/docker/docker/api"
<del> "github.com/docker/docker/pkg/version"
<ide> )
<ide>
<ide> // APIVersionKey is the client's requested API version.
<ide> func WriteJSON(w http.ResponseWriter, code int, v interface{}) error {
<ide>
<ide> // VersionFromContext returns an API version from the context using APIVersionKey.
<ide> // It panics if the context value does not have version.Version type.
<del>func VersionFromContext(ctx context.Context) (ver version.Version) {
<add>func VersionFromContext(ctx context.Context) (ver string) {
<ide> if ctx == nil {
<ide> return
<ide> }
<ide> val := ctx.Value(APIVersionKey)
<ide> if val == nil {
<ide> return
<ide> }
<del> return val.(version.Version)
<add> return val.(string)
<ide> }
<ide><path>api/server/middleware/user_agent.go
<ide> import (
<ide>
<ide> "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/api/server/httputils"
<del> "github.com/docker/docker/pkg/version"
<add> "github.com/docker/engine-api/types/versions"
<ide> "golang.org/x/net/context"
<ide> )
<ide>
<ide> // UserAgentMiddleware is a middleware that
<ide> // validates the client user-agent.
<ide> type UserAgentMiddleware struct {
<del> serverVersion version.Version
<add> serverVersion string
<ide> }
<ide>
<ide> // NewUserAgentMiddleware creates a new UserAgentMiddleware
<ide> // with the server version.
<del>func NewUserAgentMiddleware(s version.Version) UserAgentMiddleware {
<add>func NewUserAgentMiddleware(s string) UserAgentMiddleware {
<ide> return UserAgentMiddleware{
<ide> serverVersion: s,
<ide> }
<ide> func (u UserAgentMiddleware) WrapHandler(handler func(ctx context.Context, w htt
<ide> userAgent[1] = strings.Split(userAgent[1], " ")[0]
<ide> }
<ide>
<del> if len(userAgent) == 2 && !u.serverVersion.Equal(version.Version(userAgent[1])) {
<add> if len(userAgent) == 2 && !versions.Equal(u.serverVersion, userAgent[1]) {
<ide> logrus.Debugf("Client and server don't have the same version (client: %s, server: %s)", userAgent[1], u.serverVersion)
<ide> }
<ide> }
<ide><path>api/server/middleware/version.go
<ide> import (
<ide> "net/http"
<ide> "runtime"
<ide>
<del> "github.com/docker/docker/pkg/version"
<add> "github.com/docker/engine-api/types/versions"
<ide> "golang.org/x/net/context"
<ide> )
<ide>
<ide> func (badRequestError) HTTPErrorStatusCode() int {
<ide> // VersionMiddleware is a middleware that
<ide> // validates the client and server versions.
<ide> type VersionMiddleware struct {
<del> serverVersion version.Version
<del> defaultVersion version.Version
<del> minVersion version.Version
<add> serverVersion string
<add> defaultVersion string
<add> minVersion string
<ide> }
<ide>
<ide> // NewVersionMiddleware creates a new VersionMiddleware
<ide> // with the default versions.
<del>func NewVersionMiddleware(s, d, m version.Version) VersionMiddleware {
<add>func NewVersionMiddleware(s, d, m string) VersionMiddleware {
<ide> return VersionMiddleware{
<ide> serverVersion: s,
<ide> defaultVersion: d,
<ide> func NewVersionMiddleware(s, d, m version.Version) VersionMiddleware {
<ide> // WrapHandler returns a new handler function wrapping the previous one in the request chain.
<ide> func (v VersionMiddleware) WrapHandler(handler func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error) func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> return func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<del> apiVersion := version.Version(vars["version"])
<add> apiVersion := vars["version"]
<ide> if apiVersion == "" {
<ide> apiVersion = v.defaultVersion
<ide> }
<ide>
<del> if apiVersion.GreaterThan(v.defaultVersion) {
<add> if versions.GreaterThan(apiVersion, v.defaultVersion) {
<ide> return badRequestError{fmt.Errorf("client is newer than server (client API version: %s, server API version: %s)", apiVersion, v.defaultVersion)}
<ide> }
<del> if apiVersion.LessThan(v.minVersion) {
<add> if versions.LessThan(apiVersion, v.minVersion) {
<ide> return badRequestError{fmt.Errorf("client version %s is too old. Minimum supported API version is %s, please upgrade your client to a newer version", apiVersion, v.minVersion)}
<ide> }
<ide>
<ide><path>api/server/middleware/version_test.go
<ide> import (
<ide> "testing"
<ide>
<ide> "github.com/docker/docker/api/server/httputils"
<del> "github.com/docker/docker/pkg/version"
<ide> "golang.org/x/net/context"
<ide> )
<ide>
<ide> func TestVersionMiddleware(t *testing.T) {
<ide> return nil
<ide> }
<ide>
<del> defaultVersion := version.Version("1.10.0")
<del> minVersion := version.Version("1.2.0")
<add> defaultVersion := "1.10.0"
<add> minVersion := "1.2.0"
<ide> m := NewVersionMiddleware(defaultVersion, defaultVersion, minVersion)
<ide> h := m.WrapHandler(handler)
<ide>
<ide> func TestVersionMiddlewareWithErrors(t *testing.T) {
<ide> return nil
<ide> }
<ide>
<del> defaultVersion := version.Version("1.10.0")
<del> minVersion := version.Version("1.2.0")
<add> defaultVersion := "1.10.0"
<add> minVersion := "1.2.0"
<ide> m := NewVersionMiddleware(defaultVersion, defaultVersion, minVersion)
<ide> h := m.WrapHandler(handler)
<ide>
<ide><path>api/server/router/build/build_routes.go
<ide> import (
<ide> "github.com/docker/docker/pkg/streamformatter"
<ide> "github.com/docker/engine-api/types"
<ide> "github.com/docker/engine-api/types/container"
<add> "github.com/docker/engine-api/types/versions"
<ide> "github.com/docker/go-units"
<ide> "golang.org/x/net/context"
<ide> )
<ide>
<ide> func newImageBuildOptions(ctx context.Context, r *http.Request) (*types.ImageBuildOptions, error) {
<ide> version := httputils.VersionFromContext(ctx)
<ide> options := &types.ImageBuildOptions{}
<del> if httputils.BoolValue(r, "forcerm") && version.GreaterThanOrEqualTo("1.12") {
<add> if httputils.BoolValue(r, "forcerm") && versions.GreaterThanOrEqualTo(version, "1.12") {
<ide> options.Remove = true
<del> } else if r.FormValue("rm") == "" && version.GreaterThanOrEqualTo("1.12") {
<add> } else if r.FormValue("rm") == "" && versions.GreaterThanOrEqualTo(version, "1.12") {
<ide> options.Remove = true
<ide> } else {
<ide> options.Remove = httputils.BoolValue(r, "rm")
<ide> }
<del> if httputils.BoolValue(r, "pull") && version.GreaterThanOrEqualTo("1.16") {
<add> if httputils.BoolValue(r, "pull") && versions.GreaterThanOrEqualTo(version, "1.16") {
<ide> options.PullParent = true
<ide> }
<ide>
<ide><path>api/server/router/container/backend.go
<ide> import (
<ide>
<ide> "github.com/docker/docker/api/types/backend"
<ide> "github.com/docker/docker/pkg/archive"
<del> "github.com/docker/docker/pkg/version"
<ide> "github.com/docker/engine-api/types"
<ide> "github.com/docker/engine-api/types/container"
<ide> )
<ide> type stateBackend interface {
<ide> // monitorBackend includes functions to implement to provide containers monitoring functionality.
<ide> type monitorBackend interface {
<ide> ContainerChanges(name string) ([]archive.Change, error)
<del> ContainerInspect(name string, size bool, version version.Version) (interface{}, error)
<add> ContainerInspect(name string, size bool, version string) (interface{}, error)
<ide> ContainerLogs(ctx context.Context, name string, config *backend.ContainerLogsConfig, started chan struct{}) error
<ide> ContainerStats(ctx context.Context, name string, config *backend.ContainerStatsConfig) error
<ide> ContainerTop(name string, psArgs string) (*types.ContainerProcessList, error)
<ide><path>api/server/router/container/container_routes.go
<ide> import (
<ide> "github.com/docker/engine-api/types"
<ide> "github.com/docker/engine-api/types/container"
<ide> "github.com/docker/engine-api/types/filters"
<add> "github.com/docker/engine-api/types/versions"
<ide> "golang.org/x/net/context"
<ide> "golang.org/x/net/websocket"
<ide> )
<ide> func (s *containerRouter) postContainersKill(ctx context.Context, w http.Respons
<ide> // Return error if the container is not running and the api is >= 1.20
<ide> // to keep backwards compatibility.
<ide> version := httputils.VersionFromContext(ctx)
<del> if version.GreaterThanOrEqualTo("1.20") || !isStopped {
<add> if versions.GreaterThanOrEqualTo(version, "1.20") || !isStopped {
<ide> return fmt.Errorf("Cannot kill container %s: %v", name, err)
<ide> }
<ide> }
<ide> func (s *containerRouter) postContainersCreate(ctx context.Context, w http.Respo
<ide> return err
<ide> }
<ide> version := httputils.VersionFromContext(ctx)
<del> adjustCPUShares := version.LessThan("1.19")
<add> adjustCPUShares := versions.LessThan(version, "1.19")
<ide>
<ide> ccr, err := s.backend.ContainerCreate(types.ContainerCreateConfig{
<ide> Name: name,
<ide><path>api/server/router/container/exec.go
<ide> import (
<ide> "github.com/docker/docker/api/server/httputils"
<ide> "github.com/docker/docker/pkg/stdcopy"
<ide> "github.com/docker/engine-api/types"
<add> "github.com/docker/engine-api/types/versions"
<ide> "golang.org/x/net/context"
<ide> )
<ide>
<ide> func (s *containerRouter) postContainerExecStart(ctx context.Context, w http.Res
<ide> }
<ide>
<ide> version := httputils.VersionFromContext(ctx)
<del> if version.GreaterThan("1.21") {
<add> if versions.GreaterThan(version, "1.21") {
<ide> if err := httputils.CheckForJSON(r); err != nil {
<ide> return err
<ide> }
<ide><path>api/server/router/image/image_routes.go
<ide> import (
<ide> "github.com/docker/docker/pkg/streamformatter"
<ide> "github.com/docker/engine-api/types"
<ide> "github.com/docker/engine-api/types/container"
<add> "github.com/docker/engine-api/types/versions"
<ide> "golang.org/x/net/context"
<ide> )
<ide>
<ide> func (s *imageRouter) postCommit(ctx context.Context, w http.ResponseWriter, r *
<ide>
<ide> pause := httputils.BoolValue(r, "pause")
<ide> version := httputils.VersionFromContext(ctx)
<del> if r.FormValue("pause") == "" && version.GreaterThanOrEqualTo("1.13") {
<add> if r.FormValue("pause") == "" && versions.GreaterThanOrEqualTo(version, "1.13") {
<ide> pause = true
<ide> }
<ide>
<ide><path>api/server/router/system/system_routes.go
<ide> func (s *systemRouter) getInfo(ctx context.Context, w http.ResponseWriter, r *ht
<ide>
<ide> func (s *systemRouter) getVersion(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> info := s.backend.SystemVersion()
<del> info.APIVersion = api.DefaultVersion.String()
<add> info.APIVersion = api.DefaultVersion
<ide>
<ide> return httputils.WriteJSON(w, http.StatusOK, info)
<ide> }
<ide><path>api/server/server_test.go
<ide> import (
<ide> "github.com/docker/docker/api"
<ide> "github.com/docker/docker/api/server/httputils"
<ide> "github.com/docker/docker/api/server/middleware"
<del> "github.com/docker/docker/pkg/version"
<ide>
<ide> "golang.org/x/net/context"
<ide> )
<ide> func TestMiddlewares(t *testing.T) {
<ide> cfg: cfg,
<ide> }
<ide>
<del> srv.UseMiddleware(middleware.NewVersionMiddleware(version.Version("0.1omega2"), api.DefaultVersion, api.MinVersion))
<add> srv.UseMiddleware(middleware.NewVersionMiddleware("0.1omega2", api.DefaultVersion, api.MinVersion))
<ide>
<ide> req, _ := http.NewRequest("GET", "/containers/json", nil)
<ide> resp := httptest.NewRecorder()
<ide><path>daemon/inspect.go
<ide> import (
<ide> "github.com/docker/docker/api/types/backend"
<ide> "github.com/docker/docker/container"
<ide> "github.com/docker/docker/daemon/network"
<del> "github.com/docker/docker/pkg/version"
<ide> "github.com/docker/engine-api/types"
<ide> networktypes "github.com/docker/engine-api/types/network"
<add> "github.com/docker/engine-api/types/versions"
<ide> "github.com/docker/engine-api/types/versions/v1p20"
<ide> )
<ide>
<ide> // ContainerInspect returns low-level information about a
<ide> // container. Returns an error if the container cannot be found, or if
<ide> // there is an error getting the data.
<del>func (daemon *Daemon) ContainerInspect(name string, size bool, version version.Version) (interface{}, error) {
<add>func (daemon *Daemon) ContainerInspect(name string, size bool, version string) (interface{}, error) {
<ide> switch {
<del> case version.LessThan("1.20"):
<add> case versions.LessThan(version, "1.20"):
<ide> return daemon.containerInspectPre120(name)
<del> case version.Equal("1.20"):
<add> case versions.Equal(version, "1.20"):
<ide> return daemon.containerInspect120(name)
<ide> }
<ide> return daemon.containerInspectCurrent(name, size)
<ide><path>daemon/stats.go
<ide> import (
<ide>
<ide> "github.com/docker/docker/api/types/backend"
<ide> "github.com/docker/docker/pkg/ioutils"
<del> "github.com/docker/docker/pkg/version"
<ide> "github.com/docker/engine-api/types"
<add> "github.com/docker/engine-api/types/versions"
<ide> "github.com/docker/engine-api/types/versions/v1p20"
<ide> )
<ide>
<ide> func (daemon *Daemon) ContainerStats(ctx context.Context, prefixOrName string, c
<ide> return errors.New("Windows does not support stats")
<ide> }
<ide> // Remote API version (used for backwards compatibility)
<del> apiVersion := version.Version(config.Version)
<add> apiVersion := config.Version
<ide>
<ide> container, err := daemon.GetContainer(prefixOrName)
<ide> if err != nil {
<ide> func (daemon *Daemon) ContainerStats(ctx context.Context, prefixOrName string, c
<ide>
<ide> var statsJSON interface{}
<ide> statsJSONPost120 := getStatJSON(v)
<del> if apiVersion.LessThan("1.21") {
<add> if versions.LessThan(apiVersion, "1.21") {
<ide> var (
<ide> rxBytes uint64
<ide> rxPackets uint64
<ide><path>docker/daemon.go
<ide> import (
<ide> "github.com/docker/docker/pkg/pidfile"
<ide> "github.com/docker/docker/pkg/signal"
<ide> "github.com/docker/docker/pkg/system"
<del> "github.com/docker/docker/pkg/version"
<ide> "github.com/docker/docker/registry"
<ide> "github.com/docker/docker/runconfig"
<ide> "github.com/docker/docker/utils"
<ide> func initRouter(s *apiserver.Server, d *daemon.Daemon) {
<ide> }
<ide>
<ide> func (cli *DaemonCli) initMiddlewares(s *apiserver.Server, cfg *apiserver.Config) {
<del> v := version.Version(cfg.Version)
<add> v := cfg.Version
<ide>
<ide> vm := middleware.NewVersionMiddleware(v, api.DefaultVersion, api.MinVersion)
<ide> s.UseMiddleware(vm)
<ide><path>image/v1/imagev1.go
<ide> import (
<ide> "github.com/docker/distribution/digest"
<ide> "github.com/docker/docker/image"
<ide> "github.com/docker/docker/layer"
<del> "github.com/docker/docker/pkg/version"
<add> "github.com/docker/engine-api/types/versions"
<ide> )
<ide>
<ide> var validHex = regexp.MustCompile(`^([a-f0-9]{64})$`)
<ide>
<ide> // noFallbackMinVersion is the minimum version for which v1compatibility
<ide> // information will not be marshaled through the Image struct to remove
<ide> // blank fields.
<del>var noFallbackMinVersion = version.Version("1.8.3")
<add>var noFallbackMinVersion = "1.8.3"
<ide>
<ide> // HistoryFromConfig creates a History struct from v1 configuration JSON
<ide> func HistoryFromConfig(imageJSON []byte, emptyLayer bool) (image.History, error) {
<ide> func MakeConfigFromV1Config(imageJSON []byte, rootfs *image.RootFS, history []im
<ide> return nil, err
<ide> }
<ide>
<del> useFallback := version.Version(dver.DockerVersion).LessThan(noFallbackMinVersion)
<add> useFallback := versions.LessThan(dver.DockerVersion, noFallbackMinVersion)
<ide>
<ide> if useFallback {
<ide> var v1Image image.V1Image
<ide><path>integration-cli/docker_api_stats_test.go
<ide> import (
<ide> "time"
<ide>
<ide> "github.com/docker/docker/pkg/integration/checker"
<del> "github.com/docker/docker/pkg/version"
<ide> "github.com/docker/engine-api/types"
<add> "github.com/docker/engine-api/types/versions"
<ide> "github.com/go-check/check"
<ide> )
<ide>
<ide> func (s *DockerSuite) TestApiStatsNetworkStatsVersioning(c *check.C) {
<ide> for i := 17; i <= 21; i++ {
<ide> apiVersion := fmt.Sprintf("v1.%d", i)
<ide> statsJSONBlob := getVersionedStats(c, id, apiVersion)
<del> if version.Version(apiVersion).LessThan("v1.21") {
<add> if versions.LessThan(apiVersion, "v1.21") {
<ide> c.Assert(jsonBlobHasLTv121NetworkStats(statsJSONBlob), checker.Equals, true,
<ide> check.Commentf("Stats JSON blob from API %s %#v does not look like a <v1.21 API stats structure", apiVersion, statsJSONBlob))
<ide> } else {
<ide><path>integration-cli/docker_api_test.go
<ide> func (s *DockerSuite) TestApiVersionStatusCode(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestApiClientVersionNewerThanServer(c *check.C) {
<del> v := strings.Split(api.DefaultVersion.String(), ".")
<add> v := strings.Split(api.DefaultVersion, ".")
<ide> vMinInt, err := strconv.Atoi(v[1])
<ide> c.Assert(err, checker.IsNil)
<ide> vMinInt++
<ide> func (s *DockerSuite) TestApiClientVersionNewerThanServer(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestApiClientVersionOldNotSupported(c *check.C) {
<del> v := strings.Split(api.MinVersion.String(), ".")
<add> v := strings.Split(api.MinVersion, ".")
<ide> vMinInt, err := strconv.Atoi(v[1])
<ide> c.Assert(err, checker.IsNil)
<ide> vMinInt-- | 20 |
Python | Python | add tap diagnostic message for retried tests | 41519fd1a4041e46c42d94c303fcb13fa2fc9344 | <ide><path>tools/test.py
<ide> def RunSingle(self, parallel, thread_id):
<ide> sys.platform == 'sunos5' and
<ide> 'ECONNREFUSED' in output.output.stderr):
<ide> output = case.Run()
<add> output.diagnostic.append('ECONNREFUSED received, test retried')
<ide> case.duration = (datetime.now() - start)
<ide> except IOError, e:
<ide> return
<ide> def HasRun(self, output):
<ide>
<ide> class TapProgressIndicator(SimpleProgressIndicator):
<ide>
<add> def _printDiagnostic(self, messages):
<add> for l in messages.splitlines():
<add> logger.info('# ' + l)
<add>
<ide> def Starting(self):
<ide> logger.info('1..%i' % len(self.cases))
<ide> self._done = 0
<ide> def HasRun(self, output):
<ide> if FLAKY in output.test.outcomes and self.flaky_tests_mode == DONTCARE:
<ide> status_line = status_line + ' # TODO : Fix flaky test'
<ide> logger.info(status_line)
<add> self._printDiagnostic("\n".join(output.diagnostic))
<ide>
<ide> if output.HasTimedOut():
<del> logger.info('# TIMEOUT')
<add> self._printDiagnostic('TIMEOUT')
<ide>
<del> for l in output.output.stderr.splitlines():
<del> logger.info('#' + l)
<del> for l in output.output.stdout.splitlines():
<del> logger.info('#' + l)
<add> self._printDiagnostic(output.output.stderr)
<add> self._printDiagnostic(output.output.stdout)
<ide> else:
<ide> skip = skip_regex.search(output.output.stdout)
<ide> if skip:
<ide> def HasRun(self, output):
<ide> if FLAKY in output.test.outcomes:
<ide> status_line = status_line + ' # TODO : Fix flaky test'
<ide> logger.info(status_line)
<add> self._printDiagnostic("\n".join(output.diagnostic))
<ide>
<ide> duration = output.test.duration
<ide>
<ide> def __init__(self, test, command, output, store_unexpected_output):
<ide> self.command = command
<ide> self.output = output
<ide> self.store_unexpected_output = store_unexpected_output
<add> self.diagnostic = []
<ide>
<ide> def UnexpectedOutput(self):
<ide> if self.HasCrashed(): | 1 |
Python | Python | add the ability to combine methodviews | 516ce59f95a3b5d2fffbcde8abfdf1951e748361 | <ide><path>flask/views.py
<ide> def view(*args, **kwargs):
<ide> return view
<ide>
<ide>
<add>def get_methods(cls):
<add> return getattr(cls, 'methods', []) or []
<add>
<add>
<ide> class MethodViewType(type):
<ide>
<ide> def __new__(cls, name, bases, d):
<ide> rv = type.__new__(cls, name, bases, d)
<ide> if 'methods' not in d:
<del> methods = set(rv.methods or [])
<add> methods = set(m for b in bases for m in get_methods(b))
<ide> for key in d:
<ide> if key in http_method_funcs:
<ide> methods.add(key.upper())
<ide><path>tests/test_views.py
<ide> def dispatch_request(self):
<ide>
<ide> # But these tests should still pass. We just log a warning.
<ide> common_test(app)
<add>
<add>def test_multiple_inheritance():
<add> app = flask.Flask(__name__)
<add>
<add> class GetView(flask.views.MethodView):
<add> def get(self):
<add> return 'GET'
<add>
<add> class DeleteView(flask.views.MethodView):
<add> def delete(self):
<add> return 'DELETE'
<add>
<add> class GetDeleteView(GetView, DeleteView):
<add> pass
<add>
<add> app.add_url_rule('/', view_func=GetDeleteView.as_view('index'))
<add>
<add> c = app.test_client()
<add> assert c.get('/').data == b'GET'
<add> assert c.delete('/').data == b'DELETE'
<add> assert sorted(GetDeleteView.methods) == ['DELETE', 'GET']
<add>
<add>def test_remove_method_from_parent():
<add> app = flask.Flask(__name__)
<add>
<add> class GetView(flask.views.MethodView):
<add> def get(self):
<add> return 'GET'
<add>
<add> class OtherView(flask.views.MethodView):
<add> def post(self):
<add> return 'POST'
<add>
<add> class View(GetView, OtherView):
<add> methods = ['GET']
<add>
<add> app.add_url_rule('/', view_func=View.as_view('index'))
<add>
<add> c = app.test_client()
<add> assert c.get('/').data == b'GET'
<add> assert c.post('/').status_code == 405
<add> assert sorted(View.methods) == ['GET'] | 2 |
Python | Python | fix typo in example code | d07db28f52b4faf6769d6b7b454c950ec02dc641 | <ide><path>examples/run_classifier.py
<ide> def convert_examples_to_features(examples, label_list, max_seq_length,
<ide> # sequence or the second sequence. The embedding vectors for `type=0` and
<ide> # `type=1` were learned during pre-training and are added to the wordpiece
<ide> # embedding vector (and position vector). This is not *strictly* necessary
<del> # since the [SEP] token unambigiously separates the sequences, but it makes
<add> # since the [SEP] token unambiguously separates the sequences, but it makes
<ide> # it easier for the model to learn the concept of sequences.
<ide> #
<ide> # For classification tasks, the first vector (corresponding to [CLS]) is | 1 |
Javascript | Javascript | improve some assertion messages | 5de4da062376ef955677d435d721cbeb8712e9eb | <ide><path>packages/ember-handlebars/lib/helpers/collection.js
<ide> Ember.Handlebars.registerHelper('collection', function(path, options) {
<ide> // Otherwise, just default to the standard class.
<ide> var collectionClass;
<ide> collectionClass = path ? getPath(this, path, options) : Ember.CollectionView;
<del> Ember.assert(fmt("%@ #collection: Could not find %@", data.view, path), !!collectionClass);
<add> Ember.assert(fmt("%@ #collection: Could not find collection class %@", [data.view, path]), !!collectionClass);
<ide>
<ide> var hash = options.hash, itemHash = {}, match;
<ide>
<ide> Ember.Handlebars.registerHelper('collection', function(path, options) {
<ide> var collectionPrototype = collectionClass.proto();
<ide> delete hash.itemViewClass;
<ide> itemViewClass = itemViewPath ? getPath(collectionPrototype, itemViewPath, options) : collectionPrototype.itemViewClass;
<del> Ember.assert(fmt("%@ #collection: Could not find %@", data.view, itemViewPath), !!itemViewClass);
<add> Ember.assert(fmt("%@ #collection: Could not find itemViewClass %@", [data.view, itemViewPath]), !!itemViewClass);
<ide>
<ide> // Go through options passed to the {{collection}} helper and extract options
<ide> // that configure item views instead of the collection itself.
<ide><path>packages/ember-views/lib/views/view.js
<ide> Ember.View = Ember.Object.extend(Ember.Evented,
<ide> // is the view by default. A hash of data is also passed that provides
<ide> // the template with access to the view and render buffer.
<ide>
<del> Ember.assert('template must be a function. Did you mean to specify templateName instead?', typeof template === 'function');
<add> Ember.assert('template must be a function. Did you mean to call Ember.Handlebars.compile("...") or specify templateName instead?', typeof template === 'function');
<ide> // The template should write directly to the render buffer instead
<ide> // of returning a string.
<ide> var output = template(context, { data: data }); | 2 |
Text | Text | add missing options allowed in node_options | 7f812c5d8ba357d5c4942c18b3d6d3d653c4e194 | <ide><path>doc/api/cli.md
<ide> In case an option value happens to contain a space (for example a path listed in
<ide> ```
<ide>
<ide> Node.js options that are allowed are:
<del>- `--report-directory`
<del>- `--report-filename`
<del>- `--report-on-fatalerror`
<del>- `--report-on-signal`
<del>- `--report-signal`
<del>- `--report-uncaught-exception`
<ide> - `--enable-fips`
<add>- `--es-module-specifier-resolution`
<ide> - `--experimental-modules`
<add>- `--experimental-policy`
<ide> - `--experimental-repl-await`
<ide> - `--experimental-report`
<ide> - `--experimental-vm-modules`
<ide> - `--experimental-wasm-modules`
<ide> - `--force-fips`
<ide> - `--frozen-intrinsics`
<ide> - `--heapsnapshot-signal`
<add>- `--http-parser`
<ide> - `--icu-data-dir`
<del>- `--inspect`
<add>- `--input-type`
<ide> - `--inspect-brk`
<del>- `--inspect-port`
<add>- `--inspect-port`, `--debug-port`
<ide> - `--inspect-publish-uid`
<add>- `--inspect`
<ide> - `--loader`
<ide> - `--max-http-header-size`
<ide> - `--napi-modules`
<ide> Node.js options that are allowed are:
<ide> - `--no-warnings`
<ide> - `--openssl-config`
<ide> - `--pending-deprecation`
<add>- `--preserve-symlinks-main`
<add>- `--preserve-symlinks`
<add>- `--prof-process`
<ide> - `--redirect-warnings`
<add>- `--report-directory`
<add>- `--report-filename`
<add>- `--report-on-fatalerror`
<add>- `--report-on-signal`
<add>- `--report-signal`
<add>- `--report-uncaught-exception`
<ide> - `--require`, `-r`
<ide> - `--throw-deprecation`
<ide> - `--title`
<ide> Node.js options that are allowed are:
<ide> V8 options that are allowed are:
<ide> - `--abort-on-uncaught-exception`
<ide> - `--max-old-space-size`
<del>- `--perf-basic-prof`
<ide> - `--perf-basic-prof-only-functions`
<del>- `--perf-prof`
<add>- `--perf-basic-prof`
<ide> - `--perf-prof-unwinding-info`
<add>- `--perf-prof`
<ide> - `--stack-trace-limit`
<ide>
<ide> ### `NODE_PATH=path[:…]` | 1 |
Text | Text | add releases note about the `#to_s` deprecation | 16e010bae40b2f971b252f0f12b875c78be849cb | <ide><path>guides/source/7_0_release_notes.md
<ide> Please refer to the [Changelog][active-support] for detailed changes.
<ide>
<ide> ### Deprecations
<ide>
<add>* Deprecate passing a format to `#to_s` in favor of `#to_formatted_s` in `Array`, `Range`, `Date`, `DateTime`, `Time`,
<add> `BigDecimal`, `Float` and, `Integer`.
<add>
<add> This deprecation is to allow Rails application to take advantage of a Ruby 3.1
<add> [optimization][https://github.com/ruby/ruby/commit/b08dacfea39ad8da3f1fd7fdd0e4538cc892ec44] that makes
<add> interpolation of some types of objects faster.
<add>
<add> New applications will not have the `#to_s` method overriden on those classes, existing applications can use
<add> `config.active_support.disable_to_s_conversion`.
<add>
<ide> ### Notable changes
<ide>
<ide> Active Job | 1 |
Ruby | Ruby | use hgpath instead of "hg" to fix --head hg builds | 913ff483f0223f9423798c379375b7972de45f7c | <ide><path>Library/Homebrew/download_strategy.rb
<ide> def stage
<ide> end
<ide>
<ide> def source_modified_time
<del> Time.parse Utils.popen_read("hg", "tip", "--template", "{date|isodate}", "-R", cached_location.to_s)
<add> Time.parse Utils.popen_read(hgpath, "tip", "--template", "{date|isodate}", "-R", cached_location.to_s)
<ide> end
<ide>
<ide> def last_commit
<del> Utils.popen_read("hg", "parent", "--template", "{node|short}", "-R", cached_location.to_s)
<add> Utils.popen_read(hgpath, "parent", "--template", "{node|short}", "-R", cached_location.to_s)
<ide> end
<ide>
<ide> private | 1 |
Javascript | Javascript | clarify documentation on error status codes | 74db36ee94addab519a7198bd987b44228309d59 | <ide><path>src/ng/http.js
<ide> function $HttpProvider() {
<ide> * }).
<ide> * error(function(data, status, headers, config) {
<ide> * // called asynchronously if an error occurs
<del> * // or server returns response with status
<del> * // code outside of the <200, 400) range
<add> * // or server returns response with an error status.
<ide> * });
<ide> * </pre>
<ide> *
<ide> function $HttpProvider() {
<ide> * an object representing the response. See the api signature and type info below for more
<ide> * details.
<ide> *
<add> * A response status code that falls in the [200, 300) range is considered a success status and
<add> * will result in the success callback being called. Note that if the response is a redirect,
<add> * XMLHttpRequest will transparently follow it, meaning that the error callback will not be
<add> * called for such responses.
<ide> *
<ide> * # Shortcut methods
<ide> * | 1 |
Go | Go | define a context per request | 27c76522dea91ec585f0b5f0ae1fec8c255b7b22 | <ide><path>api/server/image.go
<ide> func (s *Server) postImagesCreate(ctx context.Context, w http.ResponseWriter, r
<ide> OutStream: output,
<ide> }
<ide>
<del> err = s.daemon.Repositories(ctx).Pull(ctx, image, tag, imagePullConfig)
<add> err = s.daemon.Repositories().Pull(ctx, image, tag, imagePullConfig)
<ide> } else { //import
<ide> if tag == "" {
<ide> repo, tag = parsers.ParseRepositoryTag(repo)
<ide> func (s *Server) postImagesCreate(ctx context.Context, w http.ResponseWriter, r
<ide> return err
<ide> }
<ide>
<del> err = s.daemon.Repositories(ctx).Import(ctx, src, repo, tag, message, r.Body, output, newConfig)
<add> err = s.daemon.Repositories().Import(ctx, src, repo, tag, message, r.Body, output, newConfig)
<ide> }
<ide> if err != nil {
<ide> if !output.Flushed() {
<ide> func (s *Server) postImagesPush(ctx context.Context, w http.ResponseWriter, r *h
<ide>
<ide> w.Header().Set("Content-Type", "application/json")
<ide>
<del> if err := s.daemon.Repositories(ctx).Push(ctx, name, imagePushConfig); err != nil {
<add> if err := s.daemon.Repositories().Push(ctx, name, imagePushConfig); err != nil {
<ide> if !output.Flushed() {
<ide> return err
<ide> }
<ide> func (s *Server) getImagesGet(ctx context.Context, w http.ResponseWriter, r *htt
<ide> names = r.Form["names"]
<ide> }
<ide>
<del> if err := s.daemon.Repositories(ctx).ImageExport(names, output); err != nil {
<add> if err := s.daemon.Repositories().ImageExport(names, output); err != nil {
<ide> if !output.Flushed() {
<ide> return err
<ide> }
<ide> func (s *Server) getImagesGet(ctx context.Context, w http.ResponseWriter, r *htt
<ide> }
<ide>
<ide> func (s *Server) postImagesLoad(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<del> return s.daemon.Repositories(ctx).Load(r.Body, w)
<add> return s.daemon.Repositories().Load(r.Body, w)
<ide> }
<ide>
<ide> func (s *Server) deleteImages(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> func (s *Server) getImagesByName(ctx context.Context, w http.ResponseWriter, r *
<ide> return fmt.Errorf("Missing parameter")
<ide> }
<ide>
<del> imageInspect, err := s.daemon.Repositories(ctx).Lookup(vars["name"])
<add> imageInspect, err := s.daemon.Repositories().Lookup(vars["name"])
<ide> if err != nil {
<ide> return err
<ide> }
<ide> func (s *Server) getImagesJSON(ctx context.Context, w http.ResponseWriter, r *ht
<ide> }
<ide>
<ide> // FIXME: The filter parameter could just be a match filter
<del> images, err := s.daemon.Repositories(ctx).Images(r.Form.Get("filters"), r.Form.Get("filter"), boolValue(r, "all"))
<add> images, err := s.daemon.Repositories().Images(r.Form.Get("filters"), r.Form.Get("filter"), boolValue(r, "all"))
<ide> if err != nil {
<ide> return err
<ide> }
<ide> func (s *Server) getImagesHistory(ctx context.Context, w http.ResponseWriter, r
<ide> }
<ide>
<ide> name := vars["name"]
<del> history, err := s.daemon.Repositories(ctx).History(name)
<add> history, err := s.daemon.Repositories().History(name)
<ide> if err != nil {
<ide> return err
<ide> }
<ide> func (s *Server) postImagesTag(ctx context.Context, w http.ResponseWriter, r *ht
<ide> tag := r.Form.Get("tag")
<ide> force := boolValue(r, "force")
<ide> name := vars["name"]
<del> if err := s.daemon.Repositories(ctx).Tag(repo, tag, name, force); err != nil {
<add> if err := s.daemon.Repositories().Tag(repo, tag, name, force); err != nil {
<ide> return err
<ide> }
<ide> s.daemon.EventsService.Log(ctx, "tag", utils.ImageReference(repo, tag), "")
<ide><path>api/server/server.go
<ide> type Server struct {
<ide> }
<ide>
<ide> // New returns a new instance of the server based on the specified configuration.
<del>func New(ctx context.Context, cfg *Config) *Server {
<add>func New(cfg *Config) *Server {
<ide> srv := &Server{
<ide> cfg: cfg,
<ide> start: make(chan struct{}),
<ide> }
<del> srv.router = createRouter(ctx, srv)
<add> srv.router = createRouter(srv)
<ide> return srv
<ide> }
<ide>
<ide> func (s *Server) initTCPSocket(addr string) (l net.Listener, err error) {
<ide> return
<ide> }
<ide>
<del>func (s *Server) makeHTTPHandler(ctx context.Context, localMethod string, localRoute string, localHandler HTTPAPIFunc) http.HandlerFunc {
<add>func (s *Server) makeHTTPHandler(localMethod string, localRoute string, localHandler HTTPAPIFunc) http.HandlerFunc {
<ide> return func(w http.ResponseWriter, r *http.Request) {
<ide> // log the handler generation
<ide> logrus.Debugf("Calling %s %s", localMethod, localRoute)
<ide> func (s *Server) makeHTTPHandler(ctx context.Context, localMethod string, localR
<ide> // apply to all requests. Data that is specific to the
<ide> // immediate function being called should still be passed
<ide> // as 'args' on the function call.
<add> ctx := context.Background()
<add>
<ide> reqID := stringid.TruncateID(stringid.GenerateNonCryptoID())
<ide> ctx = context.WithValue(ctx, context.RequestID, reqID)
<ide> handlerFunc := s.handleWithGlobalMiddlewares(localHandler)
<ide> func (s *Server) makeHTTPHandler(ctx context.Context, localMethod string, localR
<ide>
<ide> // createRouter initializes the main router the server uses.
<ide> // we keep enableCors just for legacy usage, need to be removed in the future
<del>func createRouter(ctx context.Context, s *Server) *mux.Router {
<add>func createRouter(s *Server) *mux.Router {
<ide> r := mux.NewRouter()
<ide> if os.Getenv("DEBUG") != "" {
<ide> profilerSetup(r, "/debug/")
<ide> func createRouter(ctx context.Context, s *Server) *mux.Router {
<ide> localMethod := method
<ide>
<ide> // build the handler function
<del> f := s.makeHTTPHandler(ctx, localMethod, localRoute, localFct)
<add> f := s.makeHTTPHandler(localMethod, localRoute, localFct)
<ide>
<ide> // add the new route
<ide> if localRoute == "" {
<ide><path>api/server/server_experimental_unix.go
<ide>
<ide> package server
<ide>
<del>import (
<del> "github.com/docker/docker/context"
<del>)
<del>
<del>func (s *Server) registerSubRouter(ctx context.Context) {
<del> httpHandler := s.daemon.NetworkAPIRouter(ctx)
<add>func (s *Server) registerSubRouter() {
<add> httpHandler := s.daemon.NetworkAPIRouter()
<ide>
<ide> subrouter := s.router.PathPrefix("/v{version:[0-9.]+}/networks").Subrouter()
<ide> subrouter.Methods("GET", "POST", "PUT", "DELETE").HandlerFunc(httpHandler)
<ide><path>api/server/server_stub.go
<ide>
<ide> package server
<ide>
<del>import (
<del> "github.com/docker/docker/context"
<del>)
<del>
<del>func (s *Server) registerSubRouter(ctx context.Context) {
<add>func (s *Server) registerSubRouter() {
<ide> }
<ide><path>api/server/server_unix.go
<ide> import (
<ide> "net/http"
<ide> "strconv"
<ide>
<del> "github.com/docker/docker/context"
<ide> "github.com/docker/docker/daemon"
<ide> "github.com/docker/docker/pkg/sockets"
<ide> "github.com/docker/libnetwork/portallocator"
<ide> func (s *Server) newServer(proto, addr string) ([]serverCloser, error) {
<ide> // AcceptConnections allows clients to connect to the API server.
<ide> // Referenced Daemon is notified about this server, and waits for the
<ide> // daemon acknowledgement before the incoming connections are accepted.
<del>func (s *Server) AcceptConnections(ctx context.Context, d *daemon.Daemon) {
<add>func (s *Server) AcceptConnections(d *daemon.Daemon) {
<ide> // Tell the init daemon we are accepting requests
<ide> s.daemon = d
<del> s.registerSubRouter(ctx)
<add> s.registerSubRouter()
<ide> go systemdDaemon.SdNotify("READY=1")
<ide> // close the lock so the listeners start accepting connections
<ide> select {
<ide><path>api/server/server_windows.go
<ide> import (
<ide> "net"
<ide> "net/http"
<ide>
<del> "github.com/docker/docker/context"
<ide> "github.com/docker/docker/daemon"
<ide> )
<ide>
<ide> func (s *Server) newServer(proto, addr string) ([]serverCloser, error) {
<ide> }
<ide>
<ide> // AcceptConnections allows router to start listening for the incoming requests.
<del>func (s *Server) AcceptConnections(ctx context.Context, d *daemon.Daemon) {
<add>func (s *Server) AcceptConnections(d *daemon.Daemon) {
<ide> s.daemon = d
<del> s.registerSubRouter(ctx)
<add> s.registerSubRouter()
<ide> // close the lock so the listeners start accepting connections
<ide> select {
<ide> case <-s.start:
<ide><path>builder/dispatchers.go
<ide> func from(ctx context.Context, b *builder, args []string, attributes map[string]
<ide> return nil
<ide> }
<ide>
<del> image, err := b.Daemon.Repositories(ctx).LookupImage(name)
<add> image, err := b.Daemon.Repositories().LookupImage(name)
<ide> if b.Pull {
<ide> image, err = b.pullImage(ctx, name)
<ide> if err != nil {
<ide> return err
<ide> }
<ide> }
<ide> if err != nil {
<del> if b.Daemon.Graph(ctx).IsNotExist(err, name) {
<add> if b.Daemon.Graph().IsNotExist(err, name) {
<ide> image, err = b.pullImage(ctx, name)
<ide> }
<ide>
<ide><path>builder/internals.go
<ide> func (b *builder) commit(ctx context.Context, id string, autoCmd *stringutils.St
<ide> if err != nil {
<ide> return err
<ide> }
<del> b.Daemon.Graph(ctx).Retain(b.id, image.ID)
<add> b.Daemon.Graph().Retain(b.id, image.ID)
<ide> b.activeImages = append(b.activeImages, image.ID)
<ide> b.image = image.ID
<ide> return nil
<ide> func (b *builder) pullImage(ctx context.Context, name string) (*image.Image, err
<ide> OutStream: ioutils.NopWriteCloser(b.OutOld),
<ide> }
<ide>
<del> if err := b.Daemon.Repositories(ctx).Pull(ctx, remote, tag, imagePullConfig); err != nil {
<add> if err := b.Daemon.Repositories().Pull(ctx, remote, tag, imagePullConfig); err != nil {
<ide> return nil, err
<ide> }
<ide>
<del> image, err := b.Daemon.Repositories(ctx).LookupImage(name)
<add> image, err := b.Daemon.Repositories().LookupImage(name)
<ide> if err != nil {
<ide> return nil, err
<ide> }
<ide> func (b *builder) probeCache(ctx context.Context) (bool, error) {
<ide> fmt.Fprintf(b.OutStream, " ---> Using cache\n")
<ide> logrus.Debugf("[BUILDER] Use cached version")
<ide> b.image = cache.ID
<del> b.Daemon.Graph(ctx).Retain(b.id, cache.ID)
<add> b.Daemon.Graph().Retain(b.id, cache.ID)
<ide> b.activeImages = append(b.activeImages, cache.ID)
<ide> return true, nil
<ide> }
<ide><path>builder/job.go
<ide> func Build(ctx context.Context, d *daemon.Daemon, buildConfig *Config) error {
<ide> }
<ide>
<ide> defer func() {
<del> builder.Daemon.Graph(ctx).Release(builder.id, builder.activeImages...)
<add> builder.Daemon.Graph().Release(builder.id, builder.activeImages...)
<ide> }()
<ide>
<ide> id, err := builder.Run(ctx, context)
<ide> if err != nil {
<ide> return err
<ide> }
<ide> if repoName != "" {
<del> return d.Repositories(ctx).Tag(repoName, tag, id, true)
<add> return d.Repositories().Tag(repoName, tag, id, true)
<ide> }
<ide> return nil
<ide> }
<ide><path>daemon/create.go
<ide> func (daemon *Daemon) ContainerCreate(ctx context.Context, name string, config *
<ide>
<ide> container, buildWarnings, err := daemon.Create(ctx, config, hostConfig, name)
<ide> if err != nil {
<del> if daemon.Graph(ctx).IsNotExist(err, config.Image) {
<add> if daemon.Graph().IsNotExist(err, config.Image) {
<ide> if strings.Contains(config.Image, "@") {
<ide> return nil, warnings, derr.ErrorCodeNoSuchImageHash.WithArgs(config.Image)
<ide> }
<ide><path>daemon/daemon.go
<ide> func (daemon *Daemon) ensureName(container *Container) error {
<ide> return nil
<ide> }
<ide>
<del>func (daemon *Daemon) restore(ctx context.Context) error {
<add>func (daemon *Daemon) restore() error {
<ide> type cr struct {
<ide> container *Container
<ide> registered bool
<ide> func (daemon *Daemon) restore(ctx context.Context) error {
<ide> }
<ide>
<ide> group := sync.WaitGroup{}
<add> ctx := context.Background()
<ide> for _, c := range containers {
<ide> group.Add(1)
<ide>
<ide> func (daemon *Daemon) registerLink(parent, child *Container, alias string) error
<ide>
<ide> // NewDaemon sets up everything for the daemon to be able to service
<ide> // requests from the webserver.
<del>func NewDaemon(ctx context.Context, config *Config, registryService *registry.Service) (daemon *Daemon, err error) {
<add>func NewDaemon(config *Config, registryService *registry.Service) (daemon *Daemon, err error) {
<ide> setDefaultMtu(config)
<ide>
<ide> // Ensure we have compatible configuration options
<ide> func NewDaemon(ctx context.Context, config *Config, registryService *registry.Se
<ide> // Ensure the graph driver is shutdown at a later point
<ide> defer func() {
<ide> if err != nil {
<del> if err := d.Shutdown(ctx); err != nil {
<add> if err := d.Shutdown(context.Background()); err != nil {
<ide> logrus.Error(err)
<ide> }
<ide> }
<ide> func NewDaemon(ctx context.Context, config *Config, registryService *registry.Se
<ide>
<ide> go d.execCommandGC()
<ide>
<del> if err := d.restore(ctx); err != nil {
<add> if err := d.restore(); err != nil {
<ide> return nil, err
<ide> }
<ide>
<ide> func (daemon *Daemon) Shutdown(ctx context.Context) error {
<ide> if daemon.containers != nil {
<ide> group := sync.WaitGroup{}
<ide> logrus.Debug("starting clean shutdown of all containers...")
<del> for _, container := range daemon.List(ctx) {
<add> for _, container := range daemon.List() {
<ide> c := container
<ide> if c.IsRunning() {
<ide> logrus.Debugf("stopping %s", c.ID)
<ide> func (daemon *Daemon) createRootfs(container *Container) error {
<ide> // which need direct access to daemon.graph.
<ide> // Once the tests switch to using engine and jobs, this method
<ide> // can go away.
<del>func (daemon *Daemon) Graph(ctx context.Context) *graph.Graph {
<add>func (daemon *Daemon) Graph() *graph.Graph {
<ide> return daemon.graph
<ide> }
<ide>
<ide> // Repositories returns all repositories.
<del>func (daemon *Daemon) Repositories(ctx context.Context) *graph.TagStore {
<add>func (daemon *Daemon) Repositories() *graph.TagStore {
<ide> return daemon.repositories
<ide> }
<ide>
<ide> func (daemon *Daemon) systemInitPath() string {
<ide>
<ide> // GraphDriver returns the currently used driver for processing
<ide> // container layers.
<del>func (daemon *Daemon) GraphDriver(ctx context.Context) graphdriver.Driver {
<add>func (daemon *Daemon) GraphDriver() graphdriver.Driver {
<ide> return daemon.driver
<ide> }
<ide>
<ide> // ExecutionDriver returns the currently used driver for creating and
<ide> // starting execs in a container.
<del>func (daemon *Daemon) ExecutionDriver(ctx context.Context) execdriver.Driver {
<add>func (daemon *Daemon) ExecutionDriver() execdriver.Driver {
<ide> return daemon.execDriver
<ide> }
<ide>
<ide> func (daemon *Daemon) containerGraph() *graphdb.Database {
<ide> // returned if the parent image cannot be found.
<ide> func (daemon *Daemon) ImageGetCached(ctx context.Context, imgID string, config *runconfig.Config) (*image.Image, error) {
<ide> // Retrieve all images
<del> images := daemon.Graph(ctx).Map()
<add> images := daemon.Graph().Map()
<ide>
<ide> // Store the tree in a map of map (map[parentId][childId])
<ide> imageMap := make(map[string]map[string]struct{})
<ide><path>daemon/daemon_unix.go
<ide> func verifyPlatformContainerSettings(ctx context.Context, daemon *Daemon, hostCo
<ide> warnings := []string{}
<ide> sysInfo := sysinfo.New(true)
<ide>
<del> if hostConfig.LxcConf.Len() > 0 && !strings.Contains(daemon.ExecutionDriver(ctx).Name(), "lxc") {
<del> return warnings, fmt.Errorf("Cannot use --lxc-conf with execdriver: %s", daemon.ExecutionDriver(ctx).Name())
<add> if hostConfig.LxcConf.Len() > 0 && !strings.Contains(daemon.ExecutionDriver().Name(), "lxc") {
<add> return warnings, fmt.Errorf("Cannot use --lxc-conf with execdriver: %s", daemon.ExecutionDriver().Name())
<ide> }
<ide>
<ide> // memory subsystem checks and adjustments
<ide> func setupInitLayer(initLayer string) error {
<ide>
<ide> // NetworkAPIRouter implements a feature for server-experimental,
<ide> // directly calling into libnetwork.
<del>func (daemon *Daemon) NetworkAPIRouter(ctx context.Context) func(w http.ResponseWriter, req *http.Request) {
<add>func (daemon *Daemon) NetworkAPIRouter() func(w http.ResponseWriter, req *http.Request) {
<ide> return nwapi.NewHTTPHandler(daemon.netController)
<ide> }
<ide>
<ide><path>daemon/image_delete.go
<ide> import (
<ide> func (daemon *Daemon) ImageDelete(ctx context.Context, imageRef string, force, prune bool) ([]types.ImageDelete, error) {
<ide> records := []types.ImageDelete{}
<ide>
<del> img, err := daemon.Repositories(ctx).LookupImage(imageRef)
<add> img, err := daemon.Repositories().LookupImage(imageRef)
<ide> if err != nil {
<ide> return nil, err
<ide> }
<ide> func (daemon *Daemon) ImageDelete(ctx context.Context, imageRef string, force, p
<ide> // true, there are multiple repository references to this
<ide> // image, or there are no containers using the given reference.
<ide> if !(force || daemon.imageHasMultipleRepositoryReferences(ctx, img.ID)) {
<del> if container := daemon.getContainerUsingImage(ctx, img.ID); container != nil {
<add> if container := daemon.getContainerUsingImage(img.ID); container != nil {
<ide> // If we removed the repository reference then
<ide> // this image would remain "dangling" and since
<ide> // we really want to avoid that the client must
<ide> func (daemon *Daemon) ImageDelete(ctx context.Context, imageRef string, force, p
<ide> // repository reference to the image then we will want to
<ide> // remove that reference.
<ide> // FIXME: Is this the behavior we want?
<del> repoRefs := daemon.Repositories(ctx).ByID()[img.ID]
<add> repoRefs := daemon.Repositories().ByID()[img.ID]
<ide> if len(repoRefs) == 1 {
<ide> parsedRef, err := daemon.removeImageRef(ctx, repoRefs[0])
<ide> if err != nil {
<ide> func isImageIDPrefix(imageID, possiblePrefix string) bool {
<ide> // imageHasMultipleRepositoryReferences returns whether there are multiple
<ide> // repository references to the given imageID.
<ide> func (daemon *Daemon) imageHasMultipleRepositoryReferences(ctx context.Context, imageID string) bool {
<del> return len(daemon.Repositories(ctx).ByID()[imageID]) > 1
<add> return len(daemon.Repositories().ByID()[imageID]) > 1
<ide> }
<ide>
<ide> // getContainerUsingImage returns a container that was created using the given
<ide> // imageID. Returns nil if there is no such container.
<del>func (daemon *Daemon) getContainerUsingImage(ctx context.Context, imageID string) *Container {
<del> for _, container := range daemon.List(ctx) {
<add>func (daemon *Daemon) getContainerUsingImage(imageID string) *Container {
<add> for _, container := range daemon.List() {
<ide> if container.ImageID == imageID {
<ide> return container
<ide> }
<ide> func (daemon *Daemon) removeImageRef(ctx context.Context, repositoryRef string)
<ide> // Ignore the boolean value returned, as far as we're concerned, this
<ide> // is an idempotent operation and it's okay if the reference didn't
<ide> // exist in the first place.
<del> _, err := daemon.Repositories(ctx).Delete(repository, ref)
<add> _, err := daemon.Repositories().Delete(repository, ref)
<ide>
<ide> return utils.ImageReference(repository, ref), err
<ide> }
<ide> func (daemon *Daemon) removeImageRef(ctx context.Context, repositoryRef string)
<ide> // daemon's event service. An "Untagged" types.ImageDelete is added to the
<ide> // given list of records.
<ide> func (daemon *Daemon) removeAllReferencesToImageID(ctx context.Context, imgID string, records *[]types.ImageDelete) error {
<del> imageRefs := daemon.Repositories(ctx).ByID()[imgID]
<add> imageRefs := daemon.Repositories().ByID()[imgID]
<ide>
<ide> for _, imageRef := range imageRefs {
<ide> parsedRef, err := daemon.removeImageRef(ctx, imageRef)
<ide> func (daemon *Daemon) imageDeleteHelper(ctx context.Context, img *image.Image, r
<ide> return err
<ide> }
<ide>
<del> if err := daemon.Graph(ctx).Delete(img.ID); err != nil {
<add> if err := daemon.Graph().Delete(img.ID); err != nil {
<ide> return err
<ide> }
<ide>
<ide> func (daemon *Daemon) imageDeleteHelper(ctx context.Context, img *image.Image, r
<ide> // We need to prune the parent image. This means delete it if there are
<ide> // no tags/digests referencing it and there are no containers using it (
<ide> // either running or stopped).
<del> parentImg, err := daemon.Graph(ctx).Get(img.Parent)
<add> parentImg, err := daemon.Graph().Get(img.Parent)
<ide> if err != nil {
<ide> return derr.ErrorCodeImgNoParent.WithArgs(err)
<ide> }
<ide> func (daemon *Daemon) checkImageDeleteConflict(ctx context.Context, img *image.I
<ide>
<ide> func (daemon *Daemon) checkImageDeleteHardConflict(ctx context.Context, img *image.Image) *imageDeleteConflict {
<ide> // Check if the image ID is being used by a pull or build.
<del> if daemon.Graph(ctx).IsHeld(img.ID) {
<add> if daemon.Graph().IsHeld(img.ID) {
<ide> return &imageDeleteConflict{
<ide> hard: true,
<ide> imgID: img.ID,
<ide> func (daemon *Daemon) checkImageDeleteHardConflict(ctx context.Context, img *ima
<ide> }
<ide>
<ide> // Check if the image has any descendent images.
<del> if daemon.Graph(ctx).HasChildren(img) {
<add> if daemon.Graph().HasChildren(img) {
<ide> return &imageDeleteConflict{
<ide> hard: true,
<ide> imgID: img.ID,
<ide> func (daemon *Daemon) checkImageDeleteHardConflict(ctx context.Context, img *ima
<ide> }
<ide>
<ide> // Check if any running container is using the image.
<del> for _, container := range daemon.List(ctx) {
<add> for _, container := range daemon.List() {
<ide> if !container.IsRunning() {
<ide> // Skip this until we check for soft conflicts later.
<ide> continue
<ide> func (daemon *Daemon) checkImageDeleteHardConflict(ctx context.Context, img *ima
<ide>
<ide> func (daemon *Daemon) checkImageDeleteSoftConflict(ctx context.Context, img *image.Image) *imageDeleteConflict {
<ide> // Check if any repository tags/digest reference this image.
<del> if daemon.Repositories(ctx).HasReferences(img) {
<add> if daemon.Repositories().HasReferences(img) {
<ide> return &imageDeleteConflict{
<ide> imgID: img.ID,
<ide> message: "image is referenced in one or more repositories",
<ide> }
<ide> }
<ide>
<ide> // Check if any stopped containers reference this image.
<del> for _, container := range daemon.List(ctx) {
<add> for _, container := range daemon.List() {
<ide> if container.IsRunning() {
<ide> // Skip this as it was checked above in hard conflict conditions.
<ide> continue
<ide> func (daemon *Daemon) checkImageDeleteSoftConflict(ctx context.Context, img *ima
<ide> // that there are no repository references to the given image and it has no
<ide> // child images.
<ide> func (daemon *Daemon) imageIsDangling(ctx context.Context, img *image.Image) bool {
<del> return !(daemon.Repositories(ctx).HasReferences(img) || daemon.Graph(ctx).HasChildren(img))
<add> return !(daemon.Repositories().HasReferences(img) || daemon.Graph().HasChildren(img))
<ide> }
<ide><path>daemon/info.go
<ide> import (
<ide>
<ide> // SystemInfo returns information about the host server the daemon is running on.
<ide> func (daemon *Daemon) SystemInfo(ctx context.Context) (*types.Info, error) {
<del> images := daemon.Graph(ctx).Map()
<add> images := daemon.Graph().Map()
<ide> var imgcount int
<ide> if images == nil {
<ide> imgcount = 0
<ide> func (daemon *Daemon) SystemInfo(ctx context.Context) (*types.Info, error) {
<ide>
<ide> v := &types.Info{
<ide> ID: daemon.ID,
<del> Containers: len(daemon.List(ctx)),
<add> Containers: len(daemon.List()),
<ide> Images: imgcount,
<del> Driver: daemon.GraphDriver(ctx).String(),
<del> DriverStatus: daemon.GraphDriver(ctx).Status(),
<add> Driver: daemon.GraphDriver().String(),
<add> DriverStatus: daemon.GraphDriver().Status(),
<ide> IPv4Forwarding: !sysInfo.IPv4ForwardingDisabled,
<ide> BridgeNfIptables: !sysInfo.BridgeNfCallIptablesDisabled,
<ide> BridgeNfIP6tables: !sysInfo.BridgeNfCallIP6tablesDisabled,
<ide> Debug: os.Getenv("DEBUG") != "",
<ide> NFd: fileutils.GetTotalUsedFds(),
<ide> NGoroutines: runtime.NumGoroutine(),
<ide> SystemTime: time.Now().Format(time.RFC3339Nano),
<del> ExecutionDriver: daemon.ExecutionDriver(ctx).Name(),
<add> ExecutionDriver: daemon.ExecutionDriver().Name(),
<ide> LoggingDriver: daemon.defaultLogConfig.Type,
<ide> NEventsListener: daemon.EventsService.SubscribersCount(),
<ide> KernelVersion: kernelVersion,
<ide><path>daemon/list.go
<ide> const (
<ide> var errStopIteration = errors.New("container list iteration stopped")
<ide>
<ide> // List returns an array of all containers registered in the daemon.
<del>func (daemon *Daemon) List(ctx context.Context) []*Container {
<add>func (daemon *Daemon) List() []*Container {
<ide> return daemon.containers.List()
<ide> }
<ide>
<ide> func (daemon *Daemon) reduceContainers(ctx context.Context, config *ContainersCo
<ide> return nil, err
<ide> }
<ide>
<del> for _, container := range daemon.List(ctx) {
<add> for _, container := range daemon.List() {
<ide> t, err := daemon.reducePsContainer(ctx, container, fctx, reducer)
<ide> if err != nil {
<ide> if err != errStopIteration {
<ide> func (daemon *Daemon) foldFilter(ctx context.Context, config *ContainersConfig)
<ide> var ancestorFilter bool
<ide> if ancestors, ok := psFilters["ancestor"]; ok {
<ide> ancestorFilter = true
<del> byParents := daemon.Graph(ctx).ByParent()
<add> byParents := daemon.Graph().ByParent()
<ide> // The idea is to walk the graph down the most "efficient" way.
<ide> for _, ancestor := range ancestors {
<ide> // First, get the imageId of the ancestor filter (yay)
<del> image, err := daemon.Repositories(ctx).LookupImage(ancestor)
<add> image, err := daemon.Repositories().LookupImage(ancestor)
<ide> if err != nil {
<ide> logrus.Warnf("Error while looking up for image %v", ancestor)
<ide> continue
<ide> func (daemon *Daemon) transformContainer(ctx context.Context, container *Contain
<ide> Names: lctx.names[container.ID],
<ide> }
<ide>
<del> img, err := daemon.Repositories(ctx).LookupImage(container.Config.Image)
<add> img, err := daemon.Repositories().LookupImage(container.Config.Image)
<ide> if err != nil {
<ide> // If the image can no longer be found by its original reference,
<ide> // it makes sense to show the ID instead of a stale reference.
<ide><path>daemon/top_unix.go
<ide> func (daemon *Daemon) ContainerTop(ctx context.Context, name string, psArgs stri
<ide> return nil, derr.ErrorCodeNotRunning.WithArgs(name)
<ide> }
<ide>
<del> pids, err := daemon.ExecutionDriver(ctx).GetPidsForContainer(container.ID)
<add> pids, err := daemon.ExecutionDriver().GetPidsForContainer(container.ID)
<ide> if err != nil {
<ide> return nil, err
<ide> }
<ide><path>docker/daemon.go
<ide> func getGlobalFlag() (globalFlag *flag.Flag) {
<ide>
<ide> // CmdDaemon is the daemon command, called the raw arguments after `docker daemon`.
<ide> func (cli *DaemonCli) CmdDaemon(args ...string) error {
<del> // This may need to be made even more global - it all depends
<del> // on whether we want the CLI to have a context object too.
<del> // For now we'll leave it as a daemon-side object only.
<del> ctx := context.Background()
<del>
<ide> // warn from uuid package when running the daemon
<ide> uuid.Loggerf = logrus.Warnf
<ide>
<ide> func (cli *DaemonCli) CmdDaemon(args ...string) error {
<ide> serverConfig.TLSConfig = tlsConfig
<ide> }
<ide>
<del> api := apiserver.New(ctx, serverConfig)
<add> api := apiserver.New(serverConfig)
<ide>
<ide> // The serve API routine never exits unless an error occurs
<ide> // We need to start it as a goroutine and wait on it so
<ide> func (cli *DaemonCli) CmdDaemon(args ...string) error {
<ide> cli.TrustKeyPath = commonFlags.TrustKey
<ide>
<ide> registryService := registry.NewService(cli.registryOptions)
<del> d, err := daemon.NewDaemon(ctx, cli.Config, registryService)
<add> d, err := daemon.NewDaemon(cli.Config, registryService)
<ide> if err != nil {
<ide> if pfile != nil {
<ide> if err := pfile.Remove(); err != nil {
<ide> func (cli *DaemonCli) CmdDaemon(args ...string) error {
<ide> logrus.WithFields(logrus.Fields{
<ide> "version": dockerversion.VERSION,
<ide> "commit": dockerversion.GITCOMMIT,
<del> "execdriver": d.ExecutionDriver(ctx).Name(),
<del> "graphdriver": d.GraphDriver(ctx).String(),
<add> "execdriver": d.ExecutionDriver().Name(),
<add> "graphdriver": d.GraphDriver().String(),
<ide> }).Info("Docker daemon")
<ide>
<ide> signal.Trap(func() {
<ide> api.Close()
<ide> <-serveAPIWait
<del> shutdownDaemon(ctx, d, 15)
<add> shutdownDaemon(d, 15)
<ide> if pfile != nil {
<ide> if err := pfile.Remove(); err != nil {
<ide> logrus.Error(err)
<ide> func (cli *DaemonCli) CmdDaemon(args ...string) error {
<ide>
<ide> // after the daemon is done setting up we can tell the api to start
<ide> // accepting connections with specified daemon
<del> api.AcceptConnections(ctx, d)
<add> api.AcceptConnections(d)
<ide>
<ide> // Daemon is fully initialized and handling API traffic
<ide> // Wait for serve API to complete
<ide> errAPI := <-serveAPIWait
<del> shutdownDaemon(ctx, d, 15)
<add> shutdownDaemon(d, 15)
<ide> if errAPI != nil {
<ide> if pfile != nil {
<ide> if err := pfile.Remove(); err != nil {
<ide> func (cli *DaemonCli) CmdDaemon(args ...string) error {
<ide> // shutdownDaemon just wraps daemon.Shutdown() to handle a timeout in case
<ide> // d.Shutdown() is waiting too long to kill container or worst it's
<ide> // blocked there
<del>func shutdownDaemon(ctx context.Context, d *daemon.Daemon, timeout time.Duration) {
<add>func shutdownDaemon(d *daemon.Daemon, timeout time.Duration) {
<ide> ch := make(chan struct{})
<ide> go func() {
<del> d.Shutdown(ctx)
<add> d.Shutdown(context.Background())
<ide> close(ch)
<ide> }()
<ide> select { | 17 |
Text | Text | fix typo in hmac.paramnames default | 802ceea905848fea64a4d0630ebff1e949dc3707 | <ide><path>doc/api/webcrypto.md
<ide> added: v15.0.0
<ide> added: v15.0.0
<ide> -->
<ide>
<del>* Type: {string} Must be `'HMAC`.
<add>* Type: {string} Must be `'HMAC'`.
<ide>
<ide> ### Class: `Pbkdf2ImportParams`
<ide> <!-- YAML | 1 |
Javascript | Javascript | reduce unmanaged parallelism in domain test | a1652324cd8cc77a1964286fa49900d89755ab0d | <ide><path>test/common.js
<ide> exports.hasIPv6 = Object.keys(ifaces).some(function(name) {
<ide> });
<ide> });
<ide>
<add>/*
<add> * Check that when running a test with
<add> * `$node --abort-on-uncaught-exception $file child`
<add> * the process aborts.
<add> */
<add>exports.childShouldThrowAndAbort = function() {
<add> var testCmd = '';
<add> if (!exports.isWindows) {
<add> // Do not create core files, as it can take a lot of disk space on
<add> // continuous testing and developers' machines
<add> testCmd += 'ulimit -c 0 && ';
<add> }
<add> testCmd += `${process.argv[0]} --abort-on-uncaught-exception `;
<add> testCmd += `${process.argv[1]} child`;
<add> const child = child_process.exec(testCmd);
<add> child.on('exit', function onExit(exitCode, signal) {
<add> const errMsg = 'Test should have aborted ' +
<add> `but instead exited with exit code ${exitCode}` +
<add> ` and signal ${signal}`;
<add> assert(exports.nodeProcessAborted(exitCode, signal), errMsg);
<add> });
<add>};
<ide>
<ide> exports.ddCommand = function(filename, kilobytes) {
<ide> if (exports.isWindows) {
<ide><path>test/parallel/test-domain-no-error-handler-abort-on-uncaught-0.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>const domain = require('domain');
<add>
<add>function test() {
<add> const d = domain.create();
<add>
<add> d.run(function() {
<add> throw new Error('boom!');
<add> });
<add>}
<add>
<add>if (process.argv[2] === 'child') {
<add> test();
<add>} else {
<add> common.childShouldThrowAndAbort();
<add>}
<ide><path>test/parallel/test-domain-no-error-handler-abort-on-uncaught-1.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>const domain = require('domain');
<add>
<add>function test() {
<add> const d = domain.create();
<add> const d2 = domain.create();
<add>
<add> d.run(function() {
<add> d2.run(function() {
<add> throw new Error('boom!');
<add> });
<add> });
<add>}
<add>
<add>if (process.argv[2] === 'child') {
<add> test();
<add>} else {
<add> common.childShouldThrowAndAbort();
<add>}
<ide><path>test/parallel/test-domain-no-error-handler-abort-on-uncaught-2.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>const domain = require('domain');
<add>
<add>function test() {
<add> const d = domain.create();
<add>
<add> d.run(function() {
<add> setTimeout(function() {
<add> throw new Error('boom!');
<add> }, 1);
<add> });
<add>}
<add>
<add>if (process.argv[2] === 'child') {
<add> test();
<add>} else {
<add> common.childShouldThrowAndAbort();
<add>}
<ide><path>test/parallel/test-domain-no-error-handler-abort-on-uncaught-3.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>const domain = require('domain');
<add>
<add>function test() {
<add> const d = domain.create();
<add>
<add> d.run(function() {
<add> setImmediate(function() {
<add> throw new Error('boom!');
<add> });
<add> });
<add>}
<add>
<add>if (process.argv[2] === 'child') {
<add> test();
<add>} else {
<add> common.childShouldThrowAndAbort();
<add>}
<ide><path>test/parallel/test-domain-no-error-handler-abort-on-uncaught-4.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>const domain = require('domain');
<add>
<add>function test() {
<add> const d = domain.create();
<add>
<add> d.run(function() {
<add> process.nextTick(function() {
<add> throw new Error('boom!');
<add> });
<add> });
<add>}
<add>
<add>if (process.argv[2] === 'child') {
<add> test();
<add>} else {
<add> common.childShouldThrowAndAbort();
<add>}
<ide><path>test/parallel/test-domain-no-error-handler-abort-on-uncaught-5.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>const domain = require('domain');
<add>
<add>function test() {
<add> const d = domain.create();
<add>
<add> d.run(function() {
<add> var fs = require('fs');
<add> fs.exists('/non/existing/file', function onExists() {
<add> throw new Error('boom!');
<add> });
<add> });
<add>}
<add>
<add>if (process.argv[2] === 'child') {
<add> test();
<add>} else {
<add> common.childShouldThrowAndAbort();
<add>}
<ide><path>test/parallel/test-domain-no-error-handler-abort-on-uncaught-6.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>const domain = require('domain');
<add>
<add>function test() {
<add> const d = domain.create();
<add> const d2 = domain.create();
<add>
<add> d.on('error', function errorHandler() {
<add> });
<add>
<add> d.run(function() {
<add> d2.run(function() {
<add> setTimeout(function() {
<add> throw new Error('boom!');
<add> }, 1);
<add> });
<add> });
<add>}
<add>
<add>if (process.argv[2] === 'child') {
<add> test();
<add>} else {
<add> common.childShouldThrowAndAbort();
<add>}
<ide><path>test/parallel/test-domain-no-error-handler-abort-on-uncaught-7.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>const domain = require('domain');
<add>
<add>function test() {
<add> const d = domain.create();
<add> const d2 = domain.create();
<add>
<add> d.on('error', function errorHandler() {
<add> });
<add>
<add> d.run(function() {
<add> d2.run(function() {
<add> setImmediate(function() {
<add> throw new Error('boom!');
<add> });
<add> });
<add> });
<add>}
<add>
<add>if (process.argv[2] === 'child') {
<add> test();
<add>} else {
<add> common.childShouldThrowAndAbort();
<add>}
<ide><path>test/parallel/test-domain-no-error-handler-abort-on-uncaught-8.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>const domain = require('domain');
<add>
<add>function test() {
<add> const d = domain.create();
<add> const d2 = domain.create();
<add>
<add> d.on('error', function errorHandler() {
<add> });
<add>
<add> d.run(function() {
<add> d2.run(function() {
<add> process.nextTick(function() {
<add> throw new Error('boom!');
<add> });
<add> });
<add> });
<add>}
<add>
<add>if (process.argv[2] === 'child') {
<add> test();
<add>} else {
<add> common.childShouldThrowAndAbort();
<add>}
<ide><path>test/parallel/test-domain-no-error-handler-abort-on-uncaught-9.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>const domain = require('domain');
<add>
<add>function test() {
<add> const d = domain.create();
<add> const d2 = domain.create();
<add>
<add> d.on('error', function errorHandler() {
<add> });
<add>
<add> d.run(function() {
<add> d2.run(function() {
<add> var fs = require('fs');
<add> fs.exists('/non/existing/file', function onExists() {
<add> throw new Error('boom!');
<add> });
<add> });
<add> });
<add>}
<add>
<add>if (process.argv[2] === 'child') {
<add> test();
<add>} else {
<add> common.childShouldThrowAndAbort();
<add>}
<ide><path>test/parallel/test-domain-no-error-handler-abort-on-uncaught.js
<del>'use strict';
<del>
<del>/*
<del> * This test makes sure that when using --abort-on-uncaught-exception and
<del> * when throwing an error from within a domain that does not have an error
<del> * handler setup, the process aborts.
<del> */
<del>const common = require('../common');
<del>const assert = require('assert');
<del>const domain = require('domain');
<del>const child_process = require('child_process');
<del>
<del>const tests = [
<del> function() {
<del> const d = domain.create();
<del>
<del> d.run(function() {
<del> throw new Error('boom!');
<del> });
<del> },
<del>
<del> function() {
<del> const d = domain.create();
<del> const d2 = domain.create();
<del>
<del> d.run(function() {
<del> d2.run(function() {
<del> throw new Error('boom!');
<del> });
<del> });
<del> },
<del>
<del> function() {
<del> const d = domain.create();
<del>
<del> d.run(function() {
<del> setTimeout(function() {
<del> throw new Error('boom!');
<del> }, 1);
<del> });
<del> },
<del>
<del> function() {
<del> const d = domain.create();
<del>
<del> d.run(function() {
<del> setImmediate(function() {
<del> throw new Error('boom!');
<del> });
<del> });
<del> },
<del>
<del> function() {
<del> const d = domain.create();
<del>
<del> d.run(function() {
<del> process.nextTick(function() {
<del> throw new Error('boom!');
<del> });
<del> });
<del> },
<del>
<del> function() {
<del> const d = domain.create();
<del>
<del> d.run(function() {
<del> var fs = require('fs');
<del> fs.exists('/non/existing/file', function onExists() {
<del> throw new Error('boom!');
<del> });
<del> });
<del> },
<del>
<del> function() {
<del> const d = domain.create();
<del> const d2 = domain.create();
<del>
<del> d.on('error', function errorHandler() {
<del> });
<del>
<del> d.run(function() {
<del> d2.run(function() {
<del> setTimeout(function() {
<del> throw new Error('boom!');
<del> }, 1);
<del> });
<del> });
<del> },
<del>
<del> function() {
<del> const d = domain.create();
<del> const d2 = domain.create();
<del>
<del> d.on('error', function errorHandler() {
<del> });
<del>
<del> d.run(function() {
<del> d2.run(function() {
<del> setImmediate(function() {
<del> throw new Error('boom!');
<del> });
<del> });
<del> });
<del> },
<del>
<del> function() {
<del> const d = domain.create();
<del> const d2 = domain.create();
<del>
<del> d.on('error', function errorHandler() {
<del> });
<del>
<del> d.run(function() {
<del> d2.run(function() {
<del> process.nextTick(function() {
<del> throw new Error('boom!');
<del> });
<del> });
<del> });
<del> },
<del>
<del> function() {
<del> const d = domain.create();
<del> const d2 = domain.create();
<del>
<del> d.on('error', function errorHandler() {
<del> });
<del>
<del> d.run(function() {
<del> d2.run(function() {
<del> var fs = require('fs');
<del> fs.exists('/non/existing/file', function onExists() {
<del> throw new Error('boom!');
<del> });
<del> });
<del> });
<del> },
<del>];
<del>
<del>if (process.argv[2] === 'child') {
<del> const testIndex = +process.argv[3];
<del> tests[testIndex]();
<del>} else {
<del>
<del> tests.forEach(function(test, testIndex) {
<del> var testCmd = '';
<del> if (!common.isWindows) {
<del> // Do not create core files, as it can take a lot of disk space on
<del> // continuous testing and developers' machines
<del> testCmd += 'ulimit -c 0 && ';
<del> }
<del>
<del> testCmd += process.argv[0];
<del> testCmd += ' ' + '--abort-on-uncaught-exception';
<del> testCmd += ' ' + process.argv[1];
<del> testCmd += ' ' + 'child';
<del> testCmd += ' ' + testIndex;
<del>
<del> var child = child_process.exec(testCmd);
<del>
<del> child.on('exit', function onExit(exitCode, signal) {
<del> const errMsg = 'Test at index ' + testIndex + ' should have aborted ' +
<del> 'but instead exited with exit code ' + exitCode +
<del> ' and signal ' + signal;
<del> assert(common.nodeProcessAborted(exitCode, signal), errMsg);
<del> });
<del> });
<del>} | 12 |
Python | Python | add l1 penalty option to parser | 35124b144a4b25f8377fcbbf0ab32fbffc3320eb | <ide><path>bin/parser/train.py
<ide> def score_model(scorer, nlp, raw_text, annot_tuples, verbose=False):
<ide>
<ide> def train(Language, train_data, dev_data, model_dir, tagger_cfg, parser_cfg, entity_cfg,
<ide> n_iter=15, seed=0, gold_preproc=False, n_sents=0, corruption_level=0):
<del> print("Itn.\tP.Loss\tN feats\tUAS\tNER F.\tTag %\tToken %")
<add> print("Itn.\tN weight\tN feats\tUAS\tNER F.\tTag %\tToken %")
<ide> format_str = '{:d}\t{:d}\t{:d}\t{uas:.3f}\t{ents_f:.3f}\t{tags_acc:.3f}\t{token_acc:.3f}'
<ide> with Language.train(model_dir, train_data,
<ide> tagger_cfg, parser_cfg, entity_cfg) as trainer:
<ide> def train(Language, train_data, dev_data, model_dir, tagger_cfg, parser_cfg, ent
<ide> for doc, gold in epoch:
<ide> trainer.update(doc, gold)
<ide> dev_scores = trainer.evaluate(dev_data, gold_preproc=gold_preproc)
<del> print(format_str.format(itn, loss,
<add> print(format_str.format(itn, trainer.nlp.parser.model.nr_weight,
<ide> trainer.nlp.parser.model.nr_active_feat, **dev_scores.scores))
<ide>
<ide>
<ide> def evaluate(Language, gold_tuples, model_dir, gold_preproc=False, verbose=False,
<ide> beam_width=None, cand_preproc=None):
<add> print("Load parser", model_dir)
<ide> nlp = Language(path=model_dir)
<ide> if nlp.lang == 'de':
<ide> nlp.vocab.morphology.lemmatizer = lambda string,pos: set([string])
<ide> def write_parses(Language, dev_loc, model_dir, out_loc):
<ide> verbose=("Verbose error reporting", "flag", "v", bool),
<ide> debug=("Debug mode", "flag", "d", bool),
<ide> pseudoprojective=("Use pseudo-projective parsing", "flag", "p", bool),
<add> L1=("L1 regularization penalty", "option", "L", float),
<ide> )
<ide> def main(language, train_loc, dev_loc, model_dir, n_sents=0, n_iter=15, out_loc="", verbose=False,
<del> debug=False, corruption_level=0.0, gold_preproc=False, eval_only=False, pseudoprojective=False):
<add> debug=False, corruption_level=0.0, gold_preproc=False, eval_only=False, pseudoprojective=False,
<add> L1=1e-6):
<ide> parser_cfg = dict(locals())
<ide> tagger_cfg = dict(locals())
<ide> entity_cfg = dict(locals())
<ide>
<ide> lang = spacy.util.get_lang_class(language)
<del>
<add>
<ide> parser_cfg['features'] = lang.Defaults.parser_features
<ide> entity_cfg['features'] = lang.Defaults.entity_features
<ide>
<ide> if not eval_only:
<ide> gold_train = list(read_json_file(train_loc))
<ide> gold_dev = list(read_json_file(dev_loc))
<del> gold_train = gold_train[:n_sents]
<add> if n_sents > 0:
<add> gold_train = gold_train[:n_sents]
<ide> train(lang, gold_train, gold_dev, model_dir, tagger_cfg, parser_cfg, entity_cfg,
<ide> n_sents=n_sents, gold_preproc=gold_preproc, corruption_level=corruption_level,
<ide> n_iter=n_iter) | 1 |
Javascript | Javascript | increase robustness with primordials | 098eac7f272f5e720c9aff8b232501928a88b82a | <ide><path>lib/internal/util/inspect.js
<ide> const {
<ide> ArrayIsArray,
<ide> ArrayPrototypeFilter,
<ide> ArrayPrototypeForEach,
<add> ArrayPrototypeIncludes,
<add> ArrayPrototypeIndexOf,
<add> ArrayPrototypeJoin,
<add> ArrayPrototypeMap,
<ide> ArrayPrototypePop,
<ide> ArrayPrototypePush,
<ide> ArrayPrototypePushApply,
<add> ArrayPrototypeSlice,
<add> ArrayPrototypeSplice,
<ide> ArrayPrototypeSort,
<ide> ArrayPrototypeUnshift,
<ide> BigIntPrototypeValueOf,
<ide> const {
<ide> DatePrototypeToISOString,
<ide> DatePrototypeToString,
<ide> ErrorPrototypeToString,
<add> FunctionPrototypeBind,
<ide> FunctionPrototypeCall,
<ide> FunctionPrototypeToString,
<ide> JSONStringify,
<ide> const {
<ide> NumberIsNaN,
<ide> NumberParseFloat,
<ide> NumberParseInt,
<add> NumberPrototypeToString,
<ide> NumberPrototypeValueOf,
<ide> Object,
<ide> ObjectAssign,
<ide> const {
<ide> ObjectPrototypePropertyIsEnumerable,
<ide> ObjectSeal,
<ide> ObjectSetPrototypeOf,
<add> ReflectApply,
<ide> ReflectOwnKeys,
<ide> RegExp,
<ide> RegExpPrototypeExec,
<ide> RegExpPrototypeSymbolReplace,
<add> RegExpPrototypeSymbolSplit,
<ide> RegExpPrototypeToString,
<ide> SafeStringIterator,
<ide> SafeMap,
<ide> const {
<ide> StringPrototypeCharCodeAt,
<ide> StringPrototypeCodePointAt,
<ide> StringPrototypeIncludes,
<add> StringPrototypeIndexOf,
<add> StringPrototypeLastIndexOf,
<ide> StringPrototypeNormalize,
<ide> StringPrototypePadEnd,
<ide> StringPrototypePadStart,
<ide> StringPrototypeRepeat,
<add> StringPrototypeReplaceAll,
<ide> StringPrototypeSlice,
<ide> StringPrototypeSplit,
<add> StringPrototypeEndsWith,
<add> StringPrototypeStartsWith,
<ide> StringPrototypeToLowerCase,
<ide> StringPrototypeTrim,
<ide> StringPrototypeValueOf,
<ide> ObjectDefineProperty(inspect, 'defaultOptions', {
<ide> // reset code as second entry.
<ide> const defaultFG = 39;
<ide> const defaultBG = 49;
<del>inspect.colors = ObjectAssign(ObjectCreate(null), {
<add>inspect.colors = {
<add> __proto__: null,
<ide> reset: [0, 0],
<ide> bold: [1, 22],
<ide> dim: [2, 22], // Alias: faint
<ide> inspect.colors = ObjectAssign(ObjectCreate(null), {
<ide> bgMagentaBright: [105, defaultBG],
<ide> bgCyanBright: [106, defaultBG],
<ide> bgWhiteBright: [107, defaultBG],
<del>});
<add>};
<ide>
<ide> function defineColorAlias(target, alias) {
<ide> ObjectDefineProperty(inspect.colors, alias, {
<ide> function addQuotes(str, quotes) {
<ide>
<ide> function escapeFn(str) {
<ide> const charCode = StringPrototypeCharCodeAt(str);
<del> return meta.length > charCode ? meta[charCode] : `\\u${charCode.toString(16)}`;
<add> return meta.length > charCode ? meta[charCode] : `\\u${NumberPrototypeToString(charCode, 16)}`;
<ide> }
<ide>
<ide> // Escape control characters, single quotes and the backslash.
<ide> function strEscape(str) {
<ide> continue;
<ide> }
<ide> }
<del> result += `${StringPrototypeSlice(str, last, i)}\\u${point.toString(16)}`;
<add> result += `${StringPrototypeSlice(str, last, i)}\\u${NumberPrototypeToString(point, 16)}`;
<ide> last = i + 1;
<ide> }
<ide> }
<ide> function formatValue(ctx, value, recurseTimes, typedArray) {
<ide> if (typeof ret !== 'string') {
<ide> return formatValue(ctx, ret, recurseTimes);
<ide> }
<del> return ret.replace(/\n/g, `\n${' '.repeat(ctx.indentationLvl)}`);
<add> return StringPrototypeReplaceAll(ret, '\n', `\n${StringPrototypeRepeat(' ', ctx.indentationLvl)}`);
<ide> }
<ide> }
<ide> }
<ide> function formatRaw(ctx, value, recurseTimes, typedArray) {
<ide> const prefix = getPrefix(constructor, tag, 'Set', `(${size})`);
<ide> keys = getKeys(value, ctx.showHidden);
<ide> formatter = constructor !== null ?
<del> formatSet.bind(null, value) :
<del> formatSet.bind(null, SetPrototypeValues(value));
<add> FunctionPrototypeBind(formatSet, null, value) :
<add> FunctionPrototypeBind(formatSet, null, SetPrototypeValues(value));
<ide> if (size === 0 && keys.length === 0 && protoProps === undefined)
<ide> return `${prefix}{}`;
<ide> braces = [`${prefix}{`, '}'];
<ide> function formatRaw(ctx, value, recurseTimes, typedArray) {
<ide> const prefix = getPrefix(constructor, tag, 'Map', `(${size})`);
<ide> keys = getKeys(value, ctx.showHidden);
<ide> formatter = constructor !== null ?
<del> formatMap.bind(null, value) :
<del> formatMap.bind(null, MapPrototypeEntries(value));
<add> FunctionPrototypeBind(formatMap, null, value) :
<add> FunctionPrototypeBind(formatMap, null, MapPrototypeEntries(value));
<ide> if (size === 0 && keys.length === 0 && protoProps === undefined)
<ide> return `${prefix}{}`;
<ide> braces = [`${prefix}{`, '}'];
<ide> function formatRaw(ctx, value, recurseTimes, typedArray) {
<ide> return `${braces[0]}]`;
<ide> // Special handle the value. The original value is required below. The
<ide> // bound function is required to reconstruct missing information.
<del> formatter = formatTypedArray.bind(null, bound, size);
<add> formatter = FunctionPrototypeBind(formatTypedArray, null, bound, size);
<ide> extrasType = kArrayExtrasType;
<ide> } else if (isMapIterator(value)) {
<ide> keys = getKeys(value, ctx.showHidden);
<ide> braces = getIteratorBraces('Map', tag);
<ide> // Add braces to the formatter parameters.
<del> formatter = formatIterator.bind(null, braces);
<add> formatter = FunctionPrototypeBind(formatIterator, null, braces);
<ide> } else if (isSetIterator(value)) {
<ide> keys = getKeys(value, ctx.showHidden);
<ide> braces = getIteratorBraces('Set', tag);
<ide> // Add braces to the formatter parameters.
<del> formatter = formatIterator.bind(null, braces);
<add> formatter = FunctionPrototypeBind(formatIterator, null, braces);
<ide> } else {
<ide> noIterator = true;
<ide> }
<ide> function formatRaw(ctx, value, recurseTimes, typedArray) {
<ide> }
<ide>
<ide> if (recurseTimes > ctx.depth && ctx.depth !== null) {
<del> let constructorName = getCtxStyle(value, constructor, tag).slice(0, -1);
<add> let constructorName = StringPrototypeSlice(getCtxStyle(value, constructor, tag), 0, -1);
<ide> if (constructor !== null)
<ide> constructorName = `[${constructorName}]`;
<ide> return ctx.stylize(constructorName, 'special');
<ide> function formatRaw(ctx, value, recurseTimes, typedArray) {
<ide> try {
<ide> output = formatter(ctx, value, recurseTimes);
<ide> for (i = 0; i < keys.length; i++) {
<del> output.push(
<del> formatProperty(ctx, value, recurseTimes, keys[i], extrasType));
<add> ArrayPrototypePush(
<add> output,
<add> formatProperty(ctx, value, recurseTimes, keys[i], extrasType),
<add> );
<ide> }
<ide> if (protoProps !== undefined) {
<del> output.push(...protoProps);
<add> ArrayPrototypePushApply(output, protoProps);
<ide> }
<ide> } catch (err) {
<del> const constructorName = getCtxStyle(value, constructor, tag).slice(0, -1);
<add> const constructorName = StringPrototypeSlice(getCtxStyle(value, constructor, tag), 0, -1);
<ide> return handleMaxCallStackSize(ctx, err, constructorName, indentationLvl);
<ide> }
<ide> if (ctx.circular !== undefined) {
<ide> function formatRaw(ctx, value, recurseTimes, typedArray) {
<ide> if (ctx.sorted) {
<ide> const comparator = ctx.sorted === true ? undefined : ctx.sorted;
<ide> if (extrasType === kObjectType) {
<del> output = output.sort(comparator);
<add> ArrayPrototypeSort(output, comparator);
<ide> } else if (keys.length > 1) {
<del> const sorted = output.slice(output.length - keys.length).sort(comparator);
<del> output.splice(output.length - keys.length, keys.length, ...sorted);
<add> const sorted = ArrayPrototypeSort(ArrayPrototypeSlice(output, output.length - keys.length), comparator);
<add> ArrayPrototypeUnshift(sorted, output, output.length - keys.length, keys.length);
<add> ReflectApply(ArrayPrototypeSplice, null, sorted);
<ide> }
<ide> }
<ide>
<ide> function getClassBase(value, constructor, tag) {
<ide>
<ide> function getFunctionBase(value, constructor, tag) {
<ide> const stringified = FunctionPrototypeToString(value);
<del> if (stringified.startsWith('class') && stringified.endsWith('}')) {
<del> const slice = stringified.slice(5, -1);
<del> const bracketIndex = slice.indexOf('{');
<add> if (StringPrototypeStartsWith(stringified, 'class') && StringPrototypeEndsWith(stringified, '}')) {
<add> const slice = StringPrototypeSlice(stringified, 5, -1);
<add> const bracketIndex = StringPrototypeIndexOf(slice, '{');
<ide> if (bracketIndex !== -1 &&
<del> (!slice.slice(0, bracketIndex).includes('(') ||
<del> // Slow path to guarantee that it's indeed a class.
<del> classRegExp.test(slice.replace(stripCommentsRegExp)))) {
<add> (!StringPrototypeIncludes(StringPrototypeSlice(slice, 0, bracketIndex), '(') ||
<add> // Slow path to guarantee that it's indeed a class.
<add> RegExpPrototypeExec(classRegExp, RegExpPrototypeSymbolReplace(stripCommentsRegExp, slice)) !== null)
<add> ) {
<ide> return getClassBase(value, constructor, tag);
<ide> }
<ide> }
<ide> function getStackString(error) {
<ide> }
<ide>
<ide> function getStackFrames(ctx, err, stack) {
<del> const frames = stack.split('\n');
<add> const frames = StringPrototypeSplit(stack, '\n');
<ide>
<ide> // Remove stack frames identical to frames in cause.
<ide> if (err.cause && isError(err.cause)) {
<ide> const causeStack = getStackString(err.cause);
<del> const causeStackStart = causeStack.indexOf('\n at');
<add> const causeStackStart = StringPrototypeIndexOf(causeStack, '\n at');
<ide> if (causeStackStart !== -1) {
<del> const causeFrames = causeStack.slice(causeStackStart + 1).split('\n');
<add> const causeFrames = StringPrototypeSplit(StringPrototypeSlice(causeStack, causeStackStart + 1), '\n');
<ide> const { len, offset } = identicalSequenceRange(frames, causeFrames);
<ide> if (len > 0) {
<ide> const skipped = len - 2;
<ide> function improveStack(stack, constructor, name, tag) {
<ide> let len = name.length;
<ide>
<ide> if (constructor === null ||
<del> (name.endsWith('Error') &&
<del> stack.startsWith(name) &&
<add> (StringPrototypeEndsWith(name, 'Error') &&
<add> StringPrototypeStartsWith(stack, name) &&
<ide> (stack.length === len || stack[len] === ':' || stack[len] === '\n'))) {
<ide> let fallback = 'Error';
<ide> if (constructor === null) {
<del> const start = stack.match(/^([A-Z][a-z_ A-Z0-9[\]()-]+)(?::|\n {4}at)/) ||
<del> stack.match(/^([a-z_A-Z0-9-]*Error)$/);
<add> const start = RegExpPrototypeExec(/^([A-Z][a-z_ A-Z0-9[\]()-]+)(?::|\n {4}at)/, stack) ||
<add> RegExpPrototypeExec(/^([a-z_A-Z0-9-]*Error)$/, stack);
<ide> fallback = (start && start[1]) || '';
<ide> len = fallback.length;
<ide> fallback = fallback || 'Error';
<ide> }
<del> const prefix = getPrefix(constructor, tag, fallback).slice(0, -1);
<add> const prefix = StringPrototypeSlice(getPrefix(constructor, tag, fallback), 0, -1);
<ide> if (name !== prefix) {
<del> if (prefix.includes(name)) {
<add> if (StringPrototypeIncludes(prefix, name)) {
<ide> if (len === 0) {
<ide> stack = `${prefix}: ${stack}`;
<ide> } else {
<del> stack = `${prefix}${stack.slice(len)}`;
<add> stack = `${prefix}${StringPrototypeSlice(stack, len)}`;
<ide> }
<ide> } else {
<del> stack = `${prefix} [${name}]${stack.slice(len)}`;
<add> stack = `${prefix} [${name}]${StringPrototypeSlice(stack, len)}`;
<ide> }
<ide> }
<ide> }
<ide> function improveStack(stack, constructor, name, tag) {
<ide> function removeDuplicateErrorKeys(ctx, keys, err, stack) {
<ide> if (!ctx.showHidden && keys.length !== 0) {
<ide> for (const name of ['name', 'message', 'stack']) {
<del> const index = keys.indexOf(name);
<add> const index = ArrayPrototypeIndexOf(keys, name);
<ide> // Only hide the property in case it's part of the original stack
<del> if (index !== -1 && stack.includes(err[name])) {
<del> keys.splice(index, 1);
<add> if (index !== -1 && StringPrototypeIncludes(stack, err[name])) {
<add> ArrayPrototypeSplice(keys, index, 1);
<ide> }
<ide> }
<ide> }
<ide> function markNodeModules(ctx, line) {
<ide> let pos = 0;
<ide> while ((nodeModule = nodeModulesRegExp.exec(line)) !== null) {
<ide> // '/node_modules/'.length === 14
<del> tempLine += line.slice(pos, nodeModule.index + 14);
<add> tempLine += StringPrototypeSlice(line, pos, nodeModule.index + 14);
<ide> tempLine += ctx.stylize(nodeModule[1], 'module');
<ide> pos = nodeModule.index + nodeModule[0].length;
<ide> }
<ide> if (pos !== 0) {
<del> line = tempLine + line.slice(pos);
<add> line = tempLine + StringPrototypeSlice(line, pos);
<ide> }
<ide> return line;
<ide> }
<ide>
<ide> function markCwd(ctx, line, workingDirectory) {
<del> let cwdStartPos = line.indexOf(workingDirectory);
<add> let cwdStartPos = StringPrototypeIndexOf(line, workingDirectory);
<ide> let tempLine = '';
<ide> let cwdLength = workingDirectory.length;
<ide> if (cwdStartPos !== -1) {
<del> if (line.slice(cwdStartPos - 7, cwdStartPos) === 'file://') {
<add> if (StringPrototypeSlice(line, cwdStartPos - 7, cwdStartPos) === 'file://') {
<ide> cwdLength += 7;
<ide> cwdStartPos -= 7;
<ide> }
<ide> const start = line[cwdStartPos - 1] === '(' ? cwdStartPos - 1 : cwdStartPos;
<del> const end = start !== cwdStartPos && line.endsWith(')') ? -1 : line.length;
<add> const end = start !== cwdStartPos && StringPrototypeEndsWith(line, ')') ? -1 : line.length;
<ide> const workingDirectoryEndPos = cwdStartPos + cwdLength + 1;
<del> const cwdSlice = line.slice(start, workingDirectoryEndPos);
<add> const cwdSlice = StringPrototypeSlice(line, start, workingDirectoryEndPos);
<ide>
<del> tempLine += line.slice(0, start);
<add> tempLine += StringPrototypeSlice(line, 0, start);
<ide> tempLine += ctx.stylize(cwdSlice, 'undefined');
<del> tempLine += line.slice(workingDirectoryEndPos, end);
<add> tempLine += StringPrototypeSlice(line, workingDirectoryEndPos, end);
<ide> if (end === -1) {
<ide> tempLine += ctx.stylize(')', 'undefined');
<ide> }
<ide> function formatError(err, constructor, tag, ctx, keys) {
<ide> removeDuplicateErrorKeys(ctx, keys, err, stack);
<ide>
<ide> if ('cause' in err &&
<del> (keys.length === 0 || !keys.includes('cause'))) {
<del> keys.push('cause');
<add> (keys.length === 0 || !ArrayPrototypeIncludes(keys, 'cause'))) {
<add> ArrayPrototypePush(keys, 'cause');
<ide> }
<ide>
<ide> // Print errors aggregated into AggregateError
<ide> if (ArrayIsArray(err.errors) &&
<del> (keys.length === 0 || !keys.includes('errors'))) {
<del> keys.push('errors');
<add> (keys.length === 0 || !ArrayPrototypeIncludes(keys, 'errors'))) {
<add> ArrayPrototypePush(keys, 'errors');
<ide> }
<ide>
<ide> stack = improveStack(stack, constructor, name, tag);
<ide>
<ide> // Ignore the error message if it's contained in the stack.
<del> let pos = (err.message && stack.indexOf(err.message)) || -1;
<add> let pos = (err.message && StringPrototypeIndexOf(stack, err.message)) || -1;
<ide> if (pos !== -1)
<ide> pos += err.message.length;
<ide> // Wrap the error in brackets in case it has no stack trace.
<del> const stackStart = stack.indexOf('\n at', pos);
<add> const stackStart = StringPrototypeIndexOf(stack, '\n at', pos);
<ide> if (stackStart === -1) {
<ide> stack = `[${stack}]`;
<ide> } else {
<del> let newStack = stack.slice(0, stackStart);
<del> const stackFramePart = stack.slice(stackStart + 1);
<add> let newStack = StringPrototypeSlice(stack, 0, stackStart);
<add> const stackFramePart = StringPrototypeSlice(stack, stackStart + 1);
<ide> const lines = getStackFrames(ctx, err, stackFramePart);
<ide> if (ctx.colors) {
<ide> // Highlight userland code and node modules.
<ide> const workingDirectory = safeGetCWD();
<ide> let esmWorkingDirectory;
<ide> for (let line of lines) {
<del> const core = line.match(coreModuleRegExp);
<add> const core = RegExpPrototypeExec(coreModuleRegExp, line);
<ide> if (core !== null && BuiltinModule.exists(core[1])) {
<ide> newStack += `\n${ctx.stylize(line, 'undefined')}`;
<ide> } else {
<ide> function formatError(err, constructor, tag, ctx, keys) {
<ide> }
<ide> }
<ide> } else {
<del> newStack += `\n${lines.join('\n')}`;
<add> newStack += `\n${ArrayPrototypeJoin(lines, '\n')}`;
<ide> }
<ide> stack = newStack;
<ide> }
<ide> // The message and the stack have to be indented as well!
<ide> if (ctx.indentationLvl !== 0) {
<del> const indentation = ' '.repeat(ctx.indentationLvl);
<del> stack = stack.replace(/\n/g, `\n${indentation}`);
<add> const indentation = StringPrototypeRepeat(' ', ctx.indentationLvl);
<add> stack = StringPrototypeReplaceAll(stack, '\n', `\n${indentation}`);
<ide> }
<ide> return stack;
<ide> }
<ide> function handleMaxCallStackSize(ctx, err, constructorName, indentationLvl) {
<ide> function addNumericSeparator(integerString) {
<ide> let result = '';
<ide> let i = integerString.length;
<del> const start = integerString.startsWith('-') ? 1 : 0;
<add> const start = StringPrototypeStartsWith(integerString, '-') ? 1 : 0;
<ide> for (; i >= start + 4; i -= 3) {
<del> result = `_${integerString.slice(i - 3, i)}${result}`;
<add> result = `_${StringPrototypeSlice(integerString, i - 3, i)}${result}`;
<ide> }
<ide> return i === integerString.length ?
<ide> integerString :
<del> `${integerString.slice(0, i)}${result}`;
<add> `${StringPrototypeSlice(integerString, 0, i)}${result}`;
<ide> }
<ide>
<ide> function addNumericSeparatorEnd(integerString) {
<ide> let result = '';
<ide> let i = 0;
<ide> for (; i < integerString.length - 3; i += 3) {
<del> result += `${integerString.slice(i, i + 3)}_`;
<add> result += `${StringPrototypeSlice(integerString, i, i + 3)}_`;
<ide> }
<ide> return i === 0 ?
<ide> integerString :
<del> `${result}${integerString.slice(i)}`;
<add> `${result}${StringPrototypeSlice(integerString, i)}`;
<ide> }
<ide>
<ide> const remainingText = (remaining) => `... ${remaining} more item${remaining > 1 ? 's' : ''}`;
<ide> function formatNumber(fn, number, numericSeparator) {
<ide> const integer = MathTrunc(number);
<ide> const string = String(integer);
<ide> if (integer === number) {
<del> if (!NumberIsFinite(number) || string.includes('e')) {
<add> if (!NumberIsFinite(number) || StringPrototypeIncludes(string, 'e')) {
<ide> return fn(string, 'number');
<ide> }
<ide> return fn(`${addNumericSeparator(string)}`, 'number');
<ide> function formatNumber(fn, number, numericSeparator) {
<ide> return fn(`${
<ide> addNumericSeparator(string)
<ide> }.${
<del> addNumericSeparatorEnd(String(number).slice(string.length + 1))
<add> addNumericSeparatorEnd(
<add> StringPrototypeSlice(String(number), string.length + 1)
<add> )
<ide> }`, 'number');
<ide> }
<ide>
<ide> function formatPrimitive(fn, value, ctx) {
<ide> let trailer = '';
<ide> if (value.length > ctx.maxStringLength) {
<ide> const remaining = value.length - ctx.maxStringLength;
<del> value = value.slice(0, ctx.maxStringLength);
<add> value = StringPrototypeSlice(value, 0, ctx.maxStringLength);
<ide> trailer = `... ${remaining} more character${remaining > 1 ? 's' : ''}`;
<ide> }
<ide> if (ctx.compact !== true &&
<ide> function formatPrimitive(fn, value, ctx) {
<ide> // performance implications.
<ide> value.length > kMinLineLength &&
<ide> value.length > ctx.breakLength - ctx.indentationLvl - 4) {
<del> return value
<del> .split(/(?<=\n)/)
<del> .map((line) => fn(strEscape(line), 'string'))
<del> .join(` +\n${' '.repeat(ctx.indentationLvl + 2)}`) + trailer;
<add> return ArrayPrototypeJoin(
<add> ArrayPrototypeMap(
<add> RegExpPrototypeSymbolSplit(/(?<=\n)/, value),
<add> (line) => fn(strEscape(line), 'string'),
<add> ),
<add> ` +\n${StringPrototypeRepeat(' ', ctx.indentationLvl + 2)}`,
<add> ) + trailer;
<ide> }
<ide> return fn(strEscape(value), 'string') + trailer;
<ide> }
<ide> function formatNamespaceObject(keys, ctx, value, recurseTimes) {
<ide> // this aligned, even though this is a hacky way of dealing with this.
<ide> const tmp = { [keys[i]]: '' };
<ide> output[i] = formatProperty(ctx, tmp, recurseTimes, keys[i], kObjectType);
<del> const pos = output[i].lastIndexOf(' ');
<add> const pos = StringPrototypeLastIndexOf(output[i], ' ');
<ide> // We have to find the last whitespace and have to replace that value as
<ide> // it will be visualized as a regular string.
<del> output[i] = output[i].slice(0, pos + 1) +
<add> output[i] = StringPrototypeSlice(output[i], 0, pos + 1) +
<ide> ctx.stylize('<uninitialized>', 'special');
<ide> }
<ide> }
<ide> function formatSpecialArray(ctx, value, recurseTimes, maxLength, output, i) {
<ide> break;
<ide> }
<ide> if (`${index}` !== key) {
<del> if (!numberRegExp.test(key)) {
<add> if (RegExpPrototypeExec(numberRegExp, key) === null) {
<ide> break;
<ide> }
<ide> const emptyItems = tmp - index;
<ide> const ending = emptyItems > 1 ? 's' : '';
<ide> const message = `<${emptyItems} empty item${ending}>`;
<del> output.push(ctx.stylize(message, 'undefined'));
<add> ArrayPrototypePush(output, ctx.stylize(message, 'undefined'));
<ide> index = tmp;
<ide> if (output.length === maxLength) {
<ide> break;
<ide> }
<ide> }
<del> output.push(formatProperty(ctx, value, recurseTimes, key, kArrayType));
<add> ArrayPrototypePush(output, formatProperty(ctx, value, recurseTimes, key, kArrayType));
<ide> index++;
<ide> }
<ide> const remaining = value.length - index;
<ide> if (output.length !== maxLength) {
<ide> if (remaining > 0) {
<ide> const ending = remaining > 1 ? 's' : '';
<ide> const message = `<${remaining} empty item${ending}>`;
<del> output.push(ctx.stylize(message, 'undefined'));
<add> ArrayPrototypePush(output, ctx.stylize(message, 'undefined'));
<ide> }
<ide> } else if (remaining > 0) {
<del> output.push(remainingText(remaining));
<add> ArrayPrototypePush(output, remainingText(remaining));
<ide> }
<ide> return output;
<ide> }
<ide> function formatArrayBuffer(ctx, value) {
<ide> let str = StringPrototypeTrim(RegExpPrototypeSymbolReplace(
<ide> /(.{2})/g,
<ide> hexSlice(buffer, 0, MathMin(ctx.maxArrayLength, buffer.length)),
<del> '$1 '));
<add> '$1 ',
<add> ));
<ide> const remaining = buffer.length - ctx.maxArrayLength;
<ide> if (remaining > 0)
<ide> str += ` ... ${remaining} more byte${remaining > 1 ? 's' : ''}`;
<ide> function formatArray(ctx, value, recurseTimes) {
<ide> if (!ObjectPrototypeHasOwnProperty(value, i)) {
<ide> return formatSpecialArray(ctx, value, recurseTimes, len, output, i);
<ide> }
<del> output.push(formatProperty(ctx, value, recurseTimes, i, kArrayType));
<add> ArrayPrototypePush(output, formatProperty(ctx, value, recurseTimes, i, kArrayType));
<add> }
<add> if (remaining > 0) {
<add> ArrayPrototypePush(output, remainingText(remaining));
<ide> }
<del> if (remaining > 0)
<del> output.push(remainingText(remaining));
<ide> return output;
<ide> }
<ide>
<ide> function formatMap(value, ctx, ignored, recurseTimes) {
<ide> let i = 0;
<ide> for (const { 0: k, 1: v } of value) {
<ide> if (i >= maxLength) break;
<del> output.push(
<del> `${formatValue(ctx, k, recurseTimes)} => ${formatValue(ctx, v, recurseTimes)}`
<add> ArrayPrototypePush(
<add> output,
<add> `${formatValue(ctx, k, recurseTimes)} => ${formatValue(ctx, v, recurseTimes)}`,
<ide> );
<ide> i++;
<ide> }
<ide> function formatMapIterInner(ctx, recurseTimes, entries, state) {
<ide> const len = entries.length / 2;
<ide> const remaining = len - maxArrayLength;
<ide> const maxLength = MathMin(maxArrayLength, len);
<del> let output = new Array(maxLength);
<add> const output = new Array(maxLength);
<ide> let i = 0;
<ide> ctx.indentationLvl += 2;
<ide> if (state === kWeak) {
<ide> function formatMapIterInner(ctx, recurseTimes, entries, state) {
<ide> // retrieved ones exist, we can not reliably return the same output) if the
<ide> // output is not sorted anyway.
<ide> if (!ctx.sorted)
<del> output = output.sort();
<add> ArrayPrototypeSort(output);
<ide> } else {
<ide> for (; i < maxLength; i++) {
<ide> const pos = i * 2;
<ide> function formatMapIterInner(ctx, recurseTimes, entries, state) {
<ide> }
<ide> ctx.indentationLvl -= 2;
<ide> if (remaining > 0) {
<del> output.push(remainingText(remaining));
<add> ArrayPrototypePush(output, remainingText(remaining));
<ide> }
<ide> return output;
<ide> }
<ide> function formatIterator(braces, ctx, value, recurseTimes) {
<ide> const { 0: entries, 1: isKeyValue } = previewEntries(value, true);
<ide> if (isKeyValue) {
<ide> // Mark entry iterators as such.
<del> braces[0] = braces[0].replace(/ Iterator] {$/, ' Entries] {');
<add> braces[0] = RegExpPrototypeSymbolReplace(/ Iterator] {$/, braces[0], ' Entries] {');
<ide> return formatMapIterInner(ctx, recurseTimes, entries, kMapEntries);
<ide> }
<ide>
<ide> function formatProperty(ctx, value, recurseTimes, key, type, desc,
<ide> ctx.indentationLvl += diff;
<ide> str = formatValue(ctx, desc.value, recurseTimes);
<ide> if (diff === 3 && ctx.breakLength < getStringWidth(str, ctx.colors)) {
<del> extra = `\n${' '.repeat(ctx.indentationLvl)}`;
<add> extra = `\n${StringPrototypeRepeat(' ', ctx.indentationLvl)}`;
<ide> }
<ide> ctx.indentationLvl -= diff;
<ide> } else if (desc.get !== undefined) {
<ide> function formatProperty(ctx, value, recurseTimes, key, type, desc,
<ide> name = "['__proto__']";
<ide> } else if (desc.enumerable === false) {
<ide> const tmp = RegExpPrototypeSymbolReplace(
<del> strEscapeSequencesReplacer, key, escapeFn);
<add> strEscapeSequencesReplacer,
<add> key,
<add> escapeFn,
<add> );
<ide> name = `[${tmp}]`;
<ide> } else if (RegExpPrototypeExec(keyStrRegExp, key) !== null) {
<ide> name = ctx.stylize(key, 'name');
<ide> function reduceToSingleString(
<ide> braces[0].length + base.length + 10;
<ide> if (isBelowBreakLength(ctx, output, start, base)) {
<ide> const joinedOutput = join(output, ', ');
<del> if (!joinedOutput.includes('\n')) {
<add> if (!StringPrototypeIncludes(joinedOutput, '\n')) {
<ide> return `${base ? `${base} ` : ''}${braces[0]} ${joinedOutput}` +
<ide> ` ${braces[1]}`;
<ide> }
<ide> function hasBuiltInToString(value) {
<ide> builtInObjects.has(descriptor.value.name);
<ide> }
<ide>
<del>const firstErrorLine = (error) =>
<del> StringPrototypeSplit(error.message, '\n', 1)[0];
<add>const firstErrorLine = (error) => StringPrototypeSplit(error.message, '\n', 1)[0];
<ide> let CIRCULAR_ERROR_MESSAGE;
<ide> function tryStringify(arg) {
<ide> try {
<ide> function tryStringify(arg) {
<ide> // Populate the circular error message lazily
<ide> if (!CIRCULAR_ERROR_MESSAGE) {
<ide> try {
<del> const a = {}; a.a = a; JSONStringify(a);
<add> const a = {};
<add> a.a = a;
<add> JSONStringify(a);
<ide> } catch (circularError) {
<ide> CIRCULAR_ERROR_MESSAGE = firstErrorLine(circularError);
<ide> }
<ide> if (internalBinding('config').hasIntl) {
<ide> getStringWidth = function getStringWidth(str, removeControlChars = true) {
<ide> let width = 0;
<ide>
<del> if (removeControlChars)
<add> if (removeControlChars) {
<ide> str = stripVTControlCharacters(str);
<add> }
<ide> for (let i = 0; i < str.length; i++) {
<ide> // Try to avoid calling into C++ by first handling the ASCII portion of
<ide> // the string. If it is fully ASCII, we skip the C++ part.
<ide> const code = str.charCodeAt(i);
<ide> if (code >= 127) {
<del> width += icu.getStringWidth(str.slice(i).normalize('NFC'));
<add> width += icu.getStringWidth(StringPrototypeNormalize(StringPrototypeSlice(str, i), 'NFC'));
<ide> break;
<ide> }
<ide> width += code >= 32 ? 1 : 0;
<ide> if (internalBinding('config').hasIntl) {
<ide> function stripVTControlCharacters(str) {
<ide> validateString(str, 'str');
<ide>
<del> return str.replace(ansi, '');
<add> return RegExpPrototypeSymbolReplace(ansi, str, '');
<ide> }
<ide>
<ide> module.exports = { | 1 |
Javascript | Javascript | use the typed array view instead of the buffer | 16a1c38c1fd5f3c91af9e3d33e975fba3e2f8316 | <ide><path>web/viewer.js
<ide> var PDFView = {
<ide>
<ide> this.pdfDocument.getData().then(
<ide> function getDataSuccess(data) {
<del> var blob = PDFJS.createBlob(data.buffer, 'application/pdf');
<add> var blob = PDFJS.createBlob(data, 'application/pdf');
<ide> downloadManager.download(blob, url, filename);
<ide> },
<ide> noData // Error occurred try downloading with just the url. | 1 |
Ruby | Ruby | add parse method to share deserialization logic | 39882c49dcb099d764788b00c64e629003235d63 | <ide><path>actionpack/lib/action_dispatch/middleware/cookies.rb
<ide> def initialize(parent_jar)
<ide> end
<ide>
<ide> def [](name)
<del> @parent_jar[name.to_s]
<add> if data = @parent_jar[name.to_s]
<add> parse name, data
<add> end
<ide> end
<ide>
<ide> def []=(name, options)
<ide> def []=(name, options)
<ide> end
<ide>
<ide> private
<add> def parse(name, data); data; end
<ide> def commit(options); end
<ide> end
<ide>
<ide> def initialize(parent_jar)
<ide> @verifier = ActiveSupport::MessageVerifier.new(secret, digest: digest, serializer: ActiveSupport::MessageEncryptor::NullSerializer)
<ide> end
<ide>
<del> # Returns the value of the cookie by +name+ if it is untampered,
<del> # returns +nil+ otherwise or if no such cookie exists.
<del> def [](name)
<del> if signed_message = @parent_jar[name]
<add> private
<add> def parse(name, signed_message)
<ide> deserialize name, verify(signed_message)
<ide> end
<del> end
<ide>
<del> private
<ide> def commit(options)
<ide> options[:value] = @verifier.generate(serialize(options[:value]))
<ide>
<ide> def verify(signed_message)
<ide> class UpgradeLegacySignedCookieJar < SignedCookieJar #:nodoc:
<ide> include VerifyAndUpgradeLegacySignedMessage
<ide>
<del> def [](name)
<del> if signed_message = @parent_jar[name]
<add> private
<add> def parse(name, signed_message)
<ide> deserialize(name, verify(signed_message)) || verify_and_upgrade_legacy_signed_message(name, signed_message)
<ide> end
<del> end
<ide> end
<ide>
<ide> class EncryptedCookieJar < AbstractCookieJar # :nodoc:
<ide> def initialize(parent_jar)
<ide> @encryptor = ActiveSupport::MessageEncryptor.new(secret, sign_secret, digest: digest, serializer: ActiveSupport::MessageEncryptor::NullSerializer)
<ide> end
<ide>
<del> # Returns the value of the cookie by +name+ if it is untampered,
<del> # returns +nil+ otherwise or if no such cookie exists.
<del> def [](name)
<del> if encrypted_message = @parent_jar[name]
<add> private
<add> def parse(name, encrypted_message)
<ide> deserialize name, decrypt_and_verify(encrypted_message)
<ide> end
<del> end
<ide>
<del> private
<ide> def commit(options)
<ide> options[:value] = @encryptor.encrypt_and_sign(serialize(options[:value]))
<ide>
<ide> def decrypt_and_verify(encrypted_message)
<ide> class UpgradeLegacyEncryptedCookieJar < EncryptedCookieJar #:nodoc:
<ide> include VerifyAndUpgradeLegacySignedMessage
<ide>
<del> def [](name)
<del> if encrypted_or_signed_message = @parent_jar[name]
<add> private
<add> def parse(name, encrypted_or_signed_message)
<ide> deserialize(name, decrypt_and_verify(encrypted_or_signed_message)) || verify_and_upgrade_legacy_signed_message(name, encrypted_or_signed_message)
<ide> end
<del> end
<ide> end
<ide>
<ide> def initialize(app) | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.