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
Mixed
Javascript
remove deprecated interaction modes
0228776e6649c18000876e43e4d44a2317a693a5
<ide><path>docs/general/interactions/modes.md <ide> var chart = new Chart(ctx, { <ide> }); <ide> ``` <ide> <del>## single (deprecated) <del>Finds the first item that intersects the point and returns it. Behaves like `'nearest'` mode with `intersect = true`. <del> <del>## label (deprecated) <del>See `'index'` mode. <del> <ide> ## index <ide> Finds item at the same index. If the `intersect` setting is true, the first intersecting item is used to determine the index in the data. If `intersect` false the nearest item, in the x direction, is used to determine the index. <ide> <ide> var chart = new Chart(ctx, { <ide> }); <ide> ``` <ide> <del>## x-axis (deprecated) <del>Behaves like `'index'` mode with `intersect = false`. <del> <ide> ## dataset <ide> Finds items in the same dataset. If the `intersect` setting is true, the first intersecting item is used to determine the index in the data. If `intersect` false the nearest item is used to determine the index. <ide> <ide><path>src/controllers/controller.bar.js <ide> var valueOrDefault = helpers.valueOrDefault; <ide> <ide> defaults._set('bar', { <ide> hover: { <del> mode: 'label' <add> mode: 'index' <ide> }, <ide> <ide> scales: { <ide><path>src/controllers/controller.bubble.js <ide> var valueOrDefault = helpers.valueOrDefault; <ide> var resolve = helpers.options.resolve; <ide> <ide> defaults._set('bubble', { <del> hover: { <del> mode: 'single' <del> }, <del> <ide> scales: { <ide> xAxes: [{ <ide> type: 'linear', // bubble should probably use a linear scale by default <ide><path>src/controllers/controller.doughnut.js <ide> defaults._set('doughnut', { <ide> // Boolean - Whether we animate scaling the Doughnut from the centre <ide> animateScale: false <ide> }, <del> hover: { <del> mode: 'single' <del> }, <ide> legendCallback: function(chart) { <ide> var list = document.createElement('ul'); <ide> var data = chart.data; <ide><path>src/controllers/controller.line.js <ide> defaults._set('line', { <ide> spanGaps: false, <ide> <ide> hover: { <del> mode: 'label' <add> mode: 'index' <ide> }, <ide> <ide> scales: { <ide><path>src/controllers/controller.scatter.js <ide> var LineController = require('./controller.line'); <ide> var defaults = require('../core/core.defaults'); <ide> <ide> defaults._set('scatter', { <del> hover: { <del> mode: 'single' <del> }, <del> <ide> scales: { <ide> xAxes: [{ <ide> id: 'x-axis-1', // need an ID so datasets can reference the scale <ide><path>src/core/core.controller.js <ide> helpers.extend(Chart.prototype, /** @lends Chart */ { <ide> * @return An object containing the dataset index and element index of the matching element. Also contains the rectangle that was draw <ide> */ <ide> getElementAtEvent: function(e) { <del> return Interaction.modes.single(this, e); <add> return Interaction.modes.nearest(this, e, {intersect: true}); <ide> }, <ide> <ide> getElementsAtEvent: function(e) { <del> return Interaction.modes.label(this, e, {intersect: true}); <add> return Interaction.modes.index(this, e, {intersect: true}); <ide> }, <ide> <ide> getElementsAtXAxis: function(e) { <del> return Interaction.modes['x-axis'](this, e, {intersect: true}); <add> return Interaction.modes.index(this, e, {intersect: false}); <ide> }, <ide> <ide> getElementsAtEventForMode: function(e, mode, options) { <ide><path>src/core/core.interaction.js <ide> function indexMode(chart, e, options) { <ide> module.exports = { <ide> // Helper function for different modes <ide> modes: { <del> single: function(chart, e) { <del> var position = getRelativePosition(e, chart); <del> var elements = []; <del> <del> parseVisibleItems(chart, function(element) { <del> if (element.inRange(position.x, position.y)) { <del> elements.push(element); <del> return elements; <del> } <del> }); <del> <del> return elements.slice(0, 1); <del> }, <del> <del> /** <del> * @function Chart.Interaction.modes.label <del> * @deprecated since version 2.4.0 <del> * @todo remove at version 3 <del> * @private <del> */ <del> label: indexMode, <del> <ide> /** <ide> * Returns items at the same index. If the options.intersect parameter is true, we only return items if we intersect something <ide> * If the options.intersect mode is false, we find the nearest item and return the items at the same index as that item <ide> module.exports = { <ide> return items; <ide> }, <ide> <del> /** <del> * @function Chart.Interaction.modes.x-axis <del> * @deprecated since version 2.4.0. Use index mode and intersect == true <del> * @todo remove at version 3 <del> * @private <del> */ <del> 'x-axis': function(chart, e) { <del> return indexMode(chart, e, {intersect: false}); <del> }, <del> <ide> /** <ide> * Point mode returns all elements that hit test based on the event position <ide> * of the event <ide><path>test/specs/controller.line.tests.js <ide> describe('Chart.controllers.line', function() { <ide> legend: false, <ide> title: false, <ide> hover: { <del> mode: 'single' <add> mode: 'nearest', <add> intersect: true <ide> }, <ide> scales: { <ide> xAxes: [{ <ide><path>test/specs/core.controller.tests.js <ide> describe('Chart', function() { <ide> defaults.global.responsiveAnimationDuration = 0; <ide> defaults.global.hover.onHover = null; <ide> defaults.line.spanGaps = false; <del> defaults.line.hover.mode = 'label'; <add> defaults.line.hover.mode = 'index'; <ide> }); <ide> <ide> it('should override default options', function() { <ide> describe('Chart', function() { <ide> <ide> defaults.global.responsiveAnimationDuration = 0; <ide> defaults.global.hover.onHover = null; <del> defaults.line.hover.mode = 'label'; <add> defaults.line.hover.mode = 'index'; <ide> defaults.line.spanGaps = false; <ide> }); <ide> <ide><path>test/specs/core.tooltip.tests.js <ide> describe('Core.Tooltip', function() { <ide> }, <ide> options: { <ide> tooltips: { <del> mode: 'single' <add> mode: 'nearest', <add> intersect: true <ide> } <ide> } <ide> }); <ide> describe('Core.Tooltip', function() { <ide> }, <ide> options: { <ide> tooltips: { <del> mode: 'label', <add> mode: 'index', <ide> callbacks: { <ide> beforeTitle: function() { <ide> return 'beforeTitle'; <ide> describe('Core.Tooltip', function() { <ide> }, <ide> options: { <ide> tooltips: { <del> mode: 'label', <add> mode: 'index', <ide> itemSort: function(a, b) { <ide> return a.datasetIndex > b.datasetIndex ? -1 : 1; <ide> } <ide> describe('Core.Tooltip', function() { <ide> }, <ide> options: { <ide> tooltips: { <del> mode: 'label', <add> mode: 'index', <ide> reverse: true <ide> } <ide> } <ide> describe('Core.Tooltip', function() { <ide> }, <ide> options: { <ide> tooltips: { <del> mode: 'label' <add> mode: 'index' <ide> } <ide> } <ide> }); <ide> describe('Core.Tooltip', function() { <ide> }, <ide> options: { <ide> tooltips: { <del> mode: 'label', <add> mode: 'index', <ide> filter: function(tooltipItem, data) { <ide> // For testing purposes remove the first dataset that has a tooltipHidden property <ide> return !data.datasets[tooltipItem.datasetIndex].tooltipHidden; <ide> describe('Core.Tooltip', function() { <ide> }, <ide> options: { <ide> tooltips: { <del> mode: 'single' <add> mode: 'nearest', <add> intersect: true <ide> } <ide> } <ide> }); <ide> describe('Core.Tooltip', function() { <ide> }, <ide> options: { <ide> tooltips: { <del> mode: 'single', <add> mode: 'nearest', <add> intersect: true, <ide> callbacks: { <ide> title: function() { <ide> return 'registering callback...'; <ide> describe('Core.Tooltip', function() { <ide> }, <ide> options: { <ide> tooltips: { <del> mode: 'label', <add> mode: 'index', <ide> callbacks: { <ide> beforeTitle: function() { <ide> return 'beforeTitle\nnewline';
11
Text
Text
fix an error in resolution algorithm steps
6f39f105435ffd5e71ece41266ef3c256b29dc88
<ide><path>doc/api/modules.md <ide> require(X) from module at path Y <ide> 3. If X begins with './' or '/' or '../' <ide> a. LOAD_AS_FILE(Y + X) <ide> b. LOAD_AS_DIRECTORY(Y + X) <add> c. THROW "not found" <ide> 4. LOAD_NODE_MODULES(X, dirname(Y)) <ide> 5. LOAD_SELF_REFERENCE(X, dirname(Y)) <ide> 6. THROW "not found"
1
Ruby
Ruby
use gitrepositoryextension for 'path' in tap
68bbe6ee5fc723f154d4a2372997d5bd9682a554
<ide><path>Library/Homebrew/tap.rb <ide> def initialize(user, repo) <ide> @repo = repo <ide> @name = "#{@user}/#{@repo}".downcase <ide> @path = TAP_DIRECTORY/"#{@user}/homebrew-#{@repo}".downcase <add> @path.extend(GitRepositoryExtension) <ide> end <ide> <ide> # clear internal cache <ide> def clear_cache <ide> # The remote path to this {Tap}. <ide> # e.g. `https://github.com/user/homebrew-repo` <ide> def remote <del> @remote ||= if installed? <del> if git? && Utils.git_available? <del> path.cd do <del> Utils.popen_read("git", "config", "--get", "remote.origin.url").chomp <del> end <del> end <del> else <del> raise TapUnavailableError, name <del> end <add> raise TapUnavailableError, name unless installed? <add> @remote ||= path.git_origin <ide> end <ide> <ide> # The default remote path to this {Tap}. <ide> def default_remote <ide> <ide> # True if this {Tap} is a git repository. <ide> def git? <del> (path/".git").exist? <add> path.git? <ide> end <ide> <ide> # git HEAD for this {Tap}. <ide> def git_head <ide> raise TapUnavailableError, name unless installed? <del> return unless git? && Utils.git_available? <del> path.cd { Utils.popen_read("git", "rev-parse", "--verify", "-q", "HEAD").chuzzle } <add> path.git_head <ide> end <ide> <ide> # git HEAD in short format for this {Tap}. <ide> def git_short_head <ide> raise TapUnavailableError, name unless installed? <del> return unless git? && Utils.git_available? <del> path.cd { Utils.popen_read("git", "rev-parse", "--short=4", "--verify", "-q", "HEAD").chuzzle } <add> path.git_short_head <ide> end <ide> <ide> # time since git last commit for this {Tap}. <ide> def git_last_commit <ide> raise TapUnavailableError, name unless installed? <del> return unless git? && Utils.git_available? <del> path.cd { Utils.popen_read("git", "show", "-s", "--format=%cr", "HEAD").chuzzle } <add> path.git_last_commit <ide> end <ide> <ide> # git last commit date for this {Tap}. <ide> def git_last_commit_date <ide> raise TapUnavailableError, name unless installed? <del> return unless git? && Utils.git_available? <del> path.cd { Utils.popen_read("git", "show", "-s", "--format=%cd", "--date=short", "HEAD").chuzzle } <add> path.git_last_commit_date <ide> end <ide> <ide> # The issues URL of this {Tap}.
1
Python
Python
install json.gz files
96dd143a18aec72fff1c0743a4a6146b45403d65
<ide><path>setup.py <ide> def is_new_osx(): <ide> return False <ide> <ide> <del>PACKAGE_DATA = {"": ["*.pyx", "*.pxd", "*.txt", "*.tokens", "*.json"]} <add>PACKAGE_DATA = {"": ["*.pyx", "*.pxd", "*.txt", "*.tokens", "*.json", "*.json.gz"]} <ide> <ide> <ide> PACKAGES = find_packages()
1
Javascript
Javascript
use const in preferences.js
de6982e58e50fbe860a801023c26d9009dc2e96d
<ide><path>web/preferences.js <ide> * See the License for the specific language governing permissions and <ide> * limitations under the License. <ide> */ <add>/* eslint no-var: error, prefer-const: error */ <ide> <ide> let defaultPreferences = null; <ide> function getDefaultPreferences() { <ide> class BasePreferences { <ide> if (!prefs) { <ide> return; <ide> } <del> for (let name in prefs) { <add> for (const name in prefs) { <ide> const defaultValue = this.defaults[name], prefValue = prefs[name]; <ide> // Ignore preferences not present in, or whose types don't match, <ide> // the default values. <ide> class BasePreferences { <ide> */ <ide> async set(name, value) { <ide> await this._initializedPromise; <del> let defaultValue = this.defaults[name]; <add> const defaultValue = this.defaults[name]; <ide> <ide> if (defaultValue === undefined) { <ide> throw new Error(`Set preference: "${name}" is undefined.`); <ide> } else if (value === undefined) { <ide> throw new Error('Set preference: no value is specified.'); <ide> } <del> let valueType = typeof value; <del> let defaultType = typeof defaultValue; <add> const valueType = typeof value; <add> const defaultType = typeof defaultValue; <ide> <ide> if (valueType !== defaultType) { <ide> if (valueType === 'number' && defaultType === 'string') { <ide> class BasePreferences { <ide> */ <ide> async get(name) { <ide> await this._initializedPromise; <del> let defaultValue = this.defaults[name]; <add> const defaultValue = this.defaults[name]; <ide> <ide> if (defaultValue === undefined) { <ide> throw new Error(`Get preference: "${name}" is undefined.`); <ide> } else { <del> let prefValue = this.prefs[name]; <add> const prefValue = this.prefs[name]; <ide> <ide> if (prefValue !== undefined) { <ide> return prefValue;
1
Javascript
Javascript
remove unused conditional stream
3439ccd2bfbe76cbddfd1416afbbec791f920a52
<ide><path>packages/ember-metal/lib/streams/conditional.js <del>import Stream from 'ember-metal/streams/stream'; <del>import { <del> read, <del> subscribe, <del> unsubscribe, <del> isStream <del>} from 'ember-metal/streams/utils'; <del> <del>export default function conditional(test, consequent, alternate) { <del> if (isStream(test)) { <del> return new ConditionalStream(test, consequent, alternate); <del> } else { <del> if (test) { <del> return consequent; <del> } else { <del> return alternate; <del> } <del> } <del>} <del> <del>function ConditionalStream(test, consequent, alternate) { <del> this.init(); <del> <del> this.oldTestResult = undefined; <del> this.test = test; <del> this.consequent = consequent; <del> this.alternate = alternate; <del>} <del> <del>ConditionalStream.prototype = Object.create(Stream.prototype); <del> <del>ConditionalStream.prototype.compute = function() { <del> var oldTestResult = this.oldTestResult; <del> var newTestResult = !!read(this.test); <del> <del> if (newTestResult !== oldTestResult) { <del> switch (oldTestResult) { <del> case true: unsubscribe(this.consequent, this.notify, this); break; <del> case false: unsubscribe(this.alternate, this.notify, this); break; <del> case undefined: subscribe(this.test, this.notify, this); <del> } <del> <del> switch (newTestResult) { <del> case true: subscribe(this.consequent, this.notify, this); break; <del> case false: subscribe(this.alternate, this.notify, this); <del> } <del> <del> this.oldTestResult = newTestResult; <del> } <del> <del> return newTestResult ? read(this.consequent) : read(this.alternate); <del>};
1
Text
Text
add v3.8.0-beta.3 to changelog
0a2f4b4d8669d1522bc683f835b37744b7ced796
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <add>### v3.8.0-beta.3 (January 28, 2019) <add> <add>- [#17498](https://github.com/emberjs/ember.js/pull/17498) [BUGFIX] Don't remove dep keys in `didUnwatch` <add>- [#17499](https://github.com/emberjs/ember.js/pull/17499) [BUGFIX] Update to glimmer-vm 0.37.1. <add> <ide> ### v3.8.0-beta.2 (January 14, 2019) <ide> <ide> - [#17467](https://github.com/emberjs/ember.js/pull/17467) [BUGFIX] Fix substate interactions with aborts
1
PHP
PHP
remove factory "types"
67b814b8350dbe0ca1682ca185f2ecef7dd67656
<ide><path>src/Illuminate/Database/Eloquent/Factory.php <ide> public static function construct(Faker $faker, $pathToFactories = null) <ide> return (new static($faker))->load($pathToFactories); <ide> } <ide> <del> /** <del> * Define a class with a given short-name. <del> * <del> * @param string $class <del> * @param string $name <del> * @param callable $attributes <del> * @return $this <del> */ <del> public function defineAs($class, $name, callable $attributes) <del> { <del> return $this->define($class, $attributes, $name); <del> } <del> <ide> /** <ide> * Define a class with a given set of attributes. <ide> * <ide> * @param string $class <ide> * @param callable $attributes <del> * @param string $name <ide> * @return $this <ide> */ <del> public function define($class, callable $attributes, $name = 'default') <add> public function define($class, callable $attributes) <ide> { <del> $this->definitions[$class][$name] = $attributes; <add> $this->definitions[$class] = $attributes; <ide> <ide> return $this; <ide> } <ide> public function create($class, array $attributes = []) <ide> return $this->of($class)->create($attributes); <ide> } <ide> <del> /** <del> * Create an instance of the given model and type and persist it to the database. <del> * <del> * @param string $class <del> * @param string $name <del> * @param array $attributes <del> * @return mixed <del> */ <del> public function createAs($class, $name, array $attributes = []) <del> { <del> return $this->of($class, $name)->create($attributes); <del> } <del> <ide> /** <ide> * Create an instance of the given model. <ide> * <ide> public function make($class, array $attributes = []) <ide> return $this->of($class)->make($attributes); <ide> } <ide> <del> /** <del> * Create an instance of the given model and type. <del> * <del> * @param string $class <del> * @param string $name <del> * @param array $attributes <del> * @return mixed <del> */ <del> public function makeAs($class, $name, array $attributes = []) <del> { <del> return $this->of($class, $name)->make($attributes); <del> } <del> <del> /** <del> * Get the raw attribute array for a given named model. <del> * <del> * @param string $class <del> * @param string $name <del> * @param array $attributes <del> * @return array <del> */ <del> public function rawOf($class, $name, array $attributes = []) <del> { <del> return $this->raw($class, $attributes, $name); <del> } <del> <ide> /** <ide> * Get the raw attribute array for a given model. <ide> * <ide> * @param string $class <ide> * @param array $attributes <del> * @param string $name <ide> * @return array <ide> */ <del> public function raw($class, array $attributes = [], $name = 'default') <add> public function raw($class, array $attributes = []) <ide> { <ide> return array_merge( <del> call_user_func($this->definitions[$class][$name], $this->faker), $attributes <add> call_user_func($this->definitions[$class], $this->faker), $attributes <ide> ); <ide> } <ide> <ide> /** <ide> * Create a builder for the given model. <ide> * <ide> * @param string $class <del> * @param string $name <ide> * @return \Illuminate\Database\Eloquent\FactoryBuilder <ide> */ <del> public function of($class, $name = 'default') <add> public function of($class) <ide> { <ide> return new FactoryBuilder( <del> $class, $name, $this->definitions, $this->states, <add> $class, $this->definitions, $this->states, <ide> $this->afterMaking, $this->afterCreating, $this->faker <ide> ); <ide> } <ide><path>src/Illuminate/Database/Eloquent/FactoryBuilder.php <ide> class FactoryBuilder <ide> */ <ide> protected $class; <ide> <del> /** <del> * The name of the model being built. <del> * <del> * @var string <del> */ <del> protected $name = 'default'; <del> <ide> /** <ide> * The database connection on which the model instance should be persisted. <ide> * <ide> class FactoryBuilder <ide> * Create an new builder instance. <ide> * <ide> * @param string $class <del> * @param string $name <ide> * @param array $definitions <ide> * @param array $states <ide> * @param array $afterMaking <ide> * @param array $afterCreating <ide> * @param \Faker\Generator $faker <ide> * @return void <ide> */ <del> public function __construct($class, $name, array $definitions, array $states, <add> public function __construct($class, array $definitions, array $states, <ide> array $afterMaking, array $afterCreating, Faker $faker) <ide> { <del> $this->name = $name; <ide> $this->class = $class; <ide> $this->faker = $faker; <ide> $this->states = $states; <ide> public function raw(array $attributes = []) <ide> */ <ide> protected function getRawAttributes(array $attributes = []) <ide> { <del> if (! isset($this->definitions[$this->class][$this->name])) { <del> throw new InvalidArgumentException("Unable to locate factory with name [{$this->name}] [{$this->class}]."); <add> if (! isset($this->definitions[$this->class])) { <add> throw new InvalidArgumentException("Unable to locate factory for [{$this->class}]."); <ide> } <ide> <ide> $definition = call_user_func( <del> $this->definitions[$this->class][$this->name], <add> $this->definitions[$this->class], <ide> $this->faker, $attributes <ide> ); <ide> <ide> public function callAfterCreating($models) <ide> */ <ide> protected function callAfter(array $afterCallbacks, $models) <ide> { <del> $states = array_merge([$this->name], $this->activeStates); <add> $states = array_merge(['default'], $this->activeStates); <ide> <ide> $models->each(function ($model) use ($states, $afterCallbacks) { <ide> foreach ($states as $state) { <ide><path>src/Illuminate/Foundation/helpers.php <ide> function event(...$args) <ide> <ide> if (! function_exists('factory')) { <ide> /** <del> * Create a model factory builder for a given class, name, and amount. <add> * Create a model factory builder for a given class and amount. <ide> * <del> * @param dynamic class|class,name|class,amount|class,name,amount <add> * @param string $class <add> * @param int $amount <ide> * @return \Illuminate\Database\Eloquent\FactoryBuilder <ide> */ <del> function factory() <add> function factory($class, $amount = null) <ide> { <ide> $factory = app(EloquentFactory::class); <ide> <del> $arguments = func_get_args(); <del> <del> if (isset($arguments[1]) && is_string($arguments[1])) { <del> return $factory->of($arguments[0], $arguments[1])->times($arguments[2] ?? null); <del> } elseif (isset($arguments[1])) { <del> return $factory->of($arguments[0])->times($arguments[1]); <add> if (isset($amount) && is_int($amount)) { <add> return $factory->of($class)->times($amount); <ide> } <ide> <del> return $factory->of($arguments[0]); <add> return $factory->of($class); <ide> } <ide> } <ide>
3
Text
Text
remove note on oss/non-oss issue
9634bad79d3c17ee1b48a6c1e5a66d5ee8c5441a
<ide><path>examples/with-docker/README.md <ide> Deploy it to the cloud with [now](https://zeit.co/now) ([download](https://zeit. <ide> now --docker -e API_URL="https://example.com" <ide> ``` <ide> <del>>*Note: Multi-stage only works in OSS plan. [\[#962\]](https://github.com/zeit/now-cli/issues/962#issuecomment-383860104)* <del> <ide> ## The idea behind the example <ide> <ide> This example show how to set custom environment variables for your __docker application__ at runtime. <ide> <ide> The `dockerfile` is the simplest way to run Next.js app in docker, and the size of output image is `173MB`. However, for an even smaller build, you can do multi-stage builds with `dockerfile.multistage`. The size of output image is `85MB`. <ide> <del>You can check the [Example Dockerfile for your own Node.js project](https://github.com/mhart/alpine-node/tree/43ca9e4bc97af3b1f124d27a2cee002d5f7d1b32#example-dockerfile-for-your-own-nodejs-project) section in [mhart/alpine-node](https://github.com/mhart/alpine-node) for more details. <ide>\ No newline at end of file <add>You can check the [Example Dockerfile for your own Node.js project](https://github.com/mhart/alpine-node/tree/43ca9e4bc97af3b1f124d27a2cee002d5f7d1b32#example-dockerfile-for-your-own-nodejs-project) section in [mhart/alpine-node](https://github.com/mhart/alpine-node) for more details.
1
Mixed
Text
move plugins out of experimental
c410222e42fb9195909390337bc129c6481e2453
<ide><path>cli/command/plugin/cmd.go <ide> func NewPluginCommand(dockerCli *command.DockerCli) *cobra.Command { <ide> cmd.SetOutput(dockerCli.Err()) <ide> cmd.HelpFunc()(cmd, args) <ide> }, <del> Tags: map[string]string{"experimental": ""}, <ide> } <ide> <ide> cmd.AddCommand( <ide><path>client/interface.go <ide> type CommonAPIClient interface { <ide> ImageAPIClient <ide> NodeAPIClient <ide> NetworkAPIClient <add> PluginAPIClient <ide> ServiceAPIClient <ide> SwarmAPIClient <ide> SecretAPIClient <ide> type NodeAPIClient interface { <ide> NodeUpdate(ctx context.Context, nodeID string, version swarm.Version, node swarm.NodeSpec) error <ide> } <ide> <add>// PluginAPIClient defines API client methods for the plugins <add>type PluginAPIClient interface { <add> PluginList(ctx context.Context) (types.PluginsListResponse, error) <add> PluginRemove(ctx context.Context, name string, options types.PluginRemoveOptions) error <add> PluginEnable(ctx context.Context, name string) error <add> PluginDisable(ctx context.Context, name string) error <add> PluginInstall(ctx context.Context, name string, options types.PluginInstallOptions) error <add> PluginPush(ctx context.Context, name string, registryAuth string) error <add> PluginSet(ctx context.Context, name string, args []string) error <add> PluginInspectWithRaw(ctx context.Context, name string) (*types.Plugin, []byte, error) <add> PluginCreate(ctx context.Context, createContext io.Reader, options types.PluginCreateOptions) error <add>} <add> <ide> // ServiceAPIClient defines API client methods for the services <ide> type ServiceAPIClient interface { <ide> ServiceCreate(ctx context.Context, service swarm.ServiceSpec, options types.ServiceCreateOptions) (types.ServiceCreateResponse, error) <ide><path>client/interface_experimental.go <ide> package client <ide> <ide> import ( <del> "io" <del> <ide> "github.com/docker/docker/api/types" <ide> "golang.org/x/net/context" <ide> ) <ide> <ide> type apiClientExperimental interface { <ide> CheckpointAPIClient <del> PluginAPIClient <ide> } <ide> <ide> // CheckpointAPIClient defines API client methods for the checkpoints <ide> type CheckpointAPIClient interface { <ide> CheckpointDelete(ctx context.Context, container string, options types.CheckpointDeleteOptions) error <ide> CheckpointList(ctx context.Context, container string, options types.CheckpointListOptions) ([]types.Checkpoint, error) <ide> } <del> <del>// PluginAPIClient defines API client methods for the plugins <del>type PluginAPIClient interface { <del> PluginList(ctx context.Context) (types.PluginsListResponse, error) <del> PluginRemove(ctx context.Context, name string, options types.PluginRemoveOptions) error <del> PluginEnable(ctx context.Context, name string) error <del> PluginDisable(ctx context.Context, name string) error <del> PluginInstall(ctx context.Context, name string, options types.PluginInstallOptions) error <del> PluginPush(ctx context.Context, name string, registryAuth string) error <del> PluginSet(ctx context.Context, name string, args []string) error <del> PluginInspectWithRaw(ctx context.Context, name string) (*types.Plugin, []byte, error) <del> PluginCreate(ctx context.Context, createContext io.Reader, options types.PluginCreateOptions) error <del>} <ide><path>cmd/dockerd/daemon.go <ide> import ( <ide> "github.com/docker/docker/api/server/router/container" <ide> "github.com/docker/docker/api/server/router/image" <ide> "github.com/docker/docker/api/server/router/network" <add> pluginrouter "github.com/docker/docker/api/server/router/plugin" <ide> swarmrouter "github.com/docker/docker/api/server/router/swarm" <ide> systemrouter "github.com/docker/docker/api/server/router/system" <ide> "github.com/docker/docker/api/server/router/volume" <ide> import ( <ide> "github.com/docker/docker/pkg/plugingetter" <ide> "github.com/docker/docker/pkg/signal" <ide> "github.com/docker/docker/pkg/system" <add> "github.com/docker/docker/plugin" <ide> "github.com/docker/docker/registry" <ide> "github.com/docker/docker/runconfig" <ide> "github.com/docker/docker/utils" <ide> func initRouter(s *apiserver.Server, d *daemon.Daemon, c *cluster.Cluster) { <ide> volume.NewRouter(d), <ide> build.NewRouter(dockerfile.NewBuildManager(d)), <ide> swarmrouter.NewRouter(d, c), <add> pluginrouter.NewRouter(plugin.GetManager()), <ide> }...) <ide> <ide> if d.NetworkControllerEnabled() { <ide><path>cmd/dockerd/routes_experimental.go <ide> import ( <ide> "github.com/docker/docker/api/server/httputils" <ide> "github.com/docker/docker/api/server/router" <ide> checkpointrouter "github.com/docker/docker/api/server/router/checkpoint" <del> pluginrouter "github.com/docker/docker/api/server/router/plugin" <ide> "github.com/docker/docker/daemon" <del> "github.com/docker/docker/plugin" <ide> ) <ide> <ide> func addExperimentalRouters(routers []router.Router, d *daemon.Daemon, decoder httputils.ContainerDecoder) []router.Router { <ide> if !d.HasExperimental() { <ide> return []router.Router{} <ide> } <del> return append(routers, checkpointrouter.NewRouter(d, decoder), pluginrouter.NewRouter(plugin.GetManager())) <add> return append(routers, checkpointrouter.NewRouter(d, decoder)) <ide> } <ide><path>daemon/daemon.go <ide> import ( <ide> "github.com/docker/docker/daemon/events" <ide> "github.com/docker/docker/daemon/exec" <ide> "github.com/docker/docker/dockerversion" <add> "github.com/docker/docker/plugin" <ide> "github.com/docker/libnetwork/cluster" <ide> // register graph drivers <ide> _ "github.com/docker/docker/daemon/graphdriver/register" <ide> func (daemon *Daemon) GetCluster() Cluster { <ide> func (daemon *Daemon) SetCluster(cluster Cluster) { <ide> daemon.cluster = cluster <ide> } <add> <add>func (daemon *Daemon) pluginInit(cfg *Config, remote libcontainerd.Remote) error { <add> return plugin.Init(cfg.Root, daemon.PluginStore, remote, daemon.RegistryService, cfg.LiveRestoreEnabled, daemon.LogPluginEvent) <add>} <add> <add>func (daemon *Daemon) pluginShutdown() { <add> manager := plugin.GetManager() <add> // Check for a valid manager object. In error conditions, daemon init can fail <add> // and shutdown called, before plugin manager is initialized. <add> if manager != nil { <add> manager.Shutdown() <add> } <add>} <ide><path>daemon/daemon_experimental.go <ide> package daemon <ide> <del>import ( <del> "github.com/docker/docker/api/types/container" <del> "github.com/docker/docker/libcontainerd" <del> "github.com/docker/docker/plugin" <del>) <add>import "github.com/docker/docker/api/types/container" <ide> <ide> func (daemon *Daemon) verifyExperimentalContainerSettings(hostConfig *container.HostConfig, config *container.Config) ([]string, error) { <ide> return nil, nil <ide> } <del> <del>func (daemon *Daemon) pluginInit(cfg *Config, remote libcontainerd.Remote) error { <del> if !daemon.HasExperimental() { <del> return nil <del> } <del> return plugin.Init(cfg.Root, daemon.PluginStore, remote, daemon.RegistryService, cfg.LiveRestoreEnabled, daemon.LogPluginEvent) <del>} <del> <del>func (daemon *Daemon) pluginShutdown() { <del> if !daemon.HasExperimental() { <del> return <del> } <del> manager := plugin.GetManager() <del> // Check for a valid manager object. In error conditions, daemon init can fail <del> // and shutdown called, before plugin manager is initialized. <del> if manager != nil { <del> manager.Shutdown() <del> } <del>} <ide><path>docs/extend/config.md <ide> aliases: [ <ide> title: "Plugin config" <ide> description: "How develop and use a plugin with the managed plugin system" <ide> keywords: "API, Usage, plugins, documentation, developer" <del>advisory: "experimental" <ide> --- <ide> <ide> <!-- This file is maintained within the docker/docker Github <ide> advisory: "experimental" <ide> <ide> # Plugin Config Version 0 of Plugin V2 <ide> <del>This document outlines the format of the V0 plugin config. The plugin <del>config described herein was introduced in the Docker daemon (experimental version) in the [v1.12.0 <add>This document outlines the format of the V0 plugin configuration. The plugin <add>config described herein was introduced in the Docker daemon in the [v1.12.0 <ide> release](https://github.com/docker/docker/commit/f37117045c5398fd3dca8016ea8ca0cb47e7312b). <ide> <ide> Plugin configs describe the various constituents of a docker plugin. Plugin <ide> Config provides the base accessible fields for working with V0 plugin format <ide> <ide> ``` <ide> { <del> "configVersion": "v0", <ide> "description": "A test plugin for Docker", <ide> "documentation": "https://docs.docker.com/engine/extend/plugins/", <ide> "entrypoint": ["plugin-no-remove", "/data"], <ide><path>docs/extend/index.md <ide> --- <del>advisory: experimental <ide> aliases: <ide> - /engine/extend/ <ide> description: Develop and use a plugin with the managed plugin system <ide> title: Managed plugin system <ide> <ide> # Docker Engine managed plugin system <ide> <del>This document describes the plugin system available today in the **experimental <del>build** of Docker 1.12: <del> <ide> * [Installing and using a plugin](index.md#installing-and-using-a-plugin) <ide> * [Developing a plugin](index.md#developing-a-plugin) <ide> <ide><path>docs/extend/legacy_plugins.md <ide> keywords: "Examples, Usage, plugins, docker, documentation, user guide" <ide> # Use Docker Engine plugins <ide> <ide> This document describes the Docker Engine plugins generally available in Docker <del>Engine. To view information on plugins managed by Docker Engine currently in <del>experimental status, refer to [Docker Engine plugin system](index.md). <add>Engine. To view information on plugins managed by Docker, <add>refer to [Docker Engine plugin system](index.md). <ide> <ide> You can extend the capabilities of the Docker Engine by loading third-party <ide> plugins. This page explains the types of plugins and provides links to several <ide><path>docs/extend/plugin_api.md <ide> Docker plugins are out-of-process extensions which add capabilities to the <ide> Docker Engine. <ide> <ide> This document describes the Docker Engine plugin API. To view information on <del>plugins managed by Docker Engine currently in experimental status, refer to <del>[Docker Engine plugin system](index.md). <add>plugins managed by Docker Engine, refer to [Docker Engine plugin system](index.md). <ide> <ide> This page is intended for people who want to develop their own Docker plugin. <ide> If you just want to learn about or use Docker plugins, look <ide><path>docs/extend/plugins_authorization.md <ide> aliases: ["/engine/extend/authorization/"] <ide> # Create an authorization plugin <ide> <ide> This document describes the Docker Engine plugins generally available in Docker <del>Engine. To view information on plugins managed by Docker Engine currently in <del>experimental status, refer to [Docker Engine plugin system](index.md). <add>Engine. To view information on plugins managed by Docker Engine, <add>refer to [Docker Engine plugin system](index.md). <ide> <ide> Docker's out-of-the-box authorization model is all or nothing. Any user with <ide> permission to access the Docker daemon can run any Docker client command. The <ide><path>docs/reference/api/docker_remote_api.md <ide> This section lists each version from latest to oldest. Each listing includes a <ide> * `POST /services/create` and `POST /services/(id or name)/update` now accept the `TTY` parameter, which allocate a pseudo-TTY in container. <ide> * `POST /services/create` and `POST /services/(id or name)/update` now accept the `DNSConfig` parameter, which specifies DNS related configurations in resolver configuration file (resolv.conf) through `Nameservers`, `Search`, and `Options`. <ide> * `GET /networks/(id or name)` now includes IP and name of all peers nodes for swarm mode overlay networks. <add>* `GET /plugins` list plugins. <add>* `POST /plugins/pull?name=<plugin name>` pulls a plugin. <add>* `GET /plugins/(plugin name)` inspect a plugin. <add>* `POST /plugins/(plugin name)/set` configure a plugin. <add>* `POST /plugins/(plugin name)/enable` enable a plugin. <add>* `POST /plugins/(plugin name)/disable` disable a plugin. <add>* `POST /plugins/(plugin name)/push` push a pluging. <add>* `POST /plugins/create?name=(plugin name)` create a plugin. <add>* `DELETE /plugins/(plugin name)` delete a plugin. <add> <ide> <ide> ### v1.24 API changes <ide> <ide><path>docs/reference/api/docker_remote_api_v1.25.md <ide> Content-Type: application/json <ide> <ide> ### Configure a plugin <ide> <del>POST /plugins/(plugin name)/set` <add>`POST /plugins/(plugin name)/set` <ide> <ide> **Example request**: <ide> <ide> Content-Type: text/plain; charset=utf-8 <ide> - **204** - no error <ide> - **500** - server error <ide> <del><!-- TODO Document "docker plugin push" endpoint once we have "plugin build" <del> <ide> ### Push a plugin <ide> <del>`POST /v1.25/plugins/tiborvass/(plugin name)/push HTTP/1.1` <add>`POST /v1.25/plugins/(plugin name)/push` <ide> <ide> Pushes a plugin to the registry. <ide> <ide> an image](#create-an-image) section for more details. <ide> - **200** - no error <ide> - **404** - plugin not installed <ide> <del>--> <ide> <ide> ## 3.7 Nodes <ide> <ide><path>docs/reference/commandline/plugin_create.md <ide> --- <del>title: "plugin create (experimental)" <add>title: "plugin create" <ide> description: "the plugin create command description and usage" <ide> keywords: "plugin, create" <del>advisory: "experimental" <ide> --- <ide> <ide> <!-- This file is maintained within the docker/docker Github <ide> advisory: "experimental" <ide> will be rejected. <ide> --> <ide> <add># plugin create <add> <ide> ```markdown <ide> Usage: docker plugin create [OPTIONS] reponame[:tag] PATH-TO-ROOTFS <ide> <del>create a plugin from the given PATH-TO-ROOTFS, which contains the plugin's root filesystem and the config file, config.json <add>Create a plugin from a rootfs and configuration <ide> <ide> Options: <ide> --compress Compress the context using gzip <ide><path>docs/reference/commandline/plugin_disable.md <ide> title: "plugin disable" <ide> description: "the plugin disable command description and usage" <ide> keywords: "plugin, disable" <del>advisory: "experimental" <ide> --- <ide> <ide> <!-- This file is maintained within the docker/docker Github <ide> advisory: "experimental" <ide> will be rejected. <ide> --> <ide> <del># plugin disable (experimental) <add># plugin disable <ide> <ide> ```markdown <ide> Usage: docker plugin disable PLUGIN <ide><path>docs/reference/commandline/plugin_enable.md <ide> title: "plugin enable" <ide> description: "the plugin enable command description and usage" <ide> keywords: "plugin, enable" <del>advisory: "experimental" <ide> --- <ide> <ide> <!-- This file is maintained within the docker/docker Github <ide> advisory: "experimental" <ide> will be rejected. <ide> --> <ide> <del># plugin enable (experimental) <add># plugin enable <ide> <ide> ```markdown <ide> Usage: docker plugin enable PLUGIN <ide><path>docs/reference/commandline/plugin_inspect.md <ide> title: "plugin inspect" <ide> description: "The plugin inspect command description and usage" <ide> keywords: "plugin, inspect" <del>advisory: "experimental" <ide> --- <ide> <ide> <!-- This file is maintained within the docker/docker Github <ide> advisory: "experimental" <ide> will be rejected. <ide> --> <ide> <del># plugin inspect (experimental) <add># plugin inspect <ide> <ide> ```markdown <ide> Usage: docker plugin inspect [OPTIONS] PLUGIN [PLUGIN...] <ide><path>docs/reference/commandline/plugin_install.md <ide> title: "plugin install" <ide> description: "the plugin install command description and usage" <ide> keywords: "plugin, install" <del>advisory: "experimental" <ide> --- <ide> <ide> <!-- This file is maintained within the docker/docker Github <ide> advisory: "experimental" <ide> will be rejected. <ide> --> <ide> <del># plugin install (experimental) <add># plugin install <ide> <ide> ```markdown <ide> Usage: docker plugin install [OPTIONS] PLUGIN [KEY=VALUE...] <ide><path>docs/reference/commandline/plugin_ls.md <ide> title: "plugin ls" <ide> description: "The plugin ls command description and usage" <ide> keywords: "plugin, list" <del>advisory: "experimental" <ide> --- <ide> <ide> <!-- This file is maintained within the docker/docker Github <ide> advisory: "experimental" <ide> will be rejected. <ide> --> <ide> <del># plugin ls (experimental) <add># plugin ls <ide> <ide> ```markdown <ide> Usage: docker plugin ls [OPTIONS] <ide><path>docs/reference/commandline/plugin_rm.md <ide> title: "plugin rm" <ide> description: "the plugin rm command description and usage" <ide> keywords: "plugin, rm" <del>advisory: "experimental" <ide> --- <ide> <ide> <!-- This file is maintained within the docker/docker Github <ide> advisory: "experimental" <ide> will be rejected. <ide> --> <ide> <del># plugin rm (experimental) <add># plugin rm <ide> <ide> ```markdown <ide> Usage: docker plugin rm [OPTIONS] PLUGIN [PLUGIN...] <ide><path>docs/reference/commandline/plugin_set.md <ide> title: "plugin set" <ide> description: "the plugin set command description and usage" <ide> keywords: "plugin, set" <del>advisory: "experimental" <ide> --- <ide> <ide> <!-- This file is maintained within the docker/docker Github <ide> advisory: "experimental" <ide> will be rejected. <ide> --> <ide> <del># plugin set (experimental) <add># plugin set <ide> <ide> ```markdown <ide> Usage: docker plugin set PLUGIN KEY=VALUE [KEY=VALUE...] <ide><path>integration-cli/docker_cli_authz_plugin_v2_test.go <ide> type DockerAuthzV2Suite struct { <ide> } <ide> <ide> func (s *DockerAuthzV2Suite) SetUpTest(c *check.C) { <del> testRequires(c, DaemonIsLinux, ExperimentalDaemon, Network) <add> testRequires(c, DaemonIsLinux, Network) <ide> s.d = NewDaemon(c) <ide> c.Assert(s.d.Start(), check.IsNil) <ide> } <add><path>integration-cli/docker_cli_daemon_plugins_test.go <del><path>integration-cli/docker_cli_daemon_experimental_test.go <ide> var pluginName = "tiborvass/no-remove" <ide> <ide> // TestDaemonRestartWithPluginEnabled tests state restore for an enabled plugin <ide> func (s *DockerDaemonSuite) TestDaemonRestartWithPluginEnabled(c *check.C) { <del> testRequires(c, Network, ExperimentalDaemon) <add> testRequires(c, Network) <ide> <ide> if err := s.d.Start(); err != nil { <ide> c.Fatalf("Could not start daemon: %v", err) <ide> func (s *DockerDaemonSuite) TestDaemonRestartWithPluginEnabled(c *check.C) { <ide> <ide> // TestDaemonRestartWithPluginDisabled tests state restore for a disabled plugin <ide> func (s *DockerDaemonSuite) TestDaemonRestartWithPluginDisabled(c *check.C) { <del> testRequires(c, Network, ExperimentalDaemon) <add> testRequires(c, Network) <ide> <ide> if err := s.d.Start(); err != nil { <ide> c.Fatalf("Could not start daemon: %v", err) <ide> func (s *DockerDaemonSuite) TestDaemonRestartWithPluginDisabled(c *check.C) { <ide> // TestDaemonKillLiveRestoreWithPlugins SIGKILLs daemon started with --live-restore. <ide> // Plugins should continue to run. <ide> func (s *DockerDaemonSuite) TestDaemonKillLiveRestoreWithPlugins(c *check.C) { <del> testRequires(c, Network, ExperimentalDaemon) <add> testRequires(c, Network) <ide> <ide> if err := s.d.Start("--live-restore"); err != nil { <ide> c.Fatalf("Could not start daemon: %v", err) <ide> func (s *DockerDaemonSuite) TestDaemonKillLiveRestoreWithPlugins(c *check.C) { <ide> // TestDaemonShutdownLiveRestoreWithPlugins SIGTERMs daemon started with --live-restore. <ide> // Plugins should continue to run. <ide> func (s *DockerDaemonSuite) TestDaemonShutdownLiveRestoreWithPlugins(c *check.C) { <del> testRequires(c, Network, ExperimentalDaemon) <add> testRequires(c, Network) <ide> <ide> if err := s.d.Start("--live-restore"); err != nil { <ide> c.Fatalf("Could not start daemon: %v", err) <ide> func (s *DockerDaemonSuite) TestDaemonShutdownLiveRestoreWithPlugins(c *check.C) <ide> <ide> // TestDaemonShutdownWithPlugins shuts down running plugins. <ide> func (s *DockerDaemonSuite) TestDaemonShutdownWithPlugins(c *check.C) { <del> testRequires(c, Network, ExperimentalDaemon) <add> testRequires(c, Network) <ide> <ide> if err := s.d.Start(); err != nil { <ide> c.Fatalf("Could not start daemon: %v", err) <ide> func (s *DockerDaemonSuite) TestDaemonShutdownWithPlugins(c *check.C) { <ide> <ide> // TestVolumePlugin tests volume creation using a plugin. <ide> func (s *DockerDaemonSuite) TestVolumePlugin(c *check.C) { <del> testRequires(c, Network, ExperimentalDaemon) <add> testRequires(c, Network) <ide> <ide> volName := "plugin-volume" <ide> volRoot := "/data" <ide><path>integration-cli/docker_cli_events_test.go <ide> func (s *DockerSuite) TestEventsImageLoad(c *check.C) { <ide> } <ide> <ide> func (s *DockerSuite) TestEventsPluginOps(c *check.C) { <del> testRequires(c, DaemonIsLinux, ExperimentalDaemon) <add> testRequires(c, DaemonIsLinux) <ide> <ide> pluginName := "tiborvass/no-remove:latest" <ide> since := daemonUnixTime(c) <ide><path>integration-cli/docker_cli_network_unix_test.go <ide> func (s *DockerNetworkSuite) TestDockerNetworkDriverOptions(c *check.C) { <ide> } <ide> <ide> func (s *DockerNetworkSuite) TestDockerPluginV2NetworkDriver(c *check.C) { <del> testRequires(c, DaemonIsLinux, ExperimentalDaemon, Network) <add> testRequires(c, DaemonIsLinux, Network) <ide> <ide> var ( <ide> npName = "mavenugo/test-docker-netplugin" <ide><path>integration-cli/docker_cli_plugins_test.go <ide> var ( <ide> ) <ide> <ide> func (s *DockerSuite) TestPluginBasicOps(c *check.C) { <del> testRequires(c, DaemonIsLinux, ExperimentalDaemon, Network) <add> testRequires(c, DaemonIsLinux, Network) <ide> _, _, err := dockerCmdWithError("plugin", "install", "--grant-all-permissions", pNameWithTag) <ide> c.Assert(err, checker.IsNil) <ide> <ide> func (s *DockerSuite) TestPluginBasicOps(c *check.C) { <ide> } <ide> <ide> func (s *DockerSuite) TestPluginForceRemove(c *check.C) { <del> testRequires(c, DaemonIsLinux, ExperimentalDaemon, Network) <add> testRequires(c, DaemonIsLinux, Network) <ide> out, _, err := dockerCmdWithError("plugin", "install", "--grant-all-permissions", pNameWithTag) <ide> c.Assert(err, checker.IsNil) <ide> <ide> func (s *DockerSuite) TestPluginForceRemove(c *check.C) { <ide> } <ide> <ide> func (s *DockerSuite) TestPluginActive(c *check.C) { <del> testRequires(c, DaemonIsLinux, ExperimentalDaemon, Network) <add> testRequires(c, DaemonIsLinux, Network) <ide> out, _, err := dockerCmdWithError("plugin", "install", "--grant-all-permissions", pNameWithTag) <ide> c.Assert(err, checker.IsNil) <ide> <ide> func (s *DockerSuite) TestPluginActive(c *check.C) { <ide> } <ide> <ide> func (s *DockerSuite) TestPluginInstallDisable(c *check.C) { <del> testRequires(c, DaemonIsLinux, ExperimentalDaemon, Network) <add> testRequires(c, DaemonIsLinux, Network) <ide> out, _, err := dockerCmdWithError("plugin", "install", "--grant-all-permissions", "--disable", pName) <ide> c.Assert(err, checker.IsNil) <ide> c.Assert(strings.TrimSpace(out), checker.Contains, pName) <ide> func (s *DockerSuite) TestPluginInstallDisable(c *check.C) { <ide> } <ide> <ide> func (s *DockerSuite) TestPluginInstallDisableVolumeLs(c *check.C) { <del> testRequires(c, DaemonIsLinux, ExperimentalDaemon, Network) <add> testRequires(c, DaemonIsLinux, Network) <ide> out, _, err := dockerCmdWithError("plugin", "install", "--grant-all-permissions", "--disable", pName) <ide> c.Assert(err, checker.IsNil) <ide> c.Assert(strings.TrimSpace(out), checker.Contains, pName) <ide> func (s *DockerSuite) TestPluginInstallDisableVolumeLs(c *check.C) { <ide> } <ide> <ide> func (s *DockerSuite) TestPluginSet(c *check.C) { <del> testRequires(c, DaemonIsLinux, ExperimentalDaemon, Network) <add> testRequires(c, DaemonIsLinux, Network) <ide> out, _ := dockerCmd(c, "plugin", "install", "--grant-all-permissions", "--disable", pName) <ide> c.Assert(strings.TrimSpace(out), checker.Contains, pName) <ide> <ide> func (s *DockerSuite) TestPluginSet(c *check.C) { <ide> } <ide> <ide> func (s *DockerSuite) TestPluginInstallArgs(c *check.C) { <del> testRequires(c, DaemonIsLinux, ExperimentalDaemon, Network) <add> testRequires(c, DaemonIsLinux, Network) <ide> out, _ := dockerCmd(c, "plugin", "install", "--grant-all-permissions", "--disable", pName, "DEBUG=1") <ide> c.Assert(strings.TrimSpace(out), checker.Contains, pName) <ide> <ide> func (s *DockerSuite) TestPluginInstallArgs(c *check.C) { <ide> } <ide> <ide> func (s *DockerSuite) TestPluginInstallImage(c *check.C) { <del> testRequires(c, DaemonIsLinux, ExperimentalDaemon) <add> testRequires(c, DaemonIsLinux) <ide> out, _, err := dockerCmdWithError("plugin", "install", "redis") <ide> c.Assert(err, checker.NotNil) <ide> c.Assert(out, checker.Contains, "content is not a plugin") <ide> } <ide> <ide> func (s *DockerSuite) TestPluginEnableDisableNegative(c *check.C) { <del> testRequires(c, DaemonIsLinux, ExperimentalDaemon, Network) <add> testRequires(c, DaemonIsLinux, Network) <ide> out, _, err := dockerCmdWithError("plugin", "install", "--grant-all-permissions", pName) <ide> c.Assert(err, checker.IsNil) <ide> c.Assert(strings.TrimSpace(out), checker.Contains, pName)
27
PHP
PHP
apply fixes from styleci
94e8cb36af27c4e85b5e30cd0501b8448ed34909
<ide><path>src/Illuminate/Contracts/Queue/Job.php <ide> public function getConnectionName(); <ide> */ <ide> public function getQueue(); <ide> <del> /** <del> * Get the raw body string for the job. <del> * <del> * @return string <del> */ <del> public function getRawBody(); <add> /** <add> * Get the raw body string for the job. <add> * <add> * @return string <add> */ <add> public function getRawBody(); <ide> } <ide><path>src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php <ide> protected function asDateTime($value) <ide> return $value; <ide> } <ide> <del> // If the value is already a DateTime instance, we will just skip the rest of <del> // these checks since they will be a waste of time, and hinder performance <del> // when checking the field. We will just return the DateTime right away. <add> // If the value is already a DateTime instance, we will just skip the rest of <add> // these checks since they will be a waste of time, and hinder performance <add> // when checking the field. We will just return the DateTime right away. <ide> if ($value instanceof DateTimeInterface) { <ide> return new Carbon( <ide> $value->format('Y-m-d H:i:s.u'), $value->getTimezone() <ide><path>src/Illuminate/Routing/MiddlewareNameResolver.php <ide> public static function resolve($name, $map, $middlewareGroups) <ide> } elseif (isset($map[$name]) && $map[$name] instanceof Closure) { <ide> return $map[$name]; <ide> <del> // If the middleware is the name of a middleware group, we will return the array <add> // If the middleware is the name of a middleware group, we will return the array <ide> // of middlewares that belong to the group. This allows developers to group a <ide> // set of middleware under single keys that can be conveniently referenced. <ide> } elseif (isset($middlewareGroups[$name])) { <ide> return static::parseMiddlewareGroup( <ide> $name, $map, $middlewareGroups <ide> ); <ide> <del> // Finally, when the middleware is simply a string mapped to a class name the <add> // Finally, when the middleware is simply a string mapped to a class name the <ide> // middleware name will get parsed into the full class name and parameters <ide> // which may be run using the Pipeline which accepts this string format. <ide> } else { <ide><path>src/Illuminate/Routing/SortedMiddleware.php <ide> protected function sortMiddleware($priorityMap, $middlewares) <ide> ) <ide> ); <ide> <del> // This middleware is in the priority map; but, this is the first middleware we have <add> // This middleware is in the priority map; but, this is the first middleware we have <ide> // encountered from the map thus far. We'll save its current index plus its index <ide> // from the priority map so we can compare against them on the next iterations. <ide> } else {
4
Javascript
Javascript
fix typo in trace_events_async_hooks.js
9545c48a5e90d53923feb485e2c02cd03126f8f2
<ide><path>lib/internal/trace_events_async_hooks.js <ide> const trace_events = process.binding('trace_events'); <ide> const async_wrap = process.binding('async_wrap'); <ide> const async_hooks = require('async_hooks'); <ide> <del>// Use small letters such that chrome://traceing groups by the name. <add>// Use small letters such that chrome://tracing groups by the name. <ide> // The behavior is not only useful but the same as the events emitted using <ide> // the specific C++ macros. <ide> const BEFORE_EVENT = 'b'.charCodeAt(0);
1
PHP
PHP
update array notation
bddea2b34bfa89b07c0bd0b2043445f884832460
<ide><path>App/webroot/index.php <ide> $Dispatcher = new Dispatcher(); <ide> $Dispatcher->dispatch( <ide> Request::createFromGlobals(), <del> new Response(array('charset' => Configure::read('App.encoding'))) <add> new Response(['charset' => Configure::read('App.encoding')]) <ide> );
1
PHP
PHP
apply fixes from styleci
ebfa75fee5acef028a09f52a78a7069b1a09a723
<ide><path>src/Illuminate/Auth/SessionGuard.php <ide> public function logoutOtherDevices($password, $attribute = 'password') <ide> protected function rehashUserPassword($password, $attribute) <ide> { <ide> if (! Hash::check($password, $this->user()->{$attribute})) { <del> throw new InvalidArgumentException("The given password does not match the current password."); <add> throw new InvalidArgumentException('The given password does not match the current password.'); <ide> } <ide> <ide> return tap($this->user()->forceFill([
1
Ruby
Ruby
add cask pre-release check
0279dda595248d6e0bc288387619d4784a1b8704
<ide><path>Library/Homebrew/cask/audit.rb <ide> def run! <ide> check_latest_with_auto_updates <ide> check_stanza_requires_uninstall <ide> check_appcast_contains_version <del> check_github_repository <ide> check_gitlab_repository <add> check_gitlab_repository_archived <add> check_gitlab_prerelease_version <add> check_github_repository <add> check_github_repository_archived <add> check_github_prerelease_version <ide> check_bitbucket_repository <ide> self <ide> rescue => e <ide> def check_appcast_contains_version <ide> " the version number '#{adjusted_version_stanza}':\n#{appcast_contents}" <ide> end <ide> <add> def check_github_prerelease_version <add> odebug "Auditing GitHub prerelease" <add> user, repo = get_repo_data(%r{https?://github\.com/([^/]+)/([^/]+)/?.*}) if @online <add> return if user.nil? <add> <add> metadata = SharedAudits.github_release_data(user, repo, cask.version) <add> return if metadata.nil? <add> <add> if metadata["prerelease"] <add> problem "#{cask.version} is a GitHub prerelease" <add> elsif metadata["draft"] <add> problem "#{cask.version} is a GitHub draft" <add> end <add> end <add> <add> def check_gitlab_prerelease_version <add> user, repo = get_repo_data(%r{https?://gitlab\.com/([^/]+)/([^/]+)/?.*}) if @online <add> return if user.nil? <add> <add> odebug "Auditing GitLab prerelease" <add> <add> metadata = SharedAudits.gitlab_release_data(user, repo, cask.version) <add> return if metadata.nil? <add> <add> problem "#{cask.version} is a GitLab prerelease" if Date.parse(metadata["released_at"]) > Date.today <add> end <add> <add> def check_github_repository_archived <add> user, repo = get_repo_data(%r{https?://github\.com/([^/]+)/([^/]+)/?.*}) if @online <add> return if user.nil? <add> <add> odebug "Auditing GitHub repo archived" <add> <add> metadata = SharedAudits.github_repo_data(user, repo) <add> return if metadata.nil? <add> <add> problem "GitHub repo is archived" if metadata["archived"] <add> end <add> <add> def check_gitlab_repository_archived <add> user, repo = get_repo_data(%r{https?://gitlab\.com/([^/]+)/([^/]+)/?.*}) if @online <add> return if user.nil? <add> <add> odebug "Auditing GitLab repo archived" <add> <add> metadata = SharedAudits.gitlab_repo_data(user, repo) <add> return if metadata.nil? <add> <add> problem "GitLab repo is archived" if metadata["archived"] <add> end <add> <ide> def check_github_repository <add> return unless @new_cask <add> <ide> user, repo = get_repo_data(%r{https?://github\.com/([^/]+)/([^/]+)/?.*}) <ide> return if user.nil? <ide> <ide> def check_github_repository <ide> end <ide> <ide> def check_gitlab_repository <add> return unless @new_cask <add> <ide> user, repo = get_repo_data(%r{https?://gitlab\.com/([^/]+)/([^/]+)/?.*}) <ide> return if user.nil? <ide> <ide> def check_gitlab_repository <ide> end <ide> <ide> def check_bitbucket_repository <add> return unless @new_cask <add> <ide> user, repo = get_repo_data(%r{https?://bitbucket\.org/([^/]+)/([^/]+)/?.*}) <ide> return if user.nil? <ide> <ide> def check_bitbucket_repository <ide> <ide> def get_repo_data(regex) <ide> return unless online? <del> return unless new_cask? <ide> <ide> _, user, repo = *regex.match(cask.url.to_s) <ide> _, user, repo = *regex.match(cask.homepage) unless user <ide><path>Library/Homebrew/dev-cmd/audit.rb <ide> def get_repo_data(regex) <ide> "libepoxy" => "1.5", <ide> }.freeze <ide> <add> GITLAB_PRERELEASE_ALLOWLIST = {}.freeze <add> <ide> GITHUB_PRERELEASE_ALLOWLIST = { <ide> "cbmc" => "5.12.6", <ide> "elm-format" => "0.8.3", <ide> def audit_specs <ide> return if stable_url_minor_version.even? <ide> <ide> problem "#{stable.version} is a development release" <add> <add> when %r{https?://gitlab\.com/([\w-]+)/([\w-]+)} <add> owner = Regexp.last_match(1) <add> repo = Regexp.last_match(2) <add> <add> return unless @online && (release = SharedAudits.gitlab_release_data(owner, repo, stable.version)) <add> <add> release_date = Date.parse(release["released_at"]) <add> if release_date > Date.today && (GITLAB_PRERELEASE_ALLOWLIST[formula.name] != formula.version) <add> problem "#{stable.version} is a GitLab prerelease" <add> end <ide> when %r{^https://github.com/([\w-]+)/([\w-]+)} <ide> owner = Regexp.last_match(1) <ide> repo = Regexp.last_match(2) <ide> def audit_specs <ide> .second <ide> tag ||= formula.stable.specs[:tag] <ide> <del> begin <del> if @online && (release = GitHub.open_api("#{GitHub::API_URL}/repos/#{owner}/#{repo}/releases/tags/#{tag}")) <del> if release["prerelease"] && (GITHUB_PRERELEASE_ALLOWLIST[formula.name] != formula.version) <del> problem "#{tag} is a GitHub prerelease" <del> elsif release["draft"] <del> problem "#{tag} is a GitHub draft" <del> end <add> if @online && (release = SharedAudits.github_release_data(owner, repo, tag)) <add> if release["prerelease"] && (GITHUB_PRERELEASE_ALLOWLIST[formula.name] != formula.version) <add> problem "#{tag} is a GitHub prerelease" <add> elsif release["draft"] <add> problem "#{tag} is a GitHub draft" <ide> end <del> rescue GitHub::HTTPNotFoundError <del> # No-op if we can't find the release. <del> nil <ide> end <ide> end <ide> end <ide><path>Library/Homebrew/utils/shared_audits.rb <ide> def github_repo_data(user, repo) <ide> nil <ide> end <ide> <add> def github_release_data(user, repo, tag) <add> id = "#{user}/#{repo}/#{tag}" <add> @github_release_data ||= {} <add> @github_release_data[id] ||= GitHub.open_api("#{GitHub::API_URL}/repos/#{user}/#{repo}/releases/tags/#{tag}") <add> <add> @github_release_data[id] <add> rescue GitHub::HTTPNotFoundError <add> nil <add> end <add> <ide> def gitlab_repo_data(user, repo) <ide> @gitlab_repo_data ||= {} <ide> @gitlab_repo_data["#{user}/#{repo}"] ||= begin <ide> def gitlab_repo_data(user, repo) <ide> @gitlab_repo_data["#{user}/#{repo}"] <ide> end <ide> <add> def gitlab_release_data(user, repo, tag) <add> id = "#{user}/#{repo}/#{tag}" <add> @gitlab_release_data ||= {} <add> @gitlab_release_data[id] ||= begin <add> out, _, status= curl_output( <add> "--request", "GET", "https://gitlab.com/api/v4/projects/#{user}%2F#{repo}/releases/#{tag}" <add> ) <add> return unless status.success? <add> <add> JSON.parse(out) <add> end <add> <add> @gitlab_release_data[id] <add> end <add> <ide> def github(user, repo) <ide> metadata = github_repo_data(user, repo) <ide>
3
Javascript
Javascript
change colour => color
592014b705d6a7803601cee4d72e917817807431
<ide><path>examples/js/ShaderGodRays.js <ide> THREE.ShaderGodRays = { <ide> // Accumulate samples, making sure we dont walk past the light source. <ide> <ide> // The check for uv.y < 1 would not be necessary with "border" UV wrap <del> // mode, with a black border colour. I don't think this is currently <add> // mode, with a black border color. I don't think this is currently <ide> // exposed by three.js. As a result there might be artifacts when the <ide> // sun is to the left, right or bottom of screen as these cases are <ide> // not specifically handled.
1
Java
Java
improve requestresponsebodymethodprocessor javadoc
2fc47d8752591da6d8533261c8ce858e0184a196
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessor.java <ide> * to the body of the request or response with an {@link HttpMessageConverter}. <ide> * <ide> * <p>An {@code @RequestBody} method argument is also validated if it is annotated <del> * with {@code @javax.validation.Valid}. In case of validation failure, <add> * with {@code @javax.validation.Valid}, Spring's {@link org.springframework.validation.annotation.Validated} <add> * or custom annotations whose name starts with "Valid". In case of validation failure, <ide> * {@link MethodArgumentNotValidException} is raised and results in an HTTP 400 <ide> * response status code if {@link DefaultHandlerExceptionResolver} is configured. <ide> *
1
Javascript
Javascript
add todo messages indicating desire to remove hack
9e4701a5ab9bbbf446e50e6e94e2c0f0ab5cdf39
<ide><path>src/ng/animate.js <ide> var $AnimateProvider = ['$provide', function($provide) { <ide> element = jqLite(element); <ide> <ide> if (runSynchronously) { <add> // TODO(@caitp/@matsko): Remove undocumented `runSynchronously` parameter, and always <add> // perform DOM manipulation asynchronously or in postDigest. <ide> self.$$addClassImmediately(element, add); <ide> self.$$removeClassImmediately(element, remove); <ide> return asyncPromise(); <ide><path>src/ngAnimate/animate.js <ide> angular.module('ngAnimate', ['ng']) <ide> element = stripCommentsFromElement(element); <ide> <ide> if (classBasedAnimationsBlocked(element)) { <add> // TODO(@caitp/@matsko): Don't use private/undocumented API here --- we should not be <add> // changing the DOM synchronously in this case. The `true` parameter must eventually be <add> // removed. <ide> return $delegate.setClass(element, add, remove, true); <ide> } <ide>
2
Go
Go
fix int format
c219311fd89b21aecc44895e3177ea3fc5b973d6
<ide><path>pkg/integration/utils_test.go <ide> func TestRandomUnixTmpDirPath(t *testing.T) { <ide> } <ide> } <ide> <del>func TestConsumeWithSpeedWith(t *testing.T) { <add>func TestConsumeWithSpeed(t *testing.T) { <ide> reader := strings.NewReader("1234567890") <ide> chunksize := 2 <ide> <ide> func TestConsumeWithSpeedWith(t *testing.T) { <ide> } <ide> <ide> if bytes1 != 10 { <del> t.Fatalf("Expected to have read 10 bytes, got %s", bytes1) <add> t.Fatalf("Expected to have read 10 bytes, got %d", bytes1) <ide> } <ide> <ide> } <ide> func TestConsumeWithSpeedWithStop(t *testing.T) { <ide> } <ide> <ide> if bytes1 != 2 { <del> t.Fatalf("Expected to have read 2 bytes, got %s", bytes1) <add> t.Fatalf("Expected to have read 2 bytes, got %d", bytes1) <ide> } <ide> <ide> }
1
Javascript
Javascript
fix dom node warning
e5ba82a44b2f3badf29312c47a7bb80e978d4e46
<ide><path>src/utils/traverseAllChildren.js <ide> var traverseAllChildrenImpl = <ide> } else { <ide> if (type === 'object') { <ide> invariant( <del> children || children.nodeType !== 1, <add> !children || children.nodeType !== 1, <ide> 'traverseAllChildren(...): Encountered an invalid child; DOM ' + <ide> 'elements are not valid children of React components.' <ide> );
1
Text
Text
improve rendering of v4.4.5 changelog entry
8c1d5e58d4ddfbac20dfd3b0816d7593fad5d256
<ide><path>doc/changelogs/CHANGELOG_V4.md <ide> will be supported actively until April 2017 and maintained until April 2018. <ide> <ide> ### Notable Changes <ide> <del>* **buffer**: <del> * Buffer no longer errors if you call lastIndexOf with a search term longer than the buffer (Anna Henningsen) [#6511](https://github.com/nodejs/node/pull/6511) <del> <del>* **contextify**: <del> * Context objects are now properly garbage collected, this solves a problem some individuals were experiencing with extreme memory growth (Ali Ijaz Sheikh) [#6871](https://github.com/nodejs/node/pull/6871) <del> <del>* **deps**: <del> * update npm to 2.15.5 (Rebecca Turner) [#6663](https://github.com/nodejs/node/pull/6663) <del> <del>* **http**: <del> * Invalid status codes can no longer be sent. Limited to 3 digit numbers between 100 - 999 (Brian White) [#6291](https://github.com/nodejs/node/pull/6291) <add>- **buffer**: <add> - Buffer.indexOf now returns correct values for all UTF-16 input (Anna Henningsen) [#6511](https://github.com/nodejs/node/pull/6511) <add>- **contextify**: <add> - Context objects are now properly garbage collected, this solves a problem some individuals were experiencing with extreme memory growth (Ali Ijaz Sheikh) [#6871](https://github.com/nodejs/node/pull/6871) <add>- **deps**: <add> - update npm to 2.15.5 (Rebecca Turner) [#6663](https://github.com/nodejs/node/pull/6663) <add>- **http**: <add> - Invalid status codes can no longer be sent. Limited to 3 digit numbers between 100 - 999 (Brian White) [#6291](https://github.com/nodejs/node/pull/6291) <ide> <ide> ### Commits <ide>
1
PHP
PHP
return new collection on values
b8d3f5f08f6cc3fa64015af1f4a062133b0d3d88
<ide><path>src/Illuminate/Support/Collection.php <ide> public function unique() <ide> */ <ide> public function values() <ide> { <del> $this->items = array_values($this->items); <del> <del> return $this; <add> return new static(array_values($this->items)); <ide> } <ide> <ide> /**
1
Javascript
Javascript
fix style errors
b1470249b4eaf257fa074f0d4fa052f980653ca4
<ide><path>packages/ember-metal/lib/streams/utils.js <ide> export function concat(array, separator) { <ide> } <ide> } <ide> <del>export function labelsFor(streams) { <add>export function labelsFor(streams) { <ide> var labels = []; <ide> <ide> for (var i=0, l=streams.length; i<l; i++) { <ide> export function labelsFor(streams) { <ide> return labels; <ide> } <ide> <del>export function labelsForObject(streams) { <add>export function labelsForObject(streams) { <ide> var labels = []; <ide> <ide> for (var prop in streams) {
1
Ruby
Ruby
fix respond_to? documentation
2dc48cd4da730980dba46de2d5898666c5f99ed3
<ide><path>activerecord/lib/active_record/attribute_methods.rb <ide> def column_for_attribute(name) <ide> # end <ide> # <ide> # person = Person.new <del> # person.respond_to(:name) # => true <del> # person.respond_to(:name=) # => true <del> # person.respond_to(:name?) # => true <del> # person.respond_to('age') # => true <del> # person.respond_to('age=') # => true <del> # person.respond_to('age?') # => true <del> # person.respond_to(:nothing) # => false <add> # person.respond_to?(:name) # => true <add> # person.respond_to?(:name=) # => true <add> # person.respond_to?(:name?) # => true <add> # person.respond_to?('age') # => true <add> # person.respond_to?('age=') # => true <add> # person.respond_to?('age?') # => true <add> # person.respond_to?(:nothing) # => false <ide> def respond_to?(name, include_private = false) <ide> return false unless super <ide>
1
Python
Python
add missing tutorials
f89665a0d09aeafdc98cdf5f5a3ad64099b725d4
<ide><path>fabfile.py <ide> def jade(source_name, out_dir): <ide> jade('blog/index.jade', 'blog/') <ide> jade('tutorials/index.jade', 'tutorials/') <ide> <del> for post_dir in (Path(__file__).parent / 'website' / 'src' / 'jade' / 'blog').iterdir(): <del> if post_dir.is_dir() \ <del> and (post_dir / 'index.jade').exists() \ <del> and (post_dir / 'meta.jade').exists(): <del> jade(str(post_dir / 'index.jade'), path.join('blog', post_dir.parts[-1])) <add> for collection in ('blog', 'tutorials'): <add> for post_dir in (Path(__file__).parent / 'website' / 'src' / 'jade' / collection).iterdir(): <add> if post_dir.is_dir() \ <add> and (post_dir / 'index.jade').exists() \ <add> and (post_dir / 'meta.jade').exists(): <add> jade(str(post_dir / 'index.jade'), path.join(collection, post_dir.parts[-1])) <ide> <ide> <ide> def web_publish(assets_path): <del> local('aws s3 sync --delete website/site/ s3://spacy.io') <add> local('aws s3 sync --delete --exclude "resources/*" website/site/ s3://spacy.io') <ide> local('aws s3 sync --delete %s s3://spacy.io/resources' % assets_path) <ide> <ide>
1
Text
Text
fix typo in crypto
4bc8f7542fe9b3fce62057e720154cef720d91f8
<ide><path>doc/api/crypto.md <ide> Returns information about a given cipher. <ide> Some ciphers accept variable length keys and initialization vectors. By default, <ide> the `crypto.getCipherInfo()` method will return the default values for these <ide> ciphers. To test if a given key length or iv length is acceptable for given <del>cipher, use the `keyLenth` and `ivLenth` options. If the given values are <add>cipher, use the `keyLength` and `ivLength` options. If the given values are <ide> unacceptable, `undefined` will be returned. <ide> <ide> ### `crypto.getCiphers()`
1
Text
Text
fix export clause
b48fc9657976091ff3833d340877aa5b761e3969
<ide><path>README.md <ide> wrong or incomplete. <ide> *Brought to you courtesy of our legal counsel. For more context, <ide> please see the Notice document.* <ide> <del>Transfers of Docker shall be in accordance with applicable export <del>controls of any country and all other applicable legal requirements. <del>Docker shall not be distributed or downloaded to or in Cuba, Iran, <del>North Korea, Sudan or Syria and shall not be distributed or downloaded <del>to any person on the Denied Persons List administered by the U.S. <del>Department of Commerce. <add>Transfers of Docker shall be in accordance with applicable export controls <add>of any country and all other applicable legal requirements. Without limiting the <add>foregoing, Docker shall not be distributed or downloaded to any individual or <add>location if such distribution or download would violate the applicable US <add>government export regulations. <ide> <add>For more information, please see http://www.bis.doc.gov
1
Go
Go
fix missing plugin name in message
b526964584d213074de7c5573a3373a58699c181
<ide><path>internal/test/daemon/plugin.go <ide> func (d *Daemon) PluginIsNotPresent(name string) func(poll.LogT) poll.Result { <ide> if err != nil { <ide> return poll.Error(err) <ide> } <del> return poll.Continue("plugin %q exists") <add> return poll.Continue("plugin %q exists", name) <ide> }) <ide> } <ide>
1
Python
Python
fix siamese layer
060fcd3ed072eb81a768d9e8da97ecb7b95c4702
<ide><path>keras/layers/core.py <ide> class Siamese(Layer): <ide> dot_axes: Same meaning as `dot_axes` argument of Merge layer <ide> ''' <ide> def __init__(self, layer, inputs, merge_mode='concat', <del> concat_axis=1, dot_axes=-1): <add> concat_axis=1, dot_axes=-1, is_graph=False): <ide> if merge_mode not in ['sum', 'mul', 'concat', 'ave', <ide> 'join', 'cos', 'dot', None]: <ide> raise Exception('Invalid merge mode: ' + str(merge_mode)) <ide> def __init__(self, layer, inputs, merge_mode='concat', <ide> raise Exception(merge_mode + ' merge takes exactly 2 layers') <ide> <ide> self.layer = layer <add> self.trainable = layer.trainable <add> self.is_graph = is_graph <ide> self.inputs = inputs <del> self.params = [] <add> self.layer.set_previous(inputs[0]) <ide> self.merge_mode = merge_mode <ide> self.concat_axis = concat_axis <ide> self.dot_axes = dot_axes <del> layer.set_previous(inputs[0]) <add> self.params = [] <ide> self.regularizers = [] <ide> self.constraints = [] <ide> self.updates = [] <ide> layers = [layer] <del> if merge_mode: <add> if merge_mode and not is_graph: <ide> layers += inputs <ide> for l in layers: <ide> params, regs, consts, updates = l.get_params() <ide> def output_shape(self): <ide> def get_params(self): <ide> return self.params, self.regularizers, self.constraints, self.updates <ide> <del> def set_layer_input(self, index): <del> l = self.layer <del> while not hasattr(l, 'previous'): <del> l = l.layers[0] <del> l.previous = self.inputs[index] <add> def set_layer_input(self, head): <add> layer = self.layer <add> from ..layers.containers import Sequential <add> while issubclass(layer.__class__, Sequential): <add> layer = layer.layers[0] <add> layer.previous = self.inputs[head] <ide> <ide> def get_output_at(self, head, train=False): <del> self.set_layer_input(head) <del> return self.layer.get_output(train) <add> X = self.inputs[head].get_output(train) <add> mask = self.inputs[head].get_output_mask(train) <add> Y = self.layer(X), mask) <add> return Y <ide> <ide> def get_output_shape(self, head, train=False): <ide> self.set_layer_input(head) <ide> def get_output_mask(self, train=None): <ide> <ide> def get_weights(self): <ide> weights = self.layer.get_weights() <del> if self.merge_mode: <add> if self.merge_mode and not self.is_graph: <ide> for m in self.inputs: <ide> weights += m.get_weights() <ide> return weights <ide> def set_weights(self, weights): <ide> nb_param = len(self.layer.params) <ide> self.layer.set_weights(weights[:nb_param]) <ide> weights = weights[nb_param:] <del> if self.merge_mode: <add> if self.merge_mode and not self.is_graph: <ide> for i in range(len(self.inputs)): <ide> nb_param = len(self.inputs[i].params) <ide> self.inputs[i].set_weights(weights[:nb_param]) <ide> def get_config(self): <ide> 'inputs': [m.get_config() for m in self.inputs], <ide> 'merge_mode': self.merge_mode, <ide> 'concat_axis': self.concat_axis, <del> 'dot_axes': self.dot_axes} <add> 'dot_axes': self.dot_axes, <add> 'is_graph': self.is_graph} <ide> base_config = super(Siamese, self).get_config() <ide> return dict(list(base_config.items()) + list(config.items())) <ide>
1
Ruby
Ruby
add constants for regexes
fc7c2434710449088361c52046d13408c0c74729
<ide><path>Library/Homebrew/version.rb <ide> def self._parse(spec, detected_from_url:) <ide> end <ide> private_class_method :_parse <ide> <add> DOT_OPTIONAL = /(?:\d+(?:\.\d+)*)/.source.freeze <add> private_constant :DOT_OPTIONAL <add> <add> DOT_REQUIRED = /(?:\d+(?:\.\d+)+)/.source.freeze <add> private_constant :DOT_REQUIRED <add> <add> MINOR_OR_PATCH = /(?:\d+(?:\.\d+){1,2})/.source.freeze <add> private_constant :MINOR_OR_PATCH <add> <add> BIN_SUFFIX = /(?:[._-](?i:bin|dist|stable|src|sources?|final|full))/.source.freeze <add> private_constant :BIN_SUFFIX <add> <add> ALPHA_SUFFIX = /(?:[._-]?(?i:alpha|beta|pre|rc)\.?\d{,2})/.source.freeze <add> private_constant :ALPHA_SUFFIX <add> <ide> VERSION_PARSERS = [ <ide> # date-based versioning <ide> # e.g. ltopers-v2017-04-14.tar.gz <ide> def self._parse(spec, detected_from_url:) <ide> # e.g. foobar-4.5.1-1 <ide> # e.g. unrtf_0.20.4-1 <ide> # e.g. ruby-1.9.1-p243 <del> StemParser.new(/[_-]((?:\d+\.)*\d+\.\d+-(?:p|rc|RC)?\d+)(?:[._-](?i:bin|dist|stable|src|sources?|final|full))?$/), <add> StemParser.new(/[_-](#{DOT_REQUIRED}-(?:p|rc|RC)?\d+)#{BIN_SUFFIX}?$/), <ide> <ide> # URL with no extension <ide> # e.g. https://waf.io/waf-1.8.12 <ide> # e.g. https://codeload.github.com/gsamokovarov/jump/tar.gz/v0.7.1 <del> UrlParser.new(/[-v]((?:\d+\.)*\d+)$/), <add> UrlParser.new(/[-v](#{DOT_OPTIONAL})$/), <ide> <ide> # e.g. lame-398-1 <ide> StemParser.new(/-(\d+-\d+)/), <ide> <ide> # e.g. foobar-4.5.1 <del> StemParser.new(/-((?:\d+\.)*\d+)$/), <add> StemParser.new(/-(#{DOT_OPTIONAL})$/), <ide> <ide> # e.g. foobar-4.5.1.post1 <del> StemParser.new(/-((?:\d+\.)*\d+(.post\d+)?)$/), <add> StemParser.new(/-(#{DOT_OPTIONAL}(.post\d+)?)$/), <ide> <ide> # e.g. foobar-4.5.1b <del> StemParser.new(/-((?:\d+\.)*\d+(?:[abc]|rc|RC)\d*)$/), <add> StemParser.new(/-(#{DOT_OPTIONAL}(?:[abc]|rc|RC)\d*)$/), <ide> <ide> # e.g. foobar-4.5.0-alpha5, foobar-4.5.0-beta1, or foobar-4.50-beta <del> StemParser.new(/-((?:\d+\.)*\d+-(?:alpha|beta|rc)\d*)$/), <add> StemParser.new(/-(#{DOT_OPTIONAL}-(?:alpha|beta|rc)\d*)$/), <ide> <ide> # e.g. https://ftpmirror.gnu.org/libidn/libidn-1.29-win64.zip <ide> # e.g. https://ftpmirror.gnu.org/libmicrohttpd/libmicrohttpd-0.9.17-w32.zip <del> StemParser.new(/-(\d+\.\d+(?:\.\d+)?)-w(?:in)?(?:32|64)$/), <add> StemParser.new(/-(#{MINOR_OR_PATCH})-w(?:in)?(?:32|64)$/), <ide> <ide> # Opam packages <ide> # e.g. https://opam.ocaml.org/archives/sha.1.9+opam.tar.gz <ide> # e.g. https://opam.ocaml.org/archives/lablgtk.2.18.3+opam.tar.gz <ide> # e.g. https://opam.ocaml.org/archives/easy-format.1.0.2+opam.tar.gz <del> StemParser.new(/\.(\d+\.\d+(?:\.\d+)?)\+opam$/), <add> StemParser.new(/\.(#{MINOR_OR_PATCH})\+opam$/), <ide> <ide> # e.g. https://ftpmirror.gnu.org/mtools/mtools-4.0.18-1.i686.rpm <ide> # e.g. https://ftpmirror.gnu.org/autogen/autogen-5.5.7-5.i386.rpm <ide> # e.g. https://ftpmirror.gnu.org/libtasn1/libtasn1-2.8-x86.zip <ide> # e.g. https://ftpmirror.gnu.org/libtasn1/libtasn1-2.8-x64.zip <ide> # e.g. https://ftpmirror.gnu.org/mtools/mtools_4.0.18_i386.deb <del> StemParser.new(/[_-](\d+\.\d+(?:\.\d+)?(?:-\d+)?)[._-](?:i[36]86|x86|x64(?:[_-](?:32|64))?)$/), <add> StemParser.new(/[_-](#{MINOR_OR_PATCH}(?:-\d+)?)[._-](?:i[36]86|x86|x64(?:[_-](?:32|64))?)$/), <ide> <ide> # e.g. https://registry.npmjs.org/@angular/cli/-/cli-1.3.0-beta.1.tgz <ide> # e.g. https://github.com/dlang/dmd/archive/v2.074.0-beta1.tar.gz <ide> # e.g. https://github.com/dlang/dmd/archive/v2.074.0-rc1.tar.gz <ide> # e.g. https://github.com/premake/premake-core/releases/download/v5.0.0-alpha10/premake-5.0.0-alpha10-src.zip <del> StemParser.new(/[-.vV]?((?:\d+\.)+\d+[._-]?(?i:alpha|beta|pre|rc)\.?\d{,2})/), <add> StemParser.new(/[-.vV]?(#{DOT_REQUIRED}#{ALPHA_SUFFIX})/), <ide> <ide> # e.g. foobar4.5.1 <del> StemParser.new(/((?:\d+\.)*\d+)$/), <add> StemParser.new(/(#{DOT_OPTIONAL})$/), <ide> <ide> # e.g. foobar-4.5.0-bin <del> StemParser.new(/[-vV]((?:\d+\.)+\d+[abc]?)[._-](?i:bin|dist|stable|src|sources?|final|full)$/), <add> StemParser.new(/[-vV](#{DOT_REQUIRED}[abc]?)#{BIN_SUFFIX}$/), <ide> <ide> # dash version style <ide> # e.g. http://www.antlr.org/download/antlr-3.4-complete.jar <ide> # e.g. https://cdn.nuxeo.com/nuxeo-9.2/nuxeo-server-9.2-tomcat.zip <ide> # e.g. https://search.maven.org/remotecontent?filepath=com/facebook/presto/presto-cli/0.181/presto-cli-0.181-executable.jar <ide> # e.g. https://search.maven.org/remotecontent?filepath=org/fusesource/fuse-extra/fusemq-apollo-mqtt/1.3/fusemq-apollo-mqtt-1.3-uber.jar <ide> # e.g. https://search.maven.org/remotecontent?filepath=org/apache/orc/orc-tools/1.2.3/orc-tools-1.2.3-uber.jar <del> StemParser.new(/-((?:\d+\.)+\d+)-/), <add> StemParser.new(/-(#{DOT_REQUIRED})-/), <ide> <ide> # e.g. dash_0.5.5.1.orig.tar.gz (Debian style) <del> StemParser.new(/_((?:\d+\.)+\d+[abc]?)\.orig$/), <add> StemParser.new(/_(#{DOT_REQUIRED}[abc]?)\.orig$/), <ide> <ide> # e.g. https://www.openssl.org/source/openssl-0.9.8s.tar.gz <ide> StemParser.new(/-v?(\d[^-]+)/), <ide> def self._parse(spec, detected_from_url:) <ide> StemParser.new(/\.v(\d+[a-z]?)/), <ide> <ide> # e.g. https://secure.php.net/get/php-7.1.10.tar.bz2/from/this/mirror <del> UrlParser.new(/[-.vV]?((?:\d+\.)+\d+(?:[._-]?(?i:alpha|beta|pre|rc)\.?\d{,2})?)/), <add> UrlParser.new(/[-.vV]?(#{DOT_REQUIRED}#{ALPHA_SUFFIX}?)/), <ide> ].freeze <ide> private_constant :VERSION_PARSERS <ide>
1
Python
Python
add support for exporting gpt-j to onnx-trt
ae189ef99199d07bc7c6dfb79c46b411e05dfe61
<ide><path>src/transformers/models/gptj/modeling_gptj.py <ide> def rotate_every_two(x): <ide> return x.flatten(-2) # in einsum notation: rearrange(x, '... d j -> ... (d j)') <ide> <ide> <add>def duplicate_interleave(m): <add> """ <add> A simple version of `torch.repeat_interleave` for duplicating a matrix while interleaving the copy. <add> """ <add> dim0 = m.shape[0] <add> m = m.view(-1, 1) # flatten the matrix <add> m = m.repeat(1, 2) # repeat all elements into the 2nd dimension <add> m = m.view(dim0, -1) # reshape into a matrix, interleaving the copy <add> return m <add> <add> <ide> def apply_rotary_pos_emb(x, sincos, offset=0): <del> sin, cos = map(lambda t: t[None, offset : x.shape[1] + offset, None, :].repeat_interleave(2, 3), sincos) <add> sin, cos = map(lambda t: duplicate_interleave(t)[None, offset : x.shape[1] + offset, None, :], sincos) <ide> # einsum notation for lambda t: repeat(t[offset:x.shape[1]+offset,:], "n d -> () n () (d j)", j=2) <ide> return (x * cos) + (rotate_every_two(x) * sin) <ide>
1
Go
Go
replace usage of pkg/nat with go-connections/nat
056e7449039af522fa0a1567ef67916eaa0de93e
<ide><path>api/client/port.go <ide> import ( <ide> <ide> Cli "github.com/docker/docker/cli" <ide> flag "github.com/docker/docker/pkg/mflag" <del> "github.com/docker/docker/pkg/nat" <add> "github.com/docker/go-connections/nat" <ide> ) <ide> <ide> // CmdPort lists port mappings for a container. <ide><path>api/types/types.go <ide> import ( <ide> <ide> "github.com/docker/docker/api/types/network" <ide> "github.com/docker/docker/api/types/registry" <del> "github.com/docker/docker/pkg/nat" <ide> "github.com/docker/docker/pkg/version" <ide> "github.com/docker/docker/runconfig" <add> "github.com/docker/go-connections/nat" <ide> ) <ide> <ide> // ContainerCreateResponse contains the information returned to a client on the <ide><path>api/types/versions/v1p19/types.go <ide> package v1p19 <ide> import ( <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/api/types/versions/v1p20" <del> "github.com/docker/docker/pkg/nat" <ide> "github.com/docker/docker/runconfig" <add> "github.com/docker/go-connections/nat" <ide> ) <ide> <ide> // ContainerJSON is a backcompatibility struct for APIs prior to 1.20. <ide><path>api/types/versions/v1p20/types.go <ide> package v1p20 <ide> <ide> import ( <ide> "github.com/docker/docker/api/types" <del> "github.com/docker/docker/pkg/nat" <ide> "github.com/docker/docker/runconfig" <add> "github.com/docker/go-connections/nat" <ide> ) <ide> <ide> // ContainerJSON is a backcompatibility struct for the API 1.20 <ide><path>builder/dockerfile/dispatchers.go <ide> import ( <ide> "github.com/docker/docker/builder" <ide> derr "github.com/docker/docker/errors" <ide> flag "github.com/docker/docker/pkg/mflag" <del> "github.com/docker/docker/pkg/nat" <ide> "github.com/docker/docker/pkg/signal" <ide> "github.com/docker/docker/pkg/system" <ide> "github.com/docker/docker/runconfig" <add> "github.com/docker/go-connections/nat" <ide> ) <ide> <ide> const ( <ide><path>container/container.go <ide> import ( <ide> derr "github.com/docker/docker/errors" <ide> "github.com/docker/docker/image" <ide> "github.com/docker/docker/layer" <del> "github.com/docker/docker/pkg/nat" <ide> "github.com/docker/docker/pkg/promise" <ide> "github.com/docker/docker/pkg/signal" <ide> "github.com/docker/docker/pkg/symlink" <ide> "github.com/docker/docker/runconfig" <ide> "github.com/docker/docker/volume" <add> "github.com/docker/go-connections/nat" <ide> "github.com/opencontainers/runc/libcontainer/label" <ide> ) <ide> <ide><path>container/container_unix.go <ide> import ( <ide> "github.com/docker/docker/daemon/execdriver" <ide> derr "github.com/docker/docker/errors" <ide> "github.com/docker/docker/pkg/chrootarchive" <del> "github.com/docker/docker/pkg/nat" <ide> "github.com/docker/docker/pkg/symlink" <ide> "github.com/docker/docker/pkg/system" <ide> "github.com/docker/docker/utils" <ide> "github.com/docker/docker/volume" <add> "github.com/docker/go-connections/nat" <ide> "github.com/docker/libnetwork" <ide> "github.com/docker/libnetwork/netlabel" <ide> "github.com/docker/libnetwork/options" <ide><path>daemon/daemon.go <ide> import ( <ide> "github.com/docker/docker/pkg/jsonmessage" <ide> "github.com/docker/docker/pkg/mount" <ide> "github.com/docker/docker/pkg/namesgenerator" <del> "github.com/docker/docker/pkg/nat" <ide> "github.com/docker/docker/pkg/progress" <ide> "github.com/docker/docker/pkg/signal" <ide> "github.com/docker/docker/pkg/streamformatter" <ide> import ( <ide> volumedrivers "github.com/docker/docker/volume/drivers" <ide> "github.com/docker/docker/volume/local" <ide> "github.com/docker/docker/volume/store" <add> "github.com/docker/go-connections/nat" <ide> "github.com/docker/libnetwork" <ide> lntypes "github.com/docker/libnetwork/types" <ide> "github.com/docker/libtrust" <ide><path>daemon/execdriver/driver_windows.go <ide> package execdriver <ide> <ide> import ( <del> "github.com/docker/docker/pkg/nat" <ide> "github.com/docker/docker/runconfig" <add> "github.com/docker/go-connections/nat" <ide> ) <ide> <ide> // Mount contains information for a mount operation. <ide><path>daemon/links/links.go <ide> import ( <ide> "path" <ide> "strings" <ide> <del> "github.com/docker/docker/pkg/nat" <add> "github.com/docker/go-connections/nat" <ide> ) <ide> <ide> // Link struct holds informations about parent/child linked container <ide><path>daemon/links/links_test.go <ide> import ( <ide> "strings" <ide> "testing" <ide> <del> "github.com/docker/docker/pkg/nat" <add> "github.com/docker/go-connections/nat" <ide> ) <ide> <ide> // Just to make life easier <ide><path>daemon/list.go <ide> import ( <ide> "github.com/docker/docker/container" <ide> "github.com/docker/docker/image" <ide> "github.com/docker/docker/pkg/graphdb" <del> "github.com/docker/docker/pkg/nat" <add> "github.com/docker/go-connections/nat" <ide> ) <ide> <ide> // iterationAction represents possible outcomes happening during the container iteration. <ide><path>daemon/network/settings.go <ide> package network <ide> <ide> import ( <ide> networktypes "github.com/docker/docker/api/types/network" <del> "github.com/docker/docker/pkg/nat" <add> "github.com/docker/go-connections/nat" <ide> ) <ide> <ide> // Settings stores configuration details about the daemon network config <ide><path>integration-cli/docker_cli_create_test.go <ide> import ( <ide> "io/ioutil" <ide> <ide> "github.com/docker/docker/pkg/integration/checker" <del> "github.com/docker/docker/pkg/nat" <ide> "github.com/docker/docker/pkg/stringid" <add> "github.com/docker/go-connections/nat" <ide> "github.com/go-check/check" <ide> ) <ide> <ide><path>integration-cli/docker_cli_run_test.go <ide> import ( <ide> <ide> "github.com/docker/docker/pkg/integration/checker" <ide> "github.com/docker/docker/pkg/mount" <del> "github.com/docker/docker/pkg/nat" <ide> "github.com/docker/docker/runconfig" <add> "github.com/docker/go-connections/nat" <ide> "github.com/docker/libnetwork/resolvconf" <ide> "github.com/go-check/check" <ide> ) <ide><path>pkg/nat/nat.go <del>package nat <del> <del>// nat is a convenience package for docker's manipulation of strings describing <del>// network ports. <del> <del>import ( <del> "fmt" <del> "net" <del> "strconv" <del> "strings" <del> <del> "github.com/docker/docker/pkg/parsers" <del>) <del> <del>const ( <del> // portSpecTemplate is the expected format for port specifications <del> portSpecTemplate = "ip:hostPort:containerPort" <del>) <del> <del>// PortBinding represents a binding between a Host IP address and a Host Port <del>type PortBinding struct { <del> // HostIP is the host IP Address <del> HostIP string `json:"HostIp"` <del> // HostPort is the host port number <del> HostPort string <del>} <del> <del>// PortMap is a collection of PortBinding indexed by Port <del>type PortMap map[Port][]PortBinding <del> <del>// PortSet is a collection of structs indexed by Port <del>type PortSet map[Port]struct{} <del> <del>// Port is a string containing port number and protocol in the format "80/tcp" <del>type Port string <del> <del>// NewPort creates a new instance of a Port given a protocol and port number or port range <del>func NewPort(proto, port string) (Port, error) { <del> // Check for parsing issues on "port" now so we can avoid having <del> // to check it later on. <del> <del> portStartInt, portEndInt, err := ParsePortRange(port) <del> if err != nil { <del> return "", err <del> } <del> <del> if portStartInt == portEndInt { <del> return Port(fmt.Sprintf("%d/%s", portStartInt, proto)), nil <del> } <del> return Port(fmt.Sprintf("%d-%d/%s", portStartInt, portEndInt, proto)), nil <del>} <del> <del>// ParsePort parses the port number string and returns an int <del>func ParsePort(rawPort string) (int, error) { <del> if len(rawPort) == 0 { <del> return 0, nil <del> } <del> port, err := strconv.ParseUint(rawPort, 10, 16) <del> if err != nil { <del> return 0, err <del> } <del> return int(port), nil <del>} <del> <del>// ParsePortRange parses the port range string and returns start/end ints <del>func ParsePortRange(rawPort string) (int, int, error) { <del> if len(rawPort) == 0 { <del> return 0, 0, nil <del> } <del> start, end, err := parsers.ParsePortRange(rawPort) <del> if err != nil { <del> return 0, 0, err <del> } <del> return int(start), int(end), nil <del>} <del> <del>// Proto returns the protocol of a Port <del>func (p Port) Proto() string { <del> proto, _ := SplitProtoPort(string(p)) <del> return proto <del>} <del> <del>// Port returns the port number of a Port <del>func (p Port) Port() string { <del> _, port := SplitProtoPort(string(p)) <del> return port <del>} <del> <del>// Int returns the port number of a Port as an int <del>func (p Port) Int() int { <del> portStr := p.Port() <del> if len(portStr) == 0 { <del> return 0 <del> } <del> <del> // We don't need to check for an error because we're going to <del> // assume that any error would have been found, and reported, in NewPort() <del> port, _ := strconv.ParseUint(portStr, 10, 16) <del> return int(port) <del>} <del> <del>// Range returns the start/end port numbers of a Port range as ints <del>func (p Port) Range() (int, int, error) { <del> return ParsePortRange(p.Port()) <del>} <del> <del>// SplitProtoPort splits a port in the format of proto/port <del>func SplitProtoPort(rawPort string) (string, string) { <del> parts := strings.Split(rawPort, "/") <del> l := len(parts) <del> if len(rawPort) == 0 || l == 0 || len(parts[0]) == 0 { <del> return "", "" <del> } <del> if l == 1 { <del> return "tcp", rawPort <del> } <del> if len(parts[1]) == 0 { <del> return "tcp", parts[0] <del> } <del> return parts[1], parts[0] <del>} <del> <del>func validateProto(proto string) bool { <del> for _, availableProto := range []string{"tcp", "udp"} { <del> if availableProto == proto { <del> return true <del> } <del> } <del> return false <del>} <del> <del>// ParsePortSpecs receives port specs in the format of ip:public:private/proto and parses <del>// these in to the internal types <del>func ParsePortSpecs(ports []string) (map[Port]struct{}, map[Port][]PortBinding, error) { <del> var ( <del> exposedPorts = make(map[Port]struct{}, len(ports)) <del> bindings = make(map[Port][]PortBinding) <del> ) <del> <del> for _, rawPort := range ports { <del> proto := "tcp" <del> <del> if i := strings.LastIndex(rawPort, "/"); i != -1 { <del> proto = rawPort[i+1:] <del> rawPort = rawPort[:i] <del> } <del> if !strings.Contains(rawPort, ":") { <del> rawPort = fmt.Sprintf("::%s", rawPort) <del> } else if len(strings.Split(rawPort, ":")) == 2 { <del> rawPort = fmt.Sprintf(":%s", rawPort) <del> } <del> <del> parts, err := parsers.PartParser(portSpecTemplate, rawPort) <del> if err != nil { <del> return nil, nil, err <del> } <del> <del> var ( <del> containerPort = parts["containerPort"] <del> rawIP = parts["ip"] <del> hostPort = parts["hostPort"] <del> ) <del> <del> if rawIP != "" && net.ParseIP(rawIP) == nil { <del> return nil, nil, fmt.Errorf("Invalid ip address: %s", rawIP) <del> } <del> if containerPort == "" { <del> return nil, nil, fmt.Errorf("No port specified: %s<empty>", rawPort) <del> } <del> <del> startPort, endPort, err := parsers.ParsePortRange(containerPort) <del> if err != nil { <del> return nil, nil, fmt.Errorf("Invalid containerPort: %s", containerPort) <del> } <del> <del> var startHostPort, endHostPort uint64 = 0, 0 <del> if len(hostPort) > 0 { <del> startHostPort, endHostPort, err = parsers.ParsePortRange(hostPort) <del> if err != nil { <del> return nil, nil, fmt.Errorf("Invalid hostPort: %s", hostPort) <del> } <del> } <del> <del> if hostPort != "" && (endPort-startPort) != (endHostPort-startHostPort) { <del> // Allow host port range iff containerPort is not a range. <del> // In this case, use the host port range as the dynamic <del> // host port range to allocate into. <del> if endPort != startPort { <del> return nil, nil, fmt.Errorf("Invalid ranges specified for container and host Ports: %s and %s", containerPort, hostPort) <del> } <del> } <del> <del> if !validateProto(strings.ToLower(proto)) { <del> return nil, nil, fmt.Errorf("Invalid proto: %s", proto) <del> } <del> <del> for i := uint64(0); i <= (endPort - startPort); i++ { <del> containerPort = strconv.FormatUint(startPort+i, 10) <del> if len(hostPort) > 0 { <del> hostPort = strconv.FormatUint(startHostPort+i, 10) <del> } <del> // Set hostPort to a range only if there is a single container port <del> // and a dynamic host port. <del> if startPort == endPort && startHostPort != endHostPort { <del> hostPort = fmt.Sprintf("%s-%s", hostPort, strconv.FormatUint(endHostPort, 10)) <del> } <del> port, err := NewPort(strings.ToLower(proto), containerPort) <del> if err != nil { <del> return nil, nil, err <del> } <del> if _, exists := exposedPorts[port]; !exists { <del> exposedPorts[port] = struct{}{} <del> } <del> <del> binding := PortBinding{ <del> HostIP: rawIP, <del> HostPort: hostPort, <del> } <del> bslice, exists := bindings[port] <del> if !exists { <del> bslice = []PortBinding{} <del> } <del> bindings[port] = append(bslice, binding) <del> } <del> } <del> return exposedPorts, bindings, nil <del>} <ide><path>pkg/nat/nat_test.go <del>package nat <del> <del>import ( <del> "testing" <del>) <del> <del>func TestParsePort(t *testing.T) { <del> var ( <del> p int <del> err error <del> ) <del> <del> p, err = ParsePort("1234") <del> <del> if err != nil || p != 1234 { <del> t.Fatal("Parsing '1234' did not succeed") <del> } <del> <del> // FIXME currently this is a valid port. I don't think it should be. <del> // I'm leaving this test commented out until we make a decision. <del> // - erikh <del> <del> /* <del> p, err = ParsePort("0123") <del> <del> if err != nil { <del> t.Fatal("Successfully parsed port '0123' to '123'") <del> } <del> */ <del> <del> p, err = ParsePort("asdf") <del> <del> if err == nil || p != 0 { <del> t.Fatal("Parsing port 'asdf' succeeded") <del> } <del> <del> p, err = ParsePort("1asdf") <del> <del> if err == nil || p != 0 { <del> t.Fatal("Parsing port '1asdf' succeeded") <del> } <del>} <del> <del>func TestParsePortRange(t *testing.T) { <del> var ( <del> begin int <del> end int <del> err error <del> ) <del> <del> type TestRange struct { <del> Range string <del> Begin int <del> End int <del> } <del> validRanges := []TestRange{ <del> {"1234", 1234, 1234}, <del> {"1234-1234", 1234, 1234}, <del> {"1234-1235", 1234, 1235}, <del> {"8000-9000", 8000, 9000}, <del> {"0", 0, 0}, <del> {"0-0", 0, 0}, <del> } <del> <del> for _, r := range validRanges { <del> begin, end, err = ParsePortRange(r.Range) <del> <del> if err != nil || begin != r.Begin { <del> t.Fatalf("Parsing port range '%s' did not succeed. Expected begin %d, got %d", r.Range, r.Begin, begin) <del> } <del> if err != nil || end != r.End { <del> t.Fatalf("Parsing port range '%s' did not succeed. Expected end %d, got %d", r.Range, r.End, end) <del> } <del> } <del> <del> invalidRanges := []string{ <del> "asdf", <del> "1asdf", <del> "9000-8000", <del> "9000-", <del> "-8000", <del> "-8000-", <del> } <del> <del> for _, r := range invalidRanges { <del> begin, end, err = ParsePortRange(r) <del> <del> if err == nil || begin != 0 || end != 0 { <del> t.Fatalf("Parsing port range '%s' succeeded", r) <del> } <del> } <del>} <del> <del>func TestPort(t *testing.T) { <del> p, err := NewPort("tcp", "1234") <del> <del> if err != nil { <del> t.Fatalf("tcp, 1234 had a parsing issue: %v", err) <del> } <del> <del> if string(p) != "1234/tcp" { <del> t.Fatal("tcp, 1234 did not result in the string 1234/tcp") <del> } <del> <del> if p.Proto() != "tcp" { <del> t.Fatal("protocol was not tcp") <del> } <del> <del> if p.Port() != "1234" { <del> t.Fatal("port string value was not 1234") <del> } <del> <del> if p.Int() != 1234 { <del> t.Fatal("port int value was not 1234") <del> } <del> <del> p, err = NewPort("tcp", "asd1234") <del> if err == nil { <del> t.Fatal("tcp, asd1234 was supposed to fail") <del> } <del> <del> p, err = NewPort("tcp", "1234-1230") <del> if err == nil { <del> t.Fatal("tcp, 1234-1230 was supposed to fail") <del> } <del> <del> p, err = NewPort("tcp", "1234-1242") <del> if err != nil { <del> t.Fatalf("tcp, 1234-1242 had a parsing issue: %v", err) <del> } <del> <del> if string(p) != "1234-1242/tcp" { <del> t.Fatal("tcp, 1234-1242 did not result in the string 1234-1242/tcp") <del> } <del>} <del> <del>func TestSplitProtoPort(t *testing.T) { <del> var ( <del> proto string <del> port string <del> ) <del> <del> proto, port = SplitProtoPort("1234/tcp") <del> <del> if proto != "tcp" || port != "1234" { <del> t.Fatal("Could not split 1234/tcp properly") <del> } <del> <del> proto, port = SplitProtoPort("") <del> <del> if proto != "" || port != "" { <del> t.Fatal("parsing an empty string yielded surprising results", proto, port) <del> } <del> <del> proto, port = SplitProtoPort("1234") <del> <del> if proto != "tcp" || port != "1234" { <del> t.Fatal("tcp is not the default protocol for portspec '1234'", proto, port) <del> } <del> <del> proto, port = SplitProtoPort("1234/") <del> <del> if proto != "tcp" || port != "1234" { <del> t.Fatal("parsing '1234/' yielded:" + port + "/" + proto) <del> } <del> <del> proto, port = SplitProtoPort("/tcp") <del> <del> if proto != "" || port != "" { <del> t.Fatal("parsing '/tcp' yielded:" + port + "/" + proto) <del> } <del>} <del> <del>func TestParsePortSpecs(t *testing.T) { <del> var ( <del> portMap map[Port]struct{} <del> bindingMap map[Port][]PortBinding <del> err error <del> ) <del> <del> portMap, bindingMap, err = ParsePortSpecs([]string{"1234/tcp", "2345/udp"}) <del> <del> if err != nil { <del> t.Fatalf("Error while processing ParsePortSpecs: %s", err) <del> } <del> <del> if _, ok := portMap[Port("1234/tcp")]; !ok { <del> t.Fatal("1234/tcp was not parsed properly") <del> } <del> <del> if _, ok := portMap[Port("2345/udp")]; !ok { <del> t.Fatal("2345/udp was not parsed properly") <del> } <del> <del> for portspec, bindings := range bindingMap { <del> if len(bindings) != 1 { <del> t.Fatalf("%s should have exactly one binding", portspec) <del> } <del> <del> if bindings[0].HostIP != "" { <del> t.Fatalf("HostIP should not be set for %s", portspec) <del> } <del> <del> if bindings[0].HostPort != "" { <del> t.Fatalf("HostPort should not be set for %s", portspec) <del> } <del> } <del> <del> portMap, bindingMap, err = ParsePortSpecs([]string{"1234:1234/tcp", "2345:2345/udp"}) <del> <del> if err != nil { <del> t.Fatalf("Error while processing ParsePortSpecs: %s", err) <del> } <del> <del> if _, ok := portMap[Port("1234/tcp")]; !ok { <del> t.Fatal("1234/tcp was not parsed properly") <del> } <del> <del> if _, ok := portMap[Port("2345/udp")]; !ok { <del> t.Fatal("2345/udp was not parsed properly") <del> } <del> <del> for portspec, bindings := range bindingMap { <del> _, port := SplitProtoPort(string(portspec)) <del> <del> if len(bindings) != 1 { <del> t.Fatalf("%s should have exactly one binding", portspec) <del> } <del> <del> if bindings[0].HostIP != "" { <del> t.Fatalf("HostIP should not be set for %s", portspec) <del> } <del> <del> if bindings[0].HostPort != port { <del> t.Fatalf("HostPort should be %s for %s", port, portspec) <del> } <del> } <del> <del> portMap, bindingMap, err = ParsePortSpecs([]string{"0.0.0.0:1234:1234/tcp", "0.0.0.0:2345:2345/udp"}) <del> <del> if err != nil { <del> t.Fatalf("Error while processing ParsePortSpecs: %s", err) <del> } <del> <del> if _, ok := portMap[Port("1234/tcp")]; !ok { <del> t.Fatal("1234/tcp was not parsed properly") <del> } <del> <del> if _, ok := portMap[Port("2345/udp")]; !ok { <del> t.Fatal("2345/udp was not parsed properly") <del> } <del> <del> for portspec, bindings := range bindingMap { <del> _, port := SplitProtoPort(string(portspec)) <del> <del> if len(bindings) != 1 { <del> t.Fatalf("%s should have exactly one binding", portspec) <del> } <del> <del> if bindings[0].HostIP != "0.0.0.0" { <del> t.Fatalf("HostIP is not 0.0.0.0 for %s", portspec) <del> } <del> <del> if bindings[0].HostPort != port { <del> t.Fatalf("HostPort should be %s for %s", port, portspec) <del> } <del> } <del> <del> _, _, err = ParsePortSpecs([]string{"localhost:1234:1234/tcp"}) <del> <del> if err == nil { <del> t.Fatal("Received no error while trying to parse a hostname instead of ip") <del> } <del>} <del> <del>func TestParsePortSpecsWithRange(t *testing.T) { <del> var ( <del> portMap map[Port]struct{} <del> bindingMap map[Port][]PortBinding <del> err error <del> ) <del> <del> portMap, bindingMap, err = ParsePortSpecs([]string{"1234-1236/tcp", "2345-2347/udp"}) <del> <del> if err != nil { <del> t.Fatalf("Error while processing ParsePortSpecs: %s", err) <del> } <del> <del> if _, ok := portMap[Port("1235/tcp")]; !ok { <del> t.Fatal("1234/tcp was not parsed properly") <del> } <del> <del> if _, ok := portMap[Port("2346/udp")]; !ok { <del> t.Fatal("2345/udp was not parsed properly") <del> } <del> <del> for portspec, bindings := range bindingMap { <del> if len(bindings) != 1 { <del> t.Fatalf("%s should have exactly one binding", portspec) <del> } <del> <del> if bindings[0].HostIP != "" { <del> t.Fatalf("HostIP should not be set for %s", portspec) <del> } <del> <del> if bindings[0].HostPort != "" { <del> t.Fatalf("HostPort should not be set for %s", portspec) <del> } <del> } <del> <del> portMap, bindingMap, err = ParsePortSpecs([]string{"1234-1236:1234-1236/tcp", "2345-2347:2345-2347/udp"}) <del> <del> if err != nil { <del> t.Fatalf("Error while processing ParsePortSpecs: %s", err) <del> } <del> <del> if _, ok := portMap[Port("1235/tcp")]; !ok { <del> t.Fatal("1234/tcp was not parsed properly") <del> } <del> <del> if _, ok := portMap[Port("2346/udp")]; !ok { <del> t.Fatal("2345/udp was not parsed properly") <del> } <del> <del> for portspec, bindings := range bindingMap { <del> _, port := SplitProtoPort(string(portspec)) <del> if len(bindings) != 1 { <del> t.Fatalf("%s should have exactly one binding", portspec) <del> } <del> <del> if bindings[0].HostIP != "" { <del> t.Fatalf("HostIP should not be set for %s", portspec) <del> } <del> <del> if bindings[0].HostPort != port { <del> t.Fatalf("HostPort should be %s for %s", port, portspec) <del> } <del> } <del> <del> portMap, bindingMap, err = ParsePortSpecs([]string{"0.0.0.0:1234-1236:1234-1236/tcp", "0.0.0.0:2345-2347:2345-2347/udp"}) <del> <del> if err != nil { <del> t.Fatalf("Error while processing ParsePortSpecs: %s", err) <del> } <del> <del> if _, ok := portMap[Port("1235/tcp")]; !ok { <del> t.Fatal("1234/tcp was not parsed properly") <del> } <del> <del> if _, ok := portMap[Port("2346/udp")]; !ok { <del> t.Fatal("2345/udp was not parsed properly") <del> } <del> <del> for portspec, bindings := range bindingMap { <del> _, port := SplitProtoPort(string(portspec)) <del> if len(bindings) != 1 || bindings[0].HostIP != "0.0.0.0" || bindings[0].HostPort != port { <del> t.Fatalf("Expect single binding to port %s but found %s", port, bindings) <del> } <del> } <del> <del> _, _, err = ParsePortSpecs([]string{"localhost:1234-1236:1234-1236/tcp"}) <del> <del> if err == nil { <del> t.Fatal("Received no error while trying to parse a hostname instead of ip") <del> } <del>} <del> <del>func TestParseNetworkOptsPrivateOnly(t *testing.T) { <del> ports, bindings, err := ParsePortSpecs([]string{"192.168.1.100::80"}) <del> if err != nil { <del> t.Fatal(err) <del> } <del> if len(ports) != 1 { <del> t.Logf("Expected 1 got %d", len(ports)) <del> t.FailNow() <del> } <del> if len(bindings) != 1 { <del> t.Logf("Expected 1 got %d", len(bindings)) <del> t.FailNow() <del> } <del> for k := range ports { <del> if k.Proto() != "tcp" { <del> t.Logf("Expected tcp got %s", k.Proto()) <del> t.Fail() <del> } <del> if k.Port() != "80" { <del> t.Logf("Expected 80 got %s", k.Port()) <del> t.Fail() <del> } <del> b, exists := bindings[k] <del> if !exists { <del> t.Log("Binding does not exist") <del> t.FailNow() <del> } <del> if len(b) != 1 { <del> t.Logf("Expected 1 got %d", len(b)) <del> t.FailNow() <del> } <del> s := b[0] <del> if s.HostPort != "" { <del> t.Logf("Expected \"\" got %s", s.HostPort) <del> t.Fail() <del> } <del> if s.HostIP != "192.168.1.100" { <del> t.Fail() <del> } <del> } <del>} <del> <del>func TestParseNetworkOptsPublic(t *testing.T) { <del> ports, bindings, err := ParsePortSpecs([]string{"192.168.1.100:8080:80"}) <del> if err != nil { <del> t.Fatal(err) <del> } <del> if len(ports) != 1 { <del> t.Logf("Expected 1 got %d", len(ports)) <del> t.FailNow() <del> } <del> if len(bindings) != 1 { <del> t.Logf("Expected 1 got %d", len(bindings)) <del> t.FailNow() <del> } <del> for k := range ports { <del> if k.Proto() != "tcp" { <del> t.Logf("Expected tcp got %s", k.Proto()) <del> t.Fail() <del> } <del> if k.Port() != "80" { <del> t.Logf("Expected 80 got %s", k.Port()) <del> t.Fail() <del> } <del> b, exists := bindings[k] <del> if !exists { <del> t.Log("Binding does not exist") <del> t.FailNow() <del> } <del> if len(b) != 1 { <del> t.Logf("Expected 1 got %d", len(b)) <del> t.FailNow() <del> } <del> s := b[0] <del> if s.HostPort != "8080" { <del> t.Logf("Expected 8080 got %s", s.HostPort) <del> t.Fail() <del> } <del> if s.HostIP != "192.168.1.100" { <del> t.Fail() <del> } <del> } <del>} <del> <del>func TestParseNetworkOptsPublicNoPort(t *testing.T) { <del> ports, bindings, err := ParsePortSpecs([]string{"192.168.1.100"}) <del> <del> if err == nil { <del> t.Logf("Expected error Invalid containerPort") <del> t.Fail() <del> } <del> if ports != nil { <del> t.Logf("Expected nil got %s", ports) <del> t.Fail() <del> } <del> if bindings != nil { <del> t.Logf("Expected nil got %s", bindings) <del> t.Fail() <del> } <del>} <del> <del>func TestParseNetworkOptsNegativePorts(t *testing.T) { <del> ports, bindings, err := ParsePortSpecs([]string{"192.168.1.100:-1:-1"}) <del> <del> if err == nil { <del> t.Fail() <del> } <del> if len(ports) != 0 { <del> t.Logf("Expected nil got %d", len(ports)) <del> t.Fail() <del> } <del> if len(bindings) != 0 { <del> t.Logf("Expected 0 got %d", len(bindings)) <del> t.Fail() <del> } <del>} <del> <del>func TestParseNetworkOptsUdp(t *testing.T) { <del> ports, bindings, err := ParsePortSpecs([]string{"192.168.1.100::6000/udp"}) <del> if err != nil { <del> t.Fatal(err) <del> } <del> if len(ports) != 1 { <del> t.Logf("Expected 1 got %d", len(ports)) <del> t.FailNow() <del> } <del> if len(bindings) != 1 { <del> t.Logf("Expected 1 got %d", len(bindings)) <del> t.FailNow() <del> } <del> for k := range ports { <del> if k.Proto() != "udp" { <del> t.Logf("Expected udp got %s", k.Proto()) <del> t.Fail() <del> } <del> if k.Port() != "6000" { <del> t.Logf("Expected 6000 got %s", k.Port()) <del> t.Fail() <del> } <del> b, exists := bindings[k] <del> if !exists { <del> t.Log("Binding does not exist") <del> t.FailNow() <del> } <del> if len(b) != 1 { <del> t.Logf("Expected 1 got %d", len(b)) <del> t.FailNow() <del> } <del> s := b[0] <del> if s.HostPort != "" { <del> t.Logf("Expected \"\" got %s", s.HostPort) <del> t.Fail() <del> } <del> if s.HostIP != "192.168.1.100" { <del> t.Fail() <del> } <del> } <del>} <ide><path>pkg/nat/sort.go <del>package nat <del> <del>import ( <del> "sort" <del> "strings" <del> <del> "github.com/docker/docker/pkg/parsers" <del>) <del> <del>type portSorter struct { <del> ports []Port <del> by func(i, j Port) bool <del>} <del> <del>func (s *portSorter) Len() int { <del> return len(s.ports) <del>} <del> <del>func (s *portSorter) Swap(i, j int) { <del> s.ports[i], s.ports[j] = s.ports[j], s.ports[i] <del>} <del> <del>func (s *portSorter) Less(i, j int) bool { <del> ip := s.ports[i] <del> jp := s.ports[j] <del> <del> return s.by(ip, jp) <del>} <del> <del>// Sort sorts a list of ports using the provided predicate <del>// This function should compare `i` and `j`, returning true if `i` is <del>// considered to be less than `j` <del>func Sort(ports []Port, predicate func(i, j Port) bool) { <del> s := &portSorter{ports, predicate} <del> sort.Sort(s) <del>} <del> <del>type portMapEntry struct { <del> port Port <del> binding PortBinding <del>} <del> <del>type portMapSorter []portMapEntry <del> <del>func (s portMapSorter) Len() int { return len(s) } <del>func (s portMapSorter) Swap(i, j int) { s[i], s[j] = s[j], s[i] } <del> <del>// sort the port so that the order is: <del>// 1. port with larger specified bindings <del>// 2. larger port <del>// 3. port with tcp protocol <del>func (s portMapSorter) Less(i, j int) bool { <del> pi, pj := s[i].port, s[j].port <del> hpi, hpj := toInt(s[i].binding.HostPort), toInt(s[j].binding.HostPort) <del> return hpi > hpj || pi.Int() > pj.Int() || (pi.Int() == pj.Int() && strings.ToLower(pi.Proto()) == "tcp") <del>} <del> <del>// SortPortMap sorts the list of ports and their respected mapping. The ports <del>// will explicit HostPort will be placed first. <del>func SortPortMap(ports []Port, bindings PortMap) { <del> s := portMapSorter{} <del> for _, p := range ports { <del> if binding, ok := bindings[p]; ok { <del> for _, b := range binding { <del> s = append(s, portMapEntry{port: p, binding: b}) <del> } <del> bindings[p] = []PortBinding{} <del> } else { <del> s = append(s, portMapEntry{port: p}) <del> } <del> } <del> <del> sort.Sort(s) <del> var ( <del> i int <del> pm = make(map[Port]struct{}) <del> ) <del> // reorder ports <del> for _, entry := range s { <del> if _, ok := pm[entry.port]; !ok { <del> ports[i] = entry.port <del> pm[entry.port] = struct{}{} <del> i++ <del> } <del> // reorder bindings for this port <del> if _, ok := bindings[entry.port]; ok { <del> bindings[entry.port] = append(bindings[entry.port], entry.binding) <del> } <del> } <del>} <del> <del>func toInt(s string) uint64 { <del> i, _, err := parsers.ParsePortRange(s) <del> if err != nil { <del> i = 0 <del> } <del> return i <del>} <ide><path>pkg/nat/sort_test.go <del>package nat <del> <del>import ( <del> "fmt" <del> "reflect" <del> "testing" <del>) <del> <del>func TestSortUniquePorts(t *testing.T) { <del> ports := []Port{ <del> Port("6379/tcp"), <del> Port("22/tcp"), <del> } <del> <del> Sort(ports, func(ip, jp Port) bool { <del> return ip.Int() < jp.Int() || (ip.Int() == jp.Int() && ip.Proto() == "tcp") <del> }) <del> <del> first := ports[0] <del> if fmt.Sprint(first) != "22/tcp" { <del> t.Log(fmt.Sprint(first)) <del> t.Fail() <del> } <del>} <del> <del>func TestSortSamePortWithDifferentProto(t *testing.T) { <del> ports := []Port{ <del> Port("8888/tcp"), <del> Port("8888/udp"), <del> Port("6379/tcp"), <del> Port("6379/udp"), <del> } <del> <del> Sort(ports, func(ip, jp Port) bool { <del> return ip.Int() < jp.Int() || (ip.Int() == jp.Int() && ip.Proto() == "tcp") <del> }) <del> <del> first := ports[0] <del> if fmt.Sprint(first) != "6379/tcp" { <del> t.Fail() <del> } <del>} <del> <del>func TestSortPortMap(t *testing.T) { <del> ports := []Port{ <del> Port("22/tcp"), <del> Port("22/udp"), <del> Port("8000/tcp"), <del> Port("6379/tcp"), <del> Port("9999/tcp"), <del> } <del> <del> portMap := PortMap{ <del> Port("22/tcp"): []PortBinding{ <del> {}, <del> }, <del> Port("8000/tcp"): []PortBinding{ <del> {}, <del> }, <del> Port("6379/tcp"): []PortBinding{ <del> {}, <del> {HostIP: "0.0.0.0", HostPort: "32749"}, <del> }, <del> Port("9999/tcp"): []PortBinding{ <del> {HostIP: "0.0.0.0", HostPort: "40000"}, <del> }, <del> } <del> <del> SortPortMap(ports, portMap) <del> if !reflect.DeepEqual(ports, []Port{ <del> Port("9999/tcp"), <del> Port("6379/tcp"), <del> Port("8000/tcp"), <del> Port("22/tcp"), <del> Port("22/udp"), <del> }) { <del> t.Errorf("failed to prioritize port with explicit mappings, got %v", ports) <del> } <del> if pm := portMap[Port("6379/tcp")]; !reflect.DeepEqual(pm, []PortBinding{ <del> {HostIP: "0.0.0.0", HostPort: "32749"}, <del> {}, <del> }) { <del> t.Errorf("failed to prioritize bindings with explicit mappings, got %v", pm) <del> } <del>} <ide><path>runconfig/compare_test.go <ide> import ( <ide> "testing" <ide> <ide> "github.com/docker/docker/api/types/strslice" <del> "github.com/docker/docker/pkg/nat" <add> "github.com/docker/go-connections/nat" <ide> ) <ide> <ide> // Just to make life easier <ide><path>runconfig/config.go <ide> import ( <ide> "io" <ide> <ide> "github.com/docker/docker/api/types/strslice" <del> "github.com/docker/docker/pkg/nat" <ide> "github.com/docker/docker/volume" <add> "github.com/docker/go-connections/nat" <ide> ) <ide> <ide> // Config contains the configuration data about a container. <ide><path>runconfig/hostconfig.go <ide> import ( <ide> <ide> "github.com/docker/docker/api/types/blkiodev" <ide> "github.com/docker/docker/api/types/strslice" <del> "github.com/docker/docker/pkg/nat" <ide> "github.com/docker/docker/pkg/ulimit" <add> "github.com/docker/go-connections/nat" <ide> ) <ide> <ide> // KeyValuePair is a structure that hold a value for a key. <ide><path>runconfig/merge.go <ide> package runconfig <ide> import ( <ide> "strings" <ide> <del> "github.com/docker/docker/pkg/nat" <add> "github.com/docker/go-connections/nat" <ide> ) <ide> <ide> // Merge merges two Config, the image container configuration (defaults values), <ide><path>runconfig/merge_test.go <ide> package runconfig <ide> import ( <ide> "testing" <ide> <del> "github.com/docker/docker/pkg/nat" <add> "github.com/docker/go-connections/nat" <ide> ) <ide> <ide> func TestMerge(t *testing.T) { <ide><path>runconfig/parse.go <ide> import ( <ide> "github.com/docker/docker/opts" <ide> flag "github.com/docker/docker/pkg/mflag" <ide> "github.com/docker/docker/pkg/mount" <del> "github.com/docker/docker/pkg/nat" <ide> "github.com/docker/docker/pkg/parsers" <ide> "github.com/docker/docker/pkg/signal" <ide> "github.com/docker/docker/volume" <add> "github.com/docker/go-connections/nat" <ide> "github.com/docker/go-units" <ide> ) <ide> <ide><path>runconfig/parse_test.go <ide> import ( <ide> "testing" <ide> <ide> flag "github.com/docker/docker/pkg/mflag" <del> "github.com/docker/docker/pkg/nat" <add> "github.com/docker/go-connections/nat" <ide> ) <ide> <ide> func parseRun(args []string) (*Config, *HostConfig, *flag.FlagSet, error) {
26
PHP
PHP
remove unnecessary sqlite test
e224e394627f7994be32b19a4ac09822a878ac4f
<ide><path>tests/Database/DatabaseQueryBuilderTest.php <ide> public function testMySqlWrapping() <ide> } <ide> <ide> <del> public function testSQLiteOrderBy() <del> { <del> $builder = $this->getSQLiteBuilder(); <del> $builder->select('*')->from('users')->orderBy('email', 'desc'); <del> $this->assertEquals('select * from "users" order by "email" collate nocase desc', $builder->toSql()); <del> } <del> <del> <ide> public function testSqlServerLimitsAndOffsets() <ide> { <ide> $builder = $this->getSqlServerBuilder();
1
Java
Java
ensure annotationutils is compatible with java 6
0637864b3909ab13727cb228258b778a265da8d9
<ide><path>spring-core/src/main/java/org/springframework/core/annotation/AnnotationUtils.java <ide> private static <A extends Annotation> A findAnnotation(Class<?> clazz, Class<A> <ide> Set<Annotation> visited) { <ide> Assert.notNull(clazz, "Class must not be null"); <ide> <del> A annotation = clazz.getDeclaredAnnotation(annotationType); <del> if (annotation != null) { <del> return annotation; <add> if (isAnnotationDeclaredLocally(annotationType, clazz)) { <add> return clazz.getAnnotation(annotationType); <ide> } <ide> for (Class<?> ifc : clazz.getInterfaces()) { <del> annotation = findAnnotation(ifc, annotationType, visited); <add> A annotation = findAnnotation(ifc, annotationType, visited); <ide> if (annotation != null) { <ide> return annotation; <ide> } <ide> } <ide> for (Annotation ann : clazz.getDeclaredAnnotations()) { <ide> if (!isInJavaLangAnnotationPackage(ann) && visited.add(ann)) { <del> annotation = findAnnotation(ann.annotationType(), annotationType, visited); <add> A annotation = findAnnotation(ann.annotationType(), annotationType, <add> visited); <ide> if (annotation != null) { <ide> return annotation; <ide> }
1
Javascript
Javascript
remove deleted files again
59212a538ed838d09e5a5d870f60e1cd66c2302c
<ide><path>src/core/ReactDOMNodeCache.js <del>/** <del> * Copyright 2013 Facebook, Inc. <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> * <del> * @providesModule ReactDOMNodeCache <del> * @typechecks static-only <del> */ <del> <del>"use strict"; <del> <del>var ReactID = require('ReactID'); <del> <del>exports.getNodeByID = ReactID.getNode; <del>exports.purgeID = ReactID.purgeID; <del>exports.purgeEntireCache = ReactID.purgeEntireCache; <ide><path>src/dom/getDOMNodeID.js <del>/** <del> * Copyright 2013 Facebook, Inc. <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> * <del> * @providesModule getDOMNodeID <del> * @typechecks static-only <del> */ <del> <del>"use strict"; <del> <del>var ReactID = require('ReactID'); <del> <del>function getDOMNodeID(domNode) { <del> return ReactID.getID(domNode); <del>} <del>module.exports = getDOMNodeID;
2
Ruby
Ruby
fix typo in `--include-optional` output
fc40e2fa4006412ba96aad8729027d40c38c7129
<ide><path>Library/Homebrew/cmd/deps.rb <ide> def dep_display_name(dep) <ide> if ARGV.include?("--annotate") <ide> str = "#{str} [build]" if dep.build? <ide> str = "#{str} [test]" if dep.test? <del> str = "#{str} [optional" if dep.optional? <add> str = "#{str} [optional]" if dep.optional? <ide> str = "#{str} [recommended]" if dep.recommended? <ide> end <ide>
1
PHP
PHP
consolidate widget adding code within on method
7a7ab006427754be6d0ef8fd8d1b1fc6e805697f
<ide><path>src/View/Widget/WidgetLocator.php <ide> public function __construct(StringTemplate $templates, View $view, array $widget <ide> $this->_templates = $templates; <ide> $this->_view = $view; <ide> <del> if (!empty($widgets)) { <del> $this->add($widgets); <del> foreach ($this->_widgets as $key => $widget) { <del> if (is_string($widget) && !class_exists($widget)) { <del> $this->load($widget); <del> unset($this->_widgets[$key]); <del> } <del> } <del> } <add> $this->add($widgets); <ide> } <ide> <ide> /** <ide> public function load(string $file): void <ide> */ <ide> public function add(array $widgets): void <ide> { <del> foreach ($widgets as $object) { <del> if (is_object($object) && !($object instanceof WidgetInterface)) { <del> throw new RuntimeException( <del> 'Widget objects must implement Cake\View\Widget\WidgetInterface.' <del> ); <add> $files = []; <add> <add> foreach ($widgets as $key => $widget) { <add> if (is_int($key)) { <add> $files[] = $widget; <add> continue; <add> } <add> <add> if (is_object($widget) && !($widget instanceof WidgetInterface)) { <add> throw new RuntimeException('Widget objects must implement ' . WidgetInterface::class); <ide> } <add> <add> $this->_widgets[$key] = $widget; <add> } <add> <add> foreach ($files as $file) { <add> $this->load($file); <ide> } <del> $this->_widgets = $widgets + $this->_widgets; <ide> } <ide> <ide> /** <ide> protected function _resolveWidget($widget): object <ide> $widget = [$widget]; <ide> } <ide> <add> if (!is_array($widget)) { <add> throw new RuntimeException('Widget config must be a string or array.'); <add> } <add> <ide> $class = array_shift($widget); <ide> $className = App::className($class, 'View/Widget', 'Widget'); <ide> if ($className === null) { <ide> throw new RuntimeException(sprintf('Unable to locate widget class "%s"', $class)); <ide> } <del> if ($type === 'array' && count($widget)) { <add> if (count($widget)) { <ide> $reflection = new ReflectionClass($className); <ide> $arguments = [$this->_templates]; <ide> foreach ($widget as $requirement) {
1
Python
Python
make assertions only if actually chunking forward
678bb248d07c593c5ce94f49328835a90e0a8403
<ide><path>src/transformers/modeling_utils.py <ide> def forward(self, hidden_states): <ide> """ <ide> <ide> assert len(input_tensors) > 0, f"{input_tensors} has to be a tuple/list of tensors" <del> tensor_shape = input_tensors[0].shape[chunk_dim] <del> assert all( <del> input_tensor.shape[chunk_dim] == tensor_shape for input_tensor in input_tensors <del> ), "All input tenors have to be of the same shape" <ide> <ide> # inspect.signature exist since python 3.5 and is a python method -> no problem with backward compatibility <ide> num_args_in_forward_chunk_fn = len(inspect.signature(forward_fn).parameters) <ide> def forward(self, hidden_states): <ide> ) <ide> <ide> if chunk_size > 0: <add> tensor_shape = input_tensors[0].shape[chunk_dim] <add> for input_tensor in input_tensors: <add> if input_tensor.shape[chunk_dim] != tensor_shape: <add> raise ValueError( <add> f"All input tenors have to be of the same shape: {tensor_shape}, " <add> f"found shape {input_tensor.shape[chunk_dim]}" <add> ) <add> <ide> if input_tensors[0].shape[chunk_dim] % chunk_size != 0: <ide> raise ValueError( <ide> f"The dimension to be chunked {input_tensors[0].shape[chunk_dim]} has to be a multiple of the chunk "
1
Java
Java
fix memory leak in concurrentreferencehashmap
2b4c81e64240527c34d9896a13746596eab6e846
<ide><path>spring-core/src/main/java/org/springframework/util/ConcurrentReferenceHashMap.java <ide> public void clear() { <ide> } <ide> } <ide> <add> /** <add> * Remove any entries that have been garbage collected and are no longer referenced. <add> * Under normal circumstances garbage collected entries are automatically purged as <add> * items are added or removed from the Map. This method can be used to force a purge, <add> * and is useful when the Map is read frequently but updated less often. <add> */ <add> public void purgeUnreferencedEntries() { <add> for (Segment segment : this.segments) { <add> segment.restructureIfNecessary(false); <add> } <add> } <add> <add> <ide> @Override <ide> public int size() { <ide> int size = 0; <ide> public void clear() { <ide> * references that have been garbage collected. <ide> * @param allowResize if resizing is permitted <ide> */ <del> private void restructureIfNecessary(boolean allowResize) { <add> protected final void restructureIfNecessary(boolean allowResize) { <ide> boolean needsResize = ((this.count > 0) && (this.count >= this.resizeThreshold)); <ide> Reference<K, V> reference = this.referenceManager.pollForPurge(); <ide> if ((reference != null) || (needsResize && allowResize)) { <ide> private void restructureIfNecessary(boolean allowResize) { <ide> restructured[i] = null; <ide> } <ide> while (reference != null) { <del> if (!toPurge.contains(reference)) { <add> if (!toPurge.contains(reference) && (reference.get() != null)) { <ide> int index = getIndex(reference.getHash(), restructured); <ide> restructured[index] = this.referenceManager.createReference( <ide> reference.get(), reference.getHash(), <ide> private void restructureIfNecessary(boolean allowResize) { <ide> if (resizing) { <ide> setReferences(restructured); <ide> } <del> this.count = countAfterRestructure; <add> this.count = Math.max(countAfterRestructure, 0); <ide> } finally { <ide> unlock(); <ide> } <ide> public void release() { <ide> enqueue(); <ide> clear(); <ide> } <add> <ide> } <ide> <ide> <ide> public void release() { <ide> enqueue(); <ide> clear(); <ide> } <add> <ide> } <ide> <ide> }
1
Java
Java
fix merge bug
f35489c5fc44e8cd3614cf4f71ab6e8734084abc
<ide><path>rxjava-core/src/main/java/rx/internal/operators/OperatorMerge.java <ide> private void emit(T t, boolean complete) { <ide> emitted++; <ide> } <ide> } else { <del> if (producer.requested > 0) { <add> // this needs to check q.count() as draining above may not have drained the full queue <add> // perf tests show this to be okay, though different queue implementations could perform poorly with this <add> if (producer.requested > 0 && q.count() == 0) { <ide> if (complete) { <ide> parentSubscriber.completeInner(this); <ide> } else {
1
Javascript
Javascript
remove usage of d3_array for efficiency
1bb3e9b02599f92a21a5b7b7b8f7492a1ba1e011
<ide><path>d3.js <ide> function d3_svg_mousePoints(container, events) { <ide> d3_mouse_bug44083 = !(ctm.f || ctm.e); <ide> svg.remove(); <ide> } <del> return events.map(function(e) { <add> var i = -1, <add> n = events.length, <add> points = []; <add> while (++i < n) { <add> var e = events[i]; <ide> if (d3_mouse_bug44083) { <ide> point.x = e.pageX; <ide> point.y = e.pageY; <ide> function d3_svg_mousePoints(container, events) { <ide> point.y = e.clientY; <ide> } <ide> point = point.matrixTransform(container.getScreenCTM().inverse()); <del> return [point.x, point.y]; <del> }); <add> points.push([point.x, point.y]); <add> } <add> return points; <ide> }; <ide> d3.svg.touches = function(container) { <ide> var touches = d3.event.touches; <ide> return touches && touches.length <del> ? d3_svg_mousePoints(container, d3_array(touches)) : []; <add> ? d3_svg_mousePoints(container, touches) : []; <ide> }; <ide> d3.svg.symbol = function() { <ide> var type = d3_svg_symbolType, <ide><path>d3.min.js <del>(function(){function cb(){return"circle"}function ca(){return 64}function b_(a,b){var c=(a.ownerSVGElement||a).createSVGPoint();if(b$<0&&(window.scrollX||window.scrollY)){var d=d3.select(document.body).append("svg:svg").style("position","absolute").style("top",0).style("left",0),e=d[0][0].getScreenCTM();b$=!e.f&&!e.e,d.remove()}return b.map(function(b){b$?(c.x=b.pageX,c.y=b.pageY):(c.x=b.clientX,c.y=b.clientY),c=c.matrixTransform(a.getScreenCTM().inverse());return[c.x,c.y]})}function bZ(a){return[a.x,a.y]}function bY(a){return a.endAngle}function bX(a){return a.startAngle}function bW(a){return a.radius}function bV(a){return a.target}function bU(a){return a.source}function bT(){return 0}function bS(a){return a.length<3?bz(a):a[0]+bF(a,bR(a))}function bR(a){var b=[],c,d,e,f,g=bQ(a),h=-1,i=a.length-1;while(++h<i)c=bP(a[h],a[h+1]),Math.abs(c)<1e-6?g[h]=g[h+1]=0:(d=g[h]/c,e=g[h+1]/c,f=d*d+e*e,f>9&&(f=c*3/Math.sqrt(f),g[h]=f*d,g[h+1]=f*e));h=-1;while(++h<=i)f=(a[Math.min(i,h+1)][0]-a[Math.max(0,h-1)][0])/(6*(1+g[h]*g[h])),b.push([f||0,g[h]*f||0]);return b}function bQ(a){var b=0,c=a.length-1,d=[],e=a[0],f=a[1],g=d[0]=bP(e,f);while(++b<c)d[b]=g+(g=bP(e=f,f=a[b+1]));d[b]=g;return d}function bP(a,b){return(b[1]-a[1])/(b[0]-a[0])}function bO(a,b,c){a.push("C",bK(bL,b),",",bK(bL,c),",",bK(bM,b),",",bK(bM,c),",",bK(bN,b),",",bK(bN,c))}function bK(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3]}function bJ(a){var b,c=-1,d=a.length,e=d+4,f,g=[],h=[];while(++c<4)f=a[c%d],g.push(f[0]),h.push(f[1]);b=[bK(bN,g),",",bK(bN,h)],--c;while(++c<e)f=a[c%d],g.shift(),g.push(f[0]),h.shift(),h.push(f[1]),bO(b,g,h);return b.join("")}function bI(a){if(a.length<4)return bz(a);var b=[],c=-1,d=a.length,e,f=[0],g=[0];while(++c<3)e=a[c],f.push(e[0]),g.push(e[1]);b.push(bK(bN,f)+","+bK(bN,g)),--c;while(++c<d)e=a[c],f.shift(),f.push(e[0]),g.shift(),g.push(e[1]),bO(b,f,g);return b.join("")}function bH(a){if(a.length<3)return bz(a);var b=[],c=1,d=a.length,e=a[0],f=e[0],g=e[1],h=[f,f,f,(e=a[1])[0]],i=[g,g,g,e[1]];b.push(f,",",g),bO(b,h,i);while(++c<d)e=a[c],h.shift(),h.push(e[0]),i.shift(),i.push(e[1]),bO(b,h,i);c=-1;while(++c<2)h.shift(),h.push(e[0]),i.shift(),i.push(e[1]),bO(b,h,i);return b.join("")}function bG(a,b){var c=[],d=(1-b)/2,e,f=a[0],g=a[1],h=1,i=a.length;while(++h<i)e=f,f=g,g=a[h],c.push([d*(g[0]-e[0]),d*(g[1]-e[1])]);return c}function bF(a,b){if(b.length<1||a.length!=b.length&&a.length!=b.length+2)return bz(a);var c=a.length!=b.length,d="",e=a[0],f=a[1],g=b[0],h=g,i=1;c&&(d+="Q"+(f[0]-g[0]*2/3)+","+(f[1]-g[1]*2/3)+","+f[0]+","+f[1],e=a[1],i=2);if(b.length>1){h=b[1],f=a[i],i++,d+="C"+(e[0]+g[0])+","+(e[1]+g[1])+","+(f[0]-h[0])+","+(f[1]-h[1])+","+f[0]+","+f[1];for(var j=2;j<b.length;j++,i++)f=a[i],h=b[j],d+="S"+(f[0]-h[0])+","+(f[1]-h[1])+","+f[0]+","+f[1]}if(c){var k=a[i];d+="Q"+(f[0]+h[0]*2/3)+","+(f[1]+h[1]*2/3)+","+k[0]+","+k[1]}return d}function bE(a,b,c){return a.length<3?bz(a):a[0]+bF(a,bG(a,b))}function bD(a,b){return a.length<3?bz(a):a[0]+bF((a.push(a[0]),a),bG([a[a.length-2]].concat(a,[a[1]]),b))}function bC(a,b){return a.length<4?bz(a):a[1]+bF(a.slice(1,a.length-1),bG(a,b))}function bB(a){var b=[],c=0,d=a.length,e=a[0];b.push(e[0],",",e[1]);while(++c<d)b.push("H",(e=a[c])[0],"V",e[1]);return b.join("")}function bA(a){var b=[],c=0,d=a.length,e=a[0];b.push(e[0],",",e[1]);while(++c<d)b.push("V",(e=a[c])[1],"H",e[0]);return b.join("")}function bz(a){var b=[],c=0,d=a.length,e=a[0];b.push(e[0],",",e[1]);while(++c<d)b.push("L",(e=a[c])[0],",",e[1]);return b.join("")}function bx(a){return a[1]}function bw(a){return a[0]}function bv(a,b,c,d){var e=[],f=-1,g=b.length,h=typeof c=="function",i=typeof d=="function",j;if(h&&i)while(++f<g)e.push([c.call(a,j=b[f],f),d.call(a,j,f)]);else if(h)while(++f<g)e.push([c.call(a,b[f],f),d]);else if(i)while(++f<g)e.push([c,d.call(a,b[f],f)]);else while(++f<g)e.push([c,d]);return e}function bu(a){return a.endAngle}function bt(a){return a.startAngle}function bs(a){return a.outerRadius}function br(a){return a.innerRadius}function bk(a){return function(b){return-Math.pow(-b,a)}}function bj(a){return function(b){return Math.pow(b,a)}}function bi(a){return-Math.log(-a)/Math.LN10}function bh(a){return Math.log(a)/Math.LN10}function bg(a,b,c,d){function i(b){var c=1,d=a.length-2;while(c<=d){var e=c+d>>1,f=a[e];if(f<b)c=e+1;else if(f>b)d=e-1;else return e}return c-1}var e=[],f=[],g=0,h=a.length;while(++g<h)e.push(c(a[g-1],a[g])),f.push(d(b[g-1],b[g]));return function(a){var b=i(a);return f[b](e[b](a))}}function bf(a,b,c,d){var e=c(a[0],a[1]),f=d(b[0],b[1]);return function(a){return f(e(a))}}function bd(){var a=null,b=$,c=Infinity;while(b)b.flush?b=a?a.next=b.next:$=b.next:(c=Math.min(c,b.then+b.delay),b=(a=b).next);return c}function bc(){var a,b=Date.now(),c=$;while(c)a=b-c.then,a>c.delay&&(c.flush=c.callback(a)),c=c.next;var d=bd()-b;d>24?(isFinite(d)&&(clearTimeout(ba),ba=setTimeout(bc,d)),_=0):(_=1,be(bc))}function bb(a,b){var c=Date.now(),d=!1,e,f=$;if(!!isFinite(b)){while(f){if(f.callback===a){f.then=c,f.delay=b,d=!0;break}e=f,f=f.next}d||($={callback:a,then:c,delay:b,next:$}),_||(ba=clearTimeout(ba),_=1,be(bc))}}function Z(a){return typeof a=="function"?function(b,c,d){return d3.interpolate(d,String(a.call(this,b,c)))}:(a=String(a),function(b,c,d){return d3.interpolate(d,a)})}function Y(a){function n(b){var g=!0,l=-1;a.each(function(){if(i[++l]!==2){var a=(b-j[l])/k[l],n=this.__transition__,o,p,q=e[l];if(a<1){g=!1;if(a<0)return}else a=1;if(i[l]){if(!n||n.active!==c){i[l]=2;return}}else{if(!n||n.active>c){i[l]=2;return}i[l]=1,h.start.dispatch.apply(this,arguments),q=e[l]={},n.active=c;for(p in d)if(o=d[p].apply(this,arguments))q[p]=o}o=m(a);for(p in q)q[p].call(this,o);if(a===1){i[l]=2;if(n.active===c){var r=n.owner;r===c&&(delete this.__transition__,f&&this.parentNode.removeChild(this)),X=c,h.end.dispatch.apply(this,arguments),X=0,n.owner=r}}}});return g}var b={},c=X||++W,d={},e=[],f=!1,h=d3.dispatch("start","end"),i=[],j=[],k=[],l,m=d3.ease("cubic-in-out");a.each(function(){(this.__transition__||(this.__transition__={})).owner=c}),b.delay=function(c){var d=Infinity,e=-1;typeof c=="function"?a.each(function(a,b){var f=j[++e]=+c.apply(this,arguments);f<d&&(d=f)}):(d=+c,a.each(function(a,b){j[++e]=d})),bb(n,d);return b},b.duration=function(c){var d=-1;typeof c=="function"?(l=0,a.each(function(a,b){var e=k[++d]=+c.apply(this,arguments);e>l&&(l=e)})):(l=+c,a.each(function(a,b){k[++d]=l}));return b},b.ease=function(a){m=typeof a=="function"?a:d3.ease.apply(d3,arguments);return b},b.attrTween=function(a,c){function f(b,d){var e=c.call(this,b,d,this.getAttributeNS(a.space,a.local));return function(b){this.setAttributeNS(a.space,a.local,e(b))}}function e(b,d){var e=c.call(this,b,d,this.getAttribute(a));return function(b){this.setAttribute(a,e(b))}}d["attr."+a]=a.local?f:e;return b},b.attr=function(a,c){return b.attrTween(a,Z(c))},b.styleTween=function(a,c,e){function f(b,d){var f=c.call(this,b,d,window.getComputedStyle(this,null).getPropertyValue(a));return function(b){this.style.setProperty(a,f(b),e)}}arguments.length<3&&(e=null),d["style."+a]=f;return b},b.style=function(a,c,d){arguments.length<3&&(d=null);return b.styleTween(a,Z(c),d)},b.text=function(a){d.text=function(b,c){this.textContent=typeof a=="function"?a.call(this,b,c):a};return b},b.select=function(b){var c,d=Y(a.select(b)).ease(m);c=-1,d.delay(function(a,b){return j[++c]}),c=-1,d.duration(function(a,b){return k[++c]});return d},b.selectAll=function(b){var c,d=Y(a.selectAll(b)).ease(m);c=-1,d.delay(function(a,b){return j[b?c:++c]}),c=-1,d.duration(function(a,b){return k[b?c:++c]});return d},b.remove=function(){f=!0;return b},b.each=function(a,c){h[a].add(c);return b},b.call=g;return b.delay(0).duration(250)}function V(a){return{__data__:a}}function U(a){arguments.length||(a=d3.ascending);return function(b,c){return a(b&&b.__data__,c&&c.__data__)}}function T(a){function b(b){var c=[],d,e,f,g;for(var h=0,i=a.length;h<i;h++){f=a[h],c.push(d=[]),d.parentNode=f.parentNode;for(var j=0,k=f.length;j<k;j++)(g=f[j])?(d.push(e=b(f.parentNode)),e.__data__=g.__data__):d.push(null)}return S(c)}a.append=function(a){function d(b){return b.appendChild(document.createElementNS(a.space,a.local))}function c(b){return b.appendChild(document.createElement(a))}a=d3.ns.qualify(a);return b(a.local?d:c)},a.insert=function(a,c){function e(b){return b.insertBefore(document.createElementNS(a.space,a.local),P(c,b))}function d(b){return b.insertBefore(document.createElement(a),P(c,b))}a=d3.ns.qualify(a);return b(a.local?e:d)};return a}function S(a){function d(b){for(var c=0,d=a.length;c<d;c++){var e=a[c];for(var f=0,g=e.length;f<g;f++){var h=e[f];if(h)return b.call(h,h.__data__,f)}}return null}function c(b){var c=[],d,e,f;for(var g=0,h=a.length;g<h;g++){e=a[g];for(var i=0,j=e.length;i<j;i++)if(f=e[i])c.push(d=b(f)),d.parentNode=f}return S(c)}function b(b){var c=[],d,e,f,g;for(var h=0,i=a.length;h<i;h++){f=a[h],c.push(d=[]),d.parentNode=f.parentNode;for(var j=0,k=f.length;j<k;j++)(g=f[j])?(d.push(e=b(g)),e&&"__data__"in g&&(e.__data__=g.__data__)):d.push(null)}return S(c)}a.select=function(a){return b(function(b){return P(a,b)})},a.selectAll=function(a){return c(function(b){return Q(a,b)})},a.filter=function(b){var c=[],d,e,f;for(var g=0,h=a.length;g<h;g++){e=a[g],c.push(d=[]),d.parentNode=e.parentNode;for(var i=0,j=e.length;i<j;i++)(f=e[i])&&b.call(f,f.__data__,i)&&d.push(f)}return S(c)},a.map=function(b){var c,d;for(var e=0,f=a.length;e<f;e++){c=a[e];for(var g=0,h=c.length;g<h;g++)if(d=c[g])d.__data__=b.call(d,d.__data__,g)}return a},a.data=function(b,c){function g(a,b){var g=0,h=a.length,i=b.length,j=Math.min(h,i),k=Math.max(h,i),l=[],m=[],n=[],o,p;if(c){var q={},r=[],s,t=b.length;for(g=0;g<h;g++)s=c.call(o=a[g],o.__data__,g),s in q?n[t++]=a[g]:q[s]=o,r.push(s);for(g=0;g<i;g++)o=q[s=c.call(b,p=b[g],g)],o?(o.__data__=p,l[g]=o,m[g]=n[g]=null):(m[g]=V(p),l[g]=n[g]=null),delete q[s];for(g=0;g<h;g++)r[g]in q&&(n[g]=a[g])}else{for(;g<j;g++)o=a[g],p=b[g],o?(o.__data__=p,l[g]=o,m[g]=n[g]=null):(m[g]=V(p),l[g]=n[g]=null);for(;g<i;g++)m[g]=V(b[g]),l[g]=n[g]=null;for(;g<k;g++)n[g]=a[g],m[g]=l[g]=null}m.parentNode=l.parentNode=n.parentNode=a.parentNode,d.push(m),e.push(l),f.push(n)}var d=[],e=[],f=[],h=-1,i=a.length,j;if(typeof b=="function")while(++h<i)g(j=a[h],b.call(j,j.parentNode.__data__,h));else while(++h<i)g(j=a[h],b);var k=S(e);k.enter=function(){return T(d)},k.exit=function(){return S(f)};return k},a.each=function(b){for(var c=0,d=a.length;c<d;c++){var e=a[c];for(var f=0,g=e.length;f<g;f++){var h=e[f];h&&b.call(h,h.__data__,f)}}return a},a.empty=function(){return!d(function(){return!0})},a.node=function(){return d(function(){return this})},a.attr=function(b,c){function j(){var a=c.apply(this,arguments);a==null?this.removeAttributeNS(b.space,b.local):this.setAttributeNS(b.space,b.local,a)}function i(){var a=c.apply(this,arguments);a==null?this.removeAttribute(b):this.setAttribute(b,a)}function h(){this.setAttributeNS(b.space,b.local,c)}function g(){this.setAttribute(b,c)}function f(){this.removeAttributeNS(b.space,b.local)}function e(){this.removeAttribute(b)}b=d3.ns.qualify(b);if(arguments.length<2)return d(b.local?function(){return this.getAttributeNS(b.space,b.local)}:function(){return this.getAttribute(b)});return a.each(c==null?b.local?f:e:typeof c=="function"?b.local?j:i:b.local?h:g)},a.classed=function(b,c){function i(){(c.apply(this,arguments)?g:h).call(this)}function h(){if(a=this.classList)return a.remove(b);var a=this.className,c=a.baseVal!=null,d=c?a.baseVal:a;d=f(d.replace(e," ")),c?a.baseVal=d:this.className=d}function g(){if(a=this.classList)return a.add(b);var a=this.className,c=a.baseVal!=null,d=c?a.baseVal:a;e.lastIndex=0,e.test(d)||(d=f(d+" "+b),c?a.baseVal=d:this.className=d)}var e=new RegExp("(^|\\s+)"+d3.requote(b)+"(\\s+|$)","g");if(arguments.length<2)return d(function(){if(a=this.classList)return a.contains(b);var a=this.className;e.lastIndex=0;return e.test(a.baseVal!=null?a.baseVal:a)});return a.each(typeof c=="function"?i:c?g:h)},a.style=function(b,c,e){function h(){var a=c.apply(this,arguments);a==null?this.style.removeProperty(b):this.style.setProperty(b,a,e)}function g(){this.style.setProperty(b,c,e)}function f(){this.style.removeProperty(b)}arguments.length<3&&(e="");if(arguments.length<2)return d(function(){return window.getComputedStyle(this,null).getPropertyValue(b)});return a.each(c==null?f:typeof c=="function"?h:g)},a.property=function(b,c){function g(){var a=c.apply(this,arguments);a==null?delete this[b]:this[b]=a}function f(){this[b]=c}function e(){delete this[b]}b=d3.ns.qualify(b);if(arguments.length<2)return d(function(){return this[b]});return a.each(c==null?e:typeof c=="function"?g:f)},a.text=function(b){function e(){this.textContent=b.apply(this,arguments)}function c(){this.textContent=b}if(arguments.length<1)return d(function(){return this.textContent});return a.each(typeof b=="function"?e:c)},a.html=function(b){function e(){this.innerHTML=b.apply(this,arguments)}function c(){this.innerHTML=b}if(arguments.length<1)return d(function(){return this.innerHTML});return a.each(typeof b=="function"?e:c)},a.append=function(a){function d(b){return b.appendChild(document.createElementNS(a.space,a.local))}function c(b){return b.appendChild(document.createElement(a))}a=d3.ns.qualify(a);return b(a.local?d:c)},a.insert=function(a,c){function e(b){return b.insertBefore(document.createElementNS(a.space,a.local),P(c,b))}function d(b){return b.insertBefore(document.createElement(a),P(c,b))}a=d3.ns.qualify(a);return b(a.local?e:d)},a.remove=function(){return a.each(function(){var a=this.parentNode;a&&a.removeChild(this)})},a.sort=function(b){b=U.apply(this,arguments);for(var c=0,d=a.length;c<d;c++){var e=a[c];e.sort(b);for(var f=1,g=e.length,h=e[0];f<g;f++){var i=e[f];i&&(h&&h.parentNode.insertBefore(i,h.nextSibling),h=i)}}return a},a.on=function(b,c,d){arguments.length<3&&(d=!1);var e=b.indexOf("."),f=e===-1?b:b.substring(0,e),g="__on"+b;return a.each(function(a,b){function h(a){var d=d3.event;d3.event=a;try{c.call(this,e.__data__,b)}finally{d3.event=d}}this[g]&&this.removeEventListener(f,this[g],d),c&&this.addEventListener(f,this[g]=h,d);var e=this})},a.transition=function(){return Y(a)},a.call=g;return a}function O(a,b,c){function g(a){return Math.round(f(a)*255)}function f(a){a>360?a-=360:a<0&&(a+=360);if(a<60)return d+(e-d)*a/60;if(a<180)return e;if(a<240)return d+(e-d)*(240-a)/60;return d}var d,e;a=a%360,a<0&&(a+=360),b=b<0?0:b>1?1:b,c=c<0?0:c>1?1:c,e=c<=.5?c*(1+b):c+b-c*b,d=2*c-e;return E(g(a+120),g(a),g(a-120))}function N(a,b,c){this.h=a,this.s=b,this.l=c}function M(a,b,c){return new N(a,b,c)}function J(a){var b=parseFloat(a);return a.charAt(a.length-1)==="%"?Math.round(b*2.55):b}function I(a,b,c){var d=Math.min(a/=255,b/=255,c/=255),e=Math.max(a,b,c),f=e-d,g,h,i=(e+d)/2;f?(h=i<.5?f/(e+d):f/(2-e-d),a==e?g=(b-c)/f+(b<c?6:0):b==e?g=(c-a)/f+2:g=(a-b)/f+4,g*=60):h=g=0;return M(g,h,i)}function H(a,b,c){var d=0,e=0,f=0,g,h,i;g=/([a-z]+)\((.*)\)/i.exec(a);if(g){h=g[2].split(",");switch(g[1]){case"hsl":return c(parseFloat(h[0]),parseFloat(h[1])/100,parseFloat(h[2])/100);case"rgb":return b(J(h[0]),J(h[1]),J(h[2]))}}if(i=K[a])return b(i.r,i.g,i.b);a!=null&&a.charAt(0)==="#"&&(a.length===4?(d=a.charAt(1),d+=d,e=a.charAt(2),e+=e,f=a.charAt(3),f+=f):a.length===7&&(d=a.substring(1,3),e=a.substring(3,5),f=a.substring(5,7)),d=parseInt(d,16),e=parseInt(e,16),f=parseInt(f,16));return b(d,e,f)}function G(a){return a<16?"0"+a.toString(16):a.toString(16)}function F(a,b,c){this.r=a,this.g=b,this.b=c}function E(a,b,c){return new F(a,b,c)}function D(a,b){b=1/(b-(a=+a));return function(c){return Math.max(0,Math.min(1,(c-a)*b))}}function C(a,b){b=1/(b-(a=+a));return function(c){return(c-a)*b}}function B(a){return a in A||/\bcolor\b/.test(a)?d3.interpolateRgb:d3.interpolate}function y(a){return a<1/2.75?7.5625*a*a:a<2/2.75?7.5625*(a-=1.5/2.75)*a+.75:a<2.5/2.75?7.5625*(a-=2.25/2.75)*a+.9375:7.5625*(a-=2.625/2.75)*a+.984375}function x(a){a||(a=1.70158);return function(b){return b*b*((a+1)*b-a)}}function w(a,b){var c;arguments.length<2&&(b=.45),arguments.length<1?(a=1,c=b/4):c=b/(2*Math.PI)*Math.asin(1/a);return function(d){return 1+a*Math.pow(2,10*-d)*Math.sin((d-c)*2*Math.PI/b)}}function v(a){return 1-Math.sqrt(1-a*a)}function u(a){return a?Math.pow(2,10*(a-1))-.001:0}function t(a){return 1-Math.cos(a*Math.PI/2)}function s(a){return function(b){return Math.pow(b,a)}}function r(a){return a}function q(a){return function(b){return.5*(b<.5?a(2*b):2-a(2-2*b))}}function p(a){return function(b){return 1-a(1-b)}}function k(a){var b=a.lastIndexOf("."),c=b>=0?a.substring(b):(b=a.length,""),d=[];while(b>0)d.push(a.substring(b-=3,b+3));return d.reverse().join(",")+c}function i(a){var b={},c=[];b.add=function(a){for(var d=0;d<c.length;d++)if(c[d].listener==a)return b;c.push({listener:a,on:!0});return b},b.remove=function(a){for(var d=0;d<c.length;d++){var e=c[d];if(e.listener==a){e.on=!1,c=c.slice(0,d).concat(c.slice(d+1));break}}return b},b.dispatch=function(){var a=c;for(var b=0,d=a.length;b<d;b++){var e=a[b];e.on&&e.listener.apply(this,arguments)}};return b}function g(a){a.apply(this,(arguments[0]=this,arguments));return this}function f(a){return a.replace(/(^\s+)|(\s+$)/g,"").replace(/\s+/g," ")}function e(a){return a==null}function c(a){return Array.prototype.slice.call(a)}function b(a){var b=-1,c=a.length,d=[];while(++b<c)d.push(a[b]);return d}d3={version:"1.15.1"},Date.now||(Date.now=function(){return+(new Date)}),Object.create||(Object.create=function(a){function b(){}b.prototype=a;return new b});var a=c;try{a(document.documentElement.childNodes)[0].nodeType}catch(d){a=b}d3.functor=function(a){return typeof a=="function"?a:function(){return a}},d3.rebind=function(a,b){return function(){var c=b.apply(a,arguments);return arguments.length?a:c}},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 c=0,d=a.length,e=a[0],f;if(arguments.length===1)while(++c<d)e>(f=a[c])&&(e=f);else{e=b(a[0]);while(++c<d)e>(f=b(a[c]))&&(e=f)}return e},d3.max=function(a,b){var c=0,d=a.length,e=a[0],f;if(arguments.length===1)while(++c<d)e<(f=a[c])&&(e=f);else{e=b(e);while(++c<d)e<(f=b(a[c]))&&(e=f)}return e},d3.nest=function(){function g(a,d){if(d>=b.length)return a;var e=[],f=c[d++],h;for(h in a)e.push({key:h,values:g(a[h],d)});f&&e.sort(function(a,b){return f(a.key,b.key)});return e}function f(c,g){if(g>=b.length)return e?e.call(a,c):d?c.sort(d):c;var h=-1,i=c.length,j=b[g++],k,l,m={};while(++h<i)(k=j(l=c[h]))in m?m[k].push(l):m[k]=[l];for(k in m)m[k]=f(m[k],g);return m}var a={},b=[],c=[],d,e;a.map=function(a){return f(a,0)},a.entries=function(a){return g(f(a,0),0)},a.key=function(c){b.push(c);return a},a.sortKeys=function(d){c[b.length-1]=d;return a},a.sortValues=function(b){d=b;return a},a.rollup=function(b){e=b;return a};return a},d3.keys=function(a){var b=[];for(var c in a)b.push(c);return b},d3.values=function(a){var b=[];for(var c in a)b.push(a[c]);return b},d3.entries=function(a){var b=[];for(var c in a)b.push({key:c,value:a[c]});return b},d3.merge=function(a){return Array.prototype.concat.apply([],a)},d3.split=function(a,b){var c=[],d=[],f,g=-1,h=a.length;arguments.length<2&&(b=e);while(++g<h)b.call(d,f=a[g],g)?d=[]:(d.length||c.push(d),d.push(f));return c},d3.range=function(a,b,c){arguments.length===1&&(b=a,a=0),c==null&&(c=1);if((b-a)/c==Infinity)throw new Error("infinite range");var d=[],e=-1,f;if(c<0)while((f=a+c*++e)>b)d.push(f);else while((f=a+c*++e)<b)d.push(f);return d},d3.requote=function(a){return a.replace(h,"\\$&")};var h=/[\\\^\$\*\+\?\[\]\(\)\.\{\}]/g;d3.xhr=function(a,b,c){var d=new XMLHttpRequest;arguments.length<3?c=b:b&&d.overrideMimeType&&d.overrideMimeType(b),d.open("GET",a,!0),d.onreadystatechange=function(){d.readyState===4&&c(d.status<300?d:null)},d.send(null)},d3.text=function(a,b,c){function d(a){c(a&&a.responseText)}arguments.length<3&&(c=b,b=null),d3.xhr(a,b,d)},d3.json=function(a,b){d3.text(a,"application/json",function(a){b(a?JSON.parse(a):null)})},d3.html=function(a,b){d3.text(a,"text/html",function(a){if(a!=null){var c=document.createRange();c.selectNode(document.body),a=c.createContextualFragment(a)}b(a)})},d3.xml=function(a,b,c){function d(a){c(a&&a.responseXML)}arguments.length<3&&(c=b,b=null),d3.xhr(a,b,d)},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(a){var b={},c;for(var d=0,e=arguments.length;d<e;d++)c=arguments[d],b[c]=i(c);return b},d3.format=function(a){var b=j.exec(a),c=b[1]||" ",d=b[3]||"",e=b[5],f=+b[6],g=b[7],h=b[8],i=b[9];h&&(h=h.substring(1)),e&&(c="0",g&&(f-=Math.floor((f-1)/4))),i==="d"&&(h="0");return function(a){var b=+a,j=b<0&&(b=-b)?"−":d;if(i==="d"&&b%1)return"";h?a=b.toFixed(h):a=""+b;if(e){var l=a.length+j.length;l<f&&(a=Array(f-l+1).join(c)+a),g&&(a=k(a)),a=j+a}else{g&&(a=k(a)),a=j+a;var l=a.length;l<f&&(a=Array(f-l+1).join(c)+a)}return a}};var j=/(?:([^{])?([<>=^]))?([+\- ])?(#)?(0)?([0-9]+)?(,)?(\.[0-9]+)?([a-zA-Z%])?/,l=s(2),m=s(3),n={linear:function(){return r},poly:s,quad:function(){return l},cubic:function(){return m},sin:function(){return t},exp:function(){return u},circle:function(){return v},elastic:w,back:x,bounce:function(){return y}},o={"in":function(a){return a},out:p,"in-out":q,"out-in":function(a){return q(p(a))}};d3.ease=function(a){var b=a.indexOf("-"),c=b>=0?a.substring(0,b):a,d=b>=0?a.substring(b+1):"in";return o[d](n[c].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 K||/^(#|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(c){return a+b*c}},d3.interpolateRound=function(a,b){b-=a;return function(c){return Math.round(a+b*c)}},d3.interpolateString=function(a,b){var c,d,e,f=0,g=0,h=[],i=[],j,k;z.lastIndex=0;for(d=0;c=z.exec(b);++d)c.index&&h.push(b.substring(f,g=c.index)),i.push({i:h.length,x:c[0]}),h.push(null),f=z.lastIndex;f<b.length&&h.push(b.substring(f));for(d=0,j=i.length;(c=z.exec(a))&&d<j;++d){k=i[d];if(k.x==c[0]){if(k.i)if(h[k.i+1]==null){h[k.i-1]+=k.x,h.splice(k.i,1);for(e=d+1;e<j;++e)i[e].i--}else{h[k.i-1]+=k.x+h[k.i+1],h.splice(k.i,2);for(e=d+1;e<j;++e)i[e].i-=2}else if(h[k.i+1]==null)h[k.i]=k.x;else{h[k.i]=k.x+h[k.i+1],h.splice(k.i+1,1);for(e=d+1;e<j;++e)i[e].i--}i.splice(d,1),j--,d--}else k.x=d3.interpolateNumber(parseFloat(c[0]),parseFloat(k.x))}while(d<j)k=i.pop(),h[k.i+1]==null?h[k.i]=k.x:(h[k.i]=k.x+h[k.i+1],h.splice(k.i+1,1)),j--;if(h.length===1)return h[0]==null?i[0].x:function(){return b};return function(a){for(d=0;d<j;++d)h[(k=i[d]).i]=k.x(a);return h.join("")}},d3.interpolateRgb=function(a,b){a=d3.rgb(a),b=d3.rgb(b);var c=a.r,d=a.g,e=a.b,f=b.r-c,g=b.g-d,h=b.b-e;return function(a){return"rgb("+Math.round(c+f*a)+","+Math.round(d+g*a)+","+Math.round(e+h*a)+")"}},d3.interpolateHsl=function(a,b){a=d3.hsl(a),b=d3.hsl(b);var c=a.h,d=a.s,e=a.l,f=b.h-c,g=b.s-d,h=b.l-e;return function(a){return O(c+f*a,d+g*a,e+h*a).toString()}},d3.interpolateArray=function(a,b){var c=[],d=[],e=a.length,f=b.length,g=Math.min(a.length,b.length),h;for(h=0;h<g;++h)c.push(d3.interpolate(a[h],b[h]));for(;h<e;++h)d[h]=a[h];for(;h<f;++h)d[h]=b[h];return function(a){for(h=0;h<g;++h)d[h]=c[h](a);return d}},d3.interpolateObject=function(a,b){var c={},d={},e;for(e in a)e in b?c[e]=B(e)(a[e],b[e]):d[e]=a[e];for(e in b)e in a||(d[e]=b[e]);return function(a){for(e in c)d[e]=c[e](a);return d}};var z=/[-+]?(?:\d+\.\d+|\d+\.|\.\d+|\d+)(?:[eE][-]?\d+)?/g,A={background:1,fill:1,stroke:1};d3.rgb=function(a,b,c){return arguments.length===1?H(""+a,E,O):E(~~a,~~b,~~c)},F.prototype.brighter=function(a){a=Math.pow(.7,arguments.length?a:1);var b=this.r,c=this.g,d=this.b,e=30;if(!b&&!c&&!d)return E(e,e,e);b&&b<e&&(b=e),c&&c<e&&(c=e),d&&d<e&&(d=e);return E(Math.min(255,Math.floor(b/a)),Math.min(255,Math.floor(c/a)),Math.min(255,Math.floor(d/a)))},F.prototype.darker=function(a){a=Math.pow(.7,arguments.length?a:1);return E(Math.max(0,Math.floor(a*this.r)),Math.max(0,Math.floor(a*this.g)),Math.max(0,Math.floor(a*this.b)))},F.prototype.hsl=function(){return I(this.r,this.g,this.b)},F.prototype.toString=function(){return"#"+G(this.r)+G(this.g)+G(this.b)};var K={aliceblue:"#f0f8ff",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",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",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",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",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",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"};for(var L in K)K[L]=H(K[L],E,O);d3.hsl=function(a,b,c){return arguments.length===1?H(""+a,I,M):M(+a,+b,+c)},N.prototype.brighter=function(a){a=Math.pow(.7,arguments.length?a:1);return M(this.h,this.s,this.l/a)},N.prototype.darker=function(a){a=Math.pow(.7,arguments.length?a:1);return M(this.h,this.s,a*this.l)},N.prototype.rgb=function(){return O(this.h,this.s,this.l)},N.prototype.toString=function(){return"hsl("+this.h+","+this.s*100+"%,"+this.l*100+"%)"};var P=function(a,b){return b.querySelector(a)},Q=function(b,c){return a(c.querySelectorAll(b))};typeof Sizzle=="function"&&(P=function(a,b){return Sizzle(a,b)[0]},Q=function(a,b){return Sizzle.uniqueSort(Sizzle(a,b))});var R=S([[document]]);R[0].parentNode=document.documentElement,d3.select=function(a){return typeof a=="string"?R.select(a):S([[a]])},d3.selectAll=function(b){return typeof b=="string"?R.selectAll(b):S([a(b)])},d3.transition=R.transition;var W=0,X=0,$=null,_,ba;d3.timer=function(a){bb(a,0)},d3.timer.flush=function(){var a,b=Date.now(),c=$;while(c)a=b-c.then,c.delay||(c.flush=c.callback(a)),c=c.next;bd()};var be=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(a){setTimeout(a,17)};d3.scale={},d3.scale.linear=function(){function i(b){var c=d3.min(a),d=d3.max(a),e=d-c,f=Math.pow(10,Math.floor(Math.log(e/b)/Math.LN10)),g=b/(e/f);g<=.15?f*=10:g<=.35?f*=5:g<=.75&&(f*=2);return{start:Math.ceil(c/f)*f,stop:Math.floor(d/f)*f+f*.5,step:f}}function h(a){return e(a)}function g(){var g=a.length==2?bf:bg,i=d?D:C;e=g(a,b,i,c),f=g(b,a,i,d3.interpolate);return h}var a=[0,1],b=[0,1],c=d3.interpolate,d=!1,e,f;h.invert=function(a){return f(a)},h.domain=function(b){if(!arguments.length)return a;a=b.map(Number);return g()},h.range=function(a){if(!arguments.length)return b;b=a;return g()},h.rangeRound=function(a){return h.range(a).interpolate(d3.interpolateRound)},h.clamp=function(a){if(!arguments.length)return d;d=a;return g()},h.interpolate=function(a){if(!arguments.length)return c;c=a;return g()},h.ticks=function(a){var b=i(a);return d3.range(b.start,b.stop,b.step)},h.tickFormat=function(a){var b=Math.max(0,-Math.floor(Math.log(i(a).step)/Math.LN10+.01));return d3.format(",."+b+"f")};return g()},d3.scale.log=function(){function d(c){return a(b(c))}var a=d3.scale.linear(),b=bh,c=b.pow;d.invert=function(b){return c(a.invert(b))},d.domain=function(e){if(!arguments.length)return a.domain().map(c);b=(e[0]||e[1])<0?bi:bh,c=b.pow,a.domain(e.map(b));return d},d.range=d3.rebind(d,a.range),d.rangeRound=d3.rebind(d,a.rangeRound),d.interpolate=d3.rebind(d,a.interpolate),d.clamp=d3.rebind(d,a.clamp),d.ticks=function(){var d=a.domain(),e=[];if(d.every(isFinite)){var f=Math.floor(d[0]),g=Math.ceil(d[1]),h=c(d[0]),i=c(d[1]);if(b===bi){e.push(c(f));for(;f++<g;)for(var j=9;j>0;j--)e.push(c(f)*j)}else{for(;f<g;f++)for(var j=1;j<10;j++)e.push(c(f)*j);e.push(c(f))}for(f=0;e[f]<h;f++);for(g=e.length;e[g-1]>i;g--);e=e.slice(f,g)}return e},d.tickFormat=function(){return function(a){return a.toPrecision(1)}};return d},bh.pow=function(a){return Math.pow(10,a)},bi.pow=function(a){return-Math.pow(10,-a)},d3.scale.pow=function(){function f(b){return a(d(b))}var a=d3.scale.linear(),b=d3.scale.linear(),c=1,d=Number,e=d;f.invert=function(b){return e(a.invert(b))},f.domain=function(g){if(!arguments.length)return a.domain().map(e);var h=(g[0]||g[1])<0?bk:bj;d=h(c),e=h(1/c),a.domain(g.map(d)),b.domain(g);return f},f.range=d3.rebind(f,a.range),f.rangeRound=d3.rebind(f,a.rangeRound),f.interpolate=d3.rebind(f,a.interpolate),f.clamp=d3.rebind(f,a.clamp),f.ticks=b.ticks,f.tickFormat=b.tickFormat,f.exponent=function(a){if(!arguments.length)return c;var b=f.domain();c=a;return f.domain(b)};return f},d3.scale.sqrt=function(){return d3.scale.pow().exponent(.5)},d3.scale.ordinal=function(){function e(d){var e=d in b?b[d]:b[d]=a.push(d)-1;return c[e%c.length]}var a=[],b={},c=[],d=0;e.domain=function(c){if(!arguments.length)return a;a=c,b={};var d=-1,f=-1,g=a.length;while(++d<g)c=a[d],c in b||(b[c]=++f);return e},e.range=function(a){if(!arguments.length)return c;c=a;return e},e.rangePoints=function(b,f){arguments.length<2&&(f=0);var g=b[0],h=b[1],i=(h-g)/(a.length-1+f);c=a.length==1?[(g+h)/2]:d3.range(g+i*f/2,h+i/2,i),d=0;return e},e.rangeBands=function(b,f){arguments.length<2&&(f=0);var g=b[0],h=b[1],i=(h-g)/(a.length+f);c=d3.range(g+i*f,h,i),d=i*(1-f);return e},e.rangeRoundBands=function(b,f){arguments.length<2&&(f=0);var g=b[0],h=b[1],i=h-g,j=Math.floor(i/(a.length+f)),k=i-(a.length-f)*j;c=d3.range(g+Math.round(k/2),h,j),d=Math.round(j*(1-f));return e},e.rangeBand=function(){return d};return e},d3.scale.category10=function(){return d3.scale.ordinal().range(bl)},d3.scale.category20=function(){return d3.scale.ordinal().range(bm)},d3.scale.category20b=function(){return d3.scale.ordinal().range(bn)},d3.scale.category20c=function(){return d3.scale.ordinal().range(bo)};var bl=["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"],bm=["#1f77b4","#aec7e8","#ff7f0e","#ffbb78","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd" <del>,"#c5b0d5","#8c564b","#c49c94","#e377c2","#f7b6d2","#7f7f7f","#c7c7c7","#bcbd22","#dbdb8d","#17becf","#9edae5"],bn=["#393b79","#5254a3","#6b6ecf","#9c9ede","#637939","#8ca252","#b5cf6b","#cedb9c","#8c6d31","#bd9e39","#e7ba52","#e7cb94","#843c39","#ad494a","#d6616b","#e7969c","#7b4173","#a55194","#ce6dbd","#de9ed6"],bo=["#3182bd","#6baed6","#9ecae1","#c6dbef","#e6550d","#fd8d3c","#fdae6b","#fdd0a2","#31a354","#74c476","#a1d99b","#c7e9c0","#756bb1","#9e9ac8","#bcbddc","#dadaeb","#636363","#969696","#bdbdbd","#d9d9d9"];d3.scale.quantile=function(){function f(a){return b[e(a)]}function e(a){if(isNaN(a=+a))return NaN;var b=0,d=c.length-1;while(b<=d){var e=b+d>>1,f=c[e];if(f<a)b=e+1;else if(f>a)d=e-1;else return e}return d<0?0:d}function d(){var d=-1,e=c.length=b.length,f=a.length/e;while(++d<e)c[d]=a[~~(d*f)]}var a=[],b=[],c=[];f.domain=function(b){if(!arguments.length)return a;a=b.filter(function(a){return!isNaN(a)}).sort(d3.ascending),d();return f},f.range=function(a){if(!arguments.length)return b;b=a,d();return f},f.quantiles=function(){return c};return f},d3.scale.quantize=function(){function f(b){return e[Math.max(0,Math.min(d,Math.floor(c*(b-a))))]}var a=0,b=1,c=2,d=1,e=[0,1];f.domain=function(d){if(!arguments.length)return[a,b];a=d[0],b=d[1],c=e.length/(b-a);return f},f.range=function(g){if(!arguments.length)return e;e=g,c=e.length/(b-a),d=e.length-1;return f};return f},d3.svg={},d3.svg.arc=function(){function e(){var e=a.apply(this,arguments),f=b.apply(this,arguments),g=c.apply(this,arguments)+bp,h=d.apply(this,arguments)+bp,i=h-g,j=i<Math.PI?"0":"1",k=Math.cos(g),l=Math.sin(g),m=Math.cos(h),n=Math.sin(h);return i>=bq?e?"M0,"+f+"A"+f+","+f+" 0 1,1 0,"+ -f+"A"+f+","+f+" 0 1,1 0,"+f+"M0,"+e+"A"+e+","+e+" 0 1,1 0,"+ -e+"A"+e+","+e+" 0 1,1 0,"+e+"Z":"M0,"+f+"A"+f+","+f+" 0 1,1 0,"+ -f+"A"+f+","+f+" 0 1,1 0,"+f+"Z":e?"M"+f*k+","+f*l+"A"+f+","+f+" 0 "+j+",1 "+f*m+","+f*n+"L"+e*m+","+e*n+"A"+e+","+e+" 0 "+j+",0 "+e*k+","+e*l+"Z":"M"+f*k+","+f*l+"A"+f+","+f+" 0 "+j+",1 "+f*m+","+f*n+"L0,0"+"Z"}var a=br,b=bs,c=bt,d=bu;e.innerRadius=function(b){if(!arguments.length)return a;a=d3.functor(b);return e},e.outerRadius=function(a){if(!arguments.length)return b;b=d3.functor(a);return e},e.startAngle=function(a){if(!arguments.length)return c;c=d3.functor(a);return e},e.endAngle=function(a){if(!arguments.length)return d;d=d3.functor(a);return e},e.centroid=function(){var e=(a.apply(this,arguments)+b.apply(this,arguments))/2,f=(c.apply(this,arguments)+d.apply(this,arguments))/2+bp;return[Math.cos(f)*e,Math.sin(f)*e]};return e};var bp=-Math.PI/2,bq=2*Math.PI-1e-6;d3.svg.line=function(){function f(c){return c.length<1?null:"M"+d(bv(this,c,a,b),e)}var a=bw,b=bx,c="linear",d=by[c],e=.7;f.x=function(b){if(!arguments.length)return a;a=b;return f},f.y=function(a){if(!arguments.length)return b;b=a;return f},f.interpolate=function(a){if(!arguments.length)return c;d=by[c=a];return f},f.tension=function(a){if(!arguments.length)return e;e=a;return f};return f};var by={linear:bz,"step-before":bA,"step-after":bB,basis:bH,"basis-open":bI,"basis-closed":bJ,cardinal:bE,"cardinal-open":bC,"cardinal-closed":bD,monotone:bS},bL=[0,2/3,1/3,0],bM=[0,1/3,2/3,0],bN=[0,1/6,2/3,1/6];d3.svg.area=function(){function g(d){return d.length<1?null:"M"+e(bv(this,d,a,c),f)+"L"+e(bv(this,d,a,b).reverse(),f)+"Z"}var a=bw,b=bT,c=bx,d="linear",e=by[d],f=.7;g.x=function(b){if(!arguments.length)return a;a=b;return g},g.y0=function(a){if(!arguments.length)return b;b=a;return g},g.y1=function(a){if(!arguments.length)return c;c=a;return g},g.interpolate=function(a){if(!arguments.length)return d;e=by[d=a];return g},g.tension=function(a){if(!arguments.length)return f;f=a;return g};return g},d3.svg.chord=function(){function j(a,b,c,d){return"Q 0,0 "+d}function i(a,b){return"A"+a+","+a+" 0 0,1 "+b}function h(a,b){return a.a0==b.a0&&a.a1==b.a1}function g(a,b,f,g){var h=b.call(a,f,g),i=c.call(a,h,g),j=d.call(a,h,g)+bp,k=e.call(a,h,g)+bp;return{r:i,a0:j,a1:k,p0:[i*Math.cos(j),i*Math.sin(j)],p1:[i*Math.cos(k),i*Math.sin(k)]}}function f(c,d){var e=g(this,a,c,d),f=g(this,b,c,d);return"M"+e.p0+i(e.r,e.p1)+(h(e,f)?j(e.r,e.p1,e.r,e.p0):j(e.r,e.p1,f.r,f.p0)+i(f.r,f.p1)+j(f.r,f.p1,e.r,e.p0))+"Z"}var a=bU,b=bV,c=bW,d=bt,e=bu;f.radius=function(a){if(!arguments.length)return c;c=d3.functor(a);return f},f.source=function(b){if(!arguments.length)return a;a=d3.functor(b);return f},f.target=function(a){if(!arguments.length)return b;b=d3.functor(a);return f},f.startAngle=function(a){if(!arguments.length)return d;d=d3.functor(a);return f},f.endAngle=function(a){if(!arguments.length)return e;e=d3.functor(a);return f};return f},d3.svg.diagonal=function(){function d(d,e){var f=a.call(this,d,e),g=b.call(this,d,e),h=(f.y+g.y)/2,i=[f,{x:f.x,y:h},{x:g.x,y:h},g];i=i.map(c);return"M"+i[0]+"C"+i[1]+" "+i[2]+" "+i[3]}var a=bU,b=bV,c=bZ;d.source=function(b){if(!arguments.length)return a;a=d3.functor(b);return d},d.target=function(a){if(!arguments.length)return b;b=d3.functor(a);return d},d.projection=function(a){if(!arguments.length)return c;c=a;return d};return d},d3.svg.mouse=function(a){return b_(a,[d3.event])[0]};var b$=/WebKit/.test(navigator.userAgent)?-1:0;d3.svg.touches=function(b){var c=d3.event.touches;return c&&c.length?b_(b,a(c)):[]},d3.svg.symbol=function(){function c(c,d){return(cc[a.call(this,c,d)]||cc.circle)(b.call(this,c,d))}var a=cb,b=ca;c.type=function(b){if(!arguments.length)return a;a=d3.functor(b);return c},c.size=function(a){if(!arguments.length)return b;b=d3.functor(a);return c};return c},d3.svg.symbolTypes=["circle","cross","diamond","square","triangle-down","triangle-up"];var cc={circle:function(a){var b=Math.sqrt(a/Math.PI);return"M0,"+b+"A"+b+","+b+" 0 1,1 0,"+ -b+"A"+b+","+b+" 0 1,1 0,"+b+"Z"},cross:function(a){var b=Math.sqrt(a/5)/2;return"M"+ -3*b+","+ -b+"H"+ -b+"V"+ -3*b+"H"+b+"V"+ -b+"H"+3*b+"V"+b+"H"+b+"V"+3*b+"H"+ -b+"V"+b+"H"+ -3*b+"Z"},diamond:function(a){var b=Math.sqrt(a/(2*ce)),c=b*ce;return"M0,"+ -b+"L"+c+",0"+" 0,"+b+" "+ -c+",0"+"Z"},square:function(a){var b=Math.sqrt(a)/2;return"M"+ -b+","+ -b+"L"+b+","+ -b+" "+b+","+b+" "+ -b+","+b+"Z"},"triangle-down":function(a){var b=Math.sqrt(a/cd),c=b*cd/2;return"M0,"+c+"L"+b+","+ -c+" "+ -b+","+ -c+"Z"},"triangle-up":function(a){var b=Math.sqrt(a/cd),c=b*cd/2;return"M0,"+ -c+"L"+b+","+c+" "+ -b+","+c+"Z"}},cd=Math.sqrt(3),ce=Math.tan(30*Math.PI/180)})() <ide>\ No newline at end of file <add>(function(){function cb(){return"circle"}function ca(){return 64}function b_(a,b){var c=(a.ownerSVGElement||a).createSVGPoint();if(b$<0&&(window.scrollX||window.scrollY)){var d=d3.select(document.body).append("svg:svg").style("position","absolute").style("top",0).style("left",0),e=d[0][0].getScreenCTM();b$=!e.f&&!e.e,d.remove()}var f=-1,g=b.length,h=[];while(++f<g){var i=b[f];b$?(c.x=i.pageX,c.y=i.pageY):(c.x=i.clientX,c.y=i.clientY),c=c.matrixTransform(a.getScreenCTM().inverse()),h.push([c.x,c.y])}return h}function bZ(a){return[a.x,a.y]}function bY(a){return a.endAngle}function bX(a){return a.startAngle}function bW(a){return a.radius}function bV(a){return a.target}function bU(a){return a.source}function bT(){return 0}function bS(a){return a.length<3?bz(a):a[0]+bF(a,bR(a))}function bR(a){var b=[],c,d,e,f,g=bQ(a),h=-1,i=a.length-1;while(++h<i)c=bP(a[h],a[h+1]),Math.abs(c)<1e-6?g[h]=g[h+1]=0:(d=g[h]/c,e=g[h+1]/c,f=d*d+e*e,f>9&&(f=c*3/Math.sqrt(f),g[h]=f*d,g[h+1]=f*e));h=-1;while(++h<=i)f=(a[Math.min(i,h+1)][0]-a[Math.max(0,h-1)][0])/(6*(1+g[h]*g[h])),b.push([f||0,g[h]*f||0]);return b}function bQ(a){var b=0,c=a.length-1,d=[],e=a[0],f=a[1],g=d[0]=bP(e,f);while(++b<c)d[b]=g+(g=bP(e=f,f=a[b+1]));d[b]=g;return d}function bP(a,b){return(b[1]-a[1])/(b[0]-a[0])}function bO(a,b,c){a.push("C",bK(bL,b),",",bK(bL,c),",",bK(bM,b),",",bK(bM,c),",",bK(bN,b),",",bK(bN,c))}function bK(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3]}function bJ(a){var b,c=-1,d=a.length,e=d+4,f,g=[],h=[];while(++c<4)f=a[c%d],g.push(f[0]),h.push(f[1]);b=[bK(bN,g),",",bK(bN,h)],--c;while(++c<e)f=a[c%d],g.shift(),g.push(f[0]),h.shift(),h.push(f[1]),bO(b,g,h);return b.join("")}function bI(a){if(a.length<4)return bz(a);var b=[],c=-1,d=a.length,e,f=[0],g=[0];while(++c<3)e=a[c],f.push(e[0]),g.push(e[1]);b.push(bK(bN,f)+","+bK(bN,g)),--c;while(++c<d)e=a[c],f.shift(),f.push(e[0]),g.shift(),g.push(e[1]),bO(b,f,g);return b.join("")}function bH(a){if(a.length<3)return bz(a);var b=[],c=1,d=a.length,e=a[0],f=e[0],g=e[1],h=[f,f,f,(e=a[1])[0]],i=[g,g,g,e[1]];b.push(f,",",g),bO(b,h,i);while(++c<d)e=a[c],h.shift(),h.push(e[0]),i.shift(),i.push(e[1]),bO(b,h,i);c=-1;while(++c<2)h.shift(),h.push(e[0]),i.shift(),i.push(e[1]),bO(b,h,i);return b.join("")}function bG(a,b){var c=[],d=(1-b)/2,e,f=a[0],g=a[1],h=1,i=a.length;while(++h<i)e=f,f=g,g=a[h],c.push([d*(g[0]-e[0]),d*(g[1]-e[1])]);return c}function bF(a,b){if(b.length<1||a.length!=b.length&&a.length!=b.length+2)return bz(a);var c=a.length!=b.length,d="",e=a[0],f=a[1],g=b[0],h=g,i=1;c&&(d+="Q"+(f[0]-g[0]*2/3)+","+(f[1]-g[1]*2/3)+","+f[0]+","+f[1],e=a[1],i=2);if(b.length>1){h=b[1],f=a[i],i++,d+="C"+(e[0]+g[0])+","+(e[1]+g[1])+","+(f[0]-h[0])+","+(f[1]-h[1])+","+f[0]+","+f[1];for(var j=2;j<b.length;j++,i++)f=a[i],h=b[j],d+="S"+(f[0]-h[0])+","+(f[1]-h[1])+","+f[0]+","+f[1]}if(c){var k=a[i];d+="Q"+(f[0]+h[0]*2/3)+","+(f[1]+h[1]*2/3)+","+k[0]+","+k[1]}return d}function bE(a,b,c){return a.length<3?bz(a):a[0]+bF(a,bG(a,b))}function bD(a,b){return a.length<3?bz(a):a[0]+bF((a.push(a[0]),a),bG([a[a.length-2]].concat(a,[a[1]]),b))}function bC(a,b){return a.length<4?bz(a):a[1]+bF(a.slice(1,a.length-1),bG(a,b))}function bB(a){var b=[],c=0,d=a.length,e=a[0];b.push(e[0],",",e[1]);while(++c<d)b.push("H",(e=a[c])[0],"V",e[1]);return b.join("")}function bA(a){var b=[],c=0,d=a.length,e=a[0];b.push(e[0],",",e[1]);while(++c<d)b.push("V",(e=a[c])[1],"H",e[0]);return b.join("")}function bz(a){var b=[],c=0,d=a.length,e=a[0];b.push(e[0],",",e[1]);while(++c<d)b.push("L",(e=a[c])[0],",",e[1]);return b.join("")}function bx(a){return a[1]}function bw(a){return a[0]}function bv(a,b,c,d){var e=[],f=-1,g=b.length,h=typeof c=="function",i=typeof d=="function",j;if(h&&i)while(++f<g)e.push([c.call(a,j=b[f],f),d.call(a,j,f)]);else if(h)while(++f<g)e.push([c.call(a,b[f],f),d]);else if(i)while(++f<g)e.push([c,d.call(a,b[f],f)]);else while(++f<g)e.push([c,d]);return e}function bu(a){return a.endAngle}function bt(a){return a.startAngle}function bs(a){return a.outerRadius}function br(a){return a.innerRadius}function bk(a){return function(b){return-Math.pow(-b,a)}}function bj(a){return function(b){return Math.pow(b,a)}}function bi(a){return-Math.log(-a)/Math.LN10}function bh(a){return Math.log(a)/Math.LN10}function bg(a,b,c,d){function i(b){var c=1,d=a.length-2;while(c<=d){var e=c+d>>1,f=a[e];if(f<b)c=e+1;else if(f>b)d=e-1;else return e}return c-1}var e=[],f=[],g=0,h=a.length;while(++g<h)e.push(c(a[g-1],a[g])),f.push(d(b[g-1],b[g]));return function(a){var b=i(a);return f[b](e[b](a))}}function bf(a,b,c,d){var e=c(a[0],a[1]),f=d(b[0],b[1]);return function(a){return f(e(a))}}function bd(){var a=null,b=$,c=Infinity;while(b)b.flush?b=a?a.next=b.next:$=b.next:(c=Math.min(c,b.then+b.delay),b=(a=b).next);return c}function bc(){var a,b=Date.now(),c=$;while(c)a=b-c.then,a>c.delay&&(c.flush=c.callback(a)),c=c.next;var d=bd()-b;d>24?(isFinite(d)&&(clearTimeout(ba),ba=setTimeout(bc,d)),_=0):(_=1,be(bc))}function bb(a,b){var c=Date.now(),d=!1,e,f=$;if(!!isFinite(b)){while(f){if(f.callback===a){f.then=c,f.delay=b,d=!0;break}e=f,f=f.next}d||($={callback:a,then:c,delay:b,next:$}),_||(ba=clearTimeout(ba),_=1,be(bc))}}function Z(a){return typeof a=="function"?function(b,c,d){return d3.interpolate(d,String(a.call(this,b,c)))}:(a=String(a),function(b,c,d){return d3.interpolate(d,a)})}function Y(a){function n(b){var g=!0,l=-1;a.each(function(){if(i[++l]!==2){var a=(b-j[l])/k[l],n=this.__transition__,o,p,q=e[l];if(a<1){g=!1;if(a<0)return}else a=1;if(i[l]){if(!n||n.active!==c){i[l]=2;return}}else{if(!n||n.active>c){i[l]=2;return}i[l]=1,h.start.dispatch.apply(this,arguments),q=e[l]={},n.active=c;for(p in d)if(o=d[p].apply(this,arguments))q[p]=o}o=m(a);for(p in q)q[p].call(this,o);if(a===1){i[l]=2;if(n.active===c){var r=n.owner;r===c&&(delete this.__transition__,f&&this.parentNode.removeChild(this)),X=c,h.end.dispatch.apply(this,arguments),X=0,n.owner=r}}}});return g}var b={},c=X||++W,d={},e=[],f=!1,h=d3.dispatch("start","end"),i=[],j=[],k=[],l,m=d3.ease("cubic-in-out");a.each(function(){(this.__transition__||(this.__transition__={})).owner=c}),b.delay=function(c){var d=Infinity,e=-1;typeof c=="function"?a.each(function(a,b){var f=j[++e]=+c.apply(this,arguments);f<d&&(d=f)}):(d=+c,a.each(function(a,b){j[++e]=d})),bb(n,d);return b},b.duration=function(c){var d=-1;typeof c=="function"?(l=0,a.each(function(a,b){var e=k[++d]=+c.apply(this,arguments);e>l&&(l=e)})):(l=+c,a.each(function(a,b){k[++d]=l}));return b},b.ease=function(a){m=typeof a=="function"?a:d3.ease.apply(d3,arguments);return b},b.attrTween=function(a,c){function f(b,d){var e=c.call(this,b,d,this.getAttributeNS(a.space,a.local));return function(b){this.setAttributeNS(a.space,a.local,e(b))}}function e(b,d){var e=c.call(this,b,d,this.getAttribute(a));return function(b){this.setAttribute(a,e(b))}}d["attr."+a]=a.local?f:e;return b},b.attr=function(a,c){return b.attrTween(a,Z(c))},b.styleTween=function(a,c,e){function f(b,d){var f=c.call(this,b,d,window.getComputedStyle(this,null).getPropertyValue(a));return function(b){this.style.setProperty(a,f(b),e)}}arguments.length<3&&(e=null),d["style."+a]=f;return b},b.style=function(a,c,d){arguments.length<3&&(d=null);return b.styleTween(a,Z(c),d)},b.text=function(a){d.text=function(b,c){this.textContent=typeof a=="function"?a.call(this,b,c):a};return b},b.select=function(b){var c,d=Y(a.select(b)).ease(m);c=-1,d.delay(function(a,b){return j[++c]}),c=-1,d.duration(function(a,b){return k[++c]});return d},b.selectAll=function(b){var c,d=Y(a.selectAll(b)).ease(m);c=-1,d.delay(function(a,b){return j[b?c:++c]}),c=-1,d.duration(function(a,b){return k[b?c:++c]});return d},b.remove=function(){f=!0;return b},b.each=function(a,c){h[a].add(c);return b},b.call=g;return b.delay(0).duration(250)}function V(a){return{__data__:a}}function U(a){arguments.length||(a=d3.ascending);return function(b,c){return a(b&&b.__data__,c&&c.__data__)}}function T(a){function b(b){var c=[],d,e,f,g;for(var h=0,i=a.length;h<i;h++){f=a[h],c.push(d=[]),d.parentNode=f.parentNode;for(var j=0,k=f.length;j<k;j++)(g=f[j])?(d.push(e=b(f.parentNode)),e.__data__=g.__data__):d.push(null)}return S(c)}a.append=function(a){function d(b){return b.appendChild(document.createElementNS(a.space,a.local))}function c(b){return b.appendChild(document.createElement(a))}a=d3.ns.qualify(a);return b(a.local?d:c)},a.insert=function(a,c){function e(b){return b.insertBefore(document.createElementNS(a.space,a.local),P(c,b))}function d(b){return b.insertBefore(document.createElement(a),P(c,b))}a=d3.ns.qualify(a);return b(a.local?e:d)};return a}function S(a){function d(b){for(var c=0,d=a.length;c<d;c++){var e=a[c];for(var f=0,g=e.length;f<g;f++){var h=e[f];if(h)return b.call(h,h.__data__,f)}}return null}function c(b){var c=[],d,e,f;for(var g=0,h=a.length;g<h;g++){e=a[g];for(var i=0,j=e.length;i<j;i++)if(f=e[i])c.push(d=b(f)),d.parentNode=f}return S(c)}function b(b){var c=[],d,e,f,g;for(var h=0,i=a.length;h<i;h++){f=a[h],c.push(d=[]),d.parentNode=f.parentNode;for(var j=0,k=f.length;j<k;j++)(g=f[j])?(d.push(e=b(g)),e&&"__data__"in g&&(e.__data__=g.__data__)):d.push(null)}return S(c)}a.select=function(a){return b(function(b){return P(a,b)})},a.selectAll=function(a){return c(function(b){return Q(a,b)})},a.filter=function(b){var c=[],d,e,f;for(var g=0,h=a.length;g<h;g++){e=a[g],c.push(d=[]),d.parentNode=e.parentNode;for(var i=0,j=e.length;i<j;i++)(f=e[i])&&b.call(f,f.__data__,i)&&d.push(f)}return S(c)},a.map=function(b){var c,d;for(var e=0,f=a.length;e<f;e++){c=a[e];for(var g=0,h=c.length;g<h;g++)if(d=c[g])d.__data__=b.call(d,d.__data__,g)}return a},a.data=function(b,c){function g(a,b){var g=0,h=a.length,i=b.length,j=Math.min(h,i),k=Math.max(h,i),l=[],m=[],n=[],o,p;if(c){var q={},r=[],s,t=b.length;for(g=0;g<h;g++)s=c.call(o=a[g],o.__data__,g),s in q?n[t++]=a[g]:q[s]=o,r.push(s);for(g=0;g<i;g++)o=q[s=c.call(b,p=b[g],g)],o?(o.__data__=p,l[g]=o,m[g]=n[g]=null):(m[g]=V(p),l[g]=n[g]=null),delete q[s];for(g=0;g<h;g++)r[g]in q&&(n[g]=a[g])}else{for(;g<j;g++)o=a[g],p=b[g],o?(o.__data__=p,l[g]=o,m[g]=n[g]=null):(m[g]=V(p),l[g]=n[g]=null);for(;g<i;g++)m[g]=V(b[g]),l[g]=n[g]=null;for(;g<k;g++)n[g]=a[g],m[g]=l[g]=null}m.parentNode=l.parentNode=n.parentNode=a.parentNode,d.push(m),e.push(l),f.push(n)}var d=[],e=[],f=[],h=-1,i=a.length,j;if(typeof b=="function")while(++h<i)g(j=a[h],b.call(j,j.parentNode.__data__,h));else while(++h<i)g(j=a[h],b);var k=S(e);k.enter=function(){return T(d)},k.exit=function(){return S(f)};return k},a.each=function(b){for(var c=0,d=a.length;c<d;c++){var e=a[c];for(var f=0,g=e.length;f<g;f++){var h=e[f];h&&b.call(h,h.__data__,f)}}return a},a.empty=function(){return!d(function(){return!0})},a.node=function(){return d(function(){return this})},a.attr=function(b,c){function j(){var a=c.apply(this,arguments);a==null?this.removeAttributeNS(b.space,b.local):this.setAttributeNS(b.space,b.local,a)}function i(){var a=c.apply(this,arguments);a==null?this.removeAttribute(b):this.setAttribute(b,a)}function h(){this.setAttributeNS(b.space,b.local,c)}function g(){this.setAttribute(b,c)}function f(){this.removeAttributeNS(b.space,b.local)}function e(){this.removeAttribute(b)}b=d3.ns.qualify(b);if(arguments.length<2)return d(b.local?function(){return this.getAttributeNS(b.space,b.local)}:function(){return this.getAttribute(b)});return a.each(c==null?b.local?f:e:typeof c=="function"?b.local?j:i:b.local?h:g)},a.classed=function(b,c){function i(){(c.apply(this,arguments)?g:h).call(this)}function h(){if(a=this.classList)return a.remove(b);var a=this.className,c=a.baseVal!=null,d=c?a.baseVal:a;d=f(d.replace(e," ")),c?a.baseVal=d:this.className=d}function g(){if(a=this.classList)return a.add(b);var a=this.className,c=a.baseVal!=null,d=c?a.baseVal:a;e.lastIndex=0,e.test(d)||(d=f(d+" "+b),c?a.baseVal=d:this.className=d)}var e=new RegExp("(^|\\s+)"+d3.requote(b)+"(\\s+|$)","g");if(arguments.length<2)return d(function(){if(a=this.classList)return a.contains(b);var a=this.className;e.lastIndex=0;return e.test(a.baseVal!=null?a.baseVal:a)});return a.each(typeof c=="function"?i:c?g:h)},a.style=function(b,c,e){function h(){var a=c.apply(this,arguments);a==null?this.style.removeProperty(b):this.style.setProperty(b,a,e)}function g(){this.style.setProperty(b,c,e)}function f(){this.style.removeProperty(b)}arguments.length<3&&(e="");if(arguments.length<2)return d(function(){return window.getComputedStyle(this,null).getPropertyValue(b)});return a.each(c==null?f:typeof c=="function"?h:g)},a.property=function(b,c){function g(){var a=c.apply(this,arguments);a==null?delete this[b]:this[b]=a}function f(){this[b]=c}function e(){delete this[b]}b=d3.ns.qualify(b);if(arguments.length<2)return d(function(){return this[b]});return a.each(c==null?e:typeof c=="function"?g:f)},a.text=function(b){function e(){this.textContent=b.apply(this,arguments)}function c(){this.textContent=b}if(arguments.length<1)return d(function(){return this.textContent});return a.each(typeof b=="function"?e:c)},a.html=function(b){function e(){this.innerHTML=b.apply(this,arguments)}function c(){this.innerHTML=b}if(arguments.length<1)return d(function(){return this.innerHTML});return a.each(typeof b=="function"?e:c)},a.append=function(a){function d(b){return b.appendChild(document.createElementNS(a.space,a.local))}function c(b){return b.appendChild(document.createElement(a))}a=d3.ns.qualify(a);return b(a.local?d:c)},a.insert=function(a,c){function e(b){return b.insertBefore(document.createElementNS(a.space,a.local),P(c,b))}function d(b){return b.insertBefore(document.createElement(a),P(c,b))}a=d3.ns.qualify(a);return b(a.local?e:d)},a.remove=function(){return a.each(function(){var a=this.parentNode;a&&a.removeChild(this)})},a.sort=function(b){b=U.apply(this,arguments);for(var c=0,d=a.length;c<d;c++){var e=a[c];e.sort(b);for(var f=1,g=e.length,h=e[0];f<g;f++){var i=e[f];i&&(h&&h.parentNode.insertBefore(i,h.nextSibling),h=i)}}return a},a.on=function(b,c,d){arguments.length<3&&(d=!1);var e=b.indexOf("."),f=e===-1?b:b.substring(0,e),g="__on"+b;return a.each(function(a,b){function h(a){var d=d3.event;d3.event=a;try{c.call(this,e.__data__,b)}finally{d3.event=d}}this[g]&&this.removeEventListener(f,this[g],d),c&&this.addEventListener(f,this[g]=h,d);var e=this})},a.transition=function(){return Y(a)},a.call=g;return a}function O(a,b,c){function g(a){return Math.round(f(a)*255)}function f(a){a>360?a-=360:a<0&&(a+=360);if(a<60)return d+(e-d)*a/60;if(a<180)return e;if(a<240)return d+(e-d)*(240-a)/60;return d}var d,e;a=a%360,a<0&&(a+=360),b=b<0?0:b>1?1:b,c=c<0?0:c>1?1:c,e=c<=.5?c*(1+b):c+b-c*b,d=2*c-e;return E(g(a+120),g(a),g(a-120))}function N(a,b,c){this.h=a,this.s=b,this.l=c}function M(a,b,c){return new N(a,b,c)}function J(a){var b=parseFloat(a);return a.charAt(a.length-1)==="%"?Math.round(b*2.55):b}function I(a,b,c){var d=Math.min(a/=255,b/=255,c/=255),e=Math.max(a,b,c),f=e-d,g,h,i=(e+d)/2;f?(h=i<.5?f/(e+d):f/(2-e-d),a==e?g=(b-c)/f+(b<c?6:0):b==e?g=(c-a)/f+2:g=(a-b)/f+4,g*=60):h=g=0;return M(g,h,i)}function H(a,b,c){var d=0,e=0,f=0,g,h,i;g=/([a-z]+)\((.*)\)/i.exec(a);if(g){h=g[2].split(",");switch(g[1]){case"hsl":return c(parseFloat(h[0]),parseFloat(h[1])/100,parseFloat(h[2])/100);case"rgb":return b(J(h[0]),J(h[1]),J(h[2]))}}if(i=K[a])return b(i.r,i.g,i.b);a!=null&&a.charAt(0)==="#"&&(a.length===4?(d=a.charAt(1),d+=d,e=a.charAt(2),e+=e,f=a.charAt(3),f+=f):a.length===7&&(d=a.substring(1,3),e=a.substring(3,5),f=a.substring(5,7)),d=parseInt(d,16),e=parseInt(e,16),f=parseInt(f,16));return b(d,e,f)}function G(a){return a<16?"0"+a.toString(16):a.toString(16)}function F(a,b,c){this.r=a,this.g=b,this.b=c}function E(a,b,c){return new F(a,b,c)}function D(a,b){b=1/(b-(a=+a));return function(c){return Math.max(0,Math.min(1,(c-a)*b))}}function C(a,b){b=1/(b-(a=+a));return function(c){return(c-a)*b}}function B(a){return a in A||/\bcolor\b/.test(a)?d3.interpolateRgb:d3.interpolate}function y(a){return a<1/2.75?7.5625*a*a:a<2/2.75?7.5625*(a-=1.5/2.75)*a+.75:a<2.5/2.75?7.5625*(a-=2.25/2.75)*a+.9375:7.5625*(a-=2.625/2.75)*a+.984375}function x(a){a||(a=1.70158);return function(b){return b*b*((a+1)*b-a)}}function w(a,b){var c;arguments.length<2&&(b=.45),arguments.length<1?(a=1,c=b/4):c=b/(2*Math.PI)*Math.asin(1/a);return function(d){return 1+a*Math.pow(2,10*-d)*Math.sin((d-c)*2*Math.PI/b)}}function v(a){return 1-Math.sqrt(1-a*a)}function u(a){return a?Math.pow(2,10*(a-1))-.001:0}function t(a){return 1-Math.cos(a*Math.PI/2)}function s(a){return function(b){return Math.pow(b,a)}}function r(a){return a}function q(a){return function(b){return.5*(b<.5?a(2*b):2-a(2-2*b))}}function p(a){return function(b){return 1-a(1-b)}}function k(a){var b=a.lastIndexOf("."),c=b>=0?a.substring(b):(b=a.length,""),d=[];while(b>0)d.push(a.substring(b-=3,b+3));return d.reverse().join(",")+c}function i(a){var b={},c=[];b.add=function(a){for(var d=0;d<c.length;d++)if(c[d].listener==a)return b;c.push({listener:a,on:!0});return b},b.remove=function(a){for(var d=0;d<c.length;d++){var e=c[d];if(e.listener==a){e.on=!1,c=c.slice(0,d).concat(c.slice(d+1));break}}return b},b.dispatch=function(){var a=c;for(var b=0,d=a.length;b<d;b++){var e=a[b];e.on&&e.listener.apply(this,arguments)}};return b}function g(a){a.apply(this,(arguments[0]=this,arguments));return this}function f(a){return a.replace(/(^\s+)|(\s+$)/g,"").replace(/\s+/g," ")}function e(a){return a==null}function c(a){return Array.prototype.slice.call(a)}function b(a){var b=-1,c=a.length,d=[];while(++b<c)d.push(a[b]);return d}d3={version:"1.15.1"},Date.now||(Date.now=function(){return+(new Date)}),Object.create||(Object.create=function(a){function b(){}b.prototype=a;return new b});var a=c;try{a(document.documentElement.childNodes)[0].nodeType}catch(d){a=b}d3.functor=function(a){return typeof a=="function"?a:function(){return a}},d3.rebind=function(a,b){return function(){var c=b.apply(a,arguments);return arguments.length?a:c}},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 c=0,d=a.length,e=a[0],f;if(arguments.length===1)while(++c<d)e>(f=a[c])&&(e=f);else{e=b(a[0]);while(++c<d)e>(f=b(a[c]))&&(e=f)}return e},d3.max=function(a,b){var c=0,d=a.length,e=a[0],f;if(arguments.length===1)while(++c<d)e<(f=a[c])&&(e=f);else{e=b(e);while(++c<d)e<(f=b(a[c]))&&(e=f)}return e},d3.nest=function(){function g(a,d){if(d>=b.length)return a;var e=[],f=c[d++],h;for(h in a)e.push({key:h,values:g(a[h],d)});f&&e.sort(function(a,b){return f(a.key,b.key)});return e}function f(c,g){if(g>=b.length)return e?e.call(a,c):d?c.sort(d):c;var h=-1,i=c.length,j=b[g++],k,l,m={};while(++h<i)(k=j(l=c[h]))in m?m[k].push(l):m[k]=[l];for(k in m)m[k]=f(m[k],g);return m}var a={},b=[],c=[],d,e;a.map=function(a){return f(a,0)},a.entries=function(a){return g(f(a,0),0)},a.key=function(c){b.push(c);return a},a.sortKeys=function(d){c[b.length-1]=d;return a},a.sortValues=function(b){d=b;return a},a.rollup=function(b){e=b;return a};return a},d3.keys=function(a){var b=[];for(var c in a)b.push(c);return b},d3.values=function(a){var b=[];for(var c in a)b.push(a[c]);return b},d3.entries=function(a){var b=[];for(var c in a)b.push({key:c,value:a[c]});return b},d3.merge=function(a){return Array.prototype.concat.apply([],a)},d3.split=function(a,b){var c=[],d=[],f,g=-1,h=a.length;arguments.length<2&&(b=e);while(++g<h)b.call(d,f=a[g],g)?d=[]:(d.length||c.push(d),d.push(f));return c},d3.range=function(a,b,c){arguments.length===1&&(b=a,a=0),c==null&&(c=1);if((b-a)/c==Infinity)throw new Error("infinite range");var d=[],e=-1,f;if(c<0)while((f=a+c*++e)>b)d.push(f);else while((f=a+c*++e)<b)d.push(f);return d},d3.requote=function(a){return a.replace(h,"\\$&")};var h=/[\\\^\$\*\+\?\[\]\(\)\.\{\}]/g;d3.xhr=function(a,b,c){var d=new XMLHttpRequest;arguments.length<3?c=b:b&&d.overrideMimeType&&d.overrideMimeType(b),d.open("GET",a,!0),d.onreadystatechange=function(){d.readyState===4&&c(d.status<300?d:null)},d.send(null)},d3.text=function(a,b,c){function d(a){c(a&&a.responseText)}arguments.length<3&&(c=b,b=null),d3.xhr(a,b,d)},d3.json=function(a,b){d3.text(a,"application/json",function(a){b(a?JSON.parse(a):null)})},d3.html=function(a,b){d3.text(a,"text/html",function(a){if(a!=null){var c=document.createRange();c.selectNode(document.body),a=c.createContextualFragment(a)}b(a)})},d3.xml=function(a,b,c){function d(a){c(a&&a.responseXML)}arguments.length<3&&(c=b,b=null),d3.xhr(a,b,d)},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(a){var b={},c;for(var d=0,e=arguments.length;d<e;d++)c=arguments[d],b[c]=i(c);return b},d3.format=function(a){var b=j.exec(a),c=b[1]||" ",d=b[3]||"",e=b[5],f=+b[6],g=b[7],h=b[8],i=b[9];h&&(h=h.substring(1)),e&&(c="0",g&&(f-=Math.floor((f-1)/4))),i==="d"&&(h="0");return function(a){var b=+a,j=b<0&&(b=-b)?"−":d;if(i==="d"&&b%1)return"";h?a=b.toFixed(h):a=""+b;if(e){var l=a.length+j.length;l<f&&(a=Array(f-l+1).join(c)+a),g&&(a=k(a)),a=j+a}else{g&&(a=k(a)),a=j+a;var l=a.length;l<f&&(a=Array(f-l+1).join(c)+a)}return a}};var j=/(?:([^{])?([<>=^]))?([+\- ])?(#)?(0)?([0-9]+)?(,)?(\.[0-9]+)?([a-zA-Z%])?/,l=s(2),m=s(3),n={linear:function(){return r},poly:s,quad:function(){return l},cubic:function(){return m},sin:function(){return t},exp:function(){return u},circle:function(){return v},elastic:w,back:x,bounce:function(){return y}},o={"in":function(a){return a},out:p,"in-out":q,"out-in":function(a){return q(p(a))}};d3.ease=function(a){var b=a.indexOf("-"),c=b>=0?a.substring(0,b):a,d=b>=0?a.substring(b+1):"in";return o[d](n[c].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 K||/^(#|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(c){return a+b*c}},d3.interpolateRound=function(a,b){b-=a;return function(c){return Math.round(a+b*c)}},d3.interpolateString=function(a,b){var c,d,e,f=0,g=0,h=[],i=[],j,k;z.lastIndex=0;for(d=0;c=z.exec(b);++d)c.index&&h.push(b.substring(f,g=c.index)),i.push({i:h.length,x:c[0]}),h.push(null),f=z.lastIndex;f<b.length&&h.push(b.substring(f));for(d=0,j=i.length;(c=z.exec(a))&&d<j;++d){k=i[d];if(k.x==c[0]){if(k.i)if(h[k.i+1]==null){h[k.i-1]+=k.x,h.splice(k.i,1);for(e=d+1;e<j;++e)i[e].i--}else{h[k.i-1]+=k.x+h[k.i+1],h.splice(k.i,2);for(e=d+1;e<j;++e)i[e].i-=2}else if(h[k.i+1]==null)h[k.i]=k.x;else{h[k.i]=k.x+h[k.i+1],h.splice(k.i+1,1);for(e=d+1;e<j;++e)i[e].i--}i.splice(d,1),j--,d--}else k.x=d3.interpolateNumber(parseFloat(c[0]),parseFloat(k.x))}while(d<j)k=i.pop(),h[k.i+1]==null?h[k.i]=k.x:(h[k.i]=k.x+h[k.i+1],h.splice(k.i+1,1)),j--;if(h.length===1)return h[0]==null?i[0].x:function(){return b};return function(a){for(d=0;d<j;++d)h[(k=i[d]).i]=k.x(a);return h.join("")}},d3.interpolateRgb=function(a,b){a=d3.rgb(a),b=d3.rgb(b);var c=a.r,d=a.g,e=a.b,f=b.r-c,g=b.g-d,h=b.b-e;return function(a){return"rgb("+Math.round(c+f*a)+","+Math.round(d+g*a)+","+Math.round(e+h*a)+")"}},d3.interpolateHsl=function(a,b){a=d3.hsl(a),b=d3.hsl(b);var c=a.h,d=a.s,e=a.l,f=b.h-c,g=b.s-d,h=b.l-e;return function(a){return O(c+f*a,d+g*a,e+h*a).toString()}},d3.interpolateArray=function(a,b){var c=[],d=[],e=a.length,f=b.length,g=Math.min(a.length,b.length),h;for(h=0;h<g;++h)c.push(d3.interpolate(a[h],b[h]));for(;h<e;++h)d[h]=a[h];for(;h<f;++h)d[h]=b[h];return function(a){for(h=0;h<g;++h)d[h]=c[h](a);return d}},d3.interpolateObject=function(a,b){var c={},d={},e;for(e in a)e in b?c[e]=B(e)(a[e],b[e]):d[e]=a[e];for(e in b)e in a||(d[e]=b[e]);return function(a){for(e in c)d[e]=c[e](a);return d}};var z=/[-+]?(?:\d+\.\d+|\d+\.|\.\d+|\d+)(?:[eE][-]?\d+)?/g,A={background:1,fill:1,stroke:1};d3.rgb=function(a,b,c){return arguments.length===1?H(""+a,E,O):E(~~a,~~b,~~c)},F.prototype.brighter=function(a){a=Math.pow(.7,arguments.length?a:1);var b=this.r,c=this.g,d=this.b,e=30;if(!b&&!c&&!d)return E(e,e,e);b&&b<e&&(b=e),c&&c<e&&(c=e),d&&d<e&&(d=e);return E(Math.min(255,Math.floor(b/a)),Math.min(255,Math.floor(c/a)),Math.min(255,Math.floor(d/a)))},F.prototype.darker=function(a){a=Math.pow(.7,arguments.length?a:1);return E(Math.max(0,Math.floor(a*this.r)),Math.max(0,Math.floor(a*this.g)),Math.max(0,Math.floor(a*this.b)))},F.prototype.hsl=function(){return I(this.r,this.g,this.b)},F.prototype.toString=function(){return"#"+G(this.r)+G(this.g)+G(this.b)};var K={aliceblue:"#f0f8ff",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",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",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",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",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",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"};for(var L in K)K[L]=H(K[L],E,O);d3.hsl=function(a,b,c){return arguments.length===1?H(""+a,I,M):M(+a,+b,+c)},N.prototype.brighter=function(a){a=Math.pow(.7,arguments.length?a:1);return M(this.h,this.s,this.l/a)},N.prototype.darker=function(a){a=Math.pow(.7,arguments.length?a:1);return M(this.h,this.s,a*this.l)},N.prototype.rgb=function(){return O(this.h,this.s,this.l)},N.prototype.toString=function(){return"hsl("+this.h+","+this.s*100+"%,"+this.l*100+"%)"};var P=function(a,b){return b.querySelector(a)},Q=function(b,c){return a(c.querySelectorAll(b))};typeof Sizzle=="function"&&(P=function(a,b){return Sizzle(a,b)[0]},Q=function(a,b){return Sizzle.uniqueSort(Sizzle(a,b))});var R=S([[document]]);R[0].parentNode=document.documentElement,d3.select=function(a){return typeof a=="string"?R.select(a):S([[a]])},d3.selectAll=function(b){return typeof b=="string"?R.selectAll(b):S([a(b)])},d3.transition=R.transition;var W=0,X=0,$=null,_,ba;d3.timer=function(a){bb(a,0)},d3.timer.flush=function(){var a,b=Date.now(),c=$;while(c)a=b-c.then,c.delay||(c.flush=c.callback(a)),c=c.next;bd()};var be=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(a){setTimeout(a,17)};d3.scale={},d3.scale.linear=function(){function i(b){var c=d3.min(a),d=d3.max(a),e=d-c,f=Math.pow(10,Math.floor(Math.log(e/b)/Math.LN10)),g=b/(e/f);g<=.15?f*=10:g<=.35?f*=5:g<=.75&&(f*=2);return{start:Math.ceil(c/f)*f,stop:Math.floor(d/f)*f+f*.5,step:f}}function h(a){return e(a)}function g(){var g=a.length==2?bf:bg,i=d?D:C;e=g(a,b,i,c),f=g(b,a,i,d3.interpolate);return h}var a=[0,1],b=[0,1],c=d3.interpolate,d=!1,e,f;h.invert=function(a){return f(a)},h.domain=function(b){if(!arguments.length)return a;a=b.map(Number);return g()},h.range=function(a){if(!arguments.length)return b;b=a;return g()},h.rangeRound=function(a){return h.range(a).interpolate(d3.interpolateRound)},h.clamp=function(a){if(!arguments.length)return d;d=a;return g()},h.interpolate=function(a){if(!arguments.length)return c;c=a;return g()},h.ticks=function(a){var b=i(a);return d3.range(b.start,b.stop,b.step)},h.tickFormat=function(a){var b=Math.max(0,-Math.floor(Math.log(i(a).step)/Math.LN10+.01));return d3.format(",."+b+"f")};return g()},d3.scale.log=function(){function d(c){return a(b(c))}var a=d3.scale.linear(),b=bh,c=b.pow;d.invert=function(b){return c(a.invert(b))},d.domain=function(e){if(!arguments.length)return a.domain().map(c);b=(e[0]||e[1])<0?bi:bh,c=b.pow,a.domain(e.map(b));return d},d.range=d3.rebind(d,a.range),d.rangeRound=d3.rebind(d,a.rangeRound),d.interpolate=d3.rebind(d,a.interpolate),d.clamp=d3.rebind(d,a.clamp),d.ticks=function(){var d=a.domain(),e=[];if(d.every(isFinite)){var f=Math.floor(d[0]),g=Math.ceil(d[1]),h=c(d[0]),i=c(d[1]);if(b===bi){e.push(c(f));for(;f++<g;)for(var j=9;j>0;j--)e.push(c(f)*j)}else{for(;f<g;f++)for(var j=1;j<10;j++)e.push(c(f)*j);e.push(c(f))}for(f=0;e[f]<h;f++);for(g=e.length;e[g-1]>i;g--);e=e.slice(f,g)}return e},d.tickFormat=function(){return function(a){return a.toPrecision(1)}};return d},bh.pow=function(a){return Math.pow(10,a)},bi.pow=function(a){return-Math.pow(10,-a)},d3.scale.pow=function(){function f(b){return a(d(b))}var a=d3.scale.linear(),b=d3.scale.linear(),c=1,d=Number,e=d;f.invert=function(b){return e(a.invert(b))},f.domain=function(g){if(!arguments.length)return a.domain().map(e);var h=(g[0]||g[1])<0?bk:bj;d=h(c),e=h(1/c),a.domain(g.map(d)),b.domain(g);return f},f.range=d3.rebind(f,a.range),f.rangeRound=d3.rebind(f,a.rangeRound),f.interpolate=d3.rebind(f,a.interpolate),f.clamp=d3.rebind(f,a.clamp),f.ticks=b.ticks,f.tickFormat=b.tickFormat,f.exponent=function(a){if(!arguments.length)return c;var b=f.domain();c=a;return f.domain(b)};return f},d3.scale.sqrt=function(){return d3.scale.pow().exponent(.5)},d3.scale.ordinal=function(){function e(d){var e=d in b?b[d]:b[d]=a.push(d)-1;return c[e%c.length]}var a=[],b={},c=[],d=0;e.domain=function(c){if(!arguments.length)return a;a=c,b={};var d=-1,f=-1,g=a.length;while(++d<g)c=a[d],c in b||(b[c]=++f);return e},e.range=function(a){if(!arguments.length)return c;c=a;return e},e.rangePoints=function(b,f){arguments.length<2&&(f=0);var g=b[0],h=b[1],i=(h-g)/(a.length-1+f);c=a.length==1?[(g+h)/2]:d3.range(g+i*f/2,h+i/2,i),d=0;return e},e.rangeBands=function(b,f){arguments.length<2&&(f=0);var g=b[0],h=b[1],i=(h-g)/(a.length+f);c=d3.range(g+i*f,h,i),d=i*(1-f);return e},e.rangeRoundBands=function(b,f){arguments.length<2&&(f=0);var g=b[0],h=b[1],i=h-g,j=Math.floor(i/(a.length+f)),k=i-(a.length-f)*j;c=d3.range(g+Math.round(k/2),h,j),d=Math.round(j*(1-f));return e},e.rangeBand=function(){return d};return e},d3.scale.category10=function(){return d3.scale.ordinal().range(bl)},d3.scale.category20=function(){return d3.scale.ordinal().range(bm)},d3.scale.category20b=function(){return d3.scale.ordinal().range(bn)},d3.scale.category20c=function(){return d3.scale.ordinal().range(bo)};var bl=["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"],bm=["#1f77b4","#aec7e8","#ff7f0e","#ffbb78","#2ca02c" <add>,"#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5","#8c564b","#c49c94","#e377c2","#f7b6d2","#7f7f7f","#c7c7c7","#bcbd22","#dbdb8d","#17becf","#9edae5"],bn=["#393b79","#5254a3","#6b6ecf","#9c9ede","#637939","#8ca252","#b5cf6b","#cedb9c","#8c6d31","#bd9e39","#e7ba52","#e7cb94","#843c39","#ad494a","#d6616b","#e7969c","#7b4173","#a55194","#ce6dbd","#de9ed6"],bo=["#3182bd","#6baed6","#9ecae1","#c6dbef","#e6550d","#fd8d3c","#fdae6b","#fdd0a2","#31a354","#74c476","#a1d99b","#c7e9c0","#756bb1","#9e9ac8","#bcbddc","#dadaeb","#636363","#969696","#bdbdbd","#d9d9d9"];d3.scale.quantile=function(){function f(a){return b[e(a)]}function e(a){if(isNaN(a=+a))return NaN;var b=0,d=c.length-1;while(b<=d){var e=b+d>>1,f=c[e];if(f<a)b=e+1;else if(f>a)d=e-1;else return e}return d<0?0:d}function d(){var d=-1,e=c.length=b.length,f=a.length/e;while(++d<e)c[d]=a[~~(d*f)]}var a=[],b=[],c=[];f.domain=function(b){if(!arguments.length)return a;a=b.filter(function(a){return!isNaN(a)}).sort(d3.ascending),d();return f},f.range=function(a){if(!arguments.length)return b;b=a,d();return f},f.quantiles=function(){return c};return f},d3.scale.quantize=function(){function f(b){return e[Math.max(0,Math.min(d,Math.floor(c*(b-a))))]}var a=0,b=1,c=2,d=1,e=[0,1];f.domain=function(d){if(!arguments.length)return[a,b];a=d[0],b=d[1],c=e.length/(b-a);return f},f.range=function(g){if(!arguments.length)return e;e=g,c=e.length/(b-a),d=e.length-1;return f};return f},d3.svg={},d3.svg.arc=function(){function e(){var e=a.apply(this,arguments),f=b.apply(this,arguments),g=c.apply(this,arguments)+bp,h=d.apply(this,arguments)+bp,i=h-g,j=i<Math.PI?"0":"1",k=Math.cos(g),l=Math.sin(g),m=Math.cos(h),n=Math.sin(h);return i>=bq?e?"M0,"+f+"A"+f+","+f+" 0 1,1 0,"+ -f+"A"+f+","+f+" 0 1,1 0,"+f+"M0,"+e+"A"+e+","+e+" 0 1,1 0,"+ -e+"A"+e+","+e+" 0 1,1 0,"+e+"Z":"M0,"+f+"A"+f+","+f+" 0 1,1 0,"+ -f+"A"+f+","+f+" 0 1,1 0,"+f+"Z":e?"M"+f*k+","+f*l+"A"+f+","+f+" 0 "+j+",1 "+f*m+","+f*n+"L"+e*m+","+e*n+"A"+e+","+e+" 0 "+j+",0 "+e*k+","+e*l+"Z":"M"+f*k+","+f*l+"A"+f+","+f+" 0 "+j+",1 "+f*m+","+f*n+"L0,0"+"Z"}var a=br,b=bs,c=bt,d=bu;e.innerRadius=function(b){if(!arguments.length)return a;a=d3.functor(b);return e},e.outerRadius=function(a){if(!arguments.length)return b;b=d3.functor(a);return e},e.startAngle=function(a){if(!arguments.length)return c;c=d3.functor(a);return e},e.endAngle=function(a){if(!arguments.length)return d;d=d3.functor(a);return e},e.centroid=function(){var e=(a.apply(this,arguments)+b.apply(this,arguments))/2,f=(c.apply(this,arguments)+d.apply(this,arguments))/2+bp;return[Math.cos(f)*e,Math.sin(f)*e]};return e};var bp=-Math.PI/2,bq=2*Math.PI-1e-6;d3.svg.line=function(){function f(c){return c.length<1?null:"M"+d(bv(this,c,a,b),e)}var a=bw,b=bx,c="linear",d=by[c],e=.7;f.x=function(b){if(!arguments.length)return a;a=b;return f},f.y=function(a){if(!arguments.length)return b;b=a;return f},f.interpolate=function(a){if(!arguments.length)return c;d=by[c=a];return f},f.tension=function(a){if(!arguments.length)return e;e=a;return f};return f};var by={linear:bz,"step-before":bA,"step-after":bB,basis:bH,"basis-open":bI,"basis-closed":bJ,cardinal:bE,"cardinal-open":bC,"cardinal-closed":bD,monotone:bS},bL=[0,2/3,1/3,0],bM=[0,1/3,2/3,0],bN=[0,1/6,2/3,1/6];d3.svg.area=function(){function g(d){return d.length<1?null:"M"+e(bv(this,d,a,c),f)+"L"+e(bv(this,d,a,b).reverse(),f)+"Z"}var a=bw,b=bT,c=bx,d="linear",e=by[d],f=.7;g.x=function(b){if(!arguments.length)return a;a=b;return g},g.y0=function(a){if(!arguments.length)return b;b=a;return g},g.y1=function(a){if(!arguments.length)return c;c=a;return g},g.interpolate=function(a){if(!arguments.length)return d;e=by[d=a];return g},g.tension=function(a){if(!arguments.length)return f;f=a;return g};return g},d3.svg.chord=function(){function j(a,b,c,d){return"Q 0,0 "+d}function i(a,b){return"A"+a+","+a+" 0 0,1 "+b}function h(a,b){return a.a0==b.a0&&a.a1==b.a1}function g(a,b,f,g){var h=b.call(a,f,g),i=c.call(a,h,g),j=d.call(a,h,g)+bp,k=e.call(a,h,g)+bp;return{r:i,a0:j,a1:k,p0:[i*Math.cos(j),i*Math.sin(j)],p1:[i*Math.cos(k),i*Math.sin(k)]}}function f(c,d){var e=g(this,a,c,d),f=g(this,b,c,d);return"M"+e.p0+i(e.r,e.p1)+(h(e,f)?j(e.r,e.p1,e.r,e.p0):j(e.r,e.p1,f.r,f.p0)+i(f.r,f.p1)+j(f.r,f.p1,e.r,e.p0))+"Z"}var a=bU,b=bV,c=bW,d=bt,e=bu;f.radius=function(a){if(!arguments.length)return c;c=d3.functor(a);return f},f.source=function(b){if(!arguments.length)return a;a=d3.functor(b);return f},f.target=function(a){if(!arguments.length)return b;b=d3.functor(a);return f},f.startAngle=function(a){if(!arguments.length)return d;d=d3.functor(a);return f},f.endAngle=function(a){if(!arguments.length)return e;e=d3.functor(a);return f};return f},d3.svg.diagonal=function(){function d(d,e){var f=a.call(this,d,e),g=b.call(this,d,e),h=(f.y+g.y)/2,i=[f,{x:f.x,y:h},{x:g.x,y:h},g];i=i.map(c);return"M"+i[0]+"C"+i[1]+" "+i[2]+" "+i[3]}var a=bU,b=bV,c=bZ;d.source=function(b){if(!arguments.length)return a;a=d3.functor(b);return d},d.target=function(a){if(!arguments.length)return b;b=d3.functor(a);return d},d.projection=function(a){if(!arguments.length)return c;c=a;return d};return d},d3.svg.mouse=function(a){return b_(a,[d3.event])[0]};var b$=/WebKit/.test(navigator.userAgent)?-1:0;d3.svg.touches=function(a){var b=d3.event.touches;return b&&b.length?b_(a,b):[]},d3.svg.symbol=function(){function c(c,d){return(cc[a.call(this,c,d)]||cc.circle)(b.call(this,c,d))}var a=cb,b=ca;c.type=function(b){if(!arguments.length)return a;a=d3.functor(b);return c},c.size=function(a){if(!arguments.length)return b;b=d3.functor(a);return c};return c},d3.svg.symbolTypes=["circle","cross","diamond","square","triangle-down","triangle-up"];var cc={circle:function(a){var b=Math.sqrt(a/Math.PI);return"M0,"+b+"A"+b+","+b+" 0 1,1 0,"+ -b+"A"+b+","+b+" 0 1,1 0,"+b+"Z"},cross:function(a){var b=Math.sqrt(a/5)/2;return"M"+ -3*b+","+ -b+"H"+ -b+"V"+ -3*b+"H"+b+"V"+ -b+"H"+3*b+"V"+b+"H"+b+"V"+3*b+"H"+ -b+"V"+b+"H"+ -3*b+"Z"},diamond:function(a){var b=Math.sqrt(a/(2*ce)),c=b*ce;return"M0,"+ -b+"L"+c+",0"+" 0,"+b+" "+ -c+",0"+"Z"},square:function(a){var b=Math.sqrt(a)/2;return"M"+ -b+","+ -b+"L"+b+","+ -b+" "+b+","+b+" "+ -b+","+b+"Z"},"triangle-down":function(a){var b=Math.sqrt(a/cd),c=b*cd/2;return"M0,"+c+"L"+b+","+ -c+" "+ -b+","+ -c+"Z"},"triangle-up":function(a){var b=Math.sqrt(a/cd),c=b*cd/2;return"M0,"+ -c+"L"+b+","+c+" "+ -b+","+c+"Z"}},cd=Math.sqrt(3),ce=Math.tan(30*Math.PI/180)})() <ide>\ No newline at end of file <ide><path>src/svg/mouse.js <ide> function d3_svg_mousePoints(container, events) { <ide> d3_mouse_bug44083 = !(ctm.f || ctm.e); <ide> svg.remove(); <ide> } <del> return events.map(function(e) { <add> var i = -1, <add> n = events.length, <add> points = []; <add> while (++i < n) { <add> var e = events[i]; <ide> if (d3_mouse_bug44083) { <ide> point.x = e.pageX; <ide> point.y = e.pageY; <ide> function d3_svg_mousePoints(container, events) { <ide> point.y = e.clientY; <ide> } <ide> point = point.matrixTransform(container.getScreenCTM().inverse()); <del> return [point.x, point.y]; <del> }); <add> points.push([point.x, point.y]); <add> } <add> return points; <ide> }; <ide><path>src/svg/touches.js <ide> d3.svg.touches = function(container) { <ide> var touches = d3.event.touches; <ide> return touches && touches.length <del> ? d3_svg_mousePoints(container, d3_array(touches)) : []; <add> ? d3_svg_mousePoints(container, touches) : []; <ide> };
4
Python
Python
add more tests
2a4f6b942db5da321c627ebc1f0ca448bf491556
<ide><path>tests/keras/backend/test_backends.py <ide> class TestBackend(object): <ide> <ide> def test_linear_operations(self): <ide> check_two_tensor_operation('dot', (4, 2), (2, 4)) <add> check_two_tensor_operation('dot', (4, 2), (5, 2, 3)) <add> <ide> check_two_tensor_operation('batch_dot', (4, 2, 3), (4, 5, 3), <ide> axes=((2,), (2,))) <ide> check_single_tensor_operation('transpose', (4, 2)) <ide><path>tests/keras/layers/test_core.py <ide> def test_dense(): <ide> <ide> <ide> def test_activity_regularization(): <del> layer_test(core.ActivityRegularization, <del> kwargs={'l1': 0.01, 'l2': 0.01}, <del> input_shape=(3, 2, 3)) <add> from keras.engine import Input, Model <add> <add> layer = core.ActivityRegularization(l1=0.01, l2=0.01) <add> <add> # test in functional API <add> x = Input(shape=(3,)) <add> z = core.Dense(2)(x) <add> y = layer(z) <add> model = Model(input=x, output=y) <add> model.compile('rmsprop', 'mse', mode='FAST_COMPILE') <add> <add> model.predict(np.random.random((2, 3))) <add> <add> # test serialization <add> model_config = model.get_config() <add> model = Model.from_config(model_config) <add> model.compile('rmsprop', 'mse') <ide> <ide> <ide> def test_maxout_dense():
2
Text
Text
update react functional component tutorial
d07a9de8203c72d2ff5d01e306954c536831cb18
<ide><path>docs/guides/react.md <ide> import "video.js/dist/video-js.css"; <ide> export const VideoJS = ( props ) => { <ide> <ide> const videoRef = React.useRef(null); <del> const { options } = props; <add> const playerRef = React.useRef(null); <add> const { options, onReady } = props; <ide> <del> // This separate functional component fixes the removal of the videoelement <del> // from the DOM when calling the dispose() method on a player <del> const VideoHtml = ( props ) => ( <del> <div data-vjs-player> <del> <video ref={videoRef} className="video-js vjs-big-play-centered" /> <del> </div> <del> ); <add> React.useEffect(() => { <add> // make sure Video.js player is only initialized once <add> if (!playerRef.current) { <add> const videoElement = videoRef.current; <add> if (!videoElement) return; <ide> <del> React.useEffect( () => { <del> const videoElement = videoRef.current; <del> let player; <del> if( videoElement ) { <del> player = videojs( videoElement, options, () => { <add> const player = playerRef.current = videojs(videoElement, options, () => { <ide> console.log("player is ready"); <add> onReady && onReady(player); <ide> }); <add> } else { <add> // you can update player here [update player through props] <add> // const player = playerRef.current; <add> // player.autoplay(options.autoplay); <add> // player.src(options.sources); <ide> } <add> }, [options]); <add> <add> // Dispose the Video.js player when the functional component unmounts <add> React.useEffect(() => { <ide> return () => { <del> if( player ) { <del> player.dispose(); <add> if (playerRef.current) { <add> playerRef.current.dispose(); <add> playerRef.current = null; <ide> } <del> } <del> }, [options]); <add> }; <add> }, []); <ide> <del> return (<VideoHtml />); <add> return ( <add> <div data-vjs-player> <add> <video ref={videoRef} className="video-js vjs-big-play-centered" /> <add> </div> <add> ); <ide> } <del>export default VideoJS; <ide> <add>export default VideoJS; <ide> ``` <ide> <ide> You can then use it like this: (see [options guide][options] for option information) <add> <ide> ```jsx <ide> import React from "react"; <ide> import VideoJS from './VideoJS' // point to where the functional component is stored <ide> <ide> const App = () => { <add> const playerRef = React.useRef(null); <ide> <ide> const videoJsOptions = { // lookup the options in the docs for more options <ide> autoplay: true, <ide> const App = () => { <ide> type: 'video/mp4' <ide> }] <ide> } <del> <add> <add> const handlePlayerReady = (player) => { <add> playerRef.current = player; <add> <add> // you can handle player events here <add> player.on('waiting', () => { <add> console.log('player is waiting'); <add> }); <add> <add> player.on('dispose', () => { <add> console.log('player will dispose'); <add> }); <add> }; <add> <add> // const changePlayerOptions = () => { <add> // // you can update the player through the Video.js player instance <add> // if (!playerRef.current) { <add> // return; <add> // } <add> // // [update player through instance's api] <add> // playerRef.current.src([{src: 'http://ex.com/video.mp4', type: 'video/mp4'}]); <add> // playerRef.current.autoplay(false); <add> // }; <add> <ide> return ( <ide> <> <ide> <div>Rest of app here</div> <del> <del> <VideoJS options={videoJsOptions}/> <del> <add> <add> <VideoJS options={videoJsOptions} onReady={handlePlayerReady} /> <add> <ide> <div>Rest of app here</div> <ide> </> <ide> ); <ide> } <del> <ide> ``` <ide> <ide> ## React Class Component Example <ide> export default class VideoPlayer extends React.Component { <ide> // see https://github.com/videojs/video.js/pull/3856 <ide> render() { <ide> return ( <del> <div> <add> <div> <ide> <div data-vjs-player> <ide> <video ref={ node => this.videoNode = node } className="video-js"></video> <ide> </div> <ide> const videoJsOptions = { <ide> <ide> return <VideoPlayer { ...videoJsOptions } /> <ide> ``` <del>[options]: /docs/guides/options.md <del> <ide> <add>[options]: /docs/guides/options.md <ide> <ide> ## Using a React Component as a Video JS Component <ide> <ide> class vjsEpisodeList extends vjsComponent { <ide> player.ready(() => { <ide> this.mount(); <ide> }); <del> <add> <ide> /* Remove React root when component is destroyed */ <ide> this.on("dispose", () => { <ide> ReactDOM.unmountComponentAtNode(this.el())
1
Text
Text
add section on how to build debug build
030ef35bf026f32a3381187c405b4495bd8bf1d4
<ide><path>BUILDING.md <ide> To install this version of Node.js into a system directory: <ide> $ [sudo] make install <ide> ``` <ide> <add>#### Building a debug build <add> <add>If you run into an issue where the information provided by the JS stack trace <add>is not enough, or if you suspect the error happens outside of the JS VM, you <add>can try to build a debug enabled binary: <add> <add>```console <add>$ ./configure --debug <add>$ make -j4 <add>``` <add> <add>`make` with `./configure --debug` generates two binaries, the regular release <add>one in `out/Release/node` and a debug binary in `out/Debug/node`, only the <add>release version is actually installed when you run `make install`. <add> <add>To use the debug build with all the normal dependencies overwrite the release <add>version in the install directory: <add> <add>``` console <add>$ make install --prefix=/opt/node-debug/ <add>$ cp -a -f out/Debug/node /opt/node-debug/node <add>``` <add> <add>When using the debug binary, core dumps will be generated in case of crashes. <add>These core dumps are useful for debugging when provided with the <add>corresponding original debug binary and system information. <add> <add>Reading the core dump requires `gdb` built on the same platform the core dump <add>was captured on (i.e. 64 bit `gdb` for `node` built on a 64 bit system, Linux <add>`gdb` for `node` built on Linux) otherwise you will get errors like <add>`not in executable format: File format not recognized`. <add> <add>Example of generating a backtrace from the core dump: <add> <add>``` console <add>$ gdb /opt/node-debug/node core.node.8.1535359906 <add>$ backtrace <add>``` <ide> <ide> ### Windows <ide>
1
PHP
PHP
add sqlsrv as group connection
e26bd3ffb01f431935f207dc7a6fdcbd5600d6f7
<ide><path>config/database.php <ide> 'schema' => 'public', <ide> 'sslmode' => 'prefer', <ide> ], <add> <add> 'sqlsrv' => [ <add> 'driver' => 'sqlsrv', <add> 'host' => env('DB_HOST', 'localhost'), <add> 'database' => env('DB_DATABASE', 'forge'), <add> 'username' => env('DB_USERNAME', 'forge'), <add> 'password' => env('DB_PASSWORD', ''), <add> 'charset' => 'utf8', <add> 'prefix' => '', <add> ], <ide> <ide> ], <ide>
1
Javascript
Javascript
give unresolved lazy() a name in component stack
3c7d52c3d6d316d09d5c2479c6851acecccc6325
<ide><path>packages/react-reconciler/src/__tests__/ReactLazy-test.internal.js <ide> let ReactFeatureFlags; <ide> let Suspense; <ide> let lazy; <ide> <add>function normalizeCodeLocInfo(str) { <add> return ( <add> str && <add> str.replace(/\n +(?:at|in) ([\S]+)[^\n]*/g, function(m, name) { <add> return '\n in ' + name + ' (at **)'; <add> }) <add> ); <add>} <add> <ide> describe('ReactLazy', () => { <ide> beforeEach(() => { <ide> jest.resetModules(); <ide> describe('ReactLazy', () => { <ide> expect(Scheduler).toFlushAndYield([]); <ide> }).toErrorDev('Function components cannot be given refs'); <ide> }); <add> <add> it('should error with a component stack naming the resolved component', async () => { <add> let componentStackMessage; <add> <add> const LazyText = lazy(() => <add> fakeImport(function ResolvedText() { <add> throw new Error('oh no'); <add> }), <add> ); <add> <add> class ErrorBoundary extends React.Component { <add> state = {error: null}; <add> <add> componentDidCatch(error, errMessage) { <add> componentStackMessage = normalizeCodeLocInfo(errMessage.componentStack); <add> this.setState({ <add> error, <add> }); <add> } <add> <add> render() { <add> return this.state.error ? null : this.props.children; <add> } <add> } <add> <add> ReactTestRenderer.create( <add> <ErrorBoundary> <add> <Suspense fallback={<Text text="Loading..." />}> <add> <LazyText text="Hi" /> <add> </Suspense> <add> </ErrorBoundary>, <add> {unstable_isConcurrent: true}, <add> ); <add> <add> expect(Scheduler).toFlushAndYield(['Loading...']); <add> <add> try { <add> await Promise.resolve(); <add> } catch (e) {} <add> <add> expect(Scheduler).toFlushAndYield([]); <add> <add> expect(componentStackMessage).toContain('in ResolvedText'); <add> }); <add> <add> it('should error with a component stack containing Lazy if unresolved', () => { <add> let componentStackMessage; <add> <add> const LazyText = lazy(() => ({ <add> then(resolve, reject) { <add> reject(new Error('oh no')); <add> }, <add> })); <add> <add> class ErrorBoundary extends React.Component { <add> state = {error: null}; <add> <add> componentDidCatch(error, errMessage) { <add> componentStackMessage = normalizeCodeLocInfo(errMessage.componentStack); <add> this.setState({ <add> error, <add> }); <add> } <add> <add> render() { <add> return this.state.error ? null : this.props.children; <add> } <add> } <add> <add> ReactTestRenderer.create( <add> <ErrorBoundary> <add> <Suspense fallback={<Text text="Loading..." />}> <add> <LazyText text="Hi" /> <add> </Suspense> <add> </ErrorBoundary>, <add> ); <add> <add> expect(Scheduler).toHaveYielded([]); <add> <add> expect(componentStackMessage).toContain('in Lazy'); <add> }); <ide> });
1
Javascript
Javascript
add missing assertions
ff16d224ca81c07f3ef744e7a461b344af98ecf4
<ide><path>test/ng/directive/ngClassSpec.js <ide> describe('ngClass', function() { <ide> element.addClass('foo'); <ide> $rootScope.dynCls = ''; <ide> $rootScope.$digest(); <add> expect(element[0].className).toBe('ng-scope'); <ide> })); <ide> <ide> <ide> it('should convert undefined and null values to an empty string', inject(function($rootScope, $compile) { <ide> element = $compile('<div ng-class="dynCls"></div>')($rootScope); <ide> $rootScope.dynCls = [undefined, null]; <ide> $rootScope.$digest(); <add> expect(element[0].className).toBe('ng-scope'); <ide> })); <ide> <ide>
1
Ruby
Ruby
fix a doc regression [ci skip]
543b865586b10eb47b7b395e4438bc9d39f2dca4
<ide><path>activerecord/lib/active_record/callbacks.rb <ide> module ActiveRecord <ide> # * (6) <tt>after_save</tt> <ide> # * (7) <tt>after_commit</tt> <ide> # <del> # Check out ActiveRecord::Transactions for more details about <tt>after_commit</tt> and <ide> # Also, an <tt>after_rollback</tt> callback can be configured to be triggered whenever a rollback is issued. <add> # Check out ActiveRecord::Transactions for more details about <tt>after_commit</tt> and <ide> # <tt>after_rollback</tt>. <ide> # <ide> # Additionally, an <tt>after_touch</tt> callback is triggered whenever an <ide> module ActiveRecord <ide> # <ide> # == Types of callbacks <ide> # <del> # There are four types of callbacks accepted by the callback macros: method references (symbol), callback objects, <add> # There are three types of callbacks accepted by the callback macros: method references (symbol), callback objects, <ide> # inline methods (using a proc). Method references and callback objects are the recommended approaches, <ide> # inline methods using a proc are sometimes appropriate (such as for creating mix-ins). <ide> #
1
Python
Python
add init and quit. clean the code. do stuff..
9aa5cbc1dbb5c04ccfac98d1be2bfd44502a6ee6
<ide><path>glances/glances.py <ide> def displayCaption(self): <ide> # Caption <ide> screen_x = self.screen.getmaxyx()[1] <ide> screen_y = self.screen.getmaxyx()[0] <del> msg = _("Press 'h' for help") <del> if (screen_y > self.caption_y and <del> screen_x > self.caption_x + 32): <add> if (client_tag): <add> msg_client = _("Connected to:")+" "+format(server_ip) <add> msg_help = _("Press 'h' for help") <add> if (client_tag): <add> if (screen_y > self.caption_y and <add> screen_x > self.caption_x + len(msg_client)): <add> self.term_window.addnstr(max(self.caption_y, screen_y - 1), <add> self.caption_x, msg_client, len(msg_client), <add> self.title_color if self.hascolors else <add> curses.A_UNDERLINE) <add> if (screen_x > self.caption_x + len(msg_client)+3+len(msg_help)): <add> self.term_window.addnstr(max(self.caption_y, screen_y - 1), <add> self.caption_x+len(msg_client), " | "+msg_help, 3+len(msg_help)) <add> else: <ide> self.term_window.addnstr(max(self.caption_y, screen_y - 1), <del> self.caption_x, msg, self.default_color) <del> <add> self.caption_x, msg_help, len(msg_help)) <add> <ide> def displayHelp(self): <ide> """ <ide> Show the help panel <ide> def update(self, stats): <ide> <ide> class GlancesHandler(SocketServer.BaseRequestHandler): <ide> """ <del> This class manages the TCP server <add> This class manages the TCP request <add> Return: <add> 0: GET Command success <add> 1: command unknown <add> 2: INIT Command success <add> 3: QUIT Command success <ide> """ <ide> <ide> def handle(self): <ide> # Get command from the Glances client <del> self.datarecv = self.request.recv(1024).strip() <add> self.datarecv = self.request.recv(1024) <ide> print "Receive the command %s from %s" % (format(self.datarecv), format(self.client_address[0])) <ide> if (self.datarecv == "GET"): <ide> # Send data to the Glances client <ide> stats.update() <add> # JSONify and ZIP stats <ide> # To be replaced when version 2.2.0 of the JSON will be available <ide> #~ self.datasend = zlib.compress(json.dumps(stats.getAll(), namedtuple_as_object = True)) <ide> self.datasend = zlib.compress(json.dumps(stats.getAll())) <ide> self.request.sendall(self.datasend) <add> return 0 <add> elif (self.datarecv == "INIT"): <add> # Send Glances version to the client <add> self.datasend = __version__ <add> self.request.sendall(self.datasend) <add> return 2 <add> elif (self.datarecv == "QUIT"): <add> # Send Glances version to the client <add> self.datasend = "BYE" <add> self.request.sendall(self.datasend) <add> return 3 <ide> else: <ide> print "Unknown command received" <add> return 1 <add> <add> <add>class GlancesServer(SocketServer.TCPServer): <add> """ <add> This class creates and manages the TCP server <add> """ <add> <add> def __init__(self, server_address, handler_class = GlancesHandler): <add> SocketServer.TCPServer.__init__(self, server_address, handler_class) <add> return <add> <add> def serve_forever(self): <add> """ <add> Main loop for the TCP server <add> """ <add> while True: <add> self.handle_request() <add> return <add> <add> <add>class GlancesClient(): <add> """ <add> This class creates and manages the TCP client <add> """ <add> <add> def __init__(self, server_address, server_port = 61209): <add> self.server_address = server_address <add> self.server_port = server_port <ide> return <ide> <add> def __sendandrecv__(self, command, jsonzip = True): <add> # Create a socket (SOCK_STREAM means a TCP socket) <add> SocketClient = socket.socket(socket.AF_INET, socket.SOCK_STREAM) <add> <add> # Connect to server and send data <add> SocketClient.connect((self.server_address, self.server_port)) <add> <add> # Send command <add> SocketClient.sendall(command) <add> <add> # Receive data from the server and shut down <add> buff_received = '' <add> while True: <add> buff = SocketClient.recv(8192) <add> if not buff: break <add> buff_received += buff <add> <add> # Close the socket <add> SocketClient.close() <add> <add> # Return the data sent by the server <add> if jsonzip: <add> # If asked: deJSONify and decompress <add> return json.loads(zlib.decompress(buff_received)) <add> else: <add> return buff_received <add> <add> def client_init(self): <add> if self.__sendandrecv__("INIT", jsonzip = False) != __version__: <add> return 1 <add> else: <add> return 0 <add> <add> def client_get(self): <add> return self.__sendandrecv__("GET") <add> <add> def client_quit(self): <add> return self.__sendandrecv__("QUIT", jsonzip = False) <ide> <ide> # Global def <ide> #=========== <ide> def init(): <ide> <ide> if server_tag: <ide> # Init the server <add> <ide> print(_("Start Glances as a server")) <del> server = SocketServer.TCPServer(("0.0.0.0", server_port), GlancesHandler) <add> server = GlancesServer(("0.0.0.0", server_port), GlancesHandler) <ide> <ide> # Init stats <ide> stats = glancesStats(server_tag = True) <ide> elif client_tag: <ide> # Init the client (displaying server stat in the CLI) <ide> <add> client = GlancesClient(server_ip, server_port) <add> <add> if client.client_init() != 0: <add> print(_("Error: The server version is not compatible")) <add> sys.exit(2) <add> <ide> # Init Limits <ide> limits = glancesLimits() <ide> <ide> def main(): <ide> <ide> if server_tag: <ide> # Start the server loop <del> # !!! TODO: Use http://www.doughellmann.com/PyMOTW/SocketServer/ <ide> server.serve_forever() <ide> elif client_tag: <ide> # Start the client loop <del> while True: <del> # Create a socket (SOCK_STREAM means a TCP socket) <del> client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) <del> <del> # Connect to server and send data <del> client.connect((server_ip, server_port)) <del> <del> # Send command <del> client.sendall("GET\n") <del> <del> # Receive data from the server and shut down <del> buff_received = '' <del> while True: <del> # !!! TODO: Test with higher buffer size <del> buff = client.recv(1024) <del> if not buff: break <del> buff_received += buff <del> client_stats = json.loads(zlib.decompress(buff_received)) <del> <del> # Close <del> client.close() <del> <del> # Get system informations <del> stats.update(client_stats) <add> while True: <add> # Get server system informations <add> stats.update(client.client_get()) <ide> <ide> # Update the screen <ide> screen.update(stats) <del> <del> # Update the HTML output <del> if html_tag: <del> htmloutput.update(stats) <del> <del> # Update the CSV output <del> if csv_tag: <del> csvoutput.update(stats) <ide> else: <ide> # Start the classical CLI loop <ide> while True: <ide> def end(): <ide> if server_tag: <ide> # Stop the server loop <ide> print(_("Stop Glances server")) <add> server.server_close() <ide> else: <del> # !!! TODO: something special to dor with client_tag ? <add> if client_tag: <add> # Stop the client loop <add> client.client_quit() <ide> <ide> # Stop the classical CLI loop <ide> screen.end()
1
Text
Text
fix windows links
1254425ba8dc8262e943f7ad09f3e3487e0b2801
<ide><path>README.md <ide> Atom will automatically update when a new release is available. <ide> <ide> **Windows Requirements** <ide> * Windows 7 or later <del> * [Visual C++ 2010 Express][http://www.microsoft.com/visualstudio/eng/products/visual-studio-2010-express] <del> * [node.js - 32bit][http://nodejs.org/] <del> * [Python 2.7.x][ http://www.python.org/download/] <del> * [GitHub for Windows][http://windows.github.com/] <del> * Clone [atom/atom][https://github.com/atom/atom/] to `C:\Users\<user>\github\atom\` <add> * [Visual C++ 2010 Express](http://www.microsoft.com/visualstudio/eng/products/visual-studio-2010-express) <add> * [node.js - 32bit](http://nodejs.org/) <add> * [Python 2.7.x](http://www.python.org/download/) <add> * [GitHub for Windows](http://windows.github.com/) <add> * Clone [atom/atom](https://github.com/atom/atom/) to `C:\Users\<user>\github\atom\` <ide> * Add `C:\Python27;C:\Program Files\nodejs;C:\Users\<user>\github\atom\node_modules\` <ide> to your PATH <ide> * Open the Windows GitHub shell
1
Javascript
Javascript
add crypto check to test-benchmark-http2
615160c38bc6c789f8215749291fea60aaae8db9
<ide><path>test/sequential/test-benchmark-http2.js <ide> 'use strict'; <ide> <ide> const common = require('../common'); <add>if (!common.hasCrypto) <add> common.skip('missing crypto'); <ide> <ide> if (!common.enoughTestMem) <ide> common.skip('Insufficient memory for HTTP/2 benchmark test');
1
Mixed
Javascript
prefix private controller methods with underscore
2f17dbcd701060c47818ea12d97ae6b813518277
<ide><path>docs/getting-started/v3-migration.md <ide> Animation system was completely rewritten in Chart.js v3. Each property can now <ide> <ide> #### Renamed private APIs <ide> <add>* `BarController.calculateBarIndexPixels` was renamed to `BarController._calculateBarIndexPixels` <add>* `BarController.calculateBarValuePixels` was renamed to `BarController._calculateBarValuePixels` <add>* `BarController.getStackCount` was renamed to `BarController._getStackCount` <add>* `BarController.getStackIndex` was renamed to `BarController._getStackIndex` <add>* `BarController.getRuler` was renamed to `BarController._getRuler` <add>* `Chart.destroyDatasetMeta` was renamed to `Chart._destroyDatasetMeta` <add>* `Chart.drawDataset` was renamed to `Chart._drawDataset` <add>* `Chart.drawDatasets` was renamed to `Chart._drawDatasets` <add>* `Chart.eventHandler` was renamed to `Chart._eventHandler` <add>* `Chart.handleEvent` was renamed to `Chart._handleEvent` <add>* `Chart.initialize` was renamed to `Chart._initialize` <add>* `Chart.resetElements` was renamed to `Chart._resetElements` <add>* `Chart.unbindEvents` was renamed to `Chart._unbindEvents` <add>* `Chart.updateDataset` was renamed to `Chart._updateDataset` <add>* `Chart.updateDatasets` was renamed to `Chart._updateDatasets` <add>* `Chart.updateLayout` was renamed to `Chart._updateLayout` <add>* `DatasetController.destroy` was renamed to `DatasetController._destroy` <add>* `DatasetController.insertElements` was renamed to `DatasetController._insertElements` <add>* `DatasetController.onDataPop` was renamed to `DatasetController._onDataPop` <add>* `DatasetController.onDataPush` was renamed to `DatasetController._onDataPush` <add>* `DatasetController.onDataShift` was renamed to `DatasetController._onDataShift` <add>* `DatasetController.onDataSplice` was renamed to `DatasetController._onDataSplice` <add>* `DatasetController.onDataUnshift` was renamed to `DatasetController._onDataUnshift` <add>* `DatasetController.removeElements` was renamed to `DatasetController._removeElements` <add>* `DatasetController.resyncElements` was renamed to `DatasetController._resyncElements` <ide> * `helpers._alignPixel` was renamed to `helpers.canvas._alignPixel` <ide> * `helpers._decimalPlaces` was renamed to `helpers.math._decimalPlaces` <del>* `chart.initialize` was renamed to `chart._initialize` (labeled as private but not named as such) <ide> <ide> ### Changed <ide> <ide><path>src/controllers/controller.bar.js <ide> class BarController extends DatasetController { <ide> const vscale = me._cachedMeta.vScale; <ide> const base = vscale.getBasePixel(); <ide> const horizontal = vscale.isHorizontal(); <del> const ruler = me.getRuler(); <add> const ruler = me._getRuler(); <ide> const firstOpts = me._resolveDataElementOptions(start, mode); <ide> const sharedOptions = me._getSharedOptions(mode, rectangles[start], firstOpts); <ide> const includeOptions = me._includeOptions(mode, sharedOptions); <ide> class BarController extends DatasetController { <ide> for (i = 0; i < rectangles.length; i++) { <ide> const index = start + i; <ide> const options = me._resolveDataElementOptions(index, mode); <del> const vpixels = me.calculateBarValuePixels(index, options); <del> const ipixels = me.calculateBarIndexPixels(index, ruler, options); <add> const vpixels = me._calculateBarValuePixels(index, options); <add> const ipixels = me._calculateBarIndexPixels(index, ruler, options); <ide> <ide> const properties = { <ide> horizontal, <ide> class BarController extends DatasetController { <ide> * Returns the effective number of stacks based on groups and bar visibility. <ide> * @private <ide> */ <del> getStackCount() { <add> _getStackCount() { <ide> return this._getStacks().length; <ide> } <ide> <ide> class BarController extends DatasetController { <ide> * @returns {number} The stack index <ide> * @private <ide> */ <del> getStackIndex(datasetIndex, name) { <add> _getStackIndex(datasetIndex, name) { <ide> var stacks = this._getStacks(datasetIndex); <ide> var index = (name !== undefined) <ide> ? stacks.indexOf(name) <ide> class BarController extends DatasetController { <ide> /** <ide> * @private <ide> */ <del> getRuler() { <add> _getRuler() { <ide> const me = this; <ide> const meta = me._cachedMeta; <ide> const iScale = meta.iScale; <ide> class BarController extends DatasetController { <ide> pixels, <ide> start: iScale._startPixel, <ide> end: iScale._endPixel, <del> stackCount: me.getStackCount(), <add> stackCount: me._getStackCount(), <ide> scale: iScale <ide> }; <ide> } <ide> class BarController extends DatasetController { <ide> * Note: pixel values are not clamped to the scale area. <ide> * @private <ide> */ <del> calculateBarValuePixels(index, options) { <add> _calculateBarValuePixels(index, options) { <ide> const me = this; <ide> const meta = me._cachedMeta; <ide> const vScale = meta.vScale; <ide> class BarController extends DatasetController { <ide> /** <ide> * @private <ide> */ <del> calculateBarIndexPixels(index, ruler, options) { <add> _calculateBarIndexPixels(index, ruler, options) { <ide> var me = this; <ide> var range = options.barThickness === 'flex' <ide> ? computeFlexCategoryTraits(index, ruler, options) <ide> : computeFitCategoryTraits(index, ruler, options); <ide> <del> var stackIndex = me.getStackIndex(me.index, me._cachedMeta.stack); <add> var stackIndex = me._getStackIndex(me.index, me._cachedMeta.stack); <ide> var center = range.start + (range.chunk * stackIndex) + (range.chunk / 2); <ide> var size = Math.min( <ide> valueOrDefault(options.maxBarThickness, Infinity), <ide><path>src/core/core.animator.js <ide> class Animator { <ide> } <ide> } <ide> <add> /** <add> * @private <add> */ <ide> _getAnims(chart) { <ide> const charts = this._charts; <ide> let anims = charts.get(chart); <ide><path>src/core/core.controller.js <ide> class Chart { <ide> this._updating = false; <ide> this.scales = {}; <ide> this.scale = undefined; <add> this.$plugins = undefined; <ide> <ide> // Add the chart instance to the global namespace <ide> Chart.instances[me.id] = me; <ide> class Chart { <ide> <ide> if (numMeta > numData) { <ide> for (let i = numData; i < numMeta; ++i) { <del> me.destroyDatasetMeta(i); <add> me._destroyDatasetMeta(i); <ide> } <ide> metasets.splice(numData, numMeta - numData); <ide> } <ide> class Chart { <ide> const type = dataset.type || me.config.type; <ide> <ide> if (meta.type && meta.type !== type) { <del> me.destroyDatasetMeta(i); <add> me._destroyDatasetMeta(i); <ide> meta = me.getDatasetMeta(i); <ide> } <ide> meta.type = type; <ide> class Chart { <ide> * Reset the elements of all datasets <ide> * @private <ide> */ <del> resetElements() { <add> _resetElements() { <ide> const me = this; <ide> helpers.each(me.data.datasets, function(dataset, datasetIndex) { <ide> me.getDatasetMeta(datasetIndex).controller.reset(); <ide> class Chart { <ide> * Resets the chart back to its state before the initial animation <ide> */ <ide> reset() { <del> this.resetElements(); <add> this._resetElements(); <ide> plugins.notify(this, 'reset'); <ide> } <ide> <ide> class Chart { <ide> me.getDatasetMeta(i).controller.buildOrUpdateElements(); <ide> } <ide> <del> me.updateLayout(); <add> me._updateLayout(); <ide> <ide> // Can only reset the new controllers after the scales have been updated <ide> if (me.options.animation) { <ide> class Chart { <ide> }); <ide> } <ide> <del> me.updateDatasets(mode); <add> me._updateDatasets(mode); <ide> <ide> // Do this before render so that any plugins that need final scale updates can use it <ide> plugins.notify(me, 'afterUpdate'); <ide> class Chart { <ide> <ide> // Replay last event from before update <ide> if (me._lastEvent) { <del> me.eventHandler(me._lastEvent); <add> me._eventHandler(me._lastEvent); <ide> } <ide> <ide> me.render(); <ide> class Chart { <ide> * hook, in which case, plugins will not be called on `afterLayout`. <ide> * @private <ide> */ <del> updateLayout() { <add> _updateLayout() { <ide> const me = this; <ide> <ide> if (plugins.notify(me, 'beforeLayout') === false) { <ide> class Chart { <ide> * hook, in which case, plugins will not be called on `afterDatasetsUpdate`. <ide> * @private <ide> */ <del> updateDatasets(mode) { <add> _updateDatasets(mode) { <ide> const me = this; <ide> const isFunction = typeof mode === 'function'; <ide> <ide> class Chart { <ide> } <ide> <ide> for (let i = 0, ilen = me.data.datasets.length; i < ilen; ++i) { <del> me.updateDataset(i, isFunction ? mode({datasetIndex: i}) : mode); <add> me._updateDataset(i, isFunction ? mode({datasetIndex: i}) : mode); <ide> } <ide> <ide> plugins.notify(me, 'afterDatasetsUpdate'); <ide> class Chart { <ide> * hook, in which case, plugins will not be called on `afterDatasetUpdate`. <ide> * @private <ide> */ <del> updateDataset(index, mode) { <add> _updateDataset(index, mode) { <ide> const me = this; <ide> const meta = me.getDatasetMeta(index); <ide> const args = {meta, index, mode}; <ide> class Chart { <ide> layers[i].draw(me.chartArea); <ide> } <ide> <del> me.drawDatasets(); <add> me._drawDatasets(); <ide> <ide> // Rest of layers <ide> for (; i < layers.length; ++i) { <ide> class Chart { <ide> * hook, in which case, plugins will not be called on `afterDatasetsDraw`. <ide> * @private <ide> */ <del> drawDatasets() { <add> _drawDatasets() { <ide> const me = this; <ide> let metasets, i; <ide> <ide> class Chart { <ide> <ide> metasets = me._getSortedVisibleDatasetMetas(); <ide> for (i = metasets.length - 1; i >= 0; --i) { <del> me.drawDataset(metasets[i]); <add> me._drawDataset(metasets[i]); <ide> } <ide> <ide> plugins.notify(me, 'afterDatasetsDraw'); <ide> class Chart { <ide> * hook, in which case, plugins will not be called on `afterDatasetDraw`. <ide> * @private <ide> */ <del> drawDataset(meta) { <add> _drawDataset(meta) { <ide> const me = this; <ide> const ctx = me.ctx; <ide> const clip = meta._clip; <ide> class Chart { <ide> /** <ide> * @private <ide> */ <del> destroyDatasetMeta(datasetIndex) { <add> _destroyDatasetMeta(datasetIndex) { <ide> const me = this; <ide> const meta = me._metasets && me._metasets[datasetIndex]; <ide> <ide> if (meta) { <del> meta.controller.destroy(); <add> meta.controller._destroy(); <ide> delete me._metasets[datasetIndex]; <ide> } <ide> } <ide> class Chart { <ide> <ide> // dataset controllers need to cleanup associated data <ide> for (i = 0, ilen = me.data.datasets.length; i < ilen; ++i) { <del> me.destroyDatasetMeta(i); <add> me._destroyDatasetMeta(i); <ide> } <ide> <ide> if (canvas) { <ide> class Chart { <ide> const me = this; <ide> const listeners = me._listeners; <ide> let listener = function() { <del> me.eventHandler.apply(me, arguments); <add> me._eventHandler.apply(me, arguments); <ide> }; <ide> <ide> helpers.each(me.options.events, function(type) { <ide> class Chart { <ide> /** <ide> * @private <ide> */ <del> eventHandler(e) { <add> _eventHandler(e) { <ide> const me = this; <ide> <ide> if (plugins.notify(me, 'beforeEvent', [e]) === false) { <ide> return; <ide> } <ide> <del> me.handleEvent(e); <add> me._handleEvent(e); <ide> <ide> plugins.notify(me, 'afterEvent', [e]); <ide> <ide> class Chart { <ide> <ide> /** <ide> * Handle an event <del> * @private <ide> * @param {IEvent} e the event to handle <ide> * @return {boolean} true if the chart needs to re-render <add> * @private <ide> */ <del> handleEvent(e) { <add> _handleEvent(e) { <ide> const me = this; <ide> const options = me.options || {}; <ide> const hoverOptions = options.hover; <ide><path>src/core/core.datasetController.js <ide> const arrayEvents = ['push', 'pop', 'shift', 'splice', 'unshift']; <ide> /** <ide> * Hooks the array methods that add or remove values ('push', pop', 'shift', 'splice', <ide> * 'unshift') and notify the listener AFTER the array has been altered. Listeners are <del> * called on the 'onData*' callbacks (e.g. onDataPush, etc.) with same arguments. <add> * called on the '_onData*' callbacks (e.g. _onDataPush, etc.) with same arguments. <ide> */ <ide> function listenArrayEvents(array, listener) { <ide> if (array._chartjs) { <ide> function listenArrayEvents(array, listener) { <ide> }); <ide> <ide> arrayEvents.forEach(function(key) { <del> var method = 'onData' + key.charAt(0).toUpperCase() + key.slice(1); <add> var method = '_onData' + key.charAt(0).toUpperCase() + key.slice(1); <ide> var base = array[key]; <ide> <ide> Object.defineProperty(array, key, { <ide> class DatasetController { <ide> /** <ide> * @private <ide> */ <del> destroy() { <add> _destroy() { <ide> if (this._data) { <ide> unlistenArrayEvents(this._data, this); <ide> } <ide> class DatasetController { <ide> <ide> // Re-sync meta data in case the user replaced the data array or if we missed <ide> // any updates and so make sure that we handle number of datapoints changing. <del> me.resyncElements(dataChanged || labelsChanged || scaleChanged || stackChanged); <add> me._resyncElements(dataChanged || labelsChanged || scaleChanged || stackChanged); <ide> <ide> // if stack changed, update stack values for the whole dataset <ide> if (stackChanged) { <ide> class DatasetController { <ide> /** <ide> * @private <ide> */ <del> resyncElements(changed) { <add> _resyncElements(changed) { <ide> const me = this; <ide> const meta = me._cachedMeta; <ide> const numMeta = meta.data.length; <ide> const numData = me._data.length; <ide> <ide> if (numData > numMeta) { <del> me.insertElements(numMeta, numData - numMeta); <add> me._insertElements(numMeta, numData - numMeta); <ide> if (changed && numMeta) { <del> // insertElements parses the new elements. The old ones might need parsing too. <add> // _insertElements parses the new elements. The old ones might need parsing too. <ide> me._parse(0, numMeta); <ide> } <ide> } else if (numData < numMeta) { <ide> class DatasetController { <ide> /** <ide> * @private <ide> */ <del> insertElements(start, count) { <add> _insertElements(start, count) { <ide> const me = this; <ide> const elements = new Array(count); <ide> const meta = me._cachedMeta; <ide> class DatasetController { <ide> /** <ide> * @private <ide> */ <del> removeElements(start, count) { <add> _removeElements(start, count) { <ide> const me = this; <ide> if (me._parsing) { <ide> me._cachedMeta._parsed.splice(start, count); <ide> class DatasetController { <ide> /** <ide> * @private <ide> */ <del> onDataPush() { <add> _onDataPush() { <ide> const count = arguments.length; <del> this.insertElements(this.getDataset().data.length - count, count); <add> this._insertElements(this.getDataset().data.length - count, count); <ide> } <ide> <ide> /** <ide> * @private <ide> */ <del> onDataPop() { <del> this.removeElements(this._cachedMeta.data.length - 1, 1); <add> _onDataPop() { <add> this._removeElements(this._cachedMeta.data.length - 1, 1); <ide> } <ide> <ide> /** <ide> * @private <ide> */ <del> onDataShift() { <del> this.removeElements(0, 1); <add> _onDataShift() { <add> this._removeElements(0, 1); <ide> } <ide> <ide> /** <ide> * @private <ide> */ <del> onDataSplice(start, count) { <del> this.removeElements(start, count); <del> this.insertElements(start, arguments.length - 2); <add> _onDataSplice(start, count) { <add> this._removeElements(start, count); <add> this._insertElements(start, arguments.length - 2); <ide> } <ide> <ide> /** <ide> * @private <ide> */ <del> onDataUnshift() { <del> this.insertElements(0, arguments.length); <add> _onDataUnshift() { <add> this._insertElements(0, arguments.length); <ide> } <ide> } <ide> <ide><path>src/core/core.plugins.js <ide> class PluginService { <ide> * @returns {boolean} false if any of the plugins return false, else returns true. <ide> */ <ide> notify(chart, hook, args) { <del> var descriptors = this.descriptors(chart); <add> var descriptors = this._descriptors(chart); <ide> var ilen = descriptors.length; <ide> var i, descriptor, plugin, params, method; <ide> <ide> class PluginService { <ide> <ide> /** <ide> * Returns descriptors of enabled plugins for the given chart. <add> * @param {Chart} chart <ide> * @returns {object[]} [{ plugin, options }] <ide> * @private <ide> */ <del> descriptors(chart) { <add> _descriptors(chart) { <ide> var cache = chart.$plugins || (chart.$plugins = {}); <ide> if (cache.id === this._cacheId) { <ide> return cache.descriptors; <ide> class PluginService { <ide> * Invalidates cache for the given chart: descriptors hold a reference on plugin option, <ide> * but in some cases, this reference can be changed by the user when updating options. <ide> * https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167 <add> * @param {Chart} chart <ide> * @private <ide> */ <ide> _invalidate(chart) { <ide><path>test/fixtures/core.tooltip/opacity.js <ide> module.exports = { <ide> clientX: rect.left + point.x, <ide> clientY: rect.top + point.y <ide> }; <del> chart.handleEvent(event); <add> chart._handleEvent(event); <ide> chart.tooltip.handleEvent(event); <ide> chart.tooltip.opacity = j / 10; <ide> chart.tooltip.draw(chart.ctx); <ide><path>test/specs/controller.bar.tests.js <ide> describe('Chart.controllers.bar', function() { <ide> }); <ide> <ide> var meta = chart.getDatasetMeta(1); <del> expect(meta.controller.getStackCount()).toBe(2); <add> expect(meta.controller._getStackCount()).toBe(2); <ide> }); <ide> }); <ide> <ide> describe('Chart.controllers.bar', function() { <ide> }); <ide> <ide> var meta = chart.getDatasetMeta(1); <del> expect(meta.controller.getStackCount()).toBe(4); <add> expect(meta.controller._getStackCount()).toBe(4); <ide> }); <ide> }); <ide> <ide> describe('Chart.controllers.bar', function() { <ide> }); <ide> <ide> var meta = chart.getDatasetMeta(1); <del> expect(meta.controller.getStackCount()).toBe(1); <add> expect(meta.controller._getStackCount()).toBe(1); <ide> }); <ide> }); <ide> <ide> describe('Chart.controllers.bar', function() { <ide> }); <ide> <ide> var meta = chart.getDatasetMeta(1); <del> expect(meta.controller.getStackCount()).toBe(4); <add> expect(meta.controller._getStackCount()).toBe(4); <ide> }); <ide> }); <ide> <ide> describe('Chart.controllers.bar', function() { <ide> }); <ide> <ide> var meta = chart.getDatasetMeta(3); <del> expect(meta.controller.getStackCount()).toBe(3); <add> expect(meta.controller._getStackCount()).toBe(3); <ide> }); <ide> }); <ide> <ide> describe('Chart.controllers.bar', function() { <ide> }); <ide> <ide> var meta = chart.getDatasetMeta(3); <del> expect(meta.controller.getStackCount()).toBe(2); <add> expect(meta.controller._getStackCount()).toBe(2); <ide> }); <ide> }); <ide> <ide> describe('Chart.controllers.bar', function() { <ide> }); <ide> <ide> var meta = chart.getDatasetMeta(3); <del> expect(meta.controller.getStackCount()).toBe(4); <add> expect(meta.controller._getStackCount()).toBe(4); <ide> }); <ide> }); <ide> <ide> describe('Chart.controllers.bar', function() { <ide> }); <ide> <ide> var meta = chart.getDatasetMeta(3); <del> expect(meta.controller.getStackCount()).toBe(2); <add> expect(meta.controller._getStackCount()).toBe(2); <ide> }); <ide> }); <ide> <ide> describe('Chart.controllers.bar', function() { <ide> }); <ide> <ide> var meta = chart.getDatasetMeta(3); <del> expect(meta.controller.getStackCount()).toBe(2); <add> expect(meta.controller._getStackCount()).toBe(2); <ide> }); <ide> }); <ide> <ide> describe('Chart.controllers.bar', function() { <ide> }); <ide> <ide> var meta = chart.getDatasetMeta(3); <del> expect(meta.controller.getStackCount()).toBe(4); <add> expect(meta.controller._getStackCount()).toBe(4); <ide> }); <ide> }); <ide> <ide> describe('Chart.controllers.bar', function() { <ide> }); <ide> <ide> var meta = chart.getDatasetMeta(1); <del> expect(meta.controller.getStackIndex(0)).toBe(0); <del> expect(meta.controller.getStackIndex(3)).toBe(1); <add> expect(meta.controller._getStackIndex(0)).toBe(0); <add> expect(meta.controller._getStackIndex(3)).toBe(1); <ide> }); <ide> }); <ide> <ide> describe('Chart.controllers.bar', function() { <ide> }); <ide> <ide> var meta = chart.getDatasetMeta(1); <del> expect(meta.controller.getStackIndex(0)).toBe(0); <del> expect(meta.controller.getStackIndex(1)).toBe(1); <del> expect(meta.controller.getStackIndex(2)).toBe(2); <del> expect(meta.controller.getStackIndex(3)).toBe(3); <add> expect(meta.controller._getStackIndex(0)).toBe(0); <add> expect(meta.controller._getStackIndex(1)).toBe(1); <add> expect(meta.controller._getStackIndex(2)).toBe(2); <add> expect(meta.controller._getStackIndex(3)).toBe(3); <ide> }); <ide> }); <ide> <ide> describe('Chart.controllers.bar', function() { <ide> }); <ide> <ide> var meta = chart.getDatasetMeta(1); <del> expect(meta.controller.getStackIndex(0)).toBe(0); <del> expect(meta.controller.getStackIndex(1)).toBe(0); <del> expect(meta.controller.getStackIndex(2)).toBe(0); <del> expect(meta.controller.getStackIndex(3)).toBe(0); <add> expect(meta.controller._getStackIndex(0)).toBe(0); <add> expect(meta.controller._getStackIndex(1)).toBe(0); <add> expect(meta.controller._getStackIndex(2)).toBe(0); <add> expect(meta.controller._getStackIndex(3)).toBe(0); <ide> }); <ide> }); <ide> <ide> describe('Chart.controllers.bar', function() { <ide> }); <ide> <ide> var meta = chart.getDatasetMeta(1); <del> expect(meta.controller.getStackIndex(0)).toBe(0); <del> expect(meta.controller.getStackIndex(1)).toBe(1); <del> expect(meta.controller.getStackIndex(2)).toBe(2); <del> expect(meta.controller.getStackIndex(3)).toBe(3); <add> expect(meta.controller._getStackIndex(0)).toBe(0); <add> expect(meta.controller._getStackIndex(1)).toBe(1); <add> expect(meta.controller._getStackIndex(2)).toBe(2); <add> expect(meta.controller._getStackIndex(3)).toBe(3); <ide> }); <ide> }); <ide> <ide> describe('Chart.controllers.bar', function() { <ide> }); <ide> <ide> var meta = chart.getDatasetMeta(1); <del> expect(meta.controller.getStackIndex(0)).toBe(0); <del> expect(meta.controller.getStackIndex(1)).toBe(0); <del> expect(meta.controller.getStackIndex(2)).toBe(1); <del> expect(meta.controller.getStackIndex(3)).toBe(2); <add> expect(meta.controller._getStackIndex(0)).toBe(0); <add> expect(meta.controller._getStackIndex(1)).toBe(0); <add> expect(meta.controller._getStackIndex(2)).toBe(1); <add> expect(meta.controller._getStackIndex(3)).toBe(2); <ide> }); <ide> }); <ide> <ide> describe('Chart.controllers.bar', function() { <ide> }); <ide> <ide> var meta = chart.getDatasetMeta(1); <del> expect(meta.controller.getStackIndex(0)).toBe(0); <del> expect(meta.controller.getStackIndex(1)).toBe(0); <del> expect(meta.controller.getStackIndex(2)).toBe(1); <del> expect(meta.controller.getStackIndex(3)).toBe(1); <add> expect(meta.controller._getStackIndex(0)).toBe(0); <add> expect(meta.controller._getStackIndex(1)).toBe(0); <add> expect(meta.controller._getStackIndex(2)).toBe(1); <add> expect(meta.controller._getStackIndex(3)).toBe(1); <ide> }); <ide> }); <ide> <ide> describe('Chart.controllers.bar', function() { <ide> }); <ide> <ide> var meta = chart.getDatasetMeta(1); <del> expect(meta.controller.getStackIndex(0)).toBe(0); <del> expect(meta.controller.getStackIndex(1)).toBe(1); <del> expect(meta.controller.getStackIndex(2)).toBe(2); <del> expect(meta.controller.getStackIndex(3)).toBe(3); <add> expect(meta.controller._getStackIndex(0)).toBe(0); <add> expect(meta.controller._getStackIndex(1)).toBe(1); <add> expect(meta.controller._getStackIndex(2)).toBe(2); <add> expect(meta.controller._getStackIndex(3)).toBe(3); <ide> }); <ide> }); <ide> <ide> describe('Chart.controllers.bar', function() { <ide> }); <ide> <ide> var meta = chart.getDatasetMeta(1); <del> expect(meta.controller.getStackIndex(0)).toBe(0); <del> expect(meta.controller.getStackIndex(1)).toBe(0); <del> expect(meta.controller.getStackIndex(2)).toBe(1); <del> expect(meta.controller.getStackIndex(3)).toBe(1); <add> expect(meta.controller._getStackIndex(0)).toBe(0); <add> expect(meta.controller._getStackIndex(1)).toBe(0); <add> expect(meta.controller._getStackIndex(2)).toBe(1); <add> expect(meta.controller._getStackIndex(3)).toBe(1); <ide> }); <ide> }); <ide> <ide> describe('Chart.controllers.bar', function() { <ide> }); <ide> <ide> var meta = chart.getDatasetMeta(1); <del> expect(meta.controller.getStackIndex(0)).toBe(0); <del> expect(meta.controller.getStackIndex(1)).toBe(0); <del> expect(meta.controller.getStackIndex(2)).toBe(1); <del> expect(meta.controller.getStackIndex(3)).toBe(1); <add> expect(meta.controller._getStackIndex(0)).toBe(0); <add> expect(meta.controller._getStackIndex(1)).toBe(0); <add> expect(meta.controller._getStackIndex(2)).toBe(1); <add> expect(meta.controller._getStackIndex(3)).toBe(1); <ide> }); <ide> }); <ide> <ide> describe('Chart.controllers.bar', function() { <ide> }); <ide> <ide> var meta = chart.getDatasetMeta(1); <del> expect(meta.controller.getStackIndex(0)).toBe(0); <del> expect(meta.controller.getStackIndex(1)).toBe(1); <del> expect(meta.controller.getStackIndex(2)).toBe(2); <del> expect(meta.controller.getStackIndex(3)).toBe(3); <add> expect(meta.controller._getStackIndex(0)).toBe(0); <add> expect(meta.controller._getStackIndex(1)).toBe(1); <add> expect(meta.controller._getStackIndex(2)).toBe(2); <add> expect(meta.controller._getStackIndex(3)).toBe(3); <ide> }); <ide> }); <ide> <ide><path>test/specs/core.datasetController.tests.js <ide> describe('Chart.DatasetController', function() { <ide> <ide> var controller = chart.getDatasetMeta(0).controller; <ide> var methods = [ <del> 'onDataPush', <del> 'onDataPop', <del> 'onDataShift', <del> 'onDataSplice', <del> 'onDataUnshift' <add> '_onDataPush', <add> '_onDataPop', <add> '_onDataShift', <add> '_onDataSplice', <add> '_onDataUnshift' <ide> ]; <ide> <ide> methods.forEach(function(method) { <ide><path>test/utils.js <ide> function waitForResize(chart, callback) { <ide> } <ide> <ide> function afterEvent(chart, type, callback) { <del> var override = chart.eventHandler; <del> chart.eventHandler = function(event) { <add> var override = chart._eventHandler; <add> chart._eventHandler = function(event) { <ide> override.call(this, event); <ide> if (event.type === type) { <del> chart.eventHandler = override; <add> chart._eventHandler = override; <ide> // eslint-disable-next-line callback-return <ide> callback(); <ide> }
10
Text
Text
update changelog for the folding changes
afa92e51f65740793c150730afafe44c9b9880d7
<ide><path>CHANGELOG.md <ide> * Added: Inspect Element context menu <ide> * Fixed: Save As dialog now defaults to directory path of current editor <ide> * Fixed: Using toggle comment shortcut respects indentation level <add>* Fixed: Folding all will fold comments as well <add>* Added: Ability to fold all code at a given indentation level <ide> <ide> * Fixed: Search never completing in the command panel <ide>
1
Javascript
Javascript
improve merging of resolve and parsing options
b3ec7754530fa6146dfe0211e014bcbbdacce065
<ide><path>lib/NormalModuleFactory.js <ide> const { <ide> const NormalModule = require("./NormalModule"); <ide> const RawModule = require("./RawModule"); <ide> const RuleSet = require("./RuleSet"); <del>const cachedMerge = require("./util/cachedMerge"); <add>const { cachedCleverMerge } = require("./util/cleverMerge"); <ide> <ide> const EMPTY_RESOLVE_OPTIONS = {}; <ide> <ide> class NormalModuleFactory extends Tapable { <ide> typeof settings[r.type] === "object" && <ide> settings[r.type] !== null <ide> ) { <del> settings[r.type] = cachedMerge(settings[r.type], r.value); <add> settings[r.type] = cachedCleverMerge(settings[r.type], r.value); <ide> } else { <ide> settings[r.type] = r.value; <ide> } <ide><path>lib/ResolverFactory.js <ide> <ide> const { Tapable, HookMap, SyncHook, SyncWaterfallHook } = require("tapable"); <ide> const Factory = require("enhanced-resolve").ResolverFactory; <add>const { cachedCleverMerge } = require("./util/cleverMerge"); <ide> <ide> /** @typedef {import("enhanced-resolve").Resolver} Resolver */ <ide> <ide> module.exports = class ResolverFactory extends Tapable { <ide> resolver.withOptions = options => { <ide> const cacheEntry = childCache.get(options); <ide> if (cacheEntry !== undefined) return cacheEntry; <del> const mergedOptions = Object.assign({}, originalResolveOptions, options); <add> const mergedOptions = cachedCleverMerge(originalResolveOptions, options); <ide> const resolver = this.get(type, mergedOptions); <ide> childCache.set(options, resolver); <ide> return resolver; <ide><path>lib/WebpackOptionsApply.js <ide> const RequireContextPlugin = require("./dependencies/RequireContextPlugin"); <ide> const RequireEnsurePlugin = require("./dependencies/RequireEnsurePlugin"); <ide> const RequireIncludePlugin = require("./dependencies/RequireIncludePlugin"); <ide> <add>const { cachedCleverMerge } = require("./util/cleverMerge"); <add> <ide> /** @typedef {import("../declarations/WebpackOptions").WebpackOptions} WebpackOptions */ <ide> /** @typedef {import("./Compiler")} Compiler */ <ide> <ide> class WebpackOptionsApply extends OptionsApply { <ide> { <ide> fileSystem: compiler.inputFileSystem <ide> }, <del> options.resolve, <del> resolveOptions <add> cachedCleverMerge(options.resolve, resolveOptions) <ide> ); <ide> }); <ide> compiler.resolverFactory.hooks.resolveOptions <ide> class WebpackOptionsApply extends OptionsApply { <ide> fileSystem: compiler.inputFileSystem, <ide> resolveToContext: true <ide> }, <del> options.resolve, <del> resolveOptions <add> cachedCleverMerge(options.resolve, resolveOptions) <ide> ); <ide> }); <ide> compiler.resolverFactory.hooks.resolveOptions <ide> class WebpackOptionsApply extends OptionsApply { <ide> { <ide> fileSystem: compiler.inputFileSystem <ide> }, <del> options.resolveLoader, <del> resolveOptions <add> cachedCleverMerge(options.resolveLoader, resolveOptions) <ide> ); <ide> }); <ide> compiler.hooks.afterResolvers.call(compiler); <ide><path>lib/util/cleverMerge.js <add>/* <add> MIT License http://www.opensource.org/licenses/mit-license.php <add> Author Tobias Koppers @sokra <add>*/ <add> <add>"use strict"; <add> <add>const mergeCache = new WeakMap(); <add> <add>/** <add> * Merges two given objects and caches the result to avoid computation if same objects passed as arguments again. <add> * @example <add> * // performs cleverMerge(first, second), stores the result in WeakMap and returns result <add> * cachedCleverMerge({a: 1}, {a: 2}) <add> * {a: 2} <add> * // when same arguments passed, gets the result from WeakMap and returns it. <add> * cachedCleverMerge({a: 1}, {a: 2}) <add> * {a: 2} <add> * @param {object} first first object <add> * @param {object} second second object <add> * @returns {object} merged object of first and second object <add> */ <add>const cachedCleverMerge = (first, second) => { <add> let innerCache = mergeCache.get(first); <add> if (innerCache === undefined) { <add> innerCache = new WeakMap(); <add> mergeCache.set(first, innerCache); <add> } <add> const prevMerge = innerCache.get(second); <add> if (prevMerge !== undefined) return prevMerge; <add> const newMerge = cleverMerge(first, second); <add> innerCache.set(second, newMerge); <add> return newMerge; <add>}; <add> <add>/** <add> * Merges two objects. Objects are not deeply merged. <add> * TODO webpack 5: merge objects deeply clever. <add> * Arrays might reference the old value with "..." <add> * @param {object} first first object <add> * @param {object} second second object <add> * @returns {object} merged object of first and second object <add> */ <add>const cleverMerge = (first, second) => { <add> const newObject = Object.assign({}, first); <add> for (const key of Object.keys(second)) { <add> if (!(key in newObject)) { <add> newObject[key] = second[key]; <add> continue; <add> } <add> const secondValue = second[key]; <add> if (!Array.isArray(secondValue)) { <add> newObject[key] = secondValue; <add> continue; <add> } <add> const firstValue = newObject[key]; <add> if (Array.isArray(firstValue)) { <add> const newArray = []; <add> for (const item of secondValue) { <add> if (item === "...") { <add> for (const item of firstValue) { <add> newArray.push(item); <add> } <add> } else { <add> newArray.push(item); <add> } <add> } <add> newObject[key] = newArray; <add> } else { <add> newObject[key] = secondValue; <add> } <add> } <add> return newObject; <add>}; <add> <add>exports.cachedCleverMerge = cachedCleverMerge; <add>exports.cleverMerge = cleverMerge; <ide><path>test/cases/loaders/resolve/index.js <ide> it("should be possible to create resolver with different options", () => { <ide> const result = require("./loader!"); <ide> expect(result).toEqual({ <ide> one: "index.js", <del> two: "index.xyz" <add> two: "index.xyz", <add> three: "index.js", <add> four: "index.xyz", <add> five: "index.js" <ide> }); <del>}) <add>}); <ide><path>test/cases/loaders/resolve/loader.js <ide> module.exports = function() { <ide> const resolve2 = this.getResolve({ <ide> extensions: [".xyz", ".js"] <ide> }); <add> const resolve3 = this.getResolve({ <add> extensions: [".hee", "..."] <add> }); <add> const resolve4 = this.getResolve({ <add> extensions: [".xyz", "..."] <add> }); <add> const resolve5 = this.getResolve({ <add> extensions: ["...", ".xyz"] <add> }); <ide> return Promise.all([ <ide> resolve1(__dirname, "./index"), <del> resolve2(__dirname, "./index") <del> ]).then(([one, two]) => { <add> resolve2(__dirname, "./index"), <add> resolve3(__dirname, "./index"), <add> resolve4(__dirname, "./index"), <add> resolve5(__dirname, "./index") <add> ]).then(([one, two, three, four, five]) => { <ide> return `module.exports = ${JSON.stringify({ <ide> one: path.basename(one), <ide> two: path.basename(two), <add> three: path.basename(three), <add> four: path.basename(four), <add> five: path.basename(five) <ide> })}`; <ide> }); <ide> }; <ide><path>test/configCases/rule-set/resolve-options/a.js <del>module.exports = require("./wrong"); <add>module.exports = require("./wrong") + require("./normal") + require("./wrong2"); <ide><path>test/configCases/rule-set/resolve-options/b.js <del>module.exports = require("./wrong"); <add>module.exports = require("./wrong") + require("./normal") + require("./wrong2"); <ide><path>test/configCases/rule-set/resolve-options/c.js <add>module.exports = require("./wrong") + require("./normal") + require("./wrong2"); <ide><path>test/configCases/rule-set/resolve-options/index.js <ide> it("should allow to set custom resolving rules", function() { <ide> var a = require("./a"); <del> expect(a).toBe("ok"); <add> expect(a).toBe("ok-normal-wrong2"); <ide> var b = require("./b"); <del> expect(b).toBe("wrong"); <add> expect(b).toBe("ok-normal-wrong2-yes"); <add> var c = require("./c"); <add> expect(c).toBe("wrong-normal-ok2"); <ide> }); <ide><path>test/configCases/rule-set/resolve-options/normal.js <add>module.exports = "-normal-"; <ide><path>test/configCases/rule-set/resolve-options/ok.ok.js <add>module.exports = "ok-ok"; <ide><path>test/configCases/rule-set/resolve-options/ok2.js <add>module.exports = "ok2"; <ide><path>test/configCases/rule-set/resolve-options/ok2.yes.js <add>module.exports = "ok2-yes"; <ide><path>test/configCases/rule-set/resolve-options/webpack.config.js <ide> module.exports = { <add> resolve: { <add> alias: { <add> "./wrong2": "./ok2" <add> } <add> }, <ide> module: { <ide> rules: [ <ide> { <ide> test: require.resolve("./a"), <ide> resolve: { <ide> alias: { <ide> "./wrong": "./ok" <del> } <add> }, <add> extensions: [".js", ".ok.js"] <add> } <add> }, <add> { <add> test: require.resolve("./b"), <add> resolve: { <add> alias: { <add> "./wrong": "./ok" <add> }, <add> extensions: ["...", ".ok.js"] <add> } <add> }, <add> { <add> test: require.resolve("./b"), <add> resolve: { <add> extensions: [".yes.js", "..."] <ide> } <ide> } <ide> ] <ide><path>test/configCases/rule-set/resolve-options/wrong2.js <add>module.exports = "wrong2"; <ide><path>test/configCases/rule-set/resolve-options/wrong2.yes.js <add>module.exports = "wrong2-yes";
17
Javascript
Javascript
move sync task queue to its own module
dbe98a5aae79efce4de3eea95171d1ef70537fdb
<ide><path>packages/react-dom/src/events/ReactDOMEventListener.js <ide> import { <ide> import getEventTarget from './getEventTarget'; <ide> import {getClosestInstanceFromNode} from '../client/ReactDOMComponentTree'; <ide> <del>import { <del> enableLegacyFBSupport, <del> enableNewReconciler, <del>} from 'shared/ReactFeatureFlags'; <add>import {enableLegacyFBSupport} from 'shared/ReactFeatureFlags'; <ide> import {dispatchEventForPluginEventSystem} from './DOMPluginEventSystem'; <ide> import { <ide> flushDiscreteUpdatesIfNeeded, <ide> discreteUpdates, <ide> } from './ReactDOMUpdateBatching'; <ide> <del>import {getCurrentPriorityLevel as getCurrentPriorityLevel_old} from 'react-reconciler/src/SchedulerWithReactIntegration.old'; <ide> import { <del> getCurrentPriorityLevel as getCurrentPriorityLevel_new, <add> getCurrentPriorityLevel as getCurrentSchedulerPriorityLevel, <ide> IdlePriority as IdleSchedulerPriority, <ide> ImmediatePriority as ImmediateSchedulerPriority, <ide> LowPriority as LowSchedulerPriority, <ide> NormalPriority as NormalSchedulerPriority, <ide> UserBlockingPriority as UserBlockingSchedulerPriority, <del>} from 'react-reconciler/src/SchedulerWithReactIntegration.new'; <add>} from 'react-reconciler/src/Scheduler'; <ide> import { <ide> DiscreteEventPriority, <ide> ContinuousEventPriority, <ide> import { <ide> setCurrentUpdatePriority, <ide> } from 'react-reconciler/src/ReactEventPriorities'; <ide> <del>const getCurrentPriorityLevel = enableNewReconciler <del> ? getCurrentPriorityLevel_new <del> : getCurrentPriorityLevel_old; <del> <ide> // TODO: can we stop exporting these? <ide> export let _enabled = true; <ide> <ide> export function getEventPriority(domEventName: DOMEventName): * { <ide> // We might be in the Scheduler callback. <ide> // Eventually this mechanism will be replaced by a check <ide> // of the current priority on the native scheduler. <del> const schedulerPriority = getCurrentPriorityLevel(); <add> const schedulerPriority = getCurrentSchedulerPriorityLevel(); <ide> switch (schedulerPriority) { <ide> case ImmediateSchedulerPriority: <ide> return DiscreteEventPriority; <ide><path>packages/react-reconciler/src/ReactFiberCompleteWork.new.js <ide> import type {Cache, SpawnedCachePool} from './ReactFiberCacheComponent.new'; <ide> <ide> import {resetWorkInProgressVersions as resetMutableSourceWorkInProgressVersions} from './ReactMutableSource.new'; <ide> <del>import {now} from './SchedulerWithReactIntegration.new'; <add>import {now} from './Scheduler'; <ide> <ide> import { <ide> IndeterminateComponent, <ide><path>packages/react-reconciler/src/ReactFiberCompleteWork.old.js <ide> import type {Cache, SpawnedCachePool} from './ReactFiberCacheComponent.old'; <ide> <ide> import {resetWorkInProgressVersions as resetMutableSourceWorkInProgressVersions} from './ReactMutableSource.old'; <ide> <del>import {now} from './SchedulerWithReactIntegration.old'; <add>import {now} from './Scheduler'; <ide> <ide> import { <ide> IndeterminateComponent, <ide><path>packages/react-reconciler/src/ReactFiberDevToolsHook.new.js <ide> import { <ide> UserBlockingPriority as UserBlockingSchedulerPriority, <ide> NormalPriority as NormalSchedulerPriority, <ide> IdlePriority as IdleSchedulerPriority, <del>} from './SchedulerWithReactIntegration.new'; <add>} from './Scheduler'; <ide> <ide> declare var __REACT_DEVTOOLS_GLOBAL_HOOK__: Object | void; <ide> <ide><path>packages/react-reconciler/src/ReactFiberDevToolsHook.old.js <ide> import { <ide> UserBlockingPriority as UserBlockingSchedulerPriority, <ide> NormalPriority as NormalSchedulerPriority, <ide> IdlePriority as IdleSchedulerPriority, <del>} from './SchedulerWithReactIntegration.old'; <add>} from './Scheduler'; <ide> <ide> declare var __REACT_DEVTOOLS_GLOBAL_HOOK__: Object | void; <ide> <ide><path>packages/react-reconciler/src/ReactFiberSyncTaskQueue.new.js <add>/** <add> * Copyright (c) Facebook, Inc. and its affiliates. <add> * <add> * This source code is licensed under the MIT license found in the <add> * LICENSE file in the root directory of this source tree. <add> * <add> * @flow <add> */ <add> <add>import type {SchedulerCallback} from './Scheduler'; <add> <add>import { <add> DiscreteEventPriority, <add> getCurrentUpdatePriority, <add> setCurrentUpdatePriority, <add>} from './ReactEventPriorities.new'; <add>import {ImmediatePriority, scheduleCallback} from './Scheduler'; <add> <add>let syncQueue: Array<SchedulerCallback> | null = null; <add>let isFlushingSyncQueue: boolean = false; <add> <add>export function scheduleSyncCallback(callback: SchedulerCallback) { <add> // Push this callback into an internal queue. We'll flush these either in <add> // the next tick, or earlier if something calls `flushSyncCallbackQueue`. <add> if (syncQueue === null) { <add> syncQueue = [callback]; <add> } else { <add> // Push onto existing queue. Don't need to schedule a callback because <add> // we already scheduled one when we created the queue. <add> syncQueue.push(callback); <add> } <add>} <add> <add>export function flushSyncCallbackQueue() { <add> if (!isFlushingSyncQueue && syncQueue !== null) { <add> // Prevent re-entrancy. <add> isFlushingSyncQueue = true; <add> let i = 0; <add> const previousUpdatePriority = getCurrentUpdatePriority(); <add> try { <add> const isSync = true; <add> const queue = syncQueue; <add> // TODO: Is this necessary anymore? The only user code that runs in this <add> // queue is in the render or commit phases. <add> setCurrentUpdatePriority(DiscreteEventPriority); <add> for (; i < queue.length; i++) { <add> let callback = queue[i]; <add> do { <add> callback = callback(isSync); <add> } while (callback !== null); <add> } <add> syncQueue = null; <add> } catch (error) { <add> // If something throws, leave the remaining callbacks on the queue. <add> if (syncQueue !== null) { <add> syncQueue = syncQueue.slice(i + 1); <add> } <add> // Resume flushing in the next tick <add> scheduleCallback(ImmediatePriority, flushSyncCallbackQueue); <add> throw error; <add> } finally { <add> setCurrentUpdatePriority(previousUpdatePriority); <add> isFlushingSyncQueue = false; <add> } <add> } <add> return null; <add>} <add><path>packages/react-reconciler/src/ReactFiberSyncTaskQueue.old.js <del><path>packages/react-reconciler/src/SchedulerWithReactIntegration.old.js <ide> * @flow <ide> */ <ide> <del>// This module only exists as an ESM wrapper around the external CommonJS <del>// Scheduler dependency. Notice that we're intentionally not using named imports <del>// because Rollup would use dynamic dispatch for CommonJS interop named imports. <del>// When we switch to ESM, we can delete this module. <del>import * as Scheduler from 'scheduler'; <del>import {__interactionsRef} from 'scheduler/tracing'; <del>import {enableSchedulerTracing} from 'shared/ReactFeatureFlags'; <del>import invariant from 'shared/invariant'; <add>import type {SchedulerCallback} from './Scheduler'; <add> <ide> import { <ide> DiscreteEventPriority, <ide> getCurrentUpdatePriority, <ide> setCurrentUpdatePriority, <ide> } from './ReactEventPriorities.old'; <add>import {ImmediatePriority, scheduleCallback} from './Scheduler'; <ide> <del>export const scheduleCallback = Scheduler.unstable_scheduleCallback; <del>export const cancelCallback = Scheduler.unstable_cancelCallback; <del>export const shouldYield = Scheduler.unstable_shouldYield; <del>export const requestPaint = Scheduler.unstable_requestPaint; <del>export const now = Scheduler.unstable_now; <del>export const getCurrentPriorityLevel = <del> Scheduler.unstable_getCurrentPriorityLevel; <del>export const ImmediatePriority = Scheduler.unstable_ImmediatePriority; <del>export const UserBlockingPriority = Scheduler.unstable_UserBlockingPriority; <del>export const NormalPriority = Scheduler.unstable_NormalPriority; <del>export const LowPriority = Scheduler.unstable_LowPriority; <del>export const IdlePriority = Scheduler.unstable_IdlePriority; <del> <del>if (enableSchedulerTracing) { <del> // Provide explicit error message when production+profiling bundle of e.g. <del> // react-dom is used with production (non-profiling) bundle of <del> // scheduler/tracing <del> invariant( <del> __interactionsRef != null && __interactionsRef.current != null, <del> 'It is not supported to run the profiling version of a renderer (for ' + <del> 'example, `react-dom/profiling`) without also replacing the ' + <del> '`scheduler/tracing` module with `scheduler/tracing-profiling`. Your ' + <del> 'bundler might have a setting for aliasing both modules. Learn more at ' + <del> 'https://reactjs.org/link/profiling', <del> ); <del>} <del> <del>export type SchedulerCallback = (isSync: boolean) => SchedulerCallback | null; <del> <del>// TODO: Move sync task queue to its own module. <ide> let syncQueue: Array<SchedulerCallback> | null = null; <ide> let isFlushingSyncQueue: boolean = false; <ide> <ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.new.js <ide> import { <ide> UserBlockingPriority as UserBlockingSchedulerPriority, <ide> NormalPriority as NormalSchedulerPriority, <ide> IdlePriority as IdleSchedulerPriority, <add>} from './Scheduler'; <add>import { <ide> flushSyncCallbackQueue, <ide> scheduleSyncCallback, <del>} from './SchedulerWithReactIntegration.new'; <add>} from './ReactFiberSyncTaskQueue.new'; <ide> import { <ide> NoFlags as NoHookEffect, <ide> Passive as HookPassive, <ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.old.js <ide> import { <ide> UserBlockingPriority as UserBlockingSchedulerPriority, <ide> NormalPriority as NormalSchedulerPriority, <ide> IdlePriority as IdleSchedulerPriority, <add>} from './Scheduler'; <add>import { <ide> flushSyncCallbackQueue, <ide> scheduleSyncCallback, <del>} from './SchedulerWithReactIntegration.old'; <add>} from './ReactFiberSyncTaskQueue.old'; <ide> import { <ide> NoFlags as NoHookEffect, <ide> Passive as HookPassive, <add><path>packages/react-reconciler/src/Scheduler.js <del><path>packages/react-reconciler/src/SchedulerWithReactIntegration.new.js <ide> import * as Scheduler from 'scheduler'; <ide> import {__interactionsRef} from 'scheduler/tracing'; <ide> import {enableSchedulerTracing} from 'shared/ReactFeatureFlags'; <ide> import invariant from 'shared/invariant'; <del>import { <del> DiscreteEventPriority, <del> getCurrentUpdatePriority, <del> setCurrentUpdatePriority, <del>} from './ReactEventPriorities.new'; <ide> <ide> export const scheduleCallback = Scheduler.unstable_scheduleCallback; <ide> export const cancelCallback = Scheduler.unstable_cancelCallback; <ide> if (enableSchedulerTracing) { <ide> } <ide> <ide> export type SchedulerCallback = (isSync: boolean) => SchedulerCallback | null; <del> <del>// TODO: Move sync task queue to its own module. <del>let syncQueue: Array<SchedulerCallback> | null = null; <del>let isFlushingSyncQueue: boolean = false; <del> <del>export function scheduleSyncCallback(callback: SchedulerCallback) { <del> // Push this callback into an internal queue. We'll flush these either in <del> // the next tick, or earlier if something calls `flushSyncCallbackQueue`. <del> if (syncQueue === null) { <del> syncQueue = [callback]; <del> } else { <del> // Push onto existing queue. Don't need to schedule a callback because <del> // we already scheduled one when we created the queue. <del> syncQueue.push(callback); <del> } <del>} <del> <del>export function flushSyncCallbackQueue() { <del> if (!isFlushingSyncQueue && syncQueue !== null) { <del> // Prevent re-entrancy. <del> isFlushingSyncQueue = true; <del> let i = 0; <del> const previousUpdatePriority = getCurrentUpdatePriority(); <del> try { <del> const isSync = true; <del> const queue = syncQueue; <del> // TODO: Is this necessary anymore? The only user code that runs in this <del> // queue is in the render or commit phases. <del> setCurrentUpdatePriority(DiscreteEventPriority); <del> for (; i < queue.length; i++) { <del> let callback = queue[i]; <del> do { <del> callback = callback(isSync); <del> } while (callback !== null); <del> } <del> syncQueue = null; <del> } catch (error) { <del> // If something throws, leave the remaining callbacks on the queue. <del> if (syncQueue !== null) { <del> syncQueue = syncQueue.slice(i + 1); <del> } <del> // Resume flushing in the next tick <del> scheduleCallback(ImmediatePriority, flushSyncCallbackQueue); <del> throw error; <del> } finally { <del> setCurrentUpdatePriority(previousUpdatePriority); <del> isFlushingSyncQueue = false; <del> } <del> } <del> return null; <del>}
10
Text
Text
fix typo in registration-form
7af4a564c008b41c3ca2d7a738f8e9bf42a091b3
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-forms-by-building-a-registration-form/step-023.md <ide> dashedName: step-23 <ide> <ide> # --description-- <ide> <del>For the terms and conditions, add an `input` of with a `type` of `checkbox` to the third `label` element. Also, as we do not want users to sign up, without having read the terms and conditions, make it `required`. <add>For the terms and conditions, add an `input` with a `type` of `checkbox` to the third `label` element. Also, as we do not want users to sign up, without having read the terms and conditions, make it `required`. <ide> <ide> # --hints-- <ide>
1
PHP
PHP
change method order
ed12061a9a5e512a32c69db00cd6922db77533a1
<ide><path>src/Illuminate/Support/Traits/EnumeratesValues.php <ide> protected function equality($value) <ide> } <ide> <ide> /** <del> * Make a function that returns what's passed to it. <add> * Make a function using another function, by negating its result. <ide> * <add> * @param \Closure $callback <ide> * @return \Closure <ide> */ <del> protected function identity() <add> protected function negate(Closure $callback) <ide> { <del> return function ($value) { <del> return $value; <add> return function (...$params) use ($callback) { <add> return ! $callback(...$params); <ide> }; <ide> } <ide> <ide> /** <del> * Make a function using another function, by negating its result. <add> * Make a function that returns what's passed to it. <ide> * <del> * @param \Closure $callback <ide> * @return \Closure <ide> */ <del> protected function negate(Closure $callback) <add> protected function identity() <ide> { <del> return function (...$params) use ($callback) { <del> return ! $callback(...$params); <add> return function ($value) { <add> return $value; <ide> }; <ide> } <ide> }
1
Python
Python
apply to_native on dictionary keys as well
a6806f03078fbdda598e10260f9d9bcdf07c1dce
<ide><path>rest_framework/fields.py <ide> def to_native(self, value): <ide> elif hasattr(value, '__iter__') and not isinstance(value, (dict, basestring)): <ide> return [self.to_native(item) for item in value] <ide> elif isinstance(value, dict): <del> return dict((k, self.to_native(v)) for k, v in value.items()) <add> return dict(map(self.to_native, (k, v)) for k, v in value.items()) <ide> return smart_unicode(value) <ide> <ide> def attributes(self):
1
Java
Java
improve the package docs of i.r.schedulers
caefffa27e7c2e8d1a9f09bc51213f77ad5ae93e
<ide><path>src/main/java/io/reactivex/schedulers/package-info.java <ide> * limitations under the License. <ide> */ <ide> /** <del> * Scheduler implementations, value+time record class and the standard factory class to <del> * return standard RxJava schedulers or wrap any Executor-based (thread pool) instances. <add> * Contains notably the factory class of {@link io.reactivex.schedulers.Schedulers Schedulers} providing methods for <add> * retrieving the standard scheduler instances, the {@link io.reactivex.schedulers.TestScheduler TestScheduler} for testing flows <add> * with scheduling in a controlled manner and the class {@link io.reactivex.schedulers.Timed Timed} that can hold <add> * a value and a timestamp associated with it. <ide> */ <ide> package io.reactivex.schedulers;
1
Text
Text
emphasize use of markdown in challenges
6d879e343993ab34ebb54bba4c5000ca97a848ae
<ide><path>docs/how-to-help-with-video-challenges.md <ide> If a question has not yet been added to a particular video challenge, it will ha <ide> <ide> ```yml <ide> question: <del> text: Question <add> text: | <add> Question <ide> answers: <del> - one <del> - two <del> - three <add> - | <add> one <add> - | <add> two <add> - | <add> three <ide> solution: 3 <ide> ``` <ide> <ide> Update the word “Question” with your question. Update the “one”, “two”, and “three” with the possible answers. Make sure to update the solution number with which answer is correct. You can add more possible answers using the same format. The question and answers can be surrounded with quotation marks. <ide> <del>Questions and answers can contain certain HTML tags like `<br>` for a new line. Surround code with `<pre></pre>` You will need to add a `<br>` at the end of each line of code. <del> <ide> #### Use markdown to format your question <ide> <del>You can also use markdown in your question as well as HTML. The simplest way to ensure that it is formatted correctly is to start the question with `text: |`, like this: <add>The text in the question is parsed as markdown. The simplest way to ensure that it is formatted correctly is to start the question with `text: |`, like this: <ide> <ide> ```yml <ide> question: <ide> text: | <ide> Question <del> answers: <del> - one <del> - two <del> - three <del> solution: 3 <ide> ``` <ide> <ide> Then you need to make sure that your question is on a new line and indented one level more than `text: |`. <ide> <del>Make sure each answer is plausible but there is only one correct answer. <del> <del>## Question examples <add>The same approach can be used for the answers, so the entire question becomes <ide> <del>#### Here are a few examples with HTML: <ide> ```yml <ide> question: <del> text: 'What will print out after running this code:<pre>width = 15<br>height = 12.0<br>print(height/3)</pre>' <add> text: | <add> Question <ide> answers: <del> - '39' <del> - '4' <del> - '4.0' <del> - '5.0' <del> - '5' <del> solution: 3 <add> - | <add> First answer <add> - | <add> Second <add> - | <add> Third <add> solution: 2 <ide> ``` <ide> <del>```yml <del>question: <del> text: 'Below is code to find the smallest value from a list of values. One line has an error that will cause the code to not work as expected. Which line is it? <del><pre> <del>1|smallest = None<br> <del>2|print("Before:", smallest)<br> <del>3|for itervar in [3, 41, 12, 9, 74, 15]:<br> <del>4| if smallest is None or itervar ⋖ smallest:<br> <del>5| smallest = itervar<br> <del>6| break<br> <del>7| print("Loop:", itervar, smallest)<br> <del>8|print("Smallest:", smallest)<br> <del></pre>' <del> answers: <del> - '3' <del> - '4' <del> - '6' <del> - '7' <del> solution: 3 <del>``` <add>Make sure each answer is plausible but there is only one correct answer. <add> <add>#### Use of HTML <add> <add>Questions and answers can contain certain HTML tags like `<br>` for a new line. HTML tags should be used sparingly, when questions cannot be expressed without them. <add> <add>### Question examples <add> <add>#### Examples without HTML <ide> <del>#### Example with markdown: <ide> ````yml <ide> question: <ide> text: | <ide> question: <ide> console.log('hello world'); <ide> ``` <ide> <del> New paragraph after an empty line. <add> Select an answer! <add> answers: <add> - | <add> hello *world* <add> - | <add> **hello** world <add> - | <add> hello world <add> solution: 3 <add>```` <add> <add>````yml <add>question: <add> text: | <add> What will print out after running this code: <add> ```py <add> width = 15 <add> height = 12.0 <add> print(height/3) <add> ``` <ide> answers: <del> - hello *world* <del> - '**hello** world' # the string cannot start with a *, hence the quotes. <del> - hello world <add> - | <add> 39 <add> - | <add> 4 <add> - | <add> 4.0 <add> - | <add> 5.0 <add> - | <add> 5 <ide> solution: 3 <ide> ```` <ide> <add>#### Example with HTML <add> <add>```yml <add>question: <add> text: | <add> What will print out after running this code: <add> <pre><code>width = 15<br>height = 12.0<br>print(height/3)<code></pre> <add> answers: <add> - | <add> 39 <add> - | <add> 4 <add> - | <add> 4.0 <add> - | <add> 5.0 <add> - | <add> 5 <add> solution: 3 <add>``` <add> <add>The final example demonstrates that HTML can be used, but that it is not as readable as the version without it. <add> <ide> For more examples, you can look at the markdown files for the following video course. All the challenges already have questions: [Python for Everybody Course](https://github.com/freeCodeCamp/freeCodeCamp/tree/next-python-projects/curriculum/challenges/english/07-scientific-computing-with-python/python-for-everybody) <ide> <ide> ## Open a pull request
1
Text
Text
fix url/slug field signatures in docs
052e236fde3453b33a4e651293da84e7d302cefb
<ide><path>docs/api-guide/fields.md <ide> or `django.db.models.fields.TextField`. <ide> <ide> Corresponds to `django.db.models.fields.URLField`. Uses Django's `django.core.validators.URLValidator` for validation. <ide> <del>**Signature:** `CharField(max_length=200, min_length=None)` <add>**Signature:** `URLField(max_length=200, min_length=None)` <ide> <ide> ## SlugField <ide> <ide> Corresponds to `django.db.models.fields.SlugField`. <ide> <del>**Signature:** `CharField(max_length=50, min_length=None)` <add>**Signature:** `SlugField(max_length=50, min_length=None)` <ide> <ide> ## ChoiceField <ide>
1
PHP
PHP
improve code readability
efeaf217b01d15488fa7098ec41420057e8423ad
<ide><path>src/Utility/Security.php <ide> public static function insecureRandomBytes(int $length): string <ide> */ <ide> public static function engine($instance = null) <ide> { <del> if ($instance === null && static::$_instance === null) { <del> if (extension_loaded('openssl')) { <del> $instance = new OpenSsl(); <del> } <del> } <ide> if ($instance) { <del> static::$_instance = $instance; <add> return static::$_instance = $instance; <ide> } <ide> if (isset(static::$_instance)) { <ide> /** @psalm-suppress LessSpecificReturnStatement */ <ide> return static::$_instance; <ide> } <add> if (extension_loaded('openssl')) { <add> return static::$_instance = new OpenSsl(); <add> } <ide> throw new InvalidArgumentException( <ide> 'No compatible crypto engine available. ' . <ide> 'Load the openssl extension.' <ide><path>tests/TestCase/Utility/SecurityTest.php <ide> */ <ide> class SecurityTest extends TestCase <ide> { <add> /** <add> * Test engine <add> */ <add> public function testEngineEquivalence(): void <add> { <add> $restore = Security::engine(); <add> $newEngine = new OpenSsl(); <add> <add> Security::engine($newEngine); <add> <add> $this->assertSame($newEngine, Security::engine()); <add> $this->assertNotSame($restore, Security::engine()); <add> } <add> <ide> /** <ide> * testHash method <ide> */ <ide> public function testDecryptInvalidData(): void <ide> Security::decrypt($txt, $key); <ide> } <ide> <del> /** <del> * Test engine <del> */ <del> public function testEngineEquivalence(): void <del> { <del> $restore = Security::engine(); <del> $newEngine = new OpenSsl(); <del> <del> Security::engine($newEngine); <del> <del> $this->assertSame($newEngine, Security::engine()); <del> $this->assertNotSame($restore, Security::engine()); <del> } <del> <ide> /** <ide> * Tests that the salt can be set and retrieved <ide> */
2
Javascript
Javascript
fix unrelated test
ab90d08292acf8fe095fea6e921b9806996692a5
<ide><path>spec/workspace-spec.js <ide> describe('Workspace', () => { <ide> <ide> results.sort((a, b) => a.filePath.localeCompare(b.filePath)) <ide> <del> expect(results).toHaveLength(3) <add> expect(results.length).toBeGreaterThan(0) <ide> expect(results[0].filePath).toBe( <ide> atom.project.getDirectories()[0].resolve('a') <ide> ) <ide> describe('Workspace', () => { <ide> <ide> await scan(/a|Elephant/, {}, result => results.push(result)) <ide> <del> expect(results).toHaveLength(3) <add> expect(results.length).toBeGreaterThan(0) <ide> const resultForA = _.find( <ide> results, <ide> ({ filePath }) => path.basename(filePath) === 'a'
1
Text
Text
fix some issues in 4.2 release notes
96e483aa1dac9f937a82c5a782bc2cb9c596b2ff
<ide><path>guides/source/4_2_release_notes.md <ide> Please refer to the [Changelog][railties] for detailed changes. <ide> * Introduced `Rails.gem_version` as a convenience method to return `Gem::Version.new(Rails.version)`. <ide> ([Pull Request](https://github.com/rails/rails/pull/14101)) <ide> <del>* Introduced an `after_bundle` callback in the Rails templates. <del> ([Pull Request](https://github.com/rails/rails/pull/16359)) <del> <ide> <ide> Action Pack <ide> -----------
1
Text
Text
add better documentation around url.parse
8a6c57de006e2af58d52bb8646b9b4a433f7f797
<ide><path>readme.md <ide> const handle = app.getRequestHandler() <ide> <ide> app.prepare().then(() => { <ide> createServer((req, res) => { <add> // Be sure to pass `true` as the second argument to `url.parse`. <add> // This tells it to parse the query portion of the URL. <ide> const parsedUrl = parse(req.url, true) <ide> const { pathname, query } = parsedUrl <ide>
1
Javascript
Javascript
fix typo in scenario jsdocs
35bb19856cc8f3d8923305869c0d4ffa4a03aa8f
<ide><path>src/scenario/dsl.js <ide> angular.scenario.dsl('binding', function() { <ide> * Usage: <ide> * input(name).enter(value) enters value in input with specified name <ide> * input(name).check() checks checkbox <del> * input(name).select(value) selects the readio button with specified name/value <add> * input(name).select(value) selects the radio button with specified name/value <ide> */ <ide> angular.scenario.dsl('input', function() { <ide> var chain = {};
1
Go
Go
add joan clarke to name collection
479b793a3efa1b07a9620ddd60c065c6b06e07c3
<ide><path>pkg/namesgenerator/names-generator.go <ide> var ( <ide> //Claude Shannon - The father of information theory and founder of digital circuit design theory. (https://en.wikipedia.org/wiki/Claude_Shannon) <ide> "shannon", <ide> <add> // Joan Clarke - Bletchley Park code breaker during the Second World War who pioneered techniques that remained top secret for decades. Also an accomplished numismatist https://en.wikipedia.org/wiki/Joan_Clarke <add> "clarke", <add> <ide> // Jane Colden - American botanist widely considered the first female American botanist - https://en.wikipedia.org/wiki/Jane_Colden <ide> "colden", <ide>
1
Go
Go
add test verify container id
76a19bb3a95ef788cd889b36b0af3b79327ff431
<ide><path>integration-cli/docker_cli_run_test.go <ide> package main <ide> import ( <ide> "fmt" <ide> "os/exec" <add> "regexp" <ide> "strings" <ide> "testing" <ide> ) <ide> func TestMultipleVolumesFrom(t *testing.T) { <ide> <ide> logDone("run - multiple volumes from") <ide> } <add> <add>// this tests verifies the ID format for the container <add>func TestVerifyContainerID(t *testing.T) { <add> cmd := exec.Command(dockerBinary, "run", "-d", "busybox", "true") <add> out, exit, err := runCommandWithOutput(cmd) <add> if err != nil { <add> t.Fatal(err) <add> } <add> if exit != 0 { <add> t.Fatalf("expected exit code 0 received %d", exit) <add> } <add> match, err := regexp.MatchString("^[0-9a-f]{64}$", strings.TrimSuffix(out, "\n")) <add> if err != nil { <add> t.Fatal(err) <add> } <add> if !match { <add> t.Fatalf("Invalid container ID: %s", out) <add> } <add> <add> deleteAllContainers() <add> <add> logDone("run - verify container ID") <add>} <ide><path>integration/container_test.go <ide> import ( <ide> "time" <ide> ) <ide> <del>func TestIDFormat(t *testing.T) { <del> daemon := mkDaemon(t) <del> defer nuke(daemon) <del> container1, _, err := daemon.Create( <del> &runconfig.Config{ <del> Image: GetTestImage(daemon).ID, <del> Cmd: []string{"/bin/sh", "-c", "echo hello world"}, <del> }, <del> "", <del> ) <del> if err != nil { <del> t.Fatal(err) <del> } <del> match, err := regexp.Match("^[0-9a-f]{64}$", []byte(container1.ID)) <del> if err != nil { <del> t.Fatal(err) <del> } <del> if !match { <del> t.Fatalf("Invalid container ID: %s", container1.ID) <del> } <del>} <del> <ide> func TestMultipleAttachRestart(t *testing.T) { <ide> daemon := mkDaemon(t) <ide> defer nuke(daemon)
2
Ruby
Ruby
fix rubocop warnings
f1c64f1cdce6f2ce1d45d93e553ae2629c2e419f
<ide><path>Library/Homebrew/dev-cmd/pull.rb <ide> def force_utf8!(str) <ide> <ide> private <ide> <del> def publish_changed_formula_bottles(tap, changed_formulae_names) <add> def publish_changed_formula_bottles(_tap, changed_formulae_names) <ide> if ENV["HOMEBREW_DISABLE_LOAD_FORMULA"] <ide> raise "Need to load formulae to publish them!" <ide> end <ide> def current_versions_from_info_external(formula_name) <ide> def subject_for_bump(formula, old, new) <ide> if old[:nonexistent] <ide> # New formula <del> headline_ver = new[:stable] ? new[:stable] : new[:devel] ? new[:devel] : new[:head] <add> headline_ver = if new[:stable] <add> new[:stable] <add> elsif new[:devel] <add> new[:devel] <add> else <add> new[:head] <add> end <ide> subject = "#{formula.name} #{headline_ver} (new formula)" <ide> else <ide> # Update to existing formula <ide> def self.lookup(name) <ide> FormulaInfoFromJson.new(Utils::JSON.load(json)[0]) <ide> end <ide> <del> def bottle_tags() <add> def bottle_tags <ide> return [] unless info["bottle"]["stable"] <ide> info["bottle"]["stable"]["files"].keys <ide> end <ide> def revision <ide> end <ide> end <ide> <del> <ide> # Bottle info as used internally by pull, with alternate platform support <ide> class BottleInfo <ide> # URL of bottle as string <ide> def verify_bintray_published(formulae_names) <ide> http.use_ssl = true <ide> retry_count = 0 <ide> http.start do <del> while true do <add> loop do <ide> req = Net::HTTP::Head.new bottle_info.url <ide> req.initialize_http_header "User-Agent" => HOMEBREW_USER_AGENT_RUBY <ide> res = http.request req <ide> def verify_bintray_published(formulae_names) <ide> max_curl_retries = 1 <ide> retry_count = 0 <ide> # We're in the cache; make sure to force re-download <del> while true do <add> loop do <ide> begin <ide> curl url, "-o", filename <ide> break
1
Mixed
Ruby
add db_runtime to active job instrumentation
9574a39a7acf38453d08a31f56a9797c7e417e94
<ide><path>activejob/CHANGELOG.md <add>* `perform.active_job` notification payloads now include `:db_runtime`, which <add> is the total time (in ms) taken by database queries while performing a job. <add> This value can be used to better understand how a job's time is spent. <add> <add> *Jonathan Hefner* <add> <ide> * Update `ActiveJob::QueueAdapters::QueAdapter` te remove deprecation warning <ide> <ide> Remove a deprecation warning introduced in que 1.2 to prepare for changes in <ide><path>activejob/lib/active_job/instrumentation.rb <ide> def _perform_job <ide> end <ide> <ide> def instrument(operation, payload = {}, &block) <del> enhanced_block = ->(event_payload) do <del> value = block.call if block <del> <del> if defined?(@_halted_callback_hook_called) && @_halted_callback_hook_called <del> event_payload[:aborted] = true <del> @_halted_callback_hook_called = nil <del> end <add> payload[:job] = self <add> payload[:adapter] = queue_adapter <ide> <add> ActiveSupport::Notifications.instrument("#{operation}.active_job", payload) do <add> value = block.call if block <add> payload[:aborted] = @_halted_callback_hook_called if defined?(@_halted_callback_hook_called) <add> @_halted_callback_hook_called = nil <ide> value <ide> end <del> <del> ActiveSupport::Notifications.instrument \ <del> "#{operation}.active_job", payload.merge(adapter: queue_adapter, job: self), &enhanced_block <ide> end <ide> <ide> def halted_callback_hook(*) <ide><path>activerecord/lib/active_record/railtie.rb <ide> class Railtie < Rails::Railtie # :nodoc: <ide> end <ide> end <ide> <del> # Expose database runtime to controller for logging. <add> # Expose database runtime for logging. <ide> initializer "active_record.log_runtime" do <ide> require "active_record/railties/controller_runtime" <ide> ActiveSupport.on_load(:action_controller) do <ide> include ActiveRecord::Railties::ControllerRuntime <ide> end <add> <add> require "active_record/railties/job_runtime" <add> ActiveSupport.on_load(:active_job) do <add> include ActiveRecord::Railties::JobRuntime <add> end <ide> end <ide> <ide> initializer "active_record.set_reloader_hooks" do <ide><path>activerecord/lib/active_record/railties/job_runtime.rb <add># frozen_string_literal: true <add> <add>require "active_record/log_subscriber" <add> <add>module ActiveRecord <add> module Railties # :nodoc: <add> module JobRuntime # :nodoc: <add> private <add> def instrument(operation, payload = {}, &block) <add> if operation == :perform && block <add> super(operation, payload) do <add> db_runtime_before_perform = ActiveRecord::LogSubscriber.runtime <add> result = block.call <add> payload[:db_runtime] = ActiveRecord::LogSubscriber.runtime - db_runtime_before_perform <add> result <add> end <add> else <add> super <add> end <add> end <add> end <add> end <add>end <ide><path>activerecord/test/activejob/job_runtime_test.rb <add># frozen_string_literal: true <add> <add>require "activejob/helper" <add>require "active_record/railties/job_runtime" <add> <add>class JobRuntimeTest < ActiveSupport::TestCase <add> class TestJob < ActiveJob::Base <add> include ActiveRecord::Railties::JobRuntime <add> <add> def perform(*) <add> ActiveRecord::LogSubscriber.runtime += 42 <add> end <add> end <add> <add> test "job notification payload includes db_runtime" do <add> ActiveRecord::LogSubscriber.runtime = 0 <add> <add> assert_equal 42, notification_payload[:db_runtime] <add> end <add> <add> test "db_runtime tracks database runtime for job only" do <add> ActiveRecord::LogSubscriber.runtime = 100 <add> <add> assert_equal 42, notification_payload[:db_runtime] <add> assert_equal 142, ActiveRecord::LogSubscriber.runtime <add> end <add> <add> private <add> def notification_payload <add> payload = nil <add> subscriber = ActiveSupport::Notifications.subscribe("perform.active_job") do |*, _payload| <add> payload = _payload <add> end <add> <add> TestJob.perform_now <add> <add> ActiveSupport::Notifications.unsubscribe(subscriber) <add> <add> payload <add> end <add>end <ide><path>guides/source/active_support_instrumentation.md <ide> INFO. Cache stores may add their own keys <ide> <ide> #### perform.active_job <ide> <del>| Key | Value | <del>| ------------ | -------------------------------------- | <del>| `:adapter` | QueueAdapter object processing the job | <del>| `:job` | Job object | <add>| Key | Value | <add>| ------------- | --------------------------------------------- | <add>| `:adapter` | QueueAdapter object processing the job | <add>| `:job` | Job object | <add>| `:db_runtime` | Amount spent executing database queries in ms | <ide> <ide> #### retry_stopped.active_job <ide> <ide><path>guides/source/configuring.md <ide> Below is a comprehensive list of all the initializers found in Rails in the orde <ide> <ide> * `active_record.initialize_database`: Loads the database configuration (by default) from `config/database.yml` and establishes a connection for the current environment. <ide> <del>* `active_record.log_runtime`: Includes `ActiveRecord::Railties::ControllerRuntime` which is responsible for reporting the time taken by Active Record calls for the request back to the logger. <add>* `active_record.log_runtime`: Includes `ActiveRecord::Railties::ControllerRuntime` and `ActiveRecord::Railties::JobRuntime` which are responsible for reporting the time taken by Active Record calls for the request back to the logger. <ide> <ide> * `active_record.set_reloader_hooks`: Resets all reloadable connections to the database if `config.enable_reloading` is set to `true`. <ide>
7
Text
Text
add v3.25.0 to changelog
d58886db594226e954b8c5e4a94a5e392b72facd
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <del>### v3.25.0-beta.5 (February 02, 2021) <add>### v3.25.0 (February 08, 2021) <ide> <add>- [#19302](https://github.com/emberjs/ember.js/pull/19302) / [#19306](https://github.com/emberjs/ember.js/pull/19306) / [#19319](https://github.com/emberjs/ember.js/pull/19319) [FEATURE] Implement the [Handlebars Strict Mode RFC](https://github.com/emberjs/rfcs/blob/master/text/0496-handlebars-strict-mode.md). <add>- [#19318](https://github.com/emberjs/ember.js/pull/19318) [FEATURE] Implement the [Named Blocks RFC](https://github.com/emberjs/rfcs/blob/master/text/0460-yieldable-named-blocks.md). <add>- [#19339](https://github.com/emberjs/ember.js/pull/19339) [DEPRECATION] Deprecate importing `htmlSafe` and `isHTMLSafe` from `@ember/string` per the [Deprecate Ember String RFC](https://github.com/emberjs/rfcs/blob/master/text/0236-deprecation-ember-string.md). <add>- [#19320](https://github.com/emberjs/ember.js/pull/19320) / [#19317](https://github.com/emberjs/ember.js/pull/19317) / [#19297](https://github.com/emberjs/ember.js/pull/19297) / [#19293](https://github.com/emberjs/ember.js/pull/19293) / [#19278](https://github.com/emberjs/ember.js/pull/19278) / [#19275](https://github.com/emberjs/ember.js/pull/19275) / [#19363](https://github.com/emberjs/ember.js/pull/19363) Update rendering engine to `@glimmer/*` 0.74.2 for various features and bugfixes including ensuring `{{component.name}}` works with implicit this fallback <add>- [#18148](https://github.com/emberjs/ember.js/pull/18148) [BUGFIX] Fix empty `htmlSafe` string to be treated as falsy <add>- [#19365](https://github.com/emberjs/ember.js/pull/19365) [BUGFIX] Remove non-existing re-export from helper-addon blueprint <ide> - [#19370](https://github.com/emberjs/ember.js/pull/19370) [BUGFIX] Update glimmer-vm to prevent errors for older inline precompilation <del> <del>### v3.25.0-beta.4 (February 01, 2021) <del> <del>- [#19363](https://github.com/emberjs/ember.js/pull/19363) [BUGFIX] Update VM, fix component name preprocessing <del> <del>### v3.25.0-beta.3 (January 25, 2021) <del> <ide> - [#19351](https://github.com/emberjs/ember.js/pull/19351) [BUGFIX] Ensure locals do not clobber components of the same name <del> <del>### v3.25.0-beta.2 (January 19, 2021) <del> <del>- [#19339](https://github.com/emberjs/ember.js/pull/19339) [DEPRECATION] Deprecate importing `htmlSafe` and `isHTMLSafe` from `@ember/string` per the [Deprecate Ember String RFC](https://github.com/emberjs/rfcs/blob/master/text/0236-deprecation-ember-string.md). <ide> - [#19336](https://github.com/emberjs/ember.js/pull/19336) [BUGFIX] Ensure Component Lookup Is Well Formed <del>- [#19337](https://github.com/emberjs/ember.js/pull/19337) [BUGFIX] Ensure query param only <LinkTo /> are properly scoped in engines. <ide> - [#19338](https://github.com/emberjs/ember.js/pull/19338) [BUGFIX] Add missing `deprecate` options (`for` + `since`) <ide> - [#19342](https://github.com/emberjs/ember.js/pull/19342) [BUGFIX] Fix misleading LinkTo error message <ide> <del>### v3.25.0-beta.1 (December 28, 2020) <del> <del>- [#19302](https://github.com/emberjs/ember.js/pull/19302) / [#19306](https://github.com/emberjs/ember.js/pull/19306) / [#19319](https://github.com/emberjs/ember.js/pull/19319) [FEATURE] Implement the [Handlebars Strict Mode RFC](https://github.com/emberjs/rfcs/blob/master/text/0496-handlebars-strict-mode.md). <del>- [#19318](https://github.com/emberjs/ember.js/pull/19318) [FEATURE] Implement the [Named Blocks RFC](https://github.com/emberjs/rfcs/blob/master/text/0460-yieldable-named-blocks.md). <del>- [#18148](https://github.com/emberjs/ember.js/pull/18148) [BUGFIX] Fix empty `htmlSafe` string to be treated as falsy <del>- [#19320](https://github.com/emberjs/ember.js/pull/19320) / [#19317](https://github.com/emberjs/ember.js/pull/19317) / [#19297](https://github.com/emberjs/ember.js/pull/19297) / [#19293](https://github.com/emberjs/ember.js/pull/19293) / [#19278](https://github.com/emberjs/ember.js/pull/19278) / [#19275](https://github.com/emberjs/ember.js/pull/19275) Update rendering engine to `@glimmer/*` 0.73.1 for various features and bugfixes including ensuring `{{component.name}}` works with implicit this fallback <del> <ide> ### v3.24.1 (January 14, 2021) <ide> <ide> - [#19337](https://github.com/emberjs/ember.js/pull/19337) [BUGFIX] Ensure query param only `<LinkTo />` are properly scoped in engines
1
Python
Python
fix a test
fa06fd7c1b46198fe39d77a167164a4d676c4d17
<ide><path>libcloud/test/compute/test_openstack.py <ide> def test_ex_list_keypairs(self): <ide> self.assertEqual(keypair.name, 'key2') <ide> self.assertEqual( <ide> keypair.fingerprint, '5d:66:33:ae:99:0f:fb:cb:86:f2:bc:ae:53:99:b6:ed') <del> self.assertTrue(keypair.public_key > 10) <add> self.assertTrue(len(keypair.public_key) > 10) <ide> self.assertEqual(keypair.private_key, None) <ide> <ide> def test_ex_create_keypair(self): <ide> def test_ex_create_keypair(self): <ide> <ide> self.assertEqual(keypair.fingerprint, <ide> '80:f8:03:a7:8e:c1:c3:b1:7e:c5:8c:50:04:5e:1c:5b') <del> self.assertTrue(keypair.public_key > 10) <del> self.assertTrue(keypair.private_key > 10) <add> self.assertTrue(len(keypair.public_key) > 10) <add> self.assertTrue(len(keypair.private_key) > 10) <ide> <ide> def test_ex_import_keypair(self): <ide> name = 'key3'
1
Ruby
Ruby
add missing require
7efb4d23c1022108319add6218ae9d9284936ac5
<ide><path>actionpack/lib/action_dispatch/http/content_security_policy.rb <ide> # frozen_string_literal: true <ide> <add>require "active_support/core_ext/object/deep_dup" <add> <ide> module ActionDispatch #:nodoc: <ide> class ContentSecurityPolicy <ide> class Middleware
1
PHP
PHP
fix bug in isclasscastable
0f693c992d0df1ee34716cdfc4d9c5a5bf9872b9
<ide><path>src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php <ide> protected function isJsonCastable($key) <ide> protected function isClassCastable($key) <ide> { <ide> return array_key_exists($key, $this->getCasts()) && <del> class_exists($class = $this->getCasts()[$key]) && <add> class_exists($class = $this->parseCasterClass($this->getCasts()[$key])) && <ide> ! in_array($class, static::$primitiveCastTypes); <ide> } <ide> <ide> protected function resolveCasterClass($key) <ide> return new $segments[0](...explode(',', $segments[1])); <ide> } <ide> <add> /** <add> * Parse the given caster class, removing any arguments. <add> * <add> * @param string $class <add> * @return string <add> */ <add> protected function parseCasterClass($class) <add> { <add> return strpos($class, ':') === false <add> ? $class <add> : explode(':', $class, 2)[0]; <add> } <add> <ide> /** <ide> * Merge the cast class attributes back into the model. <ide> *
1
Ruby
Ruby
eliminate moar `array.count` from `brew upgrade`
e527c1c83ab9a6e2b17debe7017659922bf82fbb
<ide><path>Library/Homebrew/cmd/upgrade.rb <ide> def upgrade <ide> end <ide> <ide> if outdated.length > 1 <del> oh1 "Upgrading #{outdated.count} outdated package#{outdated.count.plural_s}, with result:" <add> oh1 "Upgrading #{outdated.length} outdated package#{outdated.length.plural_s}, with result:" <ide> puts outdated.map{ |_, name, version| "#{name} #{version}" } * ", " <ide> end <ide>
1
Javascript
Javascript
fix a dangling link
071be609275558f177cdb28d8f8891bd1805af1c
<ide><path>src/ngAnimate/animateCss.js <ide> * unless you really need a digest to kick off afterwards. <ide> * <ide> * Keep in mind that, to make this easier, ngAnimate has tweaked the JS animations API to recognize when a runner instance is returned from $animateCss <del> * (so there is no need to call `runner.done(doneFn)` inside of your JavaScript animation code). Check the [animation code above](#usage) to see how this works. <add> * (so there is no need to call `runner.done(doneFn)` inside of your JavaScript animation code). <add> * Check the {@link ngAnimate.$animateCss#usage animation code above} to see how this works. <ide> * <ide> * @param {DOMElement} element the element that will be animated <ide> * @param {object} options the animation-related options that will be applied during the animation
1
Javascript
Javascript
remove common.port from test-net-timeout
794bfacb26c4059c2eab7efb475489b7010054c3
<ide><path>test/pummel/test-net-timeout.js <ide> // USE OR OTHER DEALINGS IN THE SOFTWARE. <ide> <ide> 'use strict'; <del>const common = require('../common'); <add>require('../common'); <ide> const assert = require('assert'); <ide> const net = require('net'); <ide> <ide> const echo_server = net.createServer((socket) => { <ide> }); <ide> }); <ide> <del>echo_server.listen(common.PORT, () => { <del> console.log(`server listening at ${common.PORT}`); <add>echo_server.listen(0, () => { <add> const port = echo_server.address().port; <add> console.log(`server listening at ${port}`); <ide> <del> const client = net.createConnection(common.PORT); <add> const client = net.createConnection(port); <ide> client.setEncoding('UTF8'); <ide> client.setTimeout(0); // Disable the timeout for client <ide> client.on('connect', () => {
1
Ruby
Ruby
use has_key? rather than accessing the value
4e4a5af731b9a17f401d13d9dcd9e33ee99da186
<ide><path>Library/Homebrew/extend/ENV.rb <ide> def universal_binary <ide> <ide> def replace_in_cflags before, after <ide> CC_FLAG_VARS.each do |key| <del> self[key] = self[key].sub before, after if self[key] <add> self[key] = self[key].sub(before, after) if has_key?(key) <ide> end <ide> end <ide>
1
Python
Python
fix doc tests
39e76d76fd411d64b7481cd21227f32226c124e3
<ide><path>src/transformers/models/detr/modeling_detr.py <ide> def forward( <ide> ... if score > 0.9: <ide> ... print( <ide> ... f"Detected {model.config.id2label[label.item()]} with confidence " <del> ... f"{round(score.item(), 3)} at location {box}." <add> ... f"{round(score.item(), 3)} at location {box}" <ide> ... ) <ide> Detected remote with confidence 0.998 at location [40.16, 70.81, 175.55, 117.98] <ide> Detected remote with confidence 0.996 at location [333.24, 72.55, 368.33, 187.66]
1
Ruby
Ruby
exclude more from build-from-source warning
2777369da798dad955d1dd03723425e8d105ebed
<ide><path>Library/Homebrew/formula_installer.rb <ide> def check_install_sanity <ide> <ide> if Homebrew.default_prefix? && !Homebrew::EnvConfig.developer? && <ide> !build_from_source? && !build_bottle? && <del> formula.tap&.core_tap? && !formula.bottle_unneeded? && <add> !installed_as_dependency? && <add> formula.tap&.core_tap? && !formula.bottle_unneeded? && !formula.any_version_installed? && <ide> # Integration tests override homebrew-core locations <ide> ENV["HOMEBREW_TEST_TMPDIR"].nil? && <ide> !pour_bottle? <ide> def fetch_dependency(dep) <ide> # been done for us in `compute_dependencies` and there's no requirement to <ide> # fetch in a particular order. <ide> ignore_deps: true, <add> installed_as_dependency: true, <ide> include_test_formulae: @include_test_formulae, <ide> build_from_source_formulae: @build_from_source_formulae, <ide> keep_tmp: keep_tmp?,
1
PHP
PHP
apply fixes from styleci
ef0a884b608a9ce1e1a1f25c279cfb165b907d5f
<ide><path>tests/Support/SupportStringableTest.php <ide> public function testWhenEmpty() <ide> <ide> public function testWhenFalse() <ide> { <del> $this->assertSame('when', (string) $this->stringable('when')->when(false,function($stringable,$value){ <add> $this->assertSame('when', (string) $this->stringable('when')->when(false, function ($stringable, $value) { <ide> return $stringable->append($value)->append('false'); <ide> })); <del> <del> $this->assertSame('when false fallbacks to default', (string) $this->stringable('when false ')->when(false,function($stringable,$value){ <add> <add> $this->assertSame('when false fallbacks to default', (string) $this->stringable('when false ')->when(false, function ($stringable, $value) { <ide> return $stringable->append($value); <del> },function($stringable){ <add> }, function ($stringable) { <ide> return $stringable->append('fallbacks to default'); <ide> })); <ide> } <ide> <ide> public function testWhenTrue() <ide> { <del> $this->assertSame('when true', (string) $this->stringable('when ')->when(true,function($stringable){ <add> $this->assertSame('when true', (string) $this->stringable('when ')->when(true, function ($stringable) { <ide> return $stringable->append('true'); <ide> })); <del> <del> $this->assertSame('gets a value from if', (string) $this->stringable('gets a value ')->when('from if',function($stringable,$value){ <add> <add> $this->assertSame('gets a value from if', (string) $this->stringable('gets a value ')->when('from if', function ($stringable, $value) { <ide> return $stringable->append($value); <del> },function($stringable){ <add> }, function ($stringable) { <ide> return $stringable->append('fallbacks to default'); <ide> })); <ide> }
1
Go
Go
add all backend ip into service records if no vip
10fcb9dd2a50b6a284940b5937e6af1f6e5a9825
<ide><path>libnetwork/service_linux.go <ide> func (c *controller) addServiceBinding(name, sid, nid, eid string, vip net.IP, i <ide> // applications have access to DNS RR. <ide> n.(*network).addSvcRecords("tasks."+name, ip, nil, false) <ide> <add> // Add service name to vip in DNS, if vip is valid. Otherwise resort to DNS RR <add> svcIP := vip <add> if len(svcIP) == 0 { <add> svcIP = ip <add> } <add> n.(*network).addSvcRecords(name, svcIP, nil, false) <add> <ide> s.Lock() <ide> defer s.Unlock() <ide> <ide> func (c *controller) addServiceBinding(name, sid, nid, eid string, vip net.IP, i <ide> // we add a new service service in IPVS rules. <ide> addService = true <ide> <del> // Add service name to vip in DNS, if vip is valid. Otherwise resort to DNS RR <del> svcIP := vip <del> if len(svcIP) == 0 { <del> svcIP = ip <del> } <del> <del> n.(*network).addSvcRecords(name, svcIP, nil, false) <ide> } <ide> <ide> lb.backEnds[eid] = ip <ide> func (c *controller) rmServiceBinding(name, sid, nid, eid string, vip net.IP, in <ide> // Delete the special "tasks.svc_name" backend record. <ide> n.(*network).deleteSvcRecords("tasks."+name, ip, nil, false) <ide> <add> // Make sure to remove the right IP since if vip is <add> // not valid we would have added a DNS RR record. <add> svcIP := vip <add> if len(svcIP) == 0 { <add> svcIP = ip <add> } <add> n.(*network).deleteSvcRecords(name, svcIP, nil, false) <add> <ide> s.Lock() <ide> defer s.Unlock() <ide> <ide> func (c *controller) rmServiceBinding(name, sid, nid, eid string, vip net.IP, in <ide> // remove the service entry in IPVS. <ide> rmService = true <ide> <del> // Make sure to remove the right IP since if vip is <del> // not valid we would have added a DNS RR record. <del> svcIP := vip <del> if len(svcIP) == 0 { <del> svcIP = ip <del> } <del> <del> n.(*network).deleteSvcRecords(name, svcIP, nil, false) <ide> delete(s.loadBalancers, nid) <ide> } <ide>
1
Javascript
Javascript
fix a bug with concurrent intervals
1901673b06932075005f04ae5116132613349a1c
<ide><path>d3.js <ide> function d3_selection(groups) { <ide> <ide> // TODO filter, slice? <ide> <del> groups.transition = function() { <del> return d3_transition(groups); <add> groups.transition = function(name) { <add> return d3_transition(groups, name); <ide> }; <ide> <ide> return groups; <ide> } <del>d3.transition = function() { <del> return d3_root.transition(); <del>}; <add>d3.transition = d3_root.transition; <ide> <ide> // TODO namespace transitions; cancel collisions <del>function d3_transition(groups) { <add>function d3_transition(groups, name) { <ide> var transition = {}, <ide> tweens = {}, <ide> event = d3.dispatch("start", "end"), <ide> function d3_transition(groups) { <ide> }; <ide> <ide> transition.select = function(query) { <del> var k, t = d3_transition(groups.select(query)).ease(ease); <add> var k, t = d3_transition(groups.select(query), name).ease(ease); <ide> k = -1; t.delay(function(d, i) { return delay[++k]; }); <ide> k = -1; t.duration(function(d, i) { return duration[++k]; }); <ide> return t; <ide> }; <ide> <ide> transition.selectAll = function(query) { <del> var k, t = d3_transition(groups.selectAll(query)).ease(ease); <add> var k, t = d3_transition(groups.selectAll(query), name).ease(ease); <ide> k = -1; t.delay(function(d, i) { return delay[i ? k : ++k]; }) <ide> k = -1; t.duration(function(d, i) { return duration[i ? k : ++k]; }); <ide> return t; <ide> function d3_timer_step() { <ide> t1 = d3_timer_queue; <ide> while (t1) { <ide> elapsed = now - t1.then; <del> if ((elapsed > t1.delay) && t1.callback(elapsed)) { <del> if (t0) t0.next = t1.next; <del> else d3_timer_queue = t1.next; <del> } <del> t0 = t1; <del> t1 = t1.next; <add> if (elapsed > t1.delay) t1.flush = t1.callback(elapsed); <add> t1 = (t0 = t1).next; <add> } <add> d3_timer_flush(); <add>} <add> <add>// Flush after callbacks, to avoid concurrent queue modification. <add>function d3_timer_flush() { <add> var t0 = null, <add> t1 = d3_timer_queue; <add> while (t1) { <add> t1 = t1.flush <add> ? (t0 ? t0.next = t1.next : d3_timer_queue = t1.next) <add> : (t0 = t1).next; <ide> } <ide> if (!t0) d3_timer_interval = clearInterval(d3_timer_interval); <ide> } <ide><path>d3.min.js <del>if(!Date.now)Date.now=function(){return+new Date};if(!Object.create)Object.create=function(I){function D(){}D.prototype=I;return new D}; <del>(function(I){function D(){var a={},c=[];a.add=function(b){for(var f=0;f<c.length;f++)if(c[f].listener==b)return a;c.push({listener:b,on:true});return a};a.remove=function(b){for(var f=0;f<c.length;f++){var e=c[f];if(e.listener==b){e.on=false;c=c.slice(0,f).concat(c.slice(f+1));break}}return a};a.dispatch=function(){for(var b=c,f=0,e=b.length;f<e;f++){var d=b[f];d.on&&d.listener.apply(this,arguments)}};return a}function Q(a){return function(c){return 1-a(1-c)}}function R(a){return function(c){return 0.5* <del>(c<0.5?a(2*c):2-a(2-2*c))}}function U(a){return a}function J(a){return function(c){return Math.pow(c,a)}}function V(a){return 1-Math.cos(a*Math.PI/2)}function W(a){return a?Math.pow(2,10*(a-1))-0.0010:0}function X(a){return 1-Math.sqrt(1-a*a)}function Y(a){return a<1/2.75?7.5625*a*a:a<2/2.75?7.5625*(a-=1.5/2.75)*a+0.75:a<2.5/2.75?7.5625*(a-=2.25/2.75)*a+0.9375:7.5625*(a-=2.625/2.75)*a+0.984375}function Z(a){return{nodeKey:function(c){return c.getAttribute(a)},dataKey:function(c){return c[a]}}}function K(a){var c, <del>b,f,e,d;if(e=/([a-z]+)\((.*)\)/i.exec(a)){d=e[2].split(",");switch(e[1]){case "hsl":return S(parseFloat(d[0]),parseFloat(d[1])/100,parseFloat(d[2])/100);case "rgb":return{r:L(d[0]),g:L(d[1]),b:L(d[2])}}}if(e=A[a])return e;if(a==null)return A.black;if(a.charAt(0)=="#"){if(a.length==4){c=a.charAt(1);c+=c;b=a.charAt(2);b+=b;f=a.charAt(3);f+=f}else if(a.length==7){c=a.substring(1,3);b=a.substring(3,5);f=a.substring(5,7)}c=parseInt(c,16);b=parseInt(b,16);f=parseInt(f,16)}return{r:c,g:b,b:f}}function S(a, <del>c,b){function f(h){if(h>360)h-=360;else if(h<0)h+=360;if(h<60)return e+(d-e)*h/60;if(h<180)return d;if(h<240)return e+(d-e)*(240-h)/60;return e}var e,d;a%=360;if(a<0)a+=360;c=c<0?0:c>1?1:c;b=b<0?0:b>1?1:b;d=b<=0.5?b*(1+c):b+c-b*c;e=2*b-d;return{r:Math.round(f(a+120)*255),g:Math.round(f(a)*255),b:Math.round(f(a-120)*255)}}function L(a){var c=parseFloat(a);return a.charAt(a.length-1)=="%"?Math.round(c*2.55):c}function y(a){function c(e){for(var d=[],h,i,g,o,j=0,m=a.length;j<m;j++){g=a[j];d.push(h=[]); <del>h.parentNode=g.parentNode;h.parentData=g.parentData;for(var n=0,p=g.length;n<p;n++)if(o=g[n]){h.push(i=e(o));if(i)i.__data__=o.__data__}else h.push(null)}return y(d)}function b(e){for(var d=[],h,i,g,o=0,j=a.length;o<j;o++){i=a[o];for(var m=0,n=i.length;m<n;m++)if(g=i[m]){d.push(h=e(g));h.parentNode=g;h.parentData=g.__data__}}return y(d)}function f(e){for(var d=0,h=a.length;d<h;d++)for(var i=a[d],g=0,o=i.length;g<o;g++){var j=i[g];if(j)return e.call(j,j.__data__,g)}return null}a.select=function(e){return c(function(d){return d.querySelector(e)})}; <del>a.selectAll=function(e){return b(function(d){d=d.querySelectorAll(e);return Array.prototype.slice.call(d)})};a.data=function(e,d){function h(p,t){function r($){return p.parentNode.appendChild($)}var k=0,z=p.length,s=t.length,q=Math.min(z,s),E=Math.max(z,s),v=[],w=[],u=[],x,B;if(d){q={};E=[];var F;for(k=0;k<z;k++){q[F=d.nodeKey(x=p[k])]=x;E.push(F)}for(k=0;k<s;k++){if(x=q[F=d.dataKey(B=t[k])]){x.__data__=B;v[k]=x;w[k]=u[k]=null}else{w[k]={appendChild:r,__data__:B};v[k]=u[k]=null}delete q[F]}for(k= <del>0;k<z;k++)if(E[k]in q)u[k]=p[k]}else{for(;k<q;k++){x=p[k];B=t[k];if(x){x.__data__=B;v[k]=x;w[k]=u[k]=null}else{w[k]={appendChild:r,__data__:B};v[k]=u[k]=null}}for(;k<s;k++){w[k]={appendChild:r,__data__:t[k]};v[k]=u[k]=null}for(;k<E;k++){u[k]=p[k];w[k]=v[k]=null}}w.parentNode=v.parentNode=u.parentNode=p.parentNode;w.parentData=v.parentData=u.parentData=p.parentData;j.push(w);m.push(v);n.push(u)}var i=-1,g=a.length,o,j=[],m=[],n=[];if(typeof d=="string")d=Z(d);if(typeof e=="function")for(;++i<g;)h(o= <del>a[i],e.call(o,o.parentData,i));else for(;++i<g;)h(o=a[i],e);i=y(m);i.enter=function(p){return y(j).append(p)};i.exit=function(){return y(n)};return i};a.each=function(e){for(var d=0,h=a.length;d<h;d++)for(var i=a[d],g=0,o=i.length;g<o;g++){var j=i[g];j&&e.call(j,j.__data__,g)}return a};a.attr=function(e,d){function h(){this.removeAttribute(e)}function i(){this.removeAttributeNS(e.space,e.local)}function g(){this.setAttribute(e,d)}function o(){this.setAttributeNS(e.space,e.local,d)}function j(){var n= <del>d.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}function m(){var n=d.apply(this,arguments);n==null?this.removeAttributeNS(e.space,e.local):this.setAttributeNS(e.space,e.local,n)}e=l.ns.qualify(e);if(arguments.length<2)return f(e.local?function(){return this.getAttributeNS(e.space,e.local)}:function(){return this.getAttribute(e)});return a.each(d==null?e.local?i:h:typeof d=="function"?e.local?m:j:e.local?o:g)};a.style=function(e,d,h){function i(){this.style.removeProperty(e)} <del>function g(){this.style.setProperty(e,d,h)}function o(){var j=d.apply(this,arguments);j==null?this.style.removeProperty(e):this.style.setProperty(e,j,h)}if(arguments.length<3)h=null;if(arguments.length<2)return f(function(){return window.getComputedStyle(this,null).getPropertyValue(e)});return a.each(d==null?i:typeof d=="function"?o:g)};a.text=function(e){function d(){this.appendChild(document.createTextNode(e))}function h(){var i=e.apply(this,arguments);i!=null&&this.appendChild(document.createTextNode(i))} <del>if(arguments.length<1)return f(function(){return this.textContent});a.each(function(){for(;this.lastChild;)this.removeChild(this.lastChild)});return e==null?a:a.each(typeof e=="function"?h:d)};a.html=function(e){function d(){this.innerHTML=e}function h(){this.innerHTML=e.apply(this,arguments)}if(arguments.length<1)return f(function(){return this.innerHTML});return a.each(typeof e=="function"?h:d)};a.append=function(e){function d(i){return i.appendChild(document.createElement(e))}function h(i){return i.appendChild(document.createElementNS(e.space, <del>e.local))}e=l.ns.qualify(e);return c(e.local?h:d)};a.remove=function(){return c(function(e){var d=e.parentNode;d.removeChild(e);return d})};a.on=function(e,d){e="on"+e;return a.each(function(h,i){this[e]=function(g){l.event=g;try{d.call(this,h,i)}finally{l.event=null}}})};a.transition=function(){return M(a)};return a}function M(a){function c(j){var m=true,n=-1;a.each(function(){if(d[++n]!=2){var p=(j-h[n])/i[n];if(p>=1)p=1;else{m=false;if(p<0)return;if(!d[n]){d[n]=1;e.start.dispatch.apply(this,arguments)}}var t= <del>o(p),r;for(r in f)f[r].call(this,t,n);if(p==1){d[n]=2;e.end.dispatch.apply(this,arguments)}}});return m}var b={},f={},e=l.dispatch("start","end"),d=[],h=[],i=[],g,o=l.ease("cubic-in-out");b.delay=function(j){var m=Infinity,n=-1;if(typeof j=="function")a.each(function(){var p=h[++n]=+j.apply(this,arguments);if(p<m)m=p});else{m=+j;a.each(function(){h[++n]=m})}aa(c,m);return b};b.duration=function(j){var m=-1;if(typeof j=="function"){g=0;a.each(function(){var n=i[++m]=+j.apply(this,arguments);if(n>g)g= <del>n})}else{g=+j;a.each(function(){i[++m]=g})}return b};b.ease=function(j){o=typeof j=="string"?l.ease(j):j;return b};b.attrTween=function(j,m){function n(s,q){k[++z]=m.call(this,s,q,this.getAttribute(j))}function p(s,q){k[++z]=m.call(this,s,q,this.getAttributeNS(j.space,j.local))}function t(s,q){this.setAttribute(j,k[q](s))}function r(s,q){this.setAttributeNS(j.space,j.local,k[q](s))}var k=[],z=-1;j=l.ns.qualify(j);a.each(j.local?p:n);f["attr."+j]=j.local?r:t;return b};b.attr=function(j,m){return b.attrTween(j, <del>T(m))};b.styleTween=function(j,m,n){var p=[],t=-1;a.each(function(r,k){p[++t]=m.call(this,r,k,window.getComputedStyle(this,null).getPropertyValue(j))});f["style."+j]=function(r,k){this.style.setProperty(j,p[k](r),n)};return b};b.style=function(j,m,n){return b.styleTween(j,T(m),n)};b.select=function(j){var m;j=M(a.select(j)).ease(o);m=-1;j.delay(function(){return h[++m]});m=-1;j.duration(function(){return i[++m]});return j};b.selectAll=function(j){var m;j=M(a.selectAll(j)).ease(o);m=-1;j.delay(function(n, <del>p){return h[p?m:++m]});m=-1;j.duration(function(n,p){return i[p?m:++m]});return j};b.each=function(j,m){e[j].add(m);return b};return b.delay(0).duration(250)}function aa(a,c){for(var b=Date.now(),f=false,e=b+c,d=C;d;){if(d.callback==a){d.then=b;d.delay=c;f=true}else{var h=d.then+d.delay;if(h<e)e=h}d=d.next}f||(C={callback:a,then:b,delay:c,next:C});if(!G){clearTimeout(N);N=setTimeout(ba,Math.min(24,e-b))}}function ba(){G=setInterval(ca,24);N=0}function ca(){for(var a,c=Date.now(),b=null,f=C;f;){a= <del>c-f.then;if(a>f.delay&&f.callback(a))if(b)b.next=f.next;else C=f.next;b=f;f=f.next}b||(G=clearInterval(G))}function T(a){return typeof a=="function"?function(c,b,f){return l.interpolate(f,a.call(this,c,b))}:function(c,b,f){return l.interpolate(f,a)}}var l=I.d3={};l.version="0.1.0";l.range=function(a,c,b){if(arguments.length==1){c=a;a=0}if(b==null)b=1;if((c-a)/b==Infinity)throw Error("infinite range");var f=[],e=-1,d;if(b<0)for(;(d=a+b*++e)>c;)f.push(d);else for(;(d=a+b*++e)<c;)f.push(d);return f}; <del>l.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 c=a.indexOf(":");return c<0?a:{space:l.ns.prefix[a.substring(0,c)],local:a.substring(c+1)}}};l.dispatch=function(){for(var a={},c,b=0,f=arguments.length;b<f;b++){c=arguments[b];a[c]=D(c)}return a};var da=J(2),ea=J(3),fa={linear:function(){return U},poly:J,quad:function(){return da}, <del>cubic:function(){return ea},sin:function(){return V},exp:function(){return W},circle:function(){return X},elastic:function(a,c){var b;if(arguments.length<2)c=0.45;if(arguments.length<1){a=1;b=c/4}else b=c/(2*Math.PI)*Math.asin(1/a);return function(f){return 1+a*Math.pow(2,10*-f)*Math.sin(-(f+b)*2*Math.PI/c)}},back:function(a){a||(a=1.70158);return function(c){return c*c*((a+1)*c-a)}},bounce:function(){return Y}},ga={"in":function(a){return a},out:Q,"in-out":R,"out-int":function(a){return R(Q(a))}}; <del>l.ease=function(a){var c=a.indexOf("-"),b=c>=0?a.substring(0,c):a;c=c>=0?a.substring(c+1):"in";return ga[c](fa[b].apply(null,Array.prototype.slice.call(arguments,1)))};l.event=null;l.interpolate=function(a,c){if(typeof c=="number")return l.interpolateNumber(+a,c);if(typeof c=="string")return c in A||/^(#|rgb\(|hsl\()/.test(c)?l.interpolateRgb(String(a),c):l.interpolateString(String(a),c);if(c instanceof Array)return l.interpolateArray(a,c);return l.interpolateObject(a,c)};l.interpolateNumber=function(a, <del>c){c-=a;return function(b){return a+c*b}};l.interpolateString=function(a,c){var b,f,e=0,d=[],h=[],i,g;for(f=0;b=O.exec(c);++f){b.index&&d.push(c.substring(e,b.index));h.push({i:d.length,x:b[0]});d.push(null);e=O.lastIndex}e<c.length&&d.push(c.substring(e));f=0;for(i=h.length;(b=O.exec(a))&&f<i;++f){g=h[f];if(g.x==b[0]){if(g.i)if(d[g.i+1]==null){d[g.i-1]+=g.x;d.splice(g.i,1);for(b=f+1;b<i;++b)h[b].i--}else{d[g.i-1]+=g.x+d[g.i+1];d.splice(g.i,2);for(b=f+1;b<i;++b)h[b].i-=2}else if(d[g.i+1]==null)d[g.i]= <del>g.x;else{d[g.i]=g.x+d[g.i+1];d.splice(g.i+1,1);for(b=f+1;b<i;++b)h[b].i--}h.splice(f,1);i--;f--}else g.x=l.interpolateNumber(parseFloat(b[0]),parseFloat(g.x))}for(;f<i;){g=h.pop();if(d[g.i+1]==null)d[g.i]=g.x;else{d[g.i]=g.x+d[g.i+1];d.splice(g.i+1,1)}i--}if(d.length==1)return d[0]==null?h[0].x:function(){return c};return function(o){for(f=0;f<i;++f)d[(g=h[f]).i]=g.x(o);return d.join("")}};l.interpolateRgb=function(a,c){a=K(a);c=K(c);var b=a.r,f=a.g,e=a.b,d=c.r-b,h=c.g-f,i=c.b-e;return function(g){return"rgb("+ <del>Math.round(b+d*g)+","+Math.round(f+h*g)+","+Math.round(e+i*g)+")"}};l.interpolateArray=function(a,c){var b=[],f=[],e=a.length,d=c.length,h=Math.min(a.length,c.length),i;for(i=0;i<h;++i)b.push(l.interpolate(a[i],c[i]));for(;i<e;++i)f[i]=a[i];for(;i<d;++i)f[i]=c[i];return function(g){for(i=0;i<h;++i)f[i]=b[i](g);return f}};l.interpolateObject=function(a,c){var b={},f={},e;for(e in a)if(e in c)b[e]=(e in ha||/\bcolor\b/.test(e)?l.interpolateRgb:l.interpolate)(a[e],c[e]);else f[e]=a[e];for(e in c)e in <del>a||(f[e]=c[e]);return function(d){for(e in b)f[e]=b[e](d);return f}};var O=/[-+]?(?:\d+\.\d+|\d+\.|\.\d+|\d+)(?:[eE][-]?\d+)?/g,ha={background:1,fill:1,stroke:1},A={aliceblue:"#f0f8ff",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", <del>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",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff", <del>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",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080", <del>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",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370db",mediumseagreen:"#3cb371", <del>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",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd", <del>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",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5", <del>yellow:"#ffff00",yellowgreen:"#9acd32"},P;for(P in A)A[P]=K(A[P]);l.hsl=function(a,c,b){a=S(a,c,b);return"rgb("+a.r+","+a.g+","+a.b+")"};l.linear=function(){function a(g){return i((g-b)*h)}function c(g){var o=Math.min(b,f),j=Math.max(b,f),m=j-o,n=Math.pow(10,Math.floor(Math.log(m/g)/Math.LN10));g=g/(m/n);if(g<=0.15)n*=10;else if(g<=0.35)n*=5;else if(g<=0.75)n*=2;return{start:Math.ceil(o/n)*n,stop:Math.floor(j/n)*n+n*0.5,step:n}}var b=0,f=1,e=0,d=1,h=1/(f-b),i=l.interpolate(e,d);a.invert=function(g){return(g- <del>e)/h+b};a.domain=function(g){if(!arguments.length)return[b,f];b=g[0];f=g[1];h=1/(f-b);return a};a.range=function(g){if(!arguments.length)return[e,d];e=g[0];d=g[1];i=l.interpolate(e,d);return a};a.ticks=function(g){g=c(g);return l.range(g.start,g.stop,g.step)};a.tickFormat=function(g){var o=Math.max(0,-Math.floor(Math.log(c(g).step)/Math.LN10+0.01));return function(j){return j.toFixed(o)}};return a};l.log=function(){function a(b){return c(Math.log(b))}var c=l.linear();a.invert=function(b){return Math.exp(c.invert(b))}; <del>a.domain=function(b){if(!arguments.length)return c.domain().map(Math.exp);c.domain(b.map(Math.log));return a};a.range=function(){var b=c.range.apply(c,arguments);return arguments.length?a:b};return a};l.pow=function(){function a(h){return Math.pow(h,e)}function c(h){return Math.pow(h,d)}function b(h){return f(a(h))}var f=l.linear(),e=1,d=1/e;b.invert=function(h){return c(f.invert(h))};b.domain=function(h){if(!arguments.length)return f.domain().map(c);f.domain(h.map(a));return b};b.range=function(){var h= <del>f.range.apply(f,arguments);return arguments.length?b:h};b.exponent=function(h){if(!arguments.length)return e;var i=b.domain();e=h;d=1/h;return b.domain(i)};return b};l.sqrt=function(){return l.pow().exponent(0.5)};l.ordinal=function(){function a(d){d=d in b?b[d]:b[d]=c.push(d)-1;return f[d%f.length]}var c=[],b={},f=[],e=0;a.domain=function(d){if(!arguments.length)return c;c=d;b={};for(var h=-1,i=-1,g=c.length;++h<g;){d=c[h];d in b||(b[d]=++i)}return a};a.range=function(d){if(!arguments.length)return f; <del>f=d;return a};a.rangePoints=function(d,h){if(arguments.length<2)h=0;var i=d[0],g=d[1],o=(g-i)/(c.length-1+h);f=c.length==1?[(i+g)/2]:l.range(i+o*h/2,g+o/2,o);e=0;return a};a.rangeBands=function(d,h){if(arguments.length<2)h=0;var i=d[0],g=d[1],o=(g-i)/(c.length+h);f=l.range(i+o*h,g,o);e=o*(1-h);return a};a.rangeBand=function(){return e};return a};var H=y([[document]]);H[0].parentNode=document.documentElement;l.select=function(a){return typeof a=="string"?H.select(a):y([[a]])};l.selectAll=function(a){return typeof a== <del>"string"?H.selectAll(a):y([Array.prototype.slice.call(a)])};l.transition=function(){return H.transition()};var C=null,N=0,G})(this); <add>if(!Date.now)Date.now=function(){return+new Date};if(!Object.create)Object.create=function(I){function E(){}E.prototype=I;return new E}; <add>(function(I){function E(){var a={},b=[];a.add=function(e){for(var f=0;f<b.length;f++)if(b[f].listener==e)return a;b.push({listener:e,on:true});return a};a.remove=function(e){for(var f=0;f<b.length;f++){var d=b[f];if(d.listener==e){d.on=false;b=b.slice(0,f).concat(b.slice(f+1));break}}return a};a.dispatch=function(){for(var e=b,f=0,d=e.length;f<d;f++){var c=e[f];c.on&&c.listener.apply(this,arguments)}};return a}function Q(a){return function(b){return 1-a(1-b)}}function R(a){return function(b){return 0.5* <add>(b<0.5?a(2*b):2-a(2-2*b))}}function U(a){return a}function J(a){return function(b){return Math.pow(b,a)}}function V(a){return 1-Math.cos(a*Math.PI/2)}function W(a){return a?Math.pow(2,10*(a-1))-0.0010:0}function X(a){return 1-Math.sqrt(1-a*a)}function Y(a){return a<1/2.75?7.5625*a*a:a<2/2.75?7.5625*(a-=1.5/2.75)*a+0.75:a<2.5/2.75?7.5625*(a-=2.25/2.75)*a+0.9375:7.5625*(a-=2.625/2.75)*a+0.984375}function Z(a){return{nodeKey:function(b){return b.getAttribute(a)},dataKey:function(b){return b[a]}}}function K(a){var b, <add>e,f,d,c;if(d=/([a-z]+)\((.*)\)/i.exec(a)){c=d[2].split(",");switch(d[1]){case "hsl":return S(parseFloat(c[0]),parseFloat(c[1])/100,parseFloat(c[2])/100);case "rgb":return{r:L(c[0]),g:L(c[1]),b:L(c[2])}}}if(d=B[a])return d;if(a==null)return B.black;if(a.charAt(0)=="#"){if(a.length==4){b=a.charAt(1);b+=b;e=a.charAt(2);e+=e;f=a.charAt(3);f+=f}else if(a.length==7){b=a.substring(1,3);e=a.substring(3,5);f=a.substring(5,7)}b=parseInt(b,16);e=parseInt(e,16);f=parseInt(f,16)}return{r:b,g:e,b:f}}function S(a, <add>b,e){function f(h){if(h>360)h-=360;else if(h<0)h+=360;if(h<60)return d+(c-d)*h/60;if(h<180)return c;if(h<240)return d+(c-d)*(240-h)/60;return d}var d,c;a%=360;if(a<0)a+=360;b=b<0?0:b>1?1:b;e=e<0?0:e>1?1:e;c=e<=0.5?e*(1+b):e+b-e*b;d=2*e-c;return{r:Math.round(f(a+120)*255),g:Math.round(f(a)*255),b:Math.round(f(a-120)*255)}}function L(a){var b=parseFloat(a);return a.charAt(a.length-1)=="%"?Math.round(b*2.55):b}function z(a){function b(d){for(var c=[],h,i,g,n,p=0,j=a.length;p<j;p++){g=a[p];c.push(h=[]); <add>h.parentNode=g.parentNode;h.parentData=g.parentData;for(var k=0,o=g.length;k<o;k++)if(n=g[k]){h.push(i=d(n));if(i)i.__data__=n.__data__}else h.push(null)}return z(c)}function e(d){for(var c=[],h,i,g,n=0,p=a.length;n<p;n++){i=a[n];for(var j=0,k=i.length;j<k;j++)if(g=i[j]){c.push(h=d(g));h.parentNode=g;h.parentData=g.__data__}}return z(c)}function f(d){for(var c=0,h=a.length;c<h;c++)for(var i=a[c],g=0,n=i.length;g<n;g++){var p=i[g];if(p)return d.call(p,p.__data__,g)}return null}a.select=function(d){return b(function(c){return c.querySelector(d)})}; <add>a.selectAll=function(d){return e(function(c){c=c.querySelectorAll(d);return Array.prototype.slice.call(c)})};a.data=function(d,c){function h(o,q){function v($){return o.parentNode.appendChild($)}var l=0,s=o.length,A=q.length,r=Math.min(s,A),t=Math.max(s,A),w=[],x=[],u=[],y,C;if(c){r={};t=[];var F;for(l=0;l<s;l++){r[F=c.nodeKey(y=o[l])]=y;t.push(F)}for(l=0;l<A;l++){if(y=r[F=c.dataKey(C=q[l])]){y.__data__=C;w[l]=y;x[l]=u[l]=null}else{x[l]={appendChild:v,__data__:C};w[l]=u[l]=null}delete r[F]}for(l= <add>0;l<s;l++)if(t[l]in r)u[l]=o[l]}else{for(;l<r;l++){y=o[l];C=q[l];if(y){y.__data__=C;w[l]=y;x[l]=u[l]=null}else{x[l]={appendChild:v,__data__:C};w[l]=u[l]=null}}for(;l<A;l++){x[l]={appendChild:v,__data__:q[l]};w[l]=u[l]=null}for(;l<t;l++){u[l]=o[l];x[l]=w[l]=null}}x.parentNode=w.parentNode=u.parentNode=o.parentNode;x.parentData=w.parentData=u.parentData=o.parentData;p.push(x);j.push(w);k.push(u)}var i=-1,g=a.length,n,p=[],j=[],k=[];if(typeof c=="string")c=Z(c);if(typeof d=="function")for(;++i<g;)h(n= <add>a[i],d.call(n,n.parentData,i));else for(;++i<g;)h(n=a[i],d);i=z(j);i.enter=function(o){return z(p).append(o)};i.exit=function(){return z(k)};return i};a.each=function(d){for(var c=0,h=a.length;c<h;c++)for(var i=a[c],g=0,n=i.length;g<n;g++){var p=i[g];p&&d.call(p,p.__data__,g)}return a};a.attr=function(d,c){function h(){this.removeAttribute(d)}function i(){this.removeAttributeNS(d.space,d.local)}function g(){this.setAttribute(d,c)}function n(){this.setAttributeNS(d.space,d.local,c)}function p(){var k= <add>c.apply(this,arguments);k==null?this.removeAttribute(d):this.setAttribute(d,k)}function j(){var k=c.apply(this,arguments);k==null?this.removeAttributeNS(d.space,d.local):this.setAttributeNS(d.space,d.local,k)}d=m.ns.qualify(d);if(arguments.length<2)return f(d.local?function(){return this.getAttributeNS(d.space,d.local)}:function(){return this.getAttribute(d)});return a.each(c==null?d.local?i:h:typeof c=="function"?d.local?j:p:d.local?n:g)};a.style=function(d,c,h){function i(){this.style.removeProperty(d)} <add>function g(){this.style.setProperty(d,c,h)}function n(){var p=c.apply(this,arguments);p==null?this.style.removeProperty(d):this.style.setProperty(d,p,h)}if(arguments.length<3)h=null;if(arguments.length<2)return f(function(){return window.getComputedStyle(this,null).getPropertyValue(d)});return a.each(c==null?i:typeof c=="function"?n:g)};a.text=function(d){function c(){this.appendChild(document.createTextNode(d))}function h(){var i=d.apply(this,arguments);i!=null&&this.appendChild(document.createTextNode(i))} <add>if(arguments.length<1)return f(function(){return this.textContent});a.each(function(){for(;this.lastChild;)this.removeChild(this.lastChild)});return d==null?a:a.each(typeof d=="function"?h:c)};a.html=function(d){function c(){this.innerHTML=d}function h(){this.innerHTML=d.apply(this,arguments)}if(arguments.length<1)return f(function(){return this.innerHTML});return a.each(typeof d=="function"?h:c)};a.append=function(d){function c(i){return i.appendChild(document.createElement(d))}function h(i){return i.appendChild(document.createElementNS(d.space, <add>d.local))}d=m.ns.qualify(d);return b(d.local?h:c)};a.remove=function(){return b(function(d){var c=d.parentNode;c.removeChild(d);return c})};a.on=function(d,c){d="on"+d;return a.each(function(h,i){this[d]=function(g){m.event=g;try{c.call(this,h,i)}finally{m.event=null}}})};a.transition=function(d){return M(a,d)};return a}function M(a,b){function e(j){var k=true,o=-1;a.each(function(){if(h[++o]!=2){var q=(j-i[o])/g[o];if(q>=1)q=1;else{k=false;if(q<0)return;if(!h[o]){h[o]=1;c.start.dispatch.apply(this, <add>arguments)}}var v=p(q),l;for(l in d)d[l].call(this,v,o);if(q==1){h[o]=2;c.end.dispatch.apply(this,arguments)}}});return k}var f={},d={},c=m.dispatch("start","end"),h=[],i=[],g=[],n,p=m.ease("cubic-in-out");f.delay=function(j){var k=Infinity,o=-1;if(typeof j=="function")a.each(function(){var q=i[++o]=+j.apply(this,arguments);if(q<k)k=q});else{k=+j;a.each(function(){i[++o]=k})}aa(e,k);return f};f.duration=function(j){var k=-1;if(typeof j=="function"){n=0;a.each(function(){var o=g[++k]=+j.apply(this, <add>arguments);if(o>n)n=o})}else{n=+j;a.each(function(){g[++k]=n})}return f};f.ease=function(j){p=typeof j=="string"?m.ease(j):j;return f};f.attrTween=function(j,k){function o(r,t){s[++A]=k.call(this,r,t,this.getAttribute(j))}function q(r,t){s[++A]=k.call(this,r,t,this.getAttributeNS(j.space,j.local))}function v(r,t){this.setAttribute(j,s[t](r))}function l(r,t){this.setAttributeNS(j.space,j.local,s[t](r))}var s=[],A=-1;j=m.ns.qualify(j);a.each(j.local?q:o);d["attr."+j]=j.local?l:v;return f};f.attr=function(j, <add>k){return f.attrTween(j,T(k))};f.styleTween=function(j,k,o){var q=[],v=-1;a.each(function(l,s){q[++v]=k.call(this,l,s,window.getComputedStyle(this,null).getPropertyValue(j))});d["style."+j]=function(l,s){this.style.setProperty(j,q[s](l),o)};return f};f.style=function(j,k,o){return f.styleTween(j,T(k),o)};f.select=function(j){var k;j=M(a.select(j),b).ease(p);k=-1;j.delay(function(){return i[++k]});k=-1;j.duration(function(){return g[++k]});return j};f.selectAll=function(j){var k;j=M(a.selectAll(j), <add>b).ease(p);k=-1;j.delay(function(o,q){return i[q?k:++k]});k=-1;j.duration(function(o,q){return g[q?k:++k]});return j};f.each=function(j,k){c[j].add(k);return f};return f.delay(0).duration(250)}function aa(a,b){for(var e=Date.now(),f=false,d=e+b,c=D;c;){if(c.callback==a){c.then=e;c.delay=b;f=true}else{var h=c.then+c.delay;if(h<d)d=h}c=c.next}f||(D={callback:a,then:e,delay:b,next:D});if(!G){clearTimeout(N);N=setTimeout(ba,Math.min(24,d-e))}}function ba(){G=setInterval(ca,24);N=0}function ca(){for(var a, <add>b=Date.now(),e=D;e;){a=b-e.then;if(a>e.delay)e.flush=e.callback(a);e=e.next}a=null;for(b=D;b;)b=b.flush?a?a.next=b.next:D=b.next:(a=b).next;a||(G=clearInterval(G))}function T(a){return typeof a=="function"?function(b,e,f){return m.interpolate(f,a.call(this,b,e))}:function(b,e,f){return m.interpolate(f,a)}}var m=I.d3={};m.version="0.1.0";m.range=function(a,b,e){if(arguments.length==1){b=a;a=0}if(e==null)e=1;if((b-a)/e==Infinity)throw Error("infinite range");var f=[],d=-1,c;if(e<0)for(;(c=a+e*++d)> <add>b;)f.push(c);else for(;(c=a+e*++d)<b;)f.push(c);return f};m.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:m.ns.prefix[a.substring(0,b)],local:a.substring(b+1)}}};m.dispatch=function(){for(var a={},b,e=0,f=arguments.length;e<f;e++){b=arguments[e];a[b]=E(b)}return a};var da=J(2),ea=J(3), <add>fa={linear:function(){return U},poly:J,quad:function(){return da},cubic:function(){return ea},sin:function(){return V},exp:function(){return W},circle:function(){return X},elastic:function(a,b){var e;if(arguments.length<2)b=0.45;if(arguments.length<1){a=1;e=b/4}else e=b/(2*Math.PI)*Math.asin(1/a);return function(f){return 1+a*Math.pow(2,10*-f)*Math.sin(-(f+e)*2*Math.PI/b)}},back:function(a){a||(a=1.70158);return function(b){return b*b*((a+1)*b-a)}},bounce:function(){return Y}},ga={"in":function(a){return a}, <add>out:Q,"in-out":R,"out-int":function(a){return R(Q(a))}};m.ease=function(a){var b=a.indexOf("-"),e=b>=0?a.substring(0,b):a;b=b>=0?a.substring(b+1):"in";return ga[b](fa[e].apply(null,Array.prototype.slice.call(arguments,1)))};m.event=null;m.interpolate=function(a,b){if(typeof b=="number")return m.interpolateNumber(+a,b);if(typeof b=="string")return b in B||/^(#|rgb\(|hsl\()/.test(b)?m.interpolateRgb(String(a),b):m.interpolateString(String(a),b);if(b instanceof Array)return m.interpolateArray(a,b);return m.interpolateObject(a, <add>b)};m.interpolateNumber=function(a,b){b-=a;return function(e){return a+b*e}};m.interpolateString=function(a,b){var e,f,d=0,c=[],h=[],i,g;for(f=0;e=O.exec(b);++f){e.index&&c.push(b.substring(d,e.index));h.push({i:c.length,x:e[0]});c.push(null);d=O.lastIndex}d<b.length&&c.push(b.substring(d));f=0;for(i=h.length;(e=O.exec(a))&&f<i;++f){g=h[f];if(g.x==e[0]){if(g.i)if(c[g.i+1]==null){c[g.i-1]+=g.x;c.splice(g.i,1);for(e=f+1;e<i;++e)h[e].i--}else{c[g.i-1]+=g.x+c[g.i+1];c.splice(g.i,2);for(e=f+1;e<i;++e)h[e].i-= <add>2}else if(c[g.i+1]==null)c[g.i]=g.x;else{c[g.i]=g.x+c[g.i+1];c.splice(g.i+1,1);for(e=f+1;e<i;++e)h[e].i--}h.splice(f,1);i--;f--}else g.x=m.interpolateNumber(parseFloat(e[0]),parseFloat(g.x))}for(;f<i;){g=h.pop();if(c[g.i+1]==null)c[g.i]=g.x;else{c[g.i]=g.x+c[g.i+1];c.splice(g.i+1,1)}i--}if(c.length==1)return c[0]==null?h[0].x:function(){return b};return function(n){for(f=0;f<i;++f)c[(g=h[f]).i]=g.x(n);return c.join("")}};m.interpolateRgb=function(a,b){a=K(a);b=K(b);var e=a.r,f=a.g,d=a.b,c=b.r-e,h= <add>b.g-f,i=b.b-d;return function(g){return"rgb("+Math.round(e+c*g)+","+Math.round(f+h*g)+","+Math.round(d+i*g)+")"}};m.interpolateArray=function(a,b){var e=[],f=[],d=a.length,c=b.length,h=Math.min(a.length,b.length),i;for(i=0;i<h;++i)e.push(m.interpolate(a[i],b[i]));for(;i<d;++i)f[i]=a[i];for(;i<c;++i)f[i]=b[i];return function(g){for(i=0;i<h;++i)f[i]=e[i](g);return f}};m.interpolateObject=function(a,b){var e={},f={},d;for(d in a)if(d in b)e[d]=(d in ha||/\bcolor\b/.test(d)?m.interpolateRgb:m.interpolate)(a[d], <add>b[d]);else f[d]=a[d];for(d in b)d in a||(f[d]=b[d]);return function(c){for(d in e)f[d]=e[d](c);return f}};var O=/[-+]?(?:\d+\.\d+|\d+\.|\.\d+|\d+)(?:[eE][-]?\d+)?/g,ha={background:1,fill:1,stroke:1},B={aliceblue:"#f0f8ff",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", <add>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",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3", <add>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",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd", <add>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",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370db", <add>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",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f", <add>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",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3", <add>white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"},P;for(P in B)B[P]=K(B[P]);m.hsl=function(a,b,e){a=S(a,b,e);return"rgb("+a.r+","+a.g+","+a.b+")"};m.linear=function(){function a(g){return i((g-e)*h)}function b(g){var n=Math.min(e,f),p=Math.max(e,f),j=p-n,k=Math.pow(10,Math.floor(Math.log(j/g)/Math.LN10));g=g/(j/k);if(g<=0.15)k*=10;else if(g<=0.35)k*=5;else if(g<=0.75)k*=2;return{start:Math.ceil(n/k)*k,stop:Math.floor(p/k)*k+k*0.5,step:k}}var e=0,f=1,d=0,c=1,h=1/(f-e),i= <add>m.interpolate(d,c);a.invert=function(g){return(g-d)/h+e};a.domain=function(g){if(!arguments.length)return[e,f];e=g[0];f=g[1];h=1/(f-e);return a};a.range=function(g){if(!arguments.length)return[d,c];d=g[0];c=g[1];i=m.interpolate(d,c);return a};a.ticks=function(g){g=b(g);return m.range(g.start,g.stop,g.step)};a.tickFormat=function(g){var n=Math.max(0,-Math.floor(Math.log(b(g).step)/Math.LN10+0.01));return function(p){return p.toFixed(n)}};return a};m.log=function(){function a(e){return b(Math.log(e))} <add>var b=m.linear();a.invert=function(e){return Math.exp(b.invert(e))};a.domain=function(e){if(!arguments.length)return b.domain().map(Math.exp);b.domain(e.map(Math.log));return a};a.range=function(){var e=b.range.apply(b,arguments);return arguments.length?a:e};return a};m.pow=function(){function a(h){return Math.pow(h,d)}function b(h){return Math.pow(h,c)}function e(h){return f(a(h))}var f=m.linear(),d=1,c=1/d;e.invert=function(h){return b(f.invert(h))};e.domain=function(h){if(!arguments.length)return f.domain().map(b); <add>f.domain(h.map(a));return e};e.range=function(){var h=f.range.apply(f,arguments);return arguments.length?e:h};e.exponent=function(h){if(!arguments.length)return d;var i=e.domain();d=h;c=1/h;return e.domain(i)};return e};m.sqrt=function(){return m.pow().exponent(0.5)};m.ordinal=function(){function a(c){c=c in e?e[c]:e[c]=b.push(c)-1;return f[c%f.length]}var b=[],e={},f=[],d=0;a.domain=function(c){if(!arguments.length)return b;b=c;e={};for(var h=-1,i=-1,g=b.length;++h<g;){c=b[h];c in e||(e[c]=++i)}return a}; <add>a.range=function(c){if(!arguments.length)return f;f=c;return a};a.rangePoints=function(c,h){if(arguments.length<2)h=0;var i=c[0],g=c[1],n=(g-i)/(b.length-1+h);f=b.length==1?[(i+g)/2]:m.range(i+n*h/2,g+n/2,n);d=0;return a};a.rangeBands=function(c,h){if(arguments.length<2)h=0;var i=c[0],g=c[1],n=(g-i)/(b.length+h);f=m.range(i+n*h,g,n);d=n*(1-h);return a};a.rangeBand=function(){return d};return a};var H=z([[document]]);H[0].parentNode=document.documentElement;m.select=function(a){return typeof a=="string"? <add>H.select(a):z([[a]])};m.selectAll=function(a){return typeof a=="string"?H.selectAll(a):z([Array.prototype.slice.call(a)])};m.transition=H.transition;var D=null,N=0,G})(this); <ide><path>src/selection.js <ide> function d3_selection(groups) { <ide> <ide> // TODO filter, slice? <ide> <del> groups.transition = function() { <del> return d3_transition(groups); <add> groups.transition = function(name) { <add> return d3_transition(groups, name); <ide> }; <ide> <ide> return groups; <ide><path>src/timer.js <ide> function d3_timer_step() { <ide> t1 = d3_timer_queue; <ide> while (t1) { <ide> elapsed = now - t1.then; <del> if ((elapsed > t1.delay) && t1.callback(elapsed)) { <del> if (t0) t0.next = t1.next; <del> else d3_timer_queue = t1.next; <del> } <del> t0 = t1; <del> t1 = t1.next; <add> if (elapsed > t1.delay) t1.flush = t1.callback(elapsed); <add> t1 = (t0 = t1).next; <add> } <add> d3_timer_flush(); <add>} <add> <add>// Flush after callbacks, to avoid concurrent queue modification. <add>function d3_timer_flush() { <add> var t0 = null, <add> t1 = d3_timer_queue; <add> while (t1) { <add> t1 = t1.flush <add> ? (t0 ? t0.next = t1.next : d3_timer_queue = t1.next) <add> : (t0 = t1).next; <ide> } <ide> if (!t0) d3_timer_interval = clearInterval(d3_timer_interval); <ide> } <ide><path>src/transition.js <del>d3.transition = function() { <del> return d3_root.transition(); <del>}; <add>d3.transition = d3_root.transition; <ide> <ide> // TODO namespace transitions; cancel collisions <del>function d3_transition(groups) { <add>function d3_transition(groups, name) { <ide> var transition = {}, <ide> tweens = {}, <ide> event = d3.dispatch("start", "end"), <ide> function d3_transition(groups) { <ide> }; <ide> <ide> transition.select = function(query) { <del> var k, t = d3_transition(groups.select(query)).ease(ease); <add> var k, t = d3_transition(groups.select(query), name).ease(ease); <ide> k = -1; t.delay(function(d, i) { return delay[++k]; }); <ide> k = -1; t.duration(function(d, i) { return duration[++k]; }); <ide> return t; <ide> }; <ide> <ide> transition.selectAll = function(query) { <del> var k, t = d3_transition(groups.selectAll(query)).ease(ease); <add> var k, t = d3_transition(groups.selectAll(query), name).ease(ease); <ide> k = -1; t.delay(function(d, i) { return delay[i ? k : ++k]; }) <ide> k = -1; t.duration(function(d, i) { return duration[i ? k : ++k]; }); <ide> return t;
5
Go
Go
use stdlib tls dialer
2ac277a56f50d0ad1831603dccbca5c19ff717e9
<ide><path>client/hijack.go <ide> import ( <ide> "net/http" <ide> "net/http/httputil" <ide> "net/url" <del> "strings" <ide> "time" <ide> <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/go-connections/sockets" <ide> "github.com/pkg/errors" <ide> ) <ide> <del>// tlsClientCon holds tls information and a dialed connection. <del>type tlsClientCon struct { <del> *tls.Conn <del> rawConn net.Conn <del>} <del> <del>func (c *tlsClientCon) CloseWrite() error { <del> // Go standard tls.Conn doesn't provide the CloseWrite() method so we do it <del> // on its underlying connection. <del> if conn, ok := c.rawConn.(types.CloseWriter); ok { <del> return conn.CloseWrite() <del> } <del> return nil <del>} <del> <ide> // postHijacked sends a POST request and hijacks the connection. <ide> func (cli *Client) postHijacked(ctx context.Context, path string, query url.Values, body interface{}, headers map[string][]string) (types.HijackedResponse, error) { <ide> bodyEncoded, err := encodeData(body) <ide> func (cli *Client) postHijacked(ctx context.Context, path string, query url.Valu <ide> return types.HijackedResponse{Conn: conn, Reader: bufio.NewReader(conn)}, err <ide> } <ide> <del>func tlsDial(network, addr string, config *tls.Config) (net.Conn, error) { <del> return tlsDialWithDialer(new(net.Dialer), network, addr, config) <del>} <del> <del>// We need to copy Go's implementation of tls.Dial (pkg/cryptor/tls/tls.go) in <del>// order to return our custom tlsClientCon struct which holds both the tls.Conn <del>// object _and_ its underlying raw connection. The rationale for this is that <del>// we need to be able to close the write end of the connection when attaching, <del>// which tls.Conn does not provide. <del>func tlsDialWithDialer(dialer *net.Dialer, network, addr string, config *tls.Config) (net.Conn, error) { <del> // We want the Timeout and Deadline values from dialer to cover the <del> // whole process: TCP connection and TLS handshake. This means that we <del> // also need to start our own timers now. <del> timeout := dialer.Timeout <del> <del> if !dialer.Deadline.IsZero() { <del> deadlineTimeout := time.Until(dialer.Deadline) <del> if timeout == 0 || deadlineTimeout < timeout { <del> timeout = deadlineTimeout <del> } <del> } <del> <del> var errChannel chan error <del> <del> if timeout != 0 { <del> errChannel = make(chan error, 2) <del> time.AfterFunc(timeout, func() { <del> errChannel <- errors.New("") <del> }) <del> } <del> <del> proxyDialer, err := sockets.DialerFromEnvironment(dialer) <del> if err != nil { <del> return nil, err <del> } <del> <del> rawConn, err := proxyDialer.Dial(network, addr) <del> if err != nil { <del> return nil, err <del> } <del> // When we set up a TCP connection for hijack, there could be long periods <del> // of inactivity (a long running command with no output) that in certain <del> // network setups may cause ECONNTIMEOUT, leaving the client in an unknown <del> // state. Setting TCP KeepAlive on the socket connection will prohibit <del> // ECONNTIMEOUT unless the socket connection truly is broken <del> if tcpConn, ok := rawConn.(*net.TCPConn); ok { <del> tcpConn.SetKeepAlive(true) <del> tcpConn.SetKeepAlivePeriod(30 * time.Second) <del> } <del> <del> colonPos := strings.LastIndex(addr, ":") <del> if colonPos == -1 { <del> colonPos = len(addr) <del> } <del> hostname := addr[:colonPos] <del> <del> // If no ServerName is set, infer the ServerName <del> // from the hostname we're connecting to. <del> if config.ServerName == "" { <del> // Make a copy to avoid polluting argument or default. <del> config = tlsConfigClone(config) <del> config.ServerName = hostname <del> } <del> <del> conn := tls.Client(rawConn, config) <del> <del> if timeout == 0 { <del> err = conn.Handshake() <del> } else { <del> go func() { <del> errChannel <- conn.Handshake() <del> }() <del> <del> err = <-errChannel <del> } <del> <del> if err != nil { <del> rawConn.Close() <del> return nil, err <del> } <del> <del> // This is Docker difference with standard's crypto/tls package: returned a <del> // wrapper which holds both the TLS and raw connections. <del> return &tlsClientCon{conn, rawConn}, nil <del>} <del> <ide> func dial(proto, addr string, tlsConfig *tls.Config) (net.Conn, error) { <ide> if tlsConfig != nil && proto != "unix" && proto != "npipe" { <del> // Notice this isn't Go standard's tls.Dial function <del> return tlsDial(proto, addr, tlsConfig) <add> return tls.Dial(proto, addr, tlsConfig) <ide> } <ide> if proto == "npipe" { <ide> return sockets.DialPipe(addr, 32*time.Second) <ide><path>client/hijack_test.go <add>package client <add> <add>import ( <add> "fmt" <add> "io/ioutil" <add> "net" <add> "net/http" <add> "net/http/httptest" <add> "net/url" <add> "testing" <add> <add> "github.com/docker/docker/api/server/httputils" <add> "github.com/docker/docker/api/types" <add> "github.com/gotestyourself/gotestyourself/assert" <add> "github.com/pkg/errors" <add> "golang.org/x/net/context" <add>) <add> <add>func TestTLSCloseWriter(t *testing.T) { <add> t.Parallel() <add> <add> var chErr chan error <add> ts := &httptest.Server{Config: &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { <add> chErr = make(chan error, 1) <add> defer close(chErr) <add> if err := httputils.ParseForm(req); err != nil { <add> chErr <- errors.Wrap(err, "error parsing form") <add> http.Error(w, err.Error(), 500) <add> return <add> } <add> r, rw, err := httputils.HijackConnection(w) <add> if err != nil { <add> chErr <- errors.Wrap(err, "error hijacking connection") <add> http.Error(w, err.Error(), 500) <add> return <add> } <add> defer r.Close() <add> <add> fmt.Fprint(rw, "HTTP/1.1 101 UPGRADED\r\nContent-Type: application/vnd.docker.raw-stream\r\nConnection: Upgrade\r\nUpgrade: tcp\r\n\n") <add> <add> buf := make([]byte, 5) <add> _, err = r.Read(buf) <add> if err != nil { <add> chErr <- errors.Wrap(err, "error reading from client") <add> return <add> } <add> _, err = rw.Write(buf) <add> if err != nil { <add> chErr <- errors.Wrap(err, "error writing to client") <add> return <add> } <add> })}} <add> <add> var ( <add> l net.Listener <add> err error <add> ) <add> for i := 1024; i < 10000; i++ { <add> l, err = net.Listen("tcp4", fmt.Sprintf("127.0.0.1:%d", i)) <add> if err == nil { <add> break <add> } <add> } <add> assert.Assert(t, err) <add> <add> ts.Listener = l <add> defer l.Close() <add> <add> defer func() { <add> if chErr != nil { <add> assert.Assert(t, <-chErr) <add> } <add> }() <add> <add> ts.StartTLS() <add> defer ts.Close() <add> <add> serverURL, err := url.Parse(ts.URL) <add> assert.Assert(t, err) <add> <add> client, err := NewClient("tcp://"+serverURL.Host, "", ts.Client(), nil) <add> assert.Assert(t, err) <add> <add> resp, err := client.postHijacked(context.Background(), "/asdf", url.Values{}, nil, map[string][]string{"Content-Type": {"text/plain"}}) <add> assert.Assert(t, err) <add> defer resp.Close() <add> <add> if _, ok := resp.Conn.(types.CloseWriter); !ok { <add> t.Fatal("tls conn did not implement the CloseWrite interface") <add> } <add> <add> _, err = resp.Conn.Write([]byte("hello")) <add> assert.Assert(t, err) <add> <add> b, err := ioutil.ReadAll(resp.Reader) <add> assert.Assert(t, err) <add> assert.Assert(t, string(b) == "hello") <add> assert.Assert(t, resp.CloseWrite()) <add> <add> // This should error since writes are closed <add> _, err = resp.Conn.Write([]byte("no")) <add> assert.Assert(t, err != nil) <add>} <ide><path>client/tlsconfig_clone.go <del>// +build go1.8 <del> <del>package client // import "github.com/docker/docker/client" <del> <del>import "crypto/tls" <del> <del>// tlsConfigClone returns a clone of tls.Config. This function is provided for <del>// compatibility for go1.7 that doesn't include this method in stdlib. <del>func tlsConfigClone(c *tls.Config) *tls.Config { <del> return c.Clone() <del>} <ide><path>client/tlsconfig_clone_go17.go <del>// +build go1.7,!go1.8 <del> <del>package client // import "github.com/docker/docker/client" <del> <del>import "crypto/tls" <del> <del>// tlsConfigClone returns a clone of tls.Config. This function is provided for <del>// compatibility for go1.7 that doesn't include this method in stdlib. <del>func tlsConfigClone(c *tls.Config) *tls.Config { <del> return &tls.Config{ <del> Rand: c.Rand, <del> Time: c.Time, <del> Certificates: c.Certificates, <del> NameToCertificate: c.NameToCertificate, <del> GetCertificate: c.GetCertificate, <del> RootCAs: c.RootCAs, <del> NextProtos: c.NextProtos, <del> ServerName: c.ServerName, <del> ClientAuth: c.ClientAuth, <del> ClientCAs: c.ClientCAs, <del> InsecureSkipVerify: c.InsecureSkipVerify, <del> CipherSuites: c.CipherSuites, <del> PreferServerCipherSuites: c.PreferServerCipherSuites, <del> SessionTicketsDisabled: c.SessionTicketsDisabled, <del> SessionTicketKey: c.SessionTicketKey, <del> ClientSessionCache: c.ClientSessionCache, <del> MinVersion: c.MinVersion, <del> MaxVersion: c.MaxVersion, <del> CurvePreferences: c.CurvePreferences, <del> DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled, <del> Renegotiation: c.Renegotiation, <del> } <del>}
4
Javascript
Javascript
use fixture files
ad9fbf96b2226c8d2598c137060a368bd75f0f55
<ide><path>node-tests/blueprints/service-test-test.js <ide> const chai = require('ember-cli-blueprint-test-helpers/chai'); <ide> const expect = chai.expect; <ide> <ide> const generateFakePackageManifest = require('../helpers/generate-fake-package-manifest'); <add>const fixture = require('../helpers/fixture'); <ide> <ide> describe('Blueprint: service-test', function() { <ide> setupTestHooks(this); <ide> describe('Blueprint: service-test', function() { <ide> it('service-test foo', function() { <ide> return emberGenerateDestroy(['service-test', 'foo'], _file => { <ide> expect(_file('tests/unit/services/foo-test.js')) <del> .to.contain("import { moduleFor, test } from 'ember-qunit';") <del> .to.contain("moduleFor('service:foo'"); <add> .to.equal(fixture('service-test/default.js')); <ide> }); <ide> }); <ide> <ide> describe('Blueprint: service-test', function() { <ide> it('service-test foo', function() { <ide> return emberGenerateDestroy(['service-test', 'foo'], _file => { <ide> expect(_file('tests/unit/services/foo-test.js')) <del> .to.contain("import { describeModule, it } from 'ember-mocha';") <del> .to.contain("describeModule('service:foo', 'Unit | Service | foo'"); <add> .to.equal(fixture('service-test/mocha.js')); <ide> }); <ide> }); <ide> <ide> it('service-test foo --pod', function() { <ide> return emberGenerateDestroy(['service-test', 'foo', '--pod'], _file => { <ide> expect(_file('tests/unit/foo/service-test.js')) <del> .to.contain("import { describeModule, it } from 'ember-mocha';") <del> .to.contain("describeModule('service:foo', 'Unit | Service | foo'"); <add> .to.equal(fixture('service-test/mocha.js')); <ide> }); <ide> }); <ide> }); <ide> describe('Blueprint: service-test', function() { <ide> it('service-test foo', function() { <ide> return emberGenerateDestroy(['service-test', 'foo'], _file => { <ide> expect(_file('tests/unit/services/foo-test.js')) <del> .to.contain("import { describe, it } from 'mocha';") <del> .to.contain("import { setupTest } from 'ember-mocha';") <del> .to.contain("describe('Unit | Service | foo', function() {") <del> .to.contain("setupTest('service:foo',"); <add> .to.equal(fixture('service-test/mocha-0.12.js')); <ide> }); <ide> }); <ide> <ide> it('service-test foo --pod', function() { <ide> return emberGenerateDestroy(['service-test', 'foo', '--pod'], _file => { <ide> expect(_file('tests/unit/foo/service-test.js')) <del> .to.contain("import { describe, it } from 'mocha';") <del> .to.contain("import { setupTest } from 'ember-mocha';") <del> .to.contain("describe('Unit | Service | foo', function() {") <del> .to.contain("setupTest('service:foo',"); <add> .to.equal(fixture('service-test/mocha-0.12.js')); <ide> }); <ide> }); <ide> }); <ide> describe('Blueprint: service-test', function() { <ide> it('service-test foo', function() { <ide> return emberGenerateDestroy(['service-test', 'foo'], _file => { <ide> expect(_file('tests/unit/services/foo-test.js')) <del> .to.contain("import { moduleFor, test } from 'ember-qunit';") <del> .to.contain("moduleFor('service:foo'"); <add> .to.equal(fixture('service-test/default.js')); <ide> <ide> expect(_file('app/service-test/foo.js')) <ide> .to.not.exist; <ide><path>node-tests/fixtures/service-test/default.js <add>import { moduleFor, test } from 'ember-qunit'; <add> <add>moduleFor('service:foo', 'Unit | Service | foo', { <add> // Specify the other units that are required for this test. <add> // needs: ['service:foo'] <add>}); <add> <add>// Replace this with your real tests. <add>test('it exists', function(assert) { <add> let service = this.subject(); <add> assert.ok(service); <add>}); <ide><path>node-tests/fixtures/service-test/mocha-0.12.js <add>import { expect } from 'chai'; <add>import { describe, it } from 'mocha'; <add>import { setupTest } from 'ember-mocha'; <add> <add>describe('Unit | Service | foo', function() { <add> setupTest('service:foo', { <add> // Specify the other units that are required for this test. <add> // needs: ['service:foo'] <add> }); <add> <add> // Replace this with your real tests. <add> it('exists', function() { <add> let service = this.subject(); <add> expect(service).to.be.ok; <add> }); <add>}); <ide><path>node-tests/fixtures/service-test/mocha.js <add>import { expect } from 'chai'; <add>import { describeModule, it } from 'ember-mocha'; <add> <add>describeModule('service:foo', 'Unit | Service | foo', <add> { <add> // Specify the other units that are required for this test. <add> // needs: ['service:foo'] <add> }, <add> function() { <add> // Replace this with your real tests. <add> it('exists', function() { <add> let service = this.subject(); <add> expect(service).to.be.ok; <add> }); <add> } <add>);
4
Text
Text
fix typo in adding_a_new_model readme
a5282ab4bcb0556be5bc9c82d3e17ed978419605
<ide><path>templates/adding_a_new_model/README.md <ide> You will also see a doc file and tests for your new models. First you should run <ide> <ide> ``` <ide> make style <del>maxke fix-copies <add>make fix-copies <ide> ``` <ide> <ide> and then you can start tweaking your model. You should:
1
Python
Python
update boto3 api calls in ecsoperator
2ab2cbf93df9eddfb527fcfd9d7b442678a57662
<ide><path>airflow/providers/amazon/aws/operators/ecs.py <ide> def _start_task(self): <ide> self.arn = response['tasks'][0]['taskArn'] <ide> <ide> def _try_reattach_task(self): <del> task_def_resp = self.client.describe_task_definition(self.task_definition) <add> task_def_resp = self.client.describe_task_definition(taskDefinition=self.task_definition) <ide> ecs_task_family = task_def_resp['taskDefinition']['family'] <ide> <ide> list_tasks_resp = self.client.list_tasks( <del> cluster=self.cluster, launchType=self.launch_type, desiredStatus='RUNNING', family=ecs_task_family <add> cluster=self.cluster, desiredStatus='RUNNING', family=ecs_task_family <ide> ) <ide> running_tasks = list_tasks_resp['taskArns'] <ide> <ide><path>tests/providers/amazon/aws/operators/test_ecs.py <ide> def test_reattach_successful(self, launch_type, tags, start_mock, check_mock, wa <ide> if tags: <ide> extend_args['tags'] = [{'key': k, 'value': v} for (k, v) in tags.items()] <ide> <del> client_mock.describe_task_definition.assert_called_once_with('t') <add> client_mock.describe_task_definition.assert_called_once_with(taskDefinition='t') <ide> <del> client_mock.list_tasks.assert_called_once_with( <del> cluster='c', launchType=launch_type, desiredStatus='RUNNING', family='f' <del> ) <add> client_mock.list_tasks.assert_called_once_with(cluster='c', desiredStatus='RUNNING', family='f') <ide> <ide> start_mock.assert_not_called() <ide> wait_mock.assert_called_once_with()
2
Javascript
Javascript
add type for onlayout
9108f98ca72c1d72d843145f0f1fb8b010be1d35
<ide><path>Libraries/Components/Keyboard/KeyboardAvoidingView.js <ide> const View = require('View'); <ide> const ViewPropTypes = require('ViewPropTypes'); <ide> <ide> import type EmitterSubscription from 'EmitterSubscription'; <add>import type {ViewLayout, ViewLayoutEvent} from 'ViewPropTypes'; <ide> <del>type Rect = { <del> x: number, <del> y: number, <del> width: number, <del> height: number, <del>}; <ide> type ScreenRect = { <ide> screenX: number, <ide> screenY: number, <ide> type KeyboardChangeEvent = { <ide> duration?: number, <ide> easing?: string, <ide> }; <del>type LayoutEvent = { <del> nativeEvent: { <del> layout: Rect, <del> } <del>}; <ide> <ide> const viewRef = 'VIEW'; <ide> <ide> const KeyboardAvoidingView = React.createClass({ <ide> }, <ide> <ide> subscriptions: ([]: Array<EmitterSubscription>), <del> frame: (null: ?Rect), <add> frame: (null: ?ViewLayout), <ide> <ide> relativeKeyboardHeight(keyboardFrame: ScreenRect): number { <ide> const frame = this.frame; <ide> const KeyboardAvoidingView = React.createClass({ <ide> this.setState({bottom: height}); <ide> }, <ide> <del> onLayout(event: LayoutEvent) { <add> onLayout(event: ViewLayoutEvent) { <ide> this.frame = event.nativeEvent.layout; <ide> }, <ide> <ide><path>Libraries/Components/View/ViewPropTypes.js <ide> import type {TVViewProps} from 'TVViewPropTypes'; <ide> <ide> const stylePropType = StyleSheetPropType(ViewStylePropTypes); <ide> <add>export type ViewLayout = { <add> x: number, <add> y: number, <add> width: number, <add> height: number, <add>} <add> <add>export type ViewLayoutEvent = { <add> nativeEvent: { <add> layout: ViewLayout, <add> } <add>} <add> <ide> // There's no easy way to create a different type if(Platform.isTVOS): <ide> // so we must include TVViewProps <ide> export type ViewProps = { <ide> export type ViewProps = { <ide> onMagicTap?: Function, <ide> testID?: string, <ide> nativeID?: string, <add> onLayout?: (event: ViewLayoutEvent) => void, <ide> onResponderGrant?: Function, <ide> onResponderMove?: Function, <ide> onResponderReject?: Function, <ide><path>RNTester/js/LayoutEventsExample.js <ide> var { <ide> View, <ide> } = ReactNative; <ide> <del>type Layout = { <del> x: number; <del> y: number; <del> width: number; <del> height: number; <del>}; <del> <del>type LayoutEvent = { <del> nativeEvent: { <del> layout: Layout, <del> }; <del>}; <add>import type {ViewLayout, ViewLayoutEvent} from 'ViewPropTypes'; <ide> <ide> type State = { <ide> containerStyle?: { width: number }, <ide> extraText?: string, <del> imageLayout?: Layout, <del> textLayout?: Layout, <del> viewLayout?: Layout, <add> imageLayout?: ViewLayout, <add> textLayout?: ViewLayout, <add> viewLayout?: ViewLayout, <ide> viewStyle: { margin: number }, <ide> }; <ide> <ide> class LayoutEventExample extends React.Component { <ide> this.setState({containerStyle: {width: 280}}); <ide> }; <ide> <del> onViewLayout = (e: LayoutEvent) => { <add> onViewLayout = (e: ViewLayoutEvent) => { <ide> console.log('received view layout event\n', e.nativeEvent); <ide> this.setState({viewLayout: e.nativeEvent.layout}); <ide> }; <ide> <del> onTextLayout = (e: LayoutEvent) => { <add> onTextLayout = (e: ViewLayoutEvent) => { <ide> console.log('received text layout event\n', e.nativeEvent); <ide> this.setState({textLayout: e.nativeEvent.layout}); <ide> }; <ide> <del> onImageLayout = (e: LayoutEvent) => { <add> onImageLayout = (e: ViewLayoutEvent) => { <ide> console.log('received image layout event\n', e.nativeEvent); <ide> this.setState({imageLayout: e.nativeEvent.layout}); <ide> };
3
Javascript
Javascript
fix $digest example
4e65635f85f83f3e92e279563bb4f26eb05eb02e
<ide><path>src/ng/rootScope.js <ide> function $RootScopeProvider(){ <ide> scope.counter = 0; <ide> <ide> expect(scope.counter).toEqual(0); <del> scope.$watch('name', function(scope, newValue, oldValue) { <add> scope.$watch('name', function(newValue, oldValue) { <ide> counter = counter + 1; <ide> }); <ide> expect(scope.counter).toEqual(0);
1
Javascript
Javascript
add ability to silence packager logs to stdout
d5445d5fbc5ea6d1ec01c9d4e7692613a216967f
<ide><path>local-cli/util/log.js <ide> */ <ide> 'use strict'; <ide> <add>var _enabled = true; <add> <add>function disable() { <add> _enabled = false; <add>} <add> <ide> function log(stream, module) { <ide> return function() { <add> if (!_enabled) { <add> return; <add> } <ide> const message = Array.prototype.slice.call(arguments).join(' '); <ide> stream.write(module + ': ' + message + '\n'); <ide> }; <ide> } <ide> <ide> module.exports.out = log.bind(null, process.stdout); <ide> module.exports.err = log.bind(null, process.stderr); <add>module.exports.disable = disable; <ide><path>packager/react-packager/src/Bundler/index.js <ide> const validateOpts = declareOpts({ <ide> type: 'number', <ide> required: false, <ide> }, <add> silent: { <add> type: 'boolean', <add> default: false, <add> }, <ide> }); <ide> <ide> class Bundler { <ide> class Bundler { <ide> const modulesByName = Object.create(null); <ide> <ide> if (!resolutionResponse) { <del> let onProgess; <del> if (process.stdout.isTTY) { <add> let onProgess = noop; <add> if (process.stdout.isTTY && !this._opts.silent) { <ide> const bar = new ProgressBar( <ide> 'transformed :current/:total (:percent)', <ide> {complete: '=', incomplete: ' ', width: 40, total: 1}, <ide><path>packager/react-packager/src/Server/index.js <ide> const validateOpts = declareOpts({ <ide> type: 'string', <ide> required: false, <ide> }, <add> silent: { <add> type: 'boolean', <add> default: false, <add> }, <ide> }); <ide> <ide> const bundleOpts = declareOpts({
3
Ruby
Ruby
fix conditional in env.fortran
405ba3df68ce1e03800f67d631b76bbec2b1d14a
<ide><path>Library/Homebrew/extend/ENV/shared.rb <ide> def fortran <ide> flags_to_set = FC_FLAG_VARS.reject { |key| self[key] } <ide> flags_to_set.each {|key| self[key] = cflags} <ide> set_cpu_flags(flags_to_set) <del> elsif not self['FCFLAGS'] or self['FFLAGS'] <add> elsif values_at(*FC_FLAG_VARS).compact.empty? <ide> opoo <<-EOS.undent <ide> No Fortran optimization information was provided. You may want to consider <ide> setting FCFLAGS and FFLAGS or pass the `--default-fortran-flags` option to
1
Go
Go
remove daemon dependency in containercreate()
03a170c48d660be72c387f1821ca48a713dd1cea
<ide><path>api/server/router/container/backend.go <ide> type copyBackend interface { <ide> <ide> // stateBackend includes functions to implement to provide container state lifecycle functionality. <ide> type stateBackend interface { <del> ContainerCreate(params *daemon.ContainerCreateConfig) (types.ContainerCreateResponse, error) <add> ContainerCreate(types.ContainerCreateConfig) (types.ContainerCreateResponse, error) <ide> ContainerKill(name string, sig uint64) error <ide> ContainerPause(name string) error <ide> ContainerRename(oldName, newName string) error <ide><path>api/server/router/container/container_routes.go <ide> func (s *containerRouter) postContainersCreate(ctx context.Context, w http.Respo <ide> version := httputils.VersionFromContext(ctx) <ide> adjustCPUShares := version.LessThan("1.19") <ide> <del> ccr, err := s.backend.ContainerCreate(&daemon.ContainerCreateConfig{ <add> ccr, err := s.backend.ContainerCreate(types.ContainerCreateConfig{ <ide> Name: name, <ide> Config: config, <ide> HostConfig: hostConfig, <ide><path>api/types/configs.go <ide> import ( <ide> "github.com/docker/docker/runconfig" <ide> ) <ide> <add>// ContainerCreateConfig is the parameter set to ContainerCreate() <add>type ContainerCreateConfig struct { <add> Name string <add> Config *runconfig.Config <add> HostConfig *runconfig.HostConfig <add> AdjustCPUShares bool <add>} <add> <ide> // ContainerRmConfig holds arguments for the container remove <ide> // operation. This struct is used to tell the backend what operations <ide> // to perform. <ide><path>builder/builder.go <ide> import ( <ide> "time" <ide> <ide> "github.com/docker/docker/api/types" <del> "github.com/docker/docker/daemon" <ide> "github.com/docker/docker/runconfig" <ide> ) <ide> <ide> type Backend interface { <ide> // ContainerWsAttachWithLogs attaches to container. <ide> ContainerWsAttachWithLogs(name string, cfg *daemon.ContainerWsAttachWithLogsConfig) error <ide> // ContainerCreate creates a new Docker container and returns potential warnings <del> ContainerCreate(params *daemon.ContainerCreateConfig) (types.ContainerCreateResponse, error) <add> ContainerCreate(types.ContainerCreateConfig) (types.ContainerCreateResponse, error) <ide> // ContainerRm removes a container specified by `id`. <ide> ContainerRm(name string, config *types.ContainerRmConfig) error <ide> // Commit creates a new Docker image from an existing Docker container. <ide><path>builder/dockerfile/internals.go <ide> import ( <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/builder" <ide> "github.com/docker/docker/builder/dockerfile/parser" <del> "github.com/docker/docker/daemon" <ide> "github.com/docker/docker/pkg/archive" <ide> "github.com/docker/docker/pkg/httputils" <ide> "github.com/docker/docker/pkg/ioutils" <ide> func (b *Builder) runContextCommand(args []string, allowRemote bool, allowLocalD <ide> return nil <ide> } <ide> <del> container, err := b.docker.ContainerCreate(&daemon.ContainerCreateConfig{Config: b.runConfig}) <add> container, err := b.docker.ContainerCreate(types.ContainerCreateConfig{Config: b.runConfig}) <ide> if err != nil { <ide> return err <ide> } <ide> func (b *Builder) create() (string, error) { <ide> config := *b.runConfig <ide> <ide> // Create the container <del> c, err := b.docker.ContainerCreate(&daemon.ContainerCreateConfig{ <add> c, err := b.docker.ContainerCreate(types.ContainerCreateConfig{ <ide> Config: b.runConfig, <ide> HostConfig: hostConfig, <ide> }) <ide><path>daemon/create.go <ide> import ( <ide> "github.com/opencontainers/runc/libcontainer/label" <ide> ) <ide> <del>// ContainerCreateConfig is the parameter set to ContainerCreate() <del>type ContainerCreateConfig struct { <del> Name string <del> Config *runconfig.Config <del> HostConfig *runconfig.HostConfig <del> AdjustCPUShares bool <del>} <del> <del>// ContainerCreate takes configs and creates a container. <del>func (daemon *Daemon) ContainerCreate(params *ContainerCreateConfig) (types.ContainerCreateResponse, error) { <add>// ContainerCreate creates a container. <add>func (daemon *Daemon) ContainerCreate(params types.ContainerCreateConfig) (types.ContainerCreateResponse, error) { <ide> if params.Config == nil { <ide> return types.ContainerCreateResponse{}, derr.ErrorCodeEmptyConfig <ide> } <ide> <ide> warnings, err := daemon.verifyContainerSettings(params.HostConfig, params.Config) <ide> if err != nil { <del> return types.ContainerCreateResponse{ID: "", Warnings: warnings}, err <add> return types.ContainerCreateResponse{Warnings: warnings}, err <ide> } <ide> <ide> if params.HostConfig == nil { <ide> params.HostConfig = &runconfig.HostConfig{} <ide> } <ide> err = daemon.adaptContainerSettings(params.HostConfig, params.AdjustCPUShares) <ide> if err != nil { <del> return types.ContainerCreateResponse{ID: "", Warnings: warnings}, err <add> return types.ContainerCreateResponse{Warnings: warnings}, err <ide> } <ide> <ide> container, err := daemon.create(params) <ide> if err != nil { <del> return types.ContainerCreateResponse{ID: "", Warnings: warnings}, daemon.imageNotExistToErrcode(err) <add> return types.ContainerCreateResponse{Warnings: warnings}, daemon.imageNotExistToErrcode(err) <ide> } <ide> <ide> return types.ContainerCreateResponse{ID: container.ID, Warnings: warnings}, nil <ide> } <ide> <ide> // Create creates a new container from the given configuration with a given name. <del>func (daemon *Daemon) create(params *ContainerCreateConfig) (retC *container.Container, retErr error) { <add>func (daemon *Daemon) create(params types.ContainerCreateConfig) (*container.Container, error) { <ide> var ( <ide> container *container.Container <ide> img *image.Image <ide> imgID image.ID <ide> err error <add> retErr error <ide> ) <ide> <ide> if params.Config.Image != "" {
6
Javascript
Javascript
name anonymous functions
e658f5b066e1861c6ab2ec76d9ae2a2d132aa5dd
<ide><path>lib/repl.js <ide> function REPLServer(prompt, <ide> <ide> self.eval = self._domain.bind(eval_); <ide> <del> self._domain.on('error', function(e) { <add> self._domain.on('error', function debugDomainError(e) { <ide> debug('domain error'); <ide> const top = replMap.get(self); <ide> internalUtil.decorateErrorStack(e); <ide> function REPLServer(prompt, <ide> }; <ide> } <ide> <del> self.on('close', function() { <add> self.on('close', function emitExit() { <ide> self.emit('exit'); <ide> }); <ide> <ide> var sawSIGINT = false; <ide> var sawCtrlD = false; <del> self.on('SIGINT', function() { <add> self.on('SIGINT', function onSigInt() { <ide> var empty = self.line.length === 0; <ide> self.clearLine(); <ide> self.turnOffEditorMode(); <ide> function REPLServer(prompt, <ide> self.displayPrompt(); <ide> }); <ide> <del> self.on('line', function(cmd) { <add> self.on('line', function onLine(cmd) { <ide> debug('line %j', cmd); <ide> sawSIGINT = false; <ide> <ide> function REPLServer(prompt, <ide> } <ide> }); <ide> <del> self.on('SIGCONT', function() { <add> self.on('SIGCONT', function onSigCont() { <ide> if (self.editorMode) { <ide> self.outputStream.write(`${self._initialPrompt}.editor\n`); <ide> self.outputStream.write( <ide> function complete(line, callback) { <ide> addStandardGlobals(completionGroups, filter); <ide> completionGroupsLoaded(); <ide> } else { <del> this.eval('.scope', this.context, 'repl', function(err, globals) { <add> this.eval('.scope', this.context, 'repl', function ev(err, globals) { <ide> if (err || !Array.isArray(globals)) { <ide> addStandardGlobals(completionGroups, filter); <ide> } else if (Array.isArray(globals[0])) { <ide> function complete(line, callback) { <ide> } <ide> } else { <ide> const evalExpr = `try { ${expr} } catch (e) {}`; <del> this.eval(evalExpr, this.context, 'repl', function(e, obj) { <add> this.eval(evalExpr, this.context, 'repl', function doEval(e, obj) { <ide> // if (e) console.log(e); <ide> <ide> if (obj != null) {
1
Mixed
Ruby
add collection cache versioning
4f2ac80d4cdb01c4d3c1765637bed76cc91c1e35
<ide><path>activerecord/CHANGELOG.md <add>* Add `ActiveRecord::Relation#cache_version` to support recyclable cache keys via <add> the versioned entries in `ActiveSupport::Cache`. This also means that <add> `ActiveRecord::Relation#cache_key` will now return a stable key that does not <add> include the max timestamp or count any more. <add> <add> NOTE: This feature is turned off by default, and `cache_key` will still return <add> cache keys with timestamps until you set `ActiveRecord::Base.collection_cache_versioning = true`. <add> That's the setting for all new apps on Rails 6.0+ <add> <add> *Lachlan Sylvester* <add> <ide> * Fix dirty tracking for `touch` to track saved changes. <ide> <ide> Fixes #33429. <ide><path>activerecord/lib/active_record/integration.rb <ide> module Integration <ide> # <ide> # This is +true+, by default on Rails 5.2 and above. <ide> class_attribute :cache_versioning, instance_writer: false, default: false <add> <add> ## <add> # :singleton-method: <add> # Indicates whether to use a stable #cache_key method that is accompanied <add> # by a changing version in the #cache_version method on collections. <add> # <add> # This is +false+, by default until Rails 6.1. <add> class_attribute :collection_cache_versioning, instance_writer: false, default: false <ide> end <ide> <ide> # Returns a +String+, which Action Pack uses for constructing a URL to this <ide><path>activerecord/lib/active_record/relation.rb <ide> def many? <ide> limit_value ? records.many? : size > 1 <ide> end <ide> <del> # Returns a cache key that can be used to identify the records fetched by <del> # this query. The cache key is built with a fingerprint of the sql query, <del> # the number of records matched by the query and a timestamp of the last <del> # updated record. When a new record comes to match the query, or any of <del> # the existing records is updated or deleted, the cache key changes. <add> # Returns a stable cache key that can be used to identify this query. <add> # The cache key is built with a fingerprint of the SQL query. <ide> # <del> # Product.where("name like ?", "%Cosmic Encounter%").cache_key <del> # # => "products/query-1850ab3d302391b85b8693e941286659-1-20150714212553907087000" <add> # Product.where("name like ?", "%Cosmic Encounter%").cache_key <add> # # => "products/query-1850ab3d302391b85b8693e941286659" <ide> # <del> # If the collection is loaded, the method will iterate through the records <del> # to generate the timestamp, otherwise it will trigger one SQL query like: <add> # If ActiveRecord::Base.collection_cache_versioning is turned off, as it was <add> # in Rails 6.0 and earlier, the cache key will also include a version. <ide> # <del> # SELECT COUNT(*), MAX("products"."updated_at") FROM "products" WHERE (name like '%Cosmic Encounter%') <add> # ActiveRecord::Base.collection_cache_versioning = false <add> # Product.where("name like ?", "%Cosmic Encounter%").cache_key <add> # # => "products/query-1850ab3d302391b85b8693e941286659-1-20150714212553907087000" <ide> # <ide> # You can also pass a custom timestamp column to fetch the timestamp of the <ide> # last updated record. <ide> # <ide> # Product.where("name like ?", "%Game%").cache_key(:last_reviewed_at) <del> # <del> # You can customize the strategy to generate the key on a per model basis <del> # overriding ActiveRecord::Base#collection_cache_key. <ide> def cache_key(timestamp_column = :updated_at) <ide> @cache_keys ||= {} <ide> @cache_keys[timestamp_column] ||= @klass.collection_cache_key(self, timestamp_column) <ide> def compute_cache_key(timestamp_column = :updated_at) # :nodoc: <ide> query_signature = ActiveSupport::Digest.hexdigest(to_sql) <ide> key = "#{klass.model_name.cache_key}/query-#{query_signature}" <ide> <add> if cache_version(timestamp_column) <add> key <add> else <add> "#{key}-#{compute_cache_version(timestamp_column)}" <add> end <add> end <add> <add> # Returns a cache version that can be used together with the cache key to form <add> # a recyclable caching scheme. The cache version is built with the number of records <add> # matching the query, and the timestamp of the last updated record. When a new record <add> # comes to match the query, or any of the existing records is updated or deleted, <add> # the cache version changes. <add> # <add> # If the collection is loaded, the method will iterate through the records <add> # to generate the timestamp, otherwise it will trigger one SQL query like: <add> # <add> # SELECT COUNT(*), MAX("products"."updated_at") FROM "products" WHERE (name like '%Cosmic Encounter%') <add> def cache_version(timestamp_column = :updated_at) <add> if collection_cache_versioning <add> @cache_versions ||= {} <add> @cache_versions[timestamp_column] ||= compute_cache_version(timestamp_column) <add> end <add> end <add> <add> def compute_cache_version(timestamp_column) # :nodoc: <ide> if loaded? || distinct_value <ide> size = records.size <ide> if size > 0 <ide> def compute_cache_key(timestamp_column = :updated_at) # :nodoc: <ide> end <ide> <ide> if timestamp <del> "#{key}-#{size}-#{timestamp.utc.to_s(cache_timestamp_format)}" <add> "#{size}-#{timestamp.utc.to_s(cache_timestamp_format)}" <ide> else <del> "#{key}-#{size}" <add> "#{size}" <ide> end <ide> end <ide> <ide><path>activerecord/test/cases/collection_cache_key_test.rb <ide> class CollectionCacheKeyTest < ActiveRecord::TestCase <ide> <ide> assert_match(/\Adevelopers\/query-(\h+)-(\d+)-(\d+)\z/, developers.cache_key) <ide> end <add> <add> test "cache_key should be stable when using collection_cache_versioning" do <add> with_collection_cache_versioning do <add> developers = Developer.where(salary: 100000) <add> <add> assert_match(/\Adevelopers\/query-(\h+)\z/, developers.cache_key) <add> <add> /\Adevelopers\/query-(\h+)\z/ =~ developers.cache_key <add> <add> assert_equal ActiveSupport::Digest.hexdigest(developers.to_sql), $1 <add> end <add> end <add> <add> test "cache_version for relation" do <add> with_collection_cache_versioning do <add> developers = Developer.where(salary: 100000).order(updated_at: :desc) <add> last_developer_timestamp = developers.first.updated_at <add> <add> assert_match(/(\d+)-(\d+)\z/, developers.cache_version) <add> <add> /(\d+)-(\d+)\z/ =~ developers.cache_version <add> <add> assert_equal developers.count.to_s, $1 <add> assert_equal last_developer_timestamp.to_s(ActiveRecord::Base.cache_timestamp_format), $2 <add> end <add> end <add> <add> def with_collection_cache_versioning(value = true) <add> @old_collection_cache_versioning = ActiveRecord::Base.collection_cache_versioning <add> ActiveRecord::Base.collection_cache_versioning = value <add> yield <add> ensure <add> ActiveRecord::Base.collection_cache_versioning = @old_collection_cache_versioning <add> end <ide> end <ide> end <ide><path>railties/lib/rails/application/configuration.rb <ide> def load_defaults(target_version) <ide> active_storage.queues.analysis = :active_storage_analysis <ide> active_storage.queues.purge = :active_storage_purge <ide> end <add> <add> if respond_to?(:active_record) <add> active_record.collection_cache_versioning = true <add> end <ide> else <ide> raise "Unknown version #{target_version.to_s.inspect}" <ide> end
5
Java
Java
remove stray head line
f651b7a504f9ec5c1c7f89ede072656d36def3d7
<ide><path>rxjava-core/src/main/java/rx/Observable.java <ide> public Subscription call(Observer<T> observer) { <ide> } <ide> <ide> /** <del><<<<<<< HEAD <ide> * Creates an Observable which produces buffers of collected values. This Observable produces connected <ide> * non-overlapping buffers. The current buffer is emitted and replaced with a new buffer when the <ide> * Observable produced by the specified {@link Func0} produces a {@link BufferClosing} object. The
1
Text
Text
add api challenges - spanish
f427fb4b91b1aeec7da37c8fc7b7d0d37266bb37
<ide><path>curriculum/challenges/spanish/05-apis-and-microservices/apis-and-microservices-projects/exercise-tracker.spanish.md <add>--- <add>id: 5a8b073d06fa14fcfde687aa <add>title: Exercise Tracker <add>localeTitle: Rastreador de ejercicios <add>challengeType: 4 <add>isRequired: true <add>--- <add> <add>## Description <add><section id='description'> <add>Cree una aplicación de JavaScript de pila completa que sea funcionalmente similar a esta: <a href='https://fuschia-custard.glitch.me/' target='_blank'>https://fuschia-custard.glitch.me/</a> . <add>Trabajar en este proyecto implicará que escriba su código en Glitch en nuestro proyecto de inicio. Después de completar este proyecto, puede copiar su URL de error público (en la página de inicio de su aplicación) en esta pantalla para probarlo. Opcionalmente, puede optar por escribir su proyecto en otra plataforma, pero debe ser visible públicamente para nuestras pruebas. <add>Inicie este proyecto en Glitch usando <a href='https://glitch.com/#!/import/github/freeCodeCamp/boilerplate-project-exercisetracker/' target='_blank'>este enlace</a> o clone <a href='https://github.com/freeCodeCamp/boilerplate-project-exercisetracker/'>este repositorio</a> en GitHub! Si utiliza Glitch, recuerde guardar el enlace a su proyecto en un lugar seguro. <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: Puedo crear un usuario al publicar el nombre de usuario de los datos del formulario en / api / exercise / new-user y se devolverá un objeto con nombre de usuario y <code>_id</code> . <add> testString: '' <add> - text: Puedo obtener una matriz de todos los usuarios al obtener api / ejercicio / usuarios con la misma información que cuando se crea un usuario. <add> testString: '' <add> - text: 'Puedo agregar un ejercicio a cualquier usuario publicando los datos del formulario ID de usuario (_id), descripción, duración y, opcionalmente, fechar en / api / ejercicio / agregar. Si no se proporciona la fecha, se utilizará la fecha actual. La aplicación devolverá el objeto de usuario con los campos de ejercicio agregados. ' <add> testString: '' <add> - text: Puedo recuperar un registro de ejercicio completo de cualquier usuario obteniendo / api / exercise / log con un parámetro de userId (_id). La aplicación devolverá el objeto de usuario con el registro de matriz agregada y el conteo (recuento total de ejercicios). <add> testString: '' <add> - text: 'Puedo recuperar parte del registro de cualquier usuario pasando también parámetros opcionales de desde y hasta o límite. (Formato de fecha aaaa-mm-dd, límite = 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/spanish/05-apis-and-microservices/apis-and-microservices-projects/file-metadata-microservice.spanish.md <add>--- <add>id: bd7158d8c443edefaeb5bd0f <add>title: File Metadata Microservice <add>localeTitle: Archivo de metadatos de microservicio <add>challengeType: 4 <add>isRequired: true <add>--- <add> <add>## Description <add><section id='description'> <add>Cree una aplicación de JavaScript de pila completa que sea funcionalmente similar a esto: <a href='https://purple-paladin.glitch.me/' target='_blank'>https://purple-paladin.glitch.me/</a> . <add>Trabajar en este proyecto implicará que escriba su código en Glitch en nuestro proyecto de inicio. Después de completar este proyecto, puede copiar su URL de error público (en la página de inicio de su aplicación) en esta pantalla para probarlo. Opcionalmente, puede optar por escribir su proyecto en otra plataforma, pero debe ser visible públicamente para nuestras pruebas. <add>Inicie este proyecto en Glitch usando <a href='https://glitch.com/#!/import/github/freeCodeCamp/boilerplate-project-filemetadata/' target='_blank'>este enlace</a> o clone <a href='https://github.com/freeCodeCamp/boilerplate-project-filemetadata/'>este repositorio</a> en GitHub! Si utiliza Glitch, recuerde guardar el enlace a su proyecto en un lugar seguro. <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: Puedo enviar un objeto FormData que incluya una carga de archivos. <add> testString: '' <add> - text: "Cuando envíe algo, recibiré el tamaño del archivo en bytes dentro de la respuesta 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/spanish/05-apis-and-microservices/apis-and-microservices-projects/request-header-parser-microservice.spanish.md <add>--- <add>id: bd7158d8c443edefaeb5bdff <add>title: Request Header Parser Microservice <add>localeTitle: Solicitud de encabezado Analizador de microservicio <add>challengeType: 4 <add>isRequired: true <add>--- <add> <add>## Description <add><section id='description'> <add>Cree una aplicación de JavaScript de pila completa que sea funcionalmente similar a esto: <a href='https://dandelion-roar.glitch.me/' target='_blank'>https://dandelion-roar.glitch.me/</a> . <add>Trabajar en este proyecto implicará que escriba su código en Glitch en nuestro proyecto de inicio. Después de completar este proyecto, puede copiar su URL de error público (en la página de inicio de su aplicación) en esta pantalla para probarlo. Opcionalmente, puede optar por escribir su proyecto en otra plataforma, pero debe ser visible públicamente para nuestras pruebas. <add>Inicie este proyecto en Glitch usando <a href='https://glitch.com/#!/import/github/freeCodeCamp/boilerplate-project-headerparser/' target='_blank'>este enlace</a> o clone <a href='https://github.com/freeCodeCamp/boilerplate-project-headerparser/'>este repositorio</a> en GitHub! Si utiliza Glitch, recuerde guardar el enlace a su proyecto en un lugar seguro. <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: "Puedo obtener la dirección IP, el idioma y el sistema operativo de mi navegador." <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/spanish/05-apis-and-microservices/apis-and-microservices-projects/timestamp-microservice.spanish.md <add>--- <add>id: bd7158d8c443edefaeb5bdef <add>title: Timestamp Microservice <add>localeTitle: Marca de tiempo microservicio <add>challengeType: 4 <add>isRequired: true <add>--- <add> <add>## Description <add><section id='description'> <add>Cree una aplicación de JavaScript de pila completa que sea funcionalmente similar a esto: <a href='https://curse-arrow.glitch.me/' target='_blank'>https://curse-arrow.glitch.me/</a> . <add>Trabajar en este proyecto implicará que escriba su código en Glitch en nuestro proyecto de inicio. Después de completar este proyecto, puede copiar su URL de error público (en la página de inicio de su aplicación) en esta pantalla para probarlo. Opcionalmente, puede optar por escribir su proyecto en otra plataforma, pero debe ser visible públicamente para nuestras pruebas. <add>Inicie este proyecto en Glitch usando <a href='https://glitch.com/#!/import/github/freeCodeCamp/boilerplate-project-timestamp/' target='_blank'>este enlace</a> o clone <a href='https://github.com/freeCodeCamp/boilerplate-project-timestamp/'>este repositorio</a> en GitHub! Si utiliza Glitch, recuerde guardar el enlace a su proyecto en un lugar seguro. <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: 'Debe manejar una fecha válida y devolver la marca de tiempo de Unix correcta' <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: 'Debe manejar una fecha válida y devolver la cadena UTC correcta' <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: 'Debe manejar una fecha de Unix válida y devolver la marca de tiempo de Unix correcta' <add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/api/timestamp/1482624000000'').then(data => { assert.equal(data.unix, 1482624000000) ; }, xhr => { throw new Error(xhr.responseText); })' <add> - text: Debe devolver el mensaje de error esperado para una fecha no válida <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: 'Debería manejar un parámetro de fecha vacío y devolver la hora actual en formato 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: 'Debe manejar un parámetro de fecha vacío y devolver la hora actual en formato 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/spanish/05-apis-and-microservices/apis-and-microservices-projects/url-shortener-microservice.spanish.md <add>--- <add>id: bd7158d8c443edefaeb5bd0e <add>title: URL Shortener Microservice <add>localeTitle: Microservicio de acortador de URL <add>challengeType: 4 <add>isRequired: true <add>--- <add> <add>## Description <add><section id='description'> <add>Cree una aplicación de JavaScript de pila completa que sea funcionalmente similar a esto: <a href='https://thread-paper.glitch.me/' target='_blank'>https://thread-paper.glitch.me/</a> . <add>Trabajar en este proyecto implicará que escriba su código en Glitch en nuestro proyecto de inicio. Después de completar este proyecto, puede copiar su URL de error público (en la página de inicio de su aplicación) en esta pantalla para probarlo. Opcionalmente, puede optar por escribir su proyecto en otra plataforma, pero debe ser visible públicamente para nuestras pruebas. <add>Inicie este proyecto en Glitch usando <a href='https://glitch.com/#!/import/github/freeCodeCamp/boilerplate-project-urlshortener/' target='_blank'>este enlace</a> o clone <a href='https://github.com/freeCodeCamp/boilerplate-project-urlshortener/'>este repositorio</a> en GitHub! Si utiliza Glitch, recuerde guardar el enlace a su proyecto en un lugar seguro. <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: Puedo pasar una URL como parámetro y recibiré una URL abreviada en la respuesta JSON. <add> testString: '' <add> - text: "Si paso una URL no válida que no sigue el formato válido de http://www.example.com, la respuesta JSON contendrá un error." <add> testString: '' <add> - text: "Cuando visite esa URL abreviada, me redirigirá a mi enlace original." <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/spanish/05-apis-and-microservices/basic-node-and-express/chain-middleware-to-create-a-time-server.spanish.md <add>--- <add>id: 587d7fb1367417b2b2512bf4 <add>title: Chain Middleware to Create a Time Server <add>localeTitle: Cadena de middleware para crear un servidor de tiempo <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <add>Middleware puede montarse en una ruta específica usando <code>app.METHOD(path, middlewareFunction)</code> . Middleware también puede ser encadenado dentro de la definición de ruta. <add>Mira el siguiente ejemplo: <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> <add>Este enfoque es útil para dividir las operaciones del servidor en unidades más pequeñas. Esto conduce a una mejor estructura de la aplicación y la posibilidad de reutilizar el código en diferentes lugares. Este enfoque también se puede utilizar para realizar una validación de los datos. En cada punto de la pila de middleware puede bloquear la ejecución de la cadena actual y pasar el control a funciones específicamente diseñadas para manejar errores. O puede pasar el control a la siguiente ruta coincidente, para manejar casos especiales. Veremos cómo en la sección avanzada de Express. <add>En la ruta <code>app.get('/now', ...)</code> una función de middleware y el controlador final. En la función de middleware, debe agregar la hora actual al objeto de solicitud en la clave <code>req.time</code> . Puede usar la <code>new Date().toString()</code> . En el controlador, responda con un objeto JSON, tomando la estructura <code>{time: req.time}</code> . <add>Sugerencia: la prueba no pasará si no encadena el middleware. Si monta la función en otro lugar, la prueba fallará, incluso si el resultado de salida es correcto. <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: El punto final / ahora debería tener middleware montado <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: El punto final / now debería devolver un tiempo que es de +/- 20 segundos a partir de ahora <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/spanish/05-apis-and-microservices/basic-node-and-express/get-data-from-post-requests.spanish.md <add>--- <add>id: 587d7fb2367417b2b2512bf8 <add>title: Get Data from POST Requests <add>localeTitle: Obtener datos de solicitudes POST <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <add>Monte un controlador POST en la ruta <code>/name</code> . Es el mismo camino que antes. Hemos preparado un formulario en la portada html. Se enviarán los mismos datos del ejercicio 10 (cadena de consulta). Si el analizador de cuerpo está configurado correctamente, debería encontrar los parámetros en el objeto <code>req.body</code> . Eche un vistazo al ejemplo habitual de la biblioteca: <add><blockquote>route: POST '/library'<br>urlencoded_body: userId=546&bookId=6754 <br>req.body: {userId: '546', bookId: '6754'}</blockquote> <add>Responda con el mismo objeto JSON que antes: <code>{name: 'firstname lastname'}</code> . Pruebe si su punto final funciona con el formulario html que proporcionamos en la página principal de la aplicación. <add>Sugerencia: hay varios otros métodos http distintos de GET y POST. Y, por convención, hay una correspondencia entre el verbo http y la operación que se va a ejecutar en el servidor. La asignación convencional es: <add>POST (a veces PUT): cree un nuevo recurso utilizando la información enviada con la solicitud, <add>GET: lea un recurso existente sin modificarlo, <add>PUT o PATCH (a veces POST): actualice un recurso utilizando los datos enviado, <add>BORRAR =&gt; Eliminar un recurso. <add>También hay un par de otros métodos que se utilizan para negociar una conexión con el servidor. Excepto en GET, todos los otros métodos mencionados anteriormente pueden tener una carga útil (es decir, los datos en el cuerpo de la solicitud). El middleware body-parser también funciona con estos métodos. <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: 'Prueba 1: su punto final de API debe responder con el nombre correcto' <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: 'Prueba 2: su punto final de API debe responder con el nombre correcto' <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/spanish/05-apis-and-microservices/basic-node-and-express/get-query-parameter-input-from-the-client.spanish.md <add>--- <add>id: 587d7fb2367417b2b2512bf6 <add>title: Get Query Parameter Input from the Client <add>localeTitle: Obtener entrada de parámetros de consulta del cliente <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <add>Otra forma común de obtener información del cliente es codificando los datos después de la ruta, utilizando una cadena de consulta. La cadena de consulta está delimitada por un signo de interrogación (?) E incluye parejas field = value. Cada pareja está separada por un signo (&amp;). Express puede analizar los datos de la cadena de consulta y rellenar el objeto <code>req.query</code> . Algunos caracteres no pueden estar en las URL, tienen que estar codificados en un <a href='https://en.wikipedia.org/wiki/Percent-encoding' target='_blank'>formato diferente</a> antes de poder enviarlos. Si usa la API desde JavaScript, puede usar métodos específicos para codificar / decodificar estos caracteres. <add><blockquote>route_path: '/library'<br>actual_request_URL: '/library?userId=546&bookId=6754' <br>req.query: {userId: '546', bookId: '6754'}</blockquote> <add>Construir un punto final de API, montado en <code>GET /name</code> . Responda con un documento JSON, tomando la estructura <code>{ name: 'firstname lastname'}</code> . Los parámetros de nombre y apellido deben estar codificados en una cadena de consulta, por ejemplo, <code>?first=firstname&amp;last=lastname</code> . <add>CONSEJO: En el siguiente ejercicio vamos a recibir datos de una solicitud POST, en la misma ruta de ruta <code>/name</code> . Si lo desea, puede utilizar el método <code>app.route(path).get(handler).post(handler)</code> . Esta sintaxis le permite encadenar diferentes controladores de verbos en la misma ruta de ruta. Puede guardar un poco de escritura y tener un código más limpio. <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: 'Prueba 1: su punto final de API debe responder con el nombre correcto' <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: 'Prueba 2: su punto final APi debe responder con el nombre correcto' <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/spanish/05-apis-and-microservices/basic-node-and-express/get-route-parameter-input-from-the-client.spanish.md <add>--- <add>id: 587d7fb2367417b2b2512bf5 <add>title: Get Route Parameter Input from the Client <add>localeTitle: Obtener entrada de parámetros de ruta del cliente <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <add>Al crear una API, debemos permitir que los usuarios nos comuniquen lo que desean obtener de nuestro servicio. Por ejemplo, si el cliente solicita información sobre un usuario almacenado en la base de datos, necesita una manera de informarnos en qué usuario está interesado. Una posible forma de lograr este resultado es mediante el uso de parámetros de ruta. Los parámetros de ruta se denominan segmentos de la URL, delimitados por barras inclinadas (/). Cada segmento captura el valor de la parte de la URL que coincide con su posición. Los valores capturados se pueden encontrar en el objeto <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> <add>Construya un servidor de eco, montado en la ruta <code>GET /:word/echo</code> . Responda con un objeto JSON, tomando la estructura <code>{echo: word}</code> . Puede encontrar la palabra que debe repetirse en <code>req.params.word</code> . Puede probar su ruta desde la barra de direcciones de su navegador, visitando algunas rutas coincidentes, por ejemplo, su-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: 'Prueba 1: su servidor de eco debe repetir palabras correctamente' <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: 'Prueba 2: su servidor de eco debe repetir palabras correctamente' <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/spanish/05-apis-and-microservices/basic-node-and-express/implement-a-root-level-request-logger-middleware.spanish.md <add>--- <add>id: 587d7fb1367417b2b2512bf3 <add>title: Implement a Root-Level Request Logger Middleware <add>localeTitle: Implementar un middleware de registrador de solicitudes de nivel raíz <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <add>Antes presentamos la función de middleware <code>express.static()</code> . Ahora es el momento de ver qué es el middleware, con más detalle. Las funciones de middleware son funciones que toman 3 argumentos: el objeto de solicitud, el objeto de respuesta y la siguiente función en el ciclo de solicitud-respuesta de la aplicación. Estas funciones ejecutan algunos códigos que pueden tener efectos secundarios en la aplicación y, por lo general, agregan información a los objetos de solicitud o respuesta. También pueden finalizar el ciclo enviando la respuesta, cuando se cumple alguna condición. Si no envían la respuesta, cuando terminan, comienzan la ejecución de la siguiente función en la pila. Esto se activa llamando al tercer argumento <code>next()</code> . Más información en la <a href='http://expressjs.com/en/guide/using-middleware.html' target='_blank'>documentación expresa</a> . <add>Mira el siguiente ejemplo: <add><blockquote>function(req, res, next) {<br> console.log("I'm a middleware...");<br> next();<br>}</blockquote> <add>Supongamos que montamos esta función en una ruta. Cuando una solicitud coincide con la ruta, muestra la cadena "Soy un middleware ...". Luego ejecuta la siguiente función en la pila. <add>En este ejercicio vamos a construir un middleware de nivel raíz. Como hemos visto en el desafío 4, para montar una función de middleware en el nivel raíz podemos usar el método <code>app.use(&lt;mware-function&gt;)</code> . En este caso, la función se ejecutará para todas las solicitudes, pero también puede establecer condiciones más específicas. Por ejemplo, si desea que una función se ejecute solo para solicitudes POST, puede usar <code>app.post(&lt;mware-function&gt;)</code> . Existen métodos análogos para todos los verbos http (GET, DELETE, PUT,…). <add>Construir un registrador simple. Para cada solicitud, debe iniciar sesión en la consola con una cadena que tenga el siguiente formato: <code>method path - ip</code> . Un ejemplo sería: <code>GET /json - ::ffff:127.0.0.1</code> . Tenga en cuenta que hay un espacio entre el <code>method</code> y la <code>path</code> y que la raya que separa la <code>path</code> y la <code>ip</code> está rodeada por un espacio en cada lado. Puede obtener el método de solicitud (verbo http), la ruta de ruta relativa y la dirección IP de la persona que llama desde el objeto de solicitud, utilizando <code>req.method</code> , <code>req.path</code> y <code>req.ip</code> Recuerde llamar a <code>next()</code> cuando haya terminado, o su servidor quedará atascado para siempre. Asegúrese de tener abiertos los 'Registros' y vea qué sucede cuando llega alguna solicitud ... <add>Sugerencia: Express evalúa las funciones en el orden en que aparecen en el código. Esto también es cierto para el middleware. Si desea que funcione para todas las rutas, debe montarse antes que ellas. <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: El middleware del registrador de nivel raíz debe estar activo <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/spanish/05-apis-and-microservices/basic-node-and-express/meet-the-node-console.spanish.md <add>--- <add>id: 587d7fb0367417b2b2512bed <add>title: Meet the Node console <add>localeTitle: Conozca la consola Node <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <add>Durante el proceso de desarrollo, es importante poder verificar lo que está pasando en su código. Nodo es solo un entorno de JavaScript. Al igual que JavaScript del lado del cliente, puede usar la consola para mostrar información útil de depuración. En su máquina local, vería la salida de la consola en un terminal. En Glitch puede abrir los registros en la parte inferior de la pantalla. Puede alternar el panel de registro con el botón 'Registros' (arriba a la izquierda, debajo del nombre de la aplicación). <add>Para comenzar, simplemente imprima el clásico "Hello World" en la consola. Recomendamos mantener abierto el panel de registro mientras se trabaja en estos desafíos. Al leer los registros, puede estar al tanto de la naturaleza de los errores que pueden ocurrir. <add></section> <add> <add>## Instructions <add><section id='instructions'> <add>Modifique el archivo <code>myApp.js</code> para registrar "Hello World" en la consola. <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: <code>"Hello World"</code> debería estar en la consola <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/spanish/05-apis-and-microservices/basic-node-and-express/serve-an-html-file.spanish.md <add>--- <add>id: 587d7fb0367417b2b2512bef <add>title: Serve an HTML File <add>localeTitle: Servir un archivo HTML <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <add>Podemos responder con un archivo utilizando el método <code>res.sendFile(path)</code> . <add>Puede colocarlo dentro del manejador de ruta <code>app.get('/', ...)</code> . Detrás de escena, este método establecerá los encabezados adecuados para instruir a su navegador sobre cómo manejar el archivo que desea enviar, según su tipo. Luego leerá y enviará el archivo. Este método necesita una ruta de archivo absoluta. Le recomendamos que utilice la variable global Node <code>__dirname</code> para calcular la ruta. <add>por ejemplo <code>absolutePath = __dirname + relativePath/file.ext</code> . <add>El archivo a enviar es <code>/views/index.html</code> . Intente 'Mostrar en vivo' su aplicación, debería ver un encabezado HTML grande (y un formulario que usaremos más adelante ...), sin estilo aplicado. <add>Nota: puede editar la solución del desafío anterior o crear una nueva. Si crea una nueva solución, tenga en cuenta que Express evalúa las rutas de arriba a abajo. Ejecuta el controlador para la primera partida. Debe comentar la solución anterior, o el servidor seguirá respondiendo con una cadena. <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: Su aplicación debe servir el archivo 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/spanish/05-apis-and-microservices/basic-node-and-express/serve-json-on-a-specific-route.spanish.md <add>--- <add>id: 587d7fb1367417b2b2512bf1 <add>title: Serve JSON on a Specific Route <add>localeTitle: Servir JSON en una ruta específica <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <add>Mientras que un servidor HTML sirve (¡lo has adivinado!) HTML, una API sirve datos. Una API <dfn>REST</dfn> (transferencia de estado representativa) permite el intercambio de datos de una manera sencilla, sin la necesidad de que los clientes conozcan ningún detalle sobre el servidor. El cliente solo necesita saber dónde está el recurso (la URL) y la acción que desea realizar en él (el verbo). El verbo GET se usa cuando estás obteniendo información, sin modificar nada. En estos días, el formato de datos preferido para mover información a través de la web es JSON. En pocas palabras, JSON es una forma conveniente de representar un objeto JavaScript como una cadena, por lo que se puede transmitir fácilmente. <add>Vamos a crear una API simple creando una ruta que responda con JSON en la ruta <code>/json</code> . Puedes hacerlo como de costumbre, con el método <code>app.get()</code> . Dentro del controlador de ruta use el método <code>res.json()</code> , pasando un objeto como argumento. Este método cierra el bucle de solicitud-respuesta, devolviendo los datos. Detrás de escena, convierte un objeto JavaScript válido en una cadena, luego establece los encabezados adecuados para indicar a su navegador que está sirviendo JSON y le devuelve los datos. Un objeto válido tiene la estructura habitual <code>{key: data}</code> . Los datos pueden ser un número, una cadena, un objeto anidado o una matriz. Los datos también pueden ser una variable o el resultado de una llamada de función; en cuyo caso se evaluará antes de convertirse en una cadena. <add>Servir el objeto <code>{"message": "Hello json"}</code> como respuesta en formato JSON, a las solicitudes GET a la ruta <code>/json</code> . Luego apunte su navegador a your-app-url / json, debería ver el mensaje en la pantalla. <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: 'El punto final <code>/json</code> debe servir el objeto 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/spanish/05-apis-and-microservices/basic-node-and-express/serve-static-assets.spanish.md <add>--- <add>id: 587d7fb0367417b2b2512bf0 <add>title: Serve Static Assets <add>localeTitle: Servir activos estáticos <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <add>Un servidor HTML generalmente tiene uno o más directorios que son accesibles por el usuario. Puede colocar allí los recursos estáticos que necesita su aplicación (hojas de estilo, scripts, imágenes). En Express puede implementar esta funcionalidad utilizando el middleware <code>express.static(path)</code> , donde el parámetro es la ruta absoluta de la carpeta que contiene los recursos. Si no sabes qué es un middleware, no te preocupes. Lo discutiremos más adelante en detalles. Básicamente, los middlewares son funciones que interceptan los manejadores de ruta, agregando algún tipo de información. Es necesario montar un middleware utilizando el método <code>app.use(path, middlewareFunction)</code> . El primer argumento de ruta es opcional. Si no lo pasa, el middleware se ejecutará para todas las solicitudes. <add>Monte el middleware <code>express.static()</code> para todas las solicitudes con <code>app.use()</code> . La ruta absoluta a la carpeta de activos es <code>__dirname + /public</code> . <add>Ahora su aplicación debería poder servir una hoja de estilo CSS. Desde fuera la carpeta pública aparecerá montada en el directorio raíz. Tu portada debería verse un poco mejor ahora! <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: Su aplicación debe servir archivos de activos del directorio <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/spanish/05-apis-and-microservices/basic-node-and-express/start-a-working-express-server.spanish.md <add>--- <add>id: 587d7fb0367417b2b2512bee <add>title: Start a Working Express Server <add>localeTitle: Iniciar un servidor Express de trabajo <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <add>En las dos primeras líneas del archivo myApp.js puede ver cómo es fácil crear un objeto de aplicación Express. Este objeto tiene varios métodos, y aprenderemos muchos de ellos en estos desafíos. Un método fundamental es <code>app.listen(port)</code> . Le dice a su servidor que escuche en un puerto dado, poniéndolo en estado de ejecución. Puedes verlo en la parte inferior del archivo. Se encuentra dentro de los comentarios porque, por razones de prueba, necesitamos que la aplicación se ejecute en segundo plano. Todo el código que desee agregar va entre estas dos partes fundamentales. Glitch almacena el número de puerto en la variable de entorno <code>process.env.PORT</code> . Su valor es de <code>3000</code> . <add>¡Vamos a servir nuestra primera cuerda! En Express, las rutas tienen la siguiente estructura: <code>app.METHOD(PATH, HANDLER)</code> . METHOD es un método http en minúsculas. PATH es una ruta relativa en el servidor (puede ser una cadena, o incluso una expresión regular). HANDLER es una función que llama expresamente cuando la ruta coincide. <add>manejadores toman la <code>function(req, res) {...}</code> formulario <code>function(req, res) {...}</code> , donde req es el objeto de solicitud, y res es el objeto de respuesta. Por ejemplo, el controlador <add><blockquote>function(req, res) {<br> res.send('Response String');<br>}</blockquote> <add>servirá la cadena 'Cadena de respuesta'. <add>Use el método <code>app.get()</code> para servir la cadena Hello Express, para obtener solicitudes que coincidan con la ruta / root. Asegúrese de que su código funcione mirando los registros, luego vea los resultados en su navegador y haga clic en el botón 'Mostrar en vivo' en la interfaz de usuario de 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: Su aplicación debe servir la cadena 'Hola 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/spanish/05-apis-and-microservices/basic-node-and-express/use-body-parser-to-parse-post-requests.spanish.md <add>--- <add>id: 587d7fb2367417b2b2512bf7 <add>title: Use body-parser to Parse POST Requests <add>localeTitle: Usar el analizador de cuerpo para analizar las solicitudes POST <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <add>Además de GET hay otro verbo http común, es POST. POST es el método predeterminado utilizado para enviar datos de clientes con formularios HTML. En la convención REST, POST se utiliza para enviar datos para crear nuevos elementos en la base de datos (un nuevo usuario o una nueva publicación de blog). No tenemos una base de datos en este proyecto, pero de todos modos vamos a aprender cómo manejar las solicitudes POST. <add>En este tipo de solicitudes, los datos no aparecen en la URL, están ocultos en el cuerpo de la solicitud. Esta es una parte de la solicitud HTML, también llamada carga útil. Dado que HTML está basado en texto, incluso si no ve los datos, no significa que sean secretos. El contenido sin procesar de una solicitud HTTP POST se muestra a continuación: <add><blockquote>POST /path/subpath HTTP/1.0<br>From: [email protected]<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> <add>Como puede ver, el cuerpo está codificado como la cadena de consulta. Este es el formato predeterminado utilizado por los formularios HTML. Con Ajax también podemos usar JSON para poder manejar datos que tienen una estructura más compleja. También hay otro tipo de codificación: multipart / form-data. Este se usa para subir archivos binarios. <add>En este ejercicio utilizaremos un cuerpo urlencodificado. <add>Para analizar los datos procedentes de solicitudes POST, debe instalar un paquete: el analizador de cuerpo. Este paquete le permite utilizar una serie de middleware, que puede decodificar datos en diferentes formatos. Vea los documentos <a href="https://github.com/expressjs/body-parser" target="_blank" >aquí</a> . <add>Instale el módulo body-parser en su package.json. Luego, solicítelo en la parte superior del archivo. Almacénelo en una variable llamada bodyParser. <add>El middleware para manejar los datos codificados en url es devuelto por <code>bodyParser.urlencoded({extended: false})</code> . <code>extended=false</code> es una opción de configuración que le dice al analizador que use la codificación clásica. Cuando se usa, los valores pueden ser solo cadenas o matrices. La versión extendida permite más flexibilidad de datos, pero es superada por JSON. Pase a <code>app.use()</code> la función devuelta por la llamada al método anterior. Como es habitual, el middleware debe montarse antes de todas las rutas que lo necesiten. <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: El middleware 'body-parser' debería ser montado <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/spanish/05-apis-and-microservices/basic-node-and-express/use-the-.env-file.spanish.md <add>--- <add>id: 587d7fb1367417b2b2512bf2 <add>title: Use the .env File <add>localeTitle: Usa el archivo .env <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <add>El archivo <code>.env</code> es un archivo oculto que se utiliza para pasar variables de entorno a su aplicación. Este archivo es secreto, nadie más que usted puede acceder a él, y se puede usar para almacenar datos que desea mantener privados u ocultos. Por ejemplo, puede almacenar claves de API de servicios externos o su URI de base de datos. También puedes usarlo para almacenar opciones de configuración. Al configurar las opciones de configuración, puede cambiar el comportamiento de su aplicación, sin la necesidad de volver a escribir algún código. <add>Se puede acceder a las variables de entorno desde la aplicación como <code>process.env.VAR_NAME</code> . El objeto <code>process.env</code> es un objeto de nodo global, y las variables se pasan como cadenas. Por convención, los nombres de las variables están en mayúsculas, con palabras separadas por un guión bajo. El <code>.env</code> es un archivo de shell, por lo que no necesita incluir nombres o valores entre comillas. También es importante tener en cuenta que no puede haber espacio alrededor del signo igual cuando está asignando valores a sus variables, por ejemplo, <code>VAR_NAME=value</code> . Por lo general, colocará cada definición de variable en una línea separada. <add>Agreguemos una variable de entorno como una opción de configuración. Almacene la variable <code>MESSAGE_STYLE=uppercase</code> en el archivo <code>.env</code> . Luego diga al controlador de ruta GET <code>/json</code> que creó en el último desafío para transformar el mensaje del objeto de respuesta en mayúsculas si <code>process.env.MESSAGE_STYLE</code> es igual a <code>uppercase</code> . El objeto de respuesta debe convertirse en <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: La respuesta del punto final <code>/json</code> debe cambiar de acuerdo con la variable de entorno <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/spanish/05-apis-and-microservices/managing-packages-with-npm/add-a-description-to-your-package.json.spanish.md <add>--- <add>id: 587d7fb3367417b2b2512bfc <add>title: Add a Description to Your package.json <add>localeTitle: Agregue una descripción a su package.json <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <add>La siguiente parte de un buen package.json es el campo de descripción, donde pertenece una descripción breve pero informativa sobre su proyecto. <add>Si algún día planea publicar un paquete en npm, recuerde que esta es la cadena que debe vender su idea al usuario cuando decide instalar el paquete o no. Sin embargo, este no es el único caso de uso para la descripción: es una excelente manera de resumir lo que hace un proyecto, es tan importante para sus proyectos Node.js normales para ayudar a otros desarrolladores, futuros mantenedores o incluso a su propio yo a entender el proyecto. con rapidez. <add>Independientemente de lo que planee para su proyecto, definitivamente se recomienda una descripción. Agreguemos algo similar a esto: <add><code>"description": "A project that does something awesome",</code> <add>Instrucciones <add>Agrega una descripción al package.json en tu proyecto de Glitch. <add>Recuerde usar comillas dobles para los nombres de campo (") y las comas (,) para separar los campos. <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 debería tener una clave de "descripción" válida <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/spanish/05-apis-and-microservices/managing-packages-with-npm/add-a-license-to-your-package.json.spanish.md <add>--- <add>id: 587d7fb4367417b2b2512bfe <add>title: Add a License to Your package.json <add>localeTitle: Agregue una licencia a su paquete.json <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <add>El campo de licencia es donde usted informa a los usuarios de su proyecto sobre lo que pueden hacer con él. <add>Algunas licencias comunes para proyectos de código abierto incluyen MIT y BSD. http://choosealicense.com es un gran recurso si desea obtener más información acerca de qué licencia podría adaptarse a su proyecto. <add>No se requiere información de licencia. Las leyes de derechos de autor en la mayoría de los países le otorgarán la propiedad de lo que crea de forma predeterminada. Sin embargo, siempre es una buena práctica indicar explícitamente lo que los usuarios pueden y no pueden hacer. <add>Ejemplo <add><code>"license": "MIT",</code> <add>Instrucciones <add>Rellene el campo de licencia en el paquete.json de su proyecto de Glitch cuando lo considere adecuado. <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 debería tener una clave de "licencia" válida <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/spanish/05-apis-and-microservices/managing-packages-with-npm/add-a-version-to-your-package.json.spanish.md <add>--- <add>id: 587d7fb4367417b2b2512bff <add>title: Add a Version to Your package.json <add>localeTitle: Agregue una versión a su package.json <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <add>La versión es junto con el nombre de uno de los campos requeridos en package.json. Este campo describe la versión actual de su proyecto. <add>Ejemplo <add><code>"version": "1.2",</code> <add>Instrucciones <add>Agregue una versión a package.json en su proyecto de 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: package.json debería tener una clave de "versión" válida <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/spanish/05-apis-and-microservices/managing-packages-with-npm/add-keywords-to-your-package.json.spanish.md <add>--- <add>id: 587d7fb4367417b2b2512bfd <add>title: Add Keywords to Your package.json <add>localeTitle: Añadir palabras clave a su package.json <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <add>El campo de palabras clave es donde puede describir su proyecto usando palabras clave relacionadas. <add>Ejemplo <add><code>"keywords": [ "descriptive", "related", "words" ],</code> <add>Como puede ver, este campo está estructurado como una matriz de cadenas entre comillas dobles. <add>Instrucciones <add>Agregue una serie de cadenas adecuadas al campo de palabras clave en el paquete.json de su proyecto de Glitch. <add>Una de las palabras clave debe ser 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 debe tener una clave de "palabras clave" válida <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: El campo "palabras clave" debería ser una matriz " <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: '"palabras clave" debe incluir "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/spanish/05-apis-and-microservices/managing-packages-with-npm/expand-your-project-with-external-packages-from-npm.spanish.md <add>--- <add>id: 587d7fb4367417b2b2512c00 <add>title: Expand Your Project with External Packages from npm <add>localeTitle: Expanda su proyecto con paquetes externos desde npm <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <add>Una de las razones más importantes para usar un administrador de paquetes es su poderosa administración de dependencias. En lugar de tener que asegurarse manualmente de que obtiene todas las dependencias cada vez que configura un proyecto en una computadora nueva, npm instala automáticamente todo por usted. Pero, ¿cómo puede npm saber exactamente lo que necesita su proyecto? Conoce la sección de dependencias de tu package.json. <add>En la sección de dependencias, los paquetes que requiere su proyecto se almacenan con el siguiente formato: <add><code>"dependencies": {</code> <add><code>"package-name": "version",</code> <add><code>"express": "4.14.0"</code> <add><code>}</code> <add>Instrucciones <add>Agregue la versión 2.14.0 del momento del paquete al campo de dependencias de su paquete.json <add>Moment es una biblioteca útil para trabajar con la hora y las fechas. <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: '"dependencias" debe incluir "momento"' <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: La versión "moment" debería ser "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/spanish/05-apis-and-microservices/managing-packages-with-npm/how-to-use-package.json-the-core-of-any-node.js-project-or-npm-package.spanish.md <add>--- <add>id: 587d7fb3367417b2b2512bfb <add>title: 'How to Use package.json, the Core of Any Node.js Project or npm Package' <add>localeTitle: 'Cómo usar package.json, el núcleo de cualquier proyecto Node.js o paquete npm' <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <add>El archivo package.json es el centro de cualquier proyecto Node.js o paquete npm. Almacena información sobre su proyecto al igual que la sección &lt;head&gt; en un documento HTML describe el contenido de una página web. El package.json consiste en un solo objeto JSON donde la información se almacena en "clave": pares de valores. Solo hay dos campos obligatorios en un paquete mínimo.json (nombre y versión), pero es una buena práctica proporcionar información adicional sobre su proyecto que pueda ser útil para futuros usuarios o mantenedores. <add>El campo de autor <add>Si va al proyecto de Glitch que configuró anteriormente y mira en el lado izquierdo de su pantalla, encontrará el árbol de archivos donde puede ver un resumen de los diversos archivos en su proyecto. Bajo la sección de back-end del árbol de archivos, encontrará package.json, el archivo que mejoraremos en los próximos dos desafíos. <add>Una de las piezas de información más comunes en este archivo es el campo de autor que especifica quién es el creador de un proyecto. Puede ser una cadena o un objeto con detalles de contacto. El objeto se recomienda para proyectos más grandes, pero en nuestro caso, una cadena simple como la del siguiente ejemplo servirá. <add><code>"author": "Jane Doe",</code> <add>Instrucciones <add>Agregue su nombre al campo de autor en el paquete.json de su proyecto de Glitch. <add>Recuerda que estás escribiendo JSON. <add>Todos los nombres de campo deben usar comillas dobles ("), por ejemplo," autor " <add>Todos los campos deben estar separados por una coma (,) <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 debería tener una clave de "autor" válida <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/spanish/05-apis-and-microservices/managing-packages-with-npm/manage-npm-dependencies-by-understanding-semantic-versioning.spanish.md <add>--- <add>id: 587d7fb5367417b2b2512c01 <add>title: Manage npm Dependencies By Understanding Semantic Versioning <add>localeTitle: Administre las dependencias de npm entendiendo el control de versiones semántico <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <add>Las versiones de los paquetes npm en la sección de dependencias de su package.json siguen lo que se denomina Semantic Versioning (SemVer), un estándar de la industria para las versiones de software que apunta a facilitar la administración de las dependencias. Las bibliotecas, marcos u otras herramientas publicadas en npm deben usar SemVer para comunicar claramente qué tipo de cambios pueden esperar los proyectos que dependen del paquete si se actualizan. <add>SemVer no tiene sentido en proyectos sin API públicas, por lo tanto, a menos que su proyecto sea similar a los ejemplos anteriores, use otro formato de versión. <add>Entonces, ¿por qué necesitas entender a SemVer? <add>Conocer SemVer puede ser útil cuando desarrolla software que utiliza dependencias externas (lo que casi siempre hace). Un día, su comprensión de estos números le evitará la introducción accidental de cambios de última hora en su proyecto sin comprender por qué las cosas que "funcionaron ayer" de repente no lo hacen. <add>Así es como funciona la Versión semántica según el sitio web oficial: <add>Dado un número de versión MAJOR.MINOR.PATCH, incremente la versión: <add>MAJOR cuando realice cambios en la API incompatibles, <add>versión MENOR cuando agregue la funcionalidad de una manera compatible con versiones anteriores y la versión <add>PATCH cuando realice correcciones de errores compatibles con versiones anteriores. <add>Esto significa que los PARCHES son correcciones de errores y los MENORES agregan nuevas funciones, pero ninguno de ellos rompe lo que funcionaba antes. Finalmente, MAJORs agrega cambios que no funcionarán con versiones anteriores. <add>Ejemplo <add>Un número de versión semántica: 1.3.8 <add>Instrucciones <add>En la sección de dependencias de su package.json, cambie la versión de momento para que coincida con MAJOR versión 2, MINOR versión 10 y PATCH versión 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: '"dependencias" debe incluir "momento"' <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: La versión "moment" debería ser "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/spanish/05-apis-and-microservices/managing-packages-with-npm/remove-a-package-from-your-dependencies.spanish.md <add>--- <add>id: 587d7fb5367417b2b2512c04 <add>title: Remove a Package from Your Dependencies <add>localeTitle: Retire un paquete de sus dependencias <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <add>Ahora ha probado algunas formas en que puede administrar las dependencias de su proyecto usando la sección de dependencias de package.json. Ha incluido paquetes externos al agregarlos al archivo e incluso le ha dicho a npm qué tipo de versiones desea utilizando caracteres especiales como la tilde (~) o el caret (^). <add>¿Pero qué sucede si desea eliminar un paquete externo que ya no necesita? Es posible que ya lo haya adivinado: simplemente elimine la "clave" correspondiente: par de valores para eso de sus dependencias. <add>Este mismo método se aplica a la eliminación de otros campos en su package.json y <add>Instrucciones <add>Elimine el momento del paquete de sus dependencias. <add>Asegúrese de tener la cantidad correcta de comas después de quitarla. <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: '"dependencias" no debe incluir "momento"' <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/spanish/05-apis-and-microservices/managing-packages-with-npm/use-the-caret-character-to-use-the-latest-minor-version-of-a-dependency.spanish.md <add>--- <add>id: 587d7fb5367417b2b2512c03 <add>title: Use the Caret-Character to Use the Latest Minor Version of a Dependency <add>localeTitle: Use el Caret-Character para usar la última versión menor de una dependencia <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <add>De manera similar a como aprendimos acerca de la tilde (~) en el último desafío, permite a npm instalar el último PATCH para una dependencia, el caret (^) también permite que npm instale actualizaciones futuras. La diferencia es que el compás permitirá tanto las actualizaciones MENORES como los PARCHES. <add>En este momento, su versión actual de moment debería ser ~ 2.10.2, que permite que npm se instale en la última versión 2.10.x. Si, en cambio, utilizáramos el caret (^) como nuestro prefijo de versión, a npm se le permitiría actualizar a cualquier versión 2.xx. <add>Ejemplo <add><code>"some-package-name": "^1.3.8" allows updates to any 1.xx version.</code> <add>Instrucciones <add>Use el carácter de intercalación (^) para prefijar la versión del momento en sus dependencias y permita que npm la actualice a cualquier nueva versión MINOR. <add>Tenga en cuenta que los números de versión en sí no deben cambiarse. <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: '"dependencias" debe incluir "momento"' <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: La versión "moment" debe coincidir con "^ 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/spanish/05-apis-and-microservices/managing-packages-with-npm/use-the-tilde-character-to-always-use-the-latest-patch-version-of-a-dependency.spanish.md <add>--- <add>id: 587d7fb5367417b2b2512c02 <add>title: Use the Tilde-Character to Always Use the Latest Patch Version of a Dependency <add>localeTitle: Use el carácter de tilde para usar siempre la última versión de parche de una dependencia <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <add>En el último desafío, le dijimos a npm que solo incluya una versión específica de un paquete. Es una forma útil de congelar sus dependencias si necesita asegurarse de que las diferentes partes de su proyecto sean compatibles entre sí. Pero en la mayoría de los casos de uso, no querrá perderse la corrección de errores, ya que a menudo incluyen importantes parches de seguridad y (con suerte) no rompen las cosas al hacerlo. <add>Para permitir que una dependencia npm se actualice a la última versión de PATCH, puede prefijar la versión de la dependencia con el carácter de tilde (~). En package.json, nuestra regla actual sobre cómo npm puede actualizarse en el momento es usar solo una versión específica (2.10.2), pero queremos permitir la última versión 2.10.x. <add>Ejemplo <add><code>"some-package-name": "~1.3.8" allows updates to any 1.3.x version.</code> <add>Instrucciones <add>Use el carácter de tilde (~) para prefijar la versión de momento en sus dependencias y permita que npm la actualice a cualquier nueva versión de PATCH. <add>Tenga en cuenta que los números de versión en sí no deben cambiarse. <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: '"dependencias" debe incluir "momento"' <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: La versión "moment" debe coincidir con "~ 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/spanish/05-apis-and-microservices/mongodb-and-mongoose/chain-search-query-helpers-to-narrow-search-results.spanish.md <add>--- <add>id: 587d7fb9367417b2b2512c12 <add>title: Chain Search Query Helpers to Narrow Search Results <add>localeTitle: Encadene a los ayudantes de consulta para reducir los resultados de búsqueda <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <add>Si no pasa la devolución de llamada como último argumento a Model.find () (o a los otros métodos de búsqueda), la consulta no se ejecuta. Puede almacenar la consulta en una variable para su uso posterior. Este tipo de objeto le permite crear una consulta utilizando la sintaxis de encadenamiento. La búsqueda real de db se ejecuta cuando finalmente encadena el método .exec (). Pase su devolución de llamada a este último método. Hay muchos ayudantes de consulta, aquí usaremos los más "famosos". <add>Encuentra gente que le gusta "burrito". Ordénelos por nombre, limite los resultados a dos documentos y oculte su edad. Encadene .find (), .sort (), .limit (), .select (), y luego .exec (). Pase la devolución de llamada done (err, data) a 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: Los ayudantes de encadenamiento de consultas deben tener éxito <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/spanish/05-apis-and-microservices/mongodb-and-mongoose/create-a-model.spanish.md <add>--- <add>id: 587d7fb6367417b2b2512c07 <add>title: Create a Model <add>localeTitle: Crear un modelo <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <add>Primero que todo necesitamos un esquema. Cada esquema se asigna a una colección de MongoDB. Define la forma de los documentos dentro de esa colección. <add>esquemas son bloques de construcción para los modelos. Se pueden anidar para crear modelos complejos, pero en este caso mantendremos las cosas simples. <add>Un modelo le permite crear instancias de sus objetos, llamados documentos. <add>Crea una persona que tenga este prototipo: <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> <add>Utilice los tipos de esquema básicos de mangosta. Si lo desea, también puede agregar <add>campos más, use validadores simples como requeridos o únicos, <add>y configure los valores predeterminados. Ver los <a href='http://mongoosejs.com/docs/guide.html'>documentos de mangosta</a> . <add>[C] RUD Parte I - CREAR <add>Nota: Glitch es un servidor real, y en servidores reales las interacciones con el db ocurren en las funciones del controlador. Estas funciones se ejecutan cuando ocurre algún evento (por ejemplo, alguien llega a un punto final en su API). Seguiremos el mismo enfoque en estos ejercicios. La función done () es una devolución de llamada que nos dice que podemos continuar después de completar una operación asíncrona, como insertar, buscar, actualizar o eliminar. Sigue la convención de Nodo y debe llamarse como hecho (nulo, datos) en caso de éxito o hecho (error) en caso de error <add>Advertencia: al interactuar con servicios remotos, pueden producirse errores. <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: La creación de una instancia a partir de un esquema de mangosta debería tener éxito <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/spanish/05-apis-and-microservices/mongodb-and-mongoose/create-and-save-a-record-of-a-model.spanish.md <add>--- <add>id: 587d7fb6367417b2b2512c09 <add>title: Create and Save a Record of a Model <add>localeTitle: Crear y guardar un registro de un modelo <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <add>Crea una instancia de documento utilizando el constructor de persona que creaste antes. Pase al constructor un objeto que tenga los campos nombre, edad y favoriteFoods. Sus tipos deben ser conformes a los del esquema de persona. Luego llame al método document.save () en la instancia del documento devuelto. Pasar a él una devolución de llamada utilizando la convención de nodo. Este es un patrón común, todos los siguientes métodos de CRUD toman una función de devolución de llamada como el último argumento. <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: Crear y guardar un elemento db debería tener éxito <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/spanish/05-apis-and-microservices/mongodb-and-mongoose/create-many-records-with-model.create.spanish.md <add>--- <add>id: 587d7fb7367417b2b2512c0a <add>title: Create Many Records with model.create() <add>localeTitle: Crear muchos registros con model.create () <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <add>A veces necesita crear muchas instancias de sus modelos, por ejemplo, al sembrar una base de datos con datos iniciales. Model.create () toma una matriz de objetos como [{nombre: 'John', ...}, {...}, ...] como el primer argumento, y los guarda todos en la db. Cree muchas personas con Model.create (), usando la función argumentoOfPeople. <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: La creación de muchos elementos db a la vez debe tener éxito <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/spanish/05-apis-and-microservices/mongodb-and-mongoose/delete-many-documents-with-model.remove.spanish.md <add>--- <add>id: 587d7fb8367417b2b2512c11 <add>title: Delete Many Documents with model.remove() <add>localeTitle: Eliminar muchos documentos con model.remove () <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <add>Model.remove () es útil para eliminar todos los documentos que coincidan con los criterios dados. Elimine a todas las personas cuyo nombre es "Mary", usando Model.remove (). Pasarlo a un documento de consulta con el conjunto de campos "nombre" y, por supuesto, una devolución de llamada. <add>Nota: Model.remove () no devuelve el documento eliminado, sino un objeto JSON que contiene el resultado de la operación y el número de elementos afectados. No olvide pasarlo a la devolución de llamada done (), ya que lo usamos en las pruebas. <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: Eliminar muchos elementos a la vez debería tener éxito <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/spanish/05-apis-and-microservices/mongodb-and-mongoose/delete-one-document-using-model.findbyidandremove.spanish.md <add>--- <add>id: 587d7fb8367417b2b2512c10 <add>title: Delete One Document Using model.findByIdAndRemove <add>localeTitle: Eliminar un documento utilizando model.findByIdAndRemove <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <add>Eliminar una persona por su _id. Debe usar uno de los métodos findByIdAndRemove () o findOneAndRemove (). Son como los métodos de actualización anteriores. Pasan el documento eliminado a la cb. Como de costumbre, use la función argumento personId como clave de búsqueda. <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: Eliminar un elemento debe tener éxito <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/spanish/05-apis-and-microservices/mongodb-and-mongoose/install-and-set-up-mongoose.spanish.md <add>--- <add>id: 587d7fb6367417b2b2512c06 <add>title: Install and Set Up Mongoose <add>localeTitle: Instalar y configurar la mangosta <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <add>Agregue mongodb y mongoose al package.json del proyecto. Entonces requiere mangosta. Almacene su URI de la base de datos de mLab en el archivo .env privado como MONGO_URI. Conéctese a la base de datos utilizando 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: La dependencia "mongodb" debería estar en 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: 'La dependencia de "mongoose" debe estar en 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: '"mangosta" debe estar conectada a una base de datos' <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/spanish/05-apis-and-microservices/mongodb-and-mongoose/perform-classic-updates-by-running-find-edit-then-save.spanish.md <add>--- <add>id: 587d7fb8367417b2b2512c0e <add>title: 'Perform Classic Updates by Running Find, Edit, then Save' <add>localeTitle: 'Realizar actualizaciones clásicas ejecutando Buscar, Editar y luego Guardar' <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <add>En los viejos tiempos, esto era lo que tenía que hacer si quería editar un documento y poder usarlo de alguna manera, por ejemplo, enviándolo de vuelta en una respuesta del servidor. Mongoose tiene un método de actualización dedicado: Model.update (). Está vinculado al controlador mongo de bajo nivel. Puede editar de forma masiva muchos documentos que cumplen ciertos criterios, pero no envía el documento actualizado, solo un mensaje de "estado". Además, dificulta las validaciones de modelos, ya que solo llama directamente al controlador mongo. <add>Encuentre una persona por _id (use cualquiera de los métodos anteriores) con el parámetro personId como clave de búsqueda. Agregue “hamburguesa” a la lista de sus alimentos favoritos (puede usar Array.push ()). Luego, dentro de la devolución de llamada de búsqueda, guarde () la Persona actualizada. <add>[*] Sugerencia: Esto puede ser complicado si en tu Esquema declaraste favoriteFoods como una matriz, sin especificar el tipo (es decir, [Cadena]). En ese caso, el valor predeterminado de los alimentos predeterminados es de tipo mixto, y tiene que marcarlo manualmente como editado utilizando document.markModified ('campo editado'). (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: Buscar-editar-actualizar un elemento debería tener éxito <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/spanish/05-apis-and-microservices/mongodb-and-mongoose/perform-new-updates-on-a-document-using-model.findoneandupdate.spanish.md <add>--- <add>id: 587d7fb8367417b2b2512c0f <add>title: Perform New Updates on a Document Using model.findOneAndUpdate() <add>localeTitle: Realizar nuevas actualizaciones en un documento utilizando model.findOneAndUpdate () <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <add>Las versiones recientes de mongoose tienen métodos para simplificar la actualización de documentos. Algunas características más avanzadas (es decir, ganchos pre / post, validación) se comportan de manera diferente con este enfoque, por lo que el método Classic sigue siendo útil en muchas situaciones. findByIdAndUpdate () se puede usar cuando se busca por Id. <add>Encuentre a una persona por su nombre y establezca su edad en 20. Use el parámetro de función personName como clave de búsqueda. <add>Sugerencia: queremos que devuelva el documento actualizado. Para hacerlo, debe pasar el documento de opciones {nuevo: verdadero} como el tercer argumento para findOneAndUpdate (). Por defecto, estos métodos devuelven el objeto no modificado. <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 un elemento debe tener éxito <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/spanish/05-apis-and-microservices/mongodb-and-mongoose/use-model.find-to-search-your-database.spanish.md <add>--- <add>id: 587d7fb7367417b2b2512c0b <add>title: Use model.find() to Search Your Database <add>localeTitle: Utilice model.find () para buscar su base de datos <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <add>Encuentre a todas las personas que tienen un nombre dado, usando Model.find () -&gt; [Persona] <add>En su uso más simple, Model.find () acepta un documento de consulta (un objeto JSON) como primer argumento, luego una devolución de llamada. Devuelve una serie de coincidencias. Es compatible con una amplia gama de opciones de búsqueda. Compruébalo en los documentos. Utilice la función argumento personName como clave de búsqueda. <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: Encontrar todos los elementos correspondientes a un criterio debe tener éxito <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/spanish/05-apis-and-microservices/mongodb-and-mongoose/use-model.findbyid-to-search-your-database-by-id.spanish.md <add>--- <add>id: 587d7fb7367417b2b2512c0d <add>title: Use model.findById() to Search Your Database By _id <add>localeTitle: Use model.findById () para buscar en su base de datos por _id <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <add>Al guardar un documento, mongodb agrega automáticamente el campo _id y lo configura en una clave alfanumérica única. La búsqueda por _id es una operación extremadamente frecuente, por lo que la mangosta proporciona un método dedicado para ello. Encuentre la (solo !!) persona que tiene un _id dado, usando Model.findById () -&gt; Person. Utilice el argumento de función personId como clave de búsqueda. <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: Encontrar un artículo por ID debe tener éxito <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/spanish/05-apis-and-microservices/mongodb-and-mongoose/use-model.findone-to-return-a-single-matching-document-from-your-database.spanish.md <add>--- <add>id: 587d7fb7367417b2b2512c0c <add>title: Use model.findOne() to Return a Single Matching Document from Your Database <add>localeTitle: Use model.findOne () para devolver un solo documento coincidente de su base de datos <add>challengeType: 2 <add>--- <add> <add>## Description <add><section id='description'> <add>Model.findOne () se comporta como .find (), pero solo devuelve un documento (no una matriz), incluso si hay varios elementos. Es especialmente útil cuando busca por propiedades que ha declarado como únicas. Encuentre solo una persona que tenga cierta comida en sus favoritos, usando Model.findOne () -&gt; Person. Utilice la función de argumento de alimentos como clave de búsqueda. <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: Encontrar un elemento debe tener éxito <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
Java
Java
replace spaces with tabs
66bc214a79da1bcae850fc80fae7af2b1b912822
<ide><path>org.springframework.web/src/main/java/org/springframework/http/server/ServletServerHttpRequest.java <ide> public HttpHeaders getHeaders() { <ide> this.servletRequest.getCharacterEncoding() != null) { <ide> MediaType oldContentType = this.headers.getContentType(); <ide> Charset charSet = Charset.forName(this.servletRequest.getCharacterEncoding()); <del> Map<String, String> params = new HashMap<String, String>(oldContentType.getParameters()); <del> params.put("charset", charSet.toString()); <del> MediaType newContentType = new MediaType(oldContentType.getType(), oldContentType.getSubtype(), params); <add> Map<String, String> params = new HashMap<String, String>(oldContentType.getParameters()); <add> params.put("charset", charSet.toString()); <add> MediaType newContentType = new MediaType(oldContentType.getType(), oldContentType.getSubtype(), params); <ide> this.headers.setContentType(newContentType); <ide> } <ide> if (this.headers.getContentLength() == -1 && this.servletRequest.getContentLength() != -1) {
1
Text
Text
fix tiny typo
7367bd53a908474f14f0f44f3744f2fcb1f4111c
<ide><path>docs/tutorial/quickstart.md <ide> Notice that we're using hyperlinked relations in this case, with `HyperlinkedMod <ide> <ide> ## Views <ide> <del>Right, we'd better right some views then. Open `quickstart/views.py` and get typing. <add>Right, we'd better write some views then. Open `quickstart/views.py` and get typing. <ide> <ide> from django.contrib.auth.models import User, Group <ide> from rest_framework import generics
1
Ruby
Ruby
allow nested namespaces in routing
04823ff48fbde3ecf7849a1e1a3d3bcc4cc71aa8
<ide><path>actionpack/lib/action_controller/resources.rb <ide> def resource(*entities, &block) <ide> # It'll also create admin_product_tags_url pointing to "admin/products/#{product_id}/tags", which will look for <ide> # Admin::TagsController. <ide> def namespace(name, options = {}, &block) <del> with_options({ :path_prefix => name, :name_prefix => "#{name}_", :namespace => "#{name}/" }.merge(options), &block) <add> if options[:namespace] <add> with_options({:path_prefix => "#{options.delete(:path_prefix)}/#{name}", :name_prefix => "#{options.delete(:name_prefix)}#{name}_", :namespace => "#{options.delete(:namespace)}#{name}/" }.merge(options), &block) <add> else <add> with_options({ :path_prefix => name.to_s, :name_prefix => "#{name}_", :namespace => "#{name}/" }.merge(options), &block) <add> end <ide> end <ide> <ide> <ide><path>actionpack/test/controller/resources_test.rb <ide> class AdminController < ResourcesController; end <ide> <ide> module Backoffice <ide> class ProductsController < ResourcesController; end <add> <add> module Admin <add> class ProductsController < ResourcesController; end <add> end <ide> end <ide> <ide> class ResourcesTest < Test::Unit::TestCase <ide> def test_resources_in_namespace <ide> end <ide> end <ide> <add> def test_resources_in_nested_namespace <add> with_routing do |set| <add> set.draw do |map| <add> map.namespace :backoffice do |backoffice| <add> backoffice.namespace :admin do |admin| <add> admin.resources :products <add> end <add> end <add> end <add> <add> assert_simply_restful_for :products, :controller => "backoffice/admin/products", :name_prefix => 'backoffice_admin_', :path_prefix => 'backoffice/admin/' <add> end <add> end <add> <ide> def test_resources_using_namespace <ide> with_routing do |set| <ide> set.draw do |map|
2
Python
Python
get process stats
24d6dd71ce297eb583a63569047c40cd10f79dea
<ide><path>glances/glances.py <ide> def add(self, item_state, item_type, item_value, proc_list = []): <ide> # Add Top process sort depending on alert type <ide> if (item_type.startswith("MEM")): <ide> # MEM <del> sortby = 'mem_percent' <add> sortby = 'memory_percent' <ide> else: <ide> # CPU* and LOAD <ide> sortby = 'cpu_percent' <ide> def __init__(self): <ide> else: <ide> self.host['os_version'] = "" <ide> <add> def __get_process_statsNEW__(self, proc): <add> """ <add> Get process (proc) statistics <add> !!! Waiting PATCH for PsUtil <add> !!! http://code.google.com/p/psutil/issues/detail?id=329 <add> !!! Performance ? <add> """ <add> procstat = proc.as_dict(['memory_info', 'cpu_percent', 'memory_percent', <add> 'io_counters', 'pid', 'username', 'nice', <add> 'cpu_times', 'name', 'status', 'cmdline']) <add> <add> procstat['status'] = str(procstat['status'])[:1].upper() <add> procstat['cmdline'] = " ".join(procstat['cmdline']) <add> <add> return procstat <add> <add> <add> def __get_process_stats__(self, proc): <add> """ <add> Get process (proc) statistics <add> """ <add> procstat = {} <add> <add> procstat['memory_info'] = proc.get_memory_info() <add> <add> if psutil_get_cpu_percent_tag: <add> procstat['cpu_percent'] = \ <add> proc.get_cpu_percent(interval=0) <add> <add> procstat['memory_percent'] = proc.get_memory_percent() <add> <add> if psutil_get_io_counter_tag: <add> procstat['io_counters'] = proc.get_io_counters() <add> <add> procstat['pid'] = proc.pid <add> procstat['username'] = proc.username <add> <add> try: <add> # Deprecated in PsUtil 0.5.0 <add> procstat['nice'] = proc.nice <add> except: <add> # Specific for PsUtil 0.5.0+ <add> procstat['nice'] = proc.get_nice() <add> <add> procstat['status'] = str(proc.status)[:1].upper() <add> procstat['cpu_times'] = proc.get_cpu_times() <add> procstat['name'] = proc.name <add> procstat['cmdline'] = " ".join(proc.cmdline) <add> <add> return procstat <add> <ide> <ide> def __update__(self): <ide> """ <ide> def __update__(self): <ide> self.processcount['total'] += 1 <ide> # Per process stats <ide> try: <del> procstat = {} <del> procstat['proc_size'] = proc.get_memory_info().vms <del> procstat['proc_resident'] = proc.get_memory_info().rss <del> <del> if psutil_get_cpu_percent_tag: <del> procstat['cpu_percent'] = \ <del> proc.get_cpu_percent(interval=0) <del> <del> procstat['mem_percent'] = proc.get_memory_percent() <del> <del> if psutil_get_io_counter_tag: <del> self.proc_io = proc.get_io_counters() <del> procstat['read_bytes'] = self.proc_io.read_bytes <del> procstat['write_bytes'] = self.proc_io.write_bytes <del> #~ try: <del> #~ self.procstatbkp <del> #~ except Exception: <del> #~ self.procstatbkp = [] <del> #~ try: <del> #~ self.procstatbkp[str(proc.pid)] <del> #~ except Exception: <del> #~ self.procstatbkp[str(proc.pid)] = [] <del> #~ try: <del> #~ self.procstatbkp[str(proc.pid)]['read_bytes_old'] <del> #~ self.procstatbkp[str(proc.pid)]['write_bytes_old'] <del> #~ except Exception: <del> #~ self.procstatbkp[str(proc.pid)]['read_bytes_old'] = procstat['read_bytes'] <del> #~ self.procstatbkp[str(proc.pid)]['write_bytes_old'] = procstat['write_bytes'] <del> #~ procstat['read_bytes_ps'] = procstat['read_bytes'] - self.procstatbkp[str(proc.pid)]['read_bytes_old'] <del> #~ procstat['write_bytes_ps'] = procstat['write_bytes'] - self.procstatbkp[str(proc.pid)]['write_bytes_old'] <del> #~ self.procstatbkp[str(proc.pid)]['read_bytes_old'] = procstat['read_bytes'] <del> #~ self.procstatbkp[str(proc.pid)]['write_bytes_old'] = procstat['write_bytes'] <del> <del> procstat['pid'] = proc.pid <del> procstat['uid'] = proc.username <del> <del> try: <del> # Deprecated in PsUtil 0.5.0 <del> procstat['nice'] = proc.nice <del> except: <del> # Specific for PsUtil 0.5.0+ <del> procstat['nice'] = proc.get_nice() <del> <del> procstat['status'] = str(proc.status)[:1].upper() <del> procstat['proc_time'] = proc.get_cpu_times() <del> procstat['proc_name'] = proc.name <del> procstat['proc_cmdline'] = " ".join(proc.cmdline) <del> self.process.append(procstat) <add> self.process.append(self.__get_process_stats__(proc)) <ide> except Exception: <ide> pass <del> <add> <ide> # If it is the first grab then empty process list <ide> if self.process_first_grab: <ide> self.process = [] <ide> def getProcessList(self, sortedby='auto'): <ide> if psutil_get_cpu_percent_tag: <ide> sortedby = 'cpu_percent' <ide> else: <del> sortedby = 'mem_percent' <add> sortedby = 'memory_percent' <ide> # Auto selection <ide> # If global MEM > 70% sort by MEM usage <ide> # else sort by CPU usage <ide> def getProcessList(self, sortedby='auto'): <ide> pass <ide> else: <ide> if memtotal > limits.getSTDWarning(): <del> sortedby = 'mem_percent' <del> elif sortedby == 'proc_name': <add> sortedby = 'memory_percent' <add> elif sortedby == 'name': <ide> sortedReverse = False <ide> <ide> return sorted(self.process, key=lambda process: process[sortedby], <ide> def __catchKey(self): <ide> self.log_tag = not self.log_tag <ide> elif self.pressedkey == 109: <ide> # 'm' > Sort processes by MEM usage <del> self.setProcessSortedBy('mem_percent') <add> self.setProcessSortedBy('memory_percent') <ide> elif self.pressedkey == 110 and psutil_network_io_tag: <ide> # 'n' > Show/hide network stats <ide> self.network_tag = not self.network_tag <ide> elif self.pressedkey == 112: <ide> # 'p' > Sort processes by name <del> self.setProcessSortedBy('proc_name') <add> self.setProcessSortedBy('name') <ide> <ide> # Return the key code <ide> return self.pressedkey <ide> def displayLog(self, offset_y=0): <ide> # Add top process <ide> if (log[logcount][9] != []): <ide> logmsg += " - Top process: {0}".format( <del> log[logcount][9][0]['proc_name']) <add> log[logcount][9][0]['name']) <ide> # Display the log <ide> self.term_window.addnstr(self.log_y + 1 + logcount, <ide> self.log_x, logmsg, len(logmsg)) <ide> def displayProcess(self, processcount, processlist, log_count=0): <ide> self.term_window.addnstr( <ide> self.process_y + 2, process_x + 21, <ide> _("MEM%"), 5, curses.A_UNDERLINE <del> if self.getProcessSortedBy() == 'mem_percent' else 0) <add> if self.getProcessSortedBy() == 'memory_percent' else 0) <ide> process_name_x = 28 <ide> # If screen space (X) is available then: <ide> # PID <ide> def displayProcess(self, processcount, processlist, log_count=0): <ide> self.term_window.addnstr( <ide> self.process_y + 2, process_x + process_name_x, <ide> _("NAME"), 12, curses.A_UNDERLINE <del> if self.getProcessSortedBy() == 'proc_name' else 0) <add> if self.getProcessSortedBy() == 'name' else 0) <ide> <ide> # If there is no data to display... <ide> if not processlist: <ide> def displayProcess(self, processcount, processlist, log_count=0): <ide> len(processlist)) <ide> for processes in range(0, proc_num): <ide> # VMS <del> process_size = processlist[processes]['proc_size'] <add> process_size = processlist[processes]['memory_info'].vms <ide> self.term_window.addnstr( <ide> self.process_y + 3 + processes, process_x, <ide> self.__autoUnit(process_size), 5) <ide> # RSS <del> process_resident = processlist[processes]['proc_resident'] <add> process_resident = processlist[processes]['memory_info'].rss <ide> self.term_window.addnstr( <ide> self.process_y + 3 + processes, process_x + 7, <ide> self.__autoUnit(process_resident), 5) <ide> def displayProcess(self, processcount, processlist, log_count=0): <ide> self.term_window.addnstr( <ide> self.process_y + 3 + processes, process_x, "N/A", 8) <ide> # MEM% <del> mem_percent = processlist[processes]['mem_percent'] <add> memory_percent = processlist[processes]['memory_percent'] <ide> self.term_window.addnstr( <ide> self.process_y + 3 + processes, process_x + 21, <del> "{0:.1f}".format(mem_percent), 5, <del> self.__getProcessColor(mem_percent)) <add> "{0:.1f}".format(memory_percent), 5, <add> self.__getProcessColor(memory_percent)) <ide> # If screen space (X) is available then: <ide> # PID <ide> if tag_pid: <ide> def displayProcess(self, processcount, processlist, log_count=0): <ide> str(pid), 6) <ide> # UID <ide> if tag_uid: <del> uid = processlist[processes]['uid'] <add> uid = processlist[processes]['username'] <ide> self.term_window.addnstr( <ide> self.process_y + 3 + processes, process_x + 35, <ide> str(uid), 8) <ide> def displayProcess(self, processcount, processlist, log_count=0): <ide> str(status), 1) <ide> # TIME+ <ide> if tag_proc_time: <del> process_time = processlist[processes]['proc_time'] <add> process_time = processlist[processes]['cpu_times'] <ide> dtime = timedelta(seconds=sum(process_time)) <ide> dtime = "{0}:{1}.{2}".format( <ide> str(dtime.seconds // 60 % 60).zfill(2), <ide> def displayProcess(self, processcount, processlist, log_count=0): <ide> if tag_io: <ide> # Processes are only refresh every 2 refresh_time <ide> #~ elapsed_time = max(1, self.__refresh_time) * 2 <del> io_read = processlist[processes]['read_bytes'] <add> io_read = processlist[processes]['io_counters'].read_bytes <ide> self.term_window.addnstr( <ide> self.process_y + 3 + processes, process_x + 62, <ide> self.__autoUnit(io_read), 8) <del> io_write = processlist[processes]['write_bytes'] <add> io_write = processlist[processes]['io_counters'].write_bytes <ide> self.term_window.addnstr( <ide> self.process_y + 3 + processes, process_x + 72, <ide> self.__autoUnit(io_write), 8) <ide> <ide> # display process command line <ide> max_process_name = screen_x - process_x - process_name_x <del> process_name = processlist[processes]['proc_name'] <del> process_cmdline = processlist[processes]['proc_cmdline'] <add> process_name = processlist[processes]['name'] <add> process_cmdline = processlist[processes]['cmdline'] <ide> if (len(process_cmdline) > max_process_name or <ide> len(process_cmdline) == 0): <ide> command = process_name
1