content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Text
Text
fix typo in activestorage readme [ci skip]
b08d428ba07df42f5bc945d30fe8a5a6f3f76398
<ide><path>activestorage/README.md <ide> url_for(user.avatar) <ide> <ide> class AvatarsController < ApplicationController <ide> def update <del> # params[:avatar] contains a ActionDispatch::Http::UploadedFile object <add> # params[:avatar] contains an ActionDispatch::Http::UploadedFile object <ide> Current.user.avatar.attach(params.require(:avatar)) <ide> redirect_to Current.user <ide> end
1
Ruby
Ruby
handle mkpath of node_modules directory in keg
36f5452ae362a7ce8b83a9530031f7b9f4dcb8be
<ide><path>Library/Homebrew/keg.rb <ide> def link mode=OpenStruct.new <ide> when /^gdk-pixbuf/ then :mkpath <ide> when 'ghc' then :mkpath <ide> when 'lua' then :mkpath <del> when 'node' then :mkpath <add> when /^node/ then :mkpath <ide> when /^ocaml/ then :mkpath <ide> when /^perl5/ then :mkpath <ide> when 'php' then :mkpath
1
PHP
PHP
move plugin assets from shell to command
385a8398f0724a63eb00ca7dbac9ddfcd7e1b575
<ide><path>src/Command/PluginAssetsCopyCommand.php <add><?php <add>declare(strict_types=1); <add> <add>/** <add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * <add> * Licensed under The MIT License <add> * For full copyright and license information, please see the LICENSE.txt <add> * Redistributions of files must retain the above copyright notice. <add> * <add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * @link https://cakephp.org CakePHP(tm) Project <add> * @since 3.0.0 <add> * @license https://opensource.org/licenses/mit-license.php MIT License <add> */ <add>namespace Cake\Command; <add> <add>use Cake\Console\Arguments; <add>use Cake\Console\Command; <add>use Cake\Console\ConsoleIo; <add>use Cake\Console\ConsoleOptionParser; <add> <add>/** <add> * Command for copying plugin assets to app's webroot. <add> */ <add>class PluginAssetsCopyCommand extends Command <add>{ <add> use PluginAssetsTrait; <add> <add> /** <add> * Execute the command <add> * <add> * Copying plugin assets to app's webroot. For vendor namespaced plugin, <add> * parent folder for vendor name are created if required. <add> * <add> * @param \Cake\Console\Arguments $args The command arguments. <add> * @param \Cake\Console\ConsoleIo $io The console io <add> * @return null|int The exit code or null for success <add> */ <add> public function execute(Arguments $args, ConsoleIo $io): ?int <add> { <add> $this->io = $io; <add> $this->args = $args; <add> <add> $name = $args->getArgument('name'); <add> $overwrite = $args->getOption('overwrite'); <add> $this->_process($this->_list($name), true, $overwrite); <add> return static::CODE_SUCCESS; <add> } <add> <add> /** <add> * Get the option parser. <add> * <add> * @param \Cake\Console\ConsoleOptionParser $parser The option parser to update <add> * @return \Cake\Console\ConsoleOptionParser <add> */ <add> public function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionParser <add> { <add> $parser->setDescription([ <add> 'Copy plugin assets to app\'s webroot.', <add> ])->addArgument('name', [ <add> 'help' => 'A specific plugin you want to symlink assets for.', <add> 'optional' => true, <add> ])->addOption('overwrite', [ <add> 'help' => 'Overwrite existing symlink / folder / files.', <add> 'default' => false, <add> 'boolean' => true, <add> ]); <add> <add> return $parser; <add> } <add>} <ide><path>src/Command/PluginAssetsRemoveCommand.php <add><?php <add>declare(strict_types=1); <add> <add>/** <add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * <add> * Licensed under The MIT License <add> * For full copyright and license information, please see the LICENSE.txt <add> * Redistributions of files must retain the above copyright notice. <add> * <add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * @link https://cakephp.org CakePHP(tm) Project <add> * @since 3.0.0 <add> * @license https://opensource.org/licenses/mit-license.php MIT License <add> */ <add>namespace Cake\Command; <add> <add>use Cake\Console\Arguments; <add>use Cake\Console\Command; <add>use Cake\Console\ConsoleIo; <add>use Cake\Console\ConsoleOptionParser; <add> <add>/** <add> * Command for removing plugin assets from app's webroot. <add> */ <add>class PluginAssetsRemoveCommand extends Command <add>{ <add> use PluginAssetsTrait; <add> <add> /** <add> * Execute the command <add> * <add> * Remove plugin assets from app's webroot. <add> * <add> * @param \Cake\Console\Arguments $args The command arguments. <add> * @param \Cake\Console\ConsoleIo $io The console io <add> * @return null|int The exit code or null for success <add> */ <add> public function execute(Arguments $args, ConsoleIo $io): ?int <add> { <add> $this->io = $io; <add> $this->args = $args; <add> <add> $name = $args->getArgument('name'); <add> $plugins = $this->_list($name); <add> <add> foreach ($plugins as $plugin => $config) { <add> $this->io->out(); <add> $this->io->out('For plugin: ' . $plugin); <add> $this->io->hr(); <add> <add> $this->_remove($config); <add> } <add> <add> $this->io->out(); <add> $this->io->out('Done'); <add> return static::CODE_SUCCESS; <add> } <add> <add> /** <add> * Get the option parser. <add> * <add> * @param \Cake\Console\ConsoleOptionParser $parser The option parser to update <add> * @return \Cake\Console\ConsoleOptionParser <add> */ <add> public function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionParser <add> { <add> $parser->setDescription([ <add> 'Remove plugin assets from app\'s webroot.', <add> ])->addArgument('name', [ <add> 'help' => 'A specific plugin you want to symlink assets for.', <add> 'optional' => true, <add> ]); <add> <add> return $parser; <add> } <add>} <ide><path>src/Command/PluginAssetsSymlinkCommand.php <add><?php <add>declare(strict_types=1); <add> <add>/** <add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * <add> * Licensed under The MIT License <add> * For full copyright and license information, please see the LICENSE.txt <add> * Redistributions of files must retain the above copyright notice. <add> * <add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * @link https://cakephp.org CakePHP(tm) Project <add> * @since 3.0.0 <add> * @license https://opensource.org/licenses/mit-license.php MIT License <add> */ <add>namespace Cake\Command; <add> <add>use Cake\Console\Arguments; <add>use Cake\Console\Command; <add>use Cake\Console\ConsoleIo; <add>use Cake\Console\ConsoleOptionParser; <add> <add>/** <add> * Command for symlinking / copying plugin assets to app's webroot. <add> */ <add>class PluginAssetsSymlinkCommand extends Command <add>{ <add> use PluginAssetsTrait; <add> <add> /** <add> * Execute the command <add> * <add> * Attempt to symlink plugin assets to app's webroot. If symlinking fails it <add> * fallbacks to copying the assets. For vendor namespaced plugin, parent folder <add> * for vendor name are created if required. <add> * <add> * @param \Cake\Console\Arguments $args The command arguments. <add> * @param \Cake\Console\ConsoleIo $io The console io <add> * @return null|int The exit code or null for success <add> */ <add> public function execute(Arguments $args, ConsoleIo $io): ?int <add> { <add> $this->io = $io; <add> $this->args = $args; <add> <add> $name = $args->getArgument('name'); <add> $overwrite = $args->getOption('overwrite'); <add> $this->_process($this->_list($name), false, $overwrite); <add> return static::CODE_SUCCESS; <add> } <add> <add> /** <add> * Get the option parser. <add> * <add> * @param \Cake\Console\ConsoleOptionParser $parser The option parser to update <add> * @return \Cake\Console\ConsoleOptionParser <add> */ <add> public function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionParser <add> { <add> $parser->setDescription([ <add> 'Symlink (copy as fallback) plugin assets to app\'s webroot.', <add> ])->addArgument('name', [ <add> 'help' => 'A specific plugin you want to symlink assets for.', <add> 'optional' => true, <add> ])->addOption('overwrite', [ <add> 'help' => 'Overwrite existing symlink / folder / files.', <add> 'default' => false, <add> 'boolean' => true, <add> ]); <add> <add> return $parser; <add> } <add>} <add><path>src/Command/PluginAssetsTrait.php <del><path>src/Shell/Task/AssetsTask.php <ide> * @since 3.0.0 <ide> * @license https://opensource.org/licenses/mit-license.php MIT License <ide> */ <del>namespace Cake\Shell\Task; <add>namespace Cake\Command; <ide> <ide> use Cake\Console\ConsoleOptionParser; <ide> use Cake\Console\Shell; <ide> use Cake\Utility\Inflector; <ide> <ide> /** <del> * Task for symlinking / copying plugin assets to app's webroot. <add> * trait for symlinking / copying plugin assets to app's webroot. <add> * @internal <ide> */ <del>class AssetsTask extends Shell <add>trait PluginAssetsTrait <ide> { <ide> /** <del> * Attempt to symlink plugin assets to app's webroot. If symlinking fails it <del> * fallbacks to copying the assets. For vendor namespaced plugin, parent folder <del> * for vendor name are created if required. <add> * Arguments <ide> * <del> * @param string|null $name Name of plugin for which to symlink assets. <del> * If null all plugins will be processed. <del> * @return void <add> * @var \Cake\Console\Arguments <ide> */ <del> public function symlink(?string $name = null): void <del> { <del> $this->_process($this->_list($name)); <del> } <add> protected $args; <ide> <ide> /** <del> * Copying plugin assets to app's webroot. For vendor namespaced plugin, <del> * parent folder for vendor name are created if required. <add> * Console IO <ide> * <del> * @param string|null $name Name of plugin for which to symlink assets. <del> * If null all plugins will be processed. <del> * @return void <del> */ <del> public function copy(?string $name = null): void <del> { <del> $this->_process($this->_list($name), true, (bool)$this->param('overwrite')); <del> } <del> <del> /** <del> * Remove plugin assets from app's webroot. <del> * <del> * @param string|null $name Name of plugin for which to remove assets. <del> * If null all plugins will be processed. <del> * @return void <del> * @since 3.5.12 <add> * @var \Cake\Console\ConsoleIo <ide> */ <del> public function remove(?string $name = null): void <del> { <del> $plugins = $this->_list($name); <del> <del> foreach ($plugins as $plugin => $config) { <del> $this->out(); <del> $this->out('For plugin: ' . $plugin); <del> $this->hr(); <del> <del> $this->_remove($config); <del> } <del> <del> $this->out(); <del> $this->out('Done'); <del> } <add> protected $io; <ide> <ide> /** <ide> * Get list of plugins to process. Plugins without a webroot directory are skipped. <ide> protected function _list(?string $name = null): array <ide> $pluginsList = Plugin::loaded(); <ide> } else { <ide> if (!Plugin::isLoaded($name)) { <del> $this->err(sprintf('Plugin %s is not loaded.', $name)); <add> $this->io->err(sprintf('Plugin %s is not loaded.', $name)); <ide> <ide> return []; <ide> } <ide> protected function _list(?string $name = null): array <ide> foreach ($pluginsList as $plugin) { <ide> $path = Plugin::path($plugin) . 'webroot'; <ide> if (!is_dir($path)) { <del> $this->verbose('', 1); <del> $this->verbose( <add> $this->io->verbose('', 1); <add> $this->io->verbose( <ide> sprintf('Skipping plugin %s. It does not have webroot folder.', $plugin), <ide> 2 <ide> ); <ide> protected function _list(?string $name = null): array <ide> */ <ide> protected function _process(array $plugins, bool $copy = false, bool $overwrite = false): void <ide> { <del> $overwrite = (bool)$this->param('overwrite'); <del> <ide> foreach ($plugins as $plugin => $config) { <del> $this->out(); <del> $this->out('For plugin: ' . $plugin); <del> $this->hr(); <add> $this->io->out(); <add> $this->io->out('For plugin: ' . $plugin); <add> $this->io->hr(); <ide> <ide> if ($config['namespaced'] && <ide> !is_dir($config['destDir']) && <ide> protected function _process(array $plugins, bool $copy = false, bool $overwrite <ide> if ($overwrite && !$this->_remove($config)) { <ide> continue; <ide> } elseif (!$overwrite) { <del> $this->verbose( <add> $this->io->verbose( <ide> $dest . ' already exists', <ide> 1 <ide> ); <ide> protected function _process(array $plugins, bool $copy = false, bool $overwrite <ide> ); <ide> } <ide> <del> $this->out(); <del> $this->out('Done'); <add> $this->io->out(); <add> $this->io->out('Done'); <ide> } <ide> <ide> /** <ide> protected function _process(array $plugins, bool $copy = false, bool $overwrite <ide> protected function _remove(array $config): bool <ide> { <ide> if ($config['namespaced'] && !is_dir($config['destDir'])) { <del> $this->verbose( <add> $this->io->verbose( <ide> $config['destDir'] . $config['link'] . ' does not exist', <ide> 1 <ide> ); <ide> protected function _remove(array $config): bool <ide> $dest = $config['destDir'] . $config['link']; <ide> <ide> if (!file_exists($dest)) { <del> $this->verbose( <add> $this->io->verbose( <ide> $dest . ' does not exist', <ide> 1 <ide> ); <ide> protected function _remove(array $config): bool <ide> if (is_link($dest)) { <ide> // phpcs:ignore <ide> if (@unlink($dest)) { <del> $this->out('Unlinked ' . $dest); <add> $this->io->out('Unlinked ' . $dest); <ide> <ide> return true; <ide> } else { <del> $this->err('Failed to unlink ' . $dest); <add> $this->io->err('Failed to unlink ' . $dest); <ide> <ide> return false; <ide> } <ide> } <ide> <ide> $fs = new Filesystem(); <ide> if ($fs->deleteDir($dest)) { <del> $this->out('Deleted ' . $dest); <add> $this->io->out('Deleted ' . $dest); <ide> <ide> return true; <ide> } else { <del> $this->err('Failed to delete ' . $dest); <add> $this->io->err('Failed to delete ' . $dest); <ide> <ide> return false; <ide> } <ide> protected function _createDirectory(string $dir): bool <ide> umask($old); <ide> <ide> if ($result) { <del> $this->out('Created directory ' . $dir); <add> $this->io->out('Created directory ' . $dir); <ide> <ide> return true; <ide> } <ide> <del> $this->err('Failed creating directory ' . $dir); <add> $this->io->err('Failed creating directory ' . $dir); <ide> <ide> return false; <ide> } <ide> protected function _createSymlink(string $target, string $link): bool <ide> // phpcs:enable <ide> <ide> if ($result) { <del> $this->out('Created symlink ' . $link); <add> $this->io->out('Created symlink ' . $link); <ide> <ide> return true; <ide> } <ide> protected function _copyDirectory(string $source, string $destination): bool <ide> { <ide> $fs = new Filesystem(); <ide> if ($fs->copyDir($source, $destination)) { <del> $this->out('Copied assets to directory ' . $destination); <add> $this->io->out('Copied assets to directory ' . $destination); <ide> <ide> return true; <ide> } <ide> <del> $this->err('Error copying assets to directory ' . $destination); <add> $this->io->err('Error copying assets to directory ' . $destination); <ide> <ide> return false; <ide> } <del> <del> /** <del> * Gets the option parser instance and configures it. <del> * <del> * @return \Cake\Console\ConsoleOptionParser <del> */ <del> public function getOptionParser(): ConsoleOptionParser <del> { <del> $parser = parent::getOptionParser(); <del> <del> $parser->addSubcommand('symlink', [ <del> 'help' => 'Symlink (copy as fallback) plugin assets to app\'s webroot.', <del> ])->addSubcommand('copy', [ <del> 'help' => 'Copy plugin assets to app\'s webroot.', <del> ])->addSubcommand('remove', [ <del> 'help' => 'Remove plugin assets from app\'s webroot.', <del> ])->addArgument('name', [ <del> 'help' => 'A specific plugin you want to symlink assets for.', <del> 'optional' => true, <del> ])->addOption('overwrite', [ <del> 'help' => 'Overwrite existing symlink / folder / files.', <del> 'default' => false, <del> 'boolean' => true, <del> ]); <del> <del> return $parser; <del> } <ide> }
4
Text
Text
fix wrong indent in stream documentation
9651f4400066d60869584e46428317934dc1e882
<ide><path>doc/api/stream.md <ide> async function showBoth() { <ide> showBoth(); <ide> ``` <ide> <del>### `readable.map(fn[, options])` <add>##### `readable.map(fn[, options])` <ide> <ide> <!-- YAML <ide> added: <ide> for await (const result of dnsResults) { <ide> } <ide> ``` <ide> <del>### `readable.filter(fn[, options])` <add>##### `readable.filter(fn[, options])` <ide> <ide> <!-- YAML <ide> added: <ide> for await (const result of dnsResults) { <ide> } <ide> ``` <ide> <del>### `readable.forEach(fn[, options])` <add>##### `readable.forEach(fn[, options])` <ide> <ide> <!-- YAML <ide> added: v17.5.0 <ide> await dnsResults.forEach((result) => { <ide> console.log('done'); // Stream has finished <ide> ``` <ide> <del>### `readable.toArray([options])` <add>##### `readable.toArray([options])` <ide> <ide> <!-- YAML <ide> added: v17.5.0 <ide> const dnsResults = await Readable.from([ <ide> }, { concurrency: 2 }).toArray(); <ide> ``` <ide> <del>### `readable.some(fn[, options])` <add>##### `readable.some(fn[, options])` <ide> <ide> <!-- YAML <ide> added: v17.5.0 <ide> console.log(anyBigFile); // `true` if any file in the list is bigger than 1MB <ide> console.log('done'); // Stream has finished <ide> ``` <ide> <del>### `readable.find(fn[, options])` <add>##### `readable.find(fn[, options])` <ide> <ide> <!-- YAML <ide> added: v17.5.0 <ide> console.log(foundBigFile); // File name of large file, if any file in the list i <ide> console.log('done'); // Stream has finished <ide> ``` <ide> <del>### `readable.every(fn[, options])` <add>##### `readable.every(fn[, options])` <ide> <ide> <!-- YAML <ide> added: v17.5.0 <ide> console.log(allBigFiles); <ide> console.log('done'); // Stream has finished <ide> ``` <ide> <del>### `readable.flatMap(fn[, options])` <add>##### `readable.flatMap(fn[, options])` <ide> <ide> <!-- YAML <ide> added: v17.5.0 <ide> for await (const result of concatResult) { <ide> } <ide> ``` <ide> <del>### `readable.drop(limit[, options])` <add>##### `readable.drop(limit[, options])` <ide> <ide> <!-- YAML <ide> added: v17.5.0 <ide> import { Readable } from 'stream'; <ide> await Readable.from([1, 2, 3, 4]).drop(2).toArray(); // [3, 4] <ide> ``` <ide> <del>### `readable.take(limit[, options])` <add>##### `readable.take(limit[, options])` <ide> <ide> <!-- YAML <ide> added: v17.5.0 <ide> import { Readable } from 'stream'; <ide> await Readable.from([1, 2, 3, 4]).take(2).toArray(); // [1, 2] <ide> ``` <ide> <del>### `readable.asIndexedPairs([options])` <add>##### `readable.asIndexedPairs([options])` <ide> <ide> <!-- YAML <ide> added: v17.5.0 <ide> const pairs = await Readable.from(['a', 'b', 'c']).asIndexedPairs().toArray(); <ide> console.log(pairs); // [[0, 'a'], [1, 'b'], [2, 'c']] <ide> ``` <ide> <del>### `readable.reduce(fn[, initial[, options]])` <add>##### `readable.reduce(fn[, initial[, options]])` <ide> <ide> <!-- YAML <ide> added: v17.5.0
1
Text
Text
correct the use of "to"
b0ca248d88240c58ff04554bf5df07a6dd8d9e8f
<ide><path>docs/tutorial/5-relationships-and-hyperlinked-apis.md <ide> We can change the default list style to use pagination, by modifying our `tutori <ide> <ide> Note that settings in REST framework are all namespaced into a single dictionary setting, named `REST_FRAMEWORK`, which helps keep them well separated from your other project settings. <ide> <del>We could also customize the pagination style if we needed too, but in this case we'll just stick with the default. <add>We could also customize the pagination style if we needed to, but in this case we'll just stick with the default. <ide> <ide> ## Browsing the API <ide>
1
PHP
PHP
add a note to the appserviceprovider
5194a437d5f11e9770839cf79c4dfa25ff6a31ac
<ide><path>app/Providers/AppServiceProvider.php <ide> public function boot() <ide> */ <ide> public function register() <ide> { <add> // This service provider is a great spot to register your various container <add> // bindings with the application. As you can see, we are registering our <add> // "Registrar" implementation here. You can add your own bindings too! <add> <ide> $this->app->bind( <ide> 'Illuminate\Contracts\Auth\Registrar', <ide> 'App\Services\Registrar'
1
Javascript
Javascript
add the beginning of a working cff font encoder
da69361ae057158ab6d233c2ee0a2437011374a4
<ide><path>PDFFont.js <ide> var Type1Parser = function(aAsciiStream, aBinaryStream) { <ide> "21": "rmoveto", <ide> "22": "hmoveto", <ide> "30": "vhcurveto", <del> "31": "hcurveto" <add> "31": "hvcurveto" <ide> }; <ide> <ide> function decodeCharString(aStream) { <ide> Type1Font.prototype = { <ide> <ide> //Top Dict Index <ide> var topDictIndex = [ <del> 0x00, 0x01, 0x01, 0x01, 0x29, <add> 0x00, 0x01, 0x01, 0x01, 0x2A, <ide> 248, 27, 0, // version <ide> 248, 28, 1, // Notice <ide> 248, 29, 2, // FullName <ide> 248, 30, 3, // FamilyName <ide> 248, 20, 4, // Weigth <ide> 82, 251, 98, 250, 105, 249, 72, 5, // FontBBox <ide> 248, 136, 15, // charset (offset: 500) <del> 28, 0, 0, 16, // Encoding (offset: 600) <del> 248, 236, 17, // CharStrings <del> 28, 0, 55, 28, 15, 160, 18 // Private (offset: 4000) <add> 28, 0, 0, 16, // Encoding <add> 28, 7, 208, 17, // CharStrings (offset: 2000) <add> 28, 0, 55, 28, 39, 16, 18 // Private (offset: 10000) <ide> ]; <ide> cff.set(topDictIndex, currentOffset); <ide> currentOffset += topDictIndex.length; <ide> Type1Font.prototype = { <ide> cff.set(empty, currentOffset); <ide> currentOffset += empty.length; <ide> <del> //Declare the letter 'C' <add> //Declare the letters <ide> var charset = [ <del> 0x00, 0x00, 0x42 <add> 0x00 <ide> ]; <add> var limit = 30; <add> for (var glyph in charstrings.map) { <add> if (!limit--) <add> break; <add> var index = CFFStrings.indexOf(glyph); <add> var bytes = integerToBytes(index, 2); <add> charset.push(bytes[0]); <add> charset.push(bytes[1]); <add> } <ide> cff.set(charset, currentOffset); <ide> currentOffset += charset.length; <ide> <ide> // Fill the space between this and the charstrings data by '1' <del> var empty = new Array(600 - currentOffset); <add> var empty = new Array(2000 - currentOffset); <ide> for (var i = 0; i < empty.length; i++) <ide> empty[i] = 0x01; <ide> cff.set(empty, currentOffset); <ide> currentOffset += empty.length; <ide> <ide> <add> var getNumFor = { <add> "hstem": 1, <add> "vstem": 3, <add> "vmoveto": 4, <add> "rlineto": 5, <add> "hlineto": 6, <add> "vlineto": 7, <add> "rrcurveto": 8, <add> "endchar": 14, <add> "rmoveto": 21, <add> "vhcurveto": 30, <add> "hvcurveto": 31, <add> }; <add> <ide> // Encode the glyph and add it to the FUX <del> var charStringsIndex = [ <del> 0x00, 0x02, 0x01, 0x01, 0x03, 0x05, <del> 0x40, 0x0E, <del> 0xAF, 0x0E <del> ]; <del> cff.set(charStringsIndex, currentOffset); <add> var r = [[0x40, 0xEA]]; <add> var limit = 30; <add> for (var glyph in glyphs) { <add> if (!limit--) <add> break; <add> var data = glyphs[glyph].slice(); <add> var charstring = []; <add> for (var i = 0; i < data.length; i++) { <add> var c = data[i]; <add> if (!IsNum(c)) { <add> var token = getNumFor[c]; <add> if (!token) <add> error(c); <add> charstring.push(token); <add> } else { <add> var bytes = encodeNumber(c); <add> for (var j = 0; j < bytes.length; j++) <add> charstring.push(bytes[j]); <add> } <add> } <add> r.push(charstring); <add> } <add> <add> var charStringsIndex = this.createCFFIndexHeader(r, true); <add> cff.set(charStringsIndex.join(" ").split(" "), currentOffset); <ide> currentOffset += charStringsIndex.length; <ide> <ide> // Fill the space between this and the private dict data by '1' <del> var empty = new Array(4000 - currentOffset); <add> var empty = new Array(10000 - currentOffset); <ide> for (var i = 0; i < empty.length; i++) <ide> empty[i] = 0x01; <ide> cff.set(empty, currentOffset); <ide> Type1Font.prototype = { <ide> <ide> var file = new Uint8Array(cff, 0, currentOffset); <ide> var parser = new Type2Parser(); <add> log("parse"); <ide> parser.parse(new Stream(file)); <ide> <ide> var file64 = Base64Encoder.encode(file); <ide> Type1Font.prototype = { <ide> <ide> function integerToBytes(aValue, aBytesCount) { <ide> var bytes = []; <add> for (var i = 0; i < aBytesCount; i++) <add> bytes[i] = 0x00; <ide> <ide> do { <ide> bytes[--aBytesCount] = (aValue & 0xFF); <ide> function encodeNumber(aValue) { <ide> } else { <ide> error("Value: " + aValue + " is not allowed"); <ide> } <del>} <add>}; <add> <ide><path>PDFFontUtils.js <ide> function readCharset(aStream, aCharstrings) { <ide> var count = aCharstrings.length - 1; <ide> for (var i = 1; i < count + 1; i++) { <ide> var sid = aStream.getByte() << 8 | aStream.getByte(); <del> log(sid); <ide> charset[CFFStrings[sid]] = readCharstringEncoding(aCharstrings[i]); <del> log(CFFStrings[sid] + "::" + charset[CFFStrings[sid]]); <add> //log(CFFStrings[sid] + "::" + charset[CFFStrings[sid]]); <ide> } <ide> } else if (format == 1) { <ide> error("Charset Range are not supported"); <ide> var Type2Parser = function(aFilePath) { <ide> var font = new Dict(); <ide> <ide> // Turn on this flag for additional debugging logs <del> var debug = true; <add> var debug = false; <ide> <ide> function dump(aStr) { <ide> if (debug) <ide> var Type2Parser = function(aFilePath) { <ide> <ide> function parseAsToken(aString, aMap) { <ide> var decoded = readFontDictData(aString, aMap); <del> log(decoded); <ide> <ide> var stack = []; <ide> var count = decoded.length;
2
Ruby
Ruby
add cask and download attributes
88208af8e488fe202fd5cb6b96a9f508ca635d5e
<ide><path>Library/Homebrew/requirement.rb <ide> class Requirement <ide> include Dependable <ide> <del> attr_reader :tags, :name <add> attr_reader :tags, :name, :cask, :download <ide> alias_method :option_name, :name <ide> <ide> def initialize(tags=[]) <add> @cask ||= self.class.cask <add> @download ||= self.class.download <add> tags.each do |tag| <add> next unless tag.is_a? Hash <add> @cask ||= tag[:cask] <add> @download ||= tag[:download] <add> end <ide> @tags = tags <ide> @tags << :build if self.class.build <ide> @name ||= infer_name <ide> end <ide> <ide> # The message to show when the requirement is not met. <del> def message; "" end <add> def message <add> s = "" <add> if cask <add> s += <<-EOS.undent <add> <add> You can install with Homebrew Cask: <add> brew install Caskroom/cask/#{cask} <add> EOS <add> end <add> <add> if download <add> s += <<-EOS.undent <add> <add> You can download from: <add> #{download} <add> EOS <add> end <add> s <add> end <ide> <ide> # Overriding #satisfied? is deprecated. <ide> # Pass a block or boolean to the satisfy DSL method instead. <ide> class << self <ide> <ide> attr_reader :env_proc <ide> attr_rw :fatal, :default_formula <add> attr_rw :cask, :download <ide> # build is deprecated, use `depends_on <requirement> => :build` instead <ide> attr_rw :build <ide>
1
Go
Go
remove promise package
0cd4ab3f9a3f242468484fc62b46e632fdba5e13
<ide><path>container/stream/attach.go <ide> import ( <ide> "golang.org/x/net/context" <ide> <ide> "github.com/docker/docker/pkg/pools" <del> "github.com/docker/docker/pkg/promise" <ide> "github.com/docker/docker/pkg/term" <ide> "github.com/sirupsen/logrus" <ide> ) <ide> func (c *Config) AttachStreams(cfg *AttachConfig) { <ide> } <ide> <ide> // CopyStreams starts goroutines to copy data in and out to/from the container <del>func (c *Config) CopyStreams(ctx context.Context, cfg *AttachConfig) chan error { <add>func (c *Config) CopyStreams(ctx context.Context, cfg *AttachConfig) <-chan error { <ide> var ( <ide> wg sync.WaitGroup <ide> errors = make(chan error, 3) <ide> func (c *Config) CopyStreams(ctx context.Context, cfg *AttachConfig) chan error <ide> go attachStream("stdout", cfg.Stdout, cfg.CStdout) <ide> go attachStream("stderr", cfg.Stderr, cfg.CStderr) <ide> <del> return promise.Go(func() error { <del> done := make(chan struct{}) <del> go func() { <del> wg.Wait() <del> close(done) <del> }() <del> select { <del> case <-done: <del> case <-ctx.Done(): <del> // close all pipes <del> if cfg.CStdin != nil { <del> cfg.CStdin.Close() <del> } <del> if cfg.CStdout != nil { <del> cfg.CStdout.Close() <del> } <del> if cfg.CStderr != nil { <del> cfg.CStderr.Close() <add> errs := make(chan error, 1) <add> <add> go func() { <add> defer close(errs) <add> errs <- func() error { <add> done := make(chan struct{}) <add> go func() { <add> wg.Wait() <add> close(done) <add> }() <add> select { <add> case <-done: <add> case <-ctx.Done(): <add> // close all pipes <add> if cfg.CStdin != nil { <add> cfg.CStdin.Close() <add> } <add> if cfg.CStdout != nil { <add> cfg.CStdout.Close() <add> } <add> if cfg.CStderr != nil { <add> cfg.CStderr.Close() <add> } <add> <-done <ide> } <del> <-done <del> } <del> close(errors) <del> for err := range errors { <del> if err != nil { <del> return err <add> close(errors) <add> for err := range errors { <add> if err != nil { <add> return err <add> } <ide> } <del> } <del> return nil <del> }) <add> return nil <add> }() <add> }() <add> <add> return errs <ide> } <ide> <ide> func copyEscapable(dst io.Writer, src io.ReadCloser, keys []byte) (written int64, err error) { <ide><path>pkg/archive/archive.go <ide> import ( <ide> "github.com/docker/docker/pkg/idtools" <ide> "github.com/docker/docker/pkg/ioutils" <ide> "github.com/docker/docker/pkg/pools" <del> "github.com/docker/docker/pkg/promise" <ide> "github.com/docker/docker/pkg/system" <ide> "github.com/sirupsen/logrus" <ide> ) <ide> func (archiver *Archiver) CopyFileWithTar(src, dst string) (err error) { <ide> } <ide> <ide> r, w := io.Pipe() <del> errC := promise.Go(func() error { <del> defer w.Close() <add> errC := make(chan error, 1) <ide> <del> srcF, err := os.Open(src) <del> if err != nil { <del> return err <del> } <del> defer srcF.Close() <add> go func() { <add> defer close(errC) <ide> <del> hdr, err := tar.FileInfoHeader(srcSt, "") <del> if err != nil { <del> return err <del> } <del> hdr.Name = filepath.Base(dst) <del> hdr.Mode = int64(chmodTarEntry(os.FileMode(hdr.Mode))) <add> errC <- func() error { <add> defer w.Close() <ide> <del> if err := remapIDs(archiver.IDMappingsVar, hdr); err != nil { <del> return err <del> } <add> srcF, err := os.Open(src) <add> if err != nil { <add> return err <add> } <add> defer srcF.Close() <ide> <del> tw := tar.NewWriter(w) <del> defer tw.Close() <del> if err := tw.WriteHeader(hdr); err != nil { <del> return err <del> } <del> if _, err := io.Copy(tw, srcF); err != nil { <del> return err <del> } <del> return nil <del> }) <add> hdr, err := tar.FileInfoHeader(srcSt, "") <add> if err != nil { <add> return err <add> } <add> hdr.Name = filepath.Base(dst) <add> hdr.Mode = int64(chmodTarEntry(os.FileMode(hdr.Mode))) <add> <add> if err := remapIDs(archiver.IDMappingsVar, hdr); err != nil { <add> return err <add> } <add> <add> tw := tar.NewWriter(w) <add> defer tw.Close() <add> if err := tw.WriteHeader(hdr); err != nil { <add> return err <add> } <add> if _, err := io.Copy(tw, srcF); err != nil { <add> return err <add> } <add> return nil <add> }() <add> }() <ide> defer func() { <ide> if er := <-errC; err == nil && er != nil { <ide> err = er <ide><path>pkg/containerfs/archiver.go <ide> import ( <ide> <ide> "github.com/docker/docker/pkg/archive" <ide> "github.com/docker/docker/pkg/idtools" <del> "github.com/docker/docker/pkg/promise" <ide> "github.com/docker/docker/pkg/system" <ide> "github.com/sirupsen/logrus" <ide> ) <ide> func (archiver *Archiver) CopyFileWithTar(src, dst string) (err error) { <ide> } <ide> <ide> r, w := io.Pipe() <del> errC := promise.Go(func() error { <del> defer w.Close() <del> <del> srcF, err := srcDriver.Open(src) <del> if err != nil { <del> return err <del> } <del> defer srcF.Close() <del> <del> hdr, err := tar.FileInfoHeader(srcSt, "") <del> if err != nil { <del> return err <del> } <del> hdr.Name = dstDriver.Base(dst) <del> if dstDriver.OS() == "windows" { <del> hdr.Mode = int64(chmodTarEntry(os.FileMode(hdr.Mode))) <del> } else { <del> hdr.Mode = int64(os.FileMode(hdr.Mode)) <del> } <del> <del> if err := remapIDs(archiver.IDMappingsVar, hdr); err != nil { <del> return err <del> } <del> <del> tw := tar.NewWriter(w) <del> defer tw.Close() <del> if err := tw.WriteHeader(hdr); err != nil { <del> return err <del> } <del> if _, err := io.Copy(tw, srcF); err != nil { <del> return err <del> } <del> return nil <del> }) <add> errC := make(chan error, 1) <add> <add> go func() { <add> defer close(errC) <add> errC <- func() error { <add> defer w.Close() <add> <add> srcF, err := srcDriver.Open(src) <add> if err != nil { <add> return err <add> } <add> defer srcF.Close() <add> <add> hdr, err := tar.FileInfoHeader(srcSt, "") <add> if err != nil { <add> return err <add> } <add> hdr.Name = dstDriver.Base(dst) <add> if dstDriver.OS() == "windows" { <add> hdr.Mode = int64(chmodTarEntry(os.FileMode(hdr.Mode))) <add> } else { <add> hdr.Mode = int64(os.FileMode(hdr.Mode)) <add> } <add> <add> if err := remapIDs(archiver.IDMappingsVar, hdr); err != nil { <add> return err <add> } <add> <add> tw := tar.NewWriter(w) <add> defer tw.Close() <add> if err := tw.WriteHeader(hdr); err != nil { <add> return err <add> } <add> if _, err := io.Copy(tw, srcF); err != nil { <add> return err <add> } <add> return nil <add> }() <add> }() <ide> defer func() { <ide> if er := <-errC; err == nil && er != nil { <ide> err = er <ide><path>pkg/promise/promise.go <del>package promise <del> <del>// Go is a basic promise implementation: it wraps calls a function in a goroutine, <del>// and returns a channel which will later return the function's return value. <del>func Go(f func() error) chan error { <del> ch := make(chan error, 1) <del> go func() { <del> ch <- f() <del> }() <del> return ch <del>} <ide><path>pkg/promise/promise_test.go <del>package promise <del> <del>import ( <del> "errors" <del> "testing" <del> <del> "github.com/stretchr/testify/require" <del>) <del> <del>func TestGo(t *testing.T) { <del> errCh := Go(functionWithError) <del> er := <-errCh <del> require.EqualValues(t, "Error Occurred", er.Error()) <del> <del> noErrCh := Go(functionWithNoError) <del> er = <-noErrCh <del> require.Nil(t, er) <del>} <del> <del>func functionWithError() (err error) { <del> return errors.New("Error Occurred") <del>} <del>func functionWithNoError() (err error) { <del> return nil <del>}
5
Javascript
Javascript
improve code and test
c51f0e1ce1aaca286eee10d356ed4ef2d73a5edc
<ide><path>lib/Watching.js <ide> class Watching { <ide> this.handler = handler; <ide> /** @type {Callback<void>[]} */ <ide> this.callbacks = []; <del> /** @type {Callback<void>[]} */ <del> this._closeCallbacks = []; <add> /** @type {Callback<void>[] | undefined} */ <add> this._closeCallbacks = undefined; <ide> this.closed = false; <ide> this.suspended = false; <ide> if (typeof watchOptions === "number") { <ide> class Watching { <ide> * @returns {void} <ide> */ <ide> close(callback) { <add> if (this._closeCallbacks) { <add> if (callback) { <add> this._closeCallbacks.push(callback); <add> } <add> return; <add> } <ide> const finalCallback = () => { <ide> this.running = false; <ide> this.compiler.running = false; <ide> class Watching { <ide> this.compiler.contextTimestamps = undefined; <ide> this.compiler.cache.shutdown(err => { <ide> this.compiler.hooks.watchClose.call(); <del> for (const cb of this._closeCallbacks) cb(err); <del> this._closeCallbacks.length = 0; <add> const closeCallbacks = this._closeCallbacks; <add> this._closeCallbacks = undefined; <add> for (const cb of closeCallbacks) cb(err); <ide> }); <ide> }; <ide> <ide> class Watching { <ide> this.pausedWatcher.close(); <ide> this.pausedWatcher = null; <ide> } <add> this._closeCallbacks = []; <ide> if (callback) { <ide> this._closeCallbacks.push(callback); <ide> } <ide><path>test/WatchClose.test.js <ide> describe("WatchClose", () => { <ide> close(watcher, () => (num += 1)), <ide> close(watcher, () => (num += 10)) <ide> ]); <add> await Promise.all([ <add> close(watcher, () => (num += 100)), <add> close(watcher, () => (num += 1000)) <add> ]); <ide> <del> expect(num).toBe(11); <add> expect(num).toBe(1111); <ide> <ide> done(); <ide> });
2
Java
Java
fix regression in client codecs
d1db249584c16e17ca94185e18e8da916d56190a
<ide><path>spring-web/src/main/java/org/springframework/http/codec/AbstractCodecConfigurer.java <ide> protected void addDefaultObjectWriters(List<HttpMessageWriter<?>> result) { <ide> /** <ide> * A registry and a factory for built-in HTTP message readers and writers. <ide> */ <del> public static class DefaultCodecConfigurer { <add> public abstract static class DefaultCodecConfigurer { <ide> <ide> private boolean suppressed = false; <ide> <ide> protected HttpMessageWriter<?> findWriter(Class<?> key, Supplier<HttpMessageWrit <ide> } <ide> <ide> <del> protected void addStringReaderTextOnlyTo(List<HttpMessageReader<?>> result) { <del> addReaderTo(result, () -> new DecoderHttpMessageReader<>(StringDecoder.textPlainOnly(true))); <del> } <add> protected abstract void addStringReaderTextOnlyTo(List<HttpMessageReader<?>> result); <ide> <del> protected void addStringReaderTo(List<HttpMessageReader<?>> result) { <del> addReaderTo(result, () -> new DecoderHttpMessageReader<>(StringDecoder.allMimeTypes(true))); <del> } <add> protected abstract void addStringReaderTo(List<HttpMessageReader<?>> result); <ide> <ide> protected void addStringWriterTextPlainOnlyTo(List<HttpMessageWriter<?>> result) { <ide> addWriterTo(result, () -> new EncoderHttpMessageWriter<>(CharSequenceEncoder.textPlainOnly())); <ide><path>spring-web/src/main/java/org/springframework/http/codec/ClientCodecConfigurer.java <ide> import java.util.List; <ide> <ide> import org.springframework.core.codec.Decoder; <add>import org.springframework.core.codec.StringDecoder; <ide> import org.springframework.http.codec.json.Jackson2JsonDecoder; <ide> <ide> /** <ide> public void serverSentEventDecoder(Decoder<?> decoder) { <ide> <ide> // Internal methods for building a list of default readers or writers... <ide> <add> protected void addStringReaderTextOnlyTo(List<HttpMessageReader<?>> result) { <add> addReaderTo(result, () -> new DecoderHttpMessageReader<>(StringDecoder.textPlainOnly(false))); <add> } <add> <add> protected void addStringReaderTo(List<HttpMessageReader<?>> result) { <add> addReaderTo(result, () -> new DecoderHttpMessageReader<>(StringDecoder.allMimeTypes(false))); <add> } <add> <ide> private void addServerSentEventReaderTo(List<HttpMessageReader<?>> result) { <ide> addReaderTo(result, () -> findReader(ServerSentEventHttpMessageReader.class, () -> { <ide> Decoder<?> decoder = null; <ide><path>spring-web/src/main/java/org/springframework/http/codec/ServerCodecConfigurer.java <ide> import java.util.List; <ide> <ide> import org.springframework.core.codec.Encoder; <add>import org.springframework.core.codec.StringDecoder; <ide> import org.springframework.http.codec.json.Jackson2JsonEncoder; <ide> <ide> /** <ide> public void serverSentEventEncoder(Encoder<?> encoder) { <ide> <ide> // Internal methods for building a list of default readers or writers... <ide> <add> protected void addStringReaderTextOnlyTo(List<HttpMessageReader<?>> result) { <add> addReaderTo(result, () -> new DecoderHttpMessageReader<>(StringDecoder.textPlainOnly(true))); <add> } <add> <add> protected void addStringReaderTo(List<HttpMessageReader<?>> result) { <add> addReaderTo(result, () -> new DecoderHttpMessageReader<>(StringDecoder.allMimeTypes(true))); <add> } <add> <ide> private void addServerSentEventWriterTo(List<HttpMessageWriter<?>> result) { <ide> addWriterTo(result, () -> findWriter(ServerSentEventHttpMessageWriter.class, () -> { <ide> Encoder<?> encoder = null; <ide><path>spring-web/src/test/java/org/springframework/http/codec/ClientCodecConfigurerTests.java <ide> */ <ide> package org.springframework.http.codec; <ide> <add>import java.nio.charset.StandardCharsets; <add>import java.time.Duration; <add>import java.util.Collections; <ide> import java.util.List; <ide> import java.util.concurrent.atomic.AtomicInteger; <ide> <ide> import org.junit.Test; <add>import reactor.core.publisher.Flux; <ide> <add>import org.springframework.core.ResolvableType; <ide> import org.springframework.core.codec.ByteArrayDecoder; <ide> import org.springframework.core.codec.ByteArrayEncoder; <ide> import org.springframework.core.codec.ByteBufferDecoder; <ide> import org.springframework.core.codec.Encoder; <ide> import org.springframework.core.codec.ResourceDecoder; <ide> import org.springframework.core.codec.StringDecoder; <add>import org.springframework.core.io.buffer.DefaultDataBufferFactory; <ide> import org.springframework.http.MediaType; <ide> import org.springframework.http.codec.json.Jackson2JsonDecoder; <ide> import org.springframework.http.codec.json.Jackson2JsonEncoder; <ide> private Encoder<?> getNextEncoder(List<HttpMessageWriter<?>> writers) { <ide> return ((EncoderHttpMessageWriter) writer).getEncoder(); <ide> } <ide> <add> @SuppressWarnings("unchecked") <ide> private void assertStringDecoder(Decoder<?> decoder, boolean textOnly) { <ide> assertEquals(StringDecoder.class, decoder.getClass()); <ide> assertTrue(decoder.canDecode(forClass(String.class), MimeTypeUtils.TEXT_PLAIN)); <ide> assertEquals(!textOnly, decoder.canDecode(forClass(String.class), MediaType.TEXT_EVENT_STREAM)); <add> <add> Flux<String> decoded = (Flux<String>) decoder.decode( <add> Flux.just(new DefaultDataBufferFactory().wrap("line1\nline2".getBytes(StandardCharsets.UTF_8))), <add> ResolvableType.forClass(String.class), MimeTypeUtils.TEXT_PLAIN, Collections.emptyMap()); <add> <add> assertEquals(Collections.singletonList("line1\nline2"), decoded.collectList().block(Duration.ZERO)); <ide> } <ide> <ide> private void assertStringEncoder(Encoder<?> encoder, boolean textOnly) { <ide><path>spring-web/src/test/java/org/springframework/http/codec/CodecConfigurerTests.java <ide> private void assertStringEncoder(Encoder<?> encoder, boolean textOnly) { <ide> private static class TestCodecConfigurer extends AbstractCodecConfigurer { <ide> <ide> private TestCodecConfigurer() { <del> super(new DefaultCodecConfigurer()); <add> super(new TestDefaultCodecConfigurer()); <add> } <add> <add> <add> private static class TestDefaultCodecConfigurer extends DefaultCodecConfigurer { <add> <add> protected void addStringReaderTextOnlyTo(List<HttpMessageReader<?>> result) { <add> addReaderTo(result, () -> new DecoderHttpMessageReader<>(StringDecoder.textPlainOnly(true))); <add> } <add> <add> protected void addStringReaderTo(List<HttpMessageReader<?>> result) { <add> addReaderTo(result, () -> new DecoderHttpMessageReader<>(StringDecoder.allMimeTypes(true))); <add> } <ide> } <ide> } <ide> <ide><path>spring-web/src/test/java/org/springframework/http/codec/ServerCodecConfigurerTests.java <ide> */ <ide> package org.springframework.http.codec; <ide> <add>import java.nio.charset.StandardCharsets; <add>import java.time.Duration; <add>import java.util.Arrays; <add>import java.util.Collections; <ide> import java.util.List; <ide> import java.util.concurrent.atomic.AtomicInteger; <ide> <ide> import org.junit.Test; <add>import reactor.core.publisher.Flux; <ide> <add>import org.springframework.core.ResolvableType; <ide> import org.springframework.core.codec.ByteArrayDecoder; <ide> import org.springframework.core.codec.ByteArrayEncoder; <ide> import org.springframework.core.codec.ByteBufferDecoder; <ide> import org.springframework.core.codec.Encoder; <ide> import org.springframework.core.codec.ResourceDecoder; <ide> import org.springframework.core.codec.StringDecoder; <add>import org.springframework.core.io.buffer.DefaultDataBufferFactory; <ide> import org.springframework.http.MediaType; <ide> import org.springframework.http.codec.json.Jackson2JsonDecoder; <ide> import org.springframework.http.codec.json.Jackson2JsonEncoder; <ide> private Encoder<?> getNextEncoder(List<HttpMessageWriter<?>> writers) { <ide> return ((EncoderHttpMessageWriter) writer).getEncoder(); <ide> } <ide> <add> @SuppressWarnings("unchecked") <ide> private void assertStringDecoder(Decoder<?> decoder, boolean textOnly) { <ide> assertEquals(StringDecoder.class, decoder.getClass()); <ide> assertTrue(decoder.canDecode(forClass(String.class), MimeTypeUtils.TEXT_PLAIN)); <ide> assertEquals(!textOnly, decoder.canDecode(forClass(String.class), MediaType.TEXT_EVENT_STREAM)); <add> <add> Flux<String> flux = (Flux<String>) decoder.decode( <add> Flux.just(new DefaultDataBufferFactory().wrap("line1\nline2".getBytes(StandardCharsets.UTF_8))), <add> ResolvableType.forClass(String.class), MimeTypeUtils.TEXT_PLAIN, Collections.emptyMap()); <add> <add> assertEquals(Arrays.asList("line1\n", "line2"), flux.collectList().block(Duration.ZERO)); <ide> } <ide> <ide> private void assertStringEncoder(Encoder<?> encoder, boolean textOnly) {
6
Javascript
Javascript
remove node.* deprecation messages
8f79169aef6cd447ff193616e49335473eeb15ba
<ide><path>src/node.js <ide> process.error = removed("process.error() has moved. Use require('sys') to bring <ide> process.watchFile = removed("process.watchFile() has moved to fs.watchFile()"); <ide> process.unwatchFile = removed("process.unwatchFile() has moved to fs.unwatchFile()"); <ide> process.mixin = removed('process.mixin() has been removed.'); <del> <del>GLOBAL.node = {}; <del> <del>node.createProcess = removed("node.createProcess() has been changed to process.createChildProcess() update your code"); <ide> process.createChildProcess = removed("childProcess API has changed. See doc/api.txt."); <del>node.exec = removed("process.exec() has moved. Use require('sys') to bring it back."); <del>node.inherits = removed("node.inherits() has moved. Use require('sys') to access it."); <ide> process.inherits = removed("process.inherits() has moved to sys.inherits."); <ide> <del>node.http = {}; <del>node.http.createServer = removed("node.http.createServer() has moved. Use require('http') to access it."); <del>node.http.createClient = removed("node.http.createClient() has moved. Use require('http') to access it."); <del> <del>node.tcp = {}; <del>node.tcp.createServer = removed("node.tcp.createServer() has moved. Use require('tcp') to access it."); <del>node.tcp.createConnection = removed("node.tcp.createConnection() has moved. Use require('tcp') to access it."); <del> <del>node.dns = {}; <del>node.dns.createConnection = removed("node.dns.createConnection() has moved. Use require('dns') to access it."); <del> <del> <ide> process.assert = function (x, msg) { <ide> if (!(x)) throw new Error(msg || "assertion error"); <ide> };
1
Python
Python
remove unused variable 'v'
73bcd657ebbbcd59937e4c737ce04c02662d9046
<ide><path>glances/exports/glances_influxdb.py <ide> def export(self, name, columns, points): <ide> if self.version == INFLUXDB_09: <ide> # Convert all int to float (mandatory for InfluxDB>0.9.2) <ide> # Correct issue#750 and issue#749 <del> for i, v in enumerate(points): <add> for i, _ in enumerate(points): <ide> try: <ide> points[i] = float(points[i]) <ide> except ValueError:
1
Ruby
Ruby
skip bottles for ci-syntax-only prs
e14ce96f224b2d330280e913908ea63c19d988b0
<ide><path>Library/Homebrew/dev-cmd/pr-pull.rb <ide> def cherry_pick_pr!(user, repo, pr, args:, path: ".") <ide> Utils::Git.cherry_pick!(path, "--ff", "--allow-empty", *commits, verbose: args.verbose?, resolve: args.resolve?) <ide> end <ide> <del> def formulae_need_bottles?(tap, original_commit, args:) <add> def formulae_need_bottles?(tap, original_commit, user, repo, pr, args:) <ide> return if args.dry_run? <add> return false if GitHub.pull_request_labels(user, repo, pr).include? "CI-syntax-only" <ide> <ide> changed_formulae(tap, original_commit).any? do |f| <ide> !f.bottle_unneeded? && !f.bottle_disabled? <ide> def pr_pull <ide> args: args) <ide> end <ide> <del> unless formulae_need_bottles?(tap, original_commit, args: args) <add> unless formulae_need_bottles?(tap, original_commit, user, repo, pr, args: args) <ide> ohai "Skipping artifacts for ##{pr} as the formulae don't need bottles" <ide> next <ide> end <ide><path>Library/Homebrew/utils/github.rb <ide> def pull_request_commits(user, repo, pr, per_page: 100) <ide> end <ide> end <ide> end <add> <add> def pull_request_labels(user, repo, pr) <add> pr_data = open_api(url_to("repos", user, repo, "pulls", pr)) <add> pr_data["labels"].map { |label| label["name"] } <add> end <ide> end
2
PHP
PHP
move observers below relations in command output
a299816674a5ef99092f6c2d9ed9973a77e4faa4
<ide><path>src/Illuminate/Foundation/Console/ShowModelCommand.php <ide> protected function displayCli($class, $database, $table, $attributes, $relations <ide> <ide> $this->newLine(); <ide> <del> $this->components->twoColumnDetail('<fg=green;options=bold>Eloquent Observers</>'); <del> <del> if ($observers->count()) { <del> foreach ($observers as $observer) { <del> $this->components->twoColumnDetail( <del> sprintf('%s', $observer['event']), implode(', ', $observer['observer'])); <del> } <del> } <del> <del> $this->newLine(); <del> <ide> $this->components->twoColumnDetail('<fg=green;options=bold>Relations</>'); <ide> <ide> foreach ($relations as $relation) { <ide> protected function displayCli($class, $database, $table, $attributes, $relations <ide> } <ide> <ide> $this->newLine(); <add> <add> $this->components->twoColumnDetail('<fg=green;options=bold>Observers</>'); <add> <add> if ($observers->count()) { <add> foreach ($observers as $observer) { <add> $this->components->twoColumnDetail( <add> sprintf('%s', $observer['event']), implode(', ', $observer['observer'])); <add> } <add> } <add> <add> $this->newLine(); <ide> } <ide> <ide> /**
1
Javascript
Javascript
fix lint error
03c3730b7873f5c8e303917082af790081e93c64
<ide><path>benchmarks/benchmark-runner.js <ide> module.exports = async ({test, benchmarkPaths}) => { <ide> if (data.points.length > 1) { <ide> const canvas = document.createElement('canvas') <ide> benchmarkContainer.appendChild(canvas) <del> const chart = new Chart(canvas, { <add> // eslint-disable-next-line no-new <add> new Chart(canvas, { <ide> type: 'line', <ide> data: { <ide> datasets: [{label: key, fill: false, data: data.points}]
1
PHP
PHP
update response to use cookiecollection internally
bf81b15169231e8033bca108641109bbc8bf06ee
<ide><path>src/Http/Response.php <ide> <ide> use Cake\Core\Configure; <ide> use Cake\Filesystem\File; <add>use Cake\Http\Cookie\Cookie; <add>use Cake\Http\Cookie\CookieCollection; <ide> use Cake\Log\Log; <ide> use Cake\Network\CorsBuilder; <ide> use Cake\Network\Exception\NotFoundException; <ide> class Response implements ResponseInterface <ide> protected $_cacheDirectives = []; <ide> <ide> /** <del> * Holds cookies to be sent to the client <add> * Collection of cookies to send to the client <ide> * <del> * @var array <add> * @var Cake\Http\Cookie\CookieCollection <ide> */ <del> protected $_cookies = []; <add> protected $_cookies = null; <ide> <ide> /** <ide> * Reason Phrase <ide> public function __construct(array $options = []) <ide> $this->_contentType = $this->resolveType($options['type']); <ide> } <ide> $this->_setContentType(); <add> $this->_cookies = new CookieCollection(); <ide> } <ide> <ide> /** <ide> public function __toString() <ide> public function cookie($options = null) <ide> { <ide> if ($options === null) { <del> return $this->_cookies; <add> return $this->getCookies(); <ide> } <ide> <ide> if (is_string($options)) { <del> if (!isset($this->_cookies[$options])) { <add> if (!$this->_cookies->has($options)) { <ide> return null; <ide> } <ide> <del> return $this->_cookies[$options]; <add> return $this->_cookies->get($options)->toArrayResponse(); <ide> } <ide> <ide> $defaults = [ <ide> public function cookie($options = null) <ide> 'httpOnly' => false <ide> ]; <ide> $options += $defaults; <del> <del> $this->_cookies[$options['name']] = $options; <add> $cookie = new Cookie( <add> $options['name'], <add> $options['value'], <add> $options['expire'], <add> $options['path'], <add> $options['domain'], <add> $options['secure'], <add> $options['httpOnly'] <add> ); <add> $this->_cookies = $this->_cookies->add($cookie); <ide> } <ide> <ide> /** <ide> public function withCookie($name, $data = '') <ide> 'httpOnly' => false <ide> ]; <ide> $data += $defaults; <del> $data['name'] = $name; <add> $cookie = new Cookie( <add> $name, <add> $data['value'], <add> $data['expire'], <add> $data['path'], <add> $data['domain'], <add> $data['secure'], <add> $data['httpOnly'] <add> ); <ide> <ide> $new = clone $this; <del> $new->_cookies[$name] = $data; <add> $new->_cookies = $new->_cookies->add($cookie); <ide> <ide> return $new; <ide> } <ide> public function withCookie($name, $data = '') <ide> */ <ide> public function getCookie($name) <ide> { <del> if (isset($this->_cookies[$name])) { <del> return $this->_cookies[$name]; <add> if (!$this->_cookies->has($name)) { <add> return null; <ide> } <ide> <del> return null; <add> return $this->_cookies->get($name)->toArrayResponse(); <ide> } <ide> <ide> /** <ide> public function getCookie($name) <ide> * @return array <ide> */ <ide> public function getCookies() <add> { <add> $out = []; <add> foreach ($this->_cookies as $cookie) { <add> $out[$cookie->getName()] = $cookie->toArrayResponse(); <add> } <add> <add> return $out; <add> } <add> <add> /** <add> * Get the CookieCollection from the response <add> * <add> * @return \Cake\Http\Cookie\CookieCollection <add> */ <add> public function getCookieCollection() <ide> { <ide> return $this->_cookies; <ide> } <ide><path>tests/TestCase/Http/ResponseTest.php <ide> <ide> include_once CORE_TEST_CASES . DS . 'Http' . DS . 'server_mocks.php'; <ide> <add>use Cake\Http\Cookie\Cookie; <add>use Cake\Http\Cookie\CookieCollection; <ide> use Cake\Http\Response; <ide> use Cake\Http\ServerRequest; <ide> use Cake\Network\Exception\NotFoundException; <ide> public function testCookieSettings() <ide> 'path' => '/', <ide> 'domain' => '', <ide> 'secure' => false, <del> 'httpOnly' => false]; <add> 'httpOnly' => false <add> ]; <ide> $result = $response->cookie('CakeTestCookie[Testing]'); <ide> $this->assertEquals($expected, $result); <ide> <ide> public function testWithCookieArray() <ide> public function testGetCookies() <ide> { <ide> $response = new Response(); <del> $cookie = [ <del> 'name' => 'ignored key', <del> 'value' => '[a,b,c]', <del> 'expire' => 1000, <del> 'path' => '/test', <del> 'secure' => true <del> ]; <ide> $new = $response->withCookie('testing', 'a') <ide> ->withCookie('test2', ['value' => 'b', 'path' => '/test', 'secure' => true]); <ide> $expected = [ <ide> public function testGetCookies() <ide> $this->assertEquals($expected, $new->getCookies()); <ide> } <ide> <add> /** <add> * Test getCookieCollection() as array data <add> * <add> * @return void <add> */ <add> public function testGetCookieCollection() <add> { <add> $response = new Response(); <add> $new = $response->withCookie('testing', 'a') <add> ->withCookie('test2', ['value' => 'b', 'path' => '/test', 'secure' => true]); <add> $cookies = $response->getCookieCollection(); <add> $this->assertInstanceOf(CookieCollection::class, $cookies); <add> $this->assertCount(0, $cookies, 'Original response not mutated'); <add> <add> $cookies = $new->getCookieCollection(); <add> $this->assertInstanceOf(CookieCollection::class, $cookies); <add> $this->assertCount(2, $cookies); <add> <add> $this->assertTrue($cookies->has('testing')); <add> $this->assertTrue($cookies->has('test2')); <add> } <add> <ide> /** <ide> * Test CORS <ide> * <ide> public function testDebugInfo() <ide> ], <ide> 'file' => null, <ide> 'fileRange' => [], <del> 'cookies' => [], <add> 'cookies' => new CookieCollection(), <ide> 'cacheDirectives' => [], <ide> 'body' => '' <ide> ];
2
Mixed
Python
raise an error for textcat with <2 labels
29906884c5de57c73f5512452a7eb871061fb96c
<ide><path>spacy/errors.py <ide> class Errors: <ide> E202 = ("Unsupported alignment mode '{mode}'. Supported modes: {modes}.") <ide> <ide> # New errors added in v3.x <add> E867 = ("The 'textcat' component requires at least two labels because it " <add> "uses mutually exclusive classes where exactly one label is True " <add> "for each doc. For binary classification tasks, you can use two " <add> "labels with 'textcat' (LABEL / NOT_LABEL) or alternatively, you " <add> "can use the 'textcat_multilabel' component with one label.") <ide> E868 = ("Found a conflicting gold annotation in a reference document, " <ide> "with the following char-based span occurring both in the gold ents " <ide> "as well as in the negative spans: {span}.") <ide><path>spacy/pipeline/textcat.py <ide> def initialize( <ide> else: <ide> for label in labels: <ide> self.add_label(label) <add> if len(self.labels) < 2: <add> raise ValueError(Errors.E867) <ide> if positive_label is not None: <ide> if positive_label not in self.labels: <ide> err = Errors.E920.format(pos_label=positive_label, labels=self.labels) <ide><path>spacy/tests/pipeline/test_textcat.py <ide> def test_label_types(name): <ide> textcat.add_label("answer") <ide> with pytest.raises(ValueError): <ide> textcat.add_label(9) <add> # textcat requires at least two labels <add> if name == "textcat": <add> with pytest.raises(ValueError): <add> nlp.initialize() <add> else: <add> nlp.initialize() <ide> <ide> <ide> @pytest.mark.parametrize("name", ["textcat", "textcat_multilabel"]) <ide><path>website/docs/api/textcategorizer.md <ide> api_trainable: true <ide> --- <ide> <ide> The text categorizer predicts **categories over a whole document**. and comes in <del>two flavours: `textcat` and `textcat_multilabel`. When you need to predict <add>two flavors: `textcat` and `textcat_multilabel`. When you need to predict <ide> exactly one true label per document, use the `textcat` which has mutually <ide> exclusive labels. If you want to perform multi-label classification and predict <del>zero, one or more labels per document, use the `textcat_multilabel` component <del>instead. <add>zero, one or more true labels per document, use the `textcat_multilabel` <add>component instead. For a binary classification task, you can use `textcat` with <add>**two** labels or `textcat_multilabel` with **one** label. <ide> <ide> Both components are documented on this page. <ide> <ide> This method was previously called `begin_training`. <ide> | _keyword-only_ | | <ide> | `nlp` | The current `nlp` object. Defaults to `None`. ~~Optional[Language]~~ | <ide> | `labels` | The label information to add to the component, as provided by the [`label_data`](#label_data) property after initialization. To generate a reusable JSON file from your data, you should run the [`init labels`](/api/cli#init-labels) command. If no labels are provided, the `get_examples` callback is used to extract the labels from the data, which may be a lot slower. ~~Optional[Iterable[str]]~~ | <del>| `positive_label` | The positive label for a binary task with exclusive classes, `None` otherwise and by default. This parameter is not available when using the `textcat_multilabel` component. ~~Optional[str]~~ | <add>| `positive_label` | The positive label for a binary task with exclusive classes, `None` otherwise and by default. This parameter is only used during scoring. It is not available when using the `textcat_multilabel` component. ~~Optional[str]~~ | <ide> <ide> ## TextCategorizer.predict {#predict tag="method"} <ide>
4
Python
Python
use integer division to avoid casting to int
d0e9d98b2aa126bb2654c4c5966a4034c4bb99fc
<ide><path>numpy/ma/core.py <ide> def __str__(self): <ide> # object dtype, extract the corners before the conversion. <ide> for axis in range(self.ndim): <ide> if data.shape[axis] > self._print_width: <del> ind = np.int(self._print_width / 2) <add> ind = self._print_width // 2 <ide> arr = np.split(data, (ind, -ind), axis=axis) <ide> data = np.concatenate((arr[0], arr[2]), axis=axis) <ide> arr = np.split(mask, (ind, -ind), axis=axis)
1
Javascript
Javascript
add ordinalparse support in core
0a794fa679bc1f83b5904db280007e72bbadd011
<ide><path>moment.js <ide> parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z <ide> parseTokenT = /T/i, // T (ISO separator) <ide> parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123 <del> parseTokenOrdinal = /\d{1,2}/, <ide> <ide> //strict parsing regexes <ide> parseTokenOneDigit = /\d/, // 0 - 9 <ide> this['_' + i] = prop; <ide> } <ide> } <add> // Lenient ordinal parsing accepts just a number in addition to <add> // number + (possibly) stuff coming from _ordinalParseLenient. <add> this._ordinalParseLenient = new RegExp(this._ordinalParse.source + '|' + /\d{1,2}/.source); <ide> }, <ide> <ide> _months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'), <ide> return this._ordinal.replace('%d', number); <ide> }, <ide> _ordinal : '%d', <add> _ordinalParse : /\d{1,2}/, <ide> <ide> preparse : function (string) { <ide> return string; <ide> case 'E': <ide> return parseTokenOneOrTwoDigits; <ide> case 'Do': <del> return parseTokenOrdinal; <add> return strict ? config._locale._ordinalParse : config._locale._ordinalParseLenient; <ide> default : <ide> a = new RegExp(regexpEscape(unescapeFormat(token.replace('\\', '')), 'i')); <ide> return a; <ide> break; <ide> case 'Do' : <ide> if (input != null) { <del> datePartArray[DATE] = toInt(parseInt(input, 10)); <add> datePartArray[DATE] = toInt(parseInt( <add> input.match(/\d{1,2}/)[0], 10)); <ide> } <ide> break; <ide> // DAY OF YEAR
1
Python
Python
add german norm exceptions
0d6fa8b241d1d29a99a0e12015a7fadaec217cf5
<ide><path>spacy/lang/de/__init__.py <ide> from __future__ import unicode_literals <ide> <ide> from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS <add>from .norm_exceptions import NORM_EXCEPTIONS <ide> from .tag_map import TAG_MAP <ide> from .stop_words import STOP_WORDS <ide> from .lemmatizer import LOOKUP <ide> from .syntax_iterators import SYNTAX_ITERATORS <ide> <ide> from ..tokenizer_exceptions import BASE_EXCEPTIONS <add>from ..norm_exceptions import BASE_NORMS <ide> from ...language import Language <ide> from ...lemmatizerlookup import Lemmatizer <del>from ...attrs import LANG <del>from ...util import update_exc <add>from ...attrs import LANG, NORM <add>from ...util import update_exc, add_lookups <ide> <ide> <ide> class GermanDefaults(Language.Defaults): <ide> lex_attr_getters = dict(Language.Defaults.lex_attr_getters) <ide> lex_attr_getters[LANG] = lambda text: 'de' <add> lex_attr_getters[NORM] = add_lookups(Language.Defaults.lex_attr_getters[NORM], <add> BASE_NORMS, NORM_EXCEPTIONS) <ide> <ide> tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS) <ide> tag_map = dict(TAG_MAP) <ide><path>spacy/lang/de/norm_exceptions.py <add># coding: utf8 <add>from __future__ import unicode_literals <add> <add># Here we only want to include the absolute most common words. Otherwise, <add># this list would get impossibly long for German – especially considering the <add># old vs. new spelling rules, and all possible cases. <add> <add> <add>_exc = { <add> "daß": "dass" <add>} <add> <add> <add>NORM_EXCEPTIONS = {} <add> <add>for string, norm in _exc.items(): <add> NORM_EXCEPTIONS[string.title()] = norm
2
Javascript
Javascript
ingest a player div for videojs
74530d8b3afe71a28ffc36a2623bd938a9d419ad
<ide><path>src/js/player.js <ide> class Player extends Component { <ide> * The DOM element that gets created. <ide> */ <ide> createEl() { <del> const el = this.el_ = super.createEl('div'); <ide> const tag = this.tag; <add> let el; <add> const playerElIngest = this.playerElIngest_ = tag.parentNode && tag.parentNode.hasAttribute('data-vjs-player'); <add> <add> if (playerElIngest) { <add> el = this.el_ = tag.parentNode; <add> } else { <add> el = this.el_ = super.createEl('div'); <add> } <ide> <ide> // Remove width/height attrs from tag so CSS can make it 100% width/height <ide> tag.removeAttribute('width'); <ide> class Player extends Component { <ide> // workaround so we don't totally break IE7 <ide> // http://stackoverflow.com/questions/3653444/css-styles-not-applied-on-dynamic-elements-in-internet-explorer-7 <ide> if (attr === 'class') { <del> el.className = attrs[attr]; <add> el.className += ' ' + attrs[attr]; <ide> } else { <ide> el.setAttribute(attr, attrs[attr]); <ide> } <ide> class Player extends Component { <ide> tag.initNetworkState_ = tag.networkState; <ide> <ide> // Wrap video tag in div (el/box) container <del> if (tag.parentNode) { <add> if (tag.parentNode && !playerElIngest) { <ide> tag.parentNode.insertBefore(el, tag); <ide> } <ide> <ide> class Player extends Component { <ide> 'muted': this.options_.muted, <ide> 'poster': this.poster(), <ide> 'language': this.language(), <add> 'playerElIngest': this.playerElIngest_ || false, <ide> 'vtt.js': this.options_['vtt.js'] <ide> }, this.options_[techName.toLowerCase()]); <ide> <ide><path>src/js/tech/html5.js <ide> class Html5 extends Tech { <ide> // Check if this browser supports moving the element into the box. <ide> // On the iPhone video will break if you move the element, <ide> // So we have to create a brand new element. <del> if (!el || this.movingMediaElementInDOM === false) { <add> // If we ingested the player div, we do not need to move the media element. <add> if (!el || <add> !(this.options_.playerElIngest || <add> this.movingMediaElementInDOM)) { <ide> <ide> // If the original tag is still there, clone and remove it. <ide> if (el) { <ide> const clone = el.cloneNode(true); <ide> <del> el.parentNode.insertBefore(clone, el); <add> if (el.parentNode) { <add> el.parentNode.insertBefore(clone, el); <add> } <ide> Html5.disposeMediaElement(el); <ide> el = clone; <add> <ide> } else { <ide> el = document.createElement('video'); <ide> <ide><path>test/unit/player.test.js <ide> QUnit.test('should restore attributes from the original video tag when creating <ide> assert.equal(el.getAttribute('webkit-playsinline'), '', 'webkit-playsinline attribute was set properly'); <ide> }); <ide> <add>QUnit.test('if tag exists and movingMediaElementInDOM, re-use the tag', function(assert) { <add> // simulate attributes stored from the original tag <add> const tag = Dom.createEl('video'); <add> <add> tag.setAttribute('preload', 'auto'); <add> tag.setAttribute('autoplay', ''); <add> tag.setAttribute('webkit-playsinline', ''); <add> <add> const html5Mock = { <add> options_: { <add> tag, <add> playerElIngest: false <add> }, <add> movingMediaElementInDOM: true <add> }; <add> <add> // set options that should override tag attributes <add> html5Mock.options_.preload = 'none'; <add> <add> // create the element <add> const el = Html5.prototype.createEl.call(html5Mock); <add> <add> assert.equal(el.getAttribute('preload'), 'none', 'attribute was successful overridden by an option'); <add> assert.equal(el.getAttribute('autoplay'), '', 'autoplay attribute was set properly'); <add> assert.equal(el.getAttribute('webkit-playsinline'), '', 'webkit-playsinline attribute was set properly'); <add> <add> assert.equal(el, tag, 'we have re-used the tag as expected'); <add>}); <add> <add>QUnit.test('if tag exists and *not* movingMediaElementInDOM, create a new tag', function(assert) { <add> // simulate attributes stored from the original tag <add> const tag = Dom.createEl('video'); <add> <add> tag.setAttribute('preload', 'auto'); <add> tag.setAttribute('autoplay', ''); <add> tag.setAttribute('webkit-playsinline', ''); <add> <add> const html5Mock = { <add> options_: { <add> tag, <add> playerElIngest: false <add> }, <add> movingMediaElementInDOM: false <add> }; <add> <add> // set options that should override tag attributes <add> html5Mock.options_.preload = 'none'; <add> <add> // create the element <add> const el = Html5.prototype.createEl.call(html5Mock); <add> <add> assert.equal(el.getAttribute('preload'), 'none', 'attribute was successful overridden by an option'); <add> assert.equal(el.getAttribute('autoplay'), '', 'autoplay attribute was set properly'); <add> assert.equal(el.getAttribute('webkit-playsinline'), '', 'webkit-playsinline attribute was set properly'); <add> <add> assert.notEqual(el, tag, 'we have not re-used the tag as expected'); <add>}); <add> <add>QUnit.test('if tag exists and *not* movingMediaElementInDOM, but playerElIngest re-use tag', function(assert) { <add> // simulate attributes stored from the original tag <add> const tag = Dom.createEl('video'); <add> <add> tag.setAttribute('preload', 'auto'); <add> tag.setAttribute('autoplay', ''); <add> tag.setAttribute('webkit-playsinline', ''); <add> <add> const html5Mock = { <add> options_: { <add> tag, <add> playerElIngest: true <add> }, <add> movingMediaElementInDOM: false <add> }; <add> <add> // set options that should override tag attributes <add> html5Mock.options_.preload = 'none'; <add> <add> // create the element <add> const el = Html5.prototype.createEl.call(html5Mock); <add> <add> assert.equal(el.getAttribute('preload'), 'none', 'attribute was successful overridden by an option'); <add> assert.equal(el.getAttribute('autoplay'), '', 'autoplay attribute was set properly'); <add> assert.equal(el.getAttribute('webkit-playsinline'), '', 'webkit-playsinline attribute was set properly'); <add> <add> assert.equal(el, tag, 'we have re-used the tag as expected'); <add>}); <add> <ide> QUnit.test('should honor default inactivity timeout', function(assert) { <ide> const clock = sinon.useFakeTimers(); <ide> <ide><path>test/unit/video.test.js <ide> QUnit.test('should return a video player instance', function(assert) { <ide> const player2 = videojs(tag2, { techOrder: ['techFaker'] }); <ide> <ide> assert.ok(player2.id() === 'test_vid_id2', 'created player from element'); <add> <add> player.dispose(); <add> player2.dispose(); <ide> }); <ide> <ide> QUnit.test('should return a video player instance from el html5 tech', function(assert) { <ide> QUnit.test('should return a video player instance from el html5 tech', function( <ide> const player2 = videojs(tag2, { techOrder: ['techFaker'] }); <ide> <ide> assert.ok(player2.id() === 'test_vid_id2', 'created player from element'); <add> <add> player.dispose(); <add> player2.dispose(); <ide> }); <ide> <ide> QUnit.test('should return a video player instance from el techfaker', function(assert) { <ide> QUnit.test('should return a video player instance from el techfaker', function(a <ide> const player2 = videojs(tag2, { techOrder: ['techFaker'] }); <ide> <ide> assert.ok(player2.id() === 'test_vid_id2', 'created player from element'); <add> <add> player.dispose(); <add> player2.dispose(); <ide> }); <ide> <ide> QUnit.test('should add the value to the languages object', function(assert) { <ide> QUnit.test('should expose DOM functions', function(assert) { <ide> `videojs.${vjsName} is a reference to Dom.${domName}`); <ide> }); <ide> }); <add> <add>QUnit.test('ingest player div if data-vjs-player attribute is present on video parentNode', function(assert) { <add> const fixture = document.querySelector('#qunit-fixture'); <add> <add> fixture.innerHTML = ` <add> <div data-vjs-player class="foo"> <add> <video id="test_vid_id"> <add> <source src="http://example.com/video.mp4" type="video/mp4"></source> <add> </video> <add> </div> <add> `; <add> <add> const playerDiv = document.querySelector('.foo'); <add> const vid = document.querySelector('#test_vid_id'); <add> <add> const player = videojs(vid, { <add> techOrder: ['html5'] <add> }); <add> <add> assert.equal(player.el(), playerDiv, 'we re-used the given div'); <add> assert.ok(player.hasClass('foo'), 'keeps any classes that were around previously'); <add> <add> player.dispose(); <add>}); <add> <add>QUnit.test('ingested player div should not create a new tag for movingMediaElementInDOM', function(assert) { <add> const Html5 = videojs.getTech('Html5'); <add> const oldIS = Html5.isSupported; <add> const oldMoving = Html5.prototype.movingMediaElementInDOM; <add> const oldCPT = Html5.nativeSourceHandler.canPlayType; <add> const fixture = document.querySelector('#qunit-fixture'); <add> <add> fixture.innerHTML = ` <add> <div data-vjs-player class="foo"> <add> <video id="test_vid_id"> <add> <source src="http://example.com/video.mp4" type="video/mp4"></source> <add> </video> <add> </div> <add> `; <add> Html5.prototype.movingMediaElementInDOM = false; <add> Html5.isSupported = () => true; <add> Html5.nativeSourceHandler.canPlayType = () => true; <add> <add> const playerDiv = document.querySelector('.foo'); <add> const vid = document.querySelector('#test_vid_id'); <add> <add> const player = videojs(vid, { <add> techOrder: ['html5'] <add> }); <add> <add> assert.equal(player.el(), playerDiv, 'we re-used the given div'); <add> assert.equal(player.tech_.el(), vid, 'we re-used the video element'); <add> assert.ok(player.hasClass('foo'), 'keeps any classes that were around previously'); <add> <add> player.dispose(); <add> Html5.prototype.movingMediaElementInDOM = oldMoving; <add> Html5.isSupported = oldIS; <add> Html5.nativeSourceHandler.canPlayType = oldCPT; <add>}); <add> <add>QUnit.test('should create a new tag for movingMediaElementInDOM', function(assert) { <add> const Html5 = videojs.getTech('Html5'); <add> const oldMoving = Html5.prototype.movingMediaElementInDOM; <add> const oldCPT = Html5.nativeSourceHandler.canPlayType; <add> const fixture = document.querySelector('#qunit-fixture'); <add> const oldIS = Html5.isSupported; <add> <add> fixture.innerHTML = ` <add> <div class="foo"> <add> <video id="test_vid_id"> <add> <source src="http://example.com/video.mp4" type="video/mp4"></source> <add> </video> <add> </div> <add> `; <add> Html5.prototype.movingMediaElementInDOM = false; <add> Html5.isSupported = () => true; <add> Html5.nativeSourceHandler.canPlayType = () => true; <add> <add> const playerDiv = document.querySelector('.foo'); <add> const vid = document.querySelector('#test_vid_id'); <add> <add> const player = videojs(vid, { <add> techOrder: ['html5'] <add> }); <add> <add> assert.notEqual(player.el(), playerDiv, 'we used a new div'); <add> assert.notEqual(player.tech_.el(), vid, 'we a new video element'); <add> <add> player.dispose(); <add> Html5.prototype.movingMediaElementInDOM = oldMoving; <add> Html5.isSupported = oldIS; <add> Html5.nativeSourceHandler.canPlayType = oldCPT; <add>});
4
Mixed
Go
add daemon option --default-shm-size
db575ef626e8b2660750cbede6b19e951a3b4341
<ide><path>cli/command/service/opts.go <ide> import ( <ide> "github.com/docker/docker/opts" <ide> runconfigopts "github.com/docker/docker/runconfig/opts" <ide> "github.com/docker/go-connections/nat" <del> units "github.com/docker/go-units" <ide> "github.com/spf13/cobra" <ide> ) <ide> <ide> type int64Value interface { <ide> Value() int64 <ide> } <ide> <del>type memBytes int64 <del> <del>func (m *memBytes) String() string { <del> return units.BytesSize(float64(m.Value())) <del>} <del> <del>func (m *memBytes) Set(value string) error { <del> val, err := units.RAMInBytes(value) <del> *m = memBytes(val) <del> return err <del>} <del> <del>func (m *memBytes) Type() string { <del> return "bytes" <del>} <del> <del>func (m *memBytes) Value() int64 { <del> return int64(*m) <del>} <del> <ide> // PositiveDurationOpt is an option type for time.Duration that uses a pointer. <ide> // It bahave similarly to DurationOpt but only allows positive duration values. <ide> type PositiveDurationOpt struct { <ide> type updateOptions struct { <ide> <ide> type resourceOptions struct { <ide> limitCPU opts.NanoCPUs <del> limitMemBytes memBytes <add> limitMemBytes opts.MemBytes <ide> resCPU opts.NanoCPUs <del> resMemBytes memBytes <add> resMemBytes opts.MemBytes <ide> } <ide> <ide> func (r *resourceOptions) ToResourceRequirements() *swarm.ResourceRequirements { <ide><path>cli/command/service/opts_test.go <ide> import ( <ide> ) <ide> <ide> func TestMemBytesString(t *testing.T) { <del> var mem memBytes = 1048576 <add> var mem opts.MemBytes = 1048576 <ide> assert.Equal(t, mem.String(), "1 MiB") <ide> } <ide> <ide> func TestMemBytesSetAndValue(t *testing.T) { <del> var mem memBytes <add> var mem opts.MemBytes <ide> assert.NilError(t, mem.Set("5kb")) <ide> assert.Equal(t, mem.Value(), int64(5120)) <ide> } <ide><path>container/container_unix.go <ide> import ( <ide> ) <ide> <ide> const ( <del> // DefaultSHMSize is the default size (64MB) of the SHM which will be mounted in the container <del> DefaultSHMSize int64 = 67108864 <del> containerSecretMountPath = "/run/secrets" <add> containerSecretMountPath = "/run/secrets" <ide> ) <ide> <ide> // Container holds the fields specific to unixen implementations. <ide><path>daemon/config_unix.go <ide> var ( <ide> defaultPidFile = "/var/run/docker.pid" <ide> defaultGraph = "/var/lib/docker" <ide> defaultExecRoot = "/var/run/docker" <add> defaultShmSize = int64(67108864) <ide> ) <ide> <ide> // Config defines the configuration of a docker daemon. <ide> type Config struct { <ide> Init bool `json:"init,omitempty"` <ide> InitPath string `json:"init-path,omitempty"` <ide> SeccompProfile string `json:"seccomp-profile,omitempty"` <add> ShmSize opts.MemBytes `json:"default-shm-size,omitempty"` <ide> } <ide> <ide> // bridgeConfig stores all the bridge driver specific <ide> func (config *Config) InstallFlags(flags *pflag.FlagSet) { <ide> <ide> config.Ulimits = make(map[string]*units.Ulimit) <ide> <add> // Set default value for `--default-shm-size` <add> config.ShmSize = opts.MemBytes(defaultShmSize) <add> <ide> // Then platform-specific install flags <ide> flags.BoolVar(&config.EnableSelinuxSupport, "selinux-enabled", false, "Enable selinux support") <ide> flags.Var(opts.NewUlimitOpt(&config.Ulimits), "default-ulimit", "Default ulimits for containers") <ide> func (config *Config) InstallFlags(flags *pflag.FlagSet) { <ide> flags.Int64Var(&config.CPURealtimePeriod, "cpu-rt-period", 0, "Limit the CPU real-time period in microseconds") <ide> flags.Int64Var(&config.CPURealtimeRuntime, "cpu-rt-runtime", 0, "Limit the CPU real-time runtime in microseconds") <ide> flags.StringVar(&config.SeccompProfile, "seccomp-profile", "", "Path to seccomp profile") <add> flags.Var(&config.ShmSize, "default-shm-size", "Default shm size for containers") <ide> <ide> config.attachExperimentalFlags(flags) <ide> } <ide><path>daemon/config_unix_test.go <ide> package daemon <ide> <ide> import ( <ide> "io/ioutil" <add> "runtime" <add> <ide> "testing" <add> <add> "github.com/docker/docker/pkg/testutil/assert" <add> "github.com/spf13/pflag" <ide> ) <ide> <ide> func TestDaemonConfigurationMerge(t *testing.T) { <ide> func TestDaemonConfigurationMerge(t *testing.T) { <ide> } <ide> } <ide> } <add> <add>func TestDaemonParseShmSize(t *testing.T) { <add> if runtime.GOOS == "solaris" { <add> t.Skip("ShmSize not supported on Solaris\n") <add> } <add> flags := pflag.NewFlagSet("test", pflag.ContinueOnError) <add> <add> config := &Config{} <add> config.InstallFlags(flags) <add> // By default `--default-shm-size=64M` <add> expectedValue := 64 * 1024 * 1024 <add> if config.ShmSize.Value() != int64(expectedValue) { <add> t.Fatalf("expected default shm size %d, got %d", expectedValue, config.ShmSize.Value()) <add> } <add> assert.NilError(t, flags.Set("default-shm-size", "128M")) <add> expectedValue = 128 * 1024 * 1024 <add> if config.ShmSize.Value() != int64(expectedValue) { <add> t.Fatalf("expected default shm size %d, got %d", expectedValue, config.ShmSize.Value()) <add> } <add>} <add> <add>func TestDaemonConfigurationMergeShmSize(t *testing.T) { <add> if runtime.GOOS == "solaris" { <add> t.Skip("ShmSize not supported on Solaris\n") <add> } <add> f, err := ioutil.TempFile("", "docker-config-") <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> configFile := f.Name() <add> <add> f.Write([]byte(` <add> { <add> "default-shm-size": "1g" <add> }`)) <add> <add> f.Close() <add> <add> c := &Config{} <add> cc, err := MergeDaemonConfigurations(c, nil, configFile) <add> if err != nil { <add> t.Fatal(err) <add> } <add> expectedValue := 1 * 1024 * 1024 * 1024 <add> if cc.ShmSize.Value() != int64(expectedValue) { <add> t.Fatalf("expected default shm size %d, got %d", expectedValue, cc.ShmSize.Value()) <add> } <add>} <ide><path>daemon/container_operations_unix.go <ide> func (daemon *Daemon) setupIpcDirs(c *container.Container) error { <ide> return err <ide> } <ide> <del> shmSize := container.DefaultSHMSize <add> shmSize := int64(daemon.configStore.ShmSize) <ide> if c.HostConfig.ShmSize != 0 { <ide> shmSize = c.HostConfig.ShmSize <ide> } <ide><path>daemon/daemon_unix.go <ide> func (daemon *Daemon) adaptContainerSettings(hostConfig *containertypes.HostConf <ide> hostConfig.MemorySwap = hostConfig.Memory * 2 <ide> } <ide> if hostConfig.ShmSize == 0 { <del> hostConfig.ShmSize = container.DefaultSHMSize <add> hostConfig.ShmSize = defaultShmSize <add> if daemon.configStore != nil { <add> hostConfig.ShmSize = int64(daemon.configStore.ShmSize) <add> } <ide> } <ide> var err error <ide> opts, err := daemon.generateSecurityOpt(hostConfig.IpcMode, hostConfig.PidMode, hostConfig.Privileged) <ide> func (daemon *Daemon) platformReload(config *Config) map[string]string { <ide> daemon.configStore.DefaultRuntime = config.DefaultRuntime <ide> } <ide> <add> if config.IsValueSet("default-shm-size") { <add> daemon.configStore.ShmSize = config.ShmSize <add> } <add> <ide> // Update attributes <ide> var runtimeList bytes.Buffer <ide> for name, rt := range daemon.configStore.Runtimes { <ide> func (daemon *Daemon) platformReload(config *Config) map[string]string { <ide> } <ide> <ide> return map[string]string{ <del> "runtimes": runtimeList.String(), <del> "default-runtime": daemon.configStore.DefaultRuntime, <add> "runtimes": runtimeList.String(), <add> "default-runtime": daemon.configStore.DefaultRuntime, <add> "default-shm-size": fmt.Sprintf("%d", daemon.configStore.ShmSize), <ide> } <ide> } <ide> <ide><path>docs/reference/commandline/dockerd.md <ide> Options: <ide> --default-gateway value Container default gateway IPv4 address <ide> --default-gateway-v6 value Container default gateway IPv6 address <ide> --default-runtime string Default OCI runtime for containers (default "runc") <add> --default-shm-size bytes Set the default shm size for containers (default 64 MiB) <ide> --default-ulimit value Default ulimits for containers (default []) <ide> --disable-legacy-registry Disable contacting legacy registries <ide> --dns value DNS server to use (default []) <ide> This is a full example of the allowed configuration options on Linux: <ide> "cluster-advertise": "", <ide> "max-concurrent-downloads": 3, <ide> "max-concurrent-uploads": 5, <add> "default-shm-size": "64M", <ide> "shutdown-timeout": 15, <ide> "debug": true, <ide> "hosts": [], <ide><path>integration-cli/docker_cli_daemon_test.go <ide> func (s *DockerDaemonSuite) TestRestartPolicyWithLiveRestore(c *check.C) { <ide> out, err = s.d.Cmd("stop", id) <ide> c.Assert(err, check.IsNil, check.Commentf("output: %s", out)) <ide> } <add> <add>func (s *DockerDaemonSuite) TestShmSize(c *check.C) { <add> testRequires(c, DaemonIsLinux) <add> <add> size := 67108864 * 2 <add> pattern := regexp.MustCompile(fmt.Sprintf("shm on /dev/shm type tmpfs(.*)size=%dk", size/1024)) <add> <add> s.d.StartWithBusybox(c, "--default-shm-size", fmt.Sprintf("%v", size)) <add> <add> name := "shm1" <add> out, err := s.d.Cmd("run", "--name", name, "busybox", "mount") <add> c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) <add> c.Assert(pattern.MatchString(out), checker.True) <add> out, err = s.d.Cmd("inspect", "--format", "{{.HostConfig.ShmSize}}", name) <add> c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) <add> c.Assert(strings.TrimSpace(out), check.Equals, fmt.Sprintf("%v", size)) <add>} <add> <add>func (s *DockerDaemonSuite) TestShmSizeReload(c *check.C) { <add> testRequires(c, DaemonIsLinux) <add> <add> configPath, err := ioutil.TempDir("", "test-daemon-shm-size-reload-config") <add> c.Assert(err, checker.IsNil, check.Commentf("could not create temp file for config reload")) <add> defer os.RemoveAll(configPath) // clean up <add> configFile := filepath.Join(configPath, "config.json") <add> <add> size := 67108864 * 2 <add> configData := []byte(fmt.Sprintf(`{"default-shm-size": "%dM"}`, size/1024/1024)) <add> c.Assert(ioutil.WriteFile(configFile, configData, 0666), checker.IsNil, check.Commentf("could not write temp file for config reload")) <add> pattern := regexp.MustCompile(fmt.Sprintf("shm on /dev/shm type tmpfs(.*)size=%dk", size/1024)) <add> <add> s.d.StartWithBusybox(c, "--config-file", configFile) <add> <add> name := "shm1" <add> out, err := s.d.Cmd("run", "--name", name, "busybox", "mount") <add> c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) <add> c.Assert(pattern.MatchString(out), checker.True) <add> out, err = s.d.Cmd("inspect", "--format", "{{.HostConfig.ShmSize}}", name) <add> c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) <add> c.Assert(strings.TrimSpace(out), check.Equals, fmt.Sprintf("%v", size)) <add> <add> size = 67108864 * 3 <add> configData = []byte(fmt.Sprintf(`{"default-shm-size": "%dM"}`, size/1024/1024)) <add> c.Assert(ioutil.WriteFile(configFile, configData, 0666), checker.IsNil, check.Commentf("could not write temp file for config reload")) <add> pattern = regexp.MustCompile(fmt.Sprintf("shm on /dev/shm type tmpfs(.*)size=%dk", size/1024)) <add> <add> err = s.d.ReloadConfig() <add> c.Assert(err, checker.IsNil, check.Commentf("error reloading daemon config")) <add> <add> name = "shm2" <add> out, err = s.d.Cmd("run", "--name", name, "busybox", "mount") <add> c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) <add> c.Assert(pattern.MatchString(out), checker.True) <add> out, err = s.d.Cmd("inspect", "--format", "{{.HostConfig.ShmSize}}", name) <add> c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) <add> c.Assert(strings.TrimSpace(out), check.Equals, fmt.Sprintf("%v", size)) <add>} <ide><path>integration-cli/docker_cli_events_unix_test.go <ide> func (s *DockerDaemonSuite) TestDaemonEvents(c *check.C) { <ide> out, err = s.d.Cmd("events", "--since=0", "--until", daemonUnixTime(c)) <ide> c.Assert(err, checker.IsNil) <ide> <del> c.Assert(out, checker.Contains, fmt.Sprintf("daemon reload %s (cluster-advertise=, cluster-store=, cluster-store-opts={}, debug=true, default-runtime=runc, insecure-registries=[], labels=[\"bar=foo\"], live-restore=false, max-concurrent-downloads=1, max-concurrent-uploads=5, name=%s, registry-mirrors=[], runtimes=runc:{docker-runc []}, shutdown-timeout=10)", daemonID, daemonName)) <add> c.Assert(out, checker.Contains, fmt.Sprintf("daemon reload %s (cluster-advertise=, cluster-store=, cluster-store-opts={}, debug=true, default-runtime=runc, default-shm-size=67108864, insecure-registries=[], labels=[\"bar=foo\"], live-restore=false, max-concurrent-downloads=1, max-concurrent-uploads=5, name=%s, runtimes=runc:{docker-runc []}, shutdown-timeout=10)", daemonID, daemonName)) <ide> } <ide> <ide> func (s *DockerDaemonSuite) TestDaemonEventsWithFilters(c *check.C) { <ide><path>man/dockerd.8.md <ide> dockerd - Enable daemon mode <ide> [**--default-gateway**[=*DEFAULT-GATEWAY*]] <ide> [**--default-gateway-v6**[=*DEFAULT-GATEWAY-V6*]] <ide> [**--default-runtime**[=*runc*]] <add>[**--default-shm-size**[=*64MiB*]] <ide> [**--default-ulimit**[=*[]*]] <ide> [**--disable-legacy-registry**] <ide> [**--dns**[=*[]*]] <ide> $ sudo dockerd --add-runtime runc=runc --add-runtime custom=/usr/local/bin/my-ru <ide> **--default-runtime**="runc" <ide> Set default runtime if there're more than one specified by `--add-runtime`. <ide> <add>**--default-shm-size**=*64MiB* <add> Set the daemon-wide default shm size for containers. Default is `64MiB`. <add> <ide> **--default-ulimit**=[] <ide> Default ulimits for containers. <ide> <ide><path>opts/opts.go <ide> import ( <ide> "strings" <ide> <ide> "github.com/docker/docker/api/types/filters" <add> units "github.com/docker/go-units" <ide> ) <ide> <ide> var ( <ide> func ValidateLink(val string) (string, error) { <ide> _, _, err := ParseLink(val) <ide> return val, err <ide> } <add> <add>// MemBytes is a type for human readable memory bytes (like 128M, 2g, etc) <add>type MemBytes int64 <add> <add>// String returns the string format of the human readable memory bytes <add>func (m *MemBytes) String() string { <add> return units.BytesSize(float64(m.Value())) <add>} <add> <add>// Set sets the value of the MemBytes by passing a string <add>func (m *MemBytes) Set(value string) error { <add> val, err := units.RAMInBytes(value) <add> *m = MemBytes(val) <add> return err <add>} <add> <add>// Type returns the type <add>func (m *MemBytes) Type() string { <add> return "bytes" <add>} <add> <add>// Value returns the value in int64 <add>func (m *MemBytes) Value() int64 { <add> return int64(*m) <add>} <add> <add>// UnmarshalJSON is the customized unmarshaler for MemBytes <add>func (m *MemBytes) UnmarshalJSON(s []byte) error { <add> if len(s) <= 2 || s[0] != '"' || s[len(s)-1] != '"' { <add> return fmt.Errorf("invalid size: %q", s) <add> } <add> val, err := units.RAMInBytes(string(s[1 : len(s)-1])) <add> *m = MemBytes(val) <add> return err <add>}
12
PHP
PHP
apply fixes from styleci
76faca7a1118ebdf475e94f11e2bc23f57225e8c
<ide><path>src/Illuminate/Database/Concerns/BuildsQueries.php <ide> protected function paginateUsingCursor($perPage, $columns = ['*'], $cursorName = <ide> $cursor->parameter($previousColumn) <ide> ); <ide> <del> $unionBuilders->each(function ($unionBuilder) use($previousColumn, $cursor) { <add> $unionBuilders->each(function ($unionBuilder) use ($previousColumn, $cursor) { <ide> $unionBuilder->where( <ide> $this->getOriginalColumnNameForCursorPagination($this, $previousColumn), <ide> '=', <ide> protected function paginateUsingCursor($perPage, $columns = ['*'], $cursorName = <ide> }); <ide> } <ide> <del> $unionBuilders->each(function ($unionBuilder) use ($column, $direction, $cursor, $i, $orders, $addCursorConditions){ <add> $unionBuilders->each(function ($unionBuilder) use ($column, $direction, $cursor, $i, $orders, $addCursorConditions) { <ide> $unionBuilder->where(function ($unionBuilder) use ($column, $direction, $cursor, $i, $orders, $addCursorConditions) { <ide> $unionBuilder->where( <ide> $this->getOriginalColumnNameForCursorPagination($this, $column), <ide><path>tests/Database/DatabaseQueryBuilderTest.php <ide> public function testCursorPaginateWithUnionWheres() <ide> $builder->toSql()); <ide> $this->assertEquals([$ts], $builder->bindings['where']); <ide> $this->assertEquals([$ts], $builder->bindings['union']); <add> <ide> return $results; <ide> }); <ide> <ide> public function testCursorPaginateWithUnionWheresWithRawOrderExpression() <ide> $builder->toSql()); <ide> $this->assertEquals([true, $ts], $builder->bindings['where']); <ide> $this->assertEquals([true, $ts], $builder->bindings['union']); <add> <ide> return $results; <ide> }); <ide> <ide> public function testCursorPaginateWithUnionWheresReverseOrder() <ide> $builder->toSql()); <ide> $this->assertEquals([$ts], $builder->bindings['where']); <ide> $this->assertEquals([$ts], $builder->bindings['union']); <add> <ide> return $results; <ide> }); <ide> <ide> public function testCursorPaginateWithUnionWheresReverseOrder() <ide> ]), $result); <ide> } <ide> <del> public function testCursorPaginateWithUnionWheresMultipleOrders() <del> { <add> public function testCursorPaginateWithUnionWheresMultipleOrders() <add> { <ide> $ts = now()->toDateTimeString(); <ide> <ide> $perPage = 16; <ide> public function testCursorPaginateWithUnionWheresMultipleOrders() <ide> $builder->toSql()); <ide> $this->assertEquals([$ts, $ts, 1], $builder->bindings['where']); <ide> $this->assertEquals([$ts, $ts, 1], $builder->bindings['union']); <add> <ide> return $results; <ide> }); <ide>
2
Python
Python
improve documentation for tasks run command
03fc51f0f982321b4d3da7341f2035953cbb9be0
<ide><path>airflow/cli/commands/task_command.py <ide> def _capture_task_logs(ti): <ide> <ide> @cli_utils.action_logging <ide> def task_run(args, dag=None): <del> """Runs a single task instance""" <add> """Run a single task instance. <add> <add> Note that there must be at least one DagRun for this to start, <add> i.e. it must have been scheduled and/or triggered previously. <add> Alternatively, if you just need to run it for testing then use <add> "airflow tasks test ..." command instead. <add> """ <ide> # Load custom airflow config <ide> <ide> if args.local and args.raw:
1
Javascript
Javascript
add test for stats false
f6c8039c5a993f54a7864f4c918e0d70db104290
<ide><path>test/Defaults.unittest.js <ide> describe("Defaults", () => { <ide> + "uniqueName": "@@@Hello World!", <ide> `) <ide> ); <add> <ide> test("stats true", { stats: true }, e => <ide> e.toMatchInlineSnapshot(` <ide> - Expected <ide> describe("Defaults", () => { <ide> + "stats": Object { <ide> + "preset": "normal", <ide> + }, <del> `) <add> `) <add> ); <add> <add> test("stats false", { stats: false }, e => <add> e.toMatchInlineSnapshot(` <add> - Expected <add> + Received <add> <add> <add> - "stats": Object {}, <add> + "stats": Object { <add> + "preset": "none", <add> + }, <add> `) <ide> ); <ide> });
1
Python
Python
add option to choose t5 model size.
ff80b731573d07a6633af9dac1e51f684dd6bc07
<ide><path>examples/summarization/t5/evaluate_cnn.py <ide> def chunks(lst, n): <ide> yield lst[i : i + n] <ide> <ide> <del>def generate_summaries(lns, output_file_path, batch_size, device): <add>def generate_summaries(lns, output_file_path, model_size, batch_size, device): <ide> output_file = Path(output_file_path).open("w") <ide> <del> model = T5ForConditionalGeneration.from_pretrained("t5-large") <add> model = T5ForConditionalGeneration.from_pretrained(model_size) <ide> model.to(device) <ide> <del> tokenizer = T5Tokenizer.from_pretrained("t5-large") <add> tokenizer = T5Tokenizer.from_pretrained(model_size) <ide> <ide> # update config with summarization specific params <ide> task_specific_params = model.config.task_specific_params <ide> def calculate_rouge(output_lns, reference_lns, score_path): <ide> <ide> def run_generate(): <ide> parser = argparse.ArgumentParser() <add> parser.add_argument( <add> "model_size", <add> type=str, <add> help="T5 model size, either 't5-small', 't5-base' or 't5-large'. Defaults to base.", <add> default="t5-base", <add> ) <ide> parser.add_argument( <ide> "input_path", type=str, help="like cnn_dm/test_articles_input.txt", <ide> ) <ide> def run_generate(): <ide> <ide> source_lns = [x.rstrip() for x in open(args.input_path).readlines()] <ide> <del> generate_summaries(source_lns, args.output_path, args.batch_size, args.device) <add> generate_summaries(source_lns, args.output_path, args.model_size, args.batch_size, args.device) <ide> <ide> output_lns = [x.rstrip() for x in open(args.output_path).readlines()] <ide> reference_lns = [x.rstrip() for x in open(args.reference_path).readlines()] <ide><path>examples/summarization/t5/test_t5_examples.py <ide> def test_t5_cli(self): <ide> tmp = Path(tempfile.gettempdir()) / "utest_generations.hypo" <ide> with tmp.open("w") as f: <ide> f.write("\n".join(articles)) <del> testargs = ["evaluate_cnn.py", str(tmp), "output.txt", str(tmp), "score.txt"] <add> testargs = ["evaluate_cnn.py", "t5-small", str(tmp), "output.txt", str(tmp), "score.txt"] <ide> with patch.object(sys, "argv", testargs): <ide> run_generate() <ide> self.assertTrue(Path("output.txt").exists())
2
Ruby
Ruby
fix incorrect word
ea6a2b7c111cd3794b2ee41bc60a4071631d01aa
<ide><path>activesupport/lib/active_support/log_subscriber/test_helper.rb <ide> class LogSubscriber <ide> # up the queue, subscriptions and turning colors in logs off. <ide> # <ide> # The messages are available in the @logger instance, which is a logger with limited <del> # powers (it actually do not send anything to your output), and you can collect them <add> # powers (it actually does not send anything to your output), and you can collect them <ide> # doing @logger.logged(level), where level is the level used in logging, like info, <ide> # debug, warn and so on. <ide> #
1
Python
Python
pass concurrency argument to workers
f25052cb9900393eb1cf7aacd2acbc03629636b5
<ide><path>airflow/bin/cli.py <ide> def worker(args): <ide> 'optimization': 'fair', <ide> 'O': 'fair', <ide> 'queues': args.queues, <add> 'concurrency': args.concurrency, <ide> } <ide> worker.run(**options) <ide> sp.kill() <ide> def get_parser(): <ide> "-q", "--queues", <ide> help="Comma delimited list of queues to serve", <ide> default=conf.get('celery', 'DEFAULT_QUEUE')) <add> parser_worker.add_argument( <add> "-c", "--concurrency", <add> type=int, <add> help="The number of worker processes", <add> default=conf.get('celery', 'celeryd_concurrency')) <ide> parser_worker.set_defaults(func=worker) <ide> <ide> ht = "Serve logs generate by worker"
1
Ruby
Ruby
use dir[] for globbing
8976a960df0a4768be3a6df77874a151535e14f7
<ide><path>Library/Contributions/cmd/brew-test-bot.rb <ide> def run <ide> raise "Missing Jenkins variables!" unless jenkins and job and id <ide> <ide> ARGV << '--verbose' <del> copied = system "cp #{jenkins}/jobs/\"#{job}\"/configurations/axis-version/*/builds/#{id}/archive/*.bottle*.* ." <del> exit unless copied <add> cp_args = Dir["#{jenkins}/jobs/#{job}/configurations/axis-version/*/builds/#{id}/archive/*.bottle*.*"] + ["."] <add> exit unless system "cp", *cp_args <ide> <ide> ENV["GIT_COMMITTER_NAME"] = "BrewTestBot" <ide> ENV["GIT_COMMITTER_EMAIL"] = "brew-test-bot@googlegroups.com" <ide> def run <ide> <ide> ENV["GIT_AUTHOR_NAME"] = ENV["GIT_COMMITTER_NAME"] <ide> ENV["GIT_AUTHOR_EMAIL"] = ENV["GIT_COMMITTER_EMAIL"] <del> safe_system "brew bottle --merge --write *.bottle*.rb" <add> safe_system "brew", "bottle", "--merge", "--write", *Dir["*.bottle*.rb"] <ide> <ide> remote = "git@github.com:BrewTestBot/homebrew.git" <ide> tag = pr ? "pr-#{pr}" : "testing-#{number}" <ide> safe_system "git", "push", "--force", remote, "master:master", ":refs/tags/#{tag}" <ide> <ide> path = "/home/frs/project/m/ma/machomebrew/Bottles/" <ide> url = "BrewTestBot,machomebrew@frs.sourceforge.net:#{path}" <del> options = "--partial --progress --human-readable --compress" <del> safe_system "rsync #{options} *.bottle*.tar.gz #{url}" <add> <add> rsync_args = %w[--partial --progress --human-readable --compress] <add> rsync_args += Dir["*.bottle*.tar.gz"] + [url] <add> <add> safe_system "rsync", *rsync_args <ide> safe_system "git", "tag", "--force", tag <ide> safe_system "git", "push", "--force", remote, "refs/tags/#{tag}" <ide> exit
1
PHP
PHP
use stringtemplate constructor in test cases
ff9de4e6572d945816f97b41b00623ef7adddbc3
<ide><path>tests/TestCase/View/Input/CheckboxTest.php <ide> public function setUp() { <ide> $templates = [ <ide> 'checkbox' => '<input type="checkbox" name="{{name}}" value="{{value}}"{{attrs}}>', <ide> ]; <del> $this->templates = new StringTemplate(); <del> $this->templates->add($templates); <add> $this->templates = new StringTemplate($templates); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/View/Input/MultiCheckboxTest.php <ide> public function setUp() { <ide> 'label' => '<label{{attrs}}>{{text}}</label>', <ide> 'checkboxContainer' => '<div class="checkbox">{{input}}{{label}}</div>', <ide> ]; <del> $this->templates = new StringTemplate(); <del> $this->templates->add($templates); <add> $this->templates = new StringTemplate($templates); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/View/Input/RadioTest.php <ide> public function setUp() { <ide> 'label' => '<label{{attrs}}>{{text}}</label>', <ide> 'radioContainer' => '{{input}}{{label}}', <ide> ]; <del> $this->templates = new StringTemplate(); <del> $this->templates->add($templates); <add> $this->templates = new StringTemplate($templates); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/View/Input/SelectBoxTest.php <ide> public function setUp() { <ide> 'option' => '<option value="{{value}}"{{attrs}}>{{text}}</option>', <ide> 'optgroup' => '<optgroup label="{{label}}"{{attrs}}>{{content}}</optgroup>', <ide> ]; <del> $this->templates = new StringTemplate(); <del> $this->templates->add($templates); <add> $this->templates = new StringTemplate($templates); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/View/Input/TextTest.php <ide> public function setUp() { <ide> $templates = [ <ide> 'input' => '<input type="{{type}}" name="{{name}}"{{attrs}}>', <ide> ]; <del> $this->templates = new StringTemplate(); <del> $this->templates->add($templates); <add> $this->templates = new StringTemplate($templates); <ide> } <ide> <ide> /**
5
Ruby
Ruby
use regular ruby rather than clever ruby
a704fd4ea9b8ac86f57d357bd8e2a555b69edca9
<ide><path>actionpack/lib/action_dispatch/routing/mapper.rb <ide> def normalize_path(path) <ide> # controllers with default routes like :controller/:action/:id(.:format), e.g: <ide> # GET /admin/products/show/1 <ide> # => { :controller => 'admin/products', :action => 'show', :id => '1' } <del> @options.reverse_merge!(:controller => /.+?/) <add> @options[:controller] ||= /.+?/ <ide> end <ide> <ide> # Add a constraint for wildcard route to make it non-greedy and match the <ide> # optional format part of the route by default <ide> if path.match(WILDCARD_PATH) && @options[:format] != false <del> @options.reverse_merge!(:"#{$1}" => /.+?/) <add> @options[$1.to_sym] ||= /.+?/ <ide> end <ide> <ide> if @options[:format] == false <ide> module Base <ide> # because this means it will be matched first. As this is the most popular route <ide> # of most Rails applications, this is beneficial. <ide> def root(options = {}) <del> match '/', options.reverse_merge(:as => :root) <add> match '/', { :as => :root }.merge(options) <ide> end <ide> <ide> # Matches a url pattern to one or more routes. Any symbols in a pattern
1
PHP
PHP
fix failing test with controller task listall
cbf5328b33a58fc79ca987ff5be329a5ac35c7ba
<ide><path>lib/Cake/Test/Case/Console/Command/Task/ControllerTaskTest.php <ide> public function testListAll() { <ide> <ide> $this->Task->connection = 'test'; <ide> $this->Task->interactive = true; <del> $this->Task->expects($this->at(1))->method('out')->with('1. BakeArticles'); <del> $this->Task->expects($this->at(2))->method('out')->with('2. BakeArticlesBakeTags'); <del> $this->Task->expects($this->at(3))->method('out')->with('3. BakeComments'); <del> $this->Task->expects($this->at(4))->method('out')->with('4. BakeTags'); <add> $this->Task->expects($this->at(2))->method('out')->with(' 1. BakeArticles'); <add> $this->Task->expects($this->at(3))->method('out')->with(' 2. BakeArticlesBakeTags'); <add> $this->Task->expects($this->at(4))->method('out')->with(' 3. BakeComments'); <add> $this->Task->expects($this->at(5))->method('out')->with(' 4. BakeTags'); <ide> <ide> $expected = array('BakeArticles', 'BakeArticlesBakeTags', 'BakeComments', 'BakeTags'); <ide> $result = $this->Task->listAll('test');
1
Text
Text
add exception_handler docs to exception docs
bae0ef6b5dcb0abf2be865340e5476aeab5ce137
<ide><path>docs/api-guide/exceptions.md <ide> Might receive an error response indicating that the `DELETE` method is not allow <ide> HTTP/1.1 405 Method Not Allowed <ide> Content-Type: application/json; charset=utf-8 <ide> Content-Length: 42 <del> <add> <ide> {"detail": "Method 'DELETE' not allowed."} <ide> <add>## Custom exception handling <add> <add>To implement custom exception handling (e.g. to handle additional exception classes or to override the error response format), create an exception handler function with the following signature: <add> <add> exception_handler(exc) <add> <add>* `exc`: The exception. <add> <add>If the function returns `None`, a 500 error will be raised. <add> <add>The exception handler is set globally, using the `EXCEPTION_HANDLER` setting. For example: <add> <add> 'EXCEPTION_HANDLER': 'project.app.module.function' <add> <add>If not specified, this setting defaults to the exception handler described above: <add> <add> 'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler' <add> <ide> --- <ide> <ide> # API Reference
1
Text
Text
fix indentation [ci skip]
566a056115d207fe2c83e7131bc196558331958d
<ide><path>guides/source/3_2_release_notes.md <ide> Action Pack <ide> ```ruby <ide> @items.each do |item| <ide> content_tag_for(:li, item) do <del> Title: <%= item.title %> <add> Title: <%= item.title %> <ide> end <ide> end <ide> ``` <ide><path>guides/source/active_job_basics.md <ide> class GuestsCleanupJob < ApplicationJob <ide> queue_as :default <ide> <ide> rescue_from(ActiveRecord::RecordNotFound) do |exception| <del> # Do something with the exception <add> # Do something with the exception <ide> end <ide> <ide> def perform <ide><path>guides/source/active_support_core_extensions.md <ide> Extensions to `BigDecimal` <ide> The method `to_s` provides a default specifier of "F". This means that a simple call to `to_s` will result in floating point representation instead of engineering notation: <ide> <ide> ```ruby <del>BigDecimal.new(5.00, 6).to_s # => "5.0" <add>BigDecimal.new(5.00, 6).to_s # => "5.0" <ide> ``` <ide> <ide> and that symbol specifiers are also supported: <ide> Durations can be added to and subtracted from time objects: <ide> now = Time.current <ide> # => Mon, 09 Aug 2010 23:20:05 UTC +00:00 <ide> now + 1.year <del># => Tue, 09 Aug 2011 23:21:11 UTC +00:00 <add># => Tue, 09 Aug 2011 23:21:11 UTC +00:00 <ide> now - 1.week <ide> # => Mon, 02 Aug 2010 23:21:11 UTC +00:00 <ide> ``` <ide><path>guides/source/association_basics.md <ide> By default, associations look for objects only within the current module's scope <ide> module MyApplication <ide> module Business <ide> class Supplier < ApplicationRecord <del> has_one :account <add> has_one :account <ide> end <ide> <ide> class Account < ApplicationRecord <del> belongs_to :supplier <add> belongs_to :supplier <ide> end <ide> end <ide> end <ide> This will work fine, because both the `Supplier` and the `Account` class are def <ide> module MyApplication <ide> module Business <ide> class Supplier < ApplicationRecord <del> has_one :account <add> has_one :account <ide> end <ide> end <ide> <ide> module Billing <ide> class Account < ApplicationRecord <del> belongs_to :supplier <add> belongs_to :supplier <ide> end <ide> end <ide> end <ide> To associate a model with a model in a different namespace, you must specify the <ide> module MyApplication <ide> module Business <ide> class Supplier < ApplicationRecord <del> has_one :account, <add> has_one :account, <ide> class_name: "MyApplication::Billing::Account" <ide> end <ide> end <ide> <ide> module Billing <ide> class Account < ApplicationRecord <del> belongs_to :supplier, <add> belongs_to :supplier, <ide> class_name: "MyApplication::Business::Supplier" <ide> end <ide> end <ide><path>guides/source/testing.md <ide> each of the seven default actions, you can use the following command: <ide> $ bin/rails generate test_unit:scaffold article <ide> ... <ide> invoke test_unit <del>create test/controllers/articles_controller_test.rb <add>create test/controllers/articles_controller_test.rb <ide> ... <ide> ``` <ide>
5
Text
Text
use svgs instead of pngs
5a8306352c52c080a2c88c0cd853fae4fb4491fb
<ide><path>docs/build-instructions/build-status.md <ide> | Incompatible Packages | [![macOS Build Status](https://travis-ci.org/atom/incompatible-packages.svg?branch=master)](https://travis-ci.org/atom/incompatible-packages) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/neet595s038x7w70/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/incompatible-packages/branch/master) | [![Dependency Status](https://david-dm.org/atom/incompatible-packages.svg)](https://david-dm.org/atom/incompatible-packages) | <ide> | Keybinding Resolver | [![macOS Build Status](https://travis-ci.org/atom/keybinding-resolver.svg?branch=master)](https://travis-ci.org/atom/keybinding-resolver) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/9jf31itx01hnn4nh/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/keybinding-resolver/branch/master) | [![Dependency Status](https://david-dm.org/atom/keybinding-resolver.svg)](https://david-dm.org/atom/keybinding-resolver) | <ide> | Line Ending Selector | [![macOS Build Status](https://travis-ci.org/atom/line-ending-selector.svg?branch=master)](https://travis-ci.org/atom/line-ending-selector) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/b3743n9ojomlpn1g/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/line-ending-selector/branch/master) | [![Dependency Status](https://david-dm.org/atom/line-ending-selector.svg)](https://david-dm.org/atom/line-ending-selector) | <del>| Link | [![macOS Build Status](https://travis-ci.org/atom/link.png?branch=master)](https://travis-ci.org/atom/link) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/1d3cb8ktd48k9vnl/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/link/branch/master) | [![Dependency Status](https://david-dm.org/atom/link.svg)](https://david-dm.org/atom/link) | <add>| Link | [![macOS Build Status](https://travis-ci.org/atom/link.svg?branch=master)](https://travis-ci.org/atom/link) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/1d3cb8ktd48k9vnl/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/link/branch/master) | [![Dependency Status](https://david-dm.org/atom/link.svg)](https://david-dm.org/atom/link) | <ide> | Markdown Preview | [![macOS Build Status](https://travis-ci.org/atom/markdown-preview.svg?branch=master)](https://travis-ci.org/atom/markdown-preview) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/bvh0evhh4v6w9b29/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/markdown-preview/branch/master) | [![Dependency Status](https://david-dm.org/atom/markdown-preview.svg)](https://david-dm.org/atom/markdown-preview) | <ide> | Metrics | [![macOS Build Status](https://travis-ci.org/atom/metrics.svg?branch=master)](https://travis-ci.org/atom/metrics) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/b5doi205xl3iex04/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/metrics/branch/master) | [![Dependency Status](https://david-dm.org/atom/metrics.svg)](https://david-dm.org/atom/metrics) | <ide> | Notifications | [![macOS Build Status](https://travis-ci.org/atom/notifications.svg?branch=master)](https://travis-ci.org/atom/notifications) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/ps3p8tj2okw57x0e/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/notifications/branch/master) | [![Dependency Status](https://david-dm.org/atom/notifications.svg)](https://david-dm.org/atom/notifications) | <ide> <ide> | Library | macOS | Windows | Dependencies | <ide> |---------|------|---------|--------------| <del>| Clear Cut | [![macOS Build Status](https://travis-ci.org/atom/clear-cut.png?branch=master)](https://travis-ci.org/atom/clear-cut) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/civ54x89l06286m9/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/clear-cut/branch/master) | [![Dependency Status](https://david-dm.org/atom/clear-cut.svg)](https://david-dm.org/atom/clear-cut) | <add>| Clear Cut | [![macOS Build Status](https://travis-ci.org/atom/clear-cut.svg?branch=master)](https://travis-ci.org/atom/clear-cut) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/civ54x89l06286m9/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/clear-cut/branch/master) | [![Dependency Status](https://david-dm.org/atom/clear-cut.svg)](https://david-dm.org/atom/clear-cut) | <ide> | Event Kit | [![macOS Build Status](https://travis-ci.org/atom/event-kit.svg?branch=master)](https://travis-ci.org/atom/event-kit) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/lb32q70204lpmlxo/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/event-kit/branch/master) | [![Dependency Status](https://david-dm.org/atom/event-kit.svg)](https://david-dm.org/atom/event-kit) | <ide> | Fs Plus | [![macOS Build Status](https://travis-ci.org/atom/fs-plus.svg?branch=master)](https://travis-ci.org/atom/fs-plus) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/gf2tleqp0hdek3o3/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/fs-plus/branch/master) | [![Dependency Status](https://david-dm.org/atom/fs-plus.svg)](https://david-dm.org/atom/fs-plus) | <ide> | Grim | [![macOS Build Status](https://travis-ci.org/atom/grim.svg)](https://travis-ci.org/atom/grim) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/i4m37pol77vygrvb/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/grim/branch/master) | [![Dependency Status](https://david-dm.org/atom/grim.svg)](https://david-dm.org/atom/grim) | <ide> | ShellScript | [![macOS Build Status](https://travis-ci.org/atom/language-shellscript.svg?branch=master)](https://travis-ci.org/atom/language-shellscript) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/p4um3lowgrg8y0ty/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-shellscript/branch/master) | <ide> | SQL | [![macOS Build Status](https://travis-ci.org/atom/language-sql.svg?branch=master)](https://travis-ci.org/atom/language-sql) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/ji31ouk5ehs4jdu1/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-sql/branch/master) | <ide> | TODO | [![macOS Build Status](https://travis-ci.org/atom/language-todo.svg?branch=master)](https://travis-ci.org/atom/language-todo) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/gcgb9m7h146lv6qp/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-todo/branch/master) | <del>| TOML | [![macOS Build Status](https://travis-ci.org/atom/language-toml.png?branch=master)](https://travis-ci.org/atom/language-toml) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/kohao3fjyk6xv0sc/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-toml/branch/master) | <del>| XML | [![macOS Build Status](https://travis-ci.org/atom/language-xml.png?branch=master)](https://travis-ci.org/atom/language-xml) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/m5f6rn74a6h3q5uq/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-xml/branch/master) | <add>| TOML | [![macOS Build Status](https://travis-ci.org/atom/language-toml.svg?branch=master)](https://travis-ci.org/atom/language-toml) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/kohao3fjyk6xv0sc/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-toml/branch/master) | <add>| XML | [![macOS Build Status](https://travis-ci.org/atom/language-xml.svg?branch=master)](https://travis-ci.org/atom/language-xml) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/m5f6rn74a6h3q5uq/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-xml/branch/master) | <ide> | YAML | [![macOS Build Status](https://travis-ci.org/atom/language-yaml.svg?branch=master)](https://travis-ci.org/atom/language-yaml) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/eaa4ql7kipgphc2n/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-yaml/branch/master) |
1
Javascript
Javascript
add script key for cache
cb4eaaab6d5477c2ef54b43624820c526f57e725
<ide><path>examples/with-google-tag-manager/pages/_app.js <ide> function MyApp({ Component, pageProps }) { <ide> <> <ide> {/* Google Tag Manager - Global base code */} <ide> <Script <add> id="gtag-base" <ide> strategy="afterInteractive" <ide> dangerouslySetInnerHTML={{ <ide> __html: `
1
Javascript
Javascript
remove protection from interview prep
c6eb40ceeffcbfa1ff92d09a1d78e08cfc92603d
<ide><path>client/src/templates/Challenges/rechallenge/transformers.js <ide> Babel.registerPlugin( <ide> protect(testProtectTimeout, testLoopProtectCB, loopsPerTimeoutCheck) <ide> ); <ide> <add>const babelOptionsJSBase = { <add> presets: [presetEnv] <add>}; <add> <ide> const babelOptionsJSX = { <ide> plugins: ['loopProtection'], <ide> presets: [presetEnv, presetReact] <ide> }; <ide> <ide> const babelOptionsJS = { <del> plugins: ['testLoopProtection'], <del> presets: [presetEnv] <add> ...babelOptionsJSBase, <add> plugins: ['testLoopProtection'] <ide> }; <ide> <ide> const babelOptionsJSPreview = { <del> ...babelOptionsJS, <add> ...babelOptionsJSBase, <ide> plugins: ['loopProtection'] <ide> }; <ide> <ide> function tryTransform(wrap = identity) { <ide> }; <ide> } <ide> <del>const babelTransformer = (preview = false) => <del> cond([ <add>const babelTransformer = ({ preview = false, protect = true }) => { <add> let options = babelOptionsJSBase; <add> // we always protect the preview, since it evaluates as the user types and <add> // they may briefly have infinite looping code accidentally <add> if (protect) { <add> options = preview ? babelOptionsJSPreview : babelOptionsJS; <add> } else { <add> options = preview ? babelOptionsJSPreview : options; <add> } <add> return cond([ <ide> [ <ide> testJS, <ide> flow( <ide> partial( <ide> vinyl.transformHeadTailAndContents, <del> tryTransform( <del> babelTransformCode(preview ? babelOptionsJSPreview : babelOptionsJS) <del> ) <add> tryTransform(babelTransformCode(options)) <ide> ) <ide> ) <ide> ], <ide> const babelTransformer = (preview = false) => <ide> ], <ide> [stubTrue, identity] <ide> ]); <add>}; <ide> <ide> const sassWorker = createWorker(sassCompile); <ide> async function transformSASS(element) { <ide> export const htmlTransformer = cond([ <ide> [stubTrue, identity] <ide> ]); <ide> <del>export const transformers = [ <del> replaceNBSP, <del> babelTransformer(), <del> composeHTML, <del> htmlTransformer <del>]; <del> <del>export const transformersPreview = [ <add>export const getTransformers = config => [ <ide> replaceNBSP, <del> babelTransformer(true), <add> babelTransformer(config ? config : {}), <ide> composeHTML, <ide> htmlTransformer <ide> ]; <ide><path>client/src/templates/Challenges/redux/execute-challenge-saga.js <ide> import escape from 'lodash/escape'; <ide> <ide> import { <ide> challengeDataSelector, <add> challengeMetaSelector, <ide> challengeTestsSelector, <ide> initConsole, <ide> updateConsole, <ide> import { <ide> getTestRunner, <ide> challengeHasPreview, <ide> updatePreview, <del> isJavaScriptChallenge <add> isJavaScriptChallenge, <add> isLoopProtected <ide> } from '../utils/build'; <ide> <ide> // How long before bailing out of a preview. <ide> export function* executeChallengeSaga() { <ide> const proxyLogger = args => consoleProxy.put(args); <ide> <ide> const challengeData = yield select(challengeDataSelector); <del> const buildData = yield buildChallengeData(challengeData); <add> const challengeMeta = yield select(challengeMetaSelector); <add> const protect = isLoopProtected(challengeMeta); <add> const buildData = yield buildChallengeData(challengeData, { <add> preview: false, <add> protect <add> }); <ide> const document = yield getContext('document'); <ide> const testRunner = yield call( <ide> getTestRunner, <ide> function* takeEveryConsole(channel) { <ide> }); <ide> } <ide> <del>function* buildChallengeData(challengeData, preview) { <add>function* buildChallengeData(challengeData, options) { <ide> try { <del> return yield call(buildChallenge, challengeData, preview); <add> return yield call(buildChallenge, challengeData, options); <ide> } catch (e) { <ide> yield put(disableBuildOnError()); <ide> throw e; <ide> function* previewChallengeSaga() { <ide> yield fork(takeEveryConsole, logProxy); <ide> <ide> const challengeData = yield select(challengeDataSelector); <add> <ide> if (canBuildChallenge(challengeData)) { <del> const buildData = yield buildChallengeData(challengeData, true); <add> const challengeMeta = yield select(challengeMetaSelector); <add> const protect = isLoopProtected(challengeMeta); <add> const buildData = yield buildChallengeData(challengeData, { <add> preview: true, <add> protect <add> }); <ide> // evaluate the user code in the preview frame or in the worker <ide> if (challengeHasPreview(challengeData)) { <ide> const document = yield getContext('document'); <ide><path>client/src/templates/Challenges/redux/index.js <ide> const initialState = { <ide> canFocusEditor: true, <ide> challengeFiles: {}, <ide> challengeMeta: { <add> superBlock: '', <ide> block: '', <ide> id: '', <ide> nextChallengePath: '/', <ide><path>client/src/templates/Challenges/utils/build.js <del>import { transformers, transformersPreview } from '../rechallenge/transformers'; <add>import { getTransformers } from '../rechallenge/transformers'; <ide> import { cssToHtml, jsToHtml, concatHtml } from '../rechallenge/builders.js'; <ide> import { challengeTypes } from '../../../../utils/challengeTypes'; <ide> import createWorker from './worker-executor'; <ide> export function canBuildChallenge(challengeData) { <ide> return buildFunctions.hasOwnProperty(challengeType); <ide> } <ide> <del>export async function buildChallenge(challengeData, preview = false) { <add>export async function buildChallenge(challengeData, options) { <ide> const { challengeType } = challengeData; <ide> let build = buildFunctions[challengeType]; <ide> if (build) { <del> return build(challengeData, preview); <add> return build(challengeData, options); <ide> } <ide> throw new Error(`Cannot build challenge of type ${challengeType}`); <ide> } <ide> export function buildDOMChallenge({ files, required = [], template = '' }) { <ide> const finalRequires = [...globalRequires, ...required, ...frameRunner]; <ide> const loadEnzyme = Object.keys(files).some(key => files[key].ext === 'jsx'); <ide> const toHtml = [jsToHtml, cssToHtml]; <del> const pipeLine = composeFunctions(...transformers, ...toHtml); <add> const pipeLine = composeFunctions(...getTransformers(), ...toHtml); <ide> const finalFiles = Object.keys(files) <ide> .map(key => files[key]) <ide> .map(pipeLine); <ide> export function buildDOMChallenge({ files, required = [], template = '' }) { <ide> })); <ide> } <ide> <del>export function buildJSChallenge({ files }, preview = false) { <del> const pipeLine = preview <del> ? composeFunctions(...transformersPreview) <del> : composeFunctions(...transformers); <add>export function buildJSChallenge({ files }, options) { <add> const pipeLine = composeFunctions(...getTransformers(options)); <add> <ide> const finalFiles = Object.keys(files) <ide> .map(key => files[key]) <ide> .map(pipeLine); <ide> export function isJavaScriptChallenge({ challengeType }) { <ide> challengeType === challengeTypes.bonfire <ide> ); <ide> } <add> <add>export function isLoopProtected(challengeMeta) { <add> return challengeMeta.superBlock !== 'Coding Interview Prep'; <add>} <ide><path>client/utils/gatsby/challengePageCreator.js <ide> const getIntroIfRequired = (node, index, nodeArray) => { <ide> <ide> exports.createChallengePages = createPage => ({ node }, index, thisArray) => { <ide> const { <add> superBlock, <ide> block, <ide> fields: { slug }, <ide> required = [], <ide> exports.createChallengePages = createPage => ({ node }, index, thisArray) => { <ide> component: getTemplateComponent(challengeType), <ide> context: { <ide> challengeMeta: { <add> superBlock, <ide> block: block, <ide> introPath: getIntroIfRequired(node, index, thisArray), <ide> template,
5
Text
Text
remove the detail=none from apiexception signature
ed9c3258a6f9df6fabb569a65f3eb3363affa523
<ide><path>docs/api-guide/exceptions.md <ide> Note that the exception handler will only be called for responses generated by r <ide> <ide> ## APIException <ide> <del>**Signature:** `APIException(detail=None)` <add>**Signature:** `APIException()` <ide> <ide> The **base class** for all exceptions raised inside REST framework. <ide>
1
Javascript
Javascript
add support for additional node.js builtin modules
56f42f13a0e7fcd178540952ed4fd8ba88610a6c
<ide><path>lib/node/NodeTargetPlugin.js <ide> const builtins = [ <ide> "crypto", <ide> "dgram", <ide> "dns", <add> "dns/promises", <ide> "domain", <ide> "events", <ide> "fs", <ide> const builtins = [ <ide> "readline", <ide> "repl", <ide> "stream", <add> "stream/promises", <ide> "string_decoder", <ide> "sys", <ide> "timers", <add> "timers/promises", <ide> "tls", <ide> "trace_events", <ide> "tty", <ide> "url", <ide> "util", <ide> "v8", <ide> "vm", <add> "wasi", <ide> "worker_threads", <ide> "zlib" <ide> ];
1
Javascript
Javascript
add support for sortkeys on d3.nest
0585616df1ae6019b7f21fe163f386aba305a122
<ide><path>d3.js <del>(function(){d3 = {version: "1.3.0"}; // semver <add>(function(){d3 = {version: "1.4.0"}; // semver <ide> if (!Date.now) Date.now = function() { <ide> return +new Date(); <ide> }; <ide> d3.nest = function() { <ide> sortValues, <ide> rollup; <ide> <del> function recurse(j, array) { <del> if (j >= keys.length) return rollup <add> function map(array, depth) { <add> if (depth >= keys.length) return rollup <ide> ? rollup.call(nest, array) : (sortValues <ide> ? array.sort(sortValues) <ide> : array); <ide> <ide> var i = -1, <ide> n = array.length, <del> key = keys[j], <add> key = keys[depth++], <ide> keyValue, <del> keyValues = [], <del> sortKey = sortKeys[j], <ide> object, <del> map = {}; <add> o = {}; <ide> <ide> while (++i < n) { <del> if ((keyValue = key(object = array[i])) in map) { <del> map[keyValue].push(object); <add> if ((keyValue = key(object = array[i])) in o) { <add> o[keyValue].push(object); <ide> } else { <del> map[keyValue] = [object]; <del> keyValues.push(keyValue); <add> o[keyValue] = [object]; <ide> } <ide> } <ide> <del> j++; <del> i = -1; <del> n = keyValues.length; <del> while (++i < n) { <del> object = map[keyValue = keyValues[i]]; <del> map[keyValue] = recurse(j, object); <add> for (keyValue in o) { <add> o[keyValue] = map(o[keyValue], depth); <ide> } <ide> <del> return map; <add> return o; <add> } <add> <add> function entries(map, depth) { <add> if (depth >= keys.length) return map; <add> <add> var a = [], <add> sortKey = sortKeys[depth++], <add> key; <add> <add> for (key in map) { <add> a.push({key: key, values: entries(map[key], depth)}); <add> } <add> <add> if (sortKey) a.sort(function(a, b) { <add> return sortKey(a.key, b.key); <add> }); <add> <add> return a; <ide> } <ide> <ide> nest.map = function(array) { <del> return recurse(0, array); <add> return map(array, 0); <add> }; <add> <add> nest.entries = function(array) { <add> return entries(map(array, 0), 0); <ide> }; <ide> <ide> nest.key = function(d) { <ide> keys.push(d); <ide> return nest; <ide> }; <ide> <add> // Specifies the order for the most-recently specified key. <add> // Note: only applies to entries. Map keys are unordered! <ide> nest.sortKeys = function(order) { <ide> sortKeys[keys.length - 1] = order; <ide> return nest; <ide> }; <ide> <add> // Specifies the order for leaf values. <add> // Applies to both maps and entries array. <ide> nest.sortValues = function(order) { <ide> sortValues = order; <ide> return nest; <ide><path>d3.min.js <ide> a)})}function Ia(a,b){var d=Date.now(),g=false,e=d+b,c=F;if(isFinite(b)){for(;c; <ide> function Ma(a){return a.outerRadius}function ja(a){return a.startAngle}function ka(a){return a.endAngle}function $(a,b,d,g){var e=[],c=-1,f=b.length,h=typeof d=="function",i=typeof g=="function",k;if(h&&i)for(;++c<f;)e.push([d.call(a,k=b[c],c),g.call(a,k,c)]);else if(h)for(;++c<f;)e.push([d.call(a,b[c],c),g]);else if(i)for(;++c<f;)e.push([d,g.call(a,b[c],c)]);else for(;++c<f;)e.push([d,g]);return e}function la(a){return a[0]}function ma(a){return a[1]}function H(a){var b=[],d=0,g=a.length,e=a[0]; <ide> for(b.push(e[0],",",e[1]);++d<g;)b.push("L",(e=a[d])[0],",",e[1]);return b.join("")}function na(a,b){if(b.length<1||a.length!=b.length&&a.length!=b.length+2)return H(a);var d=a.length!=b.length,g="",e=a[0],c=a[1],f=b[0],h=f,i=1;if(d){g+="Q"+(c[0]-f[0]*2/3)+","+(c[1]-f[1]*2/3)+","+c[0]+","+c[1];e=a[1];i=2}if(b.length>1){h=b[1];c=a[i];i++;g+="C"+(e[0]+f[0])+","+(e[1]+f[1])+","+(c[0]-h[0])+","+(c[1]-h[1])+","+c[0]+","+c[1];for(e=2;e<b.length;e++,i++){c=a[i];h=b[e];g+="S"+(c[0]-h[0])+","+(c[1]-h[1])+ <ide> ","+c[0]+","+c[1]}}if(d){d=a[i];g+="Q"+(c[0]+h[0]*2/3)+","+(c[1]+h[1]*2/3)+","+d[0]+","+d[1]}return g}function oa(a,b){for(var d=[],g=(1-b)/2,e=a[0],c=a[1],f=a[2],h=2,i=a.length;++h<i;){d.push([g*(f[0]-e[0]),g*(f[1]-e[1])]);e=c;c=f;f=a[h]}d.push([g*(f[0]-e[0]),g*(f[1]-e[1])]);return d}function B(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3]}function L(a,b,d){a.push("C",B(pa,b),",",B(pa,d),",",B(qa,b),",",B(qa,d),",",B(M,b),",",B(M,d))}function Na(){return 0}function Oa(a){return a.source}function Pa(a){return a.target} <del>function Qa(a){return a.radius}function Ra(){return 64}function Sa(){return"circle"}d3={version:"1.3.0"};if(!Date.now)Date.now=function(){return+new Date};if(!Object.create)Object.create=function(a){function b(){}b.prototype=a;return new b};var N=function(a){return Array.prototype.slice.call(a)};try{N(document.documentElement.childNodes)}catch(eb){N=ua}d3.ascending=function(a,b){return a<b?-1:a>b?1:0};d3.descending=function(a,b){return b<a?-1:b>a?1:0};d3.min=function(a,b){var d=0,g=a.length,e=a[0], <del>c;if(arguments.length==1)for(;++d<g;){if(e>(c=a[d]))e=c}else for(e=b(a[0]);++d<g;)if(e>(c=b(a[d])))e=c;return e};d3.max=function(a,b){var d=0,g=a.length,e=a[0],c;if(arguments.length==1)for(;++d<g;){if(e<(c=a[d]))e=c}else for(e=b(e);++d<g;)if(e<(c=b(a[d])))e=c;return e};d3.nest=function(){function a(c,f){if(c>=d.length)return e?e.call(b,f):g?f.sort(g):f;for(var h=-1,i=f.length,k=d[c],j,o=[],p,m={};++h<i;)if((j=k(p=f[h]))in m)m[j].push(p);else{m[j]=[p];o.push(j)}c++;h=-1;for(i=o.length;++h<i;){p=m[j= <del>o[h]];m[j]=a(c,p)}return m}var b={},d=[],g,e;b.map=function(c){return a(0,c)};b.key=function(c){d.push(c);return b};b.sortKeys=function(){return b};b.sortValues=function(c){g=c;return b};b.rollup=function(c){e=c;return b};return b};d3.keys=function(a){var b=[],d;for(d in a)b.push(d);return b};d3.values=function(a){var b=[],d;for(d in a)b.push(a[d]);return b};d3.entries=function(a){var b=[],d;for(d in a)b.push({key:d,value:a[d]});return b};d3.merge=function(a){return Array.prototype.concat.apply([], <del>a)};d3.split=function(a,b){var d=[],g=[],e,c=-1,f=a.length;if(arguments.length<2)b=va;for(;++c<f;)if(b.call(g,e=a[c],c))g=[];else{g.length||d.push(g);g.push(e)}return d};d3.range=function(a,b,d){if(arguments.length==1){b=a;a=0}if(d==null)d=1;if((b-a)/d==Infinity)throw Error("infinite range");var g=[],e=-1,c;if(d<0)for(;(c=a+d*++e)>b;)g.push(c);else for(;(c=a+d*++e)<b;)g.push(c);return g};d3.requote=function(a){return a.replace(Ta,"\\$&")};var Ta=/[\\\^\$\*\+\?\[\]\(\)\.\{\}]/g;d3.xhr=function(a,b, <del>d){var g=new XMLHttpRequest;if(arguments.length<3)d=b;else b&&g.overrideMimeType(b);g.open("GET",a,true);g.onreadystatechange=function(){if(g.readyState==4)d(g.status<300?g:null)};g.send(null)};d3.text=function(a,b,d){if(arguments.length<3){d=b;b=null}d3.xhr(a,b,function(g){d(g&&g.responseText)})};d3.json=function(a,b){d3.text(a,"application/json",function(d){b(d?JSON.parse(d):null)})};d3.html=function(a,b){d3.text(a,"text/html",function(d){if(d!=null){var g=document.createRange();g.selectNode(document.body); <del>d=g.createContextualFragment(d)}b(d)})};d3.xml=function(a,b,d){if(arguments.length<3){d=b;b=null}d3.xhr(a,b,function(g){d(g&&g.responseXML)})};d3.ns={prefix:{svg:"http://www.w3.org/2000/svg",xhtml:"http://www.w3.org/1999/xhtml",xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"},qualify:function(a){var b=a.indexOf(":");return b<0?a:{space:d3.ns.prefix[a.substring(0,b)],local:a.substring(b+1)}}};d3.dispatch=function(){for(var a={}, <del>b,d=0,g=arguments.length;d<g;d++){b=arguments[d];a[b]=wa(b)}return a};d3.format=function(a){a=Ua.exec(a);var b=a[1]||" ",d=ra[a[3]]||ra["-"],g=a[5],e=+a[6],c=a[7],f=a[8],h=a[9];if(f)f=f.substring(1);if(g)b="0";if(h=="d")f="0";return function(i){i=+i;var k=i<0&&(i=-i);if(h=="d"&&i%1)return"";i=f?i.toFixed(f):""+i;if(c){for(var j=i.lastIndexOf("."),o=j>=0?i.substring(j):(j=i.length,""),p=[];j>0;)p.push(i.substring(j-=3,j+3));i=p.reverse().join(",")+o}k=(i=d(k,i)).length;if(k<e)i=Array(e-k+1).join(b)+ <del>i;return i}};var Ua=/(?:([^{])?([<>=^]))?([+\- ])?(#)?(0)?([0-9]+)?(,)?(\.[0-9]+)?([a-zA-Z%])?/,ra={"+":function(a,b){return(a?"−":"+")+b}," ":function(a,b){return(a?"−":" ")+b},"-":function(a,b){return a?"−"+b:b}},Va=R(2),Wa=R(3),Xa={linear:function(){return xa},poly:R,quad:function(){return Va},cubic:function(){return Wa},sin:function(){return ya},exp:function(){return za},circle:function(){return Aa},elastic:function(a,b){var d;if(arguments.length<2)b=0.45;if(arguments.length<1){a=1;d=b/4}else d= <del>b/(2*Math.PI)*Math.asin(1/a);return function(g){return 1+a*Math.pow(2,10*-g)*Math.sin((g-d)*2*Math.PI/b)}},back:function(a){a||(a=1.70158);return function(b){return b*b*((a+1)*b-a)}},bounce:function(){return Ba}},Ya={"in":function(a){return a},out:fa,"in-out":ga,"out-in":function(a){return ga(fa(a))}};d3.ease=function(a){var b=a.indexOf("-"),d=b>=0?a.substring(0,b):a;b=b>=0?a.substring(b+1):"in";return Ya[b](Xa[d].apply(null,Array.prototype.slice.call(arguments,1)))};d3.event=null;d3.interpolate= <del>function(a,b){if(typeof b=="number")return d3.interpolateNumber(+a,b);if(typeof b=="string")return b in G||/^(#|rgb\(|hsl\()/.test(b)?d3.interpolateRgb(String(a),b):d3.interpolateString(String(a),b);if(b instanceof Array)return d3.interpolateArray(a,b);return d3.interpolateObject(a,b)};d3.interpolateNumber=function(a,b){b-=a;return function(d){return a+b*d}};d3.interpolateRound=function(a,b){b-=a;return function(d){return Math.round(a+b*d)}};d3.interpolateString=function(a,b){var d,g,e=0,c=[],f=[], <del>h,i;for(g=0;d=aa.exec(b);++g){d.index&&c.push(b.substring(e,d.index));f.push({i:c.length,x:d[0]});c.push(null);e=aa.lastIndex}e<b.length&&c.push(b.substring(e));g=0;for(h=f.length;(d=aa.exec(a))&&g<h;++g){i=f[g];if(i.x==d[0]){if(i.i)if(c[i.i+1]==null){c[i.i-1]+=i.x;c.splice(i.i,1);for(d=g+1;d<h;++d)f[d].i--}else{c[i.i-1]+=i.x+c[i.i+1];c.splice(i.i,2);for(d=g+1;d<h;++d)f[d].i-=2}else if(c[i.i+1]==null)c[i.i]=i.x;else{c[i.i]=i.x+c[i.i+1];c.splice(i.i+1,1);for(d=g+1;d<h;++d)f[d].i--}f.splice(g,1);h--; <del>g--}else i.x=d3.interpolateNumber(parseFloat(d[0]),parseFloat(i.x))}for(;g<h;){i=f.pop();if(c[i.i+1]==null)c[i.i]=i.x;else{c[i.i]=i.x+c[i.i+1];c.splice(i.i+1,1)}h--}if(c.length==1)return c[0]==null?f[0].x:function(){return b};return function(k){for(g=0;g<h;++g)c[(i=f[g]).i]=i.x(k);return c.join("")}};d3.interpolateRgb=function(a,b){a=d3.rgb(a);b=d3.rgb(b);var d=a.r,g=a.g,e=a.b,c=b.r-d,f=b.g-g,h=b.b-e;return function(i){return"rgb("+Math.round(d+c*i)+","+Math.round(g+f*i)+","+Math.round(e+h*i)+")"}}; <del>d3.interpolateHsl=function(a,b){a=d3.hsl(a);b=d3.hsl(b);var d=a.h,g=a.s,e=a.l,c=b.h-d,f=b.s-g,h=b.l-e;return function(i){return W(d+c*i,g+f*i,e+h*i).toString()}};d3.interpolateArray=function(a,b){var d=[],g=[],e=a.length,c=b.length,f=Math.min(a.length,b.length),h;for(h=0;h<f;++h)d.push(d3.interpolate(a[h],b[h]));for(;h<e;++h)g[h]=a[h];for(;h<c;++h)g[h]=b[h];return function(i){for(h=0;h<f;++h)g[h]=d[h](i);return g}};d3.interpolateObject=function(a,b){var d={},g={},e;for(e in a)if(e in b)d[e]=(e in <del>Za||/\bcolor\b/.test(e)?d3.interpolateRgb:d3.interpolate)(a[e],b[e]);else g[e]=a[e];for(e in b)e in a||(g[e]=b[e]);return function(c){for(e in d)g[e]=d[e](c);return g}};var aa=/[-+]?(?:\d+\.\d+|\d+\.|\.\d+|\d+)(?:[eE][-]?\d+)?/g,Za={background:1,fill:1,stroke:1};d3.rgb=function(a,b,d){return arguments.length==1?T(""+a,J,W):J(~~a,~~b,~~d)};var G={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd", <del>blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f", <del>darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082", <del>ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgreen:"#90ee90",lightgrey:"#d3d3d3",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6", <del>magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370db",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa", <del>palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4", <del>tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"},ba;for(ba in G)G[ba]=T(G[ba],J,W);d3.hsl=function(a,b,d){return arguments.length==1?T(""+a,Da,V):V(+a,+b,+d)};var D=function(a,b){return b.querySelector(a)},ha=function(a,b){return N(b.querySelectorAll(a))};if(typeof Sizzle=="function"){D=function(a,b){return Sizzle(a,b)[0]};ha=Sizzle}var O=y([[document]]); <del>O[0].parentNode=document.documentElement;d3.select=function(a){return typeof a=="string"?O.select(a):y([[a]])};d3.selectAll=function(a){return typeof a=="string"?O.selectAll(a):y([N(a)])};d3.transition=O.transition;var Ha=0,Y=0,F=null,Z=0,K;d3.scale={};d3.scale.linear=function(){function a(j){return k((j-d)*f)}function b(j){var o=Math.min(d,g),p=Math.max(d,g),m=p-o,n=Math.pow(10,Math.floor(Math.log(m/j)/Math.LN10));j=j/(m/n);if(j<=0.15)n*=10;else if(j<=0.35)n*=5;else if(j<=0.75)n*=2;return{start:Math.ceil(o/ <del>n)*n,stop:Math.floor(p/n)*n+n*0.5,step:n}}var d=0,g=1,e=0,c=1,f=1/(g-d),h=(g-d)/(c-e),i=d3.interpolate,k=i(e,c);a.invert=function(j){return(j-e)*h+d};a.domain=function(j){if(!arguments.length)return[d,g];d=j[0];g=j[1];f=1/(g-d);h=(g-d)/(c-e);return a};a.range=function(j){if(!arguments.length)return[e,c];e=j[0];c=j[1];h=(g-d)/(c-e);k=i(e,c);return a};a.rangeRound=function(j){return a.range(j).interpolate(d3.interpolateRound)};a.interpolate=function(j){if(!arguments.length)return i;k=(i=j)(e,c);return a}; <del>a.ticks=function(j){j=b(j);return d3.range(j.start,j.stop,j.step)};a.tickFormat=function(j){j=Math.max(0,-Math.floor(Math.log(b(j).step)/Math.LN10+0.01));return d3.format(",."+j+"f")};return a};d3.scale.log=function(){function a(c){return(e?-Math.log(-c):Math.log(c))/Math.LN10}function b(c){return e?-Math.pow(10,-c):Math.pow(10,c)}function d(c){return g(a(c))}var g=d3.scale.linear(),e=false;d.invert=function(c){return b(g.invert(c))};d.domain=function(c){if(!arguments.length)return g.domain().map(b); <del>e=(c[0]||c[1])<0;g.domain(c.map(a));return d};d.range=C(d,g.range);d.rangeRound=C(d,g.rangeRound);d.interpolate=C(d,g.interpolate);d.ticks=function(){var c=g.domain(),f=[];if(c.every(isFinite)){var h=Math.floor(c[0]),i=Math.ceil(c[1]),k=b(c[0]);c=b(c[1]);if(e)for(f.push(b(h));h++<i;)for(var j=9;j>0;j--)f.push(b(h)*j);else{for(;h<i;h++)for(j=1;j<10;j++)f.push(b(h)*j);f.push(b(h))}for(h=0;f[h]<k;h++);for(i=f.length;f[i-1]>c;i--);f=f.slice(h,i)}return f};d.tickFormat=function(){return function(c){return c.toPrecision(1)}}; <del>return d};d3.scale.pow=function(){function a(i){return h?-Math.pow(-i,c):Math.pow(i,c)}function b(i){return h?-Math.pow(-i,f):Math.pow(i,f)}function d(i){return g(a(i))}var g=d3.scale.linear(),e=d3.scale.linear(),c=1,f=1/c,h=false;d.invert=function(i){return b(g.invert(i))};d.domain=function(i){if(!arguments.length)return g.domain().map(b);h=(i[0]||i[1])<0;g.domain(i.map(a));e.domain(i);return d};d.range=C(d,g.range);d.rangeRound=C(d,g.rangeRound);d.inteprolate=C(d,g.interpolate);d.ticks=e.ticks; <del>d.tickFormat=e.tickFormat;d.exponent=function(i){if(!arguments.length)return c;var k=d.domain();c=i;f=1/i;return d.domain(k)};return d};d3.scale.sqrt=function(){return d3.scale.pow().exponent(0.5)};d3.scale.ordinal=function(){function a(c){c=c in d?d[c]:d[c]=b.push(c)-1;return g[c%g.length]}var b=[],d={},g=[],e=0;a.domain=function(c){if(!arguments.length)return b;b=c;d={};for(var f=-1,h=-1,i=b.length;++f<i;){c=b[f];c in d||(d[c]=++h)}return a};a.range=function(c){if(!arguments.length)return g;g=c; <del>return a};a.rangePoints=function(c,f){if(arguments.length<2)f=0;var h=c[0],i=c[1],k=(i-h)/(b.length-1+f);g=b.length==1?[(h+i)/2]:d3.range(h+k*f/2,i+k/2,k);e=0;return a};a.rangeBands=function(c,f){if(arguments.length<2)f=0;var h=c[0],i=c[1],k=(i-h)/(b.length+f);g=d3.range(h+k*f,i,k);e=k*(1-f);return a};a.rangeRoundBands=function(c,f){if(arguments.length<2)f=0;var h=c[0],i=c[1],k=i-h,j=Math.floor(k/(b.length+f));g=d3.range(h+Math.round((k-(b.length-f)*j)/2),i,j);e=Math.round(j*(1-f));return a};a.rangeBand= <del>function(){return e};return a};d3.scale.category10=function(){return d3.scale.ordinal().range($a)};d3.scale.category20=function(){return d3.scale.ordinal().range(ab)};d3.scale.category20b=function(){return d3.scale.ordinal().range(bb)};d3.scale.category20c=function(){return d3.scale.ordinal().range(cb)};var $a=["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"],ab=["#1f77b4","#aec7e8","#ff7f0e","#ffbb78","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd", <del>"#c5b0d5","#8c564b","#c49c94","#e377c2","#f7b6d2","#7f7f7f","#c7c7c7","#bcbd22","#dbdb8d","#17becf","#9edae5"],bb=["#393b79","#5254a3","#6b6ecf","#9c9ede","#637939","#8ca252","#b5cf6b","#cedb9c","#8c6d31","#bd9e39","#e7ba52","#e7cb94","#843c39","#ad494a","#d6616b","#e7969c","#7b4173","#a55194","#ce6dbd","#de9ed6"],cb=["#3182bd","#6baed6","#9ecae1","#c6dbef","#e6550d","#fd8d3c","#fdae6b","#fdd0a2","#31a354","#74c476","#a1d99b","#c7e9c0","#756bb1","#9e9ac8","#bcbddc","#dadaeb","#636363","#969696","#bdbdbd", <del>"#d9d9d9"];d3.scale.quantile=function(){function a(){for(var f=-1,h=c.length=e.length,i=g.length/h;++f<h;)c[f]=g[~~(f*i)]}function b(f){if(isNaN(f=+f))return NaN;for(var h=0,i=c.length-1;h<=i;){var k=h+i>>1,j=c[k];if(j<f)h=k+1;else if(j>f)i=k-1;else return k}return i<0?0:i}function d(f){return e[b(f)]}var g=[],e=[],c=[];d.domain=function(f){if(!arguments.length)return g;g=f.filter(function(h){return!isNaN(h)}).sort(d3.ascending);a();return d};d.range=function(f){if(!arguments.length)return e;e=f; <del>a();return d};d.quantiles=function(){return c};return d};d3.scale.quantize=function(){function a(f){return c[Math.max(0,Math.min(e,Math.floor(g*(f-b))))]}var b=0,d=1,g=2,e=1,c=[0,1];a.domain=function(f){if(!arguments.length)return[b,d];b=f[0];d=f[1];g=c.length/(d-b);return a};a.range=function(f){if(!arguments.length)return c;c=f;g=c.length/(d-b);e=c.length-1;return a};return a};d3.svg={};d3.svg.arc=function(){function a(){var c=b.apply(this,arguments),f=d.apply(this,arguments),h=g.apply(this,arguments)+ <del>I,i=e.apply(this,arguments)+I,k=i-h,j=k<Math.PI?"0":"1",o=Math.cos(h);h=Math.sin(h);var p=Math.cos(i);i=Math.sin(i);return k>=db?c?"M0,"+f+"A"+f+","+f+" 0 1,1 0,"+-f+"A"+f+","+f+" 0 1,1 0,"+f+"M0,"+c+"A"+c+","+c+" 0 1,1 0,"+-c+"A"+c+","+c+" 0 1,1 0,"+c+"Z":"M0,"+f+"A"+f+","+f+" 0 1,1 0,"+-f+"A"+f+","+f+" 0 1,1 0,"+f+"Z":c?"M"+f*o+","+f*h+"A"+f+","+f+" 0 "+j+",1 "+f*p+","+f*i+"L"+c*p+","+c*i+"A"+c+","+c+" 0 "+j+",0 "+c*o+","+c*h+"Z":"M"+f*o+","+f*h+"A"+f+","+f+" 0 "+j+",1 "+f*p+","+f*i+"L0,0Z"}var b= <del>La,d=Ma,g=ja,e=ka;a.innerRadius=function(c){if(!arguments.length)return b;b=v(c);return a};a.outerRadius=function(c){if(!arguments.length)return d;d=v(c);return a};a.startAngle=function(c){if(!arguments.length)return g;g=v(c);return a};a.endAngle=function(c){if(!arguments.length)return e;e=v(c);return a};a.centroid=function(){var c=(b.apply(this,arguments)+d.apply(this,arguments))/2,f=(g.apply(this,arguments)+e.apply(this,arguments))/2+I;return[Math.cos(f)*c,Math.sin(f)*c]};return a};var I=-Math.PI/ <del>2,db=2*Math.PI-1.0E-6;d3.svg.line=function(){function a(f){return f.length<1?null:"M"+e($(this,f,b,d),c)}var b=la,d=ma,g="linear",e=P[g],c=0.7;a.x=function(f){if(!arguments.length)return b;b=f;return a};a.y=function(f){if(!arguments.length)return d;d=f;return a};a.interpolate=function(f){if(!arguments.length)return g;e=P[g=f];return a};a.tension=function(f){if(!arguments.length)return c;c=f;return a};return a};var P={linear:H,basis:function(a){if(a.length<3)return H(a);var b=[],d=1,g=a.length,e=a[0], <del>c=e[0],f=e[1],h=[c,c,c,(e=a[1])[0]],i=[f,f,f,e[1]];b.push(c,",",f);for(L(b,h,i);++d<g;){e=a[d];h.shift();h.push(e[0]);i.shift();i.push(e[1]);L(b,h,i)}for(d=-1;++d<2;){h.shift();h.push(e[0]);i.shift();i.push(e[1]);L(b,h,i)}return b.join("")},"basis-closed":function(a){for(var b,d=-1,g=a.length,e=g+4,c,f=[],h=[];++d<4;){c=a[d%g];f.push(c[0]);h.push(c[1])}b=[B(M,f),",",B(M,h)];for(--d;++d<e;){c=a[d%g];f.shift();f.push(c[0]);h.shift();h.push(c[1]);L(b,f,h)}return b.join("")},cardinal:function(a,b){if(a.length< <del>3)return H(a);return a[0]+na(a,oa(a,b))},"cardinal-closed":function(a,b){if(a.length<3)return H(a);return a[0]+na(a,oa([a[a.length-2]].concat(a,[a[1]]),b))}},pa=[0,2/3,1/3,0],qa=[0,1/3,2/3,0],M=[0,1/6,2/3,1/6];d3.svg.area=function(){function a(h){return h.length<1?null:"M"+c($(this,h,b,g),f)+"L"+c($(this,h,b,d).reverse(),f)+"Z"}var b=la,d=Na,g=ma,e="linear",c=P[e],f=0.7;a.x=function(h){if(!arguments.length)return b;b=h;return a};a.y0=function(h){if(!arguments.length)return d;d=h;return a};a.y1=function(h){if(!arguments.length)return g; <del>g=h;return a};a.interpolate=function(h){if(!arguments.length)return e;c=P[e=h];return a};a.tension=function(h){if(!arguments.length)return f;f=h;return a};return a};d3.svg.chord=function(){function a(h,i){var k=b(this,d,h,i),j=b(this,g,h,i);return"M"+k.p0+("A"+k.r+","+k.r+" 0 0,1 "+k.p1)+(k.a0==j.a0&&k.a1==j.a1?"Q 0,0 "+k.p0:"Q 0,0 "+j.p0+("A"+j.r+","+j.r+" 0 0,1 "+j.p1)+("Q 0,0 "+k.p0))+"Z"}function b(h,i,k,j){var o=i.call(h,k,j);i=e.call(h,o,j);k=c.call(h,o,j)+I;h=f.call(h,o,j)+I;return{r:i,a0:k, <del>a1:h,p0:[i*Math.cos(k),i*Math.sin(k)],p1:[i*Math.cos(h),i*Math.sin(h)]}}var d=Oa,g=Pa,e=Qa,c=ja,f=ka;a.radius=function(h){if(!arguments.length)return e;e=v(h);return a};a.source=function(h){if(!arguments.length)return d;d=v(h);return a};a.target=function(h){if(!arguments.length)return g;g=v(h);return a};a.startAngle=function(h){if(!arguments.length)return c;c=v(h);return a};a.endAngle=function(h){if(!arguments.length)return f;f=v(h);return a};return a};d3.svg.mouse=function(a){var b=(a.ownerSVGElement|| <del>a).createSVGPoint();if(ca<0&&(window.scrollX||window.scrollY)){var d=d3.select(document.body).append("svg:svg").style("position","absolute").style("top",0).style("left",0),g=d[0][0].getScreenCTM();ca=!(g.f||g.e);d.remove()}if(ca){b.x=d3.event.pageX;b.y=d3.event.pageY}else{b.x=d3.event.clientX;b.y=d3.event.clientY}b=b.matrixTransform(a.getScreenCTM().inverse());return[b.x,b.y]};var ca=/WebKit/.test(navigator.userAgent)?-1:0;d3.svg.symbol=function(){function a(g,e){return(sa[b.call(this,g,e)]||sa.circle)(d.call(this, <del>g,e))}var b=Sa,d=Ra;a.type=function(g){if(!arguments.length)return b;b=v(g);return a};a.size=function(g){if(!arguments.length)return d;d=v(g);return a};return a};d3.svg.symbolTypes=["circle","cross","diamond","square","triangle-down","triangle-up"];var sa={circle:function(a){a=Math.sqrt(a/Math.PI);return"M0,"+a+"A"+a+","+a+" 0 1,1 0,"+-a+"A"+a+","+a+" 0 1,1 0,"+a+"Z"},cross:function(a){a=Math.sqrt(a/5)/2;return"M"+-3*a+","+-a+"H"+-a+"V"+-3*a+"H"+a+"V"+-a+"H"+3*a+"V"+a+"H"+a+"V"+3*a+"H"+-a+"V"+a+"H"+ <del>-3*a+"Z"},diamond:function(a){a=Math.sqrt(a/(2*ta));var b=a*ta;return"M0,"+-a+"L"+b+",0 0,"+a+" "+-b+",0Z"},square:function(a){a=Math.sqrt(a)/2;return"M"+-a+","+-a+"L"+a+","+-a+" "+a+","+a+" "+-a+","+a+"Z"},"triangle-down":function(a){a=Math.sqrt(a/Q);var b=a*Q/2;return"M0,"+b+"L"+a+","+-b+" "+-a+","+-b+"Z"},"triangle-up":function(a){a=Math.sqrt(a/Q);var b=a*Q/2;return"M0,"+-b+"L"+a+","+b+" "+-a+","+b+"Z"}},Q=Math.sqrt(3),ta=Math.tan(30*Math.PI/180)})(); <add>function Qa(a){return a.radius}function Ra(){return 64}function Sa(){return"circle"}d3={version:"1.4.0"};if(!Date.now)Date.now=function(){return+new Date};if(!Object.create)Object.create=function(a){function b(){}b.prototype=a;return new b};var N=function(a){return Array.prototype.slice.call(a)};try{N(document.documentElement.childNodes)}catch(eb){N=ua}d3.ascending=function(a,b){return a<b?-1:a>b?1:0};d3.descending=function(a,b){return b<a?-1:b>a?1:0};d3.min=function(a,b){var d=0,g=a.length,e=a[0], <add>c;if(arguments.length==1)for(;++d<g;){if(e>(c=a[d]))e=c}else for(e=b(a[0]);++d<g;)if(e>(c=b(a[d])))e=c;return e};d3.max=function(a,b){var d=0,g=a.length,e=a[0],c;if(arguments.length==1)for(;++d<g;){if(e<(c=a[d]))e=c}else for(e=b(e);++d<g;)if(e<(c=b(a[d])))e=c;return e};d3.nest=function(){function a(h,i){if(i>=g.length)return f?f.call(d,h):c?h.sort(c):h;for(var k=-1,j=h.length,o=g[i++],p,m,n={};++k<j;)if((p=o(m=h[k]))in n)n[p].push(m);else n[p]=[m];for(p in n)n[p]=a(n[p],i);return n}function b(h,i){if(i>= <add>g.length)return h;var k=[],j=e[i++],o;for(o in h)k.push({key:o,values:b(h[o],i)});j&&k.sort(function(p,m){return j(p.key,m.key)});return k}var d={},g=[],e=[],c,f;d.map=function(h){return a(h,0)};d.entries=function(h){return b(a(h,0),0)};d.key=function(h){g.push(h);return d};d.sortKeys=function(h){e[g.length-1]=h;return d};d.sortValues=function(h){c=h;return d};d.rollup=function(h){f=h;return d};return d};d3.keys=function(a){var b=[],d;for(d in a)b.push(d);return b};d3.values=function(a){var b=[], <add>d;for(d in a)b.push(a[d]);return b};d3.entries=function(a){var b=[],d;for(d in a)b.push({key:d,value:a[d]});return b};d3.merge=function(a){return Array.prototype.concat.apply([],a)};d3.split=function(a,b){var d=[],g=[],e,c=-1,f=a.length;if(arguments.length<2)b=va;for(;++c<f;)if(b.call(g,e=a[c],c))g=[];else{g.length||d.push(g);g.push(e)}return d};d3.range=function(a,b,d){if(arguments.length==1){b=a;a=0}if(d==null)d=1;if((b-a)/d==Infinity)throw Error("infinite range");var g=[],e=-1,c;if(d<0)for(;(c= <add>a+d*++e)>b;)g.push(c);else for(;(c=a+d*++e)<b;)g.push(c);return g};d3.requote=function(a){return a.replace(Ta,"\\$&")};var Ta=/[\\\^\$\*\+\?\[\]\(\)\.\{\}]/g;d3.xhr=function(a,b,d){var g=new XMLHttpRequest;if(arguments.length<3)d=b;else b&&g.overrideMimeType(b);g.open("GET",a,true);g.onreadystatechange=function(){if(g.readyState==4)d(g.status<300?g:null)};g.send(null)};d3.text=function(a,b,d){if(arguments.length<3){d=b;b=null}d3.xhr(a,b,function(g){d(g&&g.responseText)})};d3.json=function(a,b){d3.text(a, <add>"application/json",function(d){b(d?JSON.parse(d):null)})};d3.html=function(a,b){d3.text(a,"text/html",function(d){if(d!=null){var g=document.createRange();g.selectNode(document.body);d=g.createContextualFragment(d)}b(d)})};d3.xml=function(a,b,d){if(arguments.length<3){d=b;b=null}d3.xhr(a,b,function(g){d(g&&g.responseXML)})};d3.ns={prefix:{svg:"http://www.w3.org/2000/svg",xhtml:"http://www.w3.org/1999/xhtml",xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"}, <add>qualify:function(a){var b=a.indexOf(":");return b<0?a:{space:d3.ns.prefix[a.substring(0,b)],local:a.substring(b+1)}}};d3.dispatch=function(){for(var a={},b,d=0,g=arguments.length;d<g;d++){b=arguments[d];a[b]=wa(b)}return a};d3.format=function(a){a=Ua.exec(a);var b=a[1]||" ",d=ra[a[3]]||ra["-"],g=a[5],e=+a[6],c=a[7],f=a[8],h=a[9];if(f)f=f.substring(1);if(g)b="0";if(h=="d")f="0";return function(i){i=+i;var k=i<0&&(i=-i);if(h=="d"&&i%1)return"";i=f?i.toFixed(f):""+i;if(c){for(var j=i.lastIndexOf("."), <add>o=j>=0?i.substring(j):(j=i.length,""),p=[];j>0;)p.push(i.substring(j-=3,j+3));i=p.reverse().join(",")+o}k=(i=d(k,i)).length;if(k<e)i=Array(e-k+1).join(b)+i;return i}};var Ua=/(?:([^{])?([<>=^]))?([+\- ])?(#)?(0)?([0-9]+)?(,)?(\.[0-9]+)?([a-zA-Z%])?/,ra={"+":function(a,b){return(a?"−":"+")+b}," ":function(a,b){return(a?"−":" ")+b},"-":function(a,b){return a?"−"+b:b}},Va=R(2),Wa=R(3),Xa={linear:function(){return xa},poly:R,quad:function(){return Va},cubic:function(){return Wa},sin:function(){return ya}, <add>exp:function(){return za},circle:function(){return Aa},elastic:function(a,b){var d;if(arguments.length<2)b=0.45;if(arguments.length<1){a=1;d=b/4}else d=b/(2*Math.PI)*Math.asin(1/a);return function(g){return 1+a*Math.pow(2,10*-g)*Math.sin((g-d)*2*Math.PI/b)}},back:function(a){a||(a=1.70158);return function(b){return b*b*((a+1)*b-a)}},bounce:function(){return Ba}},Ya={"in":function(a){return a},out:fa,"in-out":ga,"out-in":function(a){return ga(fa(a))}};d3.ease=function(a){var b=a.indexOf("-"),d=b>= <add>0?a.substring(0,b):a;b=b>=0?a.substring(b+1):"in";return Ya[b](Xa[d].apply(null,Array.prototype.slice.call(arguments,1)))};d3.event=null;d3.interpolate=function(a,b){if(typeof b=="number")return d3.interpolateNumber(+a,b);if(typeof b=="string")return b in G||/^(#|rgb\(|hsl\()/.test(b)?d3.interpolateRgb(String(a),b):d3.interpolateString(String(a),b);if(b instanceof Array)return d3.interpolateArray(a,b);return d3.interpolateObject(a,b)};d3.interpolateNumber=function(a,b){b-=a;return function(d){return a+ <add>b*d}};d3.interpolateRound=function(a,b){b-=a;return function(d){return Math.round(a+b*d)}};d3.interpolateString=function(a,b){var d,g,e=0,c=[],f=[],h,i;for(g=0;d=aa.exec(b);++g){d.index&&c.push(b.substring(e,d.index));f.push({i:c.length,x:d[0]});c.push(null);e=aa.lastIndex}e<b.length&&c.push(b.substring(e));g=0;for(h=f.length;(d=aa.exec(a))&&g<h;++g){i=f[g];if(i.x==d[0]){if(i.i)if(c[i.i+1]==null){c[i.i-1]+=i.x;c.splice(i.i,1);for(d=g+1;d<h;++d)f[d].i--}else{c[i.i-1]+=i.x+c[i.i+1];c.splice(i.i,2); <add>for(d=g+1;d<h;++d)f[d].i-=2}else if(c[i.i+1]==null)c[i.i]=i.x;else{c[i.i]=i.x+c[i.i+1];c.splice(i.i+1,1);for(d=g+1;d<h;++d)f[d].i--}f.splice(g,1);h--;g--}else i.x=d3.interpolateNumber(parseFloat(d[0]),parseFloat(i.x))}for(;g<h;){i=f.pop();if(c[i.i+1]==null)c[i.i]=i.x;else{c[i.i]=i.x+c[i.i+1];c.splice(i.i+1,1)}h--}if(c.length==1)return c[0]==null?f[0].x:function(){return b};return function(k){for(g=0;g<h;++g)c[(i=f[g]).i]=i.x(k);return c.join("")}};d3.interpolateRgb=function(a,b){a=d3.rgb(a);b=d3.rgb(b); <add>var d=a.r,g=a.g,e=a.b,c=b.r-d,f=b.g-g,h=b.b-e;return function(i){return"rgb("+Math.round(d+c*i)+","+Math.round(g+f*i)+","+Math.round(e+h*i)+")"}};d3.interpolateHsl=function(a,b){a=d3.hsl(a);b=d3.hsl(b);var d=a.h,g=a.s,e=a.l,c=b.h-d,f=b.s-g,h=b.l-e;return function(i){return W(d+c*i,g+f*i,e+h*i).toString()}};d3.interpolateArray=function(a,b){var d=[],g=[],e=a.length,c=b.length,f=Math.min(a.length,b.length),h;for(h=0;h<f;++h)d.push(d3.interpolate(a[h],b[h]));for(;h<e;++h)g[h]=a[h];for(;h<c;++h)g[h]= <add>b[h];return function(i){for(h=0;h<f;++h)g[h]=d[h](i);return g}};d3.interpolateObject=function(a,b){var d={},g={},e;for(e in a)if(e in b)d[e]=(e in Za||/\bcolor\b/.test(e)?d3.interpolateRgb:d3.interpolate)(a[e],b[e]);else g[e]=a[e];for(e in b)e in a||(g[e]=b[e]);return function(c){for(e in d)g[e]=d[e](c);return g}};var aa=/[-+]?(?:\d+\.\d+|\d+\.|\.\d+|\d+)(?:[eE][-]?\d+)?/g,Za={background:1,fill:1,stroke:1};d3.rgb=function(a,b,d){return arguments.length==1?T(""+a,J,W):J(~~a,~~b,~~d)};var G={aliceblue:"#f0f8ff", <add>antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",darkkhaki:"#bdb76b", <add>darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700", <add>goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgreen:"#90ee90",lightgrey:"#d3d3d3",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa", <add>lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370db",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead", <add>navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d", <add>silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"},ba;for(ba in G)G[ba]=T(G[ba],J,W);d3.hsl=function(a,b,d){return arguments.length==1?T(""+a,Da,V):V(+a,+b,+d)};var D=function(a,b){return b.querySelector(a)}, <add>ha=function(a,b){return N(b.querySelectorAll(a))};if(typeof Sizzle=="function"){D=function(a,b){return Sizzle(a,b)[0]};ha=Sizzle}var O=y([[document]]);O[0].parentNode=document.documentElement;d3.select=function(a){return typeof a=="string"?O.select(a):y([[a]])};d3.selectAll=function(a){return typeof a=="string"?O.selectAll(a):y([N(a)])};d3.transition=O.transition;var Ha=0,Y=0,F=null,Z=0,K;d3.scale={};d3.scale.linear=function(){function a(j){return k((j-d)*f)}function b(j){var o=Math.min(d,g),p=Math.max(d, <add>g),m=p-o,n=Math.pow(10,Math.floor(Math.log(m/j)/Math.LN10));j=j/(m/n);if(j<=0.15)n*=10;else if(j<=0.35)n*=5;else if(j<=0.75)n*=2;return{start:Math.ceil(o/n)*n,stop:Math.floor(p/n)*n+n*0.5,step:n}}var d=0,g=1,e=0,c=1,f=1/(g-d),h=(g-d)/(c-e),i=d3.interpolate,k=i(e,c);a.invert=function(j){return(j-e)*h+d};a.domain=function(j){if(!arguments.length)return[d,g];d=j[0];g=j[1];f=1/(g-d);h=(g-d)/(c-e);return a};a.range=function(j){if(!arguments.length)return[e,c];e=j[0];c=j[1];h=(g-d)/(c-e);k=i(e,c);return a}; <add>a.rangeRound=function(j){return a.range(j).interpolate(d3.interpolateRound)};a.interpolate=function(j){if(!arguments.length)return i;k=(i=j)(e,c);return a};a.ticks=function(j){j=b(j);return d3.range(j.start,j.stop,j.step)};a.tickFormat=function(j){j=Math.max(0,-Math.floor(Math.log(b(j).step)/Math.LN10+0.01));return d3.format(",."+j+"f")};return a};d3.scale.log=function(){function a(c){return(e?-Math.log(-c):Math.log(c))/Math.LN10}function b(c){return e?-Math.pow(10,-c):Math.pow(10,c)}function d(c){return g(a(c))} <add>var g=d3.scale.linear(),e=false;d.invert=function(c){return b(g.invert(c))};d.domain=function(c){if(!arguments.length)return g.domain().map(b);e=(c[0]||c[1])<0;g.domain(c.map(a));return d};d.range=C(d,g.range);d.rangeRound=C(d,g.rangeRound);d.interpolate=C(d,g.interpolate);d.ticks=function(){var c=g.domain(),f=[];if(c.every(isFinite)){var h=Math.floor(c[0]),i=Math.ceil(c[1]),k=b(c[0]);c=b(c[1]);if(e)for(f.push(b(h));h++<i;)for(var j=9;j>0;j--)f.push(b(h)*j);else{for(;h<i;h++)for(j=1;j<10;j++)f.push(b(h)* <add>j);f.push(b(h))}for(h=0;f[h]<k;h++);for(i=f.length;f[i-1]>c;i--);f=f.slice(h,i)}return f};d.tickFormat=function(){return function(c){return c.toPrecision(1)}};return d};d3.scale.pow=function(){function a(i){return h?-Math.pow(-i,c):Math.pow(i,c)}function b(i){return h?-Math.pow(-i,f):Math.pow(i,f)}function d(i){return g(a(i))}var g=d3.scale.linear(),e=d3.scale.linear(),c=1,f=1/c,h=false;d.invert=function(i){return b(g.invert(i))};d.domain=function(i){if(!arguments.length)return g.domain().map(b); <add>h=(i[0]||i[1])<0;g.domain(i.map(a));e.domain(i);return d};d.range=C(d,g.range);d.rangeRound=C(d,g.rangeRound);d.inteprolate=C(d,g.interpolate);d.ticks=e.ticks;d.tickFormat=e.tickFormat;d.exponent=function(i){if(!arguments.length)return c;var k=d.domain();c=i;f=1/i;return d.domain(k)};return d};d3.scale.sqrt=function(){return d3.scale.pow().exponent(0.5)};d3.scale.ordinal=function(){function a(c){c=c in d?d[c]:d[c]=b.push(c)-1;return g[c%g.length]}var b=[],d={},g=[],e=0;a.domain=function(c){if(!arguments.length)return b; <add>b=c;d={};for(var f=-1,h=-1,i=b.length;++f<i;){c=b[f];c in d||(d[c]=++h)}return a};a.range=function(c){if(!arguments.length)return g;g=c;return a};a.rangePoints=function(c,f){if(arguments.length<2)f=0;var h=c[0],i=c[1],k=(i-h)/(b.length-1+f);g=b.length==1?[(h+i)/2]:d3.range(h+k*f/2,i+k/2,k);e=0;return a};a.rangeBands=function(c,f){if(arguments.length<2)f=0;var h=c[0],i=c[1],k=(i-h)/(b.length+f);g=d3.range(h+k*f,i,k);e=k*(1-f);return a};a.rangeRoundBands=function(c,f){if(arguments.length<2)f=0;var h= <add>c[0],i=c[1],k=i-h,j=Math.floor(k/(b.length+f));g=d3.range(h+Math.round((k-(b.length-f)*j)/2),i,j);e=Math.round(j*(1-f));return a};a.rangeBand=function(){return e};return a};d3.scale.category10=function(){return d3.scale.ordinal().range($a)};d3.scale.category20=function(){return d3.scale.ordinal().range(ab)};d3.scale.category20b=function(){return d3.scale.ordinal().range(bb)};d3.scale.category20c=function(){return d3.scale.ordinal().range(cb)};var $a=["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd", <add>"#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"],ab=["#1f77b4","#aec7e8","#ff7f0e","#ffbb78","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5","#8c564b","#c49c94","#e377c2","#f7b6d2","#7f7f7f","#c7c7c7","#bcbd22","#dbdb8d","#17becf","#9edae5"],bb=["#393b79","#5254a3","#6b6ecf","#9c9ede","#637939","#8ca252","#b5cf6b","#cedb9c","#8c6d31","#bd9e39","#e7ba52","#e7cb94","#843c39","#ad494a","#d6616b","#e7969c","#7b4173","#a55194","#ce6dbd","#de9ed6"],cb=["#3182bd","#6baed6","#9ecae1","#c6dbef", <add>"#e6550d","#fd8d3c","#fdae6b","#fdd0a2","#31a354","#74c476","#a1d99b","#c7e9c0","#756bb1","#9e9ac8","#bcbddc","#dadaeb","#636363","#969696","#bdbdbd","#d9d9d9"];d3.scale.quantile=function(){function a(){for(var f=-1,h=c.length=e.length,i=g.length/h;++f<h;)c[f]=g[~~(f*i)]}function b(f){if(isNaN(f=+f))return NaN;for(var h=0,i=c.length-1;h<=i;){var k=h+i>>1,j=c[k];if(j<f)h=k+1;else if(j>f)i=k-1;else return k}return i<0?0:i}function d(f){return e[b(f)]}var g=[],e=[],c=[];d.domain=function(f){if(!arguments.length)return g; <add>g=f.filter(function(h){return!isNaN(h)}).sort(d3.ascending);a();return d};d.range=function(f){if(!arguments.length)return e;e=f;a();return d};d.quantiles=function(){return c};return d};d3.scale.quantize=function(){function a(f){return c[Math.max(0,Math.min(e,Math.floor(g*(f-b))))]}var b=0,d=1,g=2,e=1,c=[0,1];a.domain=function(f){if(!arguments.length)return[b,d];b=f[0];d=f[1];g=c.length/(d-b);return a};a.range=function(f){if(!arguments.length)return c;c=f;g=c.length/(d-b);e=c.length-1;return a};return a}; <add>d3.svg={};d3.svg.arc=function(){function a(){var c=b.apply(this,arguments),f=d.apply(this,arguments),h=g.apply(this,arguments)+I,i=e.apply(this,arguments)+I,k=i-h,j=k<Math.PI?"0":"1",o=Math.cos(h);h=Math.sin(h);var p=Math.cos(i);i=Math.sin(i);return k>=db?c?"M0,"+f+"A"+f+","+f+" 0 1,1 0,"+-f+"A"+f+","+f+" 0 1,1 0,"+f+"M0,"+c+"A"+c+","+c+" 0 1,1 0,"+-c+"A"+c+","+c+" 0 1,1 0,"+c+"Z":"M0,"+f+"A"+f+","+f+" 0 1,1 0,"+-f+"A"+f+","+f+" 0 1,1 0,"+f+"Z":c?"M"+f*o+","+f*h+"A"+f+","+f+" 0 "+j+",1 "+f*p+","+ <add>f*i+"L"+c*p+","+c*i+"A"+c+","+c+" 0 "+j+",0 "+c*o+","+c*h+"Z":"M"+f*o+","+f*h+"A"+f+","+f+" 0 "+j+",1 "+f*p+","+f*i+"L0,0Z"}var b=La,d=Ma,g=ja,e=ka;a.innerRadius=function(c){if(!arguments.length)return b;b=v(c);return a};a.outerRadius=function(c){if(!arguments.length)return d;d=v(c);return a};a.startAngle=function(c){if(!arguments.length)return g;g=v(c);return a};a.endAngle=function(c){if(!arguments.length)return e;e=v(c);return a};a.centroid=function(){var c=(b.apply(this,arguments)+d.apply(this, <add>arguments))/2,f=(g.apply(this,arguments)+e.apply(this,arguments))/2+I;return[Math.cos(f)*c,Math.sin(f)*c]};return a};var I=-Math.PI/2,db=2*Math.PI-1.0E-6;d3.svg.line=function(){function a(f){return f.length<1?null:"M"+e($(this,f,b,d),c)}var b=la,d=ma,g="linear",e=P[g],c=0.7;a.x=function(f){if(!arguments.length)return b;b=f;return a};a.y=function(f){if(!arguments.length)return d;d=f;return a};a.interpolate=function(f){if(!arguments.length)return g;e=P[g=f];return a};a.tension=function(f){if(!arguments.length)return c; <add>c=f;return a};return a};var P={linear:H,basis:function(a){if(a.length<3)return H(a);var b=[],d=1,g=a.length,e=a[0],c=e[0],f=e[1],h=[c,c,c,(e=a[1])[0]],i=[f,f,f,e[1]];b.push(c,",",f);for(L(b,h,i);++d<g;){e=a[d];h.shift();h.push(e[0]);i.shift();i.push(e[1]);L(b,h,i)}for(d=-1;++d<2;){h.shift();h.push(e[0]);i.shift();i.push(e[1]);L(b,h,i)}return b.join("")},"basis-closed":function(a){for(var b,d=-1,g=a.length,e=g+4,c,f=[],h=[];++d<4;){c=a[d%g];f.push(c[0]);h.push(c[1])}b=[B(M,f),",",B(M,h)];for(--d;++d< <add>e;){c=a[d%g];f.shift();f.push(c[0]);h.shift();h.push(c[1]);L(b,f,h)}return b.join("")},cardinal:function(a,b){if(a.length<3)return H(a);return a[0]+na(a,oa(a,b))},"cardinal-closed":function(a,b){if(a.length<3)return H(a);return a[0]+na(a,oa([a[a.length-2]].concat(a,[a[1]]),b))}},pa=[0,2/3,1/3,0],qa=[0,1/3,2/3,0],M=[0,1/6,2/3,1/6];d3.svg.area=function(){function a(h){return h.length<1?null:"M"+c($(this,h,b,g),f)+"L"+c($(this,h,b,d).reverse(),f)+"Z"}var b=la,d=Na,g=ma,e="linear",c=P[e],f=0.7;a.x=function(h){if(!arguments.length)return b; <add>b=h;return a};a.y0=function(h){if(!arguments.length)return d;d=h;return a};a.y1=function(h){if(!arguments.length)return g;g=h;return a};a.interpolate=function(h){if(!arguments.length)return e;c=P[e=h];return a};a.tension=function(h){if(!arguments.length)return f;f=h;return a};return a};d3.svg.chord=function(){function a(h,i){var k=b(this,d,h,i),j=b(this,g,h,i);return"M"+k.p0+("A"+k.r+","+k.r+" 0 0,1 "+k.p1)+(k.a0==j.a0&&k.a1==j.a1?"Q 0,0 "+k.p0:"Q 0,0 "+j.p0+("A"+j.r+","+j.r+" 0 0,1 "+j.p1)+("Q 0,0 "+ <add>k.p0))+"Z"}function b(h,i,k,j){var o=i.call(h,k,j);i=e.call(h,o,j);k=c.call(h,o,j)+I;h=f.call(h,o,j)+I;return{r:i,a0:k,a1:h,p0:[i*Math.cos(k),i*Math.sin(k)],p1:[i*Math.cos(h),i*Math.sin(h)]}}var d=Oa,g=Pa,e=Qa,c=ja,f=ka;a.radius=function(h){if(!arguments.length)return e;e=v(h);return a};a.source=function(h){if(!arguments.length)return d;d=v(h);return a};a.target=function(h){if(!arguments.length)return g;g=v(h);return a};a.startAngle=function(h){if(!arguments.length)return c;c=v(h);return a};a.endAngle= <add>function(h){if(!arguments.length)return f;f=v(h);return a};return a};d3.svg.mouse=function(a){var b=(a.ownerSVGElement||a).createSVGPoint();if(ca<0&&(window.scrollX||window.scrollY)){var d=d3.select(document.body).append("svg:svg").style("position","absolute").style("top",0).style("left",0),g=d[0][0].getScreenCTM();ca=!(g.f||g.e);d.remove()}if(ca){b.x=d3.event.pageX;b.y=d3.event.pageY}else{b.x=d3.event.clientX;b.y=d3.event.clientY}b=b.matrixTransform(a.getScreenCTM().inverse());return[b.x,b.y]};var ca= <add>/WebKit/.test(navigator.userAgent)?-1:0;d3.svg.symbol=function(){function a(g,e){return(sa[b.call(this,g,e)]||sa.circle)(d.call(this,g,e))}var b=Sa,d=Ra;a.type=function(g){if(!arguments.length)return b;b=v(g);return a};a.size=function(g){if(!arguments.length)return d;d=v(g);return a};return a};d3.svg.symbolTypes=["circle","cross","diamond","square","triangle-down","triangle-up"];var sa={circle:function(a){a=Math.sqrt(a/Math.PI);return"M0,"+a+"A"+a+","+a+" 0 1,1 0,"+-a+"A"+a+","+a+" 0 1,1 0,"+a+"Z"}, <add>cross:function(a){a=Math.sqrt(a/5)/2;return"M"+-3*a+","+-a+"H"+-a+"V"+-3*a+"H"+a+"V"+-a+"H"+3*a+"V"+a+"H"+a+"V"+3*a+"H"+-a+"V"+a+"H"+-3*a+"Z"},diamond:function(a){a=Math.sqrt(a/(2*ta));var b=a*ta;return"M0,"+-a+"L"+b+",0 0,"+a+" "+-b+",0Z"},square:function(a){a=Math.sqrt(a)/2;return"M"+-a+","+-a+"L"+a+","+-a+" "+a+","+a+" "+-a+","+a+"Z"},"triangle-down":function(a){a=Math.sqrt(a/Q);var b=a*Q/2;return"M0,"+b+"L"+a+","+-b+" "+-a+","+-b+"Z"},"triangle-up":function(a){a=Math.sqrt(a/Q);var b=a*Q/2;return"M0,"+ <add>-b+"L"+a+","+b+" "+-a+","+b+"Z"}},Q=Math.sqrt(3),ta=Math.tan(30*Math.PI/180)})(); <ide><path>src/core/core.js <del>d3 = {version: "1.3.0"}; // semver <add>d3 = {version: "1.4.0"}; // semver <ide><path>src/core/nest.js <ide> d3.nest = function() { <ide> sortValues, <ide> rollup; <ide> <del> function recurse(j, array) { <del> if (j >= keys.length) return rollup <add> function map(array, depth) { <add> if (depth >= keys.length) return rollup <ide> ? rollup.call(nest, array) : (sortValues <ide> ? array.sort(sortValues) <ide> : array); <ide> <ide> var i = -1, <ide> n = array.length, <del> key = keys[j], <add> key = keys[depth++], <ide> keyValue, <del> keyValues = [], <del> sortKey = sortKeys[j], <ide> object, <del> map = {}; <add> o = {}; <ide> <ide> while (++i < n) { <del> if ((keyValue = key(object = array[i])) in map) { <del> map[keyValue].push(object); <add> if ((keyValue = key(object = array[i])) in o) { <add> o[keyValue].push(object); <ide> } else { <del> map[keyValue] = [object]; <del> keyValues.push(keyValue); <add> o[keyValue] = [object]; <ide> } <ide> } <ide> <del> j++; <del> i = -1; <del> n = keyValues.length; <del> while (++i < n) { <del> object = map[keyValue = keyValues[i]]; <del> map[keyValue] = recurse(j, object); <add> for (keyValue in o) { <add> o[keyValue] = map(o[keyValue], depth); <add> } <add> <add> return o; <add> } <add> <add> function entries(map, depth) { <add> if (depth >= keys.length) return map; <add> <add> var a = [], <add> sortKey = sortKeys[depth++], <add> key; <add> <add> for (key in map) { <add> a.push({key: key, values: entries(map[key], depth)}); <ide> } <ide> <del> return map; <add> if (sortKey) a.sort(function(a, b) { <add> return sortKey(a.key, b.key); <add> }); <add> <add> return a; <ide> } <ide> <ide> nest.map = function(array) { <del> return recurse(0, array); <add> return map(array, 0); <add> }; <add> <add> nest.entries = function(array) { <add> return entries(map(array, 0), 0); <ide> }; <ide> <ide> nest.key = function(d) { <ide> keys.push(d); <ide> return nest; <ide> }; <ide> <add> // Specifies the order for the most-recently specified key. <add> // Note: only applies to entries. Map keys are unordered! <ide> nest.sortKeys = function(order) { <ide> sortKeys[keys.length - 1] = order; <ide> return nest; <ide> }; <ide> <add> // Specifies the order for leaf values. <add> // Applies to both maps and entries array. <ide> nest.sortValues = function(order) { <ide> sortValues = order; <ide> return nest;
4
Python
Python
fix typo in merge layer docstring
6ffa6f39e6222c5417f70eea84ebd92e2d6113f5
<ide><path>keras/engine/topology.py <ide> class Merge(Layer): <ide> <ide> ```python <ide> model1 = Sequential() <del> model1.add(Dense(32)) <add> model1.add(Dense(32, input_dim=32)) <ide> <ide> model2 = Sequential() <ide> model2.add(Dense(32))
1
Python
Python
update train_tagger script
01b42c531f7ab0ca81768b6e9833062f9e31ba95
<ide><path>examples/training/train_tagger.py <add>"""A quick example for training a part-of-speech tagger, without worrying <add>about the tokenization, or other language-specific customizations.""" <add> <add>from __future__ import unicode_literals <add>from __future__ import print_function <add> <add>import plac <add>from pathlib import Path <add> <add>from spacy.vocab import Vocab <add>from spacy.tagger import Tagger <add>from spacy.tokens import Doc <add>import random <add> <add> <add># You need to define a mapping from your data's part-of-speech tag names to the <add># Universal Part-of-Speech tag set, as spaCy includes an enum of these tags. <add># See here for the Universal Tag Set: <add># http://universaldependencies.github.io/docs/u/pos/index.html <add># You may also specify morphological features for your tags, from the universal <add># scheme. <add>TAG_MAP = { <add> 'N': {"pos": "NOUN"}, <add> 'V': {"pos": "VERB"}, <add> 'J': {"pos": "ADJ"} <add> } <add> <add># Usually you'll read this in, of course. Data formats vary. <add># Ensure your strings are unicode. <add>DATA = [ <add> ( <add> ["I", "like", "green", "eggs"], <add> ["N", "V", "J", "N"] <add> ), <add> ( <add> ["Eat", "blue", "ham"], <add> ["V", "J", "N"] <add> ) <add>] <add> <add>def ensure_dir(path): <add> if not path.exists(): <add> path.mkdir() <add> <add> <add>def main(output_dir=None): <add> if output_dir is not None: <add> output_dir = Path(output_dir) <add> ensure_dir(output_dir) <add> ensure_dir(output_dir / "pos") <add> ensure_dir(output_dir / "vocab") <add> <add> vocab = Vocab(tag_map=TAG_MAP) <add> # The default_templates argument is where features are specified. See <add> # spacy/tagger.pyx for the defaults. <add> tagger = Tagger.blank(vocab, Tagger.default_templates()) <add> <add> for i in range(5): <add> for words, tags in DATA: <add> doc = Doc(vocab, orths_and_spaces=zip(words, [True] * len(words))) <add> tagger.update(doc, tags) <add> random.shuffle(DATA) <add> tagger.model.end_training() <add> doc = Doc(vocab, orths_and_spaces=zip(["I", "like", "blue", "eggs"], [True]*4)) <add> tagger(doc) <add> for word in doc: <add> print(word.text, word.tag_, word.pos_) <add> if output_dir is not None: <add> tagger.model.dump(str(output_dir / 'pos' / 'model')) <add> with (output_dir / 'vocab' / 'strings.json').open('wb') as file_: <add> tagger.vocab.strings.dump(file_) <add> <add> <add>if __name__ == '__main__': <add> plac.call(main) <add> # I V VERB <add> # like V VERB <add> # blue N NOUN <add> # eggs N NOUN
1
Mixed
Ruby
return just the address if name is blank
524c4cad07e6744da94e4e598a3bf690f20f6f81
<ide><path>actionmailer/CHANGELOG.md <add>* `email_address_with_name` returns just the address if name is blank. <add> <add> *Thomas Hutterer* <add> <add> <ide> ## Rails 7.0.0.alpha2 (September 15, 2021) ## <ide> <ide> * No changes. <ide><path>actionmailer/lib/action_mailer/base.rb <ide> def deliver_mail(mail) # :nodoc: <ide> end <ide> <ide> # Returns an email in the format "Name <email@example.com>". <add> # <add> # If the name is a blank string, it returns just the address. <ide> def email_address_with_name(address, name) <ide> Mail::Address.new.tap do |builder| <ide> builder.address = address <del> builder.display_name = name <add> builder.display_name = name.presence <ide> end.to_s <ide> end <ide> <ide> def mailer_name <ide> end <ide> <ide> # Returns an email in the format "Name <email@example.com>". <add> # <add> # If the name is a blank string, it returns just the address. <ide> def email_address_with_name(address, name) <ide> self.class.email_address_with_name(address, name) <ide> end <ide><path>actionmailer/test/base_test.rb <ide> class BaseTest < ActiveSupport::TestCase <ide> assert_equal("Mikel <mikel@test.lindsaar.net>", email["Reply-To"].value) <ide> end <ide> <add> test "mail() using email_address_with_name with blank string as name" do <add> email = BaseMailer.with_blank_name <add> assert_equal("sunny@example.com", email["To"].value) <add> end <add> <ide> # Custom headers <ide> test "custom headers" do <ide> email = BaseMailer.welcome <ide><path>actionmailer/test/mailers/base_mailer.rb <ide> def with_name <ide> mail(template_name: "welcome", to: to) <ide> end <ide> <add> def with_blank_name <add> to = email_address_with_name("sunny@example.com", "") <add> mail(template_name: "welcome", to: to) <add> end <add> <ide> def html_only(hash = {}) <ide> mail(hash) <ide> end <ide><path>guides/source/action_mailer_basics.md <ide> def welcome_email <ide> end <ide> ``` <ide> <add>If the name is a blank string, it returns just the address. <add> <ide> [`email_address_with_name`]: https://api.rubyonrails.org/classes/ActionMailer/Base.html#method-i-email_address_with_name <ide> <ide> ### Mailer Views
5
Java
Java
remove workaround for reactor netty #171
7746878b5044790a09d926522318d1c1cced397c
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/HttpHeadResponseDecorator.java <ide> */ <ide> public class HttpHeadResponseDecorator extends ServerHttpResponseDecorator { <ide> <add> <ide> public HttpHeadResponseDecorator(ServerHttpResponse delegate) { <ide> super(delegate); <ide> } <ide> public HttpHeadResponseDecorator(ServerHttpResponse delegate) { <ide> */ <ide> @Override <ide> public final Mono<Void> writeWith(Publisher<? extends DataBuffer> body) { <del> // After Reactor Netty #171 is fixed we can return without delegating <del> return getDelegate().writeWith( <del> Flux.from(body) <del> .reduce(0, (current, buffer) -> { <del> int next = current + buffer.readableByteCount(); <del> DataBufferUtils.release(buffer); <del> return next; <del> }) <del> .doOnNext(count -> getHeaders().setContentLength(count)) <del> .then(Mono.empty())); <add> return Flux.from(body) <add> .reduce(0, (current, buffer) -> { <add> int next = current + buffer.readableByteCount(); <add> DataBufferUtils.release(buffer); <add> return next; <add> }) <add> .doOnNext(count -> getHeaders().setContentLength(count)) <add> .then(); <ide> } <ide> <ide> /** <ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/ReactorHttpHandlerAdapter.java <ide> public ReactorHttpHandlerAdapter(HttpHandler httpHandler) { <ide> <ide> <ide> @Override <del> public Mono<Void> apply(HttpServerRequest request, HttpServerResponse response) { <del> NettyDataBufferFactory bufferFactory = new NettyDataBufferFactory(response.alloc()); <del> ServerHttpRequest adaptedRequest; <del> ServerHttpResponse adaptedResponse; <add> public Mono<Void> apply(HttpServerRequest reactorRequest, HttpServerResponse reactorResponse) { <add> NettyDataBufferFactory bufferFactory = new NettyDataBufferFactory(reactorResponse.alloc()); <ide> try { <del> adaptedRequest = new ReactorServerHttpRequest(request, bufferFactory); <del> adaptedResponse = new ReactorServerHttpResponse(response, bufferFactory); <add> ServerHttpRequest request = new ReactorServerHttpRequest(reactorRequest, bufferFactory); <add> ServerHttpResponse response = new ReactorServerHttpResponse(reactorResponse, bufferFactory); <add> <add> if (request.getMethod() == HttpMethod.HEAD) { <add> response = new HttpHeadResponseDecorator(response); <add> } <add> <add> String logPrefix = ((ReactorServerHttpRequest) request).getLogPrefix(); <add> <add> return this.httpHandler.handle(request, response) <add> .doOnError(ex -> logger.trace(logPrefix + "Failed to complete: " + ex.getMessage())) <add> .doOnSuccess(aVoid -> logger.trace(logPrefix + "Handling completed")); <ide> } <ide> catch (URISyntaxException ex) { <ide> if (logger.isDebugEnabled()) { <ide> logger.debug("Failed to get request URI: " + ex.getMessage()); <ide> } <del> response.status(HttpResponseStatus.BAD_REQUEST); <add> reactorResponse.status(HttpResponseStatus.BAD_REQUEST); <ide> return Mono.empty(); <ide> } <del> <del> String logPrefix = ((ReactorServerHttpRequest) adaptedRequest).getLogPrefix(); <del> <del> if (adaptedRequest.getMethod() == HttpMethod.HEAD) { <del> adaptedResponse = new HttpHeadResponseDecorator(adaptedResponse); <del> } <del> <del> return this.httpHandler.handle(adaptedRequest, adaptedResponse) <del> .doOnError(ex -> logger.trace(logPrefix + "Failed to complete: " + ex.getMessage())) <del> .doOnSuccess(aVoid -> logger.trace(logPrefix + "Handling completed")); <ide> } <ide> <ide> }
2
Javascript
Javascript
define abort on prototype
1c99cdebbc014dddde89159c24ed37cfcf1aafe1
<ide><path>lib/internal/abort_controller.js <ide> ObjectDefineProperties(AbortSignal.prototype, { <ide> aborted: { enumerable: true } <ide> }); <ide> <add>defineEventHandler(AbortSignal.prototype, 'abort'); <add> <ide> function abortSignal(signal) { <ide> if (signal[kAborted]) return; <ide> signal[kAborted] = true; <ide> class AbortController { <ide> constructor() { <ide> this[kSignal] = new AbortSignal(); <ide> emitExperimentalWarning('AbortController'); <del> defineEventHandler(this[kSignal], 'abort'); <ide> } <ide> <ide> get signal() { return this[kSignal]; } <ide><path>lib/internal/event_target.js <ide> const { <ide> ArrayFrom, <ide> Boolean, <ide> Error, <del> Map, <ide> NumberIsInteger, <ide> ObjectAssign, <ide> ObjectDefineProperties, <ide> ObjectDefineProperty, <ide> ObjectGetOwnPropertyDescriptor, <add> SafeMap, <ide> String, <ide> Symbol, <ide> SymbolFor, <ide> SymbolToStringTag, <del> SafeWeakMap, <ide> SafeWeakSet, <ide> } = primordials; <ide> <ide> const kIsEventTarget = SymbolFor('nodejs.event_target'); <ide> const kEvents = Symbol('kEvents'); <ide> const kStop = Symbol('kStop'); <ide> const kTarget = Symbol('kTarget'); <add>const kHandlers = Symbol('khandlers'); <ide> <ide> const kHybridDispatch = SymbolFor('nodejs.internal.kHybridDispatch'); <ide> const kCreateEvent = Symbol('kCreateEvent'); <ide> class Listener { <ide> } <ide> <ide> function initEventTarget(self) { <del> self[kEvents] = new Map(); <add> self[kEvents] = new SafeMap(); <ide> } <ide> <ide> class EventTarget { <ide> function emitUnhandledRejectionOrErr(that, err, event) { <ide> process.emit('error', err, event); <ide> } <ide> <del>// A map of emitter -> map of name -> handler <del>const eventHandlerValueMap = new SafeWeakMap(); <del> <ide> function defineEventHandler(emitter, name) { <ide> // 8.1.5.1 Event handlers - basically `on[eventName]` attributes <ide> ObjectDefineProperty(emitter, `on${name}`, { <ide> get() { <del> return eventHandlerValueMap.get(this)?.get(name); <add> return this[kHandlers]?.get(name); <ide> }, <ide> set(value) { <del> const oldValue = eventHandlerValueMap.get(this)?.get(name); <add> const oldValue = this[kHandlers]?.get(name); <ide> if (oldValue) { <ide> this.removeEventListener(name, oldValue); <ide> } <ide> if (typeof value === 'function') { <ide> this.addEventListener(name, value); <ide> } <del> if (!eventHandlerValueMap.has(this)) { <del> eventHandlerValueMap.set(this, new Map()); <add> if (!this[kHandlers]) { <add> this[kHandlers] = new SafeMap(); <ide> } <del> eventHandlerValueMap.get(this).set(name, value); <add> this[kHandlers].set(name, value); <ide> }, <ide> configurable: true, <ide> enumerable: true <ide><path>lib/internal/worker/io.js <ide> ObjectDefineProperty( <ide> // This is called from inside the `MessagePort` constructor. <ide> function oninit() { <ide> initNodeEventTarget(this); <del> defineEventHandler(this, 'message'); <del> defineEventHandler(this, 'messageerror'); <ide> setupPortReferencing(this, this, 'message'); <ide> } <ide>
3
Ruby
Ruby
add some assertions for bigdecimal#to_s
330e011c6c7a56a09e7f26db8750a19ca7865261
<ide><path>activesupport/test/core_ext/bigdecimal_test.rb <ide> class BigDecimalTest < ActiveSupport::TestCase <ide> def test_to_s <ide> bd = BigDecimal.new '0.01' <ide> assert_equal '0.01', bd.to_s <add> assert_equal '+0.01', bd.to_s('+F') <add> assert_equal '+0.0 1', bd.to_s('+1F') <ide> end <ide> end
1
PHP
PHP
add json alias for decoderesponsejson method
c2245992497b78c24ee912e5f6e09625258db5c4
<ide><path>src/Illuminate/Foundation/Testing/TestResponse.php <ide> public function decodeResponseJson() <ide> return $decodedResponse; <ide> } <ide> <add> /** <add> * Alias for the "decodeResponseJson" method. <add> * <add> * @return array <add> */ <add> public function json() <add> { <add> return $this->decodeResponseJson(); <add> } <add> <ide> /** <ide> * Assert that the response view has a given piece of bound data. <ide> *
1
Python
Python
add default value if hddtemp return non int
42efd95483b326f918d1c09744bbd5113f77e3a6
<ide><path>glances/glances.py <ide> def __update__(self): <ide> hddtemp_current['value'] = 0 <ide> else: <ide> hddtemp_current['label'] = fields[offset + 1].split("/")[-1] <del> hddtemp_current['value'] = int(temperature) <add> try: <add> hddtemp_current['value'] = int(temperature) <add> except TypeError: <add> hddtemp_current['label'] = fields[offset + 1].split("/")[-1] + " is unknown" <add> hddtemp_current['value'] = 0 <ide> self.hddtemp_list.append(hddtemp_current) <ide> <ide> def get(self):
1
Ruby
Ruby
reset column info after making topic tz-aware
08e78ad4ae1507a9ed70f3784370febd84a49592
<ide><path>activerecord/test/cases/attribute_methods_test.rb <ide> def topic.title() "b" end <ide> record.written_on = "Jan 01 00:00:00 2014" <ide> assert_equal record, YAML.load(YAML.dump(record)) <ide> end <add> ensure <add> # NOTE: Reset column info because global topics <add> # don't have tz-aware attributes by default. <add> Topic.reset_column_information <ide> end <ide> <ide> test "setting a time zone-aware time in the current time zone" do
1
Java
Java
improve javadoc of serverhttprequest#getpath
0ff50d6d9e8857063d36d590cf67bb9ccf69d5ec
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/ServerHttpRequest.java <ide> /* <del> * Copyright 2002-2020 the original author or authors. <add> * Copyright 2002-2021 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public interface ServerHttpRequest extends HttpRequest, ReactiveHttpInputMessage <ide> String getId(); <ide> <ide> /** <del> * Returns a structured representation of the request path including the <del> * context path + path within application portions, path segments with <del> * encoded and decoded values, and path parameters. <add> * Returns a structured representation of the full request path up to but <add> * not including the {@link #getQueryParams() query}. <add> * <p>The returned path is sub-divided into a <add> * {@link RequestPath#contextPath()} portion and the remaining <add> * {@link RequestPath#pathWithinApplication() pathwithinApplication} portion. <add> * The latter can be passed into methods of <add> * {@link org.springframework.web.util.pattern.PathPattern} for path <add> * matching purposes. <ide> */ <ide> RequestPath getPath(); <ide>
1
Javascript
Javascript
fix strict regression
8578fe22a973848b4303f915371b98153ed50d44
<ide><path>lib/assert.js <ide> assert.ifError = function ifError(err) { if (err) throw err; }; <ide> <ide> // Expose a strict only variant of assert <ide> function strict(value, message) { <del> if (!value) innerFail(value, true, message, '==', strict); <add> if (!value) { <add> innerFail({ <add> actual: value, <add> expected: true, <add> message, <add> operator: '==', <add> stackStartFn: strict <add> }); <add> } <ide> } <ide> assert.strict = Object.assign(strict, assert, { <ide> equal: assert.strictEqual, <ide><path>test/parallel/test-assert.js <ide> common.expectsError( <ide> assert.equal(Object.keys(assert).length, Object.keys(a).length); <ide> /* eslint-enable no-restricted-properties */ <ide> assert(7); <add> common.expectsError( <add> () => assert(), <add> { <add> code: 'ERR_ASSERTION', <add> type: assert.AssertionError, <add> message: 'undefined == true' <add> } <add> ); <ide> } <ide> <ide> common.expectsError(
2
Ruby
Ruby
join any extra args to the tmp path
7b6efb9cda9571d4d764c55a6ce100b04f172a8e
<ide><path>railties/test/isolation/abstract_unit.rb <ide> def app_template_path <ide> <ide> def tmp_path(*args) <ide> @tmp_path ||= File.realpath(Dir.mktmpdir) <add> File.join(@tmp_path, *args) <ide> end <ide> <ide> def app_path(*args)
1
Text
Text
fix logo path
534a991cff405a469754f6afc4fd8aa4be79e444
<ide><path>README.md <ide> Platform-as-a-Service. It benefits directly from the experience <ide> accumulated over several years of large-scale operation and support of <ide> hundreds of thousands of applications and databases. <ide> <del>![Docker L](docs/sources/static_files/dockerlogo-h.png "Docker") <add>![Docker L](docs/theme/docker/static/img/dockerlogo-h.png "Docker") <ide> <ide> ## Better than VMs <ide>
1
PHP
PHP
fix code standards
5bb8c3a942cd35c89e335d4c12317d06375b1bfb
<ide><path>lib/Cake/Test/Case/View/ViewTest.php <ide> public function testRenderUsingViewProperty() { <ide> * <ide> * @return void <ide> */ <del> public function testGetViewFileNameSubdirWithPluginAndViewPath() <del> { <add> public function testGetViewFileNameSubdirWithPluginAndViewPath() { <ide> $this->PostsController->plugin = 'TestPlugin'; <ide> $this->PostsController->viewPath = 'Elements'; <ide> $this->PostsController->name = 'Posts'; <ide> $View = new TestView($this->PostsController); <del> <add> <ide> $expected = CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS . 'TestPlugin' . <ide> DS . 'View' . DS . 'Elements' . DS . 'sub_dir' . DS . 'sub_element.ctp'; <ide> $this->assertEquals($expected, $View->getViewFileName('sub_dir/sub_element'));
1
Ruby
Ruby
implement hash equality on column
e13ac306a09611c2d7f7e3ca813e8409d7dfc834
<ide><path>activerecord/lib/active_record/connection_adapters/column.rb <ide> def ==(other) <ide> other.sql_type == sql_type && <ide> other.null == null <ide> end <add> alias :eql? :== <add> <add> def hash <add> [self.class, name, default, cast_type, sql_type, null].hash <add> end <ide> end <ide> end <ide> # :startdoc:
1
Ruby
Ruby
remove block definitions in finder methods
2c203a94136d5b8681e2b2b55783ef6dde54405f
<ide><path>activerecord/lib/active_record/relation/finder_methods.rb <ide> module FinderMethods <ide> # person.visits += 1 <ide> # person.save! <ide> # end <del> def find(*args, &block) <del> return to_a.find(&block) if block_given? <add> def find(*args) <add> return to_a.find { |*block_args| yield(*block_args) } if block_given? <ide> <ide> options = args.extract_options! <ide> <ide> def find_or_instantiator_by_attributes(match, attributes, *args) <ide> record <ide> end <ide> <del> def find_with_ids(*ids, &block) <del> return to_a.find(&block) if block_given? <add> def find_with_ids(*ids) <add> return to_a.find { |*block_args| yield(*block_args) } if block_given? <ide> <ide> expects_array = ids.first.kind_of?(Array) <ide> return ids.first if expects_array && ids.first.empty?
1
Python
Python
handle mingw module compilation in py2.7 venvs
a2b416f60e6f3f2746bf3edaf8e6161204f528a5
<ide><path>numpy/distutils/mingw32ccompiler.py <ide> def find_python_dll(): <ide> # We can't do much here: <ide> # - find it in the virtualenv (sys.prefix) <ide> # - find it in python main dir (sys.base_prefix, if in a virtualenv) <add> # - sys.real_prefix is main dir for virtualenvs in Python 2.7 <ide> # - in system32, <ide> # - ortherwise (Sxs), I don't know how to get it. <ide> stems = [sys.prefix] <ide> if hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix: <ide> stems.append(sys.base_prefix) <add> elif hasattr(sys, 'real_prefix') and sys.real_prefix != sys.prefix: <add> stems.append(sys.real_prefix) <ide> <ide> sub_dirs = ['', 'lib', 'bin'] <ide> # generate possible combinations of directory trees and sub-directories <ide> def _check_for_import_lib(): <ide> stems = [sys.prefix] <ide> if hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix: <ide> stems.append(sys.base_prefix) <add> elif hasattr(sys, 'real_prefix') and sys.real_prefix != sys.prefix: <add> stems.append(sys.real_prefix) <ide> <ide> # possible subdirectories within those trees where it is placed <ide> sub_dirs = ['libs', 'lib'] <ide> def _build_import_library_x86(): <ide> lib_file = os.path.join(sys.prefix, 'libs', lib_name) <ide> if not os.path.isfile(lib_file): <ide> # didn't find library file in virtualenv, try base distribution, too, <del> # and use that instead if found there <add> # and use that instead if found there. for Python 2.7 venvs, the base <add> # directory is in attribute real_prefix instead of base_prefix. <ide> if hasattr(sys, 'base_prefix'): <ide> base_lib = os.path.join(sys.base_prefix, 'libs', lib_name) <add> elif hasattr(sys, 'real_prefix'): <add> base_lib = os.path.join(sys.real_prefix, 'libs', lib_name) <ide> else: <ide> base_lib = '' # os.path.isfile('') == False <ide>
1
Ruby
Ruby
add missing @tap check
d8a2a90daccfb23705ef9eada2f49b800ec2c9ee
<ide><path>Library/Homebrew/dev-cmd/test-bot.rb <ide> def homebrew <ide> # test no-op update from current commit (to current commit, a no-op). <ide> test "brew", "update-test", "--commit=HEAD" <ide> end <del> else <add> elsif @tap <ide> test "brew", "readall", "--aliases", @tap.name <ide> end <ide> end
1
Javascript
Javascript
expose pointereventsexample to android
098a1163b1905b2cb3e0a36e4d75508d9a969c5e
<ide><path>Examples/UIExplorer/UIExplorerList.js <ide> var COMMON_APIS = [ <ide> require('./GeolocationExample'), <ide> require('./LayoutExample'), <ide> require('./PanResponderExample'), <add> require('./PointerEventsExample'), <ide> ]; <ide> <ide> if (Platform.OS === 'ios') { <ide> if (Platform.OS === 'ios') { <ide> require('./CameraRollExample.ios'), <ide> require('./LayoutEventsExample'), <ide> require('./NetInfoExample'), <del> require('./PointerEventsExample'), <ide> require('./PushNotificationIOSExample'), <ide> require('./StatusBarIOSExample'), <ide> require('./TimerExample'),
1
Javascript
Javascript
fix missing dot
2209226c7c69b7cb1ded9f84d2bfdcd6034a01f6
<ide><path>lib/helpers/buildUrl.js <ide> function encode(val) { <ide> replace(/%3A/gi, ':'). <ide> replace(/%24/g, '$'). <ide> replace(/%2C/gi, ','). <del> replace(/%20/g, '+') <add> replace(/%20/g, '+'). <ide> replace(/%5B/gi, '['). <ide> replace(/%5D/gi, ']'); <ide> }
1
PHP
PHP
add guard method
e422cedb76bfb689ea3873b37fdb8e4af9d81f79
<ide><path>src/Illuminate/Session/Middleware/AuthenticateSession.php <ide> public function __construct(AuthFactory $auth) <ide> */ <ide> public function handle($request, Closure $next) <ide> { <add> $guard = $this->guard(); <add> <ide> if (! $request->hasSession() || ! $request->user()) { <ide> return $next($request); <ide> } <ide> <del> if ($this->auth->viaRemember()) { <del> $passwordHash = explode('|', $request->cookies->get($this->auth->getRecallerName()))[2]; <add> if ($guard->viaRemember()) { <add> $passwordHash = explode('|', $request->cookies->get($guard->getRecallerName()))[2]; <ide> <ide> if ($passwordHash != $request->user()->getAuthPassword()) { <ide> $this->logout($request); <ide> protected function storePasswordHashInSession($request) <ide> */ <ide> protected function logout($request) <ide> { <del> $this->auth->logoutCurrentDevice(); <add> $this->guard()->logoutCurrentDevice(); <ide> <ide> $request->session()->flush(); <ide> <ide> throw new AuthenticationException('Unauthenticated.', [$this->auth->getDefaultDriver()]); <ide> } <add> <add> /** <add> * Get the guard instance that should be used by the middleware. <add> * <add> * @return \Illuminate\Contracts\Auth\Factory|\Illuminate\Contracts\Auth\Guard <add> */ <add> protected function guard() <add> { <add> return $this->auth; <add> } <ide> }
1
Text
Text
add russian translation
98a55637cac6f97421d5335ca8c679c668f6662b
<ide><path>curriculum/challenges/russian/03-front-end-libraries/jquery/target-the-parent-of-an-element-using-jquery.russian.md <ide> id: bad87fee1348bd9aed308826 <ide> title: Target the Parent of an Element Using jQuery <ide> challengeType: 6 <ide> videoUrl: '' <del>localeTitle: Задайте родительский элемент элемента с помощью jQuery <add>localeTitle: Задайте родителя элемента с помощью jQuery <ide> --- <ide> <ide> ## Description <del>undefined <add>Каждый HTML элемент имеет `родительский` элемент, от которого он `наследует` свойства. <add> <add>Например, ваш элемент `jQuery Playground h3` имеет родительский элемент `<div class="container-fluid">`, который в свою очередь имеет в качестве родителя `body`. <add> <add>В jQuery есть функция называющаяся `parent()`, которая позволяет вам получить доступ к родителю любого элемента, который вы выбрали. <add> <add>Вот пример того, как бы вы использовали функцию `parent()`, если бы вы захотели дать синий фон родительскому элементу элемента `left-well`. <add> <add>`$("#left-well").parent().css("background-color", "blue")` <ide> <ide> ## Instructions <ide> <section id="instructions">
1
PHP
PHP
fix doc strings
829b572d8d2d9f61826314022bf9f98cba1a438d
<ide><path>src/Cache/Engine/ApcuEngine.php <ide> public function set($key, $value, $ttl = null) <ide> * <ide> * @param string $key Identifier for the data <ide> * @param mixed $default Default value in case the cache misses. <del> * @return mixed The cached data, or false if the data doesn't exist, <add> * @return mixed The cached data, or default if the data doesn't exist, <ide> * has expired, or if there was an error fetching it <ide> * @link https://secure.php.net/manual/en/function.apcu-fetch.php <ide> */ <ide><path>src/Cache/Engine/FileEngine.php <ide> public function set($key, $data, $ttl = null) <ide> * <ide> * @param string $key Identifier for the data <ide> * @param mixed $default Default value to return if the key does not exist. <del> * @return mixed The cached data, or null if the data doesn't exist, has <add> * @return mixed The cached data, or default value if the data doesn't exist, has <ide> * expired, or if there was an error fetching it <ide> */ <ide> public function get($key, $default = null) <ide><path>src/Cache/Engine/MemcachedEngine.php <ide> public function setMultiple($data, $ttl = null): bool <ide> * <ide> * @param string $key Identifier for the data <ide> * @param mixed $default Default value to return if the key does not exist. <del> * @return mixed The cached data, or false if the data doesn't exist, has <add> * @return mixed The cached data, or default value if the data doesn't exist, has <ide> * expired, or if there was an error fetching it. <ide> */ <ide> public function get($key, $default = null)
3
Ruby
Ruby
fix documentation based on feedback
1cec4e1bbaba786aa4ea70a0e2b6ad6f15ec1e68
<ide><path>activerecord/lib/active_record/persistence.rb <ide> def instantiate(attributes, column_types = {}, &block) <ide> instantiate_instance_of(klass, attributes, column_types, &block) <ide> end <ide> <del> # Given a class, an attributes hash, +instantiate+ returns a new instance <del> # of the class. Accepts only keys as strings. <add> # Given a class, an attributes hash, +instantiate_instance_of+ returns a <add> # new instance of the class. Accepts only keys as strings. <add> # <add> # This is private, don't call it. :) <add> # <add> # :nodoc: <ide> def instantiate_instance_of(klass, attributes, column_types = {}, &block) <ide> attributes = klass.attributes_builder.build_from_database(attributes, column_types) <ide> klass.allocate.init_from_db(attributes, &block) <ide><path>activerecord/lib/active_record/result.rb <ide> def initialize(columns, rows, column_types = {}) <ide> @column_types = column_types <ide> end <ide> <del> # Does this result set include the column named +name+ ? <add> # Returns true if this result set includes the column named +name+ <ide> def includes_column?(name) <ide> @columns.include? name <ide> end
2
PHP
PHP
add fullpath option
fd77f752a2dd73e277f3b3187a9a9facf85913b6
<ide><path>src/Illuminate/Database/Console/Migrations/MigrateMakeCommand.php <ide> class MigrateMakeCommand extends BaseCommand <ide> {--create= : The table to be created} <ide> {--table= : The table to migrate} <ide> {--path= : The location where the migration file should be created} <del> {--realpath : Indicate any provided migration file paths are pre-resolved absolute paths}'; <add> {--realpath : Indicate any provided migration file paths are pre-resolved absolute paths} <add> {--fullpath : Output the full path of the migration}'; <ide> <ide> /** <ide> * The console command description. <ide> public function handle() <ide> */ <ide> protected function writeMigration($name, $table, $create) <ide> { <del> $file = pathinfo($this->creator->create( <add> $file = $this->creator->create( <ide> $name, $this->getMigrationPath(), $table, $create <del> ), PATHINFO_FILENAME); <add> ); <add> <add> if (!$this->option('fullpath')) { <add> $file = pathinfo($file, PATHINFO_FILENAME); <add> } <ide> <ide> $this->line("<info>Created Migration:</info> {$file}"); <ide> }
1
Python
Python
add exotic inputs to identity test
f184db8c53f547a3d48460e4992b12a5a87a2683
<ide><path>tests/auto/keras/test_constraints.py <ide> def test_maxnorm(self): <ide> x_normed_actual = norm_instance(x).eval() <ide> assert_allclose(x_normed_actual, x_normed_target) <ide> <del> <ide> def test_nonneg(self): <ide> from keras.constraints import nonneg <ide> <ide> def test_identity(self): <ide> normed = identity(self.example_array) <ide> assert (np.all(normed == self.example_array)) <ide> <add> def test_identity_oddballs(self): <add> """ <add> test the identity constraint on some more exotic input. <add> this does not need to pass for the desired real life behaviour, <add> but it should in the current implementation. <add> """ <add> from keras.constraints import identity <add> <add> oddball_examples = ["Hello", [1], -1, None] <add> assert(oddball_examples == identity(oddball_examples)) <add> <ide> def test_unitnorm(self): <ide> from keras.constraints import unitnorm <ide>
1
Ruby
Ruby
reset column info when messing with columns
cf115d2f8ef48764e095aa453f729b60705088f1
<ide><path>activerecord/test/cases/session_store/session_test.rb <ide> def test_create_table! <ide> end <ide> <ide> def test_find_by_sess_id_compat <add> Session.reset_column_information <ide> klass = Class.new(Session) do <ide> def self.session_id_column <ide> 'sessid' <ide> def self.session_id_column <ide> assert_equal session.sessid, found.session_id <ide> ensure <ide> klass.drop_table! <add> Session.reset_column_information <ide> end <ide> <ide> def test_find_by_session_id
1
Javascript
Javascript
remove some `getdomnode` from docs and examples
5561d0e9256d6337f24789f14a50ec2beb747f79
<ide><path>docs/_js/examples/markdown.js <ide> var MarkdownEditor = React.createClass({ <ide> return {value: 'Type some *markdown* here!'}; <ide> }, <ide> handleChange: function() { <del> this.setState({value: this.refs.textarea.getDOMNode().value}); <add> this.setState({value: React.findDOMNode(this.refs.textarea).value}); <ide> }, <ide> render: function() { <ide> return ( <ide><path>docs/_js/live_editor.js <ide> var CodeMirrorEditor = React.createClass({ <ide> componentDidMount: function() { <ide> if (IS_MOBILE) return; <ide> <del> this.editor = CodeMirror.fromTextArea(this.refs.editor.getDOMNode(), { <add> this.editor = CodeMirror.fromTextArea(React.findDOMNode(this.refs.editor), { <ide> mode: 'javascript', <ide> lineNumbers: this.props.lineNumbers, <ide> lineWrapping: true, <ide> var ReactPlayground = React.createClass({ <ide> }, <ide> <ide> executeCode: function() { <del> var mountNode = this.refs.mount.getDOMNode(); <add> var mountNode = React.findDOMNode(this.refs.mount); <ide> <ide> try { <ide> React.unmountComponentAtNode(mountNode); <ide><path>examples/jquery-bootstrap/js/app.js <ide> var BootstrapModal = React.createClass({ <ide> // integrate Bootstrap or jQuery with the components lifecycle methods. <ide> componentDidMount: function() { <ide> // When the component is added, turn it into a modal <del> $(this.getDOMNode()) <del> .modal({backdrop: 'static', keyboard: false, show: false}) <add> $(React.findDOMNode(this)) <add> .modal({backdrop: 'static', keyboard: false, show: false}); <ide> }, <ide> componentWillUnmount: function() { <del> $(this.getDOMNode()).off('hidden', this.handleHidden); <add> $(React.findDOMNode(this)).off('hidden', this.handleHidden); <ide> }, <ide> close: function() { <del> $(this.getDOMNode()).modal('hide'); <add> $(React.findDOMNode(this)).modal('hide'); <ide> }, <ide> open: function() { <del> $(this.getDOMNode()).modal('show'); <add> $(React.findDOMNode(this)).modal('show'); <ide> }, <ide> render: function() { <ide> var confirmButton = null;
3
Python
Python
convert other inputs to array
7916d567f2057b2d1e4d8d10f031c9b260c4df7f
<ide><path>numpy/lib/shape_base.py <ide> def kron(a, b): <ide> bs = (1,)*max(0, nda-ndb) + bs <ide> <ide> # Compute the product <del> result = a.reshape(a.size, 1) * b.reshape(1, b.size) <add> a_arr = _nx.asarray(a).reshape(a.size, 1) <add> b_arr = _nx.asarray(b).reshape(1, b.size) <add> result = a_arr * b_arr <ide> <ide> # Reshape back <ide> result = result.reshape(as_+bs) <del> transposer = _nx.arange(nd*2).reshape([2, nd]).transpose().reshape(nd*2) <add> transposer = _nx.arange(nd*2).reshape([2, nd]).ravel(order='f') <ide> result = result.transpose(transposer) <ide> result = result.reshape(_nx.multiply(as_, bs)) <ide>
1
PHP
PHP
add fresh method to model
34f63cbdd84f686aba9283ec0c95be986fb06678
<ide><path>src/Illuminate/Database/Eloquent/Model.php <ide> public static function findOrFail($id, $columns = array('*')) <ide> throw (new ModelNotFoundException)->setModel(get_called_class()); <ide> } <ide> <add> /** <add> * Reload a fresh model instance from the database. <add> * <add> * @param array $with <add> * @return $this <add> */ <add> public function fresh(array $with = array()) <add> { <add> $key = $this->getKeyName(); <add> <add> return $this->exists ? static::with($with)->where($key, $this->getKey())->first() : null; <add> } <add> <ide> /** <ide> * Eager load relations on the model. <ide> *
1
Text
Text
add changelog entry
43eabac605fedae72bd885c1d3861a6d1bfad3e0
<ide><path>activerecord/CHANGELOG.md <add>* Add `reselect` method. This is short-hand for `unscope(:select).select(fields)`. <add> <add> *Willian Gustavo Veiga* <add> <ide> * Added `index` option for `change_table` migration helpers. <ide> With this change you can create indexes while adding new <ide> columns into the existing tables.
1
Javascript
Javascript
remove check for global.process
59711abf54961ab795b1d4adb67af1f5d6e9d3fc
<ide><path>lib/internal/util.js <ide> const codesWarned = {}; <ide> // Returns a modified function which warns once by default. <ide> // If --no-deprecation is set, then it is a no-op. <ide> function deprecate(fn, msg, code) { <del> // Allow for deprecating things in the process of starting up. <del> if (global.process === undefined) { <del> return function(...args) { <del> return deprecate(fn, msg).apply(this, args); <del> }; <del> } <del> <ide> if (process.noDeprecation === true) { <ide> return fn; <ide> }
1
Python
Python
define contants and test for error states
6d01dda509b0df827252f3106f8bfb7e933c3ad7
<ide><path>libcloud/storage/drivers/digitalocean_spaces.py <ide> # limitations under the License. <ide> <ide> from libcloud.common.types import LibcloudError <del>from libcloud.common.aws import SignedAWSConnection, DEFAULT_SIGNATURE_VERSION <add>from libcloud.common.aws import SignedAWSConnection <ide> from libcloud.storage.drivers.s3 import BaseS3Connection, S3Connection <del>from libcloud.storage.drivers.s3 import S3StorageDriver, API_VERSION <add>from libcloud.storage.drivers.s3 import S3StorageDriver <ide> <ide> __all__ = [ <ide> 'DigitalOceanSpacesStorageDriver' <ide> ] <ide> <ide> DO_SPACES_HOSTS_BY_REGION = {'nyc3': 'nyc3.digitaloceanspaces.com'} <del> <ide> DO_SPACES_DEFAULT_REGION = 'nyc3' <add>DEFAULT_SIGNATURE_VERSION = '2' <add>S3_API_VERSION = '2006-03-01' <ide> <ide> <ide> class DOSpacesConnectionAWS4(SignedAWSConnection, BaseS3Connection): <ide> service_name = 's3' <del> version = API_VERSION <add> version = S3_API_VERSION <ide> <ide> def __init__(self, user_id, key, secure=True, host=None, port=None, <ide> url=None, timeout=None, proxy_url=None, token=None, <ide> def __init__(self, user_id, key, secure=True, host=None, port=None, <ide> proxy_url, token, <ide> retry_delay, <ide> backoff, <del> 4) # force aws4 <add> signature_version=4) <ide> <ide> <ide> class DOSpacesConnectionAWS2(S3Connection): <ide> def __init__(self, key, secret=None, secure=True, host=None, port=None, <ide> self.signature_version = str(kwargs.pop('signature_version', <ide> DEFAULT_SIGNATURE_VERSION)) <ide> <del> if self.signature_version not in ['2', '4']: <del> raise ValueError('Invalid signature_version: %s' % <del> (self.signature_version)) <del> <ide> if self.signature_version == '2': <ide> self.connectionCls = DOSpacesConnectionAWS2 <ide> elif self.signature_version == '4': <ide> self.connectionCls = DOSpacesConnectionAWS4 <add> else: <add> raise ValueError('Invalid signature_version: %s' % <add> (self.signature_version)) <ide> self.connectionCls.host = host <ide> <ide> super(DigitalOceanSpacesStorageDriver, <ide><path>libcloud/test/storage/test_digitalocean_spaces.py <ide> import sys <ide> import unittest <ide> <add>from libcloud.common.types import LibcloudError <add> <ide> from libcloud.storage.base import Container, Object <ide> from libcloud.storage.drivers.digitalocean_spaces import ( <ide> DigitalOceanSpacesStorageDriver, <ide> def test_object_get_cdn_url_not_implemented(self): <ide> with self.assertRaises(NotImplementedError): <ide> self.object.get_cdn_url() <ide> <add> def test_invalid_signature_version(self): <add> with self.assertRaises(ValueError): <add> self.driver_type(*self.driver_args, <add> signature_version='3', <add> host=self.default_host) <add> <add> def test_invalid_region(self): <add> with self.assertRaises(LibcloudError): <add> self.driver_type(*self.driver_args, <add> region='atlantis', <add> host=self.default_host) <add> <ide> <ide> class DigitalOceanSpacesTests_v4(DigitalOceanSpacesTests): <ide> driver_type = DigitalOceanSpacesStorageDriver
2
Javascript
Javascript
add support for disabling max length limit
5c1fdff691b9367d73f72f6a0298cb6a6e259f35
<ide><path>src/ng/directive/input.js <ide> var maxlengthDirective = function() { <ide> ctrl.$validate(); <ide> }); <ide> ctrl.$validators.maxlength = function(modelValue, viewValue) { <del> return ctrl.$isEmpty(modelValue) || viewValue.length <= maxlength; <add> return (maxlength < 0) || ctrl.$isEmpty(modelValue) || (viewValue.length <= maxlength); <ide> }; <ide> } <ide> }; <ide><path>test/ng/directive/inputSpec.js <ide> describe('input', function() { <ide> expect(inputElm).toBeValid(); <ide> }); <ide> <add> it('should accept values of any length when maxlength is negative', function() { <add> compileInput('<input type="text" ng-model="value" ng-maxlength="-1" />'); <add> <add> changeInputValueTo(''); <add> expect(inputElm).toBeValid(); <add> <add> changeInputValueTo('aaaaaaaaaa'); <add> expect(inputElm).toBeValid(); <add> }); <add> <ide> it('should listen on ng-maxlength when maxlength is observed', function() { <ide> var value = 0; <ide> compileInput('<input type="text" ng-model="value" ng-maxlength="max" attr-capture />');
2
Javascript
Javascript
fix typo in require
208f4ea18fbd0a23f157d826a5d2255bcd314d19
<ide><path>server/server.js <ide> var R = require('ramda'), <ide> secrets = require('./../config/secrets'); <ide> <ide> var generateKey = <del> require('loopback-component-passport/models/utils').generateKey; <add> require('loopback-component-passport/lib/models/utils').generateKey; <ide> /** <ide> * Create Express server. <ide> */
1
Ruby
Ruby
check has_option? for universal and 32-bit
26b1b88c974cc902b0e9c2c2b8d17a16335d8462
<ide><path>Library/Homebrew/formula_support.rb <ide> def stable? <ide> <ide> # True if the user requested a universal build. <ide> def universal? <del> @args.include? '--universal' <add> @args.include?('--universal') && has_option?('universal') <ide> end <ide> <ide> # Request a 32-bit only build. <ide> # This is needed for some use-cases though we prefer to build Universal <ide> # when a 32-bit version is needed. <ide> def build_32_bit? <del> @args.include? '--32-bit' <add> @args.include?('--32-bit') && has_option?('32-bit') <ide> end <ide> <ide> def used_options
1
PHP
PHP
apply fixes from styleci
0b8b18bfc1d8ecb1b2d7027629c1ea38f6508af6
<ide><path>tests/Integration/Foundation/DiscoverEventsTest.php <ide> use Illuminate\Tests\Integration\Foundation\Fixtures\EventDiscovery\Events\EventOne; <ide> use Illuminate\Tests\Integration\Foundation\Fixtures\EventDiscovery\Events\EventTwo; <ide> use Illuminate\Tests\Integration\Foundation\Fixtures\EventDiscovery\Listeners\Listener; <del>use Tests\Integration\Foundation\Fixtures\EventDiscovery\Listeners\Listener as ListenerAlias; <ide> use Illuminate\Tests\Integration\Foundation\Fixtures\EventDiscovery\Listeners\AbstractListener; <ide> use Illuminate\Tests\Integration\Foundation\Fixtures\EventDiscovery\Listeners\ListenerInterface; <ide>
1
Javascript
Javascript
make .write() throw on bad input
f0c1376e07e6d5a4deb3d088bd3153d7f6af1298
<ide><path>lib/net.js <ide> Socket.prototype.write = function(data, arg1, arg2) { <ide> } <ide> <ide> // Change strings to buffers. SLOW <del> if (typeof data == 'string') { <add> if (typeof data === 'string') { <ide> data = new Buffer(data, encoding); <add> } else if (!Buffer.isBuffer(data)) { <add> throw new TypeError("First argument must be a buffer or a string."); <ide> } <ide> <ide> this.bytesWritten += data.length; <ide><path>test/simple/test-net-connect-buffer.js <ide> tcp.listen(common.PORT, function() { <ide> <ide> assert.equal('opening', socket.readyState); <ide> <add> // Make sure that anything besides a buffer or a string throws. <add> [ null, <add> true, <add> false, <add> undefined, <add> 1, <add> 1.0, <add> 1 / 0, <add> +Infinity <add> -Infinity, <add> [], <add> {} <add> ].forEach(function(v) { <add> function f() { <add> socket.write(v); <add> } <add> assert.throws(f, TypeError); <add> }); <add> <ide> // Write a string that contains a multi-byte character sequence to test that <ide> // `bytesWritten` is incremented with the # of bytes, not # of characters. <ide> var a = "L'État, c'est ";
2
Ruby
Ruby
revert extra deletion
cf892c432ef12bffd01518a4fa507ae277056c63
<ide><path>Library/Homebrew/cmd/install.rb <ide> def install_formula(f) <ide> fi = FormulaInstaller.new(f) <ide> fi.options = build_options.used_options <ide> fi.invalid_option_names = build_options.invalid_option_names <add> fi.ignore_deps = ARGV.ignore_deps? <ide> fi.only_deps = ARGV.only_deps? <ide> fi.build_bottle = ARGV.build_bottle? <ide> fi.interactive = ARGV.interactive?
1
Javascript
Javascript
remove unneeded changes on webglprogram
377747780d3a5d481d52d6178e9ea7abe3cc908c
<ide><path>src/renderers/webgl/WebGLProgram.js <ide> function WebGLProgram( renderer, extensions, code, material, shader, parameters, <ide> var vertexGlsl = prefixVertex + vertexShader; <ide> var fragmentGlsl = prefixFragment + fragmentShader; <ide> <del> var glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl, renderer.debug.checkShaderErrors ); <del> var glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl, renderer.debug.checkShaderErrors ); <add> // console.log( '*VERTEX*', vertexGlsl ); <add> // console.log( '*FRAGMENT*', fragmentGlsl ); <add> <add> var glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl ); <add> var glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl ); <ide> <ide> gl.attachShader( program, glVertexShader ); <ide> gl.attachShader( program, glFragmentShader );
1
Ruby
Ruby
fix the rules
64c092708747eb6d989430ba947b9378b5aab59e
<ide><path>Library/Homebrew/sandbox.rb <ide> class SandboxProfile <ide> (debug deny) ; log all denied operations to /var/log/system.log <ide> <%= rules.join("\n") %> <ide> (allow file-write* <add> (literal "/dev/ptmx") <ide> (literal "/dev/dtracehelper") <ide> (literal "/dev/null") <del> (regex #"^/dev/fd/\\d+$") <del> (regex #"^/dev/tty\\d*$") <add> (regex #"^/dev/fd/[0-9]+$") <add> (regex #"^/dev/ttys?[0-9]*$") <ide> ) <ide> (deny file-write*) ; deny non-whitelist file write operations <ide> (allow default) ; allow everything else
1
Text
Text
remove dead link to a user's twitter
048e2a4e6e2358648eda9d42f3ba00dfdbc1881d
<ide><path>guide/english/react/state-vs-props/index.md <ide> It gives output as "I am a good person", in fact I am. <ide> <ide> There is lot more to learn on State and Props. Many things can be learnt by actually diving into coding. So get your hands dirty by coding. <ide> <del>Reach me out on [twitter](https://twitter.com/getifyJr) if needed. <del> <ide> Happy Coding !!!
1
Javascript
Javascript
reduce util.is*() usage
6ac8bdc0aba5f60f4b4f2da5abd36d664062aa40
<ide><path>lib/_debugger.js <ide> exports.Client = Client; <ide> <ide> <ide> Client.prototype._addHandle = function(desc) { <del> if (!util.isObject(desc) || !util.isNumber(desc.handle)) { <add> if (desc === null || typeof desc !== 'object' || <add> typeof desc.handle !== 'number') { <ide> return; <ide> } <ide> <ide> Client.prototype.reqLookup = function(refs, cb) { <ide> this.req(req, function(err, res) { <ide> if (err) return cb(err); <ide> for (var ref in res) { <del> if (util.isObject(res[ref])) { <add> if (res[ref] !== null && typeof res[ref] === 'object') { <ide> self._addHandle(res[ref]); <ide> } <ide> } <ide> Client.prototype.mirrorObject = function(handle, depth, cb) { <ide> mirrorValue = '[?]'; <ide> } <ide> <del> <del> if (util.isArray(mirror) && !util.isNumber(prop.name)) { <add> if (Array.isArray(mirror) && typeof prop.name !== 'number') { <ide> // Skip the 'length' property. <ide> return; <ide> } <ide> Client.prototype.mirrorObject = function(handle, depth, cb) { <ide> val = function() {}; <ide> } else if (handle.type === 'null') { <ide> val = null; <del> } else if (!util.isUndefined(handle.value)) { <add> } else if (handle.value !== undefined) { <ide> val = handle.value; <ide> } else if (handle.type === 'undefined') { <ide> val = undefined; <ide> Interface.prototype.print = function(text, oneline) { <ide> if (this.killed) return; <ide> this.clearline(); <ide> <del> this.stdout.write(util.isString(text) ? text : util.inspect(text)); <add> this.stdout.write(typeof text === 'string' ? text : util.inspect(text)); <ide> <ide> if (oneline !== true) { <ide> this.stdout.write('\n'); <ide> Interface.prototype.scripts = function() { <ide> this.pause(); <ide> for (var id in client.scripts) { <ide> var script = client.scripts[id]; <del> if (util.isObject(script) && script.name) { <add> if (script !== null && typeof script === 'object' && script.name) { <ide> if (displayNatives || <ide> script.name == client.currentScript || <ide> !script.isNative) { <ide> Interface.prototype.setBreakpoint = function(script, line, <ide> ambiguous; <ide> <ide> // setBreakpoint() should insert breakpoint on current line <del> if (util.isUndefined(script)) { <add> if (script === undefined) { <ide> script = this.client.currentScript; <ide> line = this.client.currentSourceLine + 1; <ide> } <ide> <ide> // setBreakpoint(line-number) should insert breakpoint in current script <del> if (util.isUndefined(line) && util.isNumber(script)) { <add> if (line === undefined && typeof script === 'number') { <ide> line = script; <ide> script = this.client.currentScript; <ide> } <ide> Interface.prototype.clearBreakpoint = function(script, line) { <ide> if (bp.scriptId === script || <ide> bp.scriptReq === script || <ide> (bp.script && bp.script.indexOf(script) !== -1)) { <del> if (!util.isUndefined(index)) { <add> if (index !== undefined) { <ide> ambiguous = true; <ide> } <ide> scriptId = script; <ide> Interface.prototype.clearBreakpoint = function(script, line) { <ide> <ide> if (ambiguous) return this.error('Script name is ambiguous'); <ide> <del> if (util.isUndefined(scriptId)) { <add> if (scriptId === undefined) { <ide> return this.error('Script ' + script + ' not found'); <ide> } <ide> <del> if (util.isUndefined(breakpoint)) { <add> if (breakpoint === undefined) { <ide> return this.error('Breakpoint not found on line ' + line); <ide> } <ide> <ide><path>lib/_http_client.js <ide> function ClientRequest(options, cb) { <ide> var self = this; <ide> OutgoingMessage.call(self); <ide> <del> if (util.isString(options)) { <add> if (typeof options === 'string') { <ide> options = url.parse(options); <ide> } <ide> <ide> var agent = options.agent; <ide> var defaultAgent = options._defaultAgent || Agent.globalAgent; <ide> if (agent === false) { <ide> agent = new defaultAgent.constructor(); <del> } else if (util.isNullOrUndefined(agent) && !options.createConnection) { <add> } else if ((agent === null || agent === undefined) && <add> !options.createConnection) { <ide> agent = defaultAgent; <ide> } <ide> self.agent = agent; <ide> function ClientRequest(options, cb) { <ide> var port = options.port = options.port || defaultPort || 80; <ide> var host = options.host = options.hostname || options.host || 'localhost'; <ide> <del> if (util.isUndefined(options.setHost)) { <add> if (options.setHost === undefined) { <ide> var setHost = true; <ide> } <ide> <ide> function ClientRequest(options, cb) { <ide> self.once('response', cb); <ide> } <ide> <del> if (!util.isArray(options.headers)) { <add> if (!Array.isArray(options.headers)) { <ide> if (options.headers) { <ide> var keys = Object.keys(options.headers); <ide> for (var i = 0, l = keys.length; i < l; i++) { <ide> function ClientRequest(options, cb) { <ide> self.useChunkedEncodingByDefault = true; <ide> } <ide> <del> if (util.isArray(options.headers)) { <add> if (Array.isArray(options.headers)) { <ide> self._storeHeader(self.method + ' ' + self.path + ' HTTP/1.1\r\n', <ide> options.headers); <ide> } else if (self.getHeader('expect')) { <ide> function tickOnSocket(req, socket) { <ide> httpSocketSetup(socket); <ide> <ide> // Propagate headers limit from request object to parser <del> if (util.isNumber(req.maxHeadersCount)) { <add> if (typeof req.maxHeadersCount === 'number') { <ide> parser.maxHeaderPairs = req.maxHeadersCount << 1; <ide> } else { <ide> // Set default value because parser may be reused from FreeList <ide><path>lib/_http_common.js <ide> const IncomingMessage = incoming.IncomingMessage; <ide> const readStart = incoming.readStart; <ide> const readStop = incoming.readStop; <ide> <del>const isNumber = require('util').isNumber; <ide> const debug = require('util').debuglog('http'); <ide> exports.debug = debug; <ide> <ide> function parserOnHeadersComplete(versionMajor, versionMinor, headers, method, <ide> <ide> parser.incoming._addHeaderLines(headers, n); <ide> <del> if (isNumber(method)) { <add> if (typeof method === 'number') { <ide> // server only <ide> parser.incoming.method = HTTPParser.methods[method]; <ide> } else { <ide><path>lib/_http_incoming.js <ide> IncomingMessage.prototype._addHeaderLine = function(field, value, dest) { <ide> switch (field) { <ide> // Array headers: <ide> case 'set-cookie': <del> if (!util.isUndefined(dest[field])) { <add> if (dest[field] !== undefined) { <ide> dest[field].push(value); <ide> } else { <ide> dest[field] = [value]; <ide> IncomingMessage.prototype._addHeaderLine = function(field, value, dest) { <ide> case 'location': <ide> case 'max-forwards': <ide> // drop duplicates <del> if (util.isUndefined(dest[field])) <add> if (dest[field] === undefined) <ide> dest[field] = value; <ide> break; <ide> <ide> default: <ide> // make comma-separated list <del> if (!util.isUndefined(dest[field])) <add> if (dest[field] !== undefined) <ide> dest[field] += ', ' + value; <ide> else { <ide> dest[field] = value; <ide><path>lib/_http_outgoing.js <ide> OutgoingMessage.prototype._send = function(data, encoding, callback) { <ide> // the same packet. Future versions of Node are going to take care of <ide> // this at a lower level and in a more general way. <ide> if (!this._headerSent) { <del> if (util.isString(data) && <add> if (typeof data === 'string' && <ide> encoding !== 'hex' && <ide> encoding !== 'base64') { <ide> data = this._header + data; <ide> OutgoingMessage.prototype._send = function(data, encoding, callback) { <ide> <ide> <ide> OutgoingMessage.prototype._writeRaw = function(data, encoding, callback) { <del> if (util.isFunction(encoding)) { <add> if (typeof encoding === 'function') { <ide> callback = encoding; <ide> encoding = null; <ide> } <ide> <ide> if (data.length === 0) { <del> if (util.isFunction(callback)) <add> if (typeof callback === 'function') <ide> process.nextTick(callback); <ide> return true; <ide> } <ide> OutgoingMessage.prototype._storeHeader = function(firstLine, headers) { <ide> <ide> if (headers) { <ide> var keys = Object.keys(headers); <del> var isArray = util.isArray(headers); <add> var isArray = Array.isArray(headers); <ide> var field, value; <ide> <ide> for (var i = 0, l = keys.length; i < l; i++) { <ide> OutgoingMessage.prototype._storeHeader = function(firstLine, headers) { <ide> value = headers[key]; <ide> } <ide> <del> if (util.isArray(value)) { <add> if (Array.isArray(value)) { <ide> for (var j = 0; j < value.length; j++) { <ide> storeHeader(this, state, field, value[j]); <ide> } <ide> OutgoingMessage.prototype.write = function(chunk, encoding, callback) { <ide> return true; <ide> } <ide> <del> if (!util.isString(chunk) && !util.isBuffer(chunk)) { <add> if (typeof chunk !== 'string' && !(chunk instanceof Buffer)) { <ide> throw new TypeError('first argument must be a string or Buffer'); <ide> } <ide> <ide> OutgoingMessage.prototype.write = function(chunk, encoding, callback) { <ide> <ide> var len, ret; <ide> if (this.chunkedEncoding) { <del> if (util.isString(chunk) && <add> if (typeof chunk === 'string' && <ide> encoding !== 'hex' && <ide> encoding !== 'base64' && <ide> encoding !== 'binary') { <ide> OutgoingMessage.prototype.write = function(chunk, encoding, callback) { <ide> ret = this._send(chunk, encoding, callback); <ide> } else { <ide> // buffer, or a non-toString-friendly encoding <del> if (util.isString(chunk)) <add> if (typeof chunk === 'string') <ide> len = Buffer.byteLength(chunk, encoding); <ide> else <ide> len = chunk.length; <ide> OutgoingMessage.prototype.write = function(chunk, encoding, callback) { <ide> OutgoingMessage.prototype.addTrailers = function(headers) { <ide> this._trailer = ''; <ide> var keys = Object.keys(headers); <del> var isArray = util.isArray(headers); <add> var isArray = Array.isArray(headers); <ide> var field, value; <ide> for (var i = 0, l = keys.length; i < l; i++) { <ide> var key = keys[i]; <ide> const crlf_buf = new Buffer('\r\n'); <ide> <ide> <ide> OutgoingMessage.prototype.end = function(data, encoding, callback) { <del> if (util.isFunction(data)) { <add> if (typeof data === 'function') { <ide> callback = data; <ide> data = null; <del> } else if (util.isFunction(encoding)) { <add> } else if (typeof encoding === 'function') { <ide> callback = encoding; <ide> encoding = null; <ide> } <ide> <del> if (data && !util.isString(data) && !util.isBuffer(data)) { <add> if (data && typeof data !== 'string' && !(data instanceof Buffer)) { <ide> throw new TypeError('first argument must be a string or Buffer'); <ide> } <ide> <ide> OutgoingMessage.prototype.end = function(data, encoding, callback) { <ide> self.emit('finish'); <ide> } <ide> <del> if (util.isFunction(callback)) <add> if (typeof callback === 'function') <ide> this.once('finish', callback); <ide> <del> <ide> if (!this._header) { <ide> this._implicitHeader(); <ide> } <ide><path>lib/_http_server.js <ide> ServerResponse.prototype._implicitHeader = function() { <ide> ServerResponse.prototype.writeHead = function(statusCode, reason, obj) { <ide> var headers; <ide> <del> if (util.isString(reason)) { <add> if (typeof reason === 'string') { <ide> // writeHead(statusCode, reasonPhrase[, headers]) <ide> this.statusMessage = reason; <ide> } else { <ide> function connectionListener(socket) { <ide> parser.incoming = null; <ide> <ide> // Propagate headers limit from server instance to parser <del> if (util.isNumber(this.maxHeadersCount)) { <add> if (typeof this.maxHeadersCount === 'number') { <ide> parser.maxHeaderPairs = this.maxHeadersCount << 1; <ide> } else { <ide> // Set default value because parser may be reused from FreeList <ide> function connectionListener(socket) { <ide> } <ide> } <ide> <del> if (!util.isUndefined(req.headers.expect) && <add> if (req.headers.expect !== undefined && <ide> (req.httpVersionMajor == 1 && req.httpVersionMinor == 1) && <ide> continueExpression.test(req.headers['expect'])) { <ide> res._expect_continue = true; <ide><path>lib/_stream_readable.js <ide> function Readable(options) { <ide> Readable.prototype.push = function(chunk, encoding) { <ide> var state = this._readableState; <ide> <del> if (util.isString(chunk) && !state.objectMode) { <add> if (!state.objectMode && typeof chunk === 'string') { <ide> encoding = encoding || state.defaultEncoding; <ide> if (encoding !== state.encoding) { <ide> chunk = new Buffer(chunk, encoding); <ide> function howMuchToRead(n, state) { <ide> if (state.objectMode) <ide> return n === 0 ? 0 : 1; <ide> <del> if (util.isNull(n) || isNaN(n)) { <add> if (n === null || isNaN(n)) { <ide> // only flow one buffer at a time <ide> if (state.flowing && state.buffer.length) <ide> return state.buffer[0].length; <ide> Readable.prototype.read = function(n) { <ide> var state = this._readableState; <ide> var nOrig = n; <ide> <del> if (!util.isNumber(n) || n > 0) <add> if (typeof n !== 'number' || n > 0) <ide> state.emittedReadable = false; <ide> <ide> // if we're doing read(0) to trigger a readable event, but we <ide> Readable.prototype.read = function(n) { <ide> else <ide> ret = null; <ide> <del> if (util.isNull(ret)) { <add> if (ret === null) { <ide> state.needReadable = true; <ide> n = 0; <ide> } <ide> Readable.prototype.read = function(n) { <ide> if (nOrig !== n && state.ended && state.length === 0) <ide> endReadable(this); <ide> <del> if (!util.isNull(ret)) <add> if (ret !== null) <ide> this.emit('data', ret); <ide> <ide> return ret; <ide> }; <ide> <ide> function chunkInvalid(state, chunk) { <ide> var er = null; <del> if (!util.isBuffer(chunk) && <del> !util.isString(chunk) && <del> !util.isNullOrUndefined(chunk) && <add> if (!(chunk instanceof Buffer) && <add> typeof chunk !== 'string' && <add> chunk !== null && <add> chunk !== undefined && <ide> !state.objectMode) { <ide> er = new TypeError('Invalid non-string/buffer chunk'); <ide> } <ide> Readable.prototype.wrap = function(stream) { <ide> chunk = state.decoder.write(chunk); <ide> <ide> // don't skip over falsy values in objectMode <del> //if (state.objectMode && util.isNullOrUndefined(chunk)) <ide> if (state.objectMode && (chunk === null || chunk === undefined)) <ide> return; <ide> else if (!state.objectMode && (!chunk || !chunk.length)) <ide> Readable.prototype.wrap = function(stream) { <ide> // proxy all the other methods. <ide> // important when wrapping filters and duplexes. <ide> for (var i in stream) { <del> if (util.isFunction(stream[i]) && util.isUndefined(this[i])) { <add> if (this[i] === undefined && typeof stream[i] === 'function') { <ide> this[i] = function(method) { return function() { <ide> return stream[method].apply(stream, arguments); <ide> }}(i); <ide><path>lib/_stream_transform.js <ide> function afterTransform(stream, er, data) { <ide> ts.writechunk = null; <ide> ts.writecb = null; <ide> <del> if (!util.isNullOrUndefined(data)) <add> if (data !== null && data !== undefined) <ide> stream.push(data); <ide> <ide> if (cb) <ide> function Transform(options) { <ide> this._readableState.sync = false; <ide> <ide> this.once('prefinish', function() { <del> if (util.isFunction(this._flush)) <add> if (typeof this._flush === 'function') <ide> this._flush(function(er) { <ide> done(stream, er); <ide> }); <ide> Transform.prototype._write = function(chunk, encoding, cb) { <ide> Transform.prototype._read = function(n) { <ide> var ts = this._transformState; <ide> <del> if (!util.isNull(ts.writechunk) && ts.writecb && !ts.transforming) { <add> if (ts.writechunk !== null && ts.writecb && !ts.transforming) { <ide> ts.transforming = true; <ide> this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); <ide> } else { <ide><path>lib/_stream_writable.js <ide> function writeAfterEnd(stream, state, cb) { <ide> // how many bytes or characters. <ide> function validChunk(stream, state, chunk, cb) { <ide> var valid = true; <del> if (!util.isBuffer(chunk) && <del> !util.isString(chunk) && <del> !util.isNullOrUndefined(chunk) && <add> <add> if (!(chunk instanceof Buffer) && <add> typeof chunk !== 'string' && <add> chunk !== null && <add> chunk !== undefined && <ide> !state.objectMode) { <ide> var er = new TypeError('Invalid non-string/buffer chunk'); <ide> stream.emit('error', er); <ide> Writable.prototype.write = function(chunk, encoding, cb) { <ide> var state = this._writableState; <ide> var ret = false; <ide> <del> if (util.isFunction(encoding)) { <add> if (typeof encoding === 'function') { <ide> cb = encoding; <ide> encoding = null; <ide> } <ide> <del> if (util.isBuffer(chunk)) <add> if (chunk instanceof Buffer) <ide> encoding = 'buffer'; <ide> else if (!encoding) <ide> encoding = state.defaultEncoding; <ide> <del> if (!util.isFunction(cb)) <add> if (typeof cb !== 'function') <ide> cb = nop; <ide> <ide> if (state.ended) <ide> Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { <ide> function decodeChunk(state, chunk, encoding) { <ide> if (!state.objectMode && <ide> state.decodeStrings !== false && <del> util.isString(chunk)) { <add> typeof chunk === 'string') { <ide> chunk = new Buffer(chunk, encoding); <ide> } <ide> return chunk; <ide> function decodeChunk(state, chunk, encoding) { <ide> // If we return false, then we need a drain event, so set that flag. <ide> function writeOrBuffer(stream, state, chunk, encoding, cb) { <ide> chunk = decodeChunk(state, chunk, encoding); <del> if (util.isBuffer(chunk)) <add> <add> if (chunk instanceof Buffer) <ide> encoding = 'buffer'; <ide> var len = state.objectMode ? 1 : chunk.length; <ide> <ide> Writable.prototype._writev = null; <ide> Writable.prototype.end = function(chunk, encoding, cb) { <ide> var state = this._writableState; <ide> <del> if (util.isFunction(chunk)) { <add> if (typeof chunk === 'function') { <ide> cb = chunk; <ide> chunk = null; <ide> encoding = null; <del> } else if (util.isFunction(encoding)) { <add> } else if (typeof encoding === 'function') { <ide> cb = encoding; <ide> encoding = null; <ide> } <ide> <del> if (!util.isNullOrUndefined(chunk)) <add> if (chunk !== null && chunk !== undefined) <ide> this.write(chunk, encoding); <ide> <ide> // .end() fully uncorks <ide><path>lib/_tls_common.js <ide> 'use strict'; <ide> <del>const util = require('util'); <ide> const constants = require('constants'); <ide> const tls = require('tls'); <ide> <ide> exports.createSecureContext = function createSecureContext(options, context) { <ide> // NOTE: It's important to add CA before the cert to be able to load <ide> // cert's issuer in C++ code. <ide> if (options.ca) { <del> if (util.isArray(options.ca)) { <add> if (Array.isArray(options.ca)) { <ide> for (var i = 0, len = options.ca.length; i < len; i++) { <ide> c.context.addCACert(options.ca[i]); <ide> } <ide> exports.createSecureContext = function createSecureContext(options, context) { <ide> else <ide> c.context.setCiphers(tls.DEFAULT_CIPHERS); <ide> <del> if (util.isUndefined(options.ecdhCurve)) <add> if (options.ecdhCurve === undefined) <ide> c.context.setECDHCurve(tls.DEFAULT_ECDH_CURVE); <ide> else if (options.ecdhCurve) <ide> c.context.setECDHCurve(options.ecdhCurve); <ide> <ide> if (options.dhparam) c.context.setDHParam(options.dhparam); <ide> <ide> if (options.crl) { <del> if (util.isArray(options.crl)) { <add> if (Array.isArray(options.crl)) { <ide> for (var i = 0, len = options.crl.length; i < len; i++) { <ide> c.context.addCRL(options.crl[i]); <ide> } <ide><path>lib/_tls_legacy.js <ide> SlabBuffer.prototype.use = function use(context, fn, size) { <ide> <ide> var actualSize = this.remaining; <ide> <del> if (!util.isNull(size)) actualSize = Math.min(size, actualSize); <add> if (size !== null) actualSize = Math.min(size, actualSize); <ide> <ide> var bytes = fn.call(context, this.pool, this.offset, actualSize); <ide> if (bytes > 0) { <ide> function CryptoStream(pair, options) { <ide> this._finished = false; <ide> this._opposite = null; <ide> <del> if (util.isNull(slabBuffer)) slabBuffer = new SlabBuffer(); <add> if (slabBuffer === null) slabBuffer = new SlabBuffer(); <ide> this._buffer = slabBuffer; <ide> <ide> this.once('finish', onCryptoStreamFinish); <ide> CryptoStream.prototype.init = function init() { <ide> <ide> <ide> CryptoStream.prototype._write = function write(data, encoding, cb) { <del> assert(util.isNull(this._pending)); <add> assert(this._pending === null); <ide> <ide> // Black-hole data <ide> if (!this.pair.ssl) return cb(null); <ide> CryptoStream.prototype._write = function write(data, encoding, cb) { <ide> <ide> // Invoke callback only when all data read from opposite stream <ide> if (this._opposite._halfRead) { <del> assert(util.isNull(this._sslOutCb)); <add> assert(this._sslOutCb === null); <ide> this._sslOutCb = cb; <ide> } else { <ide> cb(null); <ide> CryptoStream.prototype._read = function read(size) { <ide> } <ide> <ide> // Try writing pending data <del> if (!util.isNull(this._pending)) this._writePending(); <del> if (!util.isNull(this._opposite._pending)) this._opposite._writePending(); <add> if (this._pending !== null) this._writePending(); <add> if (this._opposite._pending !== null) this._opposite._writePending(); <ide> <ide> if (bytesRead === 0) { <ide> // EOF when cleartext has finished and we have nothing to read <ide> CryptoStream.prototype.end = function(chunk, encoding) { <ide> } <ide> <ide> // Write pending data first <del> if (!util.isNull(this._pending)) this._writePending(); <add> if (this._pending !== null) this._writePending(); <ide> <ide> this.writable = false; <ide> <ide><path>lib/_tls_wrap.js <ide> TLSSocket.prototype.setServername = function(name) { <ide> }; <ide> <ide> TLSSocket.prototype.setSession = function(session) { <del> if (util.isString(session)) <add> if (typeof session === 'string') <ide> session = new Buffer(session, 'binary'); <ide> this.ssl.setSession(session); <ide> }; <ide> TLSSocket.prototype.getCipher = function(err) { <ide> // <ide> function Server(/* [options], listener */) { <ide> var options, listener; <del> if (util.isObject(arguments[0])) { <add> <add> if (arguments[0] !== null && typeof arguments[0] === 'object') { <ide> options = arguments[0]; <ide> listener = arguments[1]; <del> } else if (util.isFunction(arguments[0])) { <add> } else if (typeof arguments[0] === 'function') { <ide> options = {}; <ide> listener = arguments[0]; <ide> } <ide> function Server(/* [options], listener */) { <ide> <ide> var timeout = options.handshakeTimeout || (120 * 1000); <ide> <del> if (!util.isNumber(timeout)) { <add> if (typeof timeout !== 'number') { <ide> throw new TypeError('handshakeTimeout must be a number'); <ide> } <ide> <ide> Server.prototype._setServerData = function(data) { <ide> <ide> <ide> Server.prototype.setOptions = function(options) { <del> if (util.isBoolean(options.requestCert)) { <add> if (typeof options.requestCert === 'boolean') { <ide> this.requestCert = options.requestCert; <ide> } else { <ide> this.requestCert = false; <ide> } <ide> <del> if (util.isBoolean(options.rejectUnauthorized)) { <add> if (typeof options.rejectUnauthorized === 'boolean') { <ide> this.rejectUnauthorized = options.rejectUnauthorized; <ide> } else { <ide> this.rejectUnauthorized = false; <ide> Server.prototype.setOptions = function(options) { <ide> if (options.secureProtocol) this.secureProtocol = options.secureProtocol; <ide> if (options.crl) this.crl = options.crl; <ide> if (options.ciphers) this.ciphers = options.ciphers; <del> if (!util.isUndefined(options.ecdhCurve)) <add> if (options.ecdhCurve !== undefined) <ide> this.ecdhCurve = options.ecdhCurve; <ide> if (options.dhparam) this.dhparam = options.dhparam; <ide> if (options.sessionTimeout) this.sessionTimeout = options.sessionTimeout; <ide> function SNICallback(servername, callback) { <ide> var ctx; <ide> <ide> this.server._contexts.some(function(elem) { <del> if (!util.isNull(servername.match(elem[0]))) { <add> if (servername.match(elem[0]) !== null) { <ide> ctx = elem[1]; <ide> return true; <ide> } <ide> function normalizeConnectArgs(listArgs) { <ide> var options = args[0]; <ide> var cb = args[1]; <ide> <del> if (util.isObject(listArgs[1])) { <add> if (listArgs[1] !== null && typeof listArgs[1] === 'object') { <ide> options = util._extend(options, listArgs[1]); <del> } else if (util.isObject(listArgs[2])) { <add> } else if (listArgs[2] !== null && typeof listArgs[2] === 'object') { <ide> options = util._extend(options, listArgs[2]); <ide> } <ide> <ide><path>lib/assert.js <ide> assert.AssertionError = function AssertionError(options) { <ide> util.inherits(assert.AssertionError, Error); <ide> <ide> function truncate(s, n) { <del> if (util.isString(s)) { <add> if (typeof s === 'string') { <ide> return s.length < n ? s : s.slice(0, n); <ide> } else { <ide> return s; <ide> function _deepEqual(actual, expected) { <ide> // 7.1. All identical values are equivalent, as determined by ===. <ide> if (actual === expected) { <ide> return true; <del> <del> } else if (util.isBuffer(actual) && util.isBuffer(expected)) { <add> } else if (actual instanceof Buffer && expected instanceof Buffer) { <ide> if (actual.length != expected.length) return false; <ide> <ide> for (var i = 0; i < actual.length; i++) { <ide> function _deepEqual(actual, expected) { <ide> <ide> // 7.4. Other pairs that do not both pass typeof value == 'object', <ide> // equivalence is determined by ==. <del> } else if (!util.isObject(actual) && !util.isObject(expected)) { <add> } else if ((actual === null || typeof actual !== 'object') && <add> (expected === null || typeof expected !== 'object')) { <ide> return actual == expected; <ide> <ide> // 7.5 For all other Object pairs, including Array objects, equivalence is <ide> function isArguments(object) { <ide> } <ide> <ide> function objEquiv(a, b) { <del> if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b)) <add> if (a === null || a === undefined || b === null || b === undefined) <ide> return false; <ide> // an identical 'prototype' property. <ide> if (a.prototype !== b.prototype) return false; <ide> function expectedException(actual, expected) { <ide> function _throws(shouldThrow, block, expected, message) { <ide> var actual; <ide> <del> if (!util.isFunction(block)) { <add> if (typeof block !== 'function') { <ide> throw new TypeError('block must be a function'); <ide> } <ide> <del> if (util.isString(expected)) { <add> if (typeof expected === 'string') { <ide> message = expected; <ide> expected = null; <ide> } <ide><path>lib/buffer.js <ide> createPool(); <ide> <ide> <ide> function Buffer(subject, encoding) { <del> if (!util.isBuffer(this)) <add> if (!(this instanceof Buffer)) <ide> return new Buffer(subject, encoding); <ide> <del> if (util.isNumber(subject)) { <add> if (typeof subject === 'number') { <ide> this.length = +subject; <ide> <del> } else if (util.isString(subject)) { <del> if (!util.isString(encoding) || encoding.length === 0) <add> } else if (typeof subject === 'string') { <add> if (typeof encoding !== 'string' || encoding.length === 0) <ide> encoding = 'utf8'; <ide> this.length = Buffer.byteLength(subject, encoding); <ide> <ide> // Handle Arrays, Buffers, Uint8Arrays or JSON. <del> } else if (util.isObject(subject)) { <del> if (subject.type === 'Buffer' && util.isArray(subject.data)) <add> } else if (subject !== null && typeof subject === 'object') { <add> if (subject.type === 'Buffer' && Array.isArray(subject.data)) <ide> subject = subject.data; <ide> this.length = +subject.length; <ide> <ide> function Buffer(subject, encoding) { <ide> alloc(this, this.length); <ide> } <ide> <del> if (util.isNumber(subject)) { <add> if (typeof subject === 'number') { <ide> return; <ide> } <ide> <del> if (util.isString(subject)) { <add> if (typeof subject === 'string') { <ide> // In the case of base64 it's possible that the size of the buffer <ide> // allocated was slightly too large. In this case we need to rewrite <ide> // the length to the actual length written. <ide> function Buffer(subject, encoding) { <ide> poolOffset -= (prevLen - len); <ide> } <ide> <del> } else if (util.isBuffer(subject)) { <add> } else if (subject instanceof Buffer) { <ide> subject.copy(this, 0, 0, this.length); <ide> <del> } else if (util.isNumber(subject.length) || util.isArray(subject)) { <add> } else if (typeof subject.length === 'number' || Array.isArray(subject)) { <ide> // Really crappy way to handle Uint8Arrays, but V8 doesn't give a simple <ide> // way to access the data from the C++ API. <ide> for (var i = 0; i < this.length; i++) <ide> buffer.setupBufferJS(NativeBuffer, internal); <ide> // Static methods <ide> <ide> Buffer.isBuffer = function isBuffer(b) { <del> return util.isBuffer(b); <add> return b instanceof Buffer; <ide> }; <ide> <ide> <ide> Buffer.isEncoding = function(encoding) { <ide> <ide> <ide> Buffer.concat = function(list, length) { <del> if (!util.isArray(list)) <add> if (!Array.isArray(list)) <ide> throw new TypeError('Usage: Buffer.concat(list[, length])'); <ide> <del> if (util.isUndefined(length)) { <add> if (length === undefined) { <ide> length = 0; <ide> for (var i = 0; i < list.length; i++) <ide> length += list[i].length; <ide> Buffer.prototype.toString = function(encoding, start, end) { <ide> var loweredCase = false; <ide> <ide> start = start >>> 0; <del> end = util.isUndefined(end) || end === Infinity ? this.length : end >>> 0; <add> end = end === undefined || end === Infinity ? this.length : end >>> 0; <ide> <ide> if (!encoding) encoding = 'utf8'; <ide> if (start < 0) start = 0; <ide> const writeMsg = '.write(string, encoding, offset, length) is deprecated.' + <ide> ' Use write(string[, offset[, length]][, encoding]) instead.'; <ide> Buffer.prototype.write = function(string, offset, length, encoding) { <ide> // Buffer#write(string); <del> if (util.isUndefined(offset)) { <add> if (offset === undefined) { <ide> encoding = 'utf8'; <ide> length = this.length; <ide> offset = 0; <ide> <ide> // Buffer#write(string, encoding) <del> } else if (util.isUndefined(length) && util.isString(offset)) { <add> } else if (length === undefined && typeof offset === 'string') { <ide> encoding = offset; <ide> length = this.length; <ide> offset = 0; <ide> Buffer.prototype.write = function(string, offset, length, encoding) { <ide> offset = offset >>> 0; <ide> if (isFinite(length)) { <ide> length = length >>> 0; <del> if (util.isUndefined(encoding)) <add> if (encoding === undefined) <ide> encoding = 'utf8'; <ide> } else { <ide> encoding = length; <ide> Buffer.prototype.write = function(string, offset, length, encoding) { <ide> } <ide> <ide> var remaining = this.length - offset; <del> if (util.isUndefined(length) || length > remaining) <add> if (length === undefined || length > remaining) <ide> length = remaining; <ide> <ide> encoding = !!encoding ? (encoding + '').toLowerCase() : 'utf8'; <ide> Buffer.prototype.toJSON = function() { <ide> Buffer.prototype.slice = function(start, end) { <ide> var len = this.length; <ide> start = ~~start; <del> end = util.isUndefined(end) ? len : ~~end; <add> end = end === undefined ? len : ~~end; <ide> <ide> if (start < 0) { <ide> start += len; <ide> Buffer.prototype.slice = function(start, end) { <ide> sliceOnto(this, buf, start, end); <ide> buf.length = end - start; <ide> if (buf.length > 0) <del> buf.parent = util.isUndefined(this.parent) ? this : this.parent; <add> buf.parent = this.parent === undefined ? this : this.parent; <ide> <ide> return buf; <ide> }; <ide><path>lib/child_process.js <ide> function handleWrapGetter(name, callback) { <ide> <ide> Object.defineProperty(handleWraps, name, { <ide> get: function() { <del> if (!util.isUndefined(cons)) return cons; <add> if (cons !== undefined) return cons; <ide> return cons = callback(); <ide> } <ide> }); <ide> function getSocketList(type, slave, key) { <ide> const INTERNAL_PREFIX = 'NODE_'; <ide> function handleMessage(target, message, handle) { <ide> var eventName = 'message'; <del> if (!util.isNull(message) && <del> util.isObject(message) && <del> util.isString(message.cmd) && <add> if (message !== null && <add> typeof message === 'object' && <add> typeof message.cmd === 'string' && <ide> message.cmd.length > INTERNAL_PREFIX.length && <ide> message.cmd.slice(0, INTERNAL_PREFIX.length) === INTERNAL_PREFIX) { <ide> eventName = 'internalMessage'; <ide> function setupChannel(target, channel) { <ide> target.on('internalMessage', function(message, handle) { <ide> // Once acknowledged - continue sending handles. <ide> if (message.cmd === 'NODE_HANDLE_ACK') { <del> assert(util.isArray(target._handleQueue)); <add> assert(Array.isArray(target._handleQueue)); <ide> var queue = target._handleQueue; <ide> target._handleQueue = null; <ide> <ide> function setupChannel(target, channel) { <ide> target._send = function(message, handle, swallowErrors) { <ide> assert(this.connected || this._channel); <ide> <del> if (util.isUndefined(message)) <add> if (message === undefined) <ide> throw new TypeError('message cannot be undefined'); <ide> <ide> // package messages with a handle object <ide> exports.fork = function(modulePath /*, args, options*/) { <ide> <ide> // Get options and args arguments. <ide> var options, args, execArgv; <del> if (util.isArray(arguments[1])) { <add> if (Array.isArray(arguments[1])) { <ide> args = arguments[1]; <ide> options = util._extend({}, arguments[2]); <ide> } else { <ide> exports._forkChild = function(fd) { <ide> function normalizeExecArgs(command /*, options, callback */) { <ide> var file, args, options, callback; <ide> <del> if (util.isFunction(arguments[1])) { <add> if (typeof arguments[1] === 'function') { <ide> options = undefined; <ide> callback = arguments[1]; <ide> } else { <ide> exports.execFile = function(file /* args, options, callback */) { <ide> <ide> // Parse the parameters. <ide> <del> if (util.isFunction(arguments[arguments.length - 1])) { <add> if (typeof arguments[arguments.length - 1] === 'function') { <ide> callback = arguments[arguments.length - 1]; <ide> } <ide> <del> if (util.isArray(arguments[1])) { <add> if (Array.isArray(arguments[1])) { <ide> args = arguments[1]; <ide> options = util._extend(options, arguments[2]); <ide> } else { <ide> function _validateStdio(stdio, sync) { <ide> ipcFd; <ide> <ide> // Replace shortcut with an array <del> if (util.isString(stdio)) { <add> if (typeof stdio === 'string') { <ide> switch (stdio) { <ide> case 'ignore': stdio = ['ignore', 'ignore', 'ignore']; break; <ide> case 'pipe': stdio = ['pipe', 'pipe', 'pipe']; break; <ide> case 'inherit': stdio = [0, 1, 2]; break; <ide> default: throw new TypeError('Incorrect value of stdio option: ' + stdio); <ide> } <del> } else if (!util.isArray(stdio)) { <add> } else if (!Array.isArray(stdio)) { <ide> throw new TypeError('Incorrect value of stdio option: ' + <ide> util.inspect(stdio)); <ide> } <ide> function _validateStdio(stdio, sync) { <ide> } <ide> <ide> // Defaults <del> if (util.isNullOrUndefined(stdio)) { <add> if (stdio === null || stdio === undefined) { <ide> stdio = i < 3 ? 'pipe' : 'ignore'; <ide> } <ide> <ide> if (stdio === null || stdio === 'ignore') { <ide> acc.push({type: 'ignore'}); <del> } else if (stdio === 'pipe' || util.isNumber(stdio) && stdio < 0) { <add> } else if (stdio === 'pipe' || typeof stdio === 'number' && stdio < 0) { <ide> var a = { <ide> type: 'pipe', <ide> readable: i === 0, <ide> function _validateStdio(stdio, sync) { <ide> <ide> acc.push(a); <ide> } else if (stdio === 'ipc') { <del> if (sync || !util.isUndefined(ipc)) { <add> if (sync || ipc !== undefined) { <ide> // Cleanup previously created pipes <ide> cleanup(); <ide> if (!sync) <ide> function _validateStdio(stdio, sync) { <ide> type: 'inherit', <ide> fd: i <ide> }); <del> } else if (util.isNumber(stdio) || util.isNumber(stdio.fd)) { <add> } else if (typeof stdio === 'number' || typeof stdio.fd === 'number') { <ide> acc.push({ <ide> type: 'fd', <ide> fd: stdio.fd || stdio <ide> function _validateStdio(stdio, sync) { <ide> wrapType: getHandleWrapType(handle), <ide> handle: handle <ide> }); <del> } else if (util.isBuffer(stdio) || util.isString(stdio)) { <add> } else if (stdio instanceof Buffer || typeof stdio === 'string') { <ide> if (!sync) { <ide> cleanup(); <ide> throw new TypeError('Asynchronous forks do not support Buffer input: ' + <ide> function normalizeSpawnArguments(file /*, args, options*/) { <ide> if (Array.isArray(arguments[1])) { <ide> args = arguments[1].slice(0); <ide> options = arguments[2]; <del> } else if (arguments[1] !== undefined && !util.isObject(arguments[1])) { <add> } else if (arguments[1] !== undefined && <add> (arguments[1] === null || typeof arguments[1] !== 'object')) { <ide> throw new TypeError('Incorrect value of args option'); <ide> } else { <ide> args = []; <ide> function normalizeSpawnArguments(file /*, args, options*/) { <ide> <ide> if (options === undefined) <ide> options = {}; <del> else if (!util.isObject(options)) <add> else if (options === null || typeof options !== 'object') <ide> throw new TypeError('options argument must be an object'); <ide> <ide> options = util._extend({}, options); <ide> ChildProcess.prototype.spawn = function(options) { <ide> ipcFd = stdio.ipcFd; <ide> stdio = options.stdio = stdio.stdio; <ide> <del> if (!util.isUndefined(ipc)) { <add> if (ipc !== undefined) { <ide> // Let child process know about opened IPC channel <ide> options.envPairs = options.envPairs || []; <ide> options.envPairs.push('NODE_CHANNEL_FD=' + ipcFd); <ide> ChildProcess.prototype.spawn = function(options) { <ide> } <ide> }); <ide> <del> this.stdin = stdio.length >= 1 && !util.isUndefined(stdio[0].socket) ? <add> this.stdin = stdio.length >= 1 && stdio[0].socket !== undefined ? <ide> stdio[0].socket : null; <del> this.stdout = stdio.length >= 2 && !util.isUndefined(stdio[1].socket) ? <add> this.stdout = stdio.length >= 2 && stdio[1].socket !== undefined ? <ide> stdio[1].socket : null; <del> this.stderr = stdio.length >= 3 && !util.isUndefined(stdio[2].socket) ? <add> this.stderr = stdio.length >= 3 && stdio[2].socket !== undefined ? <ide> stdio[2].socket : null; <ide> <ide> this.stdio = stdio.map(function(stdio) { <del> return util.isUndefined(stdio.socket) ? null : stdio.socket; <add> return stdio.socket === undefined ? null : stdio.socket; <ide> }); <ide> <ide> // Add .send() method and start listening for IPC data <del> if (!util.isUndefined(ipc)) setupChannel(this, ipc); <add> if (ipc !== undefined) setupChannel(this, ipc); <ide> <ide> return err; <ide> }; <ide> ChildProcess.prototype.kill = function(sig) { <ide> signal = constants[sig]; <ide> } <ide> <del> if (util.isUndefined(signal)) { <add> if (signal === undefined) { <ide> throw new Error('Unknown signal: ' + sig); <ide> } <ide> <ide> function spawnSync(/*file, args, options*/) { <ide> var pipe = options.stdio[i] = util._extend({}, options.stdio[i]); <ide> if (Buffer.isBuffer(input)) <ide> pipe.input = input; <del> else if (util.isString(input)) <add> else if (typeof input === 'string') <ide> pipe.input = new Buffer(input, options.encoding); <ide> else <ide> throw new TypeError(util.format( <ide><path>lib/cluster.js <ide> function Worker(options) { <ide> <ide> EventEmitter.call(this); <ide> <del> if (!util.isObject(options)) <add> if (options === null || typeof options !== 'object') <ide> options = {}; <ide> <ide> this.suicide = undefined; <ide> function SharedHandle(key, address, port, addressType, backlog, fd) { <ide> else <ide> rval = net._createServerHandle(address, port, addressType, fd); <ide> <del> if (util.isNumber(rval)) <add> if (typeof rval === 'number') <ide> this.errno = rval; <ide> else <ide> this.handle = rval; <ide> RoundRobinHandle.prototype.add = function(worker, send) { <ide> self.handoff(worker); // In case there are connections pending. <ide> } <ide> <del> if (util.isNull(this.server)) return done(); <add> if (this.server === null) return done(); <ide> // Still busy binding. <ide> this.server.once('listening', done); <ide> this.server.once('error', function(err) { <ide> RoundRobinHandle.prototype.handoff = function(worker) { <ide> return; // Worker is closing (or has closed) the server. <ide> } <ide> var handle = this.handles.shift(); <del> if (util.isUndefined(handle)) { <add> if (handle === undefined) { <ide> this.free.push(worker); // Add to ready queue again. <ide> return; <ide> } <ide> function masterInit() { <ide> 'rr': SCHED_RR <ide> }[process.env.NODE_CLUSTER_SCHED_POLICY]; <ide> <del> if (util.isUndefined(schedulingPolicy)) { <add> if (schedulingPolicy === undefined) { <ide> // FIXME Round-robin doesn't perform well on Windows right now due to the <ide> // way IOCP is wired up. Bert is going to fix that, eventually. <ide> schedulingPolicy = (process.platform === 'win32') ? SCHED_NONE : SCHED_RR; <ide> function masterInit() { <ide> message.fd]; <ide> var key = args.join(':'); <ide> var handle = handles[key]; <del> if (util.isUndefined(handle)) { <add> if (handle === undefined) { <ide> var constructor = RoundRobinHandle; <ide> // UDP is exempt from round-robin connection balancing for what should <ide> // be obvious reasons: it's connectionless. There is nothing to send to <ide> function workerInit() { <ide> delete handles[key]; <ide> return close.apply(this, arguments); <ide> }; <del> assert(util.isUndefined(handles[key])); <add> assert(handles[key] === undefined); <ide> handles[key] = handle; <ide> cb(message.errno, handle); <ide> } <ide> function workerInit() { <ide> // the ack by the master process in which we can still receive handles. <ide> // onconnection() below handles that by sending those handles back to <ide> // the master. <del> if (util.isUndefined(key)) return; <add> if (key === undefined) return; <ide> send({ act: 'close', key: key }); <ide> delete handles[key]; <ide> key = undefined; <ide> function workerInit() { <ide> if (message.sockname) { <ide> handle.getsockname = getsockname; // TCP handles only. <ide> } <del> assert(util.isUndefined(handles[key])); <add> assert(handles[key] === undefined); <ide> handles[key] = handle; <ide> cb(0, handle); <ide> } <ide> function workerInit() { <ide> function onconnection(message, handle) { <ide> var key = message.key; <ide> var server = handles[key]; <del> var accepted = !util.isUndefined(server); <add> var accepted = server !== undefined; <ide> send({ ack: message.seq, accepted: accepted }); <ide> if (accepted) server.onconnection(0, handle); <ide> } <ide> function internal(worker, cb) { <ide> return function(message, handle) { <ide> if (message.cmd !== 'NODE_CLUSTER') return; <ide> var fn = cb; <del> if (!util.isUndefined(message.ack)) { <add> if (message.ack !== undefined) { <ide> fn = callbacks[message.ack]; <ide> delete callbacks[message.ack]; <ide> } <ide><path>lib/console.js <ide> function Console(stdout, stderr) { <ide> if (!(this instanceof Console)) { <ide> return new Console(stdout, stderr); <ide> } <del> if (!stdout || !util.isFunction(stdout.write)) { <add> if (!stdout || typeof stdout.write !== 'function') { <ide> throw new TypeError('Console expects a writable stream instance'); <ide> } <ide> if (!stderr) { <ide><path>lib/crypto.js <ide> const DH_GENERATOR = 2; <ide> // to break them unnecessarily. <ide> function toBuf(str, encoding) { <ide> encoding = encoding || 'binary'; <del> if (util.isString(str)) { <add> if (typeof str === 'string') { <ide> if (encoding === 'buffer') <ide> encoding = 'binary'; <ide> str = new Buffer(str, encoding); <ide> Hash.prototype._flush = function(callback) { <ide> <ide> Hash.prototype.update = function(data, encoding) { <ide> encoding = encoding || exports.DEFAULT_ENCODING; <del> if (encoding === 'buffer' && util.isString(data)) <add> if (encoding === 'buffer' && typeof data === 'string') <ide> encoding = 'binary'; <ide> this._handle.update(data, encoding); <ide> return this; <ide> function DiffieHellman(sizeOrKey, keyEncoding, generator, genEncoding) { <ide> if (!(this instanceof DiffieHellman)) <ide> return new DiffieHellman(sizeOrKey, keyEncoding, generator, genEncoding); <ide> <del> if (!util.isBuffer(sizeOrKey) && <add> if (!(sizeOrKey instanceof Buffer) && <ide> typeof sizeOrKey !== 'number' && <ide> typeof sizeOrKey !== 'string') <ide> throw new TypeError('First argument should be number, string or Buffer'); <ide> DiffieHellman.prototype.setPrivateKey = function(key, encoding) { <ide> <ide> <ide> function ECDH(curve) { <del> if (!util.isString(curve)) <add> if (typeof curve !== 'string') <ide> throw new TypeError('curve should be a string'); <ide> <ide> this._handle = new binding.ECDH(curve); <ide> exports.pbkdf2 = function(password, <ide> keylen, <ide> digest, <ide> callback) { <del> if (util.isFunction(digest)) { <add> if (typeof digest === 'function') { <ide> callback = digest; <ide> digest = undefined; <ide> } <ide> <del> if (!util.isFunction(callback)) <add> if (typeof callback !== 'function') <ide> throw new Error('No callback provided to pbkdf2'); <ide> <ide> return pbkdf2(password, salt, iterations, keylen, digest, callback); <ide> Certificate.prototype.exportChallenge = function(object, encoding) { <ide> <ide> <ide> exports.setEngine = function setEngine(id, flags) { <del> if (!util.isString(id)) <add> if (typeof id !== 'string') <ide> throw new TypeError('id should be a string'); <ide> <del> if (flags && !util.isNumber(flags)) <add> if (flags && typeof flags !== 'number') <ide> throw new TypeError('flags should be a number, if present'); <ide> flags = flags >>> 0; <ide> <ide><path>lib/dgram.js <ide> function newHandle(type) { <ide> <ide> exports._createSocketHandle = function(address, port, addressType, fd) { <ide> // Opening an existing fd is not supported for UDP handles. <del> assert(!util.isNumber(fd) || fd < 0); <add> assert(typeof fd !== 'number' || fd < 0); <ide> <ide> var handle = newHandle(addressType); <ide> <ide> function Socket(type, listener) { <ide> // If true - UV_UDP_REUSEADDR flag will be set <ide> this._reuseAddr = options && options.reuseAddr; <ide> <del> if (util.isFunction(listener)) <add> if (typeof listener === 'function') <ide> this.on('message', listener); <ide> } <ide> util.inherits(Socket, events.EventEmitter); <ide> Socket.prototype.bind = function(port /*, address, callback*/) { <ide> <ide> this._bindState = BIND_STATE_BINDING; <ide> <del> if (util.isFunction(arguments[arguments.length - 1])) <add> if (typeof arguments[arguments.length - 1] === 'function') <ide> self.once('listening', arguments[arguments.length - 1]); <ide> <ide> const UDP = process.binding('udp_wrap').UDP; <ide> Socket.prototype.bind = function(port /*, address, callback*/) { <ide> var address; <ide> var exclusive; <ide> <del> if (util.isObject(port)) { <add> if (port !== null && typeof port === 'object') { <ide> address = port.address || ''; <ide> exclusive = !!port.exclusive; <ide> port = port.port; <ide> } else { <del> address = util.isFunction(arguments[1]) ? '' : arguments[1]; <add> address = typeof arguments[1] === 'function' ? '' : arguments[1]; <ide> exclusive = false; <ide> } <ide> <ide> Socket.prototype.sendto = function(buffer, <ide> port, <ide> address, <ide> callback) { <del> if (!util.isNumber(offset) || !util.isNumber(length)) <add> if (typeof offset !== 'number' || typeof length !== 'number') <ide> throw new Error('send takes offset and length as args 2 and 3'); <ide> <del> if (!util.isString(address)) <add> if (typeof address !== 'string') <ide> throw new Error(this.type + ' sockets must send to port, address'); <ide> <ide> this.send(buffer, offset, length, port, address, callback); <ide> Socket.prototype.send = function(buffer, <ide> callback) { <ide> var self = this; <ide> <del> if (util.isString(buffer)) <add> if (typeof buffer === 'string') <ide> buffer = new Buffer(buffer); <ide> <del> if (!util.isBuffer(buffer)) <add> if (!(buffer instanceof Buffer)) <ide> throw new TypeError('First argument must be a buffer or string.'); <ide> <ide> offset = offset | 0; <ide> Socket.prototype.send = function(buffer, <ide> <ide> // Normalize callback so it's either a function or undefined but not anything <ide> // else. <del> if (!util.isFunction(callback)) <add> if (typeof callback !== 'function') <ide> callback = undefined; <ide> <ide> self._healthCheck(); <ide> Socket.prototype.setBroadcast = function(arg) { <ide> <ide> <ide> Socket.prototype.setTTL = function(arg) { <del> if (!util.isNumber(arg)) { <add> if (typeof arg !== 'number') { <ide> throw new TypeError('Argument must be a number'); <ide> } <ide> <ide> Socket.prototype.setTTL = function(arg) { <ide> <ide> <ide> Socket.prototype.setMulticastTTL = function(arg) { <del> if (!util.isNumber(arg)) { <add> if (typeof arg !== 'number') { <ide> throw new TypeError('Argument must be a number'); <ide> } <ide> <ide><path>lib/dns.js <ide> function errnoException(err, syscall, hostname) { <ide> // callback.immediately = true; <ide> // } <ide> function makeAsync(callback) { <del> if (!util.isFunction(callback)) { <add> if (typeof callback !== 'function') { <ide> return callback; <ide> } <ide> return function asyncCallback() { <ide> exports.lookup = function lookup(hostname, options, callback) { <ide> family = 0; <ide> } else if (typeof callback !== 'function') { <ide> throw TypeError('invalid arguments: callback must be passed'); <del> } else if (util.isObject(options)) { <add> } else if (options !== null && typeof options === 'object') { <ide> hints = options.hints >>> 0; <ide> family = options.family >>> 0; <ide> <ide> function resolver(bindingName) { <ide> var binding = cares[bindingName]; <ide> <ide> return function query(name, callback) { <del> if (!util.isString(name)) { <add> if (typeof name !== 'string') { <ide> throw new Error('Name must be a string'); <del> } else if (!util.isFunction(callback)) { <add> } else if (typeof callback !== 'function') { <ide> throw new Error('Callback must be a function'); <ide> } <ide> <ide> exports.reverse = resolveMap.PTR = resolver('getHostByAddr'); <ide> <ide> exports.resolve = function(hostname, type_, callback_) { <ide> var resolver, callback; <del> if (util.isString(type_)) { <add> if (typeof type_ === 'string') { <ide> resolver = resolveMap[type_]; <ide> callback = callback_; <del> } else if (util.isFunction(type_)) { <add> } else if (typeof type_ === 'function') { <ide> resolver = exports.resolve4; <ide> callback = type_; <ide> } else { <ide> throw new Error('Type must be a string'); <ide> } <ide> <del> if (util.isFunction(resolver)) { <add> if (typeof resolver === 'function') { <ide> return resolver(hostname, callback); <ide> } else { <ide> throw new Error('Unknown type "' + type_ + '"'); <ide><path>lib/events.js <ide> 'use strict'; <ide> <ide> var domain; <del>const util = require('util'); <ide> <ide> function EventEmitter() { <ide> EventEmitter.init.call(this); <ide> EventEmitter.init = function() { <ide> // Obviously not all Emitters should be limited to 10. This function allows <ide> // that to be increased. Set to zero for unlimited. <ide> EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { <del> if (!util.isNumber(n) || n < 0 || isNaN(n)) <add> if (typeof n !== 'number' || n < 0 || isNaN(n)) <ide> throw TypeError('n must be a positive number'); <ide> this._maxListeners = n; <ide> return this; <ide> }; <ide> <ide> function $getMaxListeners(that) { <del> if (util.isUndefined(that._maxListeners)) <add> if (that._maxListeners === undefined) <ide> return EventEmitter.defaultMaxListeners; <ide> return that._maxListeners; <ide> } <ide> EventEmitter.prototype.emit = function emit(type) { <ide> <ide> handler = this._events[type]; <ide> <del> if (util.isUndefined(handler)) <add> if (handler === undefined) <ide> return false; <ide> <ide> if (this.domain && this !== process) <ide> this.domain.enter(); <ide> <del> if (util.isFunction(handler)) { <add> if (typeof handler === 'function') { <ide> switch (arguments.length) { <ide> // fast cases <ide> case 1: <ide> EventEmitter.prototype.emit = function emit(type) { <ide> args[i - 1] = arguments[i]; <ide> handler.apply(this, args); <ide> } <del> } else if (util.isObject(handler)) { <add> } else if (handler !== null && typeof handler === 'object') { <ide> len = arguments.length; <ide> args = new Array(len - 1); <ide> for (i = 1; i < len; i++) <ide> EventEmitter.prototype.emit = function emit(type) { <ide> EventEmitter.prototype.addListener = function addListener(type, listener) { <ide> var m; <ide> <del> if (!util.isFunction(listener)) <add> if (typeof listener !== 'function') <ide> throw TypeError('listener must be a function'); <ide> <ide> if (!this._events) <ide> EventEmitter.prototype.addListener = function addListener(type, listener) { <ide> // adding it to the listeners, first emit "newListener". <ide> if (this._events.newListener) <ide> this.emit('newListener', type, <del> util.isFunction(listener.listener) ? <add> typeof listener.listener === 'function' ? <ide> listener.listener : listener); <ide> <ide> if (!this._events[type]) <ide> // Optimize the case of one listener. Don't need the extra array object. <ide> this._events[type] = listener; <del> else if (util.isObject(this._events[type])) <add> else if (typeof this._events[type] === 'object') <ide> // If we've already got an array, just append. <ide> this._events[type].push(listener); <ide> else <ide> // Adding the second element, need to change to array. <ide> this._events[type] = [this._events[type], listener]; <ide> <ide> // Check for listener leak <del> if (util.isObject(this._events[type]) && !this._events[type].warned) { <add> if (this._events[type] !== null && typeof this._events[type] === 'object' && <add> !this._events[type].warned) { <ide> var m = $getMaxListeners(this); <ide> if (m && m > 0 && this._events[type].length > m) { <ide> this._events[type].warned = true; <ide> EventEmitter.prototype.addListener = function addListener(type, listener) { <ide> EventEmitter.prototype.on = EventEmitter.prototype.addListener; <ide> <ide> EventEmitter.prototype.once = function once(type, listener) { <del> if (!util.isFunction(listener)) <add> if (typeof listener !== 'function') <ide> throw TypeError('listener must be a function'); <ide> <ide> var fired = false; <ide> EventEmitter.prototype.removeListener = <ide> function removeListener(type, listener) { <ide> var list, position, length, i; <ide> <del> if (!util.isFunction(listener)) <add> if (typeof listener !== 'function') <ide> throw TypeError('listener must be a function'); <ide> <ide> if (!this._events || !this._events[type]) <ide> EventEmitter.prototype.removeListener = <ide> position = -1; <ide> <ide> if (list === listener || <del> (util.isFunction(list.listener) && list.listener === listener)) { <add> (typeof list.listener === 'function' && <add> list.listener === listener)) { <ide> delete this._events[type]; <ide> if (this._events.removeListener) <ide> this.emit('removeListener', type, listener); <ide> <del> } else if (util.isObject(list)) { <add> } else if (list !== null && typeof list === 'object') { <ide> for (i = length; i-- > 0;) { <ide> if (list[i] === listener || <ide> (list[i].listener && list[i].listener === listener)) { <ide> EventEmitter.prototype.removeAllListeners = <ide> <ide> listeners = this._events[type]; <ide> <del> if (util.isFunction(listeners)) { <add> if (typeof listeners === 'function') { <ide> this.removeListener(type, listeners); <ide> } else if (Array.isArray(listeners)) { <ide> // LIFO order <ide> EventEmitter.prototype.listeners = function listeners(type) { <ide> var ret; <ide> if (!this._events || !this._events[type]) <ide> ret = []; <del> else if (util.isFunction(this._events[type])) <add> else if (typeof this._events[type] === 'function') <ide> ret = [this._events[type]]; <ide> else <ide> ret = this._events[type].slice(); <ide> EventEmitter.listenerCount = function(emitter, type) { <ide> var ret; <ide> if (!emitter._events || !emitter._events[type]) <ide> ret = 0; <del> else if (util.isFunction(emitter._events[type])) <add> else if (typeof emitter._events[type] === 'function') <ide> ret = 1; <ide> else <ide> ret = emitter._events[type].length; <ide><path>lib/fs.js <ide> function rethrow() { <ide> } <ide> <ide> function maybeCallback(cb) { <del> return util.isFunction(cb) ? cb : rethrow(); <add> return typeof cb === 'function' ? cb : rethrow(); <ide> } <ide> <ide> // Ensure that callbacks run in the global context. Only use this function <ide> // for callbacks that are passed to the binding layer, callbacks that are <ide> // invoked from JS already run in the proper scope. <ide> function makeCallback(cb) { <del> if (!util.isFunction(cb)) { <add> if (typeof cb !== 'function') { <ide> return rethrow(); <ide> } <ide> <ide> fs.existsSync = function(path) { <ide> fs.readFile = function(path, options, callback_) { <ide> var callback = maybeCallback(arguments[arguments.length - 1]); <ide> <del> if (util.isFunction(options) || !options) { <add> if (!options || typeof options === 'function') { <ide> options = { encoding: null, flag: 'r' }; <del> } else if (util.isString(options)) { <add> } else if (typeof options === 'string') { <ide> options = { encoding: options, flag: 'r' }; <del> } else if (!util.isObject(options)) { <add> } else if (typeof options !== 'object') { <ide> throw new TypeError('Bad arguments'); <ide> } <ide> <ide> fs.readFile = function(path, options, callback_) { <ide> fs.readFileSync = function(path, options) { <ide> if (!options) { <ide> options = { encoding: null, flag: 'r' }; <del> } else if (util.isString(options)) { <add> } else if (typeof options === 'string') { <ide> options = { encoding: options, flag: 'r' }; <del> } else if (!util.isObject(options)) { <add> } else if (typeof options !== 'object') { <ide> throw new TypeError('Bad arguments'); <ide> } <ide> <ide> fs.readFileSync = function(path, options) { <ide> // Used by binding.open and friends <ide> function stringToFlags(flag) { <ide> // Only mess with strings <del> if (!util.isString(flag)) { <add> if (typeof flag !== 'string') { <ide> return flag; <ide> } <ide> <ide> fs.closeSync = function(fd) { <ide> }; <ide> <ide> function modeNum(m, def) { <del> if (util.isNumber(m)) <add> if (typeof m === 'number') <ide> return m; <del> if (util.isString(m)) <add> if (typeof m === 'string') <ide> return parseInt(m, 8); <ide> if (def) <ide> return modeNum(def); <ide> fs.openSync = function(path, flags, mode) { <ide> }; <ide> <ide> fs.read = function(fd, buffer, offset, length, position, callback) { <del> if (!util.isBuffer(buffer)) { <add> if (!(buffer instanceof Buffer)) { <ide> // legacy string interface (fd, length, position, encoding, callback) <ide> var cb = arguments[4], <ide> encoding = arguments[3]; <ide> fs.read = function(fd, buffer, offset, length, position, callback) { <ide> <ide> fs.readSync = function(fd, buffer, offset, length, position) { <ide> var legacy = false; <del> if (!util.isBuffer(buffer)) { <add> if (!(buffer instanceof Buffer)) { <ide> // legacy string interface (fd, length, position, encoding, callback) <ide> legacy = true; <ide> var encoding = arguments[3]; <ide> fs.write = function(fd, buffer, offset, length, position, callback) { <ide> callback(err, written || 0, buffer); <ide> } <ide> <del> if (util.isBuffer(buffer)) { <add> if (buffer instanceof Buffer) { <ide> // if no position is passed then assume null <del> if (util.isFunction(position)) { <add> if (typeof position === 'function') { <ide> callback = position; <ide> position = null; <ide> } <ide> fs.write = function(fd, buffer, offset, length, position, callback) { <ide> return binding.writeBuffer(fd, buffer, offset, length, position, req); <ide> } <ide> <del> if (util.isString(buffer)) <add> if (typeof buffer === 'string') <ide> buffer += ''; <del> if (!util.isFunction(position)) { <del> if (util.isFunction(offset)) { <add> if (typeof position !== 'function') { <add> if (typeof offset === 'function') { <ide> position = offset; <ide> offset = null; <ide> } else { <ide> fs.write = function(fd, buffer, offset, length, position, callback) { <ide> // OR <ide> // fs.writeSync(fd, string[, position[, encoding]]); <ide> fs.writeSync = function(fd, buffer, offset, length, position) { <del> if (util.isBuffer(buffer)) { <del> if (util.isUndefined(position)) <add> if (buffer instanceof Buffer) { <add> if (position === undefined) <ide> position = null; <ide> return binding.writeBuffer(fd, buffer, offset, length, position); <ide> } <del> if (!util.isString(buffer)) <add> if (typeof buffer !== 'string') <ide> buffer += ''; <del> if (util.isUndefined(offset)) <add> if (offset === undefined) <ide> offset = null; <ide> return binding.writeString(fd, buffer, offset, length, position); <ide> }; <ide> fs.renameSync = function(oldPath, newPath) { <ide> }; <ide> <ide> fs.truncate = function(path, len, callback) { <del> if (util.isNumber(path)) { <add> if (typeof path === 'number') { <ide> var req = new FSReqWrap(); <ide> req.oncomplete = callback; <ide> return fs.ftruncate(path, len, req); <ide> } <del> if (util.isFunction(len)) { <add> if (typeof len === 'function') { <ide> callback = len; <ide> len = 0; <del> } else if (util.isUndefined(len)) { <add> } else if (len === undefined) { <ide> len = 0; <ide> } <ide> <ide> fs.truncate = function(path, len, callback) { <ide> }; <ide> <ide> fs.truncateSync = function(path, len) { <del> if (util.isNumber(path)) { <add> if (typeof path === 'number') { <ide> // legacy <ide> return fs.ftruncateSync(path, len); <ide> } <del> if (util.isUndefined(len)) { <add> if (len === undefined) { <ide> len = 0; <ide> } <ide> // allow error to be thrown, but still close fd. <ide> fs.truncateSync = function(path, len) { <ide> }; <ide> <ide> fs.ftruncate = function(fd, len, callback) { <del> if (util.isFunction(len)) { <add> if (typeof len === 'function') { <ide> callback = len; <ide> len = 0; <del> } else if (util.isUndefined(len)) { <add> } else if (len === undefined) { <ide> len = 0; <ide> } <ide> var req = new FSReqWrap(); <ide> fs.ftruncate = function(fd, len, callback) { <ide> }; <ide> <ide> fs.ftruncateSync = function(fd, len) { <del> if (util.isUndefined(len)) { <add> if (len === undefined) { <ide> len = 0; <ide> } <ide> return binding.ftruncate(fd, len); <ide> fs.fsyncSync = function(fd) { <ide> }; <ide> <ide> fs.mkdir = function(path, mode, callback) { <del> if (util.isFunction(mode)) callback = mode; <add> if (typeof mode === 'function') callback = mode; <ide> callback = makeCallback(callback); <ide> if (!nullCheck(path, callback)) return; <ide> var req = new FSReqWrap(); <ide> function preprocessSymlinkDestination(path, type, linkPath) { <ide> } <ide> <ide> fs.symlink = function(destination, path, type_, callback) { <del> var type = (util.isString(type_) ? type_ : null); <add> var type = (typeof type_ === 'string' ? type_ : null); <ide> var callback = makeCallback(arguments[arguments.length - 1]); <ide> <ide> if (!nullCheck(destination, callback)) return; <ide> fs.symlink = function(destination, path, type_, callback) { <ide> }; <ide> <ide> fs.symlinkSync = function(destination, path, type) { <del> type = (util.isString(type) ? type : null); <add> type = (typeof type === 'string' ? type : null); <ide> <ide> nullCheck(destination); <ide> nullCheck(path); <ide> fs.chownSync = function(path, uid, gid) { <ide> <ide> // converts Date or number to a fractional UNIX timestamp <ide> function toUnixTimestamp(time) { <del> if (util.isNumber(time)) { <add> if (typeof time === 'number') { <ide> return time; <ide> } <ide> if (util.isDate(time)) { <ide> function writeAll(fd, buffer, offset, length, position, callback) { <ide> fs.writeFile = function(path, data, options, callback) { <ide> var callback = maybeCallback(arguments[arguments.length - 1]); <ide> <del> if (util.isFunction(options) || !options) { <add> if (!options || typeof options === 'function') { <ide> options = { encoding: 'utf8', mode: 0o666, flag: 'w' }; <del> } else if (util.isString(options)) { <add> } else if (typeof options === 'string') { <ide> options = { encoding: options, mode: 0o666, flag: 'w' }; <del> } else if (!util.isObject(options)) { <add> } else if (typeof options !== 'object') { <ide> throw new TypeError('Bad arguments'); <ide> } <ide> <ide> fs.writeFile = function(path, data, options, callback) { <ide> if (openErr) { <ide> if (callback) callback(openErr); <ide> } else { <del> var buffer = util.isBuffer(data) ? data : new Buffer('' + data, <add> var buffer = (data instanceof Buffer) ? data : new Buffer('' + data, <ide> options.encoding || 'utf8'); <ide> var position = /a/.test(flag) ? null : 0; <ide> writeAll(fd, buffer, 0, buffer.length, position, callback); <ide> fs.writeFile = function(path, data, options, callback) { <ide> fs.writeFileSync = function(path, data, options) { <ide> if (!options) { <ide> options = { encoding: 'utf8', mode: 0o666, flag: 'w' }; <del> } else if (util.isString(options)) { <add> } else if (typeof options === 'string') { <ide> options = { encoding: options, mode: 0o666, flag: 'w' }; <del> } else if (!util.isObject(options)) { <add> } else if (typeof options !== 'object') { <ide> throw new TypeError('Bad arguments'); <ide> } <ide> <ide> assertEncoding(options.encoding); <ide> <ide> var flag = options.flag || 'w'; <ide> var fd = fs.openSync(path, flag, options.mode); <del> if (!util.isBuffer(data)) { <add> if (!(data instanceof Buffer)) { <ide> data = new Buffer('' + data, options.encoding || 'utf8'); <ide> } <ide> var written = 0; <ide> fs.writeFileSync = function(path, data, options) { <ide> fs.appendFile = function(path, data, options, callback_) { <ide> var callback = maybeCallback(arguments[arguments.length - 1]); <ide> <del> if (util.isFunction(options) || !options) { <add> if (!options || typeof options === 'function') { <ide> options = { encoding: 'utf8', mode: 0o666, flag: 'a' }; <del> } else if (util.isString(options)) { <add> } else if (typeof options === 'string') { <ide> options = { encoding: options, mode: 0o666, flag: 'a' }; <del> } else if (!util.isObject(options)) { <add> } else if (typeof options !== 'object') { <ide> throw new TypeError('Bad arguments'); <ide> } <ide> <ide> fs.appendFile = function(path, data, options, callback_) { <ide> fs.appendFileSync = function(path, data, options) { <ide> if (!options) { <ide> options = { encoding: 'utf8', mode: 0o666, flag: 'a' }; <del> } else if (util.isString(options)) { <add> } else if (typeof options === 'string') { <ide> options = { encoding: options, mode: 0o666, flag: 'a' }; <del> } else if (!util.isObject(options)) { <add> } else if (typeof options !== 'object') { <ide> throw new TypeError('Bad arguments'); <ide> } <ide> if (!options.flag) <ide> fs.watch = function(filename) { <ide> var options; <ide> var listener; <ide> <del> if (util.isObject(arguments[1])) { <add> if (arguments[1] !== null && typeof arguments[1] === 'object') { <ide> options = arguments[1]; <ide> listener = arguments[2]; <ide> } else { <ide> options = {}; <ide> listener = arguments[1]; <ide> } <ide> <del> if (util.isUndefined(options.persistent)) options.persistent = true; <del> if (util.isUndefined(options.recursive)) options.recursive = false; <add> if (options.persistent === undefined) options.persistent = true; <add> if (options.recursive === undefined) options.recursive = false; <ide> <ide> watcher = new FSWatcher(); <ide> watcher.start(filename, options.persistent, options.recursive); <ide> fs.watchFile = function(filename) { <ide> persistent: true <ide> }; <ide> <del> if (util.isObject(arguments[1])) { <add> if (arguments[1] !== null && typeof arguments[1] === 'object') { <ide> options = util._extend(options, arguments[1]); <ide> listener = arguments[2]; <ide> } else { <ide> fs.unwatchFile = function(filename, listener) { <ide> <ide> var stat = statWatchers[filename]; <ide> <del> if (util.isFunction(listener)) { <add> if (typeof listener === 'function') { <ide> stat.removeListener('change', listener); <ide> } else { <ide> stat.removeAllListeners('change'); <ide> fs.realpathSync = function realpathSync(p, cache) { <ide> linkTarget = seenLinks[id]; <ide> } <ide> } <del> if (util.isNull(linkTarget)) { <add> if (linkTarget === null) { <ide> fs.statSync(base); <ide> linkTarget = fs.readlinkSync(base); <ide> } <ide> fs.realpathSync = function realpathSync(p, cache) { <ide> <ide> <ide> fs.realpath = function realpath(p, cache, cb) { <del> if (!util.isFunction(cb)) { <add> if (typeof cb !== 'function') { <ide> cb = maybeCallback(cache); <ide> cache = null; <ide> } <ide> function ReadStream(path, options) { <ide> options.autoClose : true; <ide> this.pos = undefined; <ide> <del> if (!util.isUndefined(this.start)) { <del> if (!util.isNumber(this.start)) { <add> if (this.start !== undefined) { <add> if (typeof this.start !== 'number') { <ide> throw TypeError('start must be a Number'); <ide> } <del> if (util.isUndefined(this.end)) { <add> if (this.end === undefined) { <ide> this.end = Infinity; <del> } else if (!util.isNumber(this.end)) { <add> } else if (typeof this.end !== 'number') { <ide> throw TypeError('end must be a Number'); <ide> } <ide> <ide> function ReadStream(path, options) { <ide> this.pos = this.start; <ide> } <ide> <del> if (!util.isNumber(this.fd)) <add> if (typeof this.fd !== 'number') <ide> this.open(); <ide> <ide> this.on('end', function() { <ide> ReadStream.prototype.open = function() { <ide> }; <ide> <ide> ReadStream.prototype._read = function(n) { <del> if (!util.isNumber(this.fd)) <add> if (typeof this.fd !== 'number') <ide> return this.once('open', function() { <ide> this._read(n); <ide> }); <ide> ReadStream.prototype._read = function(n) { <ide> var toRead = Math.min(pool.length - pool.used, n); <ide> var start = pool.used; <ide> <del> if (!util.isUndefined(this.pos)) <add> if (this.pos !== undefined) <ide> toRead = Math.min(this.end - this.pos + 1, toRead); <ide> <ide> // already read everything we were supposed to read! <ide> ReadStream.prototype._read = function(n) { <ide> fs.read(this.fd, pool, pool.used, toRead, this.pos, onread); <ide> <ide> // move the pool positions, and internal position for reading. <del> if (!util.isUndefined(this.pos)) <add> if (this.pos !== undefined) <ide> this.pos += toRead; <ide> pool.used += toRead; <ide> <ide> ReadStream.prototype.close = function(cb) { <ide> var self = this; <ide> if (cb) <ide> this.once('close', cb); <del> if (this.closed || !util.isNumber(this.fd)) { <del> if (!util.isNumber(this.fd)) { <add> if (this.closed || typeof this.fd !== 'number') { <add> if (typeof this.fd !== 'number') { <ide> this.once('open', close); <ide> return; <ide> } <ide> function WriteStream(path, options) { <ide> this.pos = undefined; <ide> this.bytesWritten = 0; <ide> <del> if (!util.isUndefined(this.start)) { <del> if (!util.isNumber(this.start)) { <add> if (this.start !== undefined) { <add> if (typeof this.start !== 'number') { <ide> throw TypeError('start must be a Number'); <ide> } <ide> if (this.start < 0) { <ide> function WriteStream(path, options) { <ide> this.pos = this.start; <ide> } <ide> <del> if (!util.isNumber(this.fd)) <add> if (typeof this.fd !== 'number') <ide> this.open(); <ide> <ide> // dispose on finish. <ide> WriteStream.prototype.open = function() { <ide> <ide> <ide> WriteStream.prototype._write = function(data, encoding, cb) { <del> if (!util.isBuffer(data)) <add> if (!(data instanceof Buffer)) <ide> return this.emit('error', new Error('Invalid data')); <ide> <del> if (!util.isNumber(this.fd)) <add> if (typeof this.fd !== 'number') <ide> return this.once('open', function() { <ide> this._write(data, encoding, cb); <ide> }); <ide> WriteStream.prototype._write = function(data, encoding, cb) { <ide> cb(); <ide> }); <ide> <del> if (!util.isUndefined(this.pos)) <add> if (this.pos !== undefined) <ide> this.pos += data.length; <ide> }; <ide> <ide> SyncWriteStream.prototype.write = function(data, arg1, arg2) { <ide> <ide> // parse arguments <ide> if (arg1) { <del> if (util.isString(arg1)) { <add> if (typeof arg1 === 'string') { <ide> encoding = arg1; <ide> cb = arg2; <del> } else if (util.isFunction(arg1)) { <add> } else if (typeof arg1 === 'function') { <ide> cb = arg1; <ide> } else { <ide> throw new Error('bad arg'); <ide> SyncWriteStream.prototype.write = function(data, arg1, arg2) { <ide> assertEncoding(encoding); <ide> <ide> // Change strings to buffers. SLOW <del> if (util.isString(data)) { <add> if (typeof data === 'string') { <ide> data = new Buffer(data, encoding); <ide> } <ide> <ide><path>lib/https.js <ide> const tls = require('tls'); <ide> const url = require('url'); <ide> const http = require('http'); <ide> const util = require('util'); <del>const inherits = require('util').inherits; <add>const inherits = util.inherits; <ide> const debug = util.debuglog('https'); <ide> <ide> function Server(opts, requestListener) { <ide> exports.createServer = function(opts, requestListener) { <ide> // HTTPS agents. <ide> <ide> function createConnection(port, host, options) { <del> if (util.isObject(port)) { <add> if (port !== null && typeof port === 'object') { <ide> options = port; <del> } else if (util.isObject(host)) { <add> } else if (host !== null && typeof host === 'object') { <ide> options = host; <del> } else if (util.isObject(options)) { <add> } else if (options !== null && typeof options === 'object') { <ide> options = options; <ide> } else { <ide> options = {}; <ide> } <ide> <del> if (util.isNumber(port)) { <add> if (typeof port === 'number') { <ide> options.port = port; <ide> } <ide> <del> if (util.isString(host)) { <add> if (typeof host === 'string') { <ide> options.host = host; <ide> } <ide> <ide> Agent.prototype.getName = function(options) { <ide> name += options.pfx; <ide> <ide> name += ':'; <del> if (!util.isUndefined(options.rejectUnauthorized)) <add> if (options.rejectUnauthorized !== undefined) <ide> name += options.rejectUnauthorized; <ide> <ide> return name; <ide> exports.globalAgent = globalAgent; <ide> exports.Agent = Agent; <ide> <ide> exports.request = function(options, cb) { <del> if (util.isString(options)) { <add> if (typeof options === 'string') { <ide> options = url.parse(options); <ide> } else { <ide> options = util._extend({}, options); <ide><path>lib/module.js <ide> Module.prototype.load = function(filename) { <ide> // `exports` property. <ide> Module.prototype.require = function(path) { <ide> assert(path, 'missing path'); <del> assert(util.isString(path), 'path must be a string'); <add> assert(typeof path === 'string', 'path must be a string'); <ide> return Module._load(path, this); <ide> }; <ide> <ide><path>lib/net.js <ide> function createHandle(fd) { <ide> const debug = util.debuglog('net'); <ide> <ide> function isPipeName(s) { <del> return util.isString(s) && toNumber(s) === false; <add> return typeof s === 'string' && toNumber(s) === false; <ide> } <ide> <ide> exports.createServer = function() { <ide> exports.connect = exports.createConnection = function() { <ide> function normalizeConnectArgs(args) { <ide> var options = {}; <ide> <del> if (util.isObject(args[0])) { <add> if (args[0] !== null && typeof args[0] === 'object') { <ide> // connect(options, [cb]) <ide> options = args[0]; <ide> } else if (isPipeName(args[0])) { <ide> function normalizeConnectArgs(args) { <ide> } else { <ide> // connect(port, [host], [cb]) <ide> options.port = args[0]; <del> if (util.isString(args[1])) { <add> if (typeof args[1] === 'string') { <ide> options.host = args[1]; <ide> } <ide> } <ide> <ide> var cb = args[args.length - 1]; <del> return util.isFunction(cb) ? [options, cb] : [options]; <add> return typeof cb === 'function' ? [options, cb] : [options]; <ide> } <ide> exports._normalizeConnectArgs = normalizeConnectArgs; <ide> <ide> function Socket(options) { <ide> this._handle = null; <ide> this._host = null; <ide> <del> if (util.isNumber(options)) <add> if (typeof options === 'number') <ide> options = { fd: options }; // Legacy interface. <del> else if (util.isUndefined(options)) <add> else if (options === undefined) <ide> options = {}; <ide> <ide> stream.Duplex.call(this, options); <ide> <ide> if (options.handle) { <ide> this._handle = options.handle; // private <del> } else if (!util.isUndefined(options.fd)) { <add> } else if (options.fd !== undefined) { <ide> this._handle = createHandle(options.fd); <ide> this._handle.open(options.fd); <ide> if ((options.fd == 1 || options.fd == 2) && <ide> function onSocketEnd() { <ide> // of the other side sending a FIN. The standard 'write after end' <ide> // is overly vague, and makes it seem like the user's code is to blame. <ide> function writeAfterFIN(chunk, encoding, cb) { <del> if (util.isFunction(encoding)) { <add> if (typeof encoding === 'function') { <ide> cb = encoding; <ide> encoding = null; <ide> } <ide> function writeAfterFIN(chunk, encoding, cb) { <ide> var self = this; <ide> // TODO: defer error events consistently everywhere, not just the cb <ide> self.emit('error', er); <del> if (util.isFunction(cb)) { <add> if (typeof cb === 'function') { <ide> process.nextTick(function() { <ide> cb(er); <ide> }); <ide> Socket.prototype._onTimeout = function() { <ide> Socket.prototype.setNoDelay = function(enable) { <ide> // backwards compatibility: assume true when `enable` is omitted <ide> if (this._handle && this._handle.setNoDelay) <del> this._handle.setNoDelay(util.isUndefined(enable) ? true : !!enable); <add> this._handle.setNoDelay(enable === undefined ? true : !!enable); <ide> }; <ide> <ide> <ide> Socket.prototype.__defineGetter__('localPort', function() { <ide> <ide> <ide> Socket.prototype.write = function(chunk, encoding, cb) { <del> if (!util.isString(chunk) && !util.isBuffer(chunk)) <add> if (typeof chunk !== 'string' && !(chunk instanceof Buffer)) <ide> throw new TypeError('invalid data'); <ide> return stream.Duplex.prototype.write.apply(this, arguments); <ide> }; <ide> Socket.prototype._writeGeneric = function(writev, data, encoding, cb) { <ide> if (err === 0) req._chunks = chunks; <ide> } else { <ide> var enc; <del> if (util.isBuffer(data)) { <add> if (data instanceof Buffer) { <ide> req.buffer = data; // Keep reference alive. <ide> enc = 'buffer'; <ide> } else { <ide> Socket.prototype.__defineGetter__('bytesWritten', function() { <ide> encoding = this._pendingEncoding; <ide> <ide> state.getBuffer().forEach(function(el) { <del> if (util.isBuffer(el.chunk)) <add> if (el.chunk instanceof Buffer) <ide> bytes += el.chunk.length; <ide> else <ide> bytes += Buffer.byteLength(el.chunk, el.encoding); <ide> }); <ide> <ide> if (data) { <del> if (util.isBuffer(data)) <add> if (data instanceof Buffer) <ide> bytes += data.length; <ide> else <ide> bytes += Buffer.byteLength(data, encoding); <ide> Socket.prototype.connect = function(options, cb) { <ide> if (this.write !== Socket.prototype.write) <ide> this.write = Socket.prototype.write; <ide> <del> if (!util.isObject(options)) { <add> if (options === null || typeof options !== 'object') { <ide> // Old API: <ide> // connect(port, [host], [cb]) <ide> // connect(path, [cb]); <ide> Socket.prototype.connect = function(options, cb) { <ide> initSocketHandle(this); <ide> } <ide> <del> if (util.isFunction(cb)) { <add> if (typeof cb === 'function') { <ide> self.once('connect', cb); <ide> } <ide> <ide> Socket.prototype.connect = function(options, cb) { <ide> if (localAddress && !exports.isIP(localAddress)) <ide> throw new TypeError('localAddress must be a valid IP: ' + localAddress); <ide> <del> if (localPort && !util.isNumber(localPort)) <add> if (localPort && typeof localPort !== 'number') <ide> throw new TypeError('localPort should be a number: ' + localPort); <ide> <ide> if (port <= 0 || port > 65535) <ide> function Server(/* [ options, ] listener */) { <ide> <ide> var options; <ide> <del> if (util.isFunction(arguments[0])) { <add> if (typeof arguments[0] === 'function') { <ide> options = {}; <ide> self.on('connection', arguments[0]); <ide> } else { <ide> options = arguments[0] || {}; <ide> <del> if (util.isFunction(arguments[1])) { <add> if (typeof arguments[1] === 'function') { <ide> self.on('connection', arguments[1]); <ide> } <ide> } <ide> var createServerHandle = exports._createServerHandle = <ide> var handle; <ide> <ide> var isTCP = false; <del> if (util.isNumber(fd) && fd >= 0) { <add> if (typeof fd === 'number' && fd >= 0) { <ide> try { <ide> handle = createHandle(fd); <ide> } <ide> Server.prototype._listen2 = function(address, port, addressType, backlog, fd) { <ide> <ide> var rval = null; <ide> <del> if (!address && !util.isNumber(fd)) { <add> if (!address && typeof fd !== 'number') { <ide> rval = createServerHandle('::', port, 6, fd); <ide> <del> if (util.isNumber(rval)) { <add> if (typeof rval === 'number') { <ide> rval = null; <ide> address = '0.0.0.0'; <ide> addressType = 4; <ide> Server.prototype._listen2 = function(address, port, addressType, backlog, fd) { <ide> if (rval === null) <ide> rval = createServerHandle(address, port, addressType, fd); <ide> <del> if (util.isNumber(rval)) { <add> if (typeof rval === 'number') { <ide> var error = exceptionWithHostPort(rval, 'listen', address, port); <ide> process.nextTick(function() { <ide> self.emit('error', error); <ide> Server.prototype.listen = function() { <ide> var self = this; <ide> <ide> var lastArg = arguments[arguments.length - 1]; <del> if (util.isFunction(lastArg)) { <add> if (typeof lastArg === 'function') { <ide> self.once('listening', lastArg); <ide> } <ide> <ide> Server.prototype.listen = function() { <ide> <ide> const TCP = process.binding('tcp_wrap').TCP; <ide> <del> if (arguments.length === 0 || util.isFunction(arguments[0])) { <add> if (arguments.length === 0 || typeof arguments[0] === 'function') { <ide> // Bind to a random port. <ide> listen(self, null, 0, null, backlog); <del> } else if (util.isObject(arguments[0])) { <add> } else if (arguments[0] !== null && typeof arguments[0] === 'object') { <ide> var h = arguments[0]; <ide> h = h._handle || h.handle || h; <ide> <ide> if (h instanceof TCP) { <ide> self._handle = h; <ide> listen(self, null, -1, -1, backlog); <del> } else if (util.isNumber(h.fd) && h.fd >= 0) { <add> } else if (typeof h.fd === 'number' && h.fd >= 0) { <ide> listen(self, null, null, null, backlog, h.fd); <ide> } else { <ide> // The first argument is a configuration object <ide> if (h.backlog) <ide> backlog = h.backlog; <ide> <del> if (util.isNumber(h.port)) { <add> if (typeof h.port === 'number') { <ide> if (h.host) <ide> listenAfterLookup(h.port, h.host, backlog, h.exclusive); <ide> else <ide> Server.prototype.listen = function() { <ide> var pipeName = self._pipeName = arguments[0]; <ide> listen(self, pipeName, -1, -1, backlog); <ide> <del> } else if (util.isUndefined(arguments[1]) || <del> util.isFunction(arguments[1]) || <del> util.isNumber(arguments[1])) { <add> } else if (arguments[1] === undefined || <add> typeof arguments[1] === 'function' || <add> typeof arguments[1] === 'number') { <ide> // The first argument is the port, no IP given. <ide> listen(self, null, port, 4, backlog); <ide> <ide> if (process.platform === 'win32') { <ide> var simultaneousAccepts; <ide> <ide> exports._setSimultaneousAccepts = function(handle) { <del> if (util.isUndefined(handle)) { <add> if (handle === undefined) { <ide> return; <ide> } <ide> <del> if (util.isUndefined(simultaneousAccepts)) { <add> if (simultaneousAccepts === undefined) { <ide> simultaneousAccepts = (process.env.NODE_MANY_ACCEPTS && <ide> process.env.NODE_MANY_ACCEPTS !== '0'); <ide> } <ide><path>lib/path.js <ide> 'use strict'; <ide> <ide> const isWindows = process.platform === 'win32'; <del>const util = require('util'); <del> <ide> <ide> // resolves . and .. elements in a path array with directory names there <ide> // must be no slashes or device names (c:\) in the array <ide> win32.resolve = function() { <ide> } <ide> <ide> // Skip empty and invalid entries <del> if (!util.isString(path)) { <add> if (typeof path !== 'string') { <ide> throw new TypeError('Arguments to path.resolve must be strings'); <ide> } else if (!path) { <ide> continue; <ide> win32.isAbsolute = function(path) { <ide> <ide> win32.join = function() { <ide> function f(p) { <del> if (!util.isString(p)) { <add> if (typeof p !== 'string') { <ide> throw new TypeError('Arguments to path.join must be strings'); <ide> } <ide> return p; <ide> win32.relative = function(from, to) { <ide> <ide> win32._makeLong = function(path) { <ide> // Note: this will *probably* throw somewhere. <del> if (!util.isString(path)) <add> if (typeof path !== 'string') <ide> return path; <ide> <ide> if (!path) { <ide> win32.extname = function(path) { <ide> <ide> <ide> win32.format = function(pathObject) { <del> if (!util.isObject(pathObject)) { <add> if (pathObject === null || typeof pathObject !== 'object') { <ide> throw new TypeError( <ide> "Parameter 'pathObject' must be an object, not " + typeof pathObject <ide> ); <ide> } <ide> <ide> var root = pathObject.root || ''; <ide> <del> if (!util.isString(root)) { <add> if (typeof root !== 'string') { <ide> throw new TypeError( <ide> "'pathObject.root' must be a string or undefined, not " + <ide> typeof pathObject.root <ide> win32.format = function(pathObject) { <ide> <ide> <ide> win32.parse = function(pathString) { <del> if (!util.isString(pathString)) { <add> if (typeof pathString !== 'string') { <ide> throw new TypeError( <ide> "Parameter 'pathString' must be a string, not " + typeof pathString <ide> ); <ide> posix.resolve = function() { <ide> var path = (i >= 0) ? arguments[i] : process.cwd(); <ide> <ide> // Skip empty and invalid entries <del> if (!util.isString(path)) { <add> if (typeof path !== 'string') { <ide> throw new TypeError('Arguments to path.resolve must be strings'); <ide> } else if (!path) { <ide> continue; <ide> posix.join = function() { <ide> var path = ''; <ide> for (var i = 0; i < arguments.length; i++) { <ide> var segment = arguments[i]; <del> if (!util.isString(segment)) { <add> if (typeof segment !== 'string') { <ide> throw new TypeError('Arguments to path.join must be strings'); <ide> } <ide> if (segment) { <ide> posix.extname = function(path) { <ide> <ide> <ide> posix.format = function(pathObject) { <del> if (!util.isObject(pathObject)) { <add> if (pathObject === null || typeof pathObject !== 'object') { <ide> throw new TypeError( <ide> "Parameter 'pathObject' must be an object, not " + typeof pathObject <ide> ); <ide> } <ide> <ide> var root = pathObject.root || ''; <ide> <del> if (!util.isString(root)) { <add> if (typeof root !== 'string') { <ide> throw new TypeError( <ide> "'pathObject.root' must be a string or undefined, not " + <ide> typeof pathObject.root <ide> posix.format = function(pathObject) { <ide> <ide> <ide> posix.parse = function(pathString) { <del> if (!util.isString(pathString)) { <add> if (typeof pathString !== 'string') { <ide> throw new TypeError( <ide> "Parameter 'pathString' must be a string, not " + typeof pathString <ide> ); <ide><path>lib/querystring.js <ide> 'use strict'; <ide> <ide> const QueryString = exports; <del>const util = require('util'); <del> <ide> <ide> // If obj.hasOwnProperty has been overridden, then calling <ide> // obj.hasOwnProperty(prop) will break. <ide> QueryString.escape = function(str) { <ide> }; <ide> <ide> var stringifyPrimitive = function(v) { <del> if (util.isString(v)) <add> let type = typeof v; <add> <add> if (type === 'string') <ide> return v; <del> if (util.isBoolean(v)) <add> if (type === 'boolean') <ide> return v ? 'true' : 'false'; <del> if (util.isNumber(v)) <add> if (type === 'number') <ide> return isFinite(v) ? v : ''; <ide> return ''; <ide> }; <ide> QueryString.stringify = QueryString.encode = function(obj, sep, eq, options) { <ide> encode = options.encodeURIComponent; <ide> } <ide> <del> if (util.isObject(obj)) { <add> if (obj !== null && typeof obj === 'object') { <ide> var keys = Object.keys(obj); <ide> var fields = []; <ide> <ide> QueryString.stringify = QueryString.encode = function(obj, sep, eq, options) { <ide> var v = obj[k]; <ide> var ks = encode(stringifyPrimitive(k)) + eq; <ide> <del> if (util.isArray(v)) { <add> if (Array.isArray(v)) { <ide> for (var j = 0; j < v.length; j++) <ide> fields.push(ks + encode(stringifyPrimitive(v[j]))); <ide> } else { <ide> QueryString.parse = QueryString.decode = function(qs, sep, eq, options) { <ide> eq = eq || '='; <ide> var obj = {}; <ide> <del> if (!util.isString(qs) || qs.length === 0) { <add> if (typeof qs !== 'string' || qs.length === 0) { <ide> return obj; <ide> } <ide> <ide> var regexp = /\+/g; <ide> qs = qs.split(sep); <ide> <ide> var maxKeys = 1000; <del> if (options && util.isNumber(options.maxKeys)) { <add> if (options && typeof options.maxKeys === 'number') { <ide> maxKeys = options.maxKeys; <ide> } <ide> <ide> QueryString.parse = QueryString.decode = function(qs, sep, eq, options) { <ide> <ide> if (!hasOwnProperty(obj, k)) { <ide> obj[k] = v; <del> } else if (util.isArray(obj[k])) { <add> } else if (Array.isArray(obj[k])) { <ide> obj[k].push(v); <ide> } else { <ide> obj[k] = [obj[k], v]; <ide><path>lib/readline.js <ide> function Interface(input, output, completer, terminal) { <ide> <ide> completer = completer || function() { return []; }; <ide> <del> if (!util.isFunction(completer)) { <add> if (typeof completer !== 'function') { <ide> throw new TypeError('Argument \'completer\' must be a function'); <ide> } <ide> <ide> // backwards compat; check the isTTY prop of the output stream <ide> // when `terminal` was not specified <del> if (util.isUndefined(terminal) && !util.isNullOrUndefined(output)) { <add> if (terminal === undefined && !(output === null || output === undefined)) { <ide> terminal = !!output.isTTY; <ide> } <ide> <ide> function Interface(input, output, completer, terminal) { <ide> } <ide> <ide> function onend() { <del> if (util.isString(self._line_buffer) && self._line_buffer.length > 0) { <add> if (typeof self._line_buffer === 'string' && <add> self._line_buffer.length > 0) { <ide> self.emit('line', self._line_buffer); <ide> } <ide> self.close(); <ide> } <ide> <ide> function ontermend() { <del> if (util.isString(self.line) && self.line.length > 0) { <add> if (typeof self.line === 'string' && self.line.length > 0) { <ide> self.emit('line', self.line); <ide> } <ide> self.close(); <ide> function Interface(input, output, completer, terminal) { <ide> this.history = []; <ide> this.historyIndex = -1; <ide> <del> if (!util.isNullOrUndefined(output)) <add> if (output !== null && output !== undefined) <ide> output.on('resize', onresize); <ide> <ide> self.once('close', function() { <ide> input.removeListener('keypress', onkeypress); <ide> input.removeListener('end', ontermend); <del> if (!util.isNullOrUndefined(output)) { <add> if (output !== null && output !== undefined) { <ide> output.removeListener('resize', onresize); <ide> } <ide> }); <ide> Interface.prototype.setPrompt = function(prompt) { <ide> <ide> <ide> Interface.prototype._setRawMode = function(mode) { <del> if (util.isFunction(this.input.setRawMode)) { <add> if (typeof this.input.setRawMode === 'function') { <ide> return this.input.setRawMode(mode); <ide> } <ide> }; <ide> Interface.prototype.prompt = function(preserveCursor) { <ide> <ide> <ide> Interface.prototype.question = function(query, cb) { <del> if (util.isFunction(cb)) { <add> if (typeof cb === 'function') { <ide> if (this._questionCallback) { <ide> this.prompt(); <ide> } else { <ide> Interface.prototype._onLine = function(line) { <ide> }; <ide> <ide> Interface.prototype._writeToOutput = function _writeToOutput(stringToWrite) { <del> if (!util.isString(stringToWrite)) <add> if (typeof stringToWrite !== 'string') <ide> throw new TypeError('stringToWrite must be a string'); <ide> <del> if (!util.isNullOrUndefined(this.output)) <add> if (this.output !== null && this.output !== undefined) <ide> this.output.write(stringToWrite); <ide> }; <ide> <ide> Interface.prototype.write = function(d, key) { <ide> // \r\n, \n, or \r followed by something other than \n <ide> const lineEnding = /\r?\n|\r(?!\n)/; <ide> Interface.prototype._normalWrite = function(b) { <del> if (util.isUndefined(b)) { <add> if (b === undefined) { <ide> return; <ide> } <ide> var string = this._decoder.write(b); <ide> Interface.prototype._ttyWrite = function(s, key) { <ide> break; <ide> <ide> default: <del> if (util.isBuffer(s)) <add> if (s instanceof Buffer) <ide> s = s.toString('utf-8'); <ide> <ide> if (s) { <ide> const escapeCodeReAnywhere = new RegExp([ <ide> ].join('|')); <ide> <ide> function emitKeys(stream, s) { <del> if (util.isBuffer(s)) { <del> if (s[0] > 127 && util.isUndefined(s[1])) { <add> if (s instanceof Buffer) { <add> if (s[0] > 127 && s[1] === undefined) { <ide> s[0] -= 128; <ide> s = '\x1b' + s.toString(stream.encoding || 'utf-8'); <ide> } else { <ide> function emitKeys(stream, s) { <ide> } <ide> <ide> // Don't emit a key if no name was found <del> if (util.isUndefined(key.name)) { <add> if (key.name === undefined) { <ide> key = undefined; <ide> } <ide> <ide> function emitKeys(stream, s) { <ide> */ <ide> <ide> function cursorTo(stream, x, y) { <del> if (util.isNullOrUndefined(stream)) <add> if (stream === null || stream === undefined) <ide> return; <ide> <del> if (!util.isNumber(x) && !util.isNumber(y)) <add> if (typeof x !== 'number' && typeof y !== 'number') <ide> return; <ide> <del> if (!util.isNumber(x)) <add> if (typeof x !== 'number') <ide> throw new Error("Can't set cursor row without also setting it's column"); <ide> <del> if (!util.isNumber(y)) { <add> if (typeof y !== 'number') { <ide> stream.write('\x1b[' + (x + 1) + 'G'); <ide> } else { <ide> stream.write('\x1b[' + (y + 1) + ';' + (x + 1) + 'H'); <ide> exports.cursorTo = cursorTo; <ide> */ <ide> <ide> function moveCursor(stream, dx, dy) { <del> if (util.isNullOrUndefined(stream)) <add> if (stream === null || stream === undefined) <ide> return; <ide> <ide> if (dx < 0) { <ide> exports.moveCursor = moveCursor; <ide> */ <ide> <ide> function clearLine(stream, dir) { <del> if (util.isNullOrUndefined(stream)) <add> if (stream === null || stream === undefined) <ide> return; <ide> <ide> if (dir < 0) { <ide> exports.clearLine = clearLine; <ide> */ <ide> <ide> function clearScreenDown(stream) { <del> if (util.isNullOrUndefined(stream)) <add> if (stream === null || stream === undefined) <ide> return; <ide> <ide> stream.write('\x1b[0J'); <ide><path>lib/repl.js <ide> function REPLServer(prompt, stream, eval_, useGlobal, ignoreUndefined) { <ide> } <ide> <ide> var options, input, output, dom; <del> if (util.isObject(prompt)) { <add> if (prompt !== null && typeof prompt === 'object') { <ide> // an options object was given <ide> options = prompt; <ide> stream = options.stream || options.socket; <ide> function REPLServer(prompt, stream, eval_, useGlobal, ignoreUndefined) { <ide> ignoreUndefined = options.ignoreUndefined; <ide> prompt = options.prompt; <ide> dom = options.domain; <del> } else if (!util.isString(prompt)) { <add> } else if (typeof prompt !== 'string') { <ide> throw new Error('An options Object, or a prompt String are required'); <ide> } else { <ide> options = {}; <ide> function REPLServer(prompt, stream, eval_, useGlobal, ignoreUndefined) { <ide> options.terminal <ide> ]); <ide> <del> self.setPrompt(!util.isUndefined(prompt) ? prompt : '> '); <add> self.setPrompt(prompt !== undefined ? prompt : '> '); <ide> <ide> this.commands = {}; <ide> defineDefaultCommands(this); <ide> <ide> // figure out which "writer" function to use <ide> self.writer = options.writer || exports.writer; <ide> <del> if (util.isUndefined(options.useColors)) { <add> if (options.useColors === undefined) { <ide> options.useColors = self.terminal; <ide> } <ide> self.useColors = !!options.useColors; <ide> function REPLServer(prompt, stream, eval_, useGlobal, ignoreUndefined) { <ide> self.bufferedCommand = ''; <ide> <ide> // If we got any output - print it (if no error) <del> if (!e && (!self.ignoreUndefined || !util.isUndefined(ret))) { <add> if (!e && (!self.ignoreUndefined || ret !== undefined)) { <ide> self.context._ = ret; <ide> self.outputStream.write(self.writer(ret) + '\n'); <ide> } <ide> const simpleExpressionRE = <ide> // getter code. <ide> REPLServer.prototype.complete = function(line, callback) { <ide> // There may be local variables to evaluate, try a nested REPL <del> if (!util.isUndefined(this.bufferedCommand) && this.bufferedCommand.length) { <add> if (this.bufferedCommand !== undefined && this.bufferedCommand.length) { <ide> // Get a new array of inputed lines <ide> var tmp = this.lines.slice(); <ide> // Kill off all function declarations to push all local variables into <ide> REPLServer.prototype.complete = function(line, callback) { <ide> this.eval('.scope', this.context, 'repl', function(err, globals) { <ide> if (err || !globals) { <ide> addStandardGlobals(completionGroups, filter); <del> } else if (util.isArray(globals[0])) { <add> } else if (Array.isArray(globals[0])) { <ide> // Add grouped globals <ide> globals.forEach(function(group) { <ide> completionGroups.push(group); <ide> REPLServer.prototype.complete = function(line, callback) { <ide> // if (e) console.log(e); <ide> <ide> if (obj != null) { <del> if (util.isObject(obj) || util.isFunction(obj)) { <add> if (typeof obj === 'object' || typeof obj === 'function') { <ide> memberGroups.push(Object.getOwnPropertyNames(obj)); <ide> } <ide> // works for non-objects <ide> try { <ide> var sentinel = 5; <ide> var p; <del> if (util.isObject(obj) || util.isFunction(obj)) { <add> if (typeof obj === 'object' || typeof obj === 'function') { <ide> p = Object.getPrototypeOf(obj); <ide> } else { <ide> p = obj.constructor ? obj.constructor.prototype : null; <ide> } <del> while (!util.isNull(p)) { <add> while (p !== null) { <ide> memberGroups.push(Object.getOwnPropertyNames(p)); <ide> p = Object.getPrototypeOf(p); <ide> // Circular refs possible? Let's guard against that. <ide> REPLServer.prototype.parseREPLKeyword = function(keyword, rest) { <ide> <ide> <ide> REPLServer.prototype.defineCommand = function(keyword, cmd) { <del> if (util.isFunction(cmd)) { <add> if (typeof cmd === 'function') { <ide> cmd = {action: cmd}; <del> } else if (!util.isFunction(cmd.action)) { <add> } else if (typeof cmd.action !== 'function') { <ide> throw new Error('bad argument, action must be a function'); <ide> } <ide> this.commands[keyword] = cmd; <ide><path>lib/smalloc.js <ide> Object.defineProperty(exports, 'Types', { <ide> function alloc(n, obj, type) { <ide> n = n >>> 0; <ide> <del> if (util.isUndefined(obj)) <add> if (obj === undefined) <ide> obj = {}; <ide> <del> if (util.isNumber(obj)) { <add> if (typeof obj === 'number') { <ide> type = obj >>> 0; <ide> obj = {}; <ide> } else if (util.isPrimitive(obj)) { <ide> function alloc(n, obj, type) { <ide> // 1 == v8::kExternalUint8Array, 9 == v8::kExternalUint8ClampedArray <ide> if (type < 1 || type > 9) <ide> throw new TypeError('unknown external array type: ' + type); <del> if (util.isArray(obj)) <add> if (Array.isArray(obj)) <ide> throw new TypeError('Arrays are not supported'); <ide> if (n > kMaxLength) <ide> throw new RangeError('n > kMaxLength'); <ide> function alloc(n, obj, type) { <ide> function dispose(obj) { <ide> if (util.isPrimitive(obj)) <ide> throw new TypeError('obj must be an Object'); <del> if (util.isBuffer(obj)) <add> if (obj instanceof Buffer) <ide> throw new TypeError('obj cannot be a Buffer'); <ide> if (smalloc.isTypedArray(obj)) <ide> throw new TypeError('obj cannot be a typed array'); <ide><path>lib/stream.js <ide> Stream.prototype.pipe = function(dest, options) { <ide> if (didOnEnd) return; <ide> didOnEnd = true; <ide> <del> if (util.isFunction(dest.destroy)) dest.destroy(); <add> if (typeof dest.destroy === 'function') dest.destroy(); <ide> } <ide> <ide> // don't leave dangling pipes when there are errors. <ide><path>lib/tls.js <ide> exports.getCiphers = function() { <ide> // ("\x06spdy/2\x08http/1.1\x08http/1.0") <ide> exports.convertNPNProtocols = function convertNPNProtocols(NPNProtocols, out) { <ide> // If NPNProtocols is Array - translate it into buffer <del> if (util.isArray(NPNProtocols)) { <add> if (Array.isArray(NPNProtocols)) { <ide> var buff = new Buffer(NPNProtocols.reduce(function(p, c) { <ide> return p + 1 + Buffer.byteLength(c); <ide> }, 0)); <ide> exports.convertNPNProtocols = function convertNPNProtocols(NPNProtocols, out) { <ide> } <ide> <ide> // If it's already a Buffer - store it <del> if (util.isBuffer(NPNProtocols)) { <add> if (NPNProtocols instanceof Buffer) { <ide> out.NPNProtocols = NPNProtocols; <ide> } <ide> }; <ide> exports.checkServerIdentity = function checkServerIdentity(host, cert) { <ide> // RFC6125 <ide> if (matchCN) { <ide> var commonNames = cert.subject.CN; <del> if (util.isArray(commonNames)) { <add> if (Array.isArray(commonNames)) { <ide> for (var i = 0, k = commonNames.length; i < k; ++i) { <ide> dnsNames.push(regexpify(commonNames[i], true)); <ide> } <ide> exports.parseCertString = function parseCertString(s) { <ide> var key = parts[i].slice(0, sepIndex); <ide> var value = parts[i].slice(sepIndex + 1); <ide> if (key in out) { <del> if (!util.isArray(out[key])) { <add> if (!Array.isArray(out[key])) { <ide> out[key] = [out[key]]; <ide> } <ide> out[key].push(value); <ide><path>lib/tty.js <ide> 'use strict'; <ide> <del>const inherits = require('util').inherits; <add>const util = require('util'); <ide> const net = require('net'); <ide> const TTY = process.binding('tty_wrap').TTY; <ide> const isTTY = process.binding('tty_wrap').isTTY; <del>const util = require('util'); <del> <add>const inherits = util.inherits; <ide> const errnoException = util._errnoException; <ide> <ide> <ide><path>lib/url.js <ide> 'use strict'; <ide> <ide> const punycode = require('punycode'); <del>const util = require('util'); <ide> <ide> exports.parse = urlParse; <ide> exports.resolve = urlResolve; <ide> const slashedProtocol = { <ide> const querystring = require('querystring'); <ide> <ide> function urlParse(url, parseQueryString, slashesDenoteHost) { <del> if (url && util.isObject(url) && url instanceof Url) return url; <add> if (url instanceof Url) return url; <ide> <ide> var u = new Url; <ide> u.parse(url, parseQueryString, slashesDenoteHost); <ide> return u; <ide> } <ide> <ide> Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { <del> if (!util.isString(url)) { <add> if (typeof url !== 'string') { <ide> throw new TypeError("Parameter 'url' must be a string, not " + typeof url); <ide> } <ide> <ide> function urlFormat(obj) { <ide> // If it's an obj, this is a no-op. <ide> // this way, you can call url_format() on strings <ide> // to clean up potentially wonky urls. <del> if (util.isString(obj)) obj = urlParse(obj); <add> if (typeof obj === 'string') obj = urlParse(obj); <ide> if (!(obj instanceof Url)) return Url.prototype.format.call(obj); <ide> return obj.format(); <ide> } <ide> Url.prototype.format = function() { <ide> } <ide> } <ide> <del> if (this.query && <del> util.isObject(this.query) && <add> if (this.query !== null && <add> typeof this.query === 'object' && <ide> Object.keys(this.query).length) { <ide> query = querystring.stringify(this.query); <ide> } <ide> function urlResolveObject(source, relative) { <ide> } <ide> <ide> Url.prototype.resolveObject = function(relative) { <del> if (util.isString(relative)) { <add> if (typeof relative === 'string') { <ide> var rel = new Url(); <ide> rel.parse(relative, false, true); <ide> relative = rel; <ide> Url.prototype.resolveObject = function(relative) { <ide> srcPath = srcPath.concat(relPath); <ide> result.search = relative.search; <ide> result.query = relative.query; <del> } else if (!util.isNullOrUndefined(relative.search)) { <add> } else if (relative.search !== null && relative.search !== undefined) { <ide> // just pull out the search. <ide> // like href='?foo'. <ide> // Put this after the other two cases because it simplifies the booleans <ide> Url.prototype.resolveObject = function(relative) { <ide> result.search = relative.search; <ide> result.query = relative.query; <ide> //to support http.request <del> if (!util.isNull(result.pathname) || !util.isNull(result.search)) { <add> if (result.pathname !== null || result.search !== null) { <ide> result.path = (result.pathname ? result.pathname : '') + <ide> (result.search ? result.search : ''); <ide> } <ide> Url.prototype.resolveObject = function(relative) { <ide> } <ide> <ide> //to support request.http <del> if (!util.isNull(result.pathname) || !util.isNull(result.search)) { <add> if (result.pathname !== null || result.search !== null) { <ide> result.path = (result.pathname ? result.pathname : '') + <ide> (result.search ? result.search : ''); <ide> } <ide><path>lib/util.js <ide> <ide> const formatRegExp = /%[sdj%]/g; <ide> exports.format = function(f) { <del> if (!isString(f)) { <add> if (typeof f !== 'string') { <ide> var objects = []; <ide> for (var i = 0; i < arguments.length; i++) { <ide> objects.push(inspect(arguments[i])); <ide> exports.format = function(f) { <ide> } <ide> }); <ide> for (var x = args[i]; i < len; x = args[++i]) { <del> if (isNull(x) || !isObject(x)) { <add> if (x === null || typeof x !== 'object') { <ide> str += ' ' + x; <ide> } else { <ide> str += ' ' + inspect(x); <ide> exports.format = function(f) { <ide> // If --no-deprecation is set, then it is a no-op. <ide> exports.deprecate = function(fn, msg) { <ide> // Allow for deprecating things in the process of starting up. <del> if (isUndefined(global.process)) { <add> if (global.process === undefined) { <ide> return function() { <ide> return exports.deprecate(fn, msg).apply(this, arguments); <ide> }; <ide> exports.deprecate = function(fn, msg) { <ide> var debugs = {}; <ide> var debugEnviron; <ide> exports.debuglog = function(set) { <del> if (isUndefined(debugEnviron)) <add> if (debugEnviron === undefined) <ide> debugEnviron = process.env.NODE_DEBUG || ''; <ide> set = set.toUpperCase(); <ide> if (!debugs[set]) { <ide> function inspect(obj, opts) { <ide> // legacy... <ide> if (arguments.length >= 3) ctx.depth = arguments[2]; <ide> if (arguments.length >= 4) ctx.colors = arguments[3]; <del> if (isBoolean(opts)) { <add> if (typeof opts === 'boolean') { <ide> // legacy... <ide> ctx.showHidden = opts; <ide> } else if (opts) { <ide> // got an "options" object <ide> exports._extend(ctx, opts); <ide> } <ide> // set default options <del> if (isUndefined(ctx.showHidden)) ctx.showHidden = false; <del> if (isUndefined(ctx.depth)) ctx.depth = 2; <del> if (isUndefined(ctx.colors)) ctx.colors = false; <del> if (isUndefined(ctx.customInspect)) ctx.customInspect = true; <add> if (ctx.showHidden === undefined) ctx.showHidden = false; <add> if (ctx.depth === undefined) ctx.depth = 2; <add> if (ctx.colors === undefined) ctx.colors = false; <add> if (ctx.customInspect === undefined) ctx.customInspect = true; <ide> if (ctx.colors) ctx.stylize = stylizeWithColor; <ide> return formatValue(ctx, obj, ctx.depth); <ide> } <ide> function formatValue(ctx, value, recurseTimes) { <ide> // Check that value is an object with an inspect function on it <ide> if (ctx.customInspect && <ide> value && <del> isFunction(value.inspect) && <add> typeof value.inspect === 'function' && <ide> // Filter out the util module, it's inspect function is special <ide> value.inspect !== exports.inspect && <ide> // Also filter out any prototype objects using the circular check. <ide> !(value.constructor && value.constructor.prototype === value)) { <ide> var ret = value.inspect(recurseTimes, ctx); <del> if (!isString(ret)) { <add> if (typeof ret !== 'string') { <ide> ret = formatValue(ctx, ret, recurseTimes); <ide> } <ide> return ret; <ide> function formatValue(ctx, value, recurseTimes) { <ide> // ignore... <ide> } <ide> <del> if (isString(raw)) { <add> if (typeof raw === 'string') { <ide> // for boxed Strings, we have to remove the 0-n indexed entries, <ide> // since they just noisey up the output and are redundant <ide> keys = keys.filter(function(key) { <ide> function formatValue(ctx, value, recurseTimes) { <ide> <ide> // Some type of object without properties can be shortcutted. <ide> if (keys.length === 0) { <del> if (isFunction(value)) { <add> if (typeof value === 'function') { <ide> var name = value.name ? ': ' + value.name : ''; <ide> return ctx.stylize('[Function' + name + ']', 'special'); <ide> } <ide> function formatValue(ctx, value, recurseTimes) { <ide> return formatError(value); <ide> } <ide> // now check the `raw` value to handle boxed primitives <del> if (isString(raw)) { <add> if (typeof raw === 'string') { <ide> formatted = formatPrimitiveNoColor(ctx, raw); <ide> return ctx.stylize('[String: ' + formatted + ']', 'string'); <ide> } <del> if (isNumber(raw)) { <add> if (typeof raw === 'number') { <ide> formatted = formatPrimitiveNoColor(ctx, raw); <ide> return ctx.stylize('[Number: ' + formatted + ']', 'number'); <ide> } <del> if (isBoolean(raw)) { <add> if (typeof raw === 'boolean') { <ide> formatted = formatPrimitiveNoColor(ctx, raw); <ide> return ctx.stylize('[Boolean: ' + formatted + ']', 'boolean'); <ide> } <ide> function formatValue(ctx, value, recurseTimes) { <ide> var base = '', array = false, braces = ['{', '}']; <ide> <ide> // Make Array say that they are Array <del> if (isArray(value)) { <add> if (Array.isArray(value)) { <ide> array = true; <ide> braces = ['[', ']']; <ide> } <ide> <ide> // Make functions say that they are functions <del> if (isFunction(value)) { <add> if (typeof value === 'function') { <ide> var n = value.name ? ': ' + value.name : ''; <ide> base = ' [Function' + n + ']'; <ide> } <ide> function formatValue(ctx, value, recurseTimes) { <ide> } <ide> <ide> // Make boxed primitive Strings look like such <del> if (isString(raw)) { <add> if (typeof raw === 'string') { <ide> formatted = formatPrimitiveNoColor(ctx, raw); <ide> base = ' ' + '[String: ' + formatted + ']'; <ide> } <ide> <ide> // Make boxed primitive Numbers look like such <del> if (isNumber(raw)) { <add> if (typeof raw === 'number') { <ide> formatted = formatPrimitiveNoColor(ctx, raw); <ide> base = ' ' + '[Number: ' + formatted + ']'; <ide> } <ide> <ide> // Make boxed primitive Booleans look like such <del> if (isBoolean(raw)) { <add> if (typeof raw === 'boolean') { <ide> formatted = formatPrimitiveNoColor(ctx, raw); <ide> base = ' ' + '[Boolean: ' + formatted + ']'; <ide> } <ide> function formatValue(ctx, value, recurseTimes) { <ide> <ide> <ide> function formatPrimitive(ctx, value) { <del> if (isUndefined(value)) <add> if (value === undefined) <ide> return ctx.stylize('undefined', 'undefined'); <del> if (isString(value)) { <add> <add> // For some reason typeof null is "object", so special case here. <add> if (value === null) <add> return ctx.stylize('null', 'null'); <add> <add> var type = typeof value; <add> <add> if (type === 'string') { <ide> var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') <ide> .replace(/'/g, "\\'") <ide> .replace(/\\"/g, '"') + '\''; <ide> return ctx.stylize(simple, 'string'); <ide> } <del> if (isNumber(value)) { <add> if (type === 'number') { <ide> // Format -0 as '-0'. Strict equality won't distinguish 0 from -0, <ide> // so instead we use the fact that 1 / -0 < 0 whereas 1 / 0 > 0 . <ide> if (value === 0 && 1 / value < 0) <ide> return ctx.stylize('-0', 'number'); <ide> return ctx.stylize('' + value, 'number'); <ide> } <del> if (isBoolean(value)) <add> if (type === 'boolean') <ide> return ctx.stylize('' + value, 'boolean'); <del> // For some reason typeof null is "object", so special case here. <del> if (isNull(value)) <del> return ctx.stylize('null', 'null'); <ide> // es6 symbol primitive <del> if (isSymbol(value)) <add> if (type === 'symbol') <ide> return ctx.stylize(value.toString(), 'symbol'); <ide> } <ide> <ide> function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { <ide> } <ide> } <ide> keys.forEach(function(key) { <del> if (isSymbol(key) || !key.match(/^\d+$/)) { <add> if (typeof key === 'symbol' || !key.match(/^\d+$/)) { <ide> output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, <ide> key, true)); <ide> } <ide> function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { <ide> } <ide> } <ide> if (!hasOwnProperty(visibleKeys, key)) { <del> if (isSymbol(key)) { <add> if (typeof key === 'symbol') { <ide> name = '[' + ctx.stylize(key.toString(), 'symbol') + ']'; <ide> } else { <ide> name = '[' + key + ']'; <ide> } <ide> } <ide> if (!str) { <ide> if (ctx.seen.indexOf(desc.value) < 0) { <del> if (isNull(recurseTimes)) { <add> if (recurseTimes === null) { <ide> str = formatValue(ctx, desc.value, null); <ide> } else { <ide> str = formatValue(ctx, desc.value, recurseTimes - 1); <ide> function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { <ide> str = ctx.stylize('[Circular]', 'special'); <ide> } <ide> } <del> if (isUndefined(name)) { <add> if (name === undefined) { <ide> if (array && key.match(/^\d+$/)) { <ide> return str; <ide> } <ide> function isNull(arg) { <ide> exports.isNull = isNull; <ide> <ide> function isNullOrUndefined(arg) { <del> return arg == null; <add> return arg === null || arg === undefined; <ide> } <ide> exports.isNullOrUndefined = isNullOrUndefined; <ide> <ide> function isSymbol(arg) { <ide> exports.isSymbol = isSymbol; <ide> <ide> function isUndefined(arg) { <del> return arg === void 0; <add> return arg === undefined; <ide> } <ide> exports.isUndefined = isUndefined; <ide> <ide> function isRegExp(re) { <del> return isObject(re) && objectToString(re) === '[object RegExp]'; <add> return re !== null && typeof re === 'object' && <add> objectToString(re) === '[object RegExp]'; <ide> } <ide> exports.isRegExp = isRegExp; <ide> <ide> function isObject(arg) { <del> return typeof arg === 'object' && arg !== null; <add> return arg !== null && typeof arg === 'object'; <ide> } <ide> exports.isObject = isObject; <ide> <ide> function isDate(d) { <del> return isObject(d) && objectToString(d) === '[object Date]'; <add> return d !== null && typeof d === 'object' && <add> objectToString(d) === '[object Date]'; <ide> } <ide> exports.isDate = isDate; <ide> <ide> function isError(e) { <del> return isObject(e) && <add> return e !== null && typeof e === 'object' && <ide> (objectToString(e) === '[object Error]' || e instanceof Error); <ide> } <ide> exports.isError = isError; <ide> exports.inherits = function(ctor, superCtor) { <ide> <ide> exports._extend = function(origin, add) { <ide> // Don't do anything if add isn't an object <del> if (!add || !isObject(add)) return origin; <add> if (add === null || typeof add !== 'object') return origin; <ide> <ide> var keys = Object.keys(add); <ide> var i = keys.length; <ide> exports.pump = exports.deprecate(function(readStream, writeStream, callback) { <ide> <ide> var uv; <ide> exports._errnoException = function(err, syscall, original) { <del> if (isUndefined(uv)) uv = process.binding('uv'); <add> if (uv === undefined) uv = process.binding('uv'); <ide> var errname = uv.errname(err); <ide> var message = syscall + ' ' + errname; <ide> if (original) <ide><path>lib/vm.js <ide> <ide> const binding = process.binding('contextify'); <ide> const Script = binding.ContextifyScript; <del>const util = require('util'); <ide> <ide> // The binding provides a few useful primitives: <ide> // - ContextifyScript(code, { filename = "evalmachine.anonymous", <ide> exports.createScript = function(code, options) { <ide> }; <ide> <ide> exports.createContext = function(sandbox) { <del> if (util.isUndefined(sandbox)) { <add> if (sandbox === undefined) { <ide> sandbox = {}; <ide> } else if (binding.isContext(sandbox)) { <ide> return sandbox; <ide><path>lib/zlib.js <ide> exports.createUnzip = function(o) { <ide> // Convenience methods. <ide> // compress/decompress a string or buffer in one step. <ide> exports.deflate = function(buffer, opts, callback) { <del> if (util.isFunction(opts)) { <add> if (typeof opts === 'function') { <ide> callback = opts; <ide> opts = {}; <ide> } <ide> exports.deflateSync = function(buffer, opts) { <ide> }; <ide> <ide> exports.gzip = function(buffer, opts, callback) { <del> if (util.isFunction(opts)) { <add> if (typeof opts === 'function') { <ide> callback = opts; <ide> opts = {}; <ide> } <ide> exports.gzipSync = function(buffer, opts) { <ide> }; <ide> <ide> exports.deflateRaw = function(buffer, opts, callback) { <del> if (util.isFunction(opts)) { <add> if (typeof opts === 'function') { <ide> callback = opts; <ide> opts = {}; <ide> } <ide> exports.deflateRawSync = function(buffer, opts) { <ide> }; <ide> <ide> exports.unzip = function(buffer, opts, callback) { <del> if (util.isFunction(opts)) { <add> if (typeof opts === 'function') { <ide> callback = opts; <ide> opts = {}; <ide> } <ide> exports.unzipSync = function(buffer, opts) { <ide> }; <ide> <ide> exports.inflate = function(buffer, opts, callback) { <del> if (util.isFunction(opts)) { <add> if (typeof opts === 'function') { <ide> callback = opts; <ide> opts = {}; <ide> } <ide> exports.inflateSync = function(buffer, opts) { <ide> }; <ide> <ide> exports.gunzip = function(buffer, opts, callback) { <del> if (util.isFunction(opts)) { <add> if (typeof opts === 'function') { <ide> callback = opts; <ide> opts = {}; <ide> } <ide> exports.gunzipSync = function(buffer, opts) { <ide> }; <ide> <ide> exports.inflateRaw = function(buffer, opts, callback) { <del> if (util.isFunction(opts)) { <add> if (typeof opts === 'function') { <ide> callback = opts; <ide> opts = {}; <ide> } <ide> function zlibBuffer(engine, buffer, callback) { <ide> } <ide> <ide> function zlibBufferSync(engine, buffer) { <del> if (util.isString(buffer)) <add> if (typeof buffer === 'string') <ide> buffer = new Buffer(buffer); <del> if (!util.isBuffer(buffer)) <add> if (!(buffer instanceof Buffer)) <ide> throw new TypeError('Not a string or buffer'); <ide> <ide> var flushFlag = binding.Z_FINISH; <ide> function Zlib(opts, mode) { <ide> } <ide> <ide> if (opts.dictionary) { <del> if (!util.isBuffer(opts.dictionary)) { <add> if (!(opts.dictionary instanceof Buffer)) { <ide> throw new Error('Invalid dictionary: it should be a Buffer instance'); <ide> } <ide> } <ide> function Zlib(opts, mode) { <ide> }; <ide> <ide> var level = exports.Z_DEFAULT_COMPRESSION; <del> if (util.isNumber(opts.level)) level = opts.level; <add> if (typeof opts.level === 'number') level = opts.level; <ide> <ide> var strategy = exports.Z_DEFAULT_STRATEGY; <del> if (util.isNumber(opts.strategy)) strategy = opts.strategy; <add> if (typeof opts.strategy === 'number') strategy = opts.strategy; <ide> <ide> this._handle.init(opts.windowBits || exports.Z_DEFAULT_WINDOWBITS, <ide> level, <ide> Zlib.prototype._flush = function(callback) { <ide> Zlib.prototype.flush = function(kind, callback) { <ide> var ws = this._writableState; <ide> <del> if (util.isFunction(kind) || (util.isUndefined(kind) && !callback)) { <add> if (typeof kind === 'function' || (kind === undefined && !callback)) { <ide> callback = kind; <ide> kind = binding.Z_FULL_FLUSH; <ide> } <ide> Zlib.prototype._transform = function(chunk, encoding, cb) { <ide> var ending = ws.ending || ws.ended; <ide> var last = ending && (!chunk || ws.length === chunk.length); <ide> <del> if (!util.isNull(chunk) && !util.isBuffer(chunk)) <add> if (chunk !== null && !(chunk instanceof Buffer)) <ide> return cb(new Error('invalid input')); <ide> <ide> if (this._closed) <ide> Zlib.prototype._processChunk = function(chunk, flushFlag, cb) { <ide> <ide> var self = this; <ide> <del> var async = util.isFunction(cb); <add> var async = typeof cb === 'function'; <ide> <ide> if (!async) { <ide> var buffers = [];
37
Ruby
Ruby
fix error on reap/flush for closed connection pool
3a8eeacf63b9f04da418eaa4bb9acc6fcce7986b
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb <ide> def remove(conn) <ide> # or a thread dies unexpectedly. <ide> def reap <ide> stale_connections = synchronize do <add> return unless @connections <ide> @connections.select do |conn| <ide> conn.in_use? && !conn.owner.alive? <ide> end.each do |conn| <ide> def flush(minimum_idle = @idle_timeout) <ide> return if minimum_idle.nil? <ide> <ide> idle_connections = synchronize do <add> return unless @connections <ide> @connections.select do |conn| <ide> !conn.in_use? && conn.seconds_idle >= minimum_idle <ide> end.each do |conn| <ide><path>activerecord/test/cases/reaper_test.rb <ide> def test_connection_pool_starts_reaper <ide> assert_not_predicate conn, :in_use? <ide> end <ide> <add> def test_reaper_works_after_pool_discard <add> spec = ActiveRecord::Base.connection_pool.spec.dup <add> spec.config[:reaping_frequency] = "0.0001" <add> <add> 2.times do <add> pool = ConnectionPool.new spec <add> <add> conn, child = new_conn_in_thread(pool) <add> <add> assert_predicate conn, :in_use? <add> <add> child.terminate <add> <add> wait_for_conn_idle(conn) <add> assert_not_predicate conn, :in_use? <add> <add> pool.discard! <add> end <add> end <add> <add> # This doesn't test the reaper directly, but we want to test the action <add> # it would take on a discarded pool <add> def test_reap_flush_on_discarded_pool <add> spec = ActiveRecord::Base.connection_pool.spec.dup <add> pool = ConnectionPool.new spec <add> <add> pool.discard! <add> pool.reap <add> pool.flush <add> end <add> <ide> def test_connection_pool_starts_reaper_in_fork <ide> spec = ActiveRecord::Base.connection_pool.spec.dup <ide> spec.config[:reaping_frequency] = "0.0001"
2
PHP
PHP
add strict_types to configure engines
8ceee4d7aa931d14ada48c7b715fde9a8bba8b1c
<ide><path>src/Core/Configure/Engine/IniConfig.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> protected function _parseNestedValues($values) <ide> $value = false; <ide> } <ide> unset($values[$key]); <del> if (strpos($key, '.') !== false) { <add> if (strpos((string)$key, '.') !== false) { <ide> $values = Hash::insert($values, $key, $value); <ide> } else { <ide> $values[$key] = $value; <ide><path>src/Core/Configure/Engine/JsonConfig.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>src/Core/Configure/Engine/PhpConfig.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> * <ide> * ``` <ide> * <?php <add>declare(strict_types=1); <ide> * return [ <ide> * 'debug' => 0, <ide> * 'Security' => [ <ide><path>tests/TestCase/Core/Configure/Engine/IniConfigTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/Core/Configure/Engine/JsonConfigTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/Core/Configure/Engine/PhpConfigTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
6
Ruby
Ruby
eliminate consideration of major_version
b6e9600b9fbcb1f86bc43d78fb461a1247e9aacd
<ide><path>Library/Homebrew/compilers.rb <ide> module CompilerConstants <ide> GNU_GCC_REGEXP = /^gcc-(4\.[3-9])$/ <ide> end <ide> <del>class Compiler < Struct.new(:name, :version, :priority) <del> # The major version for non-Apple compilers. Used to indicate a compiler <del> # series; for instance, if the version is 4.8.2, it would return "4.8". <del> def major_version <del> version.match(/(\d\.\d)/)[0] if name.is_a? String <del> end <del>end <add>Compiler = Struct.new(:name, :version, :priority) <ide> <ide> class CompilerFailure <ide> attr_reader :name <ide> def self.create(spec, &block) <ide> name = "gcc-#{major_version}" <ide> # so fails_with :gcc => '4.8' simply marks all 4.8 releases incompatible <ide> version = "#{major_version}.999" <del> GnuCompilerFailure.new(name, major_version, version, &block) <ide> else <ide> name = spec <ide> version = 9999 <del> new(name, version, &block) <ide> end <add> new(name, version, &block) <ide> end <ide> <ide> def initialize(name, version, &block) <ide> def ===(compiler) <ide> name == compiler.name && version >= (compiler.version || 0) <ide> end <ide> <del> class GnuCompilerFailure < CompilerFailure <del> attr_reader :major_version <del> <del> def initialize(name, major_version, version, &block) <del> @major_version = major_version <del> super(name, version, &block) <del> end <del> <del> def ===(compiler) <del> super && major_version == compiler.major_version <del> end <del> end <del> <ide> MESSAGES = { <ide> :cxx11 => "This compiler does not support C++11" <ide> }
1
Go
Go
use spf13/cobra for docker wait
82f84a67d6d40d4a076927c618db475191f97da0
<ide><path>api/client/commands.go <ide> func (cli *DockerCli) Command(name string) func(...string) error { <ide> "top": cli.CmdTop, <ide> "update": cli.CmdUpdate, <ide> "version": cli.CmdVersion, <del> "wait": cli.CmdWait, <ide> }[name] <ide> } <ide><path>api/client/container/wait.go <add>package container <add> <add>import ( <add> "fmt" <add> "strings" <add> <add> "golang.org/x/net/context" <add> <add> "github.com/docker/docker/api/client" <add> "github.com/docker/docker/cli" <add> "github.com/spf13/cobra" <add>) <add> <add>type waitOptions struct { <add> containers []string <add>} <add> <add>// NewWaitCommand creats a new cobra.Command for `docker wait` <add>func NewWaitCommand(dockerCli *client.DockerCli) *cobra.Command { <add> var opts waitOptions <add> <add> cmd := &cobra.Command{ <add> Use: "wait CONTAINER [CONTAINER...]", <add> Short: "Block until a container stops, then print its exit code", <add> Args: cli.RequiresMinArgs(1), <add> RunE: func(cmd *cobra.Command, args []string) error { <add> opts.containers = args <add> return runWait(dockerCli, &opts) <add> }, <add> } <add> cmd.SetFlagErrorFunc(flagErrorFunc) <add> <add> return cmd <add>} <add> <add>func runWait(dockerCli *client.DockerCli, opts *waitOptions) error { <add> ctx := context.Background() <add> <add> var errs []string <add> for _, container := range opts.containers { <add> status, err := dockerCli.Client().ContainerWait(ctx, container) <add> if err != nil { <add> errs = append(errs, err.Error()) <add> } else { <add> fmt.Fprintf(dockerCli.Out(), "%d\n", status) <add> } <add> } <add> if len(errs) > 0 { <add> return fmt.Errorf("%s", strings.Join(errs, "\n")) <add> } <add> return nil <add>} <ide><path>api/client/wait.go <del>package client <del> <del>import ( <del> "fmt" <del> "strings" <del> <del> "golang.org/x/net/context" <del> <del> Cli "github.com/docker/docker/cli" <del> flag "github.com/docker/docker/pkg/mflag" <del>) <del> <del>// CmdWait blocks until a container stops, then prints its exit code. <del>// <del>// If more than one container is specified, this will wait synchronously on each container. <del>// <del>// Usage: docker wait CONTAINER [CONTAINER...] <del>func (cli *DockerCli) CmdWait(args ...string) error { <del> cmd := Cli.Subcmd("wait", []string{"CONTAINER [CONTAINER...]"}, Cli.DockerCommands["wait"].Description, true) <del> cmd.Require(flag.Min, 1) <del> <del> cmd.ParseFlags(args, true) <del> <del> ctx := context.Background() <del> <del> var errs []string <del> for _, name := range cmd.Args() { <del> status, err := cli.client.ContainerWait(ctx, name) <del> if err != nil { <del> errs = append(errs, err.Error()) <del> } else { <del> fmt.Fprintf(cli.out, "%d\n", status) <del> } <del> } <del> if len(errs) > 0 { <del> return fmt.Errorf("%s", strings.Join(errs, "\n")) <del> } <del> return nil <del>} <ide><path>cli/cobraadaptor/adaptor.go <ide> func NewCobraAdaptor(clientFlags *cliflags.ClientFlags) CobraAdaptor { <ide> container.NewStartCommand(dockerCli), <ide> container.NewStopCommand(dockerCli), <ide> container.NewUnpauseCommand(dockerCli), <add> container.NewWaitCommand(dockerCli), <ide> image.NewRemoveCommand(dockerCli), <ide> image.NewSearchCommand(dockerCli), <ide> network.NewNetworkCommand(dockerCli), <ide><path>cli/usage.go <ide> var DockerCommandUsage = []Command{ <ide> {"top", "Display the running processes of a container"}, <ide> {"update", "Update configuration of one or more containers"}, <ide> {"version", "Show the Docker version information"}, <del> {"wait", "Block until a container stops, then print its exit code"}, <ide> } <ide> <ide> // DockerCommands stores all the docker command
5
PHP
PHP
add retry support
9495b284bb2177f6d84993442bb822ab2bb358de
<ide><path>src/Illuminate/Http/Client/PendingRequest.php <ide> class PendingRequest <ide> */ <ide> protected $options = []; <ide> <add> /** <add> * The number of times to try the request. <add> * <add> * @var int <add> */ <add> protected $tries = 1; <add> <add> /** <add> * The number of milliseconds to wait between retries. <add> * <add> * @var int <add> */ <add> protected $retryDelay = 100; <add> <ide> /** <ide> * The callbacks that should execute before the request is sent. <ide> * <ide> public function timeout(int $seconds) <ide> }); <ide> } <ide> <add> /** <add> * Specify the number of times the request should be attempted. <add> * <add> * @param int $times <add> * @param int $sleep <add> * @return $this <add> */ <add> public function retry(int $times, int $sleep = 0) <add> { <add> $this->tries = $times; <add> $this->retryDelay = $sleep; <add> <add> return $this; <add> } <add> <ide> /** <ide> * Merge new options into the client. <ide> * <ide> public function send(string $method, string $url, array $options = []) <ide> <ide> $this->pendingFiles = []; <ide> <del> try { <del> return tap(new Response($this->buildClient()->request($method, $url, $this->mergeOptions([ <del> 'laravel_data' => $options[$this->bodyFormat] ?? [], <del> 'query' => $this->parseQueryParams($url), <del> 'on_stats' => function ($transferStats) { <del> $this->transferStats = $transferStats; <del> }, <del> ], $options))), function ($response) { <del> $response->cookies = $this->cookies; <del> $response->transferStats = $this->transferStats; <del> }); <del> } catch (\GuzzleHttp\Exception\ConnectException $e) { <del> throw new ConnectionException($e->getMessage(), 0, $e); <del> } <add> return retry($this->tries ?? 1, function () use ($method, $url, $options) { <add> try { <add> return tap(new Response($this->buildClient()->request($method, $url, $this->mergeOptions([ <add> 'laravel_data' => $options[$this->bodyFormat] ?? [], <add> 'query' => $this->parseQueryParams($url), <add> 'on_stats' => function ($transferStats) { <add> $this->transferStats = $transferStats; <add> }, <add> ], $options))), function ($response) { <add> $response->cookies = $this->cookies; <add> $response->transferStats = $this->transferStats; <add> <add> if ($this->tries > 1 && ! $response->successful()) { <add> $response->throw(); <add> } <add> }); <add> } catch (\GuzzleHttp\Exception\ConnectException $e) { <add> throw new ConnectionException($e->getMessage(), 0, $e); <add> } <add> }, $this->retryDelay ?? 100); <ide> } <ide> <ide> /**
1
PHP
PHP
fix docblock.
3edb21860311d0c01bccf03ace2fec951d51c4d0
<ide><path>src/Illuminate/Validation/ValidationRuleParser.php <ide> public function __construct(array $data) <ide> * Parse the human-friendly rules into a full rules array for the validator. <ide> * <ide> * @param array $rules <del> * @return StdClass <add> * @return \StdClass <ide> */ <ide> public function explode($rules) <ide> {
1
PHP
PHP
create observermakecommand file
7a78dab48ad00161206d992d6defc43d7159779a
<ide><path>src/Illuminate/Foundation/Console/ObserverMakeCommand.php <add><?php <add> <add>namespace Illuminate\Foundation\Console; <add> <add>use Illuminate\Console\GeneratorCommand; <add> <add>class ObserverMakeCommand extends GeneratorCommand <add>{ <add> /** <add> * The console command name. <add> * <add> * @var string <add> */ <add> protected $name = 'make:observer'; <add> <add> /** <add> * The console command description. <add> * <add> * @var string <add> */ <add> protected $description = 'Create a new observer class'; <add> <add> /** <add> * The type of class being generated. <add> * <add> * @var string <add> */ <add> protected $type = 'Observer'; <add> <add> /** <add> * Get the stub file for the generator. <add> * <add> * @return string <add> */ <add> protected function getStub() <add> { <add> return __DIR__.'/stubs/observer.stub'; <add> } <add> <add> /** <add> * Get the default namespace for the class. <add> * <add> * @param string $rootNamespace <add> * @return string <add> */ <add> protected function getDefaultNamespace($rootNamespace) <add> { <add> return $rootNamespace.'\Observers'; <add> } <add>}
1
Java
Java
fix failing test
6a9455b7d0e9d8af2f3a3fd9ad832d5b25cb8f5e
<ide><path>spring-test/src/main/java/org/springframework/test/web/client/match/ContentRequestMatchers.java <ide> public void match(ClientHttpRequest request) throws IOException, AssertionError <ide> public RequestMatcher formData(final MultiValueMap<String, String> expectedContent) { <ide> return new RequestMatcher() { <ide> @Override <del> public void match(ClientHttpRequest request) throws IOException, AssertionError { <add> public void match(final ClientHttpRequest request) throws IOException, AssertionError { <ide> HttpInputMessage inputMessage = new HttpInputMessage() { <ide> @Override <ide> public InputStream getBody() throws IOException {
1
Ruby
Ruby
remove unnecessary object/conversions file
ae9b3d7cecd77b9ace38671b183e1a360bf632b6
<ide><path>activesupport/lib/active_support/core_ext/object.rb <ide> require 'active_support/core_ext/object/acts_like' <ide> require 'active_support/core_ext/object/blank' <del>require 'active_support/core_ext/object/duplicable' <ide> require 'active_support/core_ext/object/deep_dup' <del>require 'active_support/core_ext/object/try' <add>require 'active_support/core_ext/object/duplicable' <ide> require 'active_support/core_ext/object/inclusion' <del> <del>require 'active_support/core_ext/object/conversions' <ide> require 'active_support/core_ext/object/instance_variables' <del> <ide> require 'active_support/core_ext/object/to_json' <ide> require 'active_support/core_ext/object/to_param' <ide> require 'active_support/core_ext/object/to_query' <add>require 'active_support/core_ext/object/try' <ide> require 'active_support/core_ext/object/with_options' <ide><path>activesupport/lib/active_support/core_ext/object/conversions.rb <del>require 'active_support/core_ext/object/to_param' <del>require 'active_support/core_ext/object/to_query' <del>require 'active_support/core_ext/array/conversions' <del>require 'active_support/core_ext/hash/conversions' <ide><path>activesupport/test/core_ext/array_ext_test.rb <ide> require 'abstract_unit' <ide> require 'active_support/core_ext/array' <ide> require 'active_support/core_ext/big_decimal' <del>require 'active_support/core_ext/object/conversions' <ide> <ide> require 'active_support/core_ext' # FIXME: pulling in all to_xml extensions <ide> require 'active_support/hash_with_indifferent_access' <ide><path>activesupport/test/core_ext/hash_ext_test.rb <ide> require 'bigdecimal' <ide> require 'active_support/core_ext/string/access' <ide> require 'active_support/ordered_hash' <del>require 'active_support/core_ext/object/conversions' <ide> require 'active_support/core_ext/object/deep_dup' <ide> require 'active_support/inflections' <ide>
4
Text
Text
update old codepen links to ones for v3
eb1e82c9813fbfccd86f4e4b424e768332654bd9
<ide><path>.github/ISSUE_TEMPLATE/DOCS.md <ide> Documentation Is: <ide> ### Example <ide> <!-- <ide> Provide a link to a live example demonstrating the issue or feature to be documented: <del> https://codepen.io/pen?template=JXVYzq <add> https://codepen.io/pen?template=wvezeOq <ide> --> <ide><path>.github/PULL_REQUEST_TEMPLATE.md <ide> Example of changes on an interactive website such as the following: <ide> - https://jsbin.com/ <ide> - https://jsfiddle.net/ <ide> - https://codepen.io/pen/ <del>- Premade template: https://codepen.io/pen?template=JXVYzq <add>- Premade template: https://codepen.io/pen?template=wvezeOq <ide> --> <ide><path>docs/developers/contributing.md <ide> Guidelines for reporting bugs: <ide> <ide> - Check the issue search to see if it has already been reported <ide> - Isolate the problem to a simple test case <del>- Please include a demonstration of the bug on a website such as [JS Bin](https://jsbin.com/), [JS Fiddle](https://jsfiddle.net/), or [Codepen](https://codepen.io/pen/). ([Template](https://codepen.io/pen?template=JXVYzq)). If filing a bug against `master`, you may reference the latest code via <https://www.chartjs.org/dist/master/chart.min.js> (changing the filename to point at the file you need as appropriate). Do not rely on these files for production purposes as they may be removed at any time. <add>- Please include a demonstration of the bug on a website such as [JS Bin](https://jsbin.com/), [JS Fiddle](https://jsfiddle.net/), or [Codepen](https://codepen.io/pen/). ([Template](https://codepen.io/pen?template=wvezeOq)). If filing a bug against `master`, you may reference the latest code via <https://www.chartjs.org/dist/master/chart.min.js> (changing the filename to point at the file you need as appropriate). Do not rely on these files for production purposes as they may be removed at any time. <ide> <ide> Please provide any additional details associated with the bug, if it's browser or screen density specific, or only happens with a certain configuration or data.
3
Javascript
Javascript
add test for dns.promises.resolve
3898abc55cfebe3073296eb599209fbc63aa7abf
<ide><path>test/parallel/test-dns-promises-resolve.js <add>'use strict'; <add>const common = require('../common'); <add>const assert = require('assert'); <add> <add>const dnsPromises = require('dns').promises; <add> <add>common.crashOnUnhandledRejection(); <add> <add>// Error when rrtype is invalid. <add>{ <add> const rrtype = 'DUMMY'; <add> common.expectsError( <add> () => dnsPromises.resolve('example.org', rrtype), <add> { <add> code: 'ERR_INVALID_OPT_VALUE', <add> type: TypeError, <add> message: `The value "${rrtype}" is invalid for option "rrtype"` <add> } <add> ); <add>} <add> <add>// Error when rrtype is a number. <add>{ <add> const rrtype = 0; <add> common.expectsError( <add> () => dnsPromises.resolve('example.org', rrtype), <add> { <add> code: 'ERR_INVALID_ARG_TYPE', <add> type: TypeError, <add> message: 'The "rrtype" argument must be of type string. ' + <add> `Received type ${typeof rrtype}` <add> } <add> ); <add>} <add> <add>// rrtype is undefined, it's same as resolve4 <add>{ <add> (async function() { <add> const rrtype = undefined; <add> const result = await dnsPromises.resolve('example.org', rrtype); <add> assert.ok(result !== undefined); <add> assert.ok(result.length > 0); <add> })(); <add>}
1
Java
Java
skip modulefinder#ofsystem usage on native
23a58e6bab2b5aecd77e30c2b2d0ee41b643876f
<ide><path>spring-core/src/main/java/org/springframework/core/io/support/PathMatchingResourcePatternResolver.java <ide> import org.apache.commons.logging.Log; <ide> import org.apache.commons.logging.LogFactory; <ide> <add>import org.springframework.core.NativeDetector; <ide> import org.springframework.core.io.DefaultResourceLoader; <ide> import org.springframework.core.io.FileSystemResource; <ide> import org.springframework.core.io.Resource; <ide> * @author Costin Leau <ide> * @author Phillip Webb <ide> * @author Sam Brannen <add> * @author Sebastien Deleuze <ide> * @since 1.0.2 <ide> * @see #CLASSPATH_ALL_URL_PREFIX <ide> * @see org.springframework.util.AntPathMatcher <ide> public class PathMatchingResourcePatternResolver implements ResourcePatternResol <ide> * @since 6.0 <ide> * @see #isNotSystemModule <ide> */ <del> private static final Set<String> systemModuleNames = ModuleFinder.ofSystem().findAll().stream() <del> .map(moduleReference -> moduleReference.descriptor().name()).collect(Collectors.toSet()); <add> private static final Set<String> systemModuleNames = NativeDetector.inNativeImage() ? Collections.emptySet() : <add> ModuleFinder.ofSystem().findAll().stream() <add> .map(moduleReference -> moduleReference.descriptor().name()) <add> .collect(Collectors.toSet()); <ide> <ide> /** <ide> * {@link Predicate} that tests whether the supplied {@link ResolvedModule}
1
Python
Python
handle error when no links are found
06df61e38c6ed99732007b0e9f3cc26e8317389e
<ide><path>rest_framework/schemas.py <ide> def get_links(self, request=None): <ide> view_endpoints.append((path, method, view)) <ide> <ide> # Only generate the path prefix for paths that will be included <add> if not paths: <add> return None <ide> prefix = self.determine_path_prefix(paths) <ide> <ide> for path, method, view in view_endpoints:
1
Text
Text
remove unmentioned fields in line 39 query
d69472db128c7fcc7aa6821ed112e7bb71a73823
<ide><path>client/src/pages/guide/english/sql/sql-count-function/index.md <ide> Here we get a count of students in each field of study. <ide> <ide> Here we get a count of students with the same SAT scores. <ide> ```sql <del> select studentID, FullName, count(*) AS studentCount from the student table with a group by sat_score; <add> select sat_score, count(*) AS studentCount from the student table with a group by sat_score; <ide> ``` <ide> ![image-1](https://github.com/SteveChevalier/guide-images/blob/master/count04.JPG?raw=true) <ide>
1
Text
Text
create model card for codebertapy
e41212c7151d09db704682a762257aa6e024b64a
<ide><path>model_cards/mrm8488/CodeBERTaPy/README.md <add>--- <add>language: code <add>thumbnail: <add>--- <add> <add># CodeBERTaPy <add> <add>CodeBERTaPy is a RoBERTa-like model trained on the [CodeSearchNet](https://github.blog/2019-09-26-introducing-the-codesearchnet-challenge/) dataset from GitHub for `python` by [Manuel Romero](https://twitter.com/mrm8488) <add> <add>The **tokenizer** is a Byte-level BPE tokenizer trained on the corpus using Hugging Face `tokenizers`. <add> <add>Because it is trained on a corpus of code (vs. natural language), it encodes the corpus efficiently (the sequences are between 33% to 50% shorter, compared to the same corpus tokenized by gpt2/roberta). <add> <add>The (small) **model** is a 6-layer, 84M parameters, RoBERTa-like Transformer model – that’s the same number of layers & heads as DistilBERT – initialized from the default initialization settings and trained from scratch on the full `python` corpus for 4 epochs. <add> <add>## Quick start: masked language modeling prediction <add> <add>```python <add>PYTHON_CODE = """ <add>fruits = ['apples', 'bananas', 'oranges'] <add>for idx, <mask> in enumerate(fruits): <add> print("index is %d and value is %s" % (idx, val)) <add>""".lstrip() <add>``` <add> <add>### Does the model know how to complete simple Python code? <add> <add>```python <add>from transformers import pipeline <add> <add>fill_mask = pipeline( <add> "fill-mask", <add> model="mrm8488/CodeBERTaPy", <add> tokenizer="mrm8488/CodeBERTaPy" <add>) <add> <add>fill_mask(PYTHON_CODE) <add> <add>## Top 5 predictions: <add> <add>'val' # prob 0.980728805065155 <add>'value' <add>'idx' <add>',val' <add>'_' <add>``` <add> <add>### Yes! That was easy 🎉 Let's try with another Flask like example <add> <add>```python <add>PYTHON_CODE2 = """ <add>@app.route('/<name>') <add>def hello_name(name): <add> return "Hello {}!".format(<mask>) <add> <add>if __name__ == '__main__': <add> app.run() <add>""".lstrip() <add> <add> <add>fill_mask(PYTHON_CODE2) <add> <add>## Top 5 predictions: <add> <add>'name' # prob 0.9961813688278198 <add>' name' <add>'url' <add>'description' <add>'self' <add>``` <add> <add>### Yeah! It works 🎉 Let's try with another Tensorflow/Keras like example <add> <add>```python <add>PYTHON_CODE3=""" <add>model = keras.Sequential([ <add> keras.layers.Flatten(input_shape=(28, 28)), <add> keras.layers.<mask>(128, activation='relu'), <add> keras.layers.Dense(10, activation='softmax') <add>]) <add>""".lstrip() <add> <add> <add>fill_mask(PYTHON_CODE3) <add> <add>## Top 5 predictions: <add> <add>'Dense' # prob 0.4482928514480591 <add>'relu' <add>'Flatten' <add>'Activation' <add>'Conv' <add>``` <add> <add>> Great! 🎉 <add> <add>## This work is heavely inspired on [CodeBERTa](https://github.com/huggingface/transformers/blob/master/model_cards/huggingface/CodeBERTa-small-v1/README.md) by huggingface team <add> <add><br> <add> <add>## CodeSearchNet citation <add> <add><details> <add> <add>```bibtex <add>@article{husain_codesearchnet_2019, <add> title = {{CodeSearchNet} {Challenge}: {Evaluating} the {State} of {Semantic} {Code} {Search}}, <add> shorttitle = {{CodeSearchNet} {Challenge}}, <add> url = {http://arxiv.org/abs/1909.09436}, <add> urldate = {2020-03-12}, <add> journal = {arXiv:1909.09436 [cs, stat]}, <add> author = {Husain, Hamel and Wu, Ho-Hsiang and Gazit, Tiferet and Allamanis, Miltiadis and Brockschmidt, Marc}, <add> month = sep, <add> year = {2019}, <add> note = {arXiv: 1909.09436}, <add>} <add>``` <add> <add></details> <add> <add>> Created by [Manuel Romero/@mrm8488](https://twitter.com/mrm8488) <add> <add>> Made with <span style="color: #e25555;">&hearts;</span> in Spain
1
Text
Text
add api challenges - chinese translation
6b1992ee7c6f5e747244c7c7b59365496b9743ef
<ide><path>curriculum/challenges/chinese/05-apis-and-microservices/apis-and-microservices-projects/exercise-tracker.chinese.md <add>--- <add>id: 5a8b073d06fa14fcfde687aa <add>title: Exercise Tracker <add>localeTitle: 运动追踪器 <add>challengeType: 4 <add>isRequired: true <add>--- <add> <add>## Description <add><section id='description'> <code>0</code>构建一个功能类似于此的完整堆栈JavaScript应用程序: <a href='https://fuschia-custard.glitch.me/' target='_blank'>https</a> : <a href='https://fuschia-custard.glitch.me/' target='_blank'>//fuschia-custard.glitch.me/</a> 。 <code>0</code>在这个项目上工作将涉及您在我们的入门项目上的Glitch上编写代码。完成此项目后,您可以将公共故障网址(到应用程序的主页)复制到此屏幕进行测试!您可以选择在另一个平台上编写项目,但必须公开显示我们的测试。 <code>0</code>使用<a href='https://glitch.com/#!/import/github/freeCodeCamp/boilerplate-project-exercisetracker/' target='_blank'>此链接</a>在Glitch上启动此项目或在GitHub上克隆<a href='https://github.com/freeCodeCamp/boilerplate-project-exercisetracker/'>此存储库</a> !如果您使用Glitch,请记住将项目链接保存到安全的地方! <add></section> <add> <add>## Instructions <add><section id='instructions'> <add> <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: 我可以通过将表单数据用户名发布到/ api / exercise / new-user来创建用户,并返回将是具有用户名和<code>_id</code>的对象。 <add> testString: '' <add> - text: 我可以通过使用与创建用户时相同的信息获取api / exercise / users来获得所有用户的数组。 <add> testString: '' <add> - text: '我可以通过将表单数据userId(_id),描述,持续时间和可选日期发布到/ api / exercise / add来向任何用户添加练习。如果没有提供日期,它将使用当前日期。应用程序将返回添加了练习字段的用户对象。' <add> testString: '' <add> - text: 我可以通过使用userId(_id)参数获取/ api / exercise / log来检索任何用户的完整练习日志。应用程序将返回添加了数组日志和计数(总运动计数)的用户对象。 <add> testString: '' <add> - text: '我还可以通过传递from和to或limit的可选参数来检索任何用户的部分日志。 (日期格式yyyy-mm-dd,limit = int)' <add> testString: '' <add> <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>// solution required <add>``` <add></section> <ide><path>curriculum/challenges/chinese/05-apis-and-microservices/apis-and-microservices-projects/file-metadata-microservice.chinese.md <add>--- <add>id: bd7158d8c443edefaeb5bd0f <add>title: File Metadata Microservice <add>localeTitle: 文件元数据微服务 <add>challengeType: 4 <add>isRequired: true <add>--- <add> <add>## Description <add><section id='description'> <code>0</code>构建一个功能类似于此的完整堆栈JavaScript应用程序: <a href='https://purple-paladin.glitch.me/' target='_blank'>https</a> : <a href='https://purple-paladin.glitch.me/' target='_blank'>//purple-paladin.glitch.me/</a> 。 <code>0</code>在这个项目上工作将涉及您在我们的入门项目上的Glitch上编写代码。完成此项目后,您可以将公共故障网址(到应用程序的主页)复制到此屏幕进行测试!您可以选择在另一个平台上编写项目,但必须公开显示我们的测试。 <code>0</code>使用<a href='https://glitch.com/#!/import/github/freeCodeCamp/boilerplate-project-filemetadata/' target='_blank'>此链接</a>在Glitch上启动此项目或在GitHub上克隆<a href='https://github.com/freeCodeCamp/boilerplate-project-filemetadata/'>此存储库</a> !如果您使用Glitch,请记住将项目链接保存到安全的地方! <add></section> <add> <add>## Instructions <add><section id='instructions'> <add> <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: 我可以提交包含文件上传的FormData对象。 <add> testString: '' <add> - text: “当我提交某些内容时,我将在JSON响应中收到以字节为单位的文件大小。” <add> testString: '' <add> <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>// solution required <add>``` <add></section> <ide><path>curriculum/challenges/chinese/05-apis-and-microservices/apis-and-microservices-projects/request-header-parser-microservice.chinese.md <add>--- <add>id: bd7158d8c443edefaeb5bdff <add>title: Request Header Parser Microservice <add>localeTitle: 请求Header Parser Microservice <add>challengeType: 4 <add>isRequired: true <add>--- <add> <add>## Description <add><section id='description'> <code>0</code>构建一个功能类似于此的完整堆栈JavaScript应用程序: <a href='https://dandelion-roar.glitch.me/' target='_blank'>https</a> : <a href='https://dandelion-roar.glitch.me/' target='_blank'>//dandelion-roar.glitch.me/</a> 。 <code>0</code>在这个项目上工作将涉及您在我们的入门项目上的Glitch上编写代码。完成此项目后,您可以将公共故障网址(到应用程序的主页)复制到此屏幕进行测试!您可以选择在另一个平台上编写项目,但必须公开显示我们的测试。 <code>0</code>使用<a href='https://glitch.com/#!/import/github/freeCodeCamp/boilerplate-project-headerparser/' target='_blank'>此链接</a>在Glitch上启动此项目或在GitHub上克隆<a href='https://github.com/freeCodeCamp/boilerplate-project-headerparser/'>此存储库</a> !如果您使用Glitch,请记住将项目链接保存到安全的地方! <add></section> <add> <add>## Instructions <add><section id='instructions'> <add> <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: “我可以为我的浏览器获取IP地址,语言和操作系统。” <add> testString: '' <add> <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>// solution required <add>``` <add></section> <ide><path>curriculum/challenges/chinese/05-apis-and-microservices/apis-and-microservices-projects/timestamp-microservice.chinese.md <add>--- <add>id: bd7158d8c443edefaeb5bdef <add>title: Timestamp Microservice <add>localeTitle: 时间戳微服务 <add>challengeType: 4 <add>isRequired: true <add>--- <add> <add>## Description <add><section id='description'> <code>0</code>构建一个功能类似于此的完整堆栈JavaScript应用程序: <a href='https://curse-arrow.glitch.me/' target='_blank'>https</a> : <a href='https://curse-arrow.glitch.me/' target='_blank'>//curse-arrow.glitch.me/</a> 。 <code>0</code>在这个项目上工作将涉及您在我们的入门项目上的Glitch上编写代码。完成此项目后,您可以将公共故障网址(到应用程序的主页)复制到此屏幕进行测试!您可以选择在另一个平台上编写项目,但必须公开显示我们的测试。 <code>0</code>使用<a href='https://glitch.com/#!/import/github/freeCodeCamp/boilerplate-project-timestamp/' target='_blank'>此链接</a>在Glitch上启动此项目或在GitHub上克隆<a href='https://github.com/freeCodeCamp/boilerplate-project-timestamp/'>此存储库</a> !如果您使用Glitch,请记住将项目链接保存到安全的地方! <add></section> <add> <add>## Instructions <add><section id='instructions'> <add> <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: '它应该处理一个有效的日期,并返回正确的unix时间戳' <add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/api/timestamp/2016-12-25'').then(data => { assert.equal(data.unix, 1482624000000, ''Should be a valid unix timestamp''); }, xhr => { throw new Error(xhr.responseText); })' <add> - text: '它应该处理一个有效的日期,并返回正确的UTC字符串' <add> testString: 'getUserInput => $.get(getUserInput(''url'')+ ''/api/timestamp/2016-12-25'').then(data => { assert.equal(data.utc, ''Sun, 25 Dec 2016 00:00:00 GMT'', ''Should be a valid UTC date string''); }, xhr => { throw new Error(xhr.responseText); })' <add> - text: '它应该处理一个有效的unix日期,并返回正确的unix时间戳' <add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/api/timestamp/1482624000000'').then(data => { assert.equal(data.unix, 1482624000000) ; }, xhr => { throw new Error(xhr.responseText); })' <add> - text: 它应返回无效日期的预期错误消息 <add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/api/timestamp/this-is-not-a-date'').then(data => { assert.equal(data.error.toLowerCase(), ''invalid date'');}, xhr => { throw new Error(xhr.responseText); })' <add> - text: '它应该处理一个空的日期参数,并以unix格式返回当前时间' <add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/api/timestamp'').then(data => { var now = Date.now(); assert.approximately(data.unix, now, 20000) ;}, xhr => { throw new Error(xhr.responseText); })' <add> - text: '它应该处理一个空日期参数,并以UTC格式返回当前时间' <add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/api/timestamp'').then(data => { var now = Date.now(); var serverTime = (new Date(data.utc)).getTime(); assert.approximately(serverTime, now, 20000) ;}, xhr => { throw new Error(xhr.responseText); })' <add> <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>// solution required <add>``` <add></section> <ide><path>curriculum/challenges/chinese/05-apis-and-microservices/apis-and-microservices-projects/url-shortener-microservice.chinese.md <add>--- <add>id: bd7158d8c443edefaeb5bd0e <add>title: URL Shortener Microservice <add>localeTitle: URL Shortener微服务 <add>challengeType: 4 <add>isRequired: true <add>--- <add> <add>## Description <add><section id='description'> <code>0</code>构建一个功能类似于此的完整堆栈JavaScript应用程序: <a href='https://thread-paper.glitch.me/' target='_blank'>https</a> : <a href='https://thread-paper.glitch.me/' target='_blank'>//thread-paper.glitch.me/</a> 。 <code>0</code>在这个项目上工作将涉及您在我们的入门项目上的Glitch上编写代码。完成此项目后,您可以将公共故障网址(到应用程序的主页)复制到此屏幕进行测试!您可以选择在另一个平台上编写项目,但必须公开显示我们的测试。 <code>0</code>使用<a href='https://glitch.com/#!/import/github/freeCodeCamp/boilerplate-project-urlshortener/' target='_blank'>此链接</a>在Glitch上启动此项目或在GitHub上克隆<a href='https://github.com/freeCodeCamp/boilerplate-project-urlshortener/'>此存储库</a> !如果您使用Glitch,请记住将项目链接保存到安全的地方! <add></section> <add> <add>## Instructions <add><section id='instructions'> <add> <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: 我可以传递一个URL作为参数,我将在JSON响应中收到一个缩短的URL。 <add> testString: '' <add> - text: '如果我传递的网址无效,并且不遵循有效的http://www.example.com格式,则JSON响应将包含错误。' <add> testString: '' <add> - text: “当我访问缩短的网址时,它会将我重定向到我原来的链接。” <add> testString: '' <add> <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>// solution required <add>``` <add></section> <ide><path>curriculum/challenges/chinese/05-apis-and-microservices/basic-node-and-express/chain-middleware-to-create-a-time-server.chinese.md <add>--- <add>id: 587d7fb1367417b2b2512bf4 <add>title: Chain Middleware to Create a Time Server <add>localeTitle: 链中间件创建时间服务器 <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <code>0</code>使用<code>app.METHOD(path, middlewareFunction)</code>可以在特定路径上安装<code>app.METHOD(path, middlewareFunction)</code> 。中间件也可以在路由定义中链接。 <code>0</code>查看以下示例: <add><blockquote>app.get('/user', function(req, res, next) {<br> req.user = getTheUserSync(); // Hypothetical synchronous operation<br> next();<br>}, function(req, res) {<br> res.send(req.user);<br>})</blockquote> <code>0</code>此方法可用于将服务器操作拆分为较小的单元。这导致了更好的应用程序结构,以及在不同位置重用代码的可能性。此方法还可用于对数据执行某些验证。在中间件堆栈的每个点,您可以阻止当前链的执行,并将控制权传递给专门用于处理错误的函数。或者您可以将控制权传递给下一个匹配的路径,以处理特殊情况。我们将在高级Express部分中看到如何。 <code>0</code>在路径<code>app.get('/now', ...)</code>链中间件函数和最终处理程序。在中间件功能中,您应该在<code>req.time</code>键中将当前时间添加到请求对象。您可以使用<code>new Date().toString()</code> 。在处理程序中,使用JSON对象进行响应,采用结构<code>{time: req.time}</code> 。 <code>0</code>提示:如果不链接中间件,测试将无法通过。如果将函数挂载到其他位置,即使输出结果正确,测试也会失败。 <add></section> <add> <add>## Instructions <add><section id='instructions'> <add> <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: / now端点应该已经安装了中间件 <add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/chain-middleware-time'').then(data => { assert.equal(data.stackLength, 2, ''"/now" route has no mounted middleware''); }, xhr => { throw new Error(xhr.responseText); })' <add> - text: / now端点应返回从现在起+/- 20秒的时间 <add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/chain-middleware-time'').then(data => { var now = new Date(); assert.isAtMost(Math.abs(new Date(data.time) - now), 20000, ''the returned time is not between +- 20 secs from now''); }, xhr => { throw new Error(xhr.responseText); })' <add> <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>// solution required <add>``` <add></section> <ide><path>curriculum/challenges/chinese/05-apis-and-microservices/basic-node-and-express/get-data-from-post-requests.chinese.md <add>--- <add>id: 587d7fb2367417b2b2512bf8 <add>title: Get Data from POST Requests <add>localeTitle: 从POST请求中获取数据 <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <code>0</code>在路径<code>/name</code>处安装POST处理程序。它和以前一样。我们在html首页中准备了一个表单。它将提交练习10(查询字符串)的相同数据。如果正确配置了body-parser,您应该在对象<code>req.body</code>找到参数。看看通常的库示例: <add><blockquote>route: POST '/library'<br>urlencoded_body: userId=546&bookId=6754 <br>req.body: {userId: '546', bookId: '6754'}</blockquote> <code>0</code>使用与以前相同的JSON对象进行响应: <code>{name: 'firstname lastname'}</code> 。使用我们在应用程序首页中提供的html表单测试您的端点是否正常工作。 <code>0</code>提示:除了GET和POST之外,还有其他几种http方法。按照惯例,http动词与您要在服务器上执行的操作之间存在对应关系。传统的映射是: <add>POST(有时是PUT) - 使用随请求发送的信息创建新资源, <add>GET - 读取现有资源而不修改它, <add>PUT或PATCH(有时是POST) - 使用数据更新资源已发送, <add>DELETE =&gt;删除资源。 <code>0</code>还有一些其他方法用于协商与服务器的连接。除了GET之外,上面列出的所有其他方法都可以有一个有效载荷(即数据进入请求体)。身体解析器中间件也适用于这些方法。 <add></section> <add> <add>## Instructions <add><section id='instructions'> <add> <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: '测试1:您的API端点应使用正确的名称进行响应' <add> testString: 'getUserInput => $.post(getUserInput(''url'') + ''/name'', {first: ''Mick'', last: ''Jagger''}).then(data => { assert.equal(data.name, ''Mick Jagger'', ''Test 1: "POST /name" route does not behave as expected'') }, xhr => { throw new Error(xhr.responseText); })' <add> - text: '测试2:您的API端点应使用正确的名称进行响应' <add> testString: 'getUserInput => $.post(getUserInput(''url'') + ''/name'', {first: ''Keith'', last: ''Richards''}).then(data => { assert.equal(data.name, ''Keith Richards'', ''Test 2: "POST /name" route does not behave as expected'') }, xhr => { throw new Error(xhr.responseText); })' <add> <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>// solution required <add>``` <add></section> <ide><path>curriculum/challenges/chinese/05-apis-and-microservices/basic-node-and-express/get-query-parameter-input-from-the-client.chinese.md <add>--- <add>id: 587d7fb2367417b2b2512bf6 <add>title: Get Query Parameter Input from the Client <add>localeTitle: 从客户端获取查询参数输入 <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <code>0</code>从客户端获取输入的另一种常用方法是使用查询字符串对路径路径后的数据进行编码。查询字符串由问号(?)分隔,并包括field = value couple。每对夫妇用和号(&)隔开。 Express可以解析查询字符串中的数据,并填充对象<code>req.query</code> 。某些字符不能在URL中,它们必须以<a href='https://en.wikipedia.org/wiki/Percent-encoding' target='_blank'>不同的格式</a>编码才能发送它们。如果您使用JavaScript中的API,则可以使用特定方法对这些字符进行编码/解码。 <add><blockquote>route_path: '/library'<br>actual_request_URL: '/library?userId=546&bookId=6754' <br>req.query: {userId: '546', bookId: '6754'}</blockquote> <code>0</code>构建一个以<code>GET /name</code>挂载的API端点。使用结构<code>{ name: 'firstname lastname'}</code>回复JSON文档。名字和姓氏参数应该在查询字符串中编码,例如<code>?first=firstname&amp;last=lastname</code> 。 <code>0</code>提示:在下面的练习中,我们将在相同<code>/name</code>路径路径的POST请求中接收数据。如果需要,可以使用方法<code>app.route(path).get(handler).post(handler)</code> 。此语法允许您在同一路径路径上链接不同的动词处理程序。您可以节省一些打字,并拥有更清晰的代码。 <add></section> <add> <add>## Instructions <add><section id='instructions'> <add> <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: '测试1:您的API端点应使用正确的名称进行响应' <add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/name?first=Mick&last=Jagger'').then(data => { assert.equal(data.name, ''Mick Jagger'', ''Test 1: "GET /name" route does not behave as expected'') }, xhr => { throw new Error(xhr.responseText); })' <add> - text: '测试2:您的APi端点应以正确的名称响应' <add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/name?last=Richards&first=Keith'').then(data => { assert.equal(data.name, ''Keith Richards'', ''Test 2: "GET /name" route does not behave as expected'') }, xhr => { throw new Error(xhr.responseText); })' <add> <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>// solution required <add>``` <add></section> <ide><path>curriculum/challenges/chinese/05-apis-and-microservices/basic-node-and-express/get-route-parameter-input-from-the-client.chinese.md <add>--- <add>id: 587d7fb2367417b2b2512bf5 <add>title: Get Route Parameter Input from the Client <add>localeTitle: 从客户端获取路由参数输入 <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <code>0</code>构建API时,我们必须允许用户与我们沟通他们希望从我们的服务中获得什么。例如,如果客户端请求有关存储在数据库中的用户的信息,他们需要一种方法让我们知道他们感兴趣的用户。实现此结果的一种可能方法是使用路由参数。路由参数是URL的命名段,由斜杠(/)分隔。每个段捕获URL的与其位置匹配的部分的值。捕获的值可以在<code>req.params</code>对象中找到。 <add><blockquote>route_path: '/user/:userId/book/:bookId'<br>actual_request_URL: '/user/546/book/6754' <br>req.params: {userId: '546', bookId: '6754'}</blockquote> <code>0</code>构建一个安装在路径<code>GET /:word/echo</code>的回显服务器。使用结构<code>{echo: word}</code>响应JSON对象。您可以在<code>req.params.word</code>找到要重复的<code>req.params.word</code> 。您可以从浏览器的地址栏测试您的路线,访问一些匹配的路线,例如您的-app-rootpath / freecodecamp / echo <add></section> <add> <add>## Instructions <add><section id='instructions'> <add> <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: '测试1:您的echo服务器应该正确重复单词' <add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/eChOtEsT/echo'').then(data => { assert.equal(data.echo, ''eChOtEsT'', ''Test 1: the echo server is not working as expected'') }, xhr => { throw new Error(xhr.responseText); })' <add> - text: '测试2:您的echo服务器应该正确重复单词' <add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/ech0-t3st/echo'').then(data => { assert.equal(data.echo, ''ech0-t3st'', ''Test 2: the echo server is not working as expected'') }, xhr => { throw new Error(xhr.responseText); })' <add> <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>// solution required <add>``` <add></section> <ide><path>curriculum/challenges/chinese/05-apis-and-microservices/basic-node-and-express/implement-a-root-level-request-logger-middleware.chinese.md <add>--- <add>id: 587d7fb1367417b2b2512bf3 <add>title: Implement a Root-Level Request Logger Middleware <add>localeTitle: 实现根级请求记录器中间件 <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <code>0</code>在我们介绍<code>express.static()</code>中间件函数之前。现在是时候更详细地看看中间件是什么了。中间件函数是带有3个参数的函数:请求对象,响应对象和应用程序请求 - 响应周期中的下一个函数。这些函数执行一些可能对应用程序产生副作用的代码,并且通常会向请求或响应对象添加信息。当满足某些条件时,它们还可以结束发送响应的循环。如果他们没有发送响应,当他们完成时,他们开始执行堆栈中的下一个函数。触发调用第三个参数<code>next()</code> 。 <a href='http://expressjs.com/en/guide/using-middleware.html' target='_blank'>快递文档</a>中的更多信息。 <code>0</code>查看以下示例: <add><blockquote>function(req, res, next) {<br> console.log("I'm a middleware...");<br> next();<br>}</blockquote> <code>0</code>假设我们在路线上安装了此功能。当请求与路由匹配时,它会显示字符串“我是中间件......”。然后它执行堆栈中的下一个函数。 <code>0</code>在本练习中,我们将构建一个根级中间件。正如我们在挑战4中所见,要在根级别安装中间件功能,我们可以使用方法<code>app.use(&lt;mware-function&gt;)</code> 。在这种情况下,将对所有请求执行该功能,但您也可以设置更具体的条件。例如,如果您希望仅为POST请求执行某个函数,则可以使用<code>app.post(&lt;mware-function&gt;)</code> 。所有http动词都有类似的方法(GET,DELETE,PUT,...)。 <code>0</code>构建一个简单的记录器。对于每个请求,它应该在控制台中登录一个字符串,采用以下格式: <code>method path - ip</code> 。示例如下: <code>GET /json - ::ffff:127.0.0.1</code> 。请注意, <code>method</code>和<code>path</code>之间有一个空格,并且破折号分隔<code>path</code>和<code>ip</code>被两侧的空格包围。您可以使用<code>req.method</code> , <code>req.path</code>和<code>req.ip</code>从请求对象获取请求方法(http谓词),相对路由路径和调用者的ip。记得在完成后调用<code>next()</code> ,否则你的服务器将永远停留。确保打开“日志”,并查看某些请求到达时会发生什么... <code>0</code>提示:Express按照它们在代码中出现的顺序评估函数。中间件也是如此。如果您希望它适用于所有路由,则应在它们之前安装它。 <add></section> <add> <add>## Instructions <add><section id='instructions'> <add> <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: 根级别记录器中间件应该是活动的 <add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/root-middleware-logger'').then(data => { assert.isTrue(data.passed, ''root-level logger is not working as expected''); }, xhr => { throw new Error(xhr.responseText); })' <add> <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>// solution required <add>``` <add></section> <ide><path>curriculum/challenges/chinese/05-apis-and-microservices/basic-node-and-express/meet-the-node-console.chinese.md <add>--- <add>id: 587d7fb0367417b2b2512bed <add>title: Meet the Node console <add>localeTitle: 认识节点控制台 <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <code>0</code>在开发过程中,能够检查代码中发生的情况非常重要。 Node只是一个JavaScript环境。与客户端JavaScript一样,您可以使用控制台显示有用的调试信息。在本地计算机上,您将在终端中看到控制台输出。在Glitch上,您可以打开屏幕下方的日志。您可以使用“日志”按钮切换日志面板(左上角,在应用名称下)。 <code>0</code>要开始使用,只需在控制台中打印经典的“Hello World”即可。我们建议在应对这些挑战时保持日志面板处于打开状态。阅读日志,您可以了解可能发生的错误的性质。 <add></section> <add> <add>## Instructions <add><section id='instructions'> <code>0</code>修改<code>myApp.js</code>文件以将“Hello World”记录到控制台。 <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: <code>"Hello World"</code>应该在控制台中 <add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/hello-console'').then(data => { assert.isTrue(data.passed, ''"Hello World" is not in the server console''); }, xhr => { throw new Error(xhr.responseText); })' <add> <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>// solution required <add>``` <add></section> <ide><path>curriculum/challenges/chinese/05-apis-and-microservices/basic-node-and-express/serve-an-html-file.chinese.md <add>--- <add>id: 587d7fb0367417b2b2512bef <add>title: Serve an HTML File <add>localeTitle: 提供HTML文件 <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <code>0</code>我们可以使用<code>res.sendFile(path)</code>方法响应文件。 <code>0</code>您可以将它放在<code>app.get('/', ...)</code>路由处理程序中。在幕后,此方法将根据其类型设置适当的标头,以指示您的浏览器如何处理您要发送的文件。然后它将读取并发送文件。此方法需要绝对文件路径。我们建议您使用Node全局变量<code>__dirname</code>来计算路径。 <code>0</code>例如<code>absolutePath = __dirname + relativePath/file.ext</code> 。 <code>0</code>要发送的文件是<code>/views/index.html</code> 。尝试“显示”你的应用程序,你应该看到一个很大的HTML标题(以及我们稍后将使用的表单......),没有应用任何样式。 <code>0</code>注意:您可以编辑上一个挑战的解决方案,也可以创建一个新挑战。如果您创建新解决方案,请记住Express会从上到下评估路由。它执行第一个匹配的处理程序。您必须注释掉前面的解决方案,否则服务器将继续使用字符串进行响应。 <add></section> <add> <add>## Instructions <add><section id='instructions'> <add> <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: 您的应用应该提供文件views / index.html <add> testString: 'getUserInput => $.get(getUserInput(''url'')).then(data => { assert.match(data, /<h1>.*<\/h1>/, ''Your app does not serve the expected HTML''); }, xhr => { throw new Error(xhr.responseText); })' <add> <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>// solution required <add>``` <add></section> <ide><path>curriculum/challenges/chinese/05-apis-and-microservices/basic-node-and-express/serve-json-on-a-specific-route.chinese.md <add>--- <add>id: 587d7fb1367417b2b2512bf1 <add>title: Serve JSON on a Specific Route <add>localeTitle: 在特定路线上提供JSON <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <code>0</code>虽然HTML服务器提供(您猜对了!)HTML,但API提供数据。 <dfn>REST</dfn> (REpresentational State Transfer)API允许以简单的方式进行数据交换,而无需客户端知道有关服务器的任何细节。客户端只需要知道资源的位置(URL),以及它想要对其执行的操作(动词)。当您获取某些信息而不修改任何信息时,将使用GET动词。目前,用于在Web上移动信息的首选数据格式是JSON。简单地说,JSON是一种将JavaScript对象表示为字符串的便捷方式,因此可以轻松传输。 <code>0</code>让我们通过在路径<code>/json</code>处创建一个以JSON响应的路由来创建一个简单的API。您可以像往常一样使用<code>app.get()</code>方法执行此操作。在路由处理程序内部使用方法<code>res.json()</code> ,将对象作为参数传入。此方法关闭请求 - 响应循环,返回数据。在幕后,它将有效的JavaScript对象转换为字符串,然后设置相应的标题以告诉您的浏览器您正在提供JSON,并将数据发回。有效对象具有通常的结构<code>{key: data}</code> 。数据可以是数字,字符串,嵌套对象或数组。数据也可以是变量或函数调用的结果,在这种情况下,它将在转换为字符串之前进行评估。 <code>0</code>将对象<code>{"message": "Hello json"}</code>作为JSON格式的响应提供给对路由<code>/json</code>的GET请求。然后将浏览器指向your-app-url / json,您应该在屏幕上看到该消息。 <add></section> <add> <add>## Instructions <add><section id='instructions'> <add> <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: 'endpoint <code>/json</code>应该服务于json对象<code>{"message": "Hello json"}</code> ' <add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/json'').then(data => { assert.equal(data.message, ''Hello json'', ''The \''/json\'' endpoint does not serve the right data''); }, xhr => { throw new Error(xhr.responseText); })' <add> <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>// solution required <add>``` <add></section> <ide><path>curriculum/challenges/chinese/05-apis-and-microservices/basic-node-and-express/serve-static-assets.chinese.md <add>--- <add>id: 587d7fb0367417b2b2512bf0 <add>title: Serve Static Assets <add>localeTitle: 服务静态资产 <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <add>HTML服务器通常有一个或多个用户可以访问的目录。您可以放置应用程序所需的静态资产(样式表,脚本,图像)。在Express中,您可以使用中间件<code>express.static(path)</code>来实现此功能,其中参数是包含资产的文件夹的绝对路径。如果您不知道中间件是什么,请不要担心。我们稍后会详细讨论它。基本上,中间件是拦截路由处理程序,添加某种信息的函数。需要使用<code>app.use(path, middlewareFunction)</code>方法<code>app.use(path, middlewareFunction)</code> 。第一个路径参数是可选的。如果您没有通过它,将为所有请求执行中间件。 <code>0</code>使用<code>app.use()</code>为所有请求安装<code>express.static()</code>中间件。 assets文件夹的绝对路径是<code>__dirname + /public</code> 。 <code>0</code>现在,您的应用应该能够提供CSS样式表。从公共文件夹外部将显示挂载到根目录。你的头版现在应该看起来好一点! <add></section> <add> <add>## Instructions <add><section id='instructions'> <add> <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: 您的应用应该从<code>/public</code>目录提供资产文件 <add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/style.css'').then(data => { assert.match(data, /body\s*\{[^\}]*\}/, ''Your app does not serve static assets''); }, xhr => { throw new Error(xhr.responseText); })' <add> <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>// solution required <add>``` <add></section> <ide><path>curriculum/challenges/chinese/05-apis-and-microservices/basic-node-and-express/start-a-working-express-server.chinese.md <add>--- <add>id: 587d7fb0367417b2b2512bee <add>title: Start a Working Express Server <add>localeTitle: 启动Working Express服务器 <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <code>0</code>在myApp.js文件的前两行中,您可以看到如何轻松创建Express应用程序对象。这个对象有几种方法,我们将在这些挑战中学到很多方法。一个基本方法是<code>app.listen(port)</code> 。它告诉您的服务器侦听给定端口,使其处于运行状态。您可以在文件底部看到它。这是内部评论,因为出于测试原因,我们需要应用程序在后台运行。您可能想要添加的所有代码都介于这两个基本部分之间。 Glitch将端口号存储在环境变量<code>process.env.PORT</code> 。它的价值是<code>3000</code> 。 <code>0</code>让我们的第一个字符串!在Express中,路由采用以下结构: <code>app.METHOD(PATH, HANDLER)</code> 。 METHOD是小写的http方法。 PATH是服务器上的相对路径(它可以是字符串,甚至是正则表达式)。 HANDLER是Express匹配路由时调用的功能。 <code>0</code>处理程序采用表单<code>function(req, res) {...}</code> ,其中req是请求对象,res是响应对象。例如,处理程序 <add><blockquote>function(req, res) {<br> res.send('Response String');<br>}</blockquote> <code>0</code>将提供字符串'Response String'。 <code>0</code>使用<code>app.get()</code>方法为字符串Hello Express提供服务,以匹配/ root路径的GET请求。通过查看日志确保您的代码正常工作,然后在浏览器中查看结果,单击Glitch UI中的“Show Live”按钮。 <add></section> <add> <add>## Instructions <add><section id='instructions'> <add> <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: 您的应用应该提供字符串'Hello Express' <add> testString: 'getUserInput => $.get(getUserInput(''url'')).then(data => { assert.equal(data, ''Hello Express'', ''Your app does not serve the text "Hello Express"''); }, xhr => { throw new Error(xhr.responseText); })' <add> <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>// solution required <add>``` <add></section> <ide><path>curriculum/challenges/chinese/05-apis-and-microservices/basic-node-and-express/use-body-parser-to-parse-post-requests.chinese.md <add>--- <add>id: 587d7fb2367417b2b2512bf7 <add>title: Use body-parser to Parse POST Requests <add>localeTitle: 使用body-parser来解析POST请求 <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <code>0</code>除了GET之外还有另一个常见的http动词,它是POST。 POST是用于使用HTML表单发送客户端数据的默认方法。在REST约定中,POST用于发送数据以在数据库中创建新项目(新用户或新博客文章)。我们在这个项目中没有数据库,但我们将学习如何处理POST请求。 <code>0</code>在这些请求中,数据不会出现在URL中,它隐藏在请求正文中。这是HTML请求的一部分,也称为有效负载。由于HTML是基于文本的,即使您没有看到数据,也不意味着它们是秘密的。 HTTP POST请求的原始内容如下所示: <add><blockquote>POST /path/subpath HTTP/1.0<br>From: john@example.com<br>User-Agent: someBrowser/1.0<br>Content-Type: application/x-www-form-urlencoded<br>Content-Length: 20<br>name=John+Doe&age=25</blockquote> <code>0</code>正如您所见,正文被编码为查询字符串。这是HTML表单使用的默认格式。使用Ajax,我们还可以使用JSON来处理具有更复杂结构的数据。还有另一种编码类型:multipart / form-data。这个用于上传二进制文件。 <code>0</code>在本练习中,我们将使用urlencoded主体。 <code>0</code>要解析来自POST请求的数据,您必须安装一个包:body-parser。该软件包允许您使用一系列中间件,这些中间件可以解码不同格式的数据。请参阅<a href="https://github.com/expressjs/body-parser" target="_blank" >此处</a>的文档。 <code>0</code>在package.json中安装body-parser模块。然后在文件的顶部需要它。将其存储在名为bodyParser的变量中。 <add><code>bodyParser.urlencoded({extended: false})</code>返回处理url编码数据的中间件。 <code>extended=false</code>是一个配置选项,告诉解析器使用经典编码。使用它时,值可以只是字符串或数组。扩展版本允许更多的数据灵活性,但它被JSON击败。将<code>app.use()</code>传递给前一个方法调用返回的函数。像往常一样,必须在需要它的所有路由之前安装中间件。 <add></section> <add> <add>## Instructions <add><section id='instructions'> <add> <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: 应该安装'body-parser'中间件 <add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/add-body-parser'').then(data => { assert.isAbove(data.mountedAt, 0, ''"body-parser" is not mounted correctly'') }, xhr => { throw new Error(xhr.responseText); })' <add> <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>// solution required <add>``` <add></section> <ide><path>curriculum/challenges/chinese/05-apis-and-microservices/basic-node-and-express/use-the-.env-file.chinese.md <add>--- <add>id: 587d7fb1367417b2b2512bf2 <add>title: Use the .env File <add>localeTitle: 使用.env文件 <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <add><code>.env</code>文件是一个隐藏文件,用于将环境变量传递给应用程序。这个文件是秘密的,没有人可以访问它,它可以用来存储你想保密或隐藏的数据。例如,您可以存储来自外部服务或数据库URI的API密钥。您还可以使用它来存储配置选项。通过设置配置选项,您可以更改应用程序的行为,而无需重写某些代码。 <code>0</code>可以从应用程序访问环境变量<code>process.env.VAR_NAME</code> 。 <code>process.env</code>对象是一个全局Node对象,变量作为字符串传递。按照惯例,变量名都是大写的,单词用下划线分隔。 <code>.env</code>是一个shell文件,因此您不需要在引号中包装名称或值。同样重要的是要注意,当您为变量赋值时,等号周围不能有空格,例如<code>VAR_NAME=value</code> 。通常,您将每个变量定义放在单独的行上。 <code>0</code>让我们添加一个环境变量作为配置选项。将变量<code>MESSAGE_STYLE=uppercase</code>存储在<code>.env</code>文件中。然后告诉您在上一次质询中创建的GET <code>/json</code>路由处理程序,如果<code>process.env.MESSAGE_STYLE</code>等于<code>uppercase</code>则将响应对象的消息转换为<code>uppercase</code> 。响应对象应该成为<code>{"message": "HELLO JSON"}</code> 。 <add></section> <add> <add>## Instructions <add><section id='instructions'> <add> <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: 端点<code>/json</code>的响应应根据环境变量<code>MESSAGE_STYLE</code> <add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/use-env-vars'').then(data => { assert.isTrue(data.passed, ''The response of "/json" does not change according to MESSAGE_STYLE''); }, xhr => { throw new Error(xhr.responseText); })' <add> <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>// solution required <add>``` <add></section> <ide><path>curriculum/challenges/chinese/05-apis-and-microservices/managing-packages-with-npm/add-a-description-to-your-package.json.chinese.md <add>--- <add>id: 587d7fb3367417b2b2512bfc <add>title: Add a Description to Your package.json <add>localeTitle: 在package.json中添加一个描述 <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <code>0</code>一个好的package.json的下一部分是description-field,其中有关于您的项目的简短但信息丰富的描述。 <code>0</code>如果您有一天计划将软件包发布到npm,请记住这是一个字符串,当他们决定是否安装您的软件包时,应该将该想法卖给用户。然而,这并不是描述的唯一用例:这是总结项目工作的一种很好的方式,对于正常的Node.js项目来说,这对于帮助其他开发人员,未来的维护人员甚至是您未来的自我来理解项目同样重要很快。 <code>0</code>无论您对项目的计划是什么,都建议您使用说明。让我们添加类似的东西: <add><code>"description": "A project that does something awesome",</code> <code>0</code>说明<code>0</code>在Glitch项目中向package.json添加一个描述。 <code>0</code>记住要使用双引号场名称(“)和逗号(,)分隔的字段。 <add></section> <add> <add>## Instructions <add><section id='instructions'> <add> <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: package.json应该有一个有效的“描述”键 <add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert(packJson.description, ''"description" is missing''); }, xhr => { throw new Error(xhr.responseText); })' <add> <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>// solution required <add>``` <add></section> <ide><path>curriculum/challenges/chinese/05-apis-and-microservices/managing-packages-with-npm/add-a-license-to-your-package.json.chinese.md <add>--- <add>id: 587d7fb4367417b2b2512bfe <add>title: Add a License to Your package.json <add>localeTitle: 向package.json添加许可证 <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <code>0</code>许可证字段用于通知项目用户他们可以使用它做什么。 <code>0</code>开源项目的一些常见许可证包括MIT和BSD。如果您想了解更多适合您项目的许可证,http://choosealicense.com是一个很好的资源。 <code>0</code>不需要许可证信息。大多数国家/地区的版权法都将授予您默认创建的所有权。但是,明确说明用户可以做什么和不做什么总是一个好习惯。 <code>0</code>示例 <add><code>"license": "MIT",</code> <code>0</code>说明<code>0</code>如果您认为合适,请填写Glitch项目的package.json中的license-field。 <add></section> <add> <add>## Instructions <add><section id='instructions'> <add> <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: package.json应该有一个有效的“许可证”密钥 <add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert(packJson.license, ''"license" is missing''); }, xhr => { throw new Error(xhr.responseText); })' <add> <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>// solution required <add>``` <add></section> <ide><path>curriculum/challenges/chinese/05-apis-and-microservices/managing-packages-with-npm/add-a-version-to-your-package.json.chinese.md <add>--- <add>id: 587d7fb4367417b2b2512bff <add>title: Add a Version to Your package.json <add>localeTitle: 在package.json中添加一个版本 <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <code>0</code>该版本与package.json中必填字段之一一起。该字段描述了项目的当前版本。 <code>0</code>示例 <add><code>"version": "1.2",</code> <code>0</code>说明<code>0</code>在Glitch项目中向package.json添加版本。 <add></section> <add> <add>## Instructions <add><section id='instructions'> <add> <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: package.json应该有一个有效的“版本”密钥 <add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert(packJson.version, ''"version" is missing''); }, xhr => { throw new Error(xhr.responseText); })' <add> <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>// solution required <add>``` <add></section> <ide><path>curriculum/challenges/chinese/05-apis-and-microservices/managing-packages-with-npm/add-keywords-to-your-package.json.chinese.md <add>--- <add>id: 587d7fb4367417b2b2512bfd <add>title: Add Keywords to Your package.json <add>localeTitle: 将关键字添加到package.json <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <add>keywords-field是您可以使用相关关键字描述项目的地方。 <code>0</code>示例 <add><code>"keywords": [ "descriptive", "related", "words" ],</code> <code>0</code>如您所见,此字段的结构为双引号字符串数组。 <code>0</code>说明<code>0</code>将一组合适的字符串添加到Glitch项目的package.json中的keywords-field。 <code>0</code>其中一个关键字应该是freecodecamp。 <add></section> <add> <add>## Instructions <add><section id='instructions'> <add> <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: package.json应该有一个有效的“关键字”键 <add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert(packJson.keywords, ''"keywords" is missing''); }, xhr => { throw new Error(xhr.responseText); })' <add> - text: '“keywords”字段应为Array' <add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert.isArray(packJson.keywords, ''"keywords" is not an array''); }, xhr => { throw new Error(xhr.responseText); })' <add> - text: '“关键字”应包含“freecodecamp”' <add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert.include(packJson.keywords, ''freecodecamp'', ''"keywords" does not include "freecodecamp"''); }, xhr => { throw new Error(xhr.responseText); })' <add> <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>// solution required <add>``` <add></section> <ide><path>curriculum/challenges/chinese/05-apis-and-microservices/managing-packages-with-npm/expand-your-project-with-external-packages-from-npm.chinese.md <add>--- <add>id: 587d7fb4367417b2b2512c00 <add>title: Expand Your Project with External Packages from npm <add>localeTitle: 从npm扩展您的项目与外部包 <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <code>0</code>使用包管理器的一个最大原因是它们强大的依赖关系管理。 npm无需手动确保在新计算机上设置项目时获得所有依赖项,npm会自动为您安装所有内容。但是,npm怎么能确切地知道你的项目需要什么呢?遇到package.json的依赖项部分。 <code>0</code>在dependencies-section中,使用以下格式存储项目所需的包: <add><code>"dependencies": {</code> <add><code>"package-name": "version",</code> <add><code>"express": "4.14.0"</code> <add><code>}</code> <code>0</code>指令<code>0</code>将软件包时刻的2.14.0版本添加到package.json的依赖项字段中 <add>Moment是一个方便的库,用于处理时间和日期。 <add></section> <add> <add>## Instructions <add><section id='instructions'> <add> <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: '“依赖”应该包括“时刻”' <add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert.property(packJson.dependencies, ''moment'', ''"dependencies" does not include "moment"''); }, xhr => { throw new Error(xhr.responseText); })' <add> - text: '“时刻”版本应为“2.14.0”' <add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert.match(packJson.dependencies.moment, /^[\^\~]?2\.14\.0/, ''Wrong version of "moment" installed. It should be 2.14.0''); }, xhr => { throw new Error(xhr.responseText); })' <add> <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>// solution required <add>``` <add></section> <ide><path>curriculum/challenges/chinese/05-apis-and-microservices/managing-packages-with-npm/how-to-use-package.json-the-core-of-any-node.js-project-or-npm-package.chinese.md <add>--- <add>id: 587d7fb3367417b2b2512bfb <add>title: 'How to Use package.json, the Core of Any Node.js Project or npm Package' <add>localeTitle: '如何使用package.json,任何Node.js项目的核心或npm包' <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <code>0</code>文件package.json是任何Node.js项目或npm包的中心。它存储有关项目的信息,就像HTML文档中的&lt;head&gt; -section描述网页内容一样。 package.json由一个JSON对象组成,其中信息存储在“key”:value-pairs中。最小的package.json中只有两个必填字段 - 名称和版本 - 但提供有关您的项目的其他信息可能对未来的用户或维护者有用,这是一个很好的做法。 <code>0</code>作者字段<code>0</code>如果您转到之前设置的Glitch项目并在屏幕左侧查看,您将找到文件树,您可以在其中查看项目中各种文件的概述。在文件树的后端部分,你会找到package.json - 我们将在接下来的几个挑战中改进的文件。 <code>0</code>此文件中最常见的信息之一是author-field,它指定了谁是项目的创建者。它可以是字符串,也可以是具有联系人详细信息的对象。对于较大的项目,建议使用该对象,但在我们的示例中,将使用类似以下示例的简单字符串。 <add><code>"author": "Jane Doe",</code> <code>0</code>说明<code>0</code>将您的名字添加到Glitch项目的package.json中的author-field。 <code>0</code>记住你正在编写JSON。 <code>0</code>所有字段名称必须使用双引号(“),例如”author“ <code>0</code>所有字段必须用逗号分隔(,) <add></section> <add> <add>## Instructions <add><section id='instructions'> <add> <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: package.json应该有一个有效的“作者”密钥 <add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert(packJson.author, ''"author" is missing''); }, xhr => { throw new Error(xhr.responseText); })' <add> <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>// solution required <add>``` <add></section> <ide><path>curriculum/challenges/chinese/05-apis-and-microservices/managing-packages-with-npm/manage-npm-dependencies-by-understanding-semantic-versioning.chinese.md <add>--- <add>id: 587d7fb5367417b2b2512c01 <add>title: Manage npm Dependencies By Understanding Semantic Versioning <add>localeTitle: 通过了解语义版本控制来管理npm依赖项 <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <add>package.json的dependencies-section中的npm软件包的版本遵循所谓的语义版本控制(SemVer),这是软件版本控制的行业标准,旨在使管理依赖项更容易。在npm上发布的库,框架或其他工具应使用SemVer,以便清楚地传达依赖于程序包的项目在更新时可以期望的更改类型。 <add>SemVer在没有公共API的项目中没有意义 - 所以除非你的项目与上面的例子类似,否则使用另一种版本控制格式。 <code>0</code>那么为什么你需要了解SemVer? <code>0</code>了解SemVer在开发使用外部依赖项的软件时非常有用(您几乎总是这样做)。有一天,您对这些数字的理解将使您免于意外地对项目进行重大更改而不理解为什么“昨天有效”的事情突然之间没有。 <code>0</code>这是语义版本控制根据官方网站的工作方式: <code>0</code>给定版本号MAJOR.MINOR.PATCH,当您进行不兼容的API更改时,增加: <add>MAJOR版本,当以向后兼容的方式添加功能时,增加 <add>MINOR版本,当您进行向后兼容的错误修复时,和 <add>PATCH版本。 <code>0</code>这意味着PATCH是错误修复,MINOR添加了新功能,但它们都没有破坏之前的功能。最后,MAJOR添加了对早期版本无效的更改。 <code>0</code>示例<code>0</code>语义版本号:1.3.8 <code>0</code>说明<code>0</code>在package.json的dependencies-section中,更改时刻版本以匹配MAJOR版本2,MINOR版本10和PATCH版本2 <add></section> <add> <add>## Instructions <add><section id='instructions'> <add> <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: '“依赖”应该包括“时刻”' <add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert.property(packJson.dependencies, ''moment'', ''"dependencies" does not include "moment"''); }, xhr => { throw new Error(xhr.responseText); })' <add> - text: '“时刻”版应该是“2.10.2”' <add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert.match(packJson.dependencies.moment, /^[\^\~]?2\.10\.2/, ''Wrong version of "moment". It should be 2.10.2''); }, xhr => { throw new Error(xhr.responseText); })' <add> <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>// solution required <add>``` <add></section> <ide><path>curriculum/challenges/chinese/05-apis-and-microservices/managing-packages-with-npm/remove-a-package-from-your-dependencies.chinese.md <add>--- <add>id: 587d7fb5367417b2b2512c04 <add>title: Remove a Package from Your Dependencies <add>localeTitle: 从您的依赖项中删除一个包 <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <code>0</code>现在,您已经通过使用package.json的dependencies-section测试了一些可以管理项目依赖关系的方法。您已将外部包添加到文件中,甚至通过使用特殊字符作为代字号(〜)或插入符号(^)告诉npm您需要哪些类型的版本。 <code>0</code>但是如果你想删除不再需要的外部包呢?您可能已经猜到了 - 只需从依赖项中删除相应的“key”:value对。 <code>0</code>同样的方法也适用于删除package.json中的其他字段<code>0</code>说明<code>0</code>从依赖项中删除包时刻。 <code>0</code>删除后确保您有相同数量的逗号。 <add></section> <add> <add>## Instructions <add><section id='instructions'> <add> <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: '“依赖”不应该包括“时刻”' <add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert.notProperty(packJson.dependencies, ''moment'', ''"dependencies" still includes "moment"''); }, xhr => { throw new Error(xhr.responseText); })' <add> <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>// solution required <add>``` <add></section> <ide><path>curriculum/challenges/chinese/05-apis-and-microservices/managing-packages-with-npm/use-the-caret-character-to-use-the-latest-minor-version-of-a-dependency.chinese.md <add>--- <add>id: 587d7fb5367417b2b2512c03 <add>title: Use the Caret-Character to Use the Latest Minor Version of a Dependency <add>localeTitle: 使用插入符号来使用最新的次要版本的依赖项 <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <code>0</code>类似于我们在上一次挑战中学到的波形符(〜)允许npm为依赖项安装最新的PATCH,插入符号(^)允许npm也安装将来的更新。不同之处在于插入符号将允许MINOR更新和PATCH。 <code>0</code>目前,您当前版本的时刻应为~2.10.2,允许npm安装到最新的2.10.x版本。如果我们改为使用插入符号(^)作为我们的版本前缀,则允许npm更新为任何2.xx版本。 <code>0</code>示例 <add><code>"some-package-name": "^1.3.8" allows updates to any 1.xx version.</code> <code>0</code>使用说明<code>0</code>使用插入符(^)为依赖项中的时刻版本添加前缀,并允许npm将其更新为任何新的MINOR版本。 <code>0</code>请注意,不应更改版本号本身。 <add></section> <add> <add>## Instructions <add><section id='instructions'> <add> <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: '“依赖”应该包括“时刻”' <add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert.property(packJson.dependencies, ''moment'', ''"dependencies" does not include "moment"''); }, xhr => { throw new Error(xhr.responseText); })' <add> - text: '“moment”版本应匹配“^ 2.x.x”' <add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert.match(packJson.dependencies.moment, /^\^2\./, ''Wrong version of "moment". It should be ^2.10.2''); }, xhr => { throw new Error(xhr.responseText); })' <add> <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>// solution required <add>``` <add></section> <ide><path>curriculum/challenges/chinese/05-apis-and-microservices/managing-packages-with-npm/use-the-tilde-character-to-always-use-the-latest-patch-version-of-a-dependency.chinese.md <add>--- <add>id: 587d7fb5367417b2b2512c02 <add>title: Use the Tilde-Character to Always Use the Latest Patch Version of a Dependency <add>localeTitle: 使用Tilde-Character始终使用依赖项的最新修补程序版本 <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <code>0</code>在上一次挑战中,我们告诉npm只包含特定版本的软件包。如果您需要确保项目的不同部分保持彼此兼容,那么这是一种冻结依赖关系的有用方法。但在大多数用例中,您不希望错过错误修复,因为它们通常包含重要的安全补丁,并且(希望)不会破坏这样做。 <code>0</code>要允许npm依赖项更新到最新的PATCH版本,可以使用波形符(〜)为依赖项的版本添加前缀。在package.json中,我们关于npm如何升级时刻的当前规则是仅使用特定版本(2.10.2),但我们希望允许最新的2.10.x版本。 <code>0</code>示例 <add><code>"some-package-name": "~1.3.8" allows updates to any 1.3.x version.</code> <code>0</code>指令<code>0</code>使用波形符(〜)为依赖项中的时刻版本添加前缀,并允许npm将其更新为任何新的PATCH版本。 <code>0</code>请注意,不应更改版本号本身。 <add></section> <add> <add>## Instructions <add><section id='instructions'> <add> <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: '“依赖”应该包括“时刻”' <add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert.property(packJson.dependencies, ''moment'', ''"dependencies" does not include "moment"''); }, xhr => { throw new Error(xhr.responseText); })' <add> - text: '“时刻”版本应匹配“~2.10.2”' <add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert.match(packJson.dependencies.moment, /^\~2\.10\.2/, ''Wrong version of "moment". It should be ~2.10.2''); }, xhr => { throw new Error(xhr.responseText); })' <add> <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>// solution required <add>``` <add></section> <ide><path>curriculum/challenges/chinese/05-apis-and-microservices/mongodb-and-mongoose/chain-search-query-helpers-to-narrow-search-results.chinese.md <add>--- <add>id: 587d7fb9367417b2b2512c12 <add>title: Chain Search Query Helpers to Narrow Search Results <add>localeTitle: 链搜索查询帮助缩小搜索结果 <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <code>0</code>如果未将回调作为Model.find()(或其他搜索方法)的最后一个参数传递,则不执行查询。您可以将查询存储在变量中以供以后使用。这种对象使您可以使用链接语法构建查询。当您最终链接方法.exec()时,将执行实际的数据库搜索。将回调传递给最后一个方法。有很多查询助手,这里我们将使用最“着名”的助手。 <code>0</code>找到的人喜欢“burrito”。按名称对它们进行排序,将结果限制为两个文档,并隐藏它们的年龄。链.find(),. sort(),. limit(),。select(),然后是.exec()。将done(错误,数据)回调传递给exec()。 <add></section> <add> <add>## Instructions <add><section id='instructions'> <add> <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: 链接查询助手应该成功 <add> testString: 'getUserInput => $.ajax({url: getUserInput(''url'') + ''/_api/query-tools'', type: ''POST'', contentType:''application/json'', data: JSON.stringify([{name: ''Pablo'', age: 26, favoriteFoods: [''burrito'', ''hot-dog'']}, {name: ''Bob'', age: 23, favoriteFoods: [''pizza'', ''nachos'']}, {name: ''Ashley'', age: 32, favoriteFoods: [''steak'', ''burrito'']}, {name: ''Mario'', age: 51, favoriteFoods: [''burrito'', ''prosciutto'']} ]) }).then(data => { assert.isArray(data, ''the response should be an Array''); assert.equal(data.length, 2, ''the data array length is not what expected''); assert.notProperty(data[0], ''age'', ''The returned first item has too many properties''); assert.equal(data[0].name, ''Ashley'', ''The returned first item name is not what expected''); assert.notProperty(data[1], ''age'', ''The returned second item has too many properties''); assert.equal(data[1].name, ''Mario'', ''The returned second item name is not what expected'');}, xhr => { throw new Error(xhr.responseText); })' <add> <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>// solution required <add>``` <add></section> <ide><path>curriculum/challenges/chinese/05-apis-and-microservices/mongodb-and-mongoose/create-a-model.chinese.md <add>--- <add>id: 587d7fb6367417b2b2512c07 <add>title: Create a Model <add>localeTitle: 创建一个模型 <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <code>0</code>首先,我们需要一个Schema。每个模式都映射到MongoDB集合。它定义了该集合中文档的形状。 <code>0</code>模式是模型的构建块。它们可以嵌套来创建复杂的模型,但在这种情况下,我们会保持简单。 <code>0</code>模型允许您创建对象的实例,称为文档。 <code>0</code>创建一个拥有此原型的人: <add><code>- Person Prototype -</code> <add><code>--------------------</code> <add><code>name : string [required]</code> <add><code>age : number</code> <add><code>favoriteFoods : array of strings (*)</code> <code>0</code>使用mongoose基本模式类型。如果需要,还可以添加<code>0</code>个字段,使用简单的验证器,如required或unique, <code>0</code>并设置默认值。请参阅<a href='http://mongoosejs.com/docs/guide.html'>mongoose文档</a> 。 <add>[C] RUD第一部分 - 创建<code>0</code>注意:Glitch是一个真实的服务器,在真实服务器中,与db的交互发生在处理函数中。当某些事件发生时执行这些功能(例如某人在您的API上命中端点)。我们将在这些练习中遵循相同的方法。 done()函数是一个回调,告诉我们在完成插入,搜索,更新或删除等异步操作后我们可以继续。它遵循Node约定,应该在成功时调用done(null,data),或者在出错时调用(err)。 <code>0</code>警告 - 与远程服务交互时,可能会发生错误! <add><code>/* Example */</code> <add><code>var someFunc = function(done) {</code> <add><code>//... do something (risky) ...</code> <add><code>if(error) return done(error);</code> <add><code>done(null, result);</code> <add><code>};</code> <add></section> <add> <add>## Instructions <add><section id='instructions'> <add> <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: 从mongoose模式创建实例应该会成功 <add> testString: 'getUserInput => $.post(getUserInput(''url'') + ''/_api/mongoose-model'', {name: ''Mike'', age: 28, favoriteFoods: [''pizza'', ''cheese'']}).then(data => { assert.equal(data.name, ''Mike'', ''"model.name" is not what expected''); assert.equal(data.age, ''28'', ''"model.age" is not what expected''); assert.isArray(data.favoriteFoods, ''"model.favoriteFoods" is not an Array''); assert.include(data.favoriteFoods, ''pizza'', ''"model.favoriteFoods" does not include the expected items''); assert.include(data.favoriteFoods, ''cheese'', ''"model.favoriteFoods" does not include the expected items''); }, xhr => { throw new Error(xhr.responseText); })' <add> <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>// solution required <add>``` <add></section> <ide><path>curriculum/challenges/chinese/05-apis-and-microservices/mongodb-and-mongoose/create-and-save-a-record-of-a-model.chinese.md <add>--- <add>id: 587d7fb6367417b2b2512c09 <add>title: Create and Save a Record of a Model <add>localeTitle: 创建并保存模型记录 <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <code>0</code>使用之前构建的Person构造函数创建文档实例。将具有字段名称,年龄和favoriteFoods的对象传递给构造函数。它们的类型必须符合Person Schema中的类型。然后在返回的文档实例上调用方法document.save()。使用Node约定传递回调。这是一种常见模式,以下所有CRUD方法都将这样的回调函数作为最后一个参数。 <add><code>/* Example */</code> <add><code>// ...</code> <add><code>person.save(function(err, data) {</code> <add><code>// ...do your stuff here...</code> <add><code>});</code> <add></section> <add> <add>## Instructions <add><section id='instructions'> <add> <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: 创建和保存数据库项应该会成功 <add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/create-and-save-person'').then(data => { assert.isString(data.name, ''"item.name" should be a String''); assert.isNumber(data.age, ''28'', ''"item.age" should be a Number''); assert.isArray(data.favoriteFoods, ''"item.favoriteFoods" should be an Array''); assert.equal(data.__v, 0, ''The db item should be not previously edited''); }, xhr => { throw new Error(xhr.responseText); })' <add> <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>// solution required <add>``` <add></section> <ide><path>curriculum/challenges/chinese/05-apis-and-microservices/mongodb-and-mongoose/create-many-records-with-model.create.chinese.md <add>--- <add>id: 587d7fb7367417b2b2512c0a <add>title: Create Many Records with model.create() <add>localeTitle: 使用model.create()创建许多记录 <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <code>0</code>有时您需要创建模型的许多实例,例如,在使用初始数据为数据库播种时。 Model.create()接受一个对象数组,如[{name:'John',...},{...},...]作为第一个参数,并将它们全部保存在db中。使用函数参数arrayOfPeople使用Model.create()创建许多人。 <add></section> <add> <add>## Instructions <add><section id='instructions'> <add> <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: 一次创建多个数据库项应该会成功 <add> testString: 'getUserInput => $.ajax({url: getUserInput(''url'') + ''/_api/create-many-people'', type: ''POST'', contentType:''application/json'', data: JSON.stringify([{name: ''John'', age: 24, favoriteFoods: [''pizza'', ''salad'']}, {name: ''Mary'', age: 21, favoriteFoods: [''onions'', ''chicken'']}])}).then(data => { assert.isArray(data, ''the response should be an array''); assert.equal(data.length, 2, ''the response does not contain the expected number of items''); assert.equal(data[0].name, ''John'', ''The first item is not correct''); assert.equal(data[0].__v, 0, ''The first item should be not previously edited''); assert.equal(data[1].name, ''Mary'', ''The second item is not correct''); assert.equal(data[1].__v, 0, ''The second item should be not previously edited''); }, xhr => { throw new Error(xhr.responseText); })' <add> <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>// solution required <add>``` <add></section> <ide><path>curriculum/challenges/chinese/05-apis-and-microservices/mongodb-and-mongoose/delete-many-documents-with-model.remove.chinese.md <add>--- <add>id: 587d7fb8367417b2b2512c11 <add>title: Delete Many Documents with model.remove() <add>localeTitle: 使用model.remove()删除许多文档 <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <add>Model.remove()用于删除与给定条件匹配的所有文档。使用Model.remove()删除名称为“Mary”的所有人员。将其传递给查询文档,其中设置了“name”字段,当然还有回调。 <code>0</code>注意:Model.remove()不返回已删除的文档,而是返回包含操作结果和受影响项目数的JSON对象。不要忘记将它传递给done()回调,因为我们在测试中使用它。 <add></section> <add> <add>## Instructions <add><section id='instructions'> <add> <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: 一次删除多个项目应该会成功 <add> testString: 'getUserInput => $.ajax({url: getUserInput(''url'') + ''/_api/remove-many-people'', type: ''POST'', contentType:''application/json'', data: JSON.stringify([{name: ''Mary'', age: 16, favoriteFoods: [''lollipop'']}, {name: ''Mary'', age: 21, favoriteFoods: [''steak'']}])}).then(data => { assert.isTrue(!!data.ok, ''The mongo stats are not what expected''); assert.equal(data.n, 2, ''The number of items affected is not what expected''); assert.equal(data.count, 0, ''the db items count is not what expected''); }, xhr => { throw new Error(xhr.responseText); })' <add> <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>// solution required <add>``` <add></section> <ide><path>curriculum/challenges/chinese/05-apis-and-microservices/mongodb-and-mongoose/delete-one-document-using-model.findbyidandremove.chinese.md <add>--- <add>id: 587d7fb8367417b2b2512c10 <add>title: Delete One Document Using model.findByIdAndRemove <add>localeTitle: 使用model.findByIdAndRemove删除一个文档 <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <code>0</code>通过她的_id删除一个人。您应该使用findByIdAndRemove()或findOneAndRemove()方法之一。它们与之前的更新方法类似。他们将删除的文件传递给cb。像往常一样,使用函数参数personId作为搜索关键字。 <add></section> <add> <add>## Instructions <add><section id='instructions'> <add> <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: 删除项目应该会成功 <add> testString: 'getUserInput => $.post(getUserInput(''url'') + ''/_api/remove-one-person'', {name:''Jason Bourne'', age: 36, favoriteFoods:[''apples'']}).then(data => { assert.equal(data.name, ''Jason Bourne'', ''item.name is not what expected''); assert.equal(data.age, 36, ''item.age is not what expected''); assert.deepEqual(data.favoriteFoods, [''apples''], ''item.favoriteFoods is not what expected''); assert.equal(data.__v, 0); assert.equal(data.count, 0, ''the db items count is not what expected''); }, xhr => { throw new Error(xhr.responseText); })' <add> <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>// solution required <add>``` <add></section> <ide><path>curriculum/challenges/chinese/05-apis-and-microservices/mongodb-and-mongoose/install-and-set-up-mongoose.chinese.md <add>--- <add>id: 587d7fb6367417b2b2512c06 <add>title: Install and Set Up Mongoose <add>localeTitle: 安装和设置Mongoose <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <code>0</code>将mongodb和mongoose添加到项目的package.json中。然后需要猫鼬。将mLab数据库URI作为MONGO_URI存储在私有.env文件中。使用mongoose.connect连接到数据库( <Your URI> ) <add></section> <add> <add>## Instructions <add><section id='instructions'> <add> <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: '"mongodb"依赖应该在package.json' <add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/file/package.json'').then(data => { var packJson = JSON.parse(data); assert.property(packJson.dependencies, ''mongodb''); }, xhr => { throw new Error(xhr.responseText); })' <add> - text: '"mongoose"依赖应该在package.json' <add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/file/package.json'').then(data => { var packJson = JSON.parse(data); assert.property(packJson.dependencies, ''mongoose''); }, xhr => { throw new Error(xhr.responseText); })' <add> - text: '"mongoose"应该连接到数据库' <add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/is-mongoose-ok'').then(data => {assert.isTrue(data.isMongooseOk, ''mongoose is not connected'')}, xhr => { throw new Error(xhr.responseText); })' <add> <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>// solution required <add>``` <add></section> <ide><path>curriculum/challenges/chinese/05-apis-and-microservices/mongodb-and-mongoose/perform-classic-updates-by-running-find-edit-then-save.chinese.md <add>--- <add>id: 587d7fb8367417b2b2512c0e <add>title: 'Perform Classic Updates by Running Find, Edit, then Save' <add>localeTitle: '通过运行查找,编辑然后保存来执行经典更新' <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <code>0</code>在过去的好时光中,如果您想编辑文档并能够以某种方式使用它,例如在服务器响应中将其发回,则需要执行此操作。 Mongoose有一个专用的更新方法:Model.update()。它与低级mongo驱动程序绑定。它可以批量编辑符合特定条件的许多文档,但它不会发回更新的文档,只会发送“状态”消息。此外,它使模型验证变得困难,因为它只是直接调用mongo驱动程序。 <code>0</code>使用参数personId作为搜索关键字,通过_id(使用上述任何方法)查找人物。将“hamburger”添加到她最喜欢的食物列表中(您可以使用Array.push())。然后 - 在find回调中 - save()更新的Person。 <add>[*]提示:如果你的Schema中你将favoriteFoods声明为一个数组而没有指定类型(即[String]),这可能会很棘手。在那种情况下,favorsFoods默认为Mixed type,你必须使用document.markModified('edited-field')手动将其标记为已编辑。 (http://mongoosejs.com/docs/schematypes.html - #Mixed) <add></section> <add> <add>## Instructions <add><section id='instructions'> <add> <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: 查找 - 编辑 - 更新项目应该成功 <add> testString: 'getUserInput => $.post(getUserInput(''url'') + ''/_api/find-edit-save'', {name:''Poldo'', age: 40, favoriteFoods:[''spaghetti'']}).then(data => { assert.equal(data.name, ''Poldo'', ''item.name is not what expected''); assert.equal(data.age, 40, ''item.age is not what expected''); assert.deepEqual(data.favoriteFoods, [''spaghetti'', ''hamburger''], ''item.favoriteFoods is not what expected''); assert.equal(data.__v, 1, ''The item should be previously edited''); }, xhr => { throw new Error(xhr.responseText); })' <add> <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>// solution required <add>``` <add></section> <ide><path>curriculum/challenges/chinese/05-apis-and-microservices/mongodb-and-mongoose/perform-new-updates-on-a-document-using-model.findoneandupdate.chinese.md <add>--- <add>id: 587d7fb8367417b2b2512c0f <add>title: Perform New Updates on a Document Using model.findOneAndUpdate() <add>localeTitle: 使用model.findOneAndUpdate()对文档执行新更新 <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <code>0</code>最新版本的mongoose具有简化文档更新的方法。一些更高级的功能(即前/后挂钩,验证)与此方法的行为不同,因此Classic方法在许多情况下仍然有用。在按Id搜索时可以使用findByIdAndUpdate()。 <code>0</code>按名称查找人员并将其年龄设置为20.使用函数参数personName作为搜索关键字。 <code>0</code>提示:我们希望您返回更新的文档。为此,您需要将选项文档{new:true}作为findOneAndUpdate()的第三个参数传递。默认情况下,这些方法返回未修改的对象。 <add></section> <add> <add>## Instructions <add><section id='instructions'> <add> <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: findOneAndUpdate项应该成功 <add> testString: 'getUserInput => $.post(getUserInput(''url'') + ''/_api/find-one-update'', {name:''Dorian Gray'', age: 35, favoriteFoods:[''unknown'']}).then(data => { assert.equal(data.name, ''Dorian Gray'', ''item.name is not what expected''); assert.equal(data.age, 20, ''item.age is not what expected''); assert.deepEqual(data.favoriteFoods, [''unknown''], ''item.favoriteFoods is not what expected''); assert.equal(data.__v, 0, ''findOneAndUpdate does not increment version by design !!!''); }, xhr => { throw new Error(xhr.responseText); })' <add> <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>// solution required <add>``` <add></section> <ide><path>curriculum/challenges/chinese/05-apis-and-microservices/mongodb-and-mongoose/use-model.find-to-search-your-database.chinese.md <add>--- <add>id: 587d7fb7367417b2b2512c0b <add>title: Use model.find() to Search Your Database <add>localeTitle: 使用model.find()搜索数据库 <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <code>0</code>使用Model.find() - &gt; [Person]查找具有给定名称的所有人<code>0</code>在最简单的用法中,Model.find()接受查询文档(JSON对象)作为第一个参数,然后接受回调。它返回一个匹配数组。它支持极其广泛的搜索选项。在文档中查看它。使用函数参数personName作为搜索关键字。 <add></section> <add> <add>## Instructions <add><section id='instructions'> <add> <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: 找到与标准对应的所有项目都应该成功 <add> testString: 'getUserInput => $.post(getUserInput(''url'') + ''/_api/find-all-by-name'', {name: ''r@nd0mN4m3'', age: 24, favoriteFoods: [''pizza'']}).then(data => { assert.isArray(data, ''the response should be an Array''); assert.equal(data[0].name, ''r@nd0mN4m3'', ''item.name is not what expected''); assert.equal(data[0].__v, 0, ''The item should be not previously edited''); }, xhr => { throw new Error(xhr.responseText); })' <add> <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>// solution required <add>``` <add></section> <ide><path>curriculum/challenges/chinese/05-apis-and-microservices/mongodb-and-mongoose/use-model.findbyid-to-search-your-database-by-id.chinese.md <add>--- <add>id: 587d7fb7367417b2b2512c0d <add>title: Use model.findById() to Search Your Database By _id <add>localeTitle: 使用model.findById()按_id搜索数据库 <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <code>0</code>保存文档时,mongodb会自动添加字段_id,并将其设置为唯一的字母数字键。按_id搜索是一种非常频繁的操作,因此mongoose为它提供了一种专用方法。使用Model.findById() - &gt; Person找到具有给定_id的(仅!!)人物。使用函数参数personId作为搜索关键字。 <add></section> <add> <add>## Instructions <add><section id='instructions'> <add> <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: 找到Id应该成功的项目 <add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/find-by-id'').then(data => { assert.equal(data.name, ''test'', ''item.name is not what expected''); assert.equal(data.age, 0, ''item.age is not what expected''); assert.deepEqual(data.favoriteFoods, [''none''], ''item.favoriteFoods is not what expected''); assert.equal(data.__v, 0, ''The item should be not previously edited''); }, xhr => { throw new Error(xhr.responseText); })' <add> <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>// solution required <add>``` <add></section> <ide><path>curriculum/challenges/chinese/05-apis-and-microservices/mongodb-and-mongoose/use-model.findone-to-return-a-single-matching-document-from-your-database.chinese.md <add>--- <add>id: 587d7fb7367417b2b2512c0c <add>title: Use model.findOne() to Return a Single Matching Document from Your Database <add>localeTitle: 使用model.findOne()从数据库中返回单个匹配文档 <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <add>Model.findOne()的行为类似于.find(),但它只返回一个文档(不是数组),即使有多个项目也是如此。在按声明为唯一的属性进行搜索时,它尤其有用。使用Model.findOne() - &gt; Person,找到一个在她的收藏夹中有某种食物的人。使用函数参数food作为搜索键。 <add></section> <add> <add>## Instructions <add><section id='instructions'> <add> <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: 找一个项应该成功 <add> testString: 'getUserInput => $.post(getUserInput(''url'') + ''/_api/find-one-by-food'', {name: ''Gary'', age: 46, favoriteFoods: [''chicken salad'']}).then(data => { assert.equal(data.name, ''Gary'', ''item.name is not what expected''); assert.deepEqual(data.favoriteFoods, [''chicken salad''], ''item.favoriteFoods is not what expected''); assert.equal(data.__v, 0, ''The item should be not previously edited''); }, xhr => { throw new Error(xhr.responseText); })' <add> <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>// solution required <add>``` <add></section>
39