content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Text
Text
add changes for 1.6.10
77f26bddf79d812a8ac347f591896f197c8a3f08
<ide><path>CHANGELOG.md <add><a name="1.6.10"></a> <add># 1.6.10 crystalline-persuasion (2018-04-12) <add> <add>## Bug Fixes <add>- **$compile:** <add> - correctly handle `null`/`undefined` href `attrs.$set()` <add> ([f04e04](https://github.com/angular/angular.js/commit/f04e04e0e63e0d30c29718abd5cae634901793b2), <add> [#16520](https://github.com/angular/angular.js/issues/16520)) <add> - throw error in `$onChanges` immediately <add> ([b7d1e0fbd](https://github.com/angular/angular.js/commit/983e27b628fd1eab653e2b3966d90a270f27cc93), <add> [#15578](https://github.com/angular/angular.js/issues/15578), <add> [#16492](https://github.com/angular/angular.js/issues/16492)) <add>- **input:** <add> - allow overriding timezone for date input types <add> ([4355de](https://github.com/angular/angular.js/commit/4355dee21d26667bb7f6f21bf75c081351315033), <add> [#16181](https://github.com/angular/angular.js/issues/16181), <add> [#13382](https://github.com/angular/angular.js/issues/13382), <add> [#16336](https://github.com/angular/angular.js/issues/16336)) <add> - take timezone into account when validating minimum and maximum in date types <add> ([2f0ac6](https://github.com/angular/angular.js/commit/2f0ac696cb09aec3e291bb8c9c8a1092cbe3a061), <add> [#16342](https://github.com/angular/angular.js/issues/16342), <add> [#16390](https://github.com/angular/angular.js/issues/16390)) <add> - fix composition mode in IE for Korean input <add> ([9a1b7c](https://github.com/angular/angular.js/commit/9a1b7c9fa135d1dae3f9b4ccf48f081675796e92), <add> [#6656](https://github.com/angular/angular.js/issues/6656), <add> [#16273](https://github.com/angular/angular.js/issues/16273)) <add>- **jqLite:** use XHTML-compliant HTML as input for jqLite <add> ([a0c55a](https://github.com/angular/angular.js/commit/a0c55af9858075ab268a88dd7a4464788a46f4b7), <add> [#6917](https://github.com/angular/angular.js/issues/6917), <add> [#16518](https://github.com/angular/angular.js/issues/16518)) <add>- **minErr:** update url to https <add> ([52e466](https://github.com/angular/angular.js/commit/52e46683bfcc0ce0dc9a3d2ee42b389508423799)) <add>- **$http:** set correct xhrStatus in response when using 'timeout' <add> ([1faf7e](https://github.com/angular/angular.js/commit/1faf7ec30d55bba107b18efbcf0ef07732c55b91)) <add>- **browserTrigger:** support CompositionEvent <add> ([c33fd1](https://github.com/angular/angular.js/commit/c33fd1325417fdc6d7d6abc90cd935130653b149)) <add> <add> <add>## New Features <add>- **$http:** support sending XSRF token to whitelisted origins <add> ([bc7757](https://github.com/angular/angular.js/commit/bc775759c88b2221c2bb71d2335bc233c93f43b0), <add> [#7862](https://github.com/angular/angular.js/issues/7862)) <add>- **minErr:** strip error url from error parameters <add> ([980b69](https://github.com/angular/angular.js/commit/980b69dcae73dd8a3d0b9d91b63fa7711cd0ba36)) <add>- **$sanitize:** support enhancing elements/attributes white-lists <add> ([ee8e05](https://github.com/angular/angular.js/commit/ee8e05cfafe086188fc318ed4115fb56ba335112), <add> [#5900](https://github.com/angular/angular.js/issues/5900), <add> [#16326](https://github.com/angular/angular.js/issues/16326)) <add>- **$rootScope:** allow suspending and resuming watchers on scope <add> ([efb822c58](https://github.com/angular/angular.js/commit/41d5c90f170cc054b0f8f88220c22ef1ef6cc0a6), <add> [#16308](https://github.com/angular/angular.js/issues/5301)) <add> <ide> <a name="1.6.9"></a> <ide> # 1.6.9 fiery-basilisk (2018-02-02) <ide>
1
Javascript
Javascript
add tests to highlight
7dbeded1db214814040d987df8b40fc95e8badd6
<ide><path>packages/ember/tests/routing/substates_test.js <ide> import { RSVP } from '@ember/-internals/runtime'; <ide> import { Route } from '@ember/-internals/routing'; <add>import Controller from '@ember/controller'; <add> <ide> import { moduleFor, ApplicationTestCase, runTask } from 'internal-test-helpers'; <ide> <ide> let counter; <ide> moduleFor( <ide> }); <ide> } <ide> <add> ['@test Enter loading route with correct query parameters'](assert) { <add> let deferred = RSVP.defer(); <add> <add> this.router.map(function () { <add> this.route('dummy'); <add> }); <add> <add> this.add( <add> 'route:dummy', <add> Route.extend({ <add> model() { <add> step(assert, 1, 'DummyRoute#model'); <add> return deferred.promise; <add> }, <add> }) <add> ); <add> <add> this.add( <add> 'controller:application', <add> class extends Controller { <add> queryParams = ['qux']; <add> <add> qux = 'initial'; <add> } <add> ); <add> <add> this.add( <add> 'route:loading', <add> Route.extend({ <add> setupController() { <add> step(assert, 2, 'LoadingRoute#setupController'); <add> }, <add> }) <add> ); <add> this.addTemplate('dummy', 'DUMMY'); <add> <add> return this.visit('/?qux=updated').then(() => { <add> assert.equal( <add> this.getController('application').qux, <add> 'updated', <add> 'the application controller has the correct qp value' <add> ); <add> <add> let promise = this.visit('/dummy?qux=updated').then(() => { <add> let text = this.$('#app').text(); <add> <add> assert.equal(text, 'DUMMY', `dummy template has been rendered`); <add> assert.equal( <add> this.getController('application').qux, <add> 'updated', <add> 'the application controller has the correct qp value' <add> ); <add> }); <add> <add> assert.equal(this.currentPath, 'loading', `loading state entered`); <add> assert.equal( <add> this.currentURL, <add> '/dummy?qux=updated', <add> `during loading url reflect the correct state` <add> ); <add> assert.equal( <add> this.getController('application').qux, <add> 'updated', <add> 'the application controller has the correct qp value' <add> ); <add> <add> deferred.resolve(); <add> <add> return promise; <add> }); <add> } <add> <add> ['@test Enter child-loading route with correct query parameters'](assert) { <add> assert.expect(9); <add> let deferred = RSVP.defer(); <add> <add> this.router.map(function () { <add> this.route('parent', function () { <add> this.route('child'); <add> }); <add> }); <add> <add> this.add( <add> 'route:parent.child', <add> Route.extend({ <add> model() { <add> step(assert, 1, 'ChildRoute#model'); <add> return deferred.promise; <add> }, <add> }) <add> ); <add> <add> this.add( <add> 'controller:parent', <add> class extends Controller { <add> queryParams = ['qux']; <add> <add> qux = 'initial'; <add> } <add> ); <add> <add> this.add( <add> 'route:parent.child_loading', <add> Route.extend({ <add> setupController() { <add> step(assert, 2, 'ChildLoadingRoute#setupController'); <add> }, <add> }) <add> ); <add> this.addTemplate('parent', 'PARENT {{outlet}}'); <add> <add> this.addTemplate('parent.child', 'CHILD'); <add> <add> return this.visit('/parent?qux=updated').then(() => { <add> assert.equal( <add> this.getController('parent').qux, <add> 'updated', <add> 'in the parent route, the parent controller has the correct qp value' <add> ); <add> <add> let promise = this.visit('/parent/child?qux=updated').then(() => { <add> let text = this.$('#app').text(); <add> <add> assert.equal(text, 'PARENT CHILD', `child template has been rendered`); <add> assert.equal( <add> this.getController('parent').qux, <add> 'updated', <add> 'after entered in the parent.child route, the parent controller has the correct qp value' <add> ); <add> }); <add> <add> assert.equal(this.currentPath, 'parent.child_loading', `child loading state entered`); <add> assert.equal( <add> this.currentURL, <add> '/parent/child?qux=updated', <add> `during child loading, url reflect the correct state` <add> ); <add> assert.equal( <add> this.getController('parent').qux, <add> 'updated', <add> 'in the child_loading route, the parent controller has the correct qp value' <add> ); <add> <add> deferred.resolve(); <add> <add> return promise; <add> }); <add> } <add> <ide> ['@test Slow promises returned from ApplicationRoute#model enter ApplicationLoadingRoute if present']( <ide> assert <ide> ) {
1
Javascript
Javascript
implement adapter to abstract date/time features
8a3eb8592892965eb6e99750d74ef8000a409976
<ide><path>src/adapters/adapter.moment.js <add>// TODO v3 - make this adapter external (chartjs-adapter-moment) <add> <add>'use strict'; <add> <add>var moment = require('moment'); <add>var adapter = require('../core/core.adapters')._date; <add>var helpers = require('../helpers/helpers.core'); <add> <add>var FORMATS = { <add> millisecond: 'h:mm:ss.SSS a', <add> second: 'h:mm:ss a', <add> minute: 'h:mm a', <add> hour: 'hA', <add> day: 'MMM D', <add> week: 'll', <add> month: 'MMM YYYY', <add> quarter: '[Q]Q - YYYY', <add> year: 'YYYY' <add>}; <add> <add>var PRESETS = { <add> full: 'MMM D, YYYY h:mm:ss.SSS a', <add> time: 'MMM D, YYYY h:mm:ss a', <add> date: 'MMM D, YYYY' <add>}; <add> <add>helpers.merge(adapter, moment ? { <add> _id: 'moment', // DEBUG ONLY <add> <add> formats: function() { <add> return FORMATS; <add> }, <add> <add> presets: function() { <add> return PRESETS; <add> }, <add> <add> parse: function(value, format) { <add> if (typeof value === 'string' && typeof format === 'string') { <add> value = moment(value, format); <add> } else if (!(value instanceof moment)) { <add> value = moment(value); <add> } <add> return value.isValid() ? +value : null; <add> }, <add> <add> format: function(time, format) { <add> return moment(time).format(format); <add> }, <add> <add> add: function(time, amount, unit) { <add> return +moment(time).add(amount, unit); <add> }, <add> <add> diff: function(max, min, unit) { <add> return moment.duration(moment(max).diff(moment(min))).as(unit); <add> }, <add> <add> startOf: function(time, unit, weekday) { <add> time = moment(time); <add> if (unit === 'isoWeek') { <add> return +time.isoWeekday(weekday); <add> } <add> return +time.startOf(unit); <add> }, <add> <add> endOf: function(time, unit) { <add> return +moment(time).endOf(unit); <add> }, <add> <add> // DEPRECATIONS <add> <add> /** <add> * Provided for backward compatibility with scale.getValueForPixel(). <add> * @deprecated since version 2.8.0 <add> * @todo remove at version 3 <add> * @private <add> */ <add> _create: function(time) { <add> return moment(time); <add> }, <add>} : {}); <ide><path>src/adapters/index.js <add>'use strict'; <add> <add>// ----------------------------------------------------------------------------- <add>// IMPORTANT: do NOT submit new adapters to this repository, instead <add>// create an external library named `chartjs-adapter-{lib-name}` <add>// ----------------------------------------------------------------------------- <add> <add>// Built-in moment adapter that we need to keep for backward compatibility <add>// https://github.com/chartjs/Chart.js/issues/5542 <add>require('./adapter.moment'); <ide><path>src/chart.js <ide> Chart.helpers = require('./helpers/index'); <ide> // @todo dispatch these helpers into appropriated helpers/helpers.* file and write unit tests! <ide> require('./core/core.helpers')(Chart); <ide> <add>Chart._adapters = require('./core/core.adapters'); <ide> Chart.Animation = require('./core/core.animation'); <ide> Chart.animationService = require('./core/core.animations'); <ide> Chart.controllers = require('./controllers/index'); <ide> Chart.helpers.each(scales, function(scale, type) { <ide> Chart.scaleService.registerScaleType(type, scale, scale._defaults); <ide> }); <ide> <add>// Load to register built-in adapters (as side effects) <add>require('./adapters'); <add> <ide> // Loading built-in plugins <ide> var plugins = require('./plugins'); <ide> for (var k in plugins) { <ide><path>src/core/core.adapters.js <add>/** <add> * @namespace Chart._adapters <add> * @since 2.8.0 <add> * @private <add> */ <add> <add>'use strict'; <add> <add>function abstract() { <add> throw new Error( <add> 'This method is not implemented: either no adapter can ' + <add> 'be found or an incomplete integration was provided.' <add> ); <add>} <add> <add>/** <add> * Date adapter (current used by the time scale) <add> * @namespace Chart._adapters._date <add> * @memberof Chart._adapters <add> * @private <add> */ <add> <add>/** <add> * Currently supported unit string values. <add> * @typedef {('millisecond'|'second'|'minute'|'hour'|'day'|'week'|'month'|'quarter'|'year')} <add> * @memberof Chart._adapters._date <add> * @name Unit <add> */ <add> <add>/** @lends Chart._adapters._date */ <add>module.exports._date = { <add> /** <add> * Returns a map of time formats for the supported units. <add> * @returns {{string: string}} <add> */ <add> formats: abstract, <add> <add> /** <add> * Returns a map of date/time formats for the following presets: <add> * 'full': date + time + millisecond <add> * 'time': date + time <add> * 'date': date <add> * @returns {{string: string}} <add> */ <add> presets: abstract, <add> <add> /** <add> * Parses the given `value` and return the associated timestamp. <add> * @param {any} value - the value to parse (usually comes from the data) <add> * @param {string} [format] - the expected data format <add> * @returns {(number|null)} <add> * @function <add> */ <add> parse: abstract, <add> <add> /** <add> * Returns the formatted date in the specified `format` for a given `timestamp`. <add> * @param {number} timestamp - the timestamp to format <add> * @param {string} format - the date/time token <add> * @return {string} <add> * @function <add> */ <add> format: abstract, <add> <add> /** <add> * Adds the specified `amount` of `unit` to the given `timestamp`. <add> * @param {number} timestamp - the input timestamp <add> * @param {number} amount - the amount to add <add> * @param {Unit} unit - the unit as string <add> * @return {number} <add> * @function <add> */ <add> add: abstract, <add> <add> /** <add> * Returns the number of `unit` between the given timestamps. <add> * @param {number} max - the input timestamp (reference) <add> * @param {number} min - the timestamp to substract <add> * @param {Unit} unit - the unit as string <add> * @return {number} <add> * @function <add> */ <add> diff: abstract, <add> <add> /** <add> * Returns start of `unit` for the given `timestamp`. <add> * @param {number} timestamp - the input timestamp <add> * @param {Unit} unit - the unit as string <add> * @param {number} [weekday] - the ISO day of the week with 1 being Monday <add> * and 7 being Sunday (only needed if param *unit* is `isoWeek`). <add> * @function <add> */ <add> startOf: abstract, <add> <add> /** <add> * Returns end of `unit` for the given `timestamp`. <add> * @param {number} timestamp - the input timestamp <add> * @param {Unit} unit - the unit as string <add> * @function <add> */ <add> endOf: abstract, <add> <add> // DEPRECATIONS <add> <add> /** <add> * Provided for backward compatibility for scale.getValueForPixel(), <add> * this method should be overridden only by the moment adapter. <add> * @deprecated since version 2.8.0 <add> * @todo remove at version 3 <add> * @private <add> */ <add> _create: function(value) { <add> return value; <add> } <add>}; <ide><path>src/scales/scale.time.js <ide> /* global window: false */ <ide> 'use strict'; <ide> <del>var moment = require('moment'); <add>var adapter = require('../core/core.adapters')._date; <ide> var defaults = require('../core/core.defaults'); <ide> var helpers = require('../helpers/index'); <ide> var Scale = require('../core/core.scale'); <ide> function interpolate(table, skey, sval, tkey) { <ide> return prev[tkey] + offset; <ide> } <ide> <del>/** <del> * Convert the given value to a moment object using the given time options. <del> * @see https://momentjs.com/docs/#/parsing/ <del> */ <del>function momentify(value, options) { <add>function toTimestamp(input, options) { <ide> var parser = options.parser; <del> var format = options.parser || options.format; <add> var format = parser || options.format; <add> var value = input; <ide> <ide> if (typeof parser === 'function') { <del> return parser(value); <add> value = parser(value); <ide> } <ide> <del> if (typeof value === 'string' && typeof format === 'string') { <del> return moment(value, format); <add> // Only parse if its not a timestamp already <add> if (!helpers.isFinite(value)) { <add> value = typeof format === 'string' <add> ? adapter.parse(value, format) <add> : adapter.parse(value); <ide> } <ide> <del> if (!(value instanceof moment)) { <del> value = moment(value); <add> if (value !== null) { <add> return +value; <ide> } <ide> <del> if (value.isValid()) { <del> return value; <del> } <add> // Labels are in an incompatible format and no `parser` has been provided. <add> // The user might still use the deprecated `format` option for parsing. <add> if (!parser && typeof format === 'function') { <add> value = format(input); <ide> <del> // Labels are in an incompatible moment format and no `parser` has been provided. <del> // The user might still use the deprecated `format` option to convert his inputs. <del> if (typeof format === 'function') { <del> return format(value); <add> // `format` could return something else than a timestamp, if so, parse it <add> if (!helpers.isFinite(value)) { <add> value = adapter.parse(value); <add> } <ide> } <ide> <ide> return value; <ide> function parse(input, scale) { <ide> } <ide> <ide> var options = scale.options.time; <del> var value = momentify(scale.getRightValue(input), options); <del> if (!value.isValid()) { <del> return null; <add> var value = toTimestamp(scale.getRightValue(input), options); <add> if (value === null) { <add> return value; <ide> } <ide> <ide> if (options.round) { <del> value.startOf(options.round); <add> value = +adapter.startOf(value, options.round); <ide> } <ide> <del> return value.valueOf(); <add> return value; <ide> } <ide> <ide> /** <ide> function determineUnitForAutoTicks(minUnit, min, max, capacity) { <ide> * Figures out what unit to format a set of ticks with <ide> */ <ide> function determineUnitForFormatting(ticks, minUnit, min, max) { <del> var duration = moment.duration(moment(max).diff(moment(min))); <ide> var ilen = UNITS.length; <ide> var i, unit; <ide> <ide> for (i = ilen - 1; i >= UNITS.indexOf(minUnit); i--) { <ide> unit = UNITS[i]; <del> if (INTERVALS[unit].common && duration.as(unit) >= ticks.length) { <add> if (INTERVALS[unit].common && adapter.diff(max, min, unit) >= ticks.length) { <ide> return unit; <ide> } <ide> } <ide> function generate(min, max, capacity, options) { <ide> var weekday = minor === 'week' ? timeOpts.isoWeekday : false; <ide> var majorTicksEnabled = options.ticks.major.enabled; <ide> var interval = INTERVALS[minor]; <del> var first = moment(min); <del> var last = moment(max); <add> var first = min; <add> var last = max; <ide> var ticks = []; <ide> var time; <ide> <ide> function generate(min, max, capacity, options) { <ide> <ide> // For 'week' unit, handle the first day of week option <ide> if (weekday) { <del> first = first.isoWeekday(weekday); <del> last = last.isoWeekday(weekday); <add> first = +adapter.startOf(first, 'isoWeek', weekday); <add> last = +adapter.startOf(last, 'isoWeek', weekday); <ide> } <ide> <ide> // Align first/last ticks on unit <del> first = first.startOf(weekday ? 'day' : minor); <del> last = last.startOf(weekday ? 'day' : minor); <add> first = +adapter.startOf(first, weekday ? 'day' : minor); <add> last = +adapter.startOf(last, weekday ? 'day' : minor); <ide> <ide> // Make sure that the last tick include max <ide> if (last < max) { <del> last.add(1, minor); <add> last = +adapter.add(last, 1, minor); <ide> } <ide> <del> time = moment(first); <add> time = first; <ide> <ide> if (majorTicksEnabled && major && !weekday && !timeOpts.round) { <ide> // Align the first tick on the previous `minor` unit aligned on the `major` unit: <ide> // we first aligned time on the previous `major` unit then add the number of full <ide> // stepSize there is between first and the previous major time. <del> time.startOf(major); <del> time.add(~~((first - time) / (interval.size * stepSize)) * stepSize, minor); <add> time = +adapter.startOf(time, major); <add> time = +adapter.add(time, ~~((first - time) / (interval.size * stepSize)) * stepSize, minor); <ide> } <ide> <del> for (; time < last; time.add(stepSize, minor)) { <add> for (; time < last; time = +adapter.add(time, stepSize, minor)) { <ide> ticks.push(+time); <ide> } <ide> <ide> function ticksFromTimestamps(values, majorUnit) { <ide> <ide> for (i = 0, ilen = values.length; i < ilen; ++i) { <ide> value = values[i]; <del> major = majorUnit ? value === +moment(value).startOf(majorUnit) : false; <add> major = majorUnit ? value === +adapter.startOf(value, majorUnit) : false; <ide> <ide> ticks.push({ <ide> value: value, <ide> function ticksFromTimestamps(values, majorUnit) { <ide> return ticks; <ide> } <ide> <del>function determineLabelFormat(data, timeOpts) { <del> var i, momentDate, hasTime; <del> var ilen = data.length; <add>/** <add> * Return the time format for the label with the most parts (milliseconds, second, etc.) <add> */ <add>function determineLabelFormat(timestamps) { <add> var presets = adapter.presets(); <add> var ilen = timestamps.length; <add> var i, ts, hasTime; <ide> <del> // find the label with the most parts (milliseconds, minutes, etc.) <del> // format all labels with the same level of detail as the most specific label <ide> for (i = 0; i < ilen; i++) { <del> momentDate = momentify(data[i], timeOpts); <del> if (momentDate.millisecond() !== 0) { <del> return 'MMM D, YYYY h:mm:ss.SSS a'; <add> ts = timestamps[i]; <add> if (ts % INTERVALS.second.size !== 0) { <add> return presets.full; <ide> } <del> if (momentDate.second() !== 0 || momentDate.minute() !== 0 || momentDate.hour() !== 0) { <add> if (!hasTime && adapter.startOf(ts, 'day') !== ts) { <ide> hasTime = true; <ide> } <ide> } <ide> if (hasTime) { <del> return 'MMM D, YYYY h:mm:ss a'; <add> return presets.time; <ide> } <del> return 'MMM D, YYYY'; <add> return presets.date; <ide> } <ide> <ide> var defaultConfig = { <ide> var defaultConfig = { <ide> displayFormat: false, // DEPRECATED <ide> isoWeekday: false, // override week start day - see https://momentjs.com/docs/#/get-set/iso-weekday/ <ide> minUnit: 'millisecond', <del> <del> // defaults to unit's corresponding unitFormat below or override using pattern string from https://momentjs.com/docs/#/displaying/format/ <del> displayFormats: { <del> millisecond: 'h:mm:ss.SSS a', // 11:20:01.123 AM, <del> second: 'h:mm:ss a', // 11:20:01 AM <del> minute: 'h:mm a', // 11:20 AM <del> hour: 'hA', // 5PM <del> day: 'MMM D', // Sep 4 <del> week: 'll', // Week 46, or maybe "[W]WW - YYYY" ? <del> month: 'MMM YYYY', // Sept 2015 <del> quarter: '[Q]Q - YYYY', // Q3 <del> year: 'YYYY' // 2015 <del> }, <add> displayFormats: {} <ide> }, <ide> ticks: { <ide> autoSkip: false, <ide> var defaultConfig = { <ide> <ide> module.exports = Scale.extend({ <ide> initialize: function() { <del> if (!moment) { <del> throw new Error('Chart.js - Moment.js could not be found! You must include it before Chart.js to use the time scale. Download at https://momentjs.com'); <del> } <del> <ide> this.mergeTicksOptions(); <del> <ide> Scale.prototype.initialize.call(this); <ide> }, <ide> <ide> update: function() { <ide> var me = this; <ide> var options = me.options; <add> var time = options.time || (options.time = {}); <ide> <ide> // DEPRECATIONS: output a message only one time per update <del> if (options.time && options.time.format) { <add> if (time.format) { <ide> console.warn('options.time.format is deprecated and replaced by options.time.parser.'); <ide> } <ide> <add> // Backward compatibility: before introducing adapter, `displayFormats` was <add> // supposed to contain *all* unit/string pairs but this can't be resolved <add> // when loading the scale (adapters are loaded afterward), so let's populate <add> // missing formats on update <add> helpers.mergeIf(time.displayFormats, adapter.formats()); <add> <ide> return Scale.prototype.update.apply(me, arguments); <ide> }, <ide> <ide> module.exports = Scale.extend({ <ide> max = parse(timeOpts.max, me) || max; <ide> <ide> // In case there is no valid min/max, set limits based on unit time option <del> min = min === MAX_INTEGER ? +moment().startOf(unit) : min; <del> max = max === MIN_INTEGER ? +moment().endOf(unit) + 1 : max; <add> min = min === MAX_INTEGER ? +adapter.startOf(+new Date(), unit) : min; <add> max = max === MIN_INTEGER ? +adapter.endOf(+new Date(), unit) + 1 : max; <ide> <ide> // Make sure that max is strictly higher than min (required by the lookup table) <ide> me.min = Math.min(min, max); <ide> module.exports = Scale.extend({ <ide> me._majorUnit = determineMajorUnit(me._unit); <ide> me._table = buildLookupTable(me._timestamps.data, min, max, options.distribution); <ide> me._offsets = computeOffsets(me._table, ticks, min, max, options); <del> me._labelFormat = determineLabelFormat(me._timestamps.data, timeOpts); <add> me._labelFormat = determineLabelFormat(me._timestamps.data); <ide> <ide> if (options.ticks.reverse) { <ide> ticks.reverse(); <ide> module.exports = Scale.extend({ <ide> label = me.getRightValue(value); <ide> } <ide> if (timeOpts.tooltipFormat) { <del> return momentify(label, timeOpts).format(timeOpts.tooltipFormat); <add> return adapter.format(toTimestamp(label, timeOpts), timeOpts.tooltipFormat); <ide> } <ide> if (typeof label === 'string') { <ide> return label; <ide> } <ide> <del> return momentify(label, timeOpts).format(me._labelFormat); <add> return adapter.format(toTimestamp(label, timeOpts), me._labelFormat); <ide> }, <ide> <ide> /** <ide> * Function to format an individual tick mark <ide> * @private <ide> */ <del> tickFormatFunction: function(tick, index, ticks, formatOverride) { <add> tickFormatFunction: function(time, index, ticks, format) { <ide> var me = this; <ide> var options = me.options; <del> var time = tick.valueOf(); <ide> var formats = options.time.displayFormats; <ide> var minorFormat = formats[me._unit]; <ide> var majorUnit = me._majorUnit; <ide> var majorFormat = formats[majorUnit]; <del> var majorTime = tick.clone().startOf(majorUnit).valueOf(); <add> var majorTime = +adapter.startOf(time, majorUnit); <ide> var majorTickOpts = options.ticks.major; <ide> var major = majorTickOpts.enabled && majorUnit && majorFormat && time === majorTime; <del> var label = tick.format(formatOverride ? formatOverride : major ? majorFormat : minorFormat); <add> var label = adapter.format(time, format ? format : major ? majorFormat : minorFormat); <ide> var tickOpts = major ? majorTickOpts : options.ticks.minor; <ide> var formatter = valueOrDefault(tickOpts.callback, tickOpts.userCallback); <ide> <ide> module.exports = Scale.extend({ <ide> var i, ilen; <ide> <ide> for (i = 0, ilen = ticks.length; i < ilen; ++i) { <del> labels.push(this.tickFormatFunction(moment(ticks[i].value), i, ticks)); <add> labels.push(this.tickFormatFunction(ticks[i].value, i, ticks)); <ide> } <ide> <ide> return labels; <ide> module.exports = Scale.extend({ <ide> var pos = (size ? (pixel - start) / size : 0) * (me._offsets.start + 1 + me._offsets.start) - me._offsets.end; <ide> var time = interpolate(me._table, 'pos', pos, 'time'); <ide> <del> return moment(time); <add> // DEPRECATION, we should return time directly <add> return adapter._create(time); <ide> }, <ide> <ide> /** <ide> module.exports = Scale.extend({ <ide> getLabelCapacity: function(exampleTime) { <ide> var me = this; <ide> <del> var formatOverride = me.options.time.displayFormats.millisecond; // Pick the longest format for guestimation <del> <del> var exampleLabel = me.tickFormatFunction(moment(exampleTime), 0, [], formatOverride); <add> // pick the longest format (milliseconds) for guestimation <add> var format = me.options.time.displayFormats.millisecond; <add> var exampleLabel = me.tickFormatFunction(exampleTime, 0, [], format); <ide> var tickLabelWidth = me.getLabelWidth(exampleLabel); <ide> var innerWidth = me.isHorizontal() ? me.width : me.height; <del> <ide> var capacity = Math.floor(innerWidth / tickLabelWidth); <add> <ide> return capacity > 0 ? capacity : 1; <ide> } <ide> }); <ide><path>test/specs/scale.time.tests.js <ide> describe('Time scale tests', function() { <ide> isoWeekday: false, <ide> displayFormat: false, <ide> minUnit: 'millisecond', <del> displayFormats: { <del> millisecond: 'h:mm:ss.SSS a', // 11:20:01.123 AM <del> second: 'h:mm:ss a', // 11:20:01 AM <del> minute: 'h:mm a', // 11:20 AM <del> hour: 'hA', // 5PM <del> day: 'MMM D', // Sep 4 <del> week: 'll', // Week 46, or maybe "[W]WW - YYYY" ? <del> month: 'MMM YYYY', // Sept 2015 <del> quarter: '[Q]Q - YYYY', // Q3 <del> year: 'YYYY' // 2015 <del> }, <add> displayFormats: {} <ide> } <ide> }); <ide> <ide> describe('Time scale tests', function() { <ide> }); <ide> }); <ide> }); <add> <add> describe('Deprecations', function() { <add> describe('options.time.displayFormats', function() { <add> it('should generate defaults from adapter presets', function() { <add> var chart = window.acquireChart({ <add> type: 'line', <add> data: {}, <add> options: { <add> scales: { <add> xAxes: [{ <add> id: 'x', <add> type: 'time' <add> }] <add> } <add> } <add> }); <add> <add> // NOTE: built-in adapter uses moment <add> var expected = { <add> millisecond: 'h:mm:ss.SSS a', <add> second: 'h:mm:ss a', <add> minute: 'h:mm a', <add> hour: 'hA', <add> day: 'MMM D', <add> week: 'll', <add> month: 'MMM YYYY', <add> quarter: '[Q]Q - YYYY', <add> year: 'YYYY' <add> }; <add> <add> expect(chart.scales.x.options.time.displayFormats).toEqual(expected); <add> expect(chart.options.scales.xAxes[0].time.displayFormats).toEqual(expected); <add> }); <add> <add> it('should merge user formats with adapter presets', function() { <add> var chart = window.acquireChart({ <add> type: 'line', <add> data: {}, <add> options: { <add> scales: { <add> xAxes: [{ <add> id: 'x', <add> type: 'time', <add> time: { <add> displayFormats: { <add> millisecond: 'foo', <add> hour: 'bar', <add> month: 'bla' <add> } <add> } <add> }] <add> } <add> } <add> }); <add> <add> // NOTE: built-in adapter uses moment <add> var expected = { <add> millisecond: 'foo', <add> second: 'h:mm:ss a', <add> minute: 'h:mm a', <add> hour: 'bar', <add> day: 'MMM D', <add> week: 'll', <add> month: 'bla', <add> quarter: '[Q]Q - YYYY', <add> year: 'YYYY' <add> }; <add> <add> expect(chart.scales.x.options.time.displayFormats).toEqual(expected); <add> expect(chart.options.scales.xAxes[0].time.displayFormats).toEqual(expected); <add> }); <add> }); <add> }); <ide> });
6
Javascript
Javascript
remove usememo from apollo examples
ba246446ef8069e160c3a9a010549e89e222dd1e
<ide><path>examples/api-routes-apollo-server-and-client/apollo/client.js <del>import React, { useMemo } from 'react' <add>import React from 'react' <ide> import Head from 'next/head' <ide> import { ApolloProvider } from '@apollo/react-hooks' <ide> import { ApolloClient } from 'apollo-client' <ide> let apolloClient = null <ide> */ <ide> export function withApollo (PageComponent, { ssr = true } = {}) { <ide> const WithApollo = ({ apolloClient, apolloState, ...pageProps }) => { <del> const client = useMemo( <del> () => apolloClient || initApolloClient(apolloState), <del> [] <del> ) <add> const client = apolloClient || initApolloClient(apolloState) <ide> return ( <ide> <ApolloProvider client={client}> <ide> <PageComponent {...pageProps} /> <ide><path>examples/with-apollo-auth/lib/apollo.js <del>import React, { useMemo } from 'react' <add>import React from 'react' <ide> import PropTypes from 'prop-types' <ide> import cookie from 'cookie' <ide> import Head from 'next/head' <ide> import fetch from 'isomorphic-unfetch' <ide> */ <ide> export function withApollo (PageComponent, { ssr = true } = {}) { <ide> const WithApollo = ({ apolloClient, apolloState, ...pageProps }) => { <del> const client = useMemo(() => { <del> // We pass in the apolloClient directly when using getDataFromTree <del> if (apolloClient) { <del> return apolloClient <del> } <del> <del> // Otherwise initClient using apolloState <del> return initApolloClient(apolloState, { getToken }) <del> }, []) <add> const client = apolloClient || initApolloClient(apolloState, { getToken }) <ide> return ( <ide> <ApolloProvider client={client}> <ide> <PageComponent {...pageProps} /> <ide><path>examples/with-apollo/lib/apollo.js <del>import React, { useMemo } from 'react' <add>import React from 'react' <ide> import Head from 'next/head' <ide> import { ApolloProvider } from '@apollo/react-hooks' <ide> import { ApolloClient } from 'apollo-client' <ide> let apolloClient = null <ide> */ <ide> export function withApollo (PageComponent, { ssr = true } = {}) { <ide> const WithApollo = ({ apolloClient, apolloState, ...pageProps }) => { <del> const client = useMemo( <del> () => apolloClient || initApolloClient(apolloState), <del> [] <del> ) <add> const client = apolloClient || initApolloClient(apolloState) <ide> return ( <ide> <ApolloProvider client={client}> <ide> <PageComponent {...pageProps} />
3
Python
Python
fix error in reduceat documentation
a258e3cfbd28fb48722c5c83999f6910ef8d827a
<ide><path>numpy/add_newdocs.py <ide> def luf(lamdaexpr, *args, **kwargs): <ide> ``ufunc.reduce(a[indices[i]:indices[i+1]])``, which becomes the i-th <ide> generalized "row" parallel to `axis` in the final result (i.e., in a <ide> 2-D array, for example, if `axis = 0`, it becomes the i-th row, but if <del> `axis = 1`, it becomes the i-th column). There are two exceptions to this: <add> `axis = 1`, it becomes the i-th column). There are three exceptions to this: <ide> <del> * when ``i = len(indices) - 1`` (so for the last index), <del> ``indices[i+1] = a.shape[axis]``. <del> * if ``indices[i] >= indices[i + 1]``, the i-th generalized "row" is <del> simply ``a[indices[i]]``. <add> * when ``i = len(indices) - 1`` (so for the last index), <add> ``indices[i+1] = a.shape[axis]``. <add> * if ``indices[i] >= indices[i + 1]``, the i-th generalized "row" is <add> simply ``a[indices[i]]``. <add> * if ``indices[i] >= len(a)`` or ``indices[i] < 0``, an error is raised. <ide> <ide> The shape of the output depends on the size of `indices`, and may be <ide> larger than `a` (this happens if ``len(indices) > a.shape[axis]``).
1
PHP
PHP
add some tests for fifo naming conventions
f8da97b1ea5c27ad5ed12e5b4c93dfd7329930ac
<ide><path>tests/Queue/QueueSqsQueueTest.php <ide> public function testGetQueueProperlyResolvesUrlWithPrefix() <ide> $this->assertEquals($queueUrl, $queue->getQueue('test')); <ide> } <ide> <add> public function testGetQueueProperlyResolvesFifoUrlWithPrefix() <add> { <add> $this->queueName = 'emails.fifo'; <add> $this->queueUrl = $this->prefix . $this->queueName; <add> $queue = new SqsQueue($this->sqs, $this->queueName, $this->prefix); <add> $this->assertEquals($this->queueUrl, $queue->getQueue(null)); <add> $queueUrl = $this->baseUrl . '/' . $this->account . '/test.fifo'; <add> $this->assertEquals($queueUrl, $queue->getQueue('test.fifo')); <add> } <add> <ide> public function testGetQueueProperlyResolvesUrlWithoutPrefix() <ide> { <ide> $queue = new SqsQueue($this->sqs, $this->queueUrl); <ide> public function testGetQueueProperlyResolvesUrlWithSuffix() <ide> $this->assertEquals($queueUrl, $queue->getQueue('test')); <ide> } <ide> <add> public function testGetQueueProperlyResolvesFifoUrlWithSuffix() <add> { <add> $this->queueName = 'emails.fifo'; <add> $queue = new SqsQueue($this->sqs, $this->queueName, $this->prefix, $suffix = '-staging'); <add> $this->assertEquals("{$this->prefix}emails-staging.fifo", $queue->getQueue(null)); <add> $queueUrl = $this->baseUrl . '/' . $this->account . '/test' . $suffix . '.fifo'; <add> $this->assertEquals($queueUrl, $queue->getQueue('test.fifo')); <add> } <add> <ide> public function testGetQueueEnsuresTheQueueIsOnlySuffixedOnce() <ide> { <ide> $queue = new SqsQueue($this->sqs, "{$this->queueName}-staging", $this->prefix, $suffix = '-staging'); <ide> $this->assertEquals($this->queueUrl.$suffix, $queue->getQueue(null)); <ide> $queueUrl = $this->baseUrl.'/'.$this->account.'/test'.$suffix; <ide> $this->assertEquals($queueUrl, $queue->getQueue('test-staging')); <ide> } <add> <add> public function testGetFifoQueueEnsuresTheQueueIsOnlySuffixedOnce() <add> { <add> $queue = new SqsQueue($this->sqs, "{$this->queueName}-staging.fifo", $this->prefix, $suffix = '-staging'); <add> $this->assertEquals("{$this->prefix}{$this->queueName}{$suffix}.fifo", $queue->getQueue(null)); <add> $queueUrl = $this->baseUrl . '/' . $this->account . '/test' . $suffix . '.fifo'; <add> $this->assertEquals($queueUrl, $queue->getQueue('test-staging.fifo')); <add> } <ide> }
1
Javascript
Javascript
enable stable concurrent apis flag for 16.7 alpha
275e76e83bc2be5dc0be9185ff747f383969289a
<ide><path>packages/react-dom/src/client/ReactDOM.js <ide> import getComponentName from 'shared/getComponentName'; <ide> import invariant from 'shared/invariant'; <ide> import lowPriorityWarning from 'shared/lowPriorityWarning'; <ide> import warningWithoutStack from 'shared/warningWithoutStack'; <add>import {enableStableConcurrentModeAPIs} from 'shared/ReactFeatureFlags'; <ide> <ide> import * as ReactDOMComponentTree from './ReactDOMComponentTree'; <ide> import {restoreControlledState} from './ReactDOMComponent'; <ide> type RootOptions = { <ide> hydrate?: boolean, <ide> }; <ide> <del>ReactDOM.unstable_createRoot = function createRoot( <del> container: DOMContainer, <del> options?: RootOptions, <del>): ReactRoot { <add>function createRoot(container: DOMContainer, options?: RootOptions): ReactRoot { <ide> invariant( <ide> isValidContainer(container), <ide> 'unstable_createRoot(...): Target container is not a DOM element.', <ide> ); <ide> const hydrate = options != null && options.hydrate === true; <ide> return new ReactRoot(container, true, hydrate); <del>}; <add>} <add> <add>if (enableStableConcurrentModeAPIs) { <add> ReactDOM.createRoot = createRoot; <add>} else { <add> ReactDOM.unstable_createRoot = createRoot; <add>} <ide> <ide> const foundDevTools = DOMRenderer.injectIntoDevTools({ <ide> findFiberByHostInstance: ReactDOMComponentTree.getClosestInstanceFromNode, <ide><path>packages/react/src/React.js <ide> import { <ide> cloneElementWithValidation, <ide> } from './ReactElementValidator'; <ide> import ReactSharedInternals from './ReactSharedInternals'; <add>import {enableStableConcurrentModeAPIs} from 'shared/ReactFeatureFlags'; <ide> <ide> const React = { <ide> Children: { <ide> const React = { <ide> <ide> Fragment: REACT_FRAGMENT_TYPE, <ide> StrictMode: REACT_STRICT_MODE_TYPE, <del> unstable_ConcurrentMode: REACT_CONCURRENT_MODE_TYPE, <ide> Suspense: REACT_SUSPENSE_TYPE, <del> unstable_Profiler: REACT_PROFILER_TYPE, <ide> <ide> createElement: __DEV__ ? createElementWithValidation : createElement, <ide> cloneElement: __DEV__ ? cloneElementWithValidation : cloneElement, <ide> const React = { <ide> __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: ReactSharedInternals, <ide> }; <ide> <add>if (enableStableConcurrentModeAPIs) { <add> React.ConcurrentMode = REACT_CONCURRENT_MODE_TYPE; <add> React.Profiler = REACT_PROFILER_TYPE; <add>} else { <add> React.unstable_ConcurrentMode = REACT_CONCURRENT_MODE_TYPE; <add> React.unstable_Profiler = REACT_PROFILER_TYPE; <add>} <add> <ide> export default React; <ide><path>packages/shared/ReactFeatureFlags.js <ide> export function addUserTimingListener() { <ide> // React Fire: prevent the value and checked attributes from syncing <ide> // with their related DOM properties <ide> export const disableInputAttributeSyncing = false; <add> <add>// These APIs will no longer be "unstable" in the upcoming 16.7 release, <add>// Control this behavior with a flag to support 16.6 minor releases in the meanwhile. <add>export const enableStableConcurrentModeAPIs = false; <ide><path>packages/shared/forks/ReactFeatureFlags.native-fabric-fb.js <ide> export const enableProfilerTimer = __PROFILE__; <ide> export const enableSchedulerTracing = __PROFILE__; <ide> export const enableSuspenseServerRenderer = false; <ide> export const disableInputAttributeSyncing = false; <add>export const enableStableConcurrentModeAPIs = false; <ide> <ide> // Only used in www builds. <ide> export function addUserTimingListener() { <ide><path>packages/shared/forks/ReactFeatureFlags.native-fabric-oss.js <ide> export const enableProfilerTimer = __PROFILE__; <ide> export const enableSchedulerTracing = __PROFILE__; <ide> export const enableSuspenseServerRenderer = false; <ide> export const disableInputAttributeSyncing = false; <add>export const enableStableConcurrentModeAPIs = false; <ide> <ide> // Only used in www builds. <ide> export function addUserTimingListener() { <ide><path>packages/shared/forks/ReactFeatureFlags.native-fb.js <ide> export const enableUserTimingAPI = __DEV__; <ide> export const enableProfilerTimer = __PROFILE__; <ide> export const enableSchedulerTracing = __PROFILE__; <ide> export const enableSuspenseServerRenderer = false; <add>export const enableStableConcurrentModeAPIs = false; <ide> <ide> // Only used in www builds. <ide> export function addUserTimingListener() { <ide><path>packages/shared/forks/ReactFeatureFlags.native-oss.js <ide> export const enableProfilerTimer = __PROFILE__; <ide> export const enableSchedulerTracing = __PROFILE__; <ide> export const enableSuspenseServerRenderer = false; <ide> export const disableInputAttributeSyncing = false; <add>export const enableStableConcurrentModeAPIs = false; <ide> <ide> // Only used in www builds. <ide> export function addUserTimingListener() { <ide><path>packages/shared/forks/ReactFeatureFlags.persistent.js <ide> export const enableProfilerTimer = __PROFILE__; <ide> export const enableSchedulerTracing = __PROFILE__; <ide> export const enableSuspenseServerRenderer = false; <ide> export const disableInputAttributeSyncing = false; <add>export const enableStableConcurrentModeAPIs = false; <ide> <ide> // Only used in www builds. <ide> export function addUserTimingListener() { <ide><path>packages/shared/forks/ReactFeatureFlags.test-renderer.js <ide> export const enableProfilerTimer = false; <ide> export const enableSchedulerTracing = false; <ide> export const enableSuspenseServerRenderer = false; <ide> export const disableInputAttributeSyncing = false; <add>export const enableStableConcurrentModeAPIs = false; <ide> <ide> // Only used in www builds. <ide> export function addUserTimingListener() { <ide><path>packages/shared/forks/ReactFeatureFlags.test-renderer.www.js <ide> export const replayFailedUnitOfWorkWithInvokeGuardedCallback = false; <ide> export const enableProfilerTimer = false; <ide> export const enableSchedulerTracing = false; <ide> export const enableSuspenseServerRenderer = false; <add>export const enableStableConcurrentModeAPIs = false; <ide> <ide> // Only used in www builds. <ide> export function addUserTimingListener() { <ide><path>packages/shared/forks/ReactFeatureFlags.www.js <ide> export let enableUserTimingAPI = __DEV__; <ide> export const enableProfilerTimer = __PROFILE__; <ide> export const enableSchedulerTracing = __PROFILE__; <ide> <add>export const enableStableConcurrentModeAPIs = false; <add> <ide> let refCount = 0; <ide> export function addUserTimingListener() { <ide> if (__DEV__) {
11
Ruby
Ruby
add test cases for cache#fetch instrumentation
a948490b9c9dc31afb3ece482fb6dafb76c34225
<ide><path>activesupport/test/caching_test.rb <ide> def test_really_long_keys <ide> assert_equal({key => "bar"}, @cache.read_multi(key)) <ide> assert @cache.delete(key) <ide> end <add> <add> def test_cache_hit_instrumentation <add> key = "test_key" <add> subscribe_executed = false <add> ActiveSupport::Notifications.subscribe "cache_read.active_support" do |name, start, finish, id, payload| <add> subscribe_executed = true <add> assert_equal :fetch, payload[:super_operation] <add> assert payload[:hit] <add> end <add> assert @cache.write(key, "1", :raw => true) <add> assert @cache.fetch(key) {} <add> assert subscribe_executed <add> ensure <add> ActiveSupport::Notifications.unsubscribe "cache_read.active_support" <add> end <add> <add> def test_cache_miss_instrumentation <add> subscribe_executed = false <add> ActiveSupport::Notifications.subscribe "cache_read.active_support" do |name, start, finish, id, payload| <add> subscribe_executed = true <add> assert_equal :fetch, payload[:super_operation] <add> assert_not payload[:hit] <add> end <add> assert_not @cache.fetch("bad_key") {} <add> assert subscribe_executed <add> ensure <add> ActiveSupport::Notifications.unsubscribe "cache_read.active_support" <add> end <ide> end <ide> <ide> # https://rails.lighthouseapp.com/projects/8994/tickets/6225-memcachestore-cant-deal-with-umlauts-and-special-characters
1
Text
Text
add explaination for options used with tar
74f842838efa9d463ef2b28ee6dc5c30c7f2a7f5
<ide><path>guide/english/linux/how-to-extract-or-decompress-a-compressed-file-in-linux/index.md <ide> Step 1: To Know the file type<br> <ide> `file File-Name` <ide> <ide> Step 2: To Decompress a tar file<br> <add>Here options used with "tar" depends on the archive type, use `man tar` for more details on how to use tar cammand. <add>x - to extract files from an archive <add>v - show verbose output <add>f - use archive file or device ARCHIVE <add> <ide> `tar xvf File-Name -C /Directory-Location` <ide> <ide> `We Use (-C) for specific directory if we do not use (-C) then it automatically extract to current directory.`
1
Java
Java
refine testpropertysourceutils for direct use
fc839331a7bd2064ed9bb215b5f5ff5259f05f21
<ide><path>spring-test/src/main/java/org/springframework/test/context/support/TestPropertySourceUtils.java <ide> /* <del> * Copyright 2002-2015 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> <ide> import org.apache.commons.logging.Log; <ide> import org.apache.commons.logging.LogFactory; <del> <ide> import org.springframework.context.ConfigurableApplicationContext; <ide> import org.springframework.core.env.ConfigurableEnvironment; <ide> import org.springframework.core.env.Environment; <ide> private static String[] mergeProperties(List<TestPropertySourceAttributes> attri <ide> * @throws IllegalStateException if an error occurs while processing a properties file <ide> */ <ide> public static void addPropertiesFilesToEnvironment(ConfigurableApplicationContext context, <del> String[] locations) { <add> String... locations) { <ide> Assert.notNull(context, "context must not be null"); <ide> Assert.notNull(locations, "locations must not be null"); <ide> try { <ide> public static void addPropertiesFilesToEnvironment(ConfigurableApplicationContex <ide> * @see #addInlinedPropertiesToEnvironment(ConfigurableEnvironment, String[]) <ide> */ <ide> public static void addInlinedPropertiesToEnvironment(ConfigurableApplicationContext context, <del> String[] inlinedProperties) { <add> String... inlinedProperties) { <ide> Assert.notNull(context, "context must not be null"); <ide> Assert.notNull(inlinedProperties, "inlinedProperties must not be null"); <ide> addInlinedPropertiesToEnvironment(context.getEnvironment(), inlinedProperties); <ide> public static void addInlinedPropertiesToEnvironment(ConfigurableApplicationCont <ide> * @see TestPropertySource#properties <ide> * @see #convertInlinedPropertiesToMap <ide> */ <del> public static void addInlinedPropertiesToEnvironment(ConfigurableEnvironment environment, String[] inlinedProperties) { <add> public static void addInlinedPropertiesToEnvironment(ConfigurableEnvironment environment, String... inlinedProperties) { <ide> Assert.notNull(environment, "environment must not be null"); <ide> Assert.notNull(inlinedProperties, "inlinedProperties must not be null"); <ide> if (!ObjectUtils.isEmpty(inlinedProperties)) { <ide> if (logger.isDebugEnabled()) { <ide> logger.debug("Adding inlined properties to environment: " <ide> + ObjectUtils.nullSafeToString(inlinedProperties)); <ide> } <del> MapPropertySource ps = new MapPropertySource(INLINED_PROPERTIES_PROPERTY_SOURCE_NAME, <del> convertInlinedPropertiesToMap(inlinedProperties)); <del> environment.getPropertySources().addFirst(ps); <add> MapPropertySource ps = (MapPropertySource) environment.getPropertySources().get(INLINED_PROPERTIES_PROPERTY_SOURCE_NAME); <add> if (ps == null) { <add> ps = new MapPropertySource(INLINED_PROPERTIES_PROPERTY_SOURCE_NAME, <add> new LinkedHashMap<String, Object>()); <add> environment.getPropertySources().addFirst(ps); <add> } <add> ps.getSource().putAll(convertInlinedPropertiesToMap(inlinedProperties)); <ide> } <ide> } <ide> <ide> public static void addInlinedPropertiesToEnvironment(ConfigurableEnvironment env <ide> * a given inlined property contains multiple key-value pairs <ide> * @see #addInlinedPropertiesToEnvironment(ConfigurableEnvironment, String[]) <ide> */ <del> public static Map<String, Object> convertInlinedPropertiesToMap(String[] inlinedProperties) { <add> public static Map<String, Object> convertInlinedPropertiesToMap(String... inlinedProperties) { <ide> Assert.notNull(inlinedProperties, "inlinedProperties must not be null"); <ide> Map<String, Object> map = new LinkedHashMap<String, Object>(); <ide> <ide><path>spring-test/src/test/java/org/springframework/test/context/support/TestPropertySourceUtilsTests.java <ide> /* <del> * Copyright 2002-2015 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public void addInlinedPropertiesToEnvironmentWithNullContext() { <ide> public void addInlinedPropertiesToEnvironmentWithContextAndNullInlinedProperties() { <ide> expectedException.expect(IllegalArgumentException.class); <ide> expectedException.expectMessage("inlined"); <del> addInlinedPropertiesToEnvironment(mock(ConfigurableApplicationContext.class), null); <add> addInlinedPropertiesToEnvironment(mock(ConfigurableApplicationContext.class), (String[]) null); <ide> } <ide> <ide> /** <ide> public void addInlinedPropertiesToEnvironmentWithNullEnvironment() { <ide> public void addInlinedPropertiesToEnvironmentWithEnvironmentAndNullInlinedProperties() { <ide> expectedException.expect(IllegalArgumentException.class); <ide> expectedException.expectMessage("inlined"); <del> addInlinedPropertiesToEnvironment(new MockEnvironment(), null); <add> addInlinedPropertiesToEnvironment(new MockEnvironment(), (String[]) null); <ide> } <ide> <ide> /** <ide> public void addInlinedPropertiesToEnvironmentWithEmptyProperty() { <ide> public void convertInlinedPropertiesToMapWithNullInlinedProperties() { <ide> expectedException.expect(IllegalArgumentException.class); <ide> expectedException.expectMessage("inlined"); <del> convertInlinedPropertiesToMap(null); <add> convertInlinedPropertiesToMap((String[]) null); <ide> } <ide> <ide> // -------------------------------------------------------------------
2
Ruby
Ruby
remove special case for symbols at find
e7e72ec7d7a5869a070c086cf5d5b2cb869e19a6
<ide><path>activerecord/lib/active_record/core.rb <ide> def inherited(child_class) <ide> def find(*ids) <ide> # We don't have cache keys for this stuff yet <ide> return super unless ids.length == 1 <del> # Allow symbols to super to maintain compatibility for deprecated finders until Rails 5 <del> return super if ids.first.kind_of?(Symbol) <ide> return super if block_given? || <ide> primary_key.nil? || <ide> default_scopes.any? ||
1
Ruby
Ruby
restore support for model.pluck('sql fragment')
3f352d040575c9a08d13e10fd6191fbf2fa674ba
<ide><path>activerecord/lib/active_record/relation/calculations.rb <ide> def pluck(column_name) <ide> column = types[key] <ide> <ide> result.map do |attributes| <del> value = klass.initialize_attributes(attributes)[key] <add> raise ArgumentError, "Pluck expects to select just one attribute: #{attributes.inspect}" unless attributes.one? <add> value = klass.initialize_attributes(attributes).first[1] <ide> if column <ide> column.type_cast value <ide> else <ide><path>activerecord/test/cases/calculations_test.rb <ide> def test_pluck_not_auto_table_name_prefix_if_column_joined <ide> assert_equal [7], Company.joins(:contracts).pluck(:developer_id) <ide> end <ide> <add> def test_pluck_with_selection_clause <add> assert_equal [50, 53, 55, 60], Account.pluck('DISTINCT credit_limit').sort <add> end <add> <add> def test_pluck_expects_a_single_selection <add> assert_raise(ArgumentError) { Account.pluck 'id, credit_limit' } <add> end <add> <ide> def test_plucks_with_ids <ide> assert_equal Company.all.map(&:id).sort, Company.ids.sort <ide> end
2
Javascript
Javascript
remove unneeded string splitting
88d2e699d8287218cc6cd4cc80e13e1055e07fce
<ide><path>test/parallel/test-cluster-dgram-1.js <ide> const dgram = require('dgram'); <ide> <ide> <ide> if (common.isWindows) { <del> common.skip('dgram clustering is currently not supported ' + <del> 'on windows.'); <add> common.skip('dgram clustering is currently not supported on Windows.'); <ide> return; <ide> } <ide> <ide><path>test/parallel/test-cluster-dgram-2.js <ide> const assert = require('assert'); <ide> <ide> <ide> if (common.isWindows) { <del> common.skip('dgram clustering is currently not supported ' + <del> 'on windows.'); <add> common.skip('dgram clustering is currently not supported on Windows.'); <ide> return; <ide> } <ide> <ide><path>test/parallel/test-cluster-dgram-reuse.js <ide> const cluster = require('cluster'); <ide> const dgram = require('dgram'); <ide> <ide> if (common.isWindows) { <del> common.skip('dgram clustering is currently not supported ' + <del> 'on windows.'); <add> common.skip('dgram clustering is currently not supported on windows.'); <ide> return; <ide> } <ide> <ide><path>test/parallel/test-cluster-fork-env.js <ide> if (cluster.isWorker) { <ide> <ide> process.once('exit', function() { <ide> assert.ok(checks.using, 'The worker did not receive the correct env.'); <del> assert.ok(checks.overwrite, 'The custom environment did not overwrite ' + <del> 'the existing environment.'); <add> assert.ok( <add> checks.overwrite, <add> 'The custom environment did not overwrite the existing environment.'); <ide> }); <ide> <ide> } <ide><path>test/parallel/test-cluster-http-pipe.js <ide> const cluster = require('cluster'); <ide> const http = require('http'); <ide> <ide> if (common.isWindows) { <del> common.skip('It is not possible to send pipe handles over ' + <del> 'the IPC pipe on Windows'); <add> common.skip( <add> 'It is not possible to send pipe handles over the IPC pipe on Windows'); <ide> return; <ide> } <ide> <ide><path>test/parallel/test-cluster-worker-isdead.js <ide> const assert = require('assert'); <ide> <ide> if (cluster.isMaster) { <ide> const worker = cluster.fork(); <del> assert.ok(!worker.isDead(), <del> 'isDead() should return false right after the worker has been ' + <del> 'created.'); <add> assert.ok( <add> !worker.isDead(), <add> 'isDead() should return false right after the worker has been created.'); <ide> <ide> worker.on('exit', function() { <ide> assert.ok(worker.isDead(), <del> 'After an event has been emitted, ' + <del> 'isDead should return true'); <add> 'After an event has been emitted, isDead should return true'); <ide> }); <ide> <ide> worker.on('message', function(msg) { <ide><path>test/parallel/test-crypto-padding-aes256.js <ide> crypto.DEFAULT_ENCODING = 'buffer'; <ide> function aes256(decipherFinal) { <ide> const iv = Buffer.from('00000000000000000000000000000000', 'hex'); <ide> const key = Buffer.from('0123456789abcdef0123456789abcdef' + <del> '0123456789abcdef0123456789abcdef', 'hex'); <add> '0123456789abcdef0123456789abcdef', 'hex'); <ide> <ide> function encrypt(val, pad) { <ide> const c = crypto.createCipheriv('aes256', key, iv); <ide><path>test/parallel/test-crypto-padding.js <ide> const EVEN_LENGTH_ENCRYPTED = <ide> // openssl enc -aes-128-cbc -e -K 5333632e722e652e742e4b2e652e5921 \ <ide> // -iv 626c616846697a7a3230313142757a7a -nopad | xxd -p -c256 <ide> const EVEN_LENGTH_ENCRYPTED_NOPAD = <del> '7f57859550d4d2fdb9806da2a750461ab46e' + <del> '71b3d78ebe2d9684dfc87f7575b9'; <add> '7f57859550d4d2fdb9806da2a750461ab46e71b3d78ebe2d9684dfc87f7575b9'; <ide> <ide> <ide> /* <ide><path>test/parallel/test-domain-stack-empty-in-process-uncaughtexception.js <ide> const assert = require('assert'); <ide> const d = domain.create(); <ide> <ide> process.on('uncaughtException', common.mustCall(function onUncaught() { <del> assert.strictEqual(process.domain, null, <del> 'domains stack should be empty in uncaughtException' + <del> ' handler'); <add> assert.strictEqual( <add> process.domain, null, <add> 'domains stack should be empty in uncaughtException handler'); <ide> })); <ide> <ide> process.on('beforeExit', common.mustCall(function onBeforeExit() { <ide><path>test/parallel/test-http-expect-continue.js <ide> let sent_continue = false; <ide> let got_continue = false; <ide> <ide> function handler(req, res) { <del> assert.strictEqual(sent_continue, true, 'Full response sent before ' + <del> '100 Continue'); <add> assert.strictEqual(sent_continue, true, <add> 'Full response sent before 100 Continue'); <ide> console.error('Server sending full response...'); <ide> res.writeHead(200, { <ide> 'Content-Type': 'text/plain', <ide><path>test/parallel/test-http-url.parse-auth-with-header-in-request.js <ide> const server = http.createServer(function(request, response) { <ide> }); <ide> <ide> server.listen(0, function() { <del> const testURL = url.parse('http://asdf:qwer@localhost:' + <del> `${this.address().port}`); <add> const testURL = <add> url.parse(`http://asdf:qwer@localhost:${this.address().port}`); <ide> // the test here is if you set a specific authorization header in the <ide> // request we should not override that with basic auth <ide> testURL.headers = { <ide><path>test/parallel/test-http-url.parse-only-support-http-https-protocol.js <ide> assert.throws(function() { <ide> http.request(url.parse('file:///whatever')); <ide> }, function(err) { <ide> if (err instanceof Error) { <del> assert.strictEqual(err.message, 'Protocol "file:" not supported.' + <del> ' Expected "http:"'); <add> assert.strictEqual( <add> err.message, 'Protocol "file:" not supported. Expected "http:"'); <ide> return true; <ide> } <ide> }); <ide> assert.throws(function() { <ide> http.request(url.parse('mailto:asdf@asdf.com')); <ide> }, function(err) { <ide> if (err instanceof Error) { <del> assert.strictEqual(err.message, 'Protocol "mailto:" not supported.' + <del> ' Expected "http:"'); <add> assert.strictEqual( <add> err.message, 'Protocol "mailto:" not supported. Expected "http:"'); <ide> return true; <ide> } <ide> }); <ide> assert.throws(function() { <ide> http.request(url.parse('ftp://www.example.com')); <ide> }, function(err) { <ide> if (err instanceof Error) { <del> assert.strictEqual(err.message, 'Protocol "ftp:" not supported.' + <del> ' Expected "http:"'); <add> assert.strictEqual( <add> err.message, 'Protocol "ftp:" not supported. Expected "http:"'); <ide> return true; <ide> } <ide> }); <ide> assert.throws(function() { <ide> http.request(url.parse('javascript:alert(\'hello\');')); <ide> }, function(err) { <ide> if (err instanceof Error) { <del> assert.strictEqual(err.message, 'Protocol "javascript:" not supported.' + <del> ' Expected "http:"'); <add> assert.strictEqual( <add> err.message, 'Protocol "javascript:" not supported. Expected "http:"'); <ide> return true; <ide> } <ide> }); <ide> assert.throws(function() { <ide> http.request(url.parse('xmpp:isaacschlueter@jabber.org')); <ide> }, function(err) { <ide> if (err instanceof Error) { <del> assert.strictEqual(err.message, 'Protocol "xmpp:" not supported.' + <del> ' Expected "http:"'); <add> assert.strictEqual( <add> err.message, 'Protocol "xmpp:" not supported. Expected "http:"'); <ide> return true; <ide> } <ide> }); <ide> assert.throws(function() { <ide> http.request(url.parse('f://some.host/path')); <ide> }, function(err) { <ide> if (err instanceof Error) { <del> assert.strictEqual(err.message, 'Protocol "f:" not supported.' + <del> ' Expected "http:"'); <add> assert.strictEqual( <add> err.message, 'Protocol "f:" not supported. Expected "http:"'); <ide> return true; <ide> } <ide> }); <ide><path>test/parallel/test-intl.js <ide> if (!common.hasIntl) { <ide> <ide> // If list is specified and doesn't contain 'en' then return. <ide> if (process.config.variables.icu_locales && !haveLocale('en')) { <del> common.skip('detailed Intl tests because English is not ' + <del> 'listed as supported.'); <add> common.skip( <add> 'detailed Intl tests because English is not listed as supported.'); <ide> // Smoke test. Does it format anything, or fail? <ide> console.log(`Date(0) formatted to: ${dtf.format(date0)}`); <ide> return; <ide><path>test/parallel/test-tls-alpn-server-client.js <ide> if (!common.hasCrypto) { <ide> } <ide> <ide> if (!process.features.tls_alpn || !process.features.tls_npn) { <del> common.skip('Skipping because node compiled without NPN or ALPN' + <del> ' feature of OpenSSL.'); <add> common.skip( <add> 'Skipping because node compiled without NPN or ALPN feature of OpenSSL.'); <ide> return; <ide> } <ide> <ide><path>test/parallel/test-tls-client-mindhsize.js <ide> function test(size, err, next) { <ide> if (err) { <ide> client.on('error', function(e) { <ide> nerror++; <del> assert.strictEqual(e.message, 'DH parameter size 1024 is less' + <del> ' than 2048'); <add> assert.strictEqual(e.message, <add> 'DH parameter size 1024 is less than 2048'); <ide> server.close(); <ide> }); <ide> } <ide><path>test/parallel/test-tls-npn-server-client.js <ide> 'use strict'; <ide> const common = require('../common'); <ide> if (!process.features.tls_npn) { <del> common.skip('Skipping because node compiled without NPN feature of' + <del> ' OpenSSL.'); <add> common.skip('Skipping because node compiled without NPN feature of OpenSSL.'); <ide> return; <ide> } <ide> <ide><path>test/parallel/test-tls-ocsp-callback.js <ide> const common = require('../common'); <ide> <ide> if (!process.features.tls_ocsp) { <del> common.skip('node compiled without OpenSSL or ' + <del> 'with old OpenSSL version.'); <add> common.skip('node compiled without OpenSSL or with old OpenSSL version.'); <ide> return; <ide> } <ide> if (!common.opensslCli) { <ide><path>test/parallel/test-tls-sni-option.js <ide> 'use strict'; <ide> const common = require('../common'); <ide> if (!process.features.tls_sni) { <del> common.skip('node compiled without OpenSSL or ' + <del> 'with old OpenSSL version.'); <add> common.skip('node compiled without OpenSSL or with old OpenSSL version.'); <ide> return; <ide> } <ide> <ide><path>test/parallel/test-tls-sni-server-client.js <ide> 'use strict'; <ide> const common = require('../common'); <ide> if (!process.features.tls_sni) { <del> common.skip('node compiled without OpenSSL or ' + <del> 'with old OpenSSL version.'); <add> common.skip('node compiled without OpenSSL or with old OpenSSL version.'); <ide> return; <ide> } <ide> <ide><path>test/parallel/test-url-format-invalid-input.js <ide> const throwsObjsAndReportTypes = new Map([ <ide> ]); <ide> <ide> for (const [obj, type] of throwsObjsAndReportTypes) { <del> const error = new RegExp('^TypeError: Parameter "urlObj" must be an object' + <del> `, not ${type}$`); <add> const error = new RegExp( <add> `^TypeError: Parameter "urlObj" must be an object, not ${type}$`); <ide> assert.throws(function() { url.format(obj); }, error); <ide> } <ide> assert.strictEqual(url.format(''), ''); <ide><path>test/parallel/test-zlib-flush-drain.js <ide> deflater.on('drain', function() { <ide> }); <ide> <ide> process.once('exit', function() { <del> assert.strictEqual(beforeFlush, true, 'before calling flush, writable ' + <del> 'stream should need to drain'); <del> assert.strictEqual(afterFlush, false, 'after calling flush, writable ' + <del> 'stream should not need to drain'); <del> assert.strictEqual(drainCount, 1, <del> 'the deflater should have emitted a single drain event'); <del> assert.strictEqual(flushCount, 2, <del> 'flush should be called twice'); <add> assert.strictEqual( <add> beforeFlush, true, <add> 'before calling flush, writable stream should need to drain'); <add> assert.strictEqual( <add> afterFlush, false, <add> 'after calling flush, writable stream should not need to drain'); <add> assert.strictEqual( <add> drainCount, 1, 'the deflater should have emitted a single drain event'); <add> assert.strictEqual( <add> flushCount, 2, 'flush should be called twice'); <ide> }); <ide><path>test/pummel/test-net-timeout.js <ide> const echo_server = net.createServer(function(socket) { <ide> }); <ide> <ide> socket.on('error', function(e) { <del> throw new Error('Server side socket should not get error. ' + <del> 'We disconnect willingly.'); <add> throw new Error( <add> 'Server side socket should not get error. We disconnect willingly.'); <ide> }); <ide> <ide> socket.on('data', function(d) {
22
Python
Python
update tfrecord example
05b234f993b7dba88e8f468a1c8aba272ee8a55a
<ide><path>examples/mnist_tfrecord.py <ide> tensors, save the model weights, and then evaluate the <ide> model using the numpy based Keras API. <ide> <del>Gets to 99.1% test accuracy after 78 epochs <del>(there is still a lot of margin for parameter tuning). <add>Gets to ~99.1% validation accuracy after 5 epochs <add>(high variance from run to run: 98.9-99.3). <ide> ''' <del>import os <del>import copy <del>import time <del> <ide> import numpy as np <ide> <ide> import tensorflow as tf <add>import keras <ide> from keras import backend as K <del>from keras.models import Model <ide> from keras import layers <del>from keras import objectives <del>from keras.utils import np_utils <del>from keras import objectives <ide> <ide> from tensorflow.contrib.learn.python.learn.datasets import mnist <ide> <ide> if K.backend() != 'tensorflow': <ide> raise RuntimeError('This example can only run with the ' <del> 'TensorFlow backend for the time being, ' <add> 'TensorFlow backend, ' <ide> 'because it requires TFRecords, which ' <ide> 'are not supported on other platforms.') <ide> <ide> <ide> def cnn_layers(x_train_input): <ide> x = layers.Conv2D(32, (3, 3), <ide> activation='relu', padding='valid')(x_train_input) <add> x = layers.MaxPooling2D(pool_size=(2, 2))(x) <ide> x = layers.Conv2D(64, (3, 3), activation='relu')(x) <ide> x = layers.MaxPooling2D(pool_size=(2, 2))(x) <del> x = layers.Dropout(0.25)(x) <ide> x = layers.Flatten()(x) <del> x = layers.Dense(128, activation='relu')(x) <add> x = layers.Dense(512, activation='relu')(x) <ide> x = layers.Dropout(0.5)(x) <ide> x_train_out = layers.Dense(classes, <ide> activation='softmax', <ide> def cnn_layers(x_train_input): <ide> batch_size = 128 <ide> batch_shape = (batch_size, 28, 28, 1) <ide> steps_per_epoch = 469 <del>epochs = 78 <add>epochs = 5 <ide> classes = 10 <ide> <ide> # The capacity variable controls the maximum queue size <ide> def cnn_layers(x_train_input): <ide> <ide> x_train_input = layers.Input(tensor=x_train_batch, batch_shape=x_batch_shape) <ide> x_train_out = cnn_layers(x_train_input) <del>train_model = Model(inputs=x_train_input, outputs=x_train_out) <del> <del>cce = objectives.categorical_crossentropy(y_train_batch, x_train_out) <del>train_model.add_loss(cce) <del> <del># Do not pass the loss directly to model.compile() <del># because it is not yet supported for Input Tensors. <del>train_model.compile(optimizer='rmsprop', <del> loss=None, <del> metrics=['accuracy']) <add>train_model = keras.models.Model(inputs=x_train_input, outputs=x_train_out) <add> <add># Pass the target tensor `y_train_batch` to `compile` <add># via the `target_tensors` keyword argument: <add>train_model.compile(optimizer=keras.optimizers.RMSprop(lr=2e-3, decay=1e-5), <add> loss='categorical_crossentropy', <add> metrics=['accuracy'], <add> target_tensors=[y_train_batch]) <ide> train_model.summary() <ide> <add># Fit the model using data from the TFRecord data tensors. <ide> coord = tf.train.Coordinator() <ide> threads = tf.train.start_queue_runners(sess, coord) <add> <ide> train_model.fit(epochs=epochs, <ide> steps_per_epoch=steps_per_epoch) <ide> <add># Save the model weights. <ide> train_model.save_weights('saved_wt.h5') <ide> <add># Clean up the TF session. <ide> coord.request_stop() <ide> coord.join(threads) <ide> K.clear_session() <ide> <ide> # Second Session to test loading trained model without tensors <ide> x_test = np.reshape(data.validation.images, (data.validation.images.shape[0], 28, 28, 1)) <ide> y_test = data.validation.labels <del>x_test_inp = layers.Input(batch_shape=(None,) + (x_test.shape[1:])) <add>x_test_inp = layers.Input(shape=(x_test.shape[1:])) <ide> test_out = cnn_layers(x_test_inp) <del>test_model = Model(inputs=x_test_inp, outputs=test_out) <add>test_model = keras.models.Model(inputs=x_test_inp, outputs=test_out) <ide> <ide> test_model.load_weights('saved_wt.h5') <del>test_model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy']) <add>test_model.compile(optimizer='rmsprop', <add> loss='categorical_crossentropy', <add> metrics=['accuracy']) <ide> test_model.summary() <ide> <del>loss, acc = test_model.evaluate(x_test, np_utils.to_categorical(y_test), classes) <add>loss, acc = test_model.evaluate(x_test, <add> keras.utils.to_categorical(y_test), <add> classes) <ide> print('\nTest accuracy: {0}'.format(acc))
1
Python
Python
enable cache by default
2a18b709989d3cbb27ca7c5162ec2e89b067324f
<ide><path>src/transformers/models/bert_generation/configuration_bert_generation.py <ide> class BertGenerationConfig(PretrainedConfig): <ide> <https://arxiv.org/abs/1803.02155>`__. For more information on :obj:`"relative_key_query"`, please refer to <ide> `Method 4` in `Improve Transformer Models with Better Relative Position Embeddings (Huang et al.) <ide> <https://arxiv.org/abs/2009.13658>`__. <add> use_cache (:obj:`bool`, `optional`, defaults to :obj:`True`): <add> Whether or not the model should return the last key/values attentions (not used by all models). Only <add> relevant if ``config.is_decoder=True``. <ide> <ide> Examples:: <ide> <ide> def __init__( <ide> eos_token_id=1, <ide> gradient_checkpointing=False, <ide> position_embedding_type="absolute", <add> use_cache=True, <ide> **kwargs <ide> ): <ide> super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs) <ide> def __init__( <ide> self.layer_norm_eps = layer_norm_eps <ide> self.gradient_checkpointing = gradient_checkpointing <ide> self.position_embedding_type = position_embedding_type <add> self.use_cache = use_cache <ide><path>src/transformers/models/bert_generation/modeling_bert_generation.py <ide> def forward( <ide> ) <ide> return_dict = return_dict if return_dict is not None else self.config.use_return_dict <ide> <add> if self.config.is_decoder: <add> use_cache = use_cache if use_cache is not None else self.config.use_cache <add> else: <add> use_cache = False <add> <ide> if input_ids is not None and inputs_embeds is not None: <ide> raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time") <ide> elif input_ids is not None:
2
Python
Python
add failing regression test for unsafe casts
367c5a2138d4bfdeb41c0de9ac8db8b974656f2e
<ide><path>numpy/core/tests/test_regression.py <ide> def test_unicode_to_string_cast(self): <ide> dtype='U') <ide> assert_raises(UnicodeEncodeError, np.array, a, 'S4') <ide> <add> def test_unicode_to_string_cast_error(self): <add> # gh-15790 <add> a = np.array([u'\x80'] * 129, dtype='U3') <add> assert_raises(UnicodeEncodeError, np.array, a, 'S') <add> <ide> def test_mixed_string_unicode_array_creation(self): <ide> a = np.array(['1234', u'123']) <ide> assert_(a.itemsize == 16) <ide> def test_to_ctypes(self): <ide> assert arr.size * arr.itemsize > 2 ** 31 <ide> c_arr = np.ctypeslib.as_ctypes(arr) <ide> assert_equal(c_arr._length_, arr.size) <del>
1
Javascript
Javascript
reverse change that was locking users out
94e855040892afe1919398fd2dafbae92c1a36d9
<ide><path>app.js <ide> app.use(helmet.contentSecurityPolicy({ <ide> <ide> app.use(function (req, res, next) { <ide> // Make user object available in templates. <del> fullUser = req.user ? req.user : null; <del> if (fullUser) fullUser.password = null; <del> res.locals.user = fullUser; <add> res.locals.user = req.user; <ide> next(); <ide> }); <ide>
1
Python
Python
set version to 2.1.0a0
c0e596283bb6d799afea7c1c246b2b03b9437be0
<ide><path>spacy/about.py <ide> # https://github.com/pypa/warehouse/blob/master/warehouse/__about__.py <ide> <ide> __title__ = 'spacy-nightly' <del>__version__ = '2.1.0.dev5' <add>__version__ = '2.1.0a0' <ide> __summary__ = 'Industrial-strength Natural Language Processing (NLP) with Python and Cython' <ide> __uri__ = 'https://spacy.io' <ide> __author__ = 'Explosion AI'
1
Text
Text
use code markup/markdown in headers
e11b3274fb0d83b9a138ef0417e4a1d8ba996c83
<ide><path>doc/api/tls.md <ide> The first 3 are enabled by default. The last 2 `CCM`-based suites are supported <ide> by TLSv1.3 because they may be more performant on constrained systems, but they <ide> are not enabled by default since they offer less security. <ide> <del>## Class: tls.Server <add>## Class: `tls.Server` <ide> <!-- YAML <ide> added: v0.3.2 <ide> --> <ide> added: v0.3.2 <ide> <ide> Accepts encrypted connections using TLS or SSL. <ide> <del>### Event: 'keylog' <add>### Event: `'keylog'` <ide> <!-- YAML <ide> added: v12.3.0 <ide> --> <ide> server.on('keylog', (line, tlsSocket) => { <ide> }); <ide> ``` <ide> <del>### Event: 'newSession' <add>### Event: `'newSession'` <ide> <!-- YAML <ide> added: v0.9.2 <ide> --> <ide> The listener callback is passed three arguments when called: <ide> Listening for this event will have an effect only on connections established <ide> after the addition of the event listener. <ide> <del>### Event: 'OCSPRequest' <add>### Event: `'OCSPRequest'` <ide> <!-- YAML <ide> added: v0.11.13 <ide> --> <ide> after the addition of the event listener. <ide> <ide> An npm module like [asn1.js][] may be used to parse the certificates. <ide> <del>### Event: 'resumeSession' <add>### Event: `'resumeSession'` <ide> <!-- YAML <ide> added: v0.9.2 <ide> --> <ide> server.on('resumeSession', (id, cb) => { <ide> }); <ide> ``` <ide> <del>### Event: 'secureConnection' <add>### Event: `'secureConnection'` <ide> <!-- YAML <ide> added: v0.3.2 <ide> --> <ide> equals `false`. <ide> The `tlsSocket.servername` property is a string containing the server name <ide> requested via SNI. <ide> <del>### Event: 'tlsClientError' <add>### Event: `'tlsClientError'` <ide> <!-- YAML <ide> added: v6.0.0 <ide> --> <ide> called: <ide> * `tlsSocket` {tls.TLSSocket} The `tls.TLSSocket` instance from which the <ide> error originated. <ide> <del>### server.addContext(hostname, context) <add>### `server.addContext(hostname, context)` <ide> <!-- YAML <ide> added: v0.5.3 <ide> --> <ide> added: v0.5.3 <ide> The `server.addContext()` method adds a secure context that will be used if <ide> the client request's SNI name matches the supplied `hostname` (or wildcard). <ide> <del>### server.address() <add>### `server.address()` <ide> <!-- YAML <ide> added: v0.6.0 <ide> --> <ide> Returns the bound address, the address family name, and port of the <ide> server as reported by the operating system. See [`net.Server.address()`][] for <ide> more information. <ide> <del>### server.close(\[callback\]) <add>### `server.close([callback])` <ide> <!-- YAML <ide> added: v0.3.2 <ide> --> <ide> The `server.close()` method stops the server from accepting new connections. <ide> This function operates asynchronously. The `'close'` event will be emitted <ide> when the server has no more open connections. <ide> <del>### server.connections <add>### `server.connections` <ide> <!-- YAML <ide> added: v0.3.2 <ide> deprecated: v0.9.7 <ide> deprecated: v0.9.7 <ide> <ide> Returns the current number of concurrent connections on the server. <ide> <del>### server.getTicketKeys() <add>### `server.getTicketKeys()` <ide> <!-- YAML <ide> added: v3.0.0 <ide> --> <ide> Returns the session ticket keys. <ide> <ide> See [Session Resumption][] for more information. <ide> <del>### server.listen() <add>### `server.listen()` <ide> <ide> Starts the server listening for encrypted connections. <ide> This method is identical to [`server.listen()`][] from [`net.Server`][]. <ide> <del>### server.setSecureContext(options) <add>### `server.setSecureContext(options)` <ide> <!-- YAML <ide> added: v11.0.0 <ide> --> <ide> added: v11.0.0 <ide> The `server.setSecureContext()` method replaces the secure context of an <ide> existing server. Existing connections to the server are not interrupted. <ide> <del>### server.setTicketKeys(keys) <add>### `server.setTicketKeys(keys)` <ide> <!-- YAML <ide> added: v3.0.0 <ide> --> <ide> Existing or currently pending server connections will use the previous keys. <ide> <ide> See [Session Resumption][] for more information. <ide> <del>## Class: tls.TLSSocket <add>## Class: `tls.TLSSocket` <ide> <!-- YAML <ide> added: v0.11.4 <ide> --> <ide> Methods that return TLS connection metadata (e.g. <ide> [`tls.TLSSocket.getPeerCertificate()`][] will only return data while the <ide> connection is open. <ide> <del>### new tls.TLSSocket(socket\[, options\]) <add>### `new tls.TLSSocket(socket[, options])` <ide> <!-- YAML <ide> added: v0.11.4 <ide> changes: <ide> changes: <ide> <ide> Construct a new `tls.TLSSocket` object from an existing TCP socket. <ide> <del>### Event: 'keylog' <add>### Event: `'keylog'` <ide> <!-- YAML <ide> added: v12.3.0 <ide> --> <ide> const logFile = fs.createWriteStream('/tmp/ssl-keys.log', { flags: 'a' }); <ide> tlsSocket.on('keylog', (line) => logFile.write(line)); <ide> ``` <ide> <del>### Event: 'OCSPResponse' <add>### Event: `'OCSPResponse'` <ide> <!-- YAML <ide> added: v0.11.13 <ide> --> <ide> The listener callback is passed a single argument when called: <ide> Typically, the `response` is a digitally signed object from the server's CA that <ide> contains information about server's certificate revocation status. <ide> <del>### Event: 'secureConnect' <add>### Event: `'secureConnect'` <ide> <!-- YAML <ide> added: v0.11.4 <ide> --> <ide> determine if the server certificate was signed by one of the specified CAs. If <ide> `tlsSocket.alpnProtocol` property can be checked to determine the negotiated <ide> protocol. <ide> <del>### Event: 'session' <add>### Event: `'session'` <ide> <!-- YAML <ide> added: v11.10.0 <ide> --> <ide> tlsSocket.once('session', (session) => { <ide> }); <ide> ``` <ide> <del>### tlsSocket.address() <add>### `tlsSocket.address()` <ide> <!-- YAML <ide> added: v0.11.4 <ide> --> <ide> Returns the bound `address`, the address `family` name, and `port` of the <ide> underlying socket as reported by the operating system: <ide> `{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`. <ide> <del>### tlsSocket.authorizationError <add>### `tlsSocket.authorizationError` <ide> <!-- YAML <ide> added: v0.11.4 <ide> --> <ide> <ide> Returns the reason why the peer's certificate was not been verified. This <ide> property is set only when `tlsSocket.authorized === false`. <ide> <del>### tlsSocket.authorized <add>### `tlsSocket.authorized` <ide> <!-- YAML <ide> added: v0.11.4 <ide> --> <ide> added: v0.11.4 <ide> Returns `true` if the peer certificate was signed by one of the CAs specified <ide> when creating the `tls.TLSSocket` instance, otherwise `false`. <ide> <del>### tlsSocket.disableRenegotiation() <add>### `tlsSocket.disableRenegotiation()` <ide> <!-- YAML <ide> added: v8.4.0 <ide> --> <ide> <ide> Disables TLS renegotiation for this `TLSSocket` instance. Once called, attempts <ide> to renegotiate will trigger an `'error'` event on the `TLSSocket`. <ide> <del>### tlsSocket.enableTrace() <add>### `tlsSocket.enableTrace()` <ide> <!-- YAML <ide> added: v12.2.0 <ide> --> <ide> Note: The format of the output is identical to the output of `openssl s_client <ide> `SSL_trace()` function, the format is undocumented, can change without notice, <ide> and should not be relied on. <ide> <del>### tlsSocket.encrypted <add>### `tlsSocket.encrypted` <ide> <!-- YAML <ide> added: v0.11.4 <ide> --> <ide> <ide> Always returns `true`. This may be used to distinguish TLS sockets from regular <ide> `net.Socket` instances. <ide> <del>### tlsSocket.getCertificate() <add>### `tlsSocket.getCertificate()` <ide> <!-- YAML <ide> added: v11.2.0 <ide> --> <ide> structure. <ide> If there is no local certificate, an empty object will be returned. If the <ide> socket has been destroyed, `null` will be returned. <ide> <del>### tlsSocket.getCipher() <add>### `tlsSocket.getCipher()` <ide> <!-- YAML <ide> added: v0.11.4 <ide> changes: <ide> See <ide> [SSL_CIPHER_get_name](https://www.openssl.org/docs/man1.1.1/man3/SSL_CIPHER_get_name.html) <ide> for more information. <ide> <del>### tlsSocket.getEphemeralKeyInfo() <add>### `tlsSocket.getEphemeralKeyInfo()` <ide> <!-- YAML <ide> added: v5.0.0 <ide> --> <ide> if called on a server socket. The supported types are `'DH'` and `'ECDH'`. The <ide> <ide> For example: `{ type: 'ECDH', name: 'prime256v1', size: 256 }`. <ide> <del>### tlsSocket.getFinished() <add>### `tlsSocket.getFinished()` <ide> <!-- YAML <ide> added: v9.9.0 <ide> --> <ide> provided by SSL/TLS is not desired or is not enough. <ide> Corresponds to the `SSL_get_finished` routine in OpenSSL and may be used <ide> to implement the `tls-unique` channel binding from [RFC 5929][]. <ide> <del>### tlsSocket.getPeerCertificate(\[detailed\]) <add>### `tlsSocket.getPeerCertificate([detailed])` <ide> <!-- YAML <ide> added: v0.11.4 <ide> --> <ide> Example certificate: <ide> raw: <Buffer ... > } <ide> ``` <ide> <del>### tlsSocket.getPeerFinished() <add>### `tlsSocket.getPeerFinished()` <ide> <!-- YAML <ide> added: v9.9.0 <ide> --> <ide> provided by SSL/TLS is not desired or is not enough. <ide> Corresponds to the `SSL_get_peer_finished` routine in OpenSSL and may be used <ide> to implement the `tls-unique` channel binding from [RFC 5929][]. <ide> <del>### tlsSocket.getProtocol() <add>### `tlsSocket.getProtocol()` <ide> <!-- YAML <ide> added: v5.7.0 <ide> --> <ide> Protocol versions are: <ide> <ide> See the OpenSSL [`SSL_get_version`][] documentation for more information. <ide> <del>### tlsSocket.getSession() <add>### `tlsSocket.getSession()` <ide> <!-- YAML <ide> added: v0.11.4 <ide> --> <ide> See [Session Resumption][] for more information. <ide> Note: `getSession()` works only for TLSv1.2 and below. For TLSv1.3, applications <ide> must use the [`'session'`][] event (it also works for TLSv1.2 and below). <ide> <del>### tlsSocket.getSharedSigalgs() <add>### `tlsSocket.getSharedSigalgs()` <ide> <!-- YAML <ide> added: v12.11.0 <ide> --> <ide> See <ide> [SSL_get_shared_sigalgs](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_shared_sigalgs.html) <ide> for more information. <ide> <del>### tlsSocket.getTLSTicket() <add>### `tlsSocket.getTLSTicket()` <ide> <!-- YAML <ide> added: v0.11.4 <ide> --> <ide> It may be useful for debugging. <ide> <ide> See [Session Resumption][] for more information. <ide> <del>### tlsSocket.isSessionReused() <add>### `tlsSocket.isSessionReused()` <ide> <!-- YAML <ide> added: v0.5.6 <ide> --> <ide> added: v0.5.6 <ide> <ide> See [Session Resumption][] for more information. <ide> <del>### tlsSocket.localAddress <add>### `tlsSocket.localAddress` <ide> <!-- YAML <ide> added: v0.11.4 <ide> --> <ide> added: v0.11.4 <ide> <ide> Returns the string representation of the local IP address. <ide> <del>### tlsSocket.localPort <add>### `tlsSocket.localPort` <ide> <!-- YAML <ide> added: v0.11.4 <ide> --> <ide> added: v0.11.4 <ide> <ide> Returns the numeric representation of the local port. <ide> <del>### tlsSocket.remoteAddress <add>### `tlsSocket.remoteAddress` <ide> <!-- YAML <ide> added: v0.11.4 <ide> --> <ide> added: v0.11.4 <ide> Returns the string representation of the remote IP address. For example, <ide> `'74.125.127.100'` or `'2001:4860:a005::68'`. <ide> <del>### tlsSocket.remoteFamily <add>### `tlsSocket.remoteFamily` <ide> <!-- YAML <ide> added: v0.11.4 <ide> --> <ide> added: v0.11.4 <ide> <ide> Returns the string representation of the remote IP family. `'IPv4'` or `'IPv6'`. <ide> <del>### tlsSocket.remotePort <add>### `tlsSocket.remotePort` <ide> <!-- YAML <ide> added: v0.11.4 <ide> --> <ide> added: v0.11.4 <ide> <ide> Returns the numeric representation of the remote port. For example, `443`. <ide> <del>### tlsSocket.renegotiate(options, callback) <add>### `tlsSocket.renegotiate(options, callback)` <ide> <!-- YAML <ide> added: v0.11.8 <ide> --> <ide> When running as the server, the socket will be destroyed with an error after <ide> For TLSv1.3, renegotiation cannot be initiated, it is not supported by the <ide> protocol. <ide> <del>### tlsSocket.setMaxSendFragment(size) <add>### `tlsSocket.setMaxSendFragment(size)` <ide> <!-- YAML <ide> added: v0.11.11 <ide> --> <ide> and their processing can be delayed due to packet loss or reordering. However, <ide> smaller fragments add extra TLS framing bytes and CPU overhead, which may <ide> decrease overall server throughput. <ide> <del>## tls.checkServerIdentity(hostname, cert) <add>## `tls.checkServerIdentity(hostname, cert)` <ide> <!-- YAML <ide> added: v0.8.4 <ide> --> <ide> the checks done with additional verification. <ide> This function is only called if the certificate passed all other checks, such as <ide> being issued by trusted CA (`options.ca`). <ide> <del>## tls.connect(options\[, callback\]) <add>## `tls.connect(options[, callback])` <ide> <!-- YAML <ide> added: v0.11.3 <ide> changes: <ide> socket.on('end', () => { <ide> }); <ide> ``` <ide> <del>## tls.connect(path\[, options\]\[, callback\]) <add>## `tls.connect(path[, options][, callback])` <ide> <!-- YAML <ide> added: v0.11.3 <ide> --> <ide> as an argument instead of an option. <ide> <ide> A path option, if specified, will take precedence over the path argument. <ide> <del>## tls.connect(port\[, host\]\[, options\]\[, callback\]) <add>## `tls.connect(port[, host][, options][, callback])` <ide> <!-- YAML <ide> added: v0.11.3 <ide> --> <ide> as arguments instead of options. <ide> A port or host option, if specified, will take precedence over any port or host <ide> argument. <ide> <del>## tls.createSecureContext(\[options\]) <add>## `tls.createSecureContext([options])` <ide> <!-- YAML <ide> added: v0.11.13 <ide> changes: <ide> A key is *required* for ciphers that make use of certificates. Either `key` or <ide> If the `ca` option is not given, then Node.js will default to using <ide> [Mozilla's publicly trusted list of CAs][]. <ide> <del>## tls.createServer(\[options\]\[, secureConnectionListener\]) <add>## `tls.createServer([options][, secureConnectionListener])` <ide> <!-- YAML <ide> added: v0.3.2 <ide> changes: <ide> server.listen(8000, () => { <ide> The server can be tested by connecting to it using the example client from <ide> [`tls.connect()`][]. <ide> <del>## tls.getCiphers() <add>## `tls.getCiphers()` <ide> <!-- YAML <ide> added: v0.10.2 <ide> --> <ide> TLSv1.2 and below. <ide> console.log(tls.getCiphers()); // ['aes128-gcm-sha256', 'aes128-sha', ...] <ide> ``` <ide> <del>## tls.rootCertificates <add>## `tls.rootCertificates` <ide> <!-- YAML <ide> added: v12.3.0 <ide> --> <ide> An immutable array of strings representing the root certificates (in PEM format) <ide> used for verifying peer certificates. This is the default value of the `ca` <ide> option to [`tls.createSecureContext()`][]. <ide> <del>## tls.DEFAULT_ECDH_CURVE <add>## `tls.DEFAULT_ECDH_CURVE` <ide> <!-- YAML <ide> added: v0.11.13 <ide> changes: <ide> The default curve name to use for ECDH key agreement in a tls server. The <ide> default value is `'auto'`. See [`tls.createSecureContext()`][] for further <ide> information. <ide> <del>## tls.DEFAULT_MAX_VERSION <add>## `tls.DEFAULT_MAX_VERSION` <ide> <!-- YAML <ide> added: v11.4.0 <ide> --> <ide> added: v11.4.0 <ide> the default to `'TLSv1.3'`. If multiple of the options are provided, the <ide> highest maximum is used. <ide> <del>## tls.DEFAULT_MIN_VERSION <add>## `tls.DEFAULT_MIN_VERSION` <ide> <!-- YAML <ide> added: v11.4.0 <ide> --> <ide> added: v11.4.0 <ide> <ide> ## Deprecated APIs <ide> <del>### Class: CryptoStream <add>### Class: `CryptoStream` <ide> <!-- YAML <ide> added: v0.3.4 <ide> deprecated: v0.11.3 <ide> deprecated: v0.11.3 <ide> The `tls.CryptoStream` class represents a stream of encrypted data. This class <ide> is deprecated and should no longer be used. <ide> <del>#### cryptoStream.bytesWritten <add>#### `cryptoStream.bytesWritten` <ide> <!-- YAML <ide> added: v0.3.4 <ide> deprecated: v0.11.3 <ide> The `cryptoStream.bytesWritten` property returns the total number of bytes <ide> written to the underlying socket *including* the bytes required for the <ide> implementation of the TLS protocol. <ide> <del>### Class: SecurePair <add>### Class: `SecurePair` <ide> <!-- YAML <ide> added: v0.3.2 <ide> deprecated: v0.11.3 <ide> deprecated: v0.11.3 <ide> <ide> Returned by [`tls.createSecurePair()`][]. <ide> <del>#### Event: 'secure' <add>#### Event: `'secure'` <ide> <!-- YAML <ide> added: v0.3.2 <ide> deprecated: v0.11.3 <ide> As with checking for the server <ide> event, `pair.cleartext.authorized` should be inspected to confirm whether the <ide> certificate used is properly authorized. <ide> <del>### tls.createSecurePair(\[context\]\[, isServer\]\[, requestCert\]\[, rejectUnauthorized\]\[, options\]) <add>### `tls.createSecurePair([context][, isServer][, requestCert][, rejectUnauthorized][, options])` <ide> <!-- YAML <ide> added: v0.3.2 <ide> deprecated: v0.11.3
1
Ruby
Ruby
remove autoloads for removed classes
c70bd1345d0eb33f4558b1a0813c742f0fec0645
<ide><path>actionview/lib/action_view.rb <ide> module ActionView <ide> <ide> autoload_at "action_view/template/resolver" do <ide> autoload :Resolver <del> autoload :PathResolver <ide> autoload :FileSystemResolver <del> autoload :OptimizedFileSystemResolver <del> autoload :FallbackFileSystemResolver <ide> end <ide> <ide> autoload_at "action_view/buffers" do
1
Ruby
Ruby
fix unscope with subquery
22ca710f20c3c656811df006cbf1f4dbc359f7a6
<ide><path>activerecord/lib/active_record/relation/where_clause.rb <ide> def merge(other) <ide> end <ide> <ide> def except(*columns) <del> WhereClause.new( <del> predicates_except(columns), <del> binds_except(columns), <del> ) <add> WhereClause.new(*except_predicates_and_binds(columns)) <ide> end <ide> <ide> def or(other) <ide> def invert_predicate(node) <ide> end <ide> end <ide> <del> def predicates_except(columns) <del> predicates.reject do |node| <add> def except_predicates_and_binds(columns) <add> except_binds = [] <add> binds_index = 0 <add> <add> predicates = self.predicates.reject do |node| <ide> case node <ide> when Arel::Nodes::Between, Arel::Nodes::In, Arel::Nodes::NotIn, Arel::Nodes::Equality, Arel::Nodes::NotEqual, Arel::Nodes::LessThan, Arel::Nodes::LessThanOrEqual, Arel::Nodes::GreaterThan, Arel::Nodes::GreaterThanOrEqual <add> binds_contains = node.grep(Arel::Nodes::BindParam).size <ide> subrelation = (node.left.kind_of?(Arel::Attributes::Attribute) ? node.left : node.right) <ide> columns.include?(subrelation.name.to_s) <add> end.tap do |except| <add> if except && binds_contains > 0 <add> (binds_index...(binds_index + binds_contains)).each do |i| <add> except_binds[i] = true <add> end <add> <add> binds_index += binds_contains <add> end <ide> end <ide> end <del> end <ide> <del> def binds_except(columns) <del> binds.reject do |attr| <del> columns.include?(attr.name) <add> binds = self.binds.reject.with_index do |_, i| <add> except_binds[i] <ide> end <add> <add> [predicates, binds] <ide> end <ide> <ide> def predicates_with_wrapped_sql_literals <ide><path>activerecord/test/cases/relations_test.rb <ide> def test_presence <ide> assert !Post.all.respond_to?(:by_lifo) <ide> end <ide> <add> def test_unscope_with_subquery <add> p1 = Post.where(id: 1) <add> p2 = Post.where(id: 2) <add> <add> assert_not_equal p1, p2 <add> <add> comments = Comment.where(post: p1).unscope(where: :post_id).where(post: p2) <add> <add> assert_not_equal p1.first.comments, comments <add> assert_equal p2.first.comments, comments <add> end <add> <ide> def test_unscope_removes_binds <ide> left = Post.where(id: Arel::Nodes::BindParam.new) <ide> column = Post.columns_hash["id"]
2
PHP
PHP
add the beforerefreshingdatabase function
8c737f054fe54076556870ae6a5b4745b554a063
<ide><path>src/Illuminate/Foundation/Testing/RefreshDatabase.php <ide> trait RefreshDatabase <ide> */ <ide> public function refreshDatabase() <ide> { <add> $this->beforeRefreshingDatabase(); <add> <ide> $this->usingInMemoryDatabase() <ide> ? $this->refreshInMemoryDatabase() <ide> : $this->refreshTestDatabase(); <ide> protected function connectionsToTransact() <ide> ? $this->connectionsToTransact : [null]; <ide> } <ide> <add> /** <add> * Perform any work that should take place before the database has started refreshing. <add> * <add> * @return void <add> */ <add> protected function beforeRefreshingDatabase() <add> { <add> // ... <add> } <add> <ide> /** <ide> * Perform any work that should take place once the database has finished refreshing. <ide> *
1
Go
Go
fix tests regarding the new test image
a8a6848ce0c3c54d00cfcd85727546e54a4dcf7e
<ide><path>api_test.go <ide> func TestGetContainersTop(t *testing.T) { <ide> t.Fatalf("Expected 2 processes, found %d.", len(procs)) <ide> } <ide> <del> if procs[0].Cmd != "sh" && procs[0].Cmd != "exe" { <del> t.Fatalf("Expected `sleep` or `sh`, found %s.", procs[0].Cmd) <add> if procs[0].Cmd != "sh" && procs[0].Cmd != "busybox" { <add> t.Fatalf("Expected `busybox` or `sh`, found %s.", procs[0].Cmd) <ide> } <ide> <del> if procs[1].Cmd != "sh" && procs[1].Cmd != "exe" { <del> t.Fatalf("Expected `sleep` or `sh`, found %s.", procs[1].Cmd) <add> if procs[1].Cmd != "sh" && procs[1].Cmd != "busybox" { <add> t.Fatalf("Expected `busybox` or `sh`, found %s.", procs[1].Cmd) <ide> } <ide> } <ide>
1
PHP
PHP
set the controller router on the routelistcommand
7768a18fb4db21d82172abd875aca08e3d00267e
<ide><path>src/Illuminate/Foundation/Console/RouteListCommand.php <ide> use Illuminate\Routing\Route; <ide> use Illuminate\Routing\Router; <ide> use Illuminate\Console\Command; <add>use Illuminate\Routing\Controller; <ide> use Symfony\Component\Console\Input\InputOption; <ide> <ide> class RouteListCommand extends Command { <ide> protected function getMiddleware($route) <ide> */ <ide> protected function getControllerMiddleware($actionName) <ide> { <add> Controller::setRouter($this->laravel['router']); <add> <ide> $segments = explode('@', $actionName); <ide> <ide> return $this->getControllerMiddlewareFromInstance(
1
Text
Text
save option description in validations
73fece000f93d811337e18f376acc6df3efed6b3
<ide><path>guides/source/active_record_validations.md <ide> class Person < ActiveRecord::Base <ide> validates :age, numericality: true, on: :update <ide> <ide> # the default (validates on both create and update) <del> # The following line is in review state and as of now, it is not running in any version of Rails 3.2.x as discussed in this [issue](https://github.com/rails/rails/issues/10248) <del> <ide> validates :name, presence: true, on: :save <ide> end <ide> ``` <add>The last line is in review state and as of now, it is not running in any version of Rails 3.2.x as discussed in this [issue](https://github.com/rails/rails/issues/10248) <ide> <ide> Strict Validations <ide> ------------------ <ide><path>guides/source/ruby_on_rails_guides_guidelines.md <ide> Those guidelines apply also to guides. <ide> HTML Guides <ide> ----------- <ide> <add>Before generating the guides, make sure that you have the latest version of Bundler installed on your system. As of this writing, you must install Bundler 1.3.5 on your device. <add> <add>To install the latest version of Bundler, simply run the `gem install bundler` command <add> <ide> ### Generation <ide> <ide> To generate all the guides, just `cd` into the `guides` directory, run `bundle install` and execute:
2
PHP
PHP
fix whitespace and add usage to doc block
bf43a5ee24838755dcc3007a59a55e1f800d6297
<ide><path>lib/Cake/Controller/Component/AuthComponent.php <ide> public function constructAuthorize() { <ide> * <ide> * `$this->Auth->allow(array('edit', 'add'));` or <ide> * `$this->Auth->allow('edit', 'add');` <add> * `$this->Auth->allow();` to allow all actions. <ide> * <ide> * allow() also supports '*' as a wildcard to mean all actions. <ide> * <ide> public function allow($action = null) { <ide> */ <ide> public function deny($action = null) { <ide> $args = func_get_args(); <del> if(empty($args)){ <add> if (empty($args)) { <ide> $this->allowedActions = array(); <del> }else{ <add> } else { <ide> if (isset($args[0]) && is_array($args[0])) { <ide> $args = $args[0]; <ide> }
1
Go
Go
relax restriction on ipamconfig
24339bea4333f0d33a90d67becf13e067a632b41
<ide><path>libnetwork/libnetwork_internal_test.go <ide> func compareIpamConfList(listA, listB []*IpamConf) bool { <ide> a = listA[i] <ide> b = listB[i] <ide> if a.PreferredPool != b.PreferredPool || <del> a.SubPool != b.SubPool || a.IsV6 != b.IsV6 || <add> a.SubPool != b.SubPool || <ide> !compareStringMaps(a.Options, b.Options) || <ide> a.Gateway != b.Gateway || !compareStringMaps(a.AuxAddresses, b.AuxAddresses) { <ide> return false <ide><path>libnetwork/network.go <ide> type IpamConf struct { <ide> SubPool string <ide> // Input options for IPAM Driver (optional) <ide> Options map[string]string <del> // IPv6 flag, Needed when no preferred pool is specified <del> IsV6 bool <ide> // Preferred Network Gateway address (optional) <ide> Gateway string <ide> // Auxiliary addresses for network driver. Must be within the master pool. <ide> func (n *network) ipamAllocateVersion(ipVer int, ipam ipamapi.Ipam) error { <ide> return types.InternalErrorf("incorrect ip version passed to ipam allocate: %d", ipVer) <ide> } <ide> <del> if *cfgList == nil { <add> if len(*cfgList) == 0 { <ide> if ipVer == 6 { <ide> return nil <ide> } <ide> func (n *network) ipamAllocateVersion(ipVer int, ipam ipamapi.Ipam) error { <ide> d := &IpamInfo{} <ide> (*infoList)[i] = d <ide> <del> d.PoolID, d.Pool, d.Meta, err = ipam.RequestPool(n.addrSpace, cfg.PreferredPool, cfg.SubPool, cfg.Options, cfg.IsV6) <add> d.PoolID, d.Pool, d.Meta, err = ipam.RequestPool(n.addrSpace, cfg.PreferredPool, cfg.SubPool, cfg.Options, ipVer == 6) <ide> if err != nil { <ide> return err <ide> }
2
Python
Python
add serialization tests for tensorizer
cef547a9f05fc39ee667606b6561ea3f106a7018
<ide><path>spacy/tests/serialize/test_serialize_tensorizer.py <add># coding: utf-8 <add>from __future__ import unicode_literals <add> <add>from ..util import make_tempdir <add>from ...pipeline import TokenVectorEncoder as Tensorizer <add> <add>import pytest <add> <add> <add>def test_serialize_tensorizer_roundtrip_bytes(en_vocab): <add> tensorizer = Tensorizer(en_vocab) <add> tensorizer.model = tensorizer.Model() <add> tensorizer_b = tensorizer.to_bytes() <add> new_tensorizer = Tensorizer(en_vocab).from_bytes(tensorizer_b) <add> assert new_tensorizer.to_bytes() == tensorizer_b <add> <add> <add>def test_serialize_tensorizer_roundtrip_disk(en_vocab): <add> tensorizer = Tensorizer(en_vocab) <add> tensorizer.model = tensorizer.Model() <add> with make_tempdir() as d: <add> file_path = d / 'tensorizer' <add> tensorizer.to_disk(file_path) <add> tensorizer_d = Tensorizer(en_vocab).from_disk(file_path) <add> assert tensorizer.to_bytes() == tensorizer_d.to_bytes()
1
Javascript
Javascript
add serializer for regexp
06cd79f17f69782386650cef7e7427c0b39bcf4d
<ide><path>lib/serialization/ObjectMiddleware.js <ide> <ide> const MapObjectSerializer = require("./MapObjectSerializer"); <ide> const PlainObjectSerializer = require("./PlainObjectSerializer"); <add>const RegExpObjectSerializer = require("./RegExpObjectSerializer"); <ide> const SerializerMiddleware = require("./SerializerMiddleware"); <ide> const SetObjectSerializer = require("./SetObjectSerializer"); <ide> <ide> const CURRENT_VERSION = 1; <ide> const plainObjectSerializer = new PlainObjectSerializer(); <ide> const mapObjectSerializer = new MapObjectSerializer(); <ide> const setObjectSerializer = new SetObjectSerializer(); <add>const regExpObjectSerializer = new RegExpObjectSerializer(); <ide> <ide> const serializers = new Map(); <ide> const serializerInversed = new Map(); <ide> serializers.set(Set, { <ide> name: 2, <ide> serializer: setObjectSerializer <ide> }); <add>serializers.set(RegExp, { <add> request: "", <add> name: 3, <add> serializer: regExpObjectSerializer <add>}); <ide> for (const { request, name, serializer } of serializers.values()) { <ide> serializerInversed.set(`${request}/${name}`, serializer); <ide> } <ide><path>lib/serialization/RegExpObjectSerializer.js <add>/* <add> MIT License http://www.opensource.org/licenses/mit-license.php <add>*/ <add> <add>"use strict"; <add> <add>class RegExpObjectSerializer { <add> serialize(obj, { write }) { <add> write(obj.source); <add> write(obj.flags); <add> } <add> deserialize({ read }) { <add> return new RegExp(read(), read()); <add> } <add>} <add> <add>module.exports = RegExpObjectSerializer;
2
Mixed
Javascript
find next todo id correctly. fixes #524
408941a74348fb0482b0f13c438ff9196e79ee24
<ide><path>docs/recipes/WritingTests.md <ide> export default function todos(state = initialState, action) { <ide> switch (action.type) { <ide> case ADD_TODO: <ide> return [{ <del> id: state.length, <add> id: state.reduce((maxId, todo) => Math.max(todo.id, maxId), -1) + 1, <ide> completed: false, <ide> text: action.text <ide> }, ...state]; <ide><path>examples/todomvc/reducers/todos.js <ide> export default function todos(state = initialState, action) { <ide> switch (action.type) { <ide> case ADD_TODO: <ide> return [{ <del> id: state.length, <add> id: state.reduce((maxId, todo) => Math.max(todo.id, maxId), -1) + 1, <ide> completed: false, <ide> text: action.text <ide> }, ...state]; <ide><path>examples/todomvc/test/reducers/todos.spec.js <ide> describe('todos reducer', () => { <ide> completed: false, <ide> id: 0 <ide> }]); <add> <add> expect( <add> todos([{ <add> text: 'Run the tests', <add> completed: false, <add> id: 1 <add> }, { <add> text: 'Use Redux', <add> completed: false, <add> id: 0 <add> }], { <add> type: types.ADD_TODO, <add> text: 'Fix the tests' <add> }) <add> ).toEqual([{ <add> text: 'Fix the tests', <add> completed: false, <add> id: 2 <add> }, { <add> text: 'Run the tests', <add> completed: false, <add> id: 1 <add> }, { <add> text: 'Use Redux', <add> completed: false, <add> id: 0 <add> }]); <ide> }); <ide> <ide> it('should handle DELETE_TODO', () => { <ide> describe('todos reducer', () => { <ide> id: 0 <ide> }]); <ide> }); <add> <add> it('should not generate duplicate ids after CLEAR_COMPLETED', () => { <add> expect( <add> [{ <add> type: types.COMPLETE_TODO, <add> id: 0 <add> }, { <add> type: types.CLEAR_COMPLETED <add> }, { <add> type: types.ADD_TODO, <add> text: 'Write more tests' <add> }].reduce(todos, [{ <add> id: 0, <add> completed: false, <add> text: 'Use Redux' <add> }, { <add> id: 1, <add> completed: false, <add> text: 'Write tests' <add> }]) <add> ).toEqual([{ <add> text: 'Write more tests', <add> completed: false, <add> id: 2 <add> }, { <add> text: 'Write tests', <add> completed: false, <add> id: 1 <add> }]); <add> }); <ide> });
3
PHP
PHP
add alias for phpunit\framework\error\notice
ae397d77386bf77c31b12f4e3fd1ac8fc45b9f02
<ide><path>tests/TestCase/Controller/ControllerTest.php <ide> public function testUndefinedPropertyError() <ide> $controller->Bar = true; <ide> $this->assertTrue($controller->Bar); <ide> <del> if (class_exists(Notice::class)) { <del> $this->expectException(Notice::class); <del> } else { <del> $this->expectException(\PHPUnit_Framework_Error_Notice::class); <del> } <add> $this->expectException(Notice::class); <ide> $this->expectExceptionMessage(sprintf( <ide> 'Undefined property: Controller::$Foo in %s on line %s', <ide> __FILE__, <ide><path>tests/phpunit_aliases.php <ide> class_alias('PHPUnit_Framework_TestSuite', 'PHPUnit\Framework\TestSuite'); <ide> class_alias('PHPUnit_Framework_TestResult', 'PHPUnit\Framework\TestResult'); <ide> class_alias('PHPUnit_Framework_Error', 'PHPUnit\Framework\Error\Error'); <ide> class_alias('PHPUnit_Framework_Error_Deprecated', 'PHPUnit\Framework\Error\Deprecated'); <add> class_alias('PHPUnit_Framework_Error_Notice', 'PHPUnit\Framework\Error\Notice'); <ide> class_alias('PHPUnit_Framework_Error_Warning', 'PHPUnit\Framework\Error\Warning'); <ide> class_alias('PHPUnit_Framework_ExpectationFailedException', 'PHPUnit\Framework\ExpectationFailedException'); <ide> }
2
Go
Go
remove job from rmi
e4afc379dcee66475f3becb34cd2675f3ee9279c
<ide><path>api/client/build.go <ide> func (cli *DockerCli) CmdBuild(args ...string) error { <ide> // And canonicalize dockerfile name to a platform-independent one <ide> *dockerfileName, err = archive.CanonicalTarNameForPath(*dockerfileName) <ide> if err != nil { <del> return fmt.Errorf("Cannot canonicalize dockerfile path %s: %v", dockerfileName, err) <add> return fmt.Errorf("Cannot canonicalize dockerfile path %s: %v", *dockerfileName, err) <ide> } <ide> <ide> if _, err = os.Lstat(filename); os.IsNotExist(err) { <ide><path>api/server/server.go <ide> func deleteImages(eng *engine.Engine, version version.Version, w http.ResponseWr <ide> if vars == nil { <ide> return fmt.Errorf("Missing parameter") <ide> } <del> var job = eng.Job("image_delete", vars["name"]) <del> streamJSON(job, w, false) <del> job.Setenv("force", r.Form.Get("force")) <del> job.Setenv("noprune", r.Form.Get("noprune")) <ide> <del> return job.Run() <add> d := getDaemon(eng) <add> name := vars["name"] <add> force := toBool(r.Form.Get("force")) <add> noprune := toBool(r.Form.Get("noprune")) <add> <add> list, err := d.ImageDelete(name, force, noprune) <add> if err != nil { <add> return err <add> } <add> <add> return writeJSON(w, http.StatusOK, list) <ide> } <ide> <ide> func postContainersStart(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <ide><path>daemon/daemon.go <ide> type Daemon struct { <ide> <ide> // Install installs daemon capabilities to eng. <ide> func (daemon *Daemon) Install(eng *engine.Engine) error { <del> // FIXME: remove ImageDelete's dependency on Daemon, then move to graph/ <ide> for name, method := range map[string]engine.Handler{ <ide> "commit": daemon.ContainerCommit, <ide> "container_copy": daemon.ContainerCopy, <ide> func (daemon *Daemon) Install(eng *engine.Engine) error { <ide> "top": daemon.ContainerTop, <ide> "unpause": daemon.ContainerUnpause, <ide> "wait": daemon.ContainerWait, <del> "image_delete": daemon.ImageDelete, // FIXME: see above <ide> "execCreate": daemon.ContainerExecCreate, <ide> "execStart": daemon.ContainerExecStart, <ide> "execResize": daemon.ContainerExecResize, <ide><path>daemon/image_delete.go <ide> package daemon <ide> <ide> import ( <del> "encoding/json" <ide> "fmt" <ide> "strings" <ide> <ide> "github.com/docker/docker/api/types" <del> "github.com/docker/docker/engine" <ide> "github.com/docker/docker/graph" <ide> "github.com/docker/docker/image" <ide> "github.com/docker/docker/pkg/parsers" <ide> "github.com/docker/docker/pkg/stringid" <ide> "github.com/docker/docker/utils" <ide> ) <ide> <del>func (daemon *Daemon) ImageDelete(job *engine.Job) error { <del> if n := len(job.Args); n != 1 { <del> return fmt.Errorf("Usage: %s IMAGE", job.Name) <del> } <del> <add>// FIXME: remove ImageDelete's dependency on Daemon, then move to graph/ <add>func (daemon *Daemon) ImageDelete(name string, force, noprune bool) ([]types.ImageDelete, error) { <ide> list := []types.ImageDelete{} <del> if err := daemon.DeleteImage(job.Eng, job.Args[0], &list, true, job.GetenvBool("force"), job.GetenvBool("noprune")); err != nil { <del> return err <add> if err := daemon.imgDeleteHelper(name, &list, true, force, noprune); err != nil { <add> return nil, err <ide> } <ide> if len(list) == 0 { <del> return fmt.Errorf("Conflict, %s wasn't deleted", job.Args[0]) <add> return nil, fmt.Errorf("Conflict, %s wasn't deleted", name) <ide> } <del> if err := json.NewEncoder(job.Stdout).Encode(list); err != nil { <del> return err <del> } <del> return nil <add> <add> return list, nil <ide> } <ide> <del>// FIXME: make this private and use the job instead <del>func (daemon *Daemon) DeleteImage(eng *engine.Engine, name string, list *[]types.ImageDelete, first, force, noprune bool) error { <add>func (daemon *Daemon) imgDeleteHelper(name string, list *[]types.ImageDelete, first, force, noprune bool) error { <ide> var ( <ide> repoName, tag string <ide> tags = []string{} <ide> func (daemon *Daemon) DeleteImage(eng *engine.Engine, name string, list *[]types <ide> Deleted: img.ID, <ide> }) <ide> daemon.EventsService.Log("delete", img.ID, "") <del> eng.Job("log", "delete", img.ID, "").Run() <ide> if img.Parent != "" && !noprune { <del> err := daemon.DeleteImage(eng, img.Parent, list, false, force, noprune) <add> err := daemon.imgDeleteHelper(img.Parent, list, false, force, noprune) <ide> if first { <ide> return err <ide> }
4
Text
Text
move fishrock123 to emeritus
7c2b4906faf8b4afdb2f917a5ec22c167b2f90d8
<ide><path>README.md <ide> For information about the governance of the Node.js project, see <ide> **Evan Lucas** \<evanlucas@me.com> (he/him) <ide> * [fhinkel](https://github.com/fhinkel) - <ide> **Franziska Hinkelmann** \<franziska.hinkelmann@gmail.com> (she/her) <del>* [Fishrock123](https://github.com/Fishrock123) - <del> **Jeremiah Senkpiel** \<fishrock123@rocketmail.com> (he/they) <ide> * [Flarna](https://github.com/Flarna) - <ide> **Gerhard Stöbich** \<deb2001-github@yahoo.de> (he/they) <ide> * [gabrielschulhof](https://github.com/gabrielschulhof) - <ide> For information about the governance of the Node.js project, see <ide> **Alexander Makarenko** \<estliberitas@gmail.com> <ide> * [firedfox](https://github.com/firedfox) - <ide> **Daniel Wang** \<wangyang0123@gmail.com> <add>* [Fishrock123](https://github.com/Fishrock123) - <add> **Jeremiah Senkpiel** \<fishrock123@rocketmail.com> (he/they) <ide> * [gdams](https://github.com/gdams) - <ide> **George Adams** \<gadams@microsoft.com> (he/him) <ide> * [geek](https://github.com/geek) -
1
Go
Go
add new functions to unsupported file
17719cab91e175a7bd11f9852e27638df1202b8b
<ide><path>pkg/netlink/netlink_unsupported.go <ide> package netlink <ide> <ide> import ( <del> "fmt" <add> "errors" <ide> "net" <ide> ) <ide> <add>var ( <add> ErrNotImplemented = errors.New("not implemented") <add>) <add> <ide> func NetworkGetRoutes() ([]Route, error) { <del> return nil, fmt.Errorf("Not implemented") <add> return nil, ErrNotImplemented <ide> } <ide> <ide> func NetworkLinkAdd(name string, linkType string) error { <del> return fmt.Errorf("Not implemented") <add> return ErrNotImplemented <ide> } <ide> <ide> func NetworkLinkUp(iface *net.Interface) error { <del> return fmt.Errorf("Not implemented") <add> return ErrNotImplemented <ide> } <ide> <ide> func NetworkLinkAddIp(iface *net.Interface, ip net.IP, ipNet *net.IPNet) error { <del> return fmt.Errorf("Not implemented") <add> return ErrNotImplemented <ide> } <ide> <ide> func AddDefaultGw(ip net.IP) error { <del> return fmt.Errorf("Not implemented") <add> return ErrNotImplemented <ide> <ide> } <ide> <ide> func NetworkSetMTU(iface *net.Interface, mtu int) error { <del> return fmt.Errorf("Not implemented") <add> return ErrNotImplemented <add>} <add> <add>func NetworkCreateVethPair(name1, name2 string) error { <add> return ErrNotImplemented <add>} <add> <add>func NetworkChangeName(iface *net.Interface, newName string) error { <add> return ErrNotImplemented <add>} <add> <add>func NetworkSetNsFd(iface *net.Interface, fd int) error { <add> return ErrNotImplemented <add>} <add> <add>func NetworkSetNsPid(iface *net.Interface, nspid int) error { <add> return ErrNotImplemented <add>} <add> <add>func NetworkSetMaster(iface, master *net.Interface) error { <add> return ErrNotImplemented <add>} <add> <add>func NetworkLinkDown(iface *net.Interface) error { <add> return ErrNotImplemented <ide> }
1
Text
Text
add v4.0.0-beta.5 to changelog
7457fdbffa3280ca3908db865340ce4b7595356d
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <add>### v4.0.0-beta.5 (October 11, 2021) <add> <add>- [#19761](https://github.com/emberjs/ember.js/pull/19761) [BREAKING] Require ember-auto-import >= 2 or higher to enable ember-source to become a v2 addon in the 4.x cycle <add> <ide> ### v4.0.0-beta.4 (September 13, 2021) <ide> <ide> - [#19733](https://github.com/emberjs/ember.js/pull/19733) [BUGFIX] Ensure that using `routerService.urlFor(...)` and `routerService.recognize(...)` does not error if the router is not fully initialized
1
Ruby
Ruby
improve string#to docs
0822dc01f68eb262274fbedcf97a224e6457ff3b
<ide><path>activesupport/lib/active_support/core_ext/string/access.rb <ide> def from(position) <ide> self[position..-1] <ide> end <ide> <del> # Returns the beginning of the string up to position. If the position is <del> # negative, it is counted from the end of the string. <add> # Returns a substring from the beginning of the string to the given position. <add> # If the position is negative, it is counted from the end of the string. <ide> # <ide> # str = "hello" <ide> # str.to(0) #=> "h"
1
Text
Text
update readme to remove .nspid
2f35f8e2a88a378d7ff8eacf5346f9711a59489a
<ide><path>pkg/libcontainer/README.md <ide> nsinit exec /bin/bash <ide> If you wish to spawn another process inside the container while your current bash session is <ide> running just run the exact same command again to get another bash shell or change the command. If the original process dies, PID 1, all other processes spawned inside the container will also be killed and the namespace will be removed. <ide> <del>You can identify if a process is running in a container by looking to see if `.nspid` is in the root of the directory. <add>You can identify if a process is running in a container by looking to see if `pid` is in the root of the directory.
1
Text
Text
correct globalid mixin name in the guides
79e5c0de6d87a7957889a0ff1fe9063337e627a2
<ide><path>guides/source/active_job_basics.md <ide> class TrashableCleanupJob <ide> end <ide> ``` <ide> <del>This works with any class that mixes in `ActiveModel::GlobalIdentification`, which <add>This works with any class that mixes in `GlobalID::Identification`, which <ide> by default has been mixed into Active Model classes. <ide> <ide>
1
PHP
PHP
fix form populating with array names
02b8a36cb846a12493acee332ac6019069a5ebe1
<ide><path>src/Illuminate/Html/FormBuilder.php <ide> protected function getCheckedState($type, $name, $value, $checked) <ide> switch ($type) <ide> { <ide> case 'checkbox': <del> return $this->getCheckboxCheckedState($name, $checked); <add> return $this->getCheckboxCheckedState($name, $value, $checked); <ide> <ide> case 'radio': <ide> return $this->getRadioCheckedState($name, $value, $checked); <ide> protected function getCheckedState($type, $name, $value, $checked) <ide> * @param bool $checked <ide> * @return bool <ide> */ <del> protected function getCheckboxCheckedState($name, $checked) <add> protected function getCheckboxCheckedState($name, $value, $checked) <ide> { <ide> if ( ! $this->oldInputIsEmpty() and is_null($this->old($name))) return false; <ide> <ide> if ($this->missingOldAndModel($name)) return $checked; <ide> <del> return (bool) $this->getValueAttribute($name); <add> $valueAttribute = $this->getValueAttribute($name); <add> <add> if (is_array($valueAttribute)) return in_array($value, $valueAttribute); <add> <add> return (bool) $valueAttribute; <ide> } <ide> <ide> /** <ide> public function getValueAttribute($name, $value = null) <ide> { <ide> if (is_null($name)) return $value; <ide> <del> if (isset($this->session) and $this->session->hasOldInput($name)) <add> if ( ! is_null($this->old($name))) <ide> { <del> return $this->session->getOldInput($name); <add> return $this->old($name); <ide> } <ide> <ide> if ( ! is_null($value)) return $value; <ide> <del> if (isset($this->model) and isset($this->model[$name])) <add> if (isset($this->model)) <ide> { <ide> return $this->getModelValueAttribute($name); <ide> } <ide> protected function getModelValueAttribute($name) <ide> { <ide> if (is_object($this->model)) <ide> { <del> return object_get($this->model, $name); <add> return object_get($this->model, $this->transformKey($name)); <ide> } <ide> elseif (is_array($this->model)) <ide> { <del> return array_get($this->model, $name); <add> return array_get($this->model, $this->transformKey($name)); <ide> } <ide> } <ide> <ide> public function old($name) <ide> { <ide> if (isset($this->session)) <ide> { <del> return $this->session->getOldInput($name); <add> return $this->session->getOldInput($this->transformKey($name)); <ide> } <ide> } <ide> <ide> public function oldInputIsEmpty() <ide> return (isset($this->session) and count($this->session->getOldInput()) == 0); <ide> } <ide> <add> /** <add> * Transform key from array to dot syntax. <add> * <add> * @param string $key <add> * @return string <add> */ <add> protected function transformKey($key) <add> { <add> return str_replace(array('.', '[]', '[', ']'), array('_', '', '.', ''), $key); <add> } <add> <ide> /** <ide> * Get the session store implementation. <ide> *
1
Mixed
Python
add densenet models
caf05b43d1eed9f77c8b220be57f7bfd878abb76
<ide><path>docs/templates/applications.md <ide> Weights are downloaded automatically when instantiating a model. They are stored <ide> - [InceptionV3](#inceptionv3) <ide> - [InceptionResNetV2](#inceptionresnetv2) <ide> - [MobileNet](#mobilenet) <add>- [DenseNet](#densenet) <ide> - [NASNet](#nasnet) <ide> <ide> All of these architectures (except Xception and MobileNet) are compatible with both TensorFlow and Theano, and upon instantiation the models will be built according to the image data format set in your Keras configuration file at `~/.keras/keras.json`. For instance, if you have set `image_data_format=channels_last`, then any model loaded from this repository will get built according to the TensorFlow data format convention, "Height-Width-Depth". <ide> model = InceptionV3(input_tensor=input_tensor, weights='imagenet', include_top=T <ide> | [InceptionV3](#inceptionv3) | 92 MB | 0.788 | 0.944 | 23,851,784 | 159 | <ide> | [InceptionResNetV2](#inceptionresnetv2) | 215 MB | 0.804 | 0.953 | 55,873,736 | 572 | <ide> | [MobileNet](#mobilenet) | 17 MB | 0.665 | 0.871 | 4,253,864 | 88 <add>| [DenseNet121](#densenet) | 33 MB | 0.745 | 0.918 | 8,062,504 | 121 <add>| [DenseNet169](#densenet) | 57 MB | 0.759 | 0.928 | 14,307,880 | 169 <add>| [DenseNet201](#densenet) | 80 MB | 0.770 | 0.933 | 20,242,984 | 201 <ide> <ide> <ide> The top-1 and top-5 accuracy refers to the model's performance on the ImageNet validation dataset. <ide> These weights are released under [the Apache License](https://github.com/tensorf <ide> <ide> ----- <ide> <add>## DenseNet <add> <add> <add>```python <add>keras.applications.densenet.DenseNet121(include_top=True, weights='imagenet', input_tensor=None, input_shape=None, pooling=None, classes=1000) <add>keras.applications.densenet.DenseNet169(include_top=True, weights='imagenet', input_tensor=None, input_shape=None, pooling=None, classes=1000) <add>keras.applications.densenet.DenseNet201(include_top=True, weights='imagenet', input_tensor=None, input_shape=None, pooling=None, classes=1000) <add>``` <add> <add>Optionally loads weights pre-trained <add>on ImageNet. Note that when using TensorFlow, <add>for best performance you should set <add>`image_data_format='channels_last'` in your Keras config <add>at ~/.keras/keras.json. <add> <add>The model and the weights are compatible with <add>TensorFlow, Theano, and CNTK. The data format <add>convention used by the model is the one <add>specified in your Keras config file. <add> <add>### Arguments <add> <add>- blocks: numbers of building blocks for the four dense layers. <add>- include_top: whether to include the fully-connected <add> layer at the top of the network. <add>- weights: one of `None` (random initialization), <add> 'imagenet' (pre-training on ImageNet), <add> or the path to the weights file to be loaded. <add>- input_tensor: optional Keras tensor (i.e. output of `layers.Input()`) <add> to use as image input for the model. <add>- input_shape: optional shape tuple, only to be specified <add> if `include_top` is False (otherwise the input shape <add> has to be `(224, 224, 3)` (with `channels_last` data format) <add> or `(3, 224, 224)` (with `channels_first` data format). <add> It should have exactly 3 inputs channels. <add>- pooling: optional pooling mode for feature extraction <add> when `include_top` is `False`. <add> - `None` means that the output of the model will be <add> the 4D tensor output of the <add> last convolutional layer. <add> - `avg` means that global average pooling <add> will be applied to the output of the <add> last convolutional layer, and thus <add> the output of the model will be a 2D tensor. <add> - `max` means that global max pooling will <add> be applied. <add>- classes: optional number of classes to classify images <add> into, only to be specified if `include_top` is True, and <add> if no `weights` argument is specified. <add> <add>### Returns <add> <add>A Keras model instance. <add> <add>### References <add> <add>- [Densely Connected Convolutional Networks](https://arxiv.org/abs/1608.06993) (CVPR 2017 Best Paper Award) <add> <add>### License <add> <add>These weights are released under [the BSD 3-clause License](https://github.com/liuzhuang13/DenseNet/blob/master/LICENSE). <add> <add>----- <add> <ide> ## NASNet <ide> <ide> <ide><path>keras/applications/__init__.py <ide> from .inception_resnet_v2 import InceptionResNetV2 <ide> from .xception import Xception <ide> from .mobilenet import MobileNet <add>from .densenet import DenseNet121, DenseNet169, DenseNet201 <ide> from .nasnet import NASNetMobile, NASNetLarge <ide><path>keras/applications/densenet.py <add># -*- coding: utf-8 -*- <add>"""DenseNet models for Keras. <add> <add># Reference paper: <add> <add>- [Densely Connected Convolutional Networks](https://arxiv.org/abs/1608.06993) (CVPR 2017 Best Paper Award) <add> <add># Reference implementation: <add> <add>- [Torch DenseNets](https://github.com/liuzhuang13/DenseNet/blob/master/models/densenet.lua) <add>- [TensorNets](https://github.com/taehoonlee/tensornets/blob/master/tensornets/densenets.py) <add>""" <add>from __future__ import print_function <add>from __future__ import absolute_import <add> <add>import os <add> <add>from .. import backend as K <add>from ..models import Model <add>from ..layers import Activation <add>from ..layers import AveragePooling2D <add>from ..layers import BatchNormalization <add>from ..layers import Concatenate <add>from ..layers import Conv2D <add>from ..layers import Dense <add>from ..layers import Flatten <add>from ..layers import GlobalAveragePooling2D <add>from ..layers import Input <add>from ..layers import MaxPooling2D <add>from ..layers import ZeroPadding2D <add>from ..utils.data_utils import get_file <add>from ..engine.topology import get_source_inputs <add>from . import imagenet_utils <add>from .imagenet_utils import decode_predictions <add>from .imagenet_utils import _obtain_input_shape <add> <add> <add>DENSENET121_WEIGHT_PATH = 'https://github.com/taehoonlee/deep-learning-models/releases/download/densenet/densenet121_weights_tf_dim_ordering_tf_kernels.h5' <add>DENSENET121_WEIGHT_PATH_NO_TOP = 'https://github.com/taehoonlee/deep-learning-models/releases/download/densenet/densenet121_weights_tf_dim_ordering_tf_kernels_notop.h5' <add>DENSENET169_WEIGHT_PATH = 'https://github.com/taehoonlee/deep-learning-models/releases/download/densenet/densenet169_weights_tf_dim_ordering_tf_kernels.h5' <add>DENSENET169_WEIGHT_PATH_NO_TOP = 'https://github.com/taehoonlee/deep-learning-models/releases/download/densenet/densenet169_weights_tf_dim_ordering_tf_kernels_notop.h5' <add>DENSENET201_WEIGHT_PATH = 'https://github.com/taehoonlee/deep-learning-models/releases/download/densenet/densenet201_weights_tf_dim_ordering_tf_kernels.h5' <add>DENSENET201_WEIGHT_PATH_NO_TOP = 'https://github.com/taehoonlee/deep-learning-models/releases/download/densenet/densenet201_weights_tf_dim_ordering_tf_kernels_notop.h5' <add> <add> <add>def dense_block(x, blocks, name): <add> """A dense block. <add> <add> # Arguments <add> x: input tensor. <add> blocks: integer, the number of building blocks. <add> name: string, block label. <add> <add> # Returns <add> output tensor for the block. <add> """ <add> for i in range(blocks): <add> x = conv_block(x, 32, name=name + '_block' + str(i + 1)) <add> return x <add> <add> <add>def transition_block(x, reduction, name): <add> """A transition block. <add> <add> # Arguments <add> x: input tensor. <add> reduction: float, compression rate at transition layers. <add> name: string, block label. <add> <add> # Returns <add> output tensor for the block. <add> """ <add> bn_axis = 3 if K.image_data_format() == 'channels_last' else 1 <add> x = BatchNormalization(axis=bn_axis, epsilon=1.001e-5, <add> name=name + '_bn')(x) <add> x = Activation('relu', name=name + '_relu')(x) <add> x = Conv2D(int(x._keras_shape[bn_axis] * reduction), 1, use_bias=False, <add> name=name + '_conv')(x) <add> x = AveragePooling2D(2, strides=2, name=name + '_pool')(x) <add> return x <add> <add> <add>def conv_block(x, growth_rate, name): <add> """A building block for a dense block. <add> <add> # Arguments <add> x: input tensor. <add> growth_rate: float, growth rate at dense layers. <add> name: string, block label. <add> <add> # Returns <add> output tensor for the block. <add> """ <add> bn_axis = 3 if K.image_data_format() == 'channels_last' else 1 <add> x1 = BatchNormalization(axis=bn_axis, epsilon=1.001e-5, <add> name=name + '_0_bn')(x) <add> x1 = Activation('relu', name=name + '_0_relu')(x1) <add> x1 = Conv2D(4 * growth_rate, 1, use_bias=False, <add> name=name + '_1_conv')(x1) <add> x1 = BatchNormalization(axis=bn_axis, epsilon=1.001e-5, <add> name=name + '_1_bn')(x1) <add> x1 = Activation('relu', name=name + '_1_relu')(x1) <add> x1 = Conv2D(growth_rate, 3, padding='same', use_bias=False, <add> name=name + '_2_conv')(x1) <add> x = Concatenate(axis=bn_axis, name=name + '_concat')([x, x1]) <add> return x <add> <add> <add>def DenseNet(blocks, <add> include_top=True, <add> weights='imagenet', <add> input_tensor=None, <add> input_shape=None, <add> pooling=None, <add> classes=1000): <add> """Instantiates the DenseNet architecture. <add> <add> Optionally loads weights pre-trained <add> on ImageNet. Note that when using TensorFlow, <add> for best performance you should set <add> `image_data_format='channels_last'` in your Keras config <add> at ~/.keras/keras.json. <add> <add> The model and the weights are compatible with <add> TensorFlow, Theano, and CNTK. The data format <add> convention used by the model is the one <add> specified in your Keras config file. <add> <add> # Arguments <add> blocks: numbers of building blocks for the four dense layers. <add> include_top: whether to include the fully-connected <add> layer at the top of the network. <add> weights: one of `None` (random initialization), <add> 'imagenet' (pre-training on ImageNet), <add> or the path to the weights file to be loaded. <add> input_tensor: optional Keras tensor (i.e. output of `layers.Input()`) <add> to use as image input for the model. <add> input_shape: optional shape tuple, only to be specified <add> if `include_top` is False (otherwise the input shape <add> has to be `(224, 224, 3)` (with `channels_last` data format) <add> or `(3, 224, 224)` (with `channels_first` data format). <add> It should have exactly 3 inputs channels. <add> pooling: optional pooling mode for feature extraction <add> when `include_top` is `False`. <add> - `None` means that the output of the model will be <add> the 4D tensor output of the <add> last convolutional layer. <add> - `avg` means that global average pooling <add> will be applied to the output of the <add> last convolutional layer, and thus <add> the output of the model will be a 2D tensor. <add> - `max` means that global max pooling will <add> be applied. <add> classes: optional number of classes to classify images <add> into, only to be specified if `include_top` is True, and <add> if no `weights` argument is specified. <add> <add> # Returns <add> A Keras model instance. <add> <add> # Raises <add> ValueError: in case of invalid argument for `weights`, <add> or invalid input shape. <add> """ <add> if not (weights in {'imagenet', None} or os.path.exists(weights)): <add> raise ValueError('The `weights` argument should be either ' <add> '`None` (random initialization), `imagenet` ' <add> '(pre-training on ImageNet), ' <add> 'or the path to the weights file to be loaded.') <add> <add> if weights == 'imagenet' and include_top and classes != 1000: <add> raise ValueError('If using `weights` as imagenet with `include_top`' <add> ' as true, `classes` should be 1000') <add> <add> # Determine proper input shape <add> input_shape = _obtain_input_shape(input_shape, <add> default_size=224, <add> min_size=221, <add> data_format=K.image_data_format(), <add> require_flatten=include_top, <add> weights=weights) <add> <add> if input_tensor is None: <add> img_input = Input(shape=input_shape) <add> else: <add> if not K.is_keras_tensor(input_tensor): <add> img_input = Input(tensor=input_tensor, shape=input_shape) <add> else: <add> img_input = input_tensor <add> <add> bn_axis = 3 if K.image_data_format() == 'channels_last' else 1 <add> <add> x = ZeroPadding2D(padding=((3, 3), (3, 3)))(img_input) <add> x = Conv2D(64, 7, strides=2, use_bias=False, name='conv1/conv')(x) <add> x = BatchNormalization(axis=bn_axis, epsilon=1.001e-5, <add> name='conv1/bn')(x) <add> x = Activation('relu', name='conv1/relu')(x) <add> x = ZeroPadding2D(padding=((1, 1), (1, 1)))(x) <add> x = MaxPooling2D(3, strides=2, name='pool1')(x) <add> <add> x = dense_block(x, blocks[0], name='conv2') <add> x = transition_block(x, 0.5, name='pool2') <add> x = dense_block(x, blocks[1], name='conv3') <add> x = transition_block(x, 0.5, name='pool3') <add> x = dense_block(x, blocks[2], name='conv4') <add> x = transition_block(x, 0.5, name='pool4') <add> x = dense_block(x, blocks[3], name='conv5') <add> <add> x = BatchNormalization(axis=bn_axis, epsilon=1.001e-5, <add> name='bn')(x) <add> <add> if include_top: <add> x = GlobalAveragePooling2D(name='avg_pool')(x) <add> x = Dense(classes, activation='softmax', name='fc1000')(x) <add> else: <add> if pooling == 'avg': <add> x = AveragePooling2D(7, name='avg_pool')(x) <add> elif pooling == 'max': <add> x = MaxPooling2D(7, name='max_pool')(x) <add> <add> # Ensure that the model takes into account <add> # any potential predecessors of `input_tensor`. <add> if input_tensor is not None: <add> inputs = get_source_inputs(input_tensor) <add> else: <add> inputs = img_input <add> <add> # Create model. <add> if blocks == [6, 12, 24, 16]: <add> model = Model(inputs, x, name='densenet121') <add> elif blocks == [6, 12, 32, 32]: <add> model = Model(inputs, x, name='densenet169') <add> elif blocks == [6, 12, 48, 32]: <add> model = Model(inputs, x, name='densenet201') <add> else: <add> model = Model(inputs, x, name='densenet') <add> <add> # Load weights. <add> if weights == 'imagenet': <add> if include_top: <add> if blocks == [6, 12, 24, 16]: <add> weights_path = get_file( <add> 'densenet121_weights_tf_dim_ordering_tf_kernels.h5', <add> DENSENET121_WEIGHT_PATH, <add> cache_subdir='models', <add> file_hash='0962ca643bae20f9b6771cb844dca3b0') <add> elif blocks == [6, 12, 32, 32]: <add> weights_path = get_file( <add> 'densenet169_weights_tf_dim_ordering_tf_kernels.h5', <add> DENSENET169_WEIGHT_PATH, <add> cache_subdir='models', <add> file_hash='bcf9965cf5064a5f9eb6d7dc69386f43') <add> elif blocks == [6, 12, 48, 32]: <add> weights_path = get_file( <add> 'densenet201_weights_tf_dim_ordering_tf_kernels.h5', <add> DENSENET201_WEIGHT_PATH, <add> cache_subdir='models', <add> file_hash='7bb75edd58cb43163be7e0005fbe95ef') <add> else: <add> if blocks == [6, 12, 24, 16]: <add> weights_path = get_file( <add> 'densenet121_weights_tf_dim_ordering_tf_kernels_notop.h5', <add> DENSENET121_WEIGHT_PATH_NO_TOP, <add> cache_subdir='models', <add> file_hash='4912a53fbd2a69346e7f2c0b5ec8c6d3') <add> elif blocks == [6, 12, 32, 32]: <add> weights_path = get_file( <add> 'densenet169_weights_tf_dim_ordering_tf_kernels_notop.h5', <add> DENSENET169_WEIGHT_PATH_NO_TOP, <add> cache_subdir='models', <add> file_hash='50662582284e4cf834ce40ab4dfa58c6') <add> elif blocks == [6, 12, 48, 32]: <add> weights_path = get_file( <add> 'densenet201_weights_tf_dim_ordering_tf_kernels_notop.h5', <add> DENSENET201_WEIGHT_PATH_NO_TOP, <add> cache_subdir='models', <add> file_hash='1c2de60ee40562448dbac34a0737e798') <add> model.load_weights(weights_path) <add> elif weights is not None: <add> model.load_weights(weights) <add> <add> return model <add> <add> <add>def DenseNet121(include_top=True, <add> weights='imagenet', <add> input_tensor=None, <add> input_shape=None, <add> pooling=None, <add> classes=1000): <add> return DenseNet([6, 12, 24, 16], <add> include_top, weights, <add> input_tensor, input_shape, <add> pooling, classes) <add> <add> <add>def DenseNet169(include_top=True, <add> weights='imagenet', <add> input_tensor=None, <add> input_shape=None, <add> pooling=None, <add> classes=1000): <add> return DenseNet([6, 12, 32, 32], <add> include_top, weights, <add> input_tensor, input_shape, <add> pooling, classes) <add> <add> <add>def DenseNet201(include_top=True, <add> weights='imagenet', <add> input_tensor=None, <add> input_shape=None, <add> pooling=None, <add> classes=1000): <add> return DenseNet([6, 12, 48, 32], <add> include_top, weights, <add> input_tensor, input_shape, <add> pooling, classes) <add> <add> <add>def preprocess_input(x, data_format=None): <add> """Preprocesses a numpy array encoding a batch of images. <add> <add> # Arguments <add> x: a 3D or 4D numpy array consists of RGB values within [0, 255]. <add> data_format: data format of the image tensor. <add> <add> # Returns <add> Preprocessed array. <add> """ <add> return imagenet_utils.preprocess_input(x, data_format, mode='torch') <add> <add> <add>setattr(DenseNet121, '__doc__', DenseNet.__doc__) <add>setattr(DenseNet169, '__doc__', DenseNet.__doc__) <add>setattr(DenseNet201, '__doc__', DenseNet.__doc__) <ide><path>keras/applications/imagenet_utils.py <ide> def _preprocess_numpy_input(x, data_format, mode): <ide> x -= 1. <ide> return x <ide> <add> if mode == 'torch': <add> x /= 255. <add> mean = [0.485, 0.456, 0.406] <add> std = [0.229, 0.224, 0.225] <add> else: <add> if data_format == 'channels_first': <add> # 'RGB'->'BGR' <add> if x.ndim == 3: <add> x = x[::-1, ...] <add> else: <add> x = x[:, ::-1, ...] <add> else: <add> # 'RGB'->'BGR' <add> x = x[..., ::-1] <add> mean = [103.939, 116.779, 123.68] <add> std = None <add> <add> # Zero-center by mean pixel <ide> if data_format == 'channels_first': <ide> if x.ndim == 3: <del> # 'RGB'->'BGR' <del> x = x[::-1, ...] <del> # Zero-center by mean pixel <del> x[0, :, :] -= 103.939 <del> x[1, :, :] -= 116.779 <del> x[2, :, :] -= 123.68 <add> x[0, :, :] -= mean[0] <add> x[1, :, :] -= mean[1] <add> x[2, :, :] -= mean[2] <add> if std is not None: <add> x[0, :, :] /= std[0] <add> x[1, :, :] /= std[1] <add> x[2, :, :] /= std[2] <ide> else: <del> x = x[:, ::-1, ...] <del> x[:, 0, :, :] -= 103.939 <del> x[:, 1, :, :] -= 116.779 <del> x[:, 2, :, :] -= 123.68 <add> x[:, 0, :, :] -= mean[0] <add> x[:, 1, :, :] -= mean[1] <add> x[:, 2, :, :] -= mean[2] <add> if std is not None: <add> x[:, 0, :, :] /= std[0] <add> x[:, 1, :, :] /= std[1] <add> x[:, 2, :, :] /= std[2] <ide> else: <del> # 'RGB'->'BGR' <del> x = x[..., ::-1] <del> # Zero-center by mean pixel <del> x[..., 0] -= 103.939 <del> x[..., 1] -= 116.779 <del> x[..., 2] -= 123.68 <add> x[..., 0] -= mean[0] <add> x[..., 1] -= mean[1] <add> x[..., 2] -= mean[2] <add> if std is not None: <add> x[..., 0] /= std[0] <add> x[..., 1] /= std[1] <add> x[..., 2] /= std[2] <ide> return x <ide> <ide> <ide> def _preprocess_symbolic_input(x, data_format, mode): <ide> x -= 1. <ide> return x <ide> <del> if data_format == 'channels_first': <del> # 'RGB'->'BGR' <del> if K.ndim(x) == 3: <del> x = x[::-1, ...] <del> else: <del> x = x[:, ::-1, ...] <add> if mode == 'torch': <add> x /= 255. <add> mean = [0.485, 0.456, 0.406] <add> std = [0.229, 0.224, 0.225] <ide> else: <del> # 'RGB'->'BGR' <del> x = x[..., ::-1] <add> if data_format == 'channels_first': <add> # 'RGB'->'BGR' <add> if K.ndim(x) == 3: <add> x = x[::-1, ...] <add> else: <add> x = x[:, ::-1, ...] <add> else: <add> # 'RGB'->'BGR' <add> x = x[..., ::-1] <add> mean = [103.939, 116.779, 123.68] <add> std = None <ide> <ide> if _IMAGENET_MEAN is None: <del> _IMAGENET_MEAN = K.constant(-np.array([103.939, 116.779, 123.68])) <add> _IMAGENET_MEAN = K.constant(-np.array(mean)) <add> <ide> # Zero-center by mean pixel <ide> if K.dtype(x) != K.dtype(_IMAGENET_MEAN): <ide> x = K.bias_add(x, K.cast(_IMAGENET_MEAN, K.dtype(x)), data_format) <ide> else: <ide> x = K.bias_add(x, _IMAGENET_MEAN, data_format) <add> if std is not None: <add> x /= std <ide> return x <ide> <ide> <ide><path>tests/keras/applications/applications_test.py <ide> def test_mobilenet_image_size(): <ide> model = applications.MobileNet(input_shape=invalid_image_shape, weights='imagenet', include_top=True) <ide> <ide> <add>@keras_test <add>@pytest.mark.parametrize('fun', [ <add> applications.DenseNet121, <add> applications.DenseNet169, <add> applications.DenseNet201], <add> ids=['DenseNet121', 'DenseNet169', 'DenseNet201']) <add>def test_densenet(fun): <add> model = fun(weights=None) <add> assert model.output_shape == (None, 1000) <add> <add> <add>@keras_test <add>@pytest.mark.parametrize('fun,dim', [ <add> (applications.DenseNet121, 1024), <add> (applications.DenseNet169, 1664), <add> (applications.DenseNet201, 1920)], <add> ids=['DenseNet121', 'DenseNet169', 'DenseNet201']) <add>def test_densenet_no_top(fun, dim): <add> model = fun(weights=None, include_top=False) <add> assert model.output_shape == (None, None, None, dim) <add> <add> <add>@keras_test <add>@pytest.mark.parametrize('fun,dim', [ <add> (applications.DenseNet121, 1024), <add> (applications.DenseNet169, 1664), <add> (applications.DenseNet201, 1920)], <add> ids=['DenseNet121', 'DenseNet169', 'DenseNet201']) <add>def test_densenet_pooling(fun, dim): <add> model = fun(weights=None, include_top=False, pooling='avg') <add> assert model.output_shape == (None, None, None, dim) <add> <add> <add>@keras_test <add>@pytest.mark.parametrize('fun,dim', [ <add> (applications.DenseNet121, 1024), <add> (applications.DenseNet169, 1664), <add> (applications.DenseNet201, 1920)], <add> ids=['DenseNet121', 'DenseNet169', 'DenseNet201']) <add>def test_densenet_variable_input_channels(fun, dim): <add> input_shape = (1, None, None) if K.image_data_format() == 'channels_first' else (None, None, 1) <add> model = fun(weights=None, include_top=False, input_shape=input_shape) <add> assert model.output_shape == (None, None, None, dim) <add> <add> input_shape = (4, None, None) if K.image_data_format() == 'channels_first' else (None, None, 4) <add> model = fun(weights=None, include_top=False, input_shape=input_shape) <add> assert model.output_shape == (None, None, None, dim) <add> <add> <ide> @keras_test <ide> @pytest.mark.skipif((K.backend() != 'tensorflow'), <ide> reason='NASNets are supported only on TensorFlow')
5
Javascript
Javascript
fix package resolution for edge case
34e3dd50348dd824c881c183824237532c7721c5
<ide><path>lib/internal/modules/cjs/loader.js <ide> function trySelf(parentPath, request) { <ide> try { <ide> return finalizeEsmResolution(packageExportsResolve( <ide> pathToFileURL(pkgPath + '/package.json'), expansion, pkg, <del> pathToFileURL(parentPath), cjsConditions).resolved, parentPath, pkgPath); <add> pathToFileURL(parentPath), cjsConditions), parentPath, pkgPath); <ide> } catch (e) { <ide> if (e.code === 'ERR_MODULE_NOT_FOUND') <ide> throw createEsmNotFoundErr(request, pkgPath + '/package.json'); <ide> function resolveExports(nmPath, request) { <ide> try { <ide> return finalizeEsmResolution(packageExportsResolve( <ide> pathToFileURL(pkgPath + '/package.json'), '.' + expansion, pkg, null, <del> cjsConditions).resolved, null, pkgPath); <add> cjsConditions), null, pkgPath); <ide> } catch (e) { <ide> if (e.code === 'ERR_MODULE_NOT_FOUND') <ide> throw createEsmNotFoundErr(request, pkgPath + '/package.json'); <ide><path>lib/internal/modules/esm/get_format.js <ide> const legacyExtensionFormatMap = { <ide> '.node': 'commonjs' <ide> }; <ide> <add>let experimentalSpecifierResolutionWarned = false; <add> <ide> if (experimentalWasmModules) <ide> extensionFormatMap['.wasm'] = legacyExtensionFormatMap['.wasm'] = 'wasm'; <ide> <ide> const protocolHandlers = ObjectAssign(ObjectCreate(null), { <ide> <ide> return format; <ide> }, <del> 'file:'(parsed, url) { <del> const ext = extname(parsed.pathname); <del> let format; <del> <del> if (ext === '.js') { <del> format = getPackageType(parsed.href) === 'module' ? 'module' : 'commonjs'; <del> } else { <del> format = extensionFormatMap[ext]; <del> } <del> if (!format) { <del> if (experimentalSpecifierResolution === 'node') { <del> process.emitWarning( <del> 'The Node.js specifier resolution in ESM is experimental.', <del> 'ExperimentalWarning'); <del> format = legacyExtensionFormatMap[ext]; <del> } else { <del> throw new ERR_UNKNOWN_FILE_EXTENSION(ext, fileURLToPath(url)); <del> } <del> } <del> <del> return format || null; <del> }, <add> 'file:': getFileProtocolModuleFormat, <ide> 'node:'() { return 'builtin'; }, <ide> }); <ide> <del>function defaultGetFormat(url, context) { <add>function getLegacyExtensionFormat(ext) { <add> if ( <add> experimentalSpecifierResolution === 'node' && <add> !experimentalSpecifierResolutionWarned <add> ) { <add> process.emitWarning( <add> 'The Node.js specifier resolution in ESM is experimental.', <add> 'ExperimentalWarning'); <add> experimentalSpecifierResolutionWarned = true; <add> } <add> return legacyExtensionFormatMap[ext]; <add>} <add> <add>function getFileProtocolModuleFormat(url, ignoreErrors) { <add> const ext = extname(url.pathname); <add> if (ext === '.js') { <add> return getPackageType(url) === 'module' ? 'module' : 'commonjs'; <add> } <add> <add> const format = extensionFormatMap[ext]; <add> if (format) return format; <add> if (experimentalSpecifierResolution !== 'node') { <add> // Explicit undefined return indicates load hook should rerun format check <add> if (ignoreErrors) <add> return undefined; <add> throw new ERR_UNKNOWN_FILE_EXTENSION(ext, fileURLToPath(url)); <add> } <add> return getLegacyExtensionFormat(ext) ?? null; <add>} <add> <add>function defaultGetFormatWithoutErrors(url, context) { <ide> const parsed = new URL(url); <add> if (!ObjectPrototypeHasOwnProperty(protocolHandlers, parsed.protocol)) <add> return null; <add> return protocolHandlers[parsed.protocol](parsed, true); <add>} <ide> <add>function defaultGetFormat(url, context) { <add> const parsed = new URL(url); <ide> return ObjectPrototypeHasOwnProperty(protocolHandlers, parsed.protocol) ? <del> protocolHandlers[parsed.protocol](parsed, url) : <add> protocolHandlers[parsed.protocol](parsed, false) : <ide> null; <ide> } <ide> <ide> module.exports = { <ide> defaultGetFormat, <add> defaultGetFormatWithoutErrors, <ide> extensionFormatMap, <ide> legacyExtensionFormatMap, <ide> }; <ide><path>lib/internal/modules/esm/load.js <ide> <ide> const { defaultGetFormat } = require('internal/modules/esm/get_format'); <ide> const { defaultGetSource } = require('internal/modules/esm/get_source'); <del>const { translators } = require('internal/modules/esm/translators'); <ide> const { validateAssertions } = require('internal/modules/esm/assert'); <ide> <ide> /** <ide> async function defaultLoad(url, context) { <ide> } = context; <ide> const { importAssertions } = context; <ide> <del> if (!format || !translators.has(format)) { <add> if (format == null) { <ide> format = defaultGetFormat(url); <ide> } <ide> <ide><path>lib/internal/modules/esm/resolve.js <ide> function emitTrailingSlashPatternDeprecation(match, pjsonUrl, base) { <ide> * @returns {void} <ide> */ <ide> function emitLegacyIndexDeprecation(url, packageJSONUrl, base, main) { <del> const format = defaultGetFormat(url); <add> const format = defaultGetFormatWithoutErrors(url); <ide> if (format !== 'module') <ide> return; <ide> const path = fileURLToPath(url); <ide> const patternRegEx = /\*/g; <ide> function resolvePackageTargetString( <ide> target, subpath, match, packageJSONUrl, base, pattern, internal, conditions) { <ide> <del> const composeResult = (resolved) => { <del> let format; <del> try { <del> format = getPackageType(resolved); <del> } catch (err) { <del> if (err.code === 'ERR_INVALID_FILE_URL_PATH') { <del> const invalidModuleErr = new ERR_INVALID_MODULE_SPECIFIER( <del> resolved, 'must not include encoded "/" or "\\" characters', base); <del> invalidModuleErr.cause = err; <del> throw invalidModuleErr; <del> } <del> throw err; <del> } <del> return { resolved, ...(format !== 'none') && { format } }; <del> }; <del> <ide> if (subpath !== '' && !pattern && target[target.length - 1] !== '/') <ide> throwInvalidPackageTarget(match, target, packageJSONUrl, internal, base); <ide> <ide> function resolvePackageTargetString( <ide> if (!StringPrototypeStartsWith(resolvedPath, packagePath)) <ide> throwInvalidPackageTarget(match, target, packageJSONUrl, internal, base); <ide> <del> if (subpath === '') return composeResult(resolved); <add> if (subpath === '') return resolved; <ide> <ide> if (RegExpPrototypeTest(invalidSegmentRegEx, subpath)) { <ide> const request = pattern ? <ide> function resolvePackageTargetString( <ide> } <ide> <ide> if (pattern) { <del> return composeResult(new URL(RegExpPrototypeSymbolReplace(patternRegEx, <del> resolved.href, <del> () => subpath))); <add> return new URL( <add> RegExpPrototypeSymbolReplace( <add> patternRegEx, <add> resolved.href, <add> () => subpath <add> ) <add> ); <ide> } <ide> <del> return composeResult(new URL(subpath, resolved)); <add> return new URL(subpath, resolved); <ide> } <ide> <ide> /** <ide> function packageImportsResolve(name, base, conditions) { <ide> packageJSONUrl, imports[name], '', name, base, false, true, conditions <ide> ); <ide> if (resolveResult != null) { <del> return resolveResult.resolved; <add> return resolveResult; <ide> } <ide> } else { <ide> let bestMatch = ''; <ide> function packageImportsResolve(name, base, conditions) { <ide> bestMatch, base, true, <ide> true, conditions); <ide> if (resolveResult != null) { <del> return resolveResult.resolved; <add> return resolveResult; <ide> } <ide> } <ide> } <ide> function parsePackageName(specifier, base) { <ide> */ <ide> function packageResolve(specifier, base, conditions) { <ide> if (NativeModule.canBeRequiredByUsers(specifier)) <del> return { resolved: new URL('node:' + specifier) }; <add> return new URL('node:' + specifier); <ide> <ide> const { packageName, packageSubpath, isScoped } = <ide> parsePackageName(specifier, base); <ide> function packageResolve(specifier, base, conditions) { <ide> packageJSONUrl, packageSubpath, packageConfig, base, conditions); <ide> } <ide> if (packageSubpath === '.') { <del> return { <del> resolved: legacyMainResolve( <del> packageJSONUrl, <del> packageConfig, <del> base), <del> ...(packageConfig.type !== 'none') && { format: packageConfig.type } <del> }; <add> return legacyMainResolve( <add> packageJSONUrl, <add> packageConfig, <add> base <add> ); <ide> } <ide> <del> return { <del> resolved: new URL(packageSubpath, packageJSONUrl), <del> ...(packageConfig.type !== 'none') && { format: packageConfig.type } <del> }; <add> return new URL(packageSubpath, packageJSONUrl); <ide> // Cross-platform root check. <ide> } while (packageJSONPath.length !== lastPath.length); <ide> <ide> function moduleResolve(specifier, base, conditions, preserveSymlinks) { <ide> // Order swapped from spec for minor perf gain. <ide> // Ok since relative URLs cannot parse as URLs. <ide> let resolved; <del> let format; <ide> if (shouldBeTreatedAsRelativeOrAbsolutePath(specifier)) { <ide> resolved = new URL(specifier, base); <ide> } else if (specifier[0] === '#') { <ide> function moduleResolve(specifier, base, conditions, preserveSymlinks) { <ide> try { <ide> resolved = new URL(specifier); <ide> } catch { <del> ({ resolved, format } = packageResolve(specifier, base, conditions)); <add> resolved = packageResolve(specifier, base, conditions); <ide> } <ide> } <ide> if (resolved.protocol !== 'file:') { <del> return { <del> url: resolved <del> }; <add> return resolved; <ide> } <del> <del> return { <del> url: finalizeResolution(resolved, base, preserveSymlinks), <del> ...(format != null) && { format } <del> }; <add> return finalizeResolution(resolved, base, preserveSymlinks); <ide> } <ide> <ide> /** <ide> function resolveAsCommonJS(specifier, parentURL) { <ide> } <ide> } <ide> <add>function throwIfUnsupportedURLProtocol(url) { <add> if (url.protocol !== 'file:' && url.protocol !== 'data:' && <add> url.protocol !== 'node:') { <add> throw new ERR_UNSUPPORTED_ESM_URL_SCHEME(url); <add> } <add>} <add> <ide> function defaultResolve(specifier, context = {}, defaultResolveUnused) { <ide> let { parentURL, conditions } = context; <ide> if (parentURL && policy?.manifest) { <ide> function defaultResolve(specifier, context = {}, defaultResolveUnused) { <ide> <ide> conditions = getConditionsSet(conditions); <ide> let url; <del> let format; <ide> try { <del> ({ url, format } = <del> moduleResolve( <del> specifier, <del> parentURL, <del> conditions, <del> isMain ? preserveSymlinksMain : preserveSymlinks <del> )); <add> url = moduleResolve( <add> specifier, <add> parentURL, <add> conditions, <add> isMain ? preserveSymlinksMain : preserveSymlinks <add> ); <ide> } catch (error) { <ide> // Try to give the user a hint of what would have been the <ide> // resolved CommonJS module <ide> function defaultResolve(specifier, context = {}, defaultResolveUnused) { <ide> throw error; <ide> } <ide> <del> if (url.protocol !== 'file:' && url.protocol !== 'data:' && <del> url.protocol !== 'node:') <del> throw new ERR_UNSUPPORTED_ESM_URL_SCHEME(url); <add> throwIfUnsupportedURLProtocol(url); <ide> <ide> return { <ide> url: `${url}`, <del> ...(format != null) && { format } <add> format: defaultGetFormatWithoutErrors(url), <ide> }; <ide> } <ide> <ide> module.exports = { <ide> }; <ide> <ide> // cycle <del>const { defaultGetFormat } = require('internal/modules/esm/get_format'); <add>const { <add> defaultGetFormatWithoutErrors, <add>} = require('internal/modules/esm/get_format'); <ide><path>test/es-module/test-esm-resolve-type.js <ide> try { <ide> * ensure that resolving by full path does not return the format <ide> * with the defaultResolver <ide> */ <del> [ [ '/es-modules/package-type-module/index.js', undefined ], <del> [ '/es-modules/package-type-commonjs/index.js', undefined ], <del> [ '/es-modules/package-without-type/index.js', undefined ], <del> [ '/es-modules/package-without-pjson/index.js', undefined ], <add> [ <add> [ '/es-modules/package-type-module/index.js', 'module' ], <add> [ '/es-modules/package-type-commonjs/index.js', 'commonjs' ], <add> [ '/es-modules/package-without-type/index.js', 'commonjs' ], <add> [ '/es-modules/package-without-pjson/index.js', 'commonjs' ], <ide> ].forEach((testVariant) => { <ide> const [ testScript, expectedType ] = testVariant; <ide> const resolvedPath = path.resolve(fixtures.path(testScript)); <ide> try { <ide> /** <ide> * create a test module and try to resolve it by module name. <ide> * check the result is as expected <add> * <add> * for test-module-ne: everything .js that is not 'module' is 'commonjs' <ide> */ <ide> <ide> [ [ 'test-module-mainjs', 'js', 'module', 'module'], <ide> [ 'test-module-mainmjs', 'mjs', 'module', 'module'], <ide> [ 'test-module-cjs', 'js', 'commonjs', 'commonjs'], <del> [ 'test-module-ne', 'js', undefined, undefined], <add> [ 'test-module-ne', 'js', undefined, 'commonjs'], <ide> ].forEach((testVariant) => { <ide> const [ moduleName, <ide> moduleExtenstion, <ide> try { <ide> } <ide> }; <ide> <del> // Create a dummy dual package <del> // <del> /** <del> * this creates following directory structure: <del> * <del> * ./node_modules: <del> * |-> my-dual-package <del> * |-> es <del> * |-> index.js <del> * |-> package.json [2] <del> * |-> lib <del> * |-> index.js <del> * |->package.json [1] <del> * <del> * [1] - main package.json of the package <del> * - it contains: <del> * - type: 'commonjs' <del> * - main: 'lib/mainfile.js' <del> * - conditional exports for 'require' (lib/index.js) and <del> * 'import' (es/index.js) <del> * [2] - package.json add-on for the import case <del> * - it only contains: <del> * - type: 'module' <del> * <del> * in case the package is consumed as an ESM by importing it: <del> * import * as my-package from 'my-dual-package' <del> * it will cause the resolve method to return: <del> * { <del> * url: '<base_path>/node_modules/my-dual-package/es/index.js', <del> * format: 'module' <del> * } <del> * <del> * following testcase ensures that resolve works correctly in this case <del> * returning the information as specified above. Source for 'url' value <del> * is [1], source for 'format' value is [2] <del> */ <add> function testDualPackageWithJsMainScriptAndModuleType() { <add> // Create a dummy dual package <add> // <add> /** <add> * this creates the following directory structure: <add> * <add> * ./node_modules: <add> * |-> my-dual-package <add> * |-> es <add> * |-> index.js <add> * |-> package.json [2] <add> * |-> lib <add> * |-> index.js <add> * |->package.json [1] <add> * <add> * in case the package is imported: <add> * import * as my-package from 'my-dual-package' <add> * it will cause the resolve method to return: <add> * { <add> * url: '<base_path>/node_modules/my-dual-package/es/index.js', <add> * format: 'module' <add> * } <add> * <add> * following testcase ensures that resolve works correctly in this case <add> * returning the information as specified above. Source for 'url' value <add> * is [1], source for 'format' value is [2] <add> */ <add> <add> const moduleName = 'my-dual-package'; <ide> <del> const moduleName = 'my-dual-package'; <del> <del> const mDir = rel(`node_modules/${moduleName}`); <del> const esSubDir = rel(`node_modules/${moduleName}/es`); <del> const cjsSubDir = rel(`node_modules/${moduleName}/lib`); <del> const pkg = rel(`node_modules/${moduleName}/package.json`); <del> const esmPkg = rel(`node_modules/${moduleName}/es/package.json`); <del> const esScript = rel(`node_modules/${moduleName}/es/index.js`); <del> const cjsScript = rel(`node_modules/${moduleName}/lib/index.js`); <del> <del> createDir(nmDir); <del> createDir(mDir); <del> createDir(esSubDir); <del> createDir(cjsSubDir); <del> <del> const mainPkgJsonContent = { <del> type: 'commonjs', <del> main: 'lib/index.js', <del> exports: { <del> '.': { <del> 'require': './lib/index.js', <del> 'import': './es/index.js' <del> }, <del> './package.json': './package.json', <del> } <del> }; <del> const esmPkgJsonContent = { <del> type: 'module' <del> }; <add> const mDir = rel(`node_modules/${moduleName}`); <add> const esSubDir = rel(`node_modules/${moduleName}/es`); <add> const cjsSubDir = rel(`node_modules/${moduleName}/lib`); <add> const pkg = rel(`node_modules/${moduleName}/package.json`); <add> const esmPkg = rel(`node_modules/${moduleName}/es/package.json`); <add> const esScript = rel(`node_modules/${moduleName}/es/index.js`); <add> const cjsScript = rel(`node_modules/${moduleName}/lib/index.js`); <ide> <del> fs.writeFileSync(pkg, JSON.stringify(mainPkgJsonContent)); <del> fs.writeFileSync(esmPkg, JSON.stringify(esmPkgJsonContent)); <del> fs.writeFileSync(esScript, <del> 'export function esm-resolve-tester() {return 42}'); <del> fs.writeFileSync(cjsScript, <del> `module.exports = { <del> esm-resolve-tester: () => {return 42}}` <del> ); <add> createDir(nmDir); <add> createDir(mDir); <add> createDir(esSubDir); <add> createDir(cjsSubDir); <add> <add> const mainPkgJsonContent = { <add> type: 'commonjs', <add> exports: { <add> '.': { <add> 'require': './lib/index.js', <add> 'import': './es/index.js', <add> 'default': './lib/index.js' <add> }, <add> './package.json': './package.json', <add> } <add> }; <add> const esmPkgJsonContent = { <add> type: 'module' <add> }; <add> <add> fs.writeFileSync(pkg, JSON.stringify(mainPkgJsonContent)); <add> fs.writeFileSync(esmPkg, JSON.stringify(esmPkgJsonContent)); <add> fs.writeFileSync( <add> esScript, <add> 'export function esm-resolve-tester() {return 42}' <add> ); <add> fs.writeFileSync( <add> cjsScript, <add> 'module.exports = {esm-resolve-tester: () => {return 42}}' <add> ); <add> <add> // test the resolve <add> const resolveResult = resolve(`${moduleName}`); <add> assert.strictEqual(resolveResult.format, 'module'); <add> assert.ok(resolveResult.url.includes('my-dual-package/es/index.js')); <add> } <add> <add> testDualPackageWithJsMainScriptAndModuleType(); <add> <add> // TestParameters are ModuleName, mainRequireScript, mainImportScript, <add> // mainPackageType, subdirPkgJsonType, expectedResolvedFormat, mainSuffix <add> [ <add> [ 'mjs-mod-mod', 'index.js', 'index.mjs', 'module', 'module', 'module'], <add> [ 'mjs-com-com', 'idx.js', 'idx.mjs', 'commonjs', 'commonjs', 'module'], <add> [ 'mjs-mod-com', 'index.js', 'imp.mjs', 'module', 'commonjs', 'module'], <add> [ 'cjs-mod-mod', 'index.cjs', 'imp.cjs', 'module', 'module', 'commonjs'], <add> [ 'js-com-com', 'index.js', 'imp.js', 'commonjs', 'commonjs', 'commonjs'], <add> [ 'js-com-mod', 'index.js', 'imp.js', 'commonjs', 'module', 'module'], <add> [ 'qmod', 'index.js', 'imp.js', 'commonjs', 'module', 'module', '?k=v'], <add> [ 'hmod', 'index.js', 'imp.js', 'commonjs', 'module', 'module', '#Key'], <add> [ 'qhmod', 'index.js', 'imp.js', 'commonjs', 'module', 'module', '?k=v#h'], <add> [ 'ts-mod-com', 'index.js', 'imp.ts', 'module', 'commonjs', undefined], <add> ].forEach((testVariant) => { <add> const [ <add> moduleName, <add> mainRequireScript, <add> mainImportScript, <add> mainPackageType, <add> subdirPackageType, <add> expectedResolvedFormat, <add> mainSuffix = '' ] = testVariant; <add> <add> const mDir = rel(`node_modules/${moduleName}`); <add> const subDir = rel(`node_modules/${moduleName}/subdir`); <add> const pkg = rel(`node_modules/${moduleName}/package.json`); <add> const subdirPkg = rel(`node_modules/${moduleName}/subdir/package.json`); <add> const esScript = rel(`node_modules/${moduleName}/subdir/${mainImportScript}`); <add> const cjsScript = rel(`node_modules/${moduleName}/subdir/${mainRequireScript}`); <add> <add> createDir(nmDir); <add> createDir(mDir); <add> createDir(subDir); <add> <add> const mainPkgJsonContent = { <add> type: mainPackageType, <add> exports: { <add> '.': { <add> 'require': `./subdir/${mainRequireScript}${mainSuffix}`, <add> 'import': `./subdir/${mainImportScript}${mainSuffix}`, <add> 'default': `./subdir/${mainRequireScript}${mainSuffix}` <add> }, <add> './package.json': './package.json', <add> } <add> }; <add> const subdirPkgJsonContent = { <add> type: `${subdirPackageType}` <add> }; <add> <add> fs.writeFileSync(pkg, JSON.stringify(mainPkgJsonContent)); <add> fs.writeFileSync(subdirPkg, JSON.stringify(subdirPkgJsonContent)); <add> fs.writeFileSync( <add> esScript, <add> 'export function esm-resolve-tester() {return 42}' <add> ); <add> fs.writeFileSync( <add> cjsScript, <add> 'module.exports = {esm-resolve-tester: () => {return 42}}' <add> ); <add> <add> // test the resolve <add> const resolveResult = resolve(`${moduleName}`); <add> assert.strictEqual(resolveResult.format, expectedResolvedFormat); <add> assert.ok(resolveResult.url.endsWith(`${moduleName}/subdir/${mainImportScript}${mainSuffix}`)); <add> }); <ide> <del> // test the resolve <del> const resolveResult = resolve(`${moduleName}`); <del> assert.strictEqual(resolveResult.format, 'module'); <del> assert.ok(resolveResult.url.includes('my-dual-package/es/index.js')); <ide> } finally { <ide> process.chdir(previousCwd); <ide> fs.rmSync(nmDir, { recursive: true, force: true });
5
Python
Python
add algorithm for casimir effect
553624fcd4d7e8a4c561b182967291a1cc44ade9
<ide><path>physics/casimir_effect.py <add>""" <add>Title : Finding the value of magnitude of either the Casimir force, the surface area <add>of one of the plates or distance between the plates provided that the other <add>two parameters are given. <add> <add>Description : In quantum field theory, the Casimir effect is a physical force <add>acting on the macroscopic boundaries of a confined space which arises from the <add>quantum fluctuations of the field. It is a physical force exerted between separate <add>objects, which is due to neither charge, gravity, nor the exchange of particles, <add>but instead is due to resonance of all-pervasive energy fields in the intervening <add>space between the objects. Since the strength of the force falls off rapidly with <add>distance it is only measurable when the distance between the objects is extremely <add>small. On a submicron scale, this force becomes so strong that it becomes the <add>dominant force between uncharged conductors. <add> <add>Dutch physicist Hendrik B. G. Casimir first proposed the existence of the force, <add>and he formulated an experiment to detect it in 1948 while participating in research <add>at Philips Research Labs. The classic form of his experiment used a pair of uncharged <add>parallel metal plates in a vacuum, and successfully demonstrated the force to within <add>15% of the value he had predicted according to his theory. <add> <add>The Casimir force F for idealized, perfectly conducting plates of surface area <add>A square meter and placed at a distance of a meter apart with vacuum between <add>them is expressed as - <add> <add>F = - ((Reduced Planck Constant ℏ) * c * Pi^2 * A) / (240 * a^4) <add> <add>Here, the negative sign indicates the force is attractive in nature. For the ease <add>of calculation, only the magnitude of the force is considered. <add> <add>Source : <add>- https://en.wikipedia.org/wiki/Casimir_effect <add>- https://www.cs.mcgill.ca/~rwest/wikispeedia/wpcd/wp/c/Casimir_effect.htm <add>- Casimir, H. B. ; Polder, D. (1948) "The Influence of Retardation on the <add> London-van der Waals Forces", Physical Review, vol. 73, Issue 4, pp. 360-372 <add>""" <add> <add>from __future__ import annotations <add> <add>from math import pi <add> <add># Define the Reduced Planck Constant ℏ (H bar), speed of light C, value of <add># Pi and the function <add>REDUCED_PLANCK_CONSTANT = 1.054571817e-34 # unit of ℏ : J * s <add> <add>SPEED_OF_LIGHT = 3e8 # unit of c : m * s^-1 <add> <add> <add>def casimir_force(force: float, area: float, distance: float) -> dict[str, float]: <add> <add> """ <add> Input Parameters <add> ---------------- <add> force -> Casimir Force : magnitude in Newtons <add> <add> area -> Surface area of each plate : magnitude in square meters <add> <add> distance -> Distance between two plates : distance in Meters <add> <add> Returns <add> ------- <add> result : dict name, value pair of the parameter having Zero as it's value <add> <add> Returns the value of one of the parameters specified as 0, provided the values of <add> other parameters are given. <add> >>> casimir_force(force = 0, area = 4, distance = 0.03) <add> {'force': 6.4248189174864216e-21} <add> <add> >>> casimir_force(force = 2635e-13, area = 0.0023, distance = 0) <add> {'distance': 1.0323056015031114e-05} <add> <add> >>> casimir_force(force = 2737e-21, area = 0, distance = 0.0023746) <add> {'area': 0.06688838837354052} <add> <add> >>> casimir_force(force = 3457e-12, area = 0, distance = 0) <add> Traceback (most recent call last): <add> ... <add> ValueError: One and only one argument must be 0 <add> <add> >>> casimir_force(force = 3457e-12, area = 0, distance = -0.00344) <add> Traceback (most recent call last): <add> ... <add> ValueError: Distance can not be negative <add> <add> >>> casimir_force(force = -912e-12, area = 0, distance = 0.09374) <add> Traceback (most recent call last): <add> ... <add> ValueError: Magnitude of force can not be negative <add> """ <add> <add> if (force, area, distance).count(0) != 1: <add> raise ValueError("One and only one argument must be 0") <add> if force < 0: <add> raise ValueError("Magnitude of force can not be negative") <add> if distance < 0: <add> raise ValueError("Distance can not be negative") <add> if area < 0: <add> raise ValueError("Area can not be negative") <add> if force == 0: <add> force = (REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 * area) / ( <add> 240 * (distance) ** 4 <add> ) <add> return {"force": force} <add> elif area == 0: <add> area = (240 * force * (distance) ** 4) / ( <add> REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 <add> ) <add> return {"area": area} <add> elif distance == 0: <add> distance = ( <add> (REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 * area) / (240 * force) <add> ) ** (1 / 4) <add> return {"distance": distance} <add> raise ValueError("One and only one argument must be 0") <add> <add> <add># Run doctest <add>if __name__ == "__main__": <add> import doctest <add> <add> doctest.testmod()
1
Python
Python
add task adoption to celerykubernetesexecutor
7338912a78b87be9abcec197bff609b63e396fea
<ide><path>airflow/executors/celery_kubernetes_executor.py <ide> # KIND, either express or implied. See the License for the <ide> # specific language governing permissions and limitations <ide> # under the License. <del>from typing import Dict, Optional, Set, Union <add>from typing import Dict, List, Optional, Set, Union <ide> <ide> from airflow.configuration import conf <ide> from airflow.executors.base_executor import CommandType, EventBufferValueType, QueuedTaskInstanceType <ide> def get_event_buffer(self, dag_ids=None) -> Dict[TaskInstanceKey, EventBufferVal <ide> <ide> return {**cleared_events_from_celery, **cleared_events_from_kubernetes} <ide> <add> def try_adopt_task_instances(self, tis: List[TaskInstance]) -> List[TaskInstance]: <add> """ <add> Try to adopt running task instances that have been abandoned by a SchedulerJob dying. <add> <add> Anything that is not adopted will be cleared by the scheduler (and then become eligible for <add> re-scheduling) <add> <add> :return: any TaskInstances that were unable to be adopted <add> :rtype: list[airflow.models.TaskInstance] <add> """ <add> celery_tis = [] <add> kubernetes_tis = [] <add> abandoned_tis = [] <add> for ti in tis: <add> if ti.queue == self.KUBERNETES_QUEUE: <add> kubernetes_tis.append(ti) <add> else: <add> celery_tis.append(ti) <add> abandoned_tis.extend(self.celery_executor.try_adopt_task_instances(celery_tis)) <add> abandoned_tis.extend(self.kubernetes_executor.try_adopt_task_instances(kubernetes_tis)) <add> return abandoned_tis <add> <ide> def end(self) -> None: <ide> """ <ide> End celery and kubernetes executor <ide><path>tests/executors/test_celery_kubernetes_executor.py <ide> def when_ti_in_celery_executor(): <ide> when_ti_in_k8s_executor() <ide> when_ti_in_celery_executor() <ide> <add> def test_adopt_tasks(self): <add> ti = mock.MagicMock <add> <add> def when_ti_in_k8s_executor(): <add> celery_executor_mock = mock.MagicMock() <add> k8s_executor_mock = mock.MagicMock() <add> ti.queue = "kubernetes" <add> cke = CeleryKubernetesExecutor(celery_executor_mock, k8s_executor_mock) <add> <add> celery_executor_mock.try_adopt_task_instances.return_value = [] <add> k8s_executor_mock.try_adopt_task_instances.return_value = [] <add> <add> cke.try_adopt_task_instances([ti]) <add> celery_executor_mock.try_adopt_task_instances.assert_called_once_with([]) <add> k8s_executor_mock.try_adopt_task_instances.assert_called_once_with([ti]) <add> <add> def when_ti_in_celery_executor(): <add> celery_executor_mock = mock.MagicMock() <add> k8s_executor_mock = mock.MagicMock() <add> ti.queue = "default" <add> cke = CeleryKubernetesExecutor(celery_executor_mock, k8s_executor_mock) <add> <add> celery_executor_mock.try_adopt_task_instances.return_value = [] <add> k8s_executor_mock.try_adopt_task_instances.return_value = [] <add> <add> cke.try_adopt_task_instances([ti]) <add> celery_executor_mock.try_adopt_task_instances.assert_called_once_with([ti]) <add> k8s_executor_mock.try_adopt_task_instances.assert_called_once_with([]) <add> <add> when_ti_in_k8s_executor() <add> when_ti_in_celery_executor() <add> <ide> def test_get_event_buffer(self): <ide> celery_executor_mock = mock.MagicMock() <ide> k8s_executor_mock = mock.MagicMock()
2
PHP
PHP
fix doc block line
1c6b605e06b29a411857563924241de6f2a6f37f
<ide><path>src/Datasource/EntityTrait.php <ide> public function setDirty($property, $isDirty) <ide> /** <ide> * Checks if the entity is dirty or if a single property of it is dirty. <ide> * <del> * @param string $property the field to check the status for <add> * @param string|null $property The field to check the status for. Null for the whole entity. <ide> * @return bool Whether the property was changed or not <ide> */ <ide> public function isDirty($property = null)
1
Javascript
Javascript
add script to fix color maps
d55958ea47ae293282e8c06667a0910c60d6f956
<ide><path>editor/js/Menubar.Edit.js <ide> Menubar.Edit = function ( editor ) { <ide> } ); <ide> options.add( option ); <ide> <add> options.add( new UI.HorizontalRule() ); <add> <add> // Set textures to sRGB. See #15903 <add> <add> var option = new UI.Row(); <add> option.setClass( 'option' ); <add> option.setTextContent( strings.getKey( 'menubar/edit/fixcolormaps' ) ); <add> option.onClick(function() <add> { <add> editor.scene.traverse(fixColorMap); <add> }); <add> options.add(option); <add> <add> var colorMaps = ['map', 'envMap', 'emissiveMap']; <add> <add> function fixColorMap(obj) <add> { <add> var material = obj.material; <add> if(Array.isArray(material) === true) <add> { <add> for(var i = 0; i < material.length; ++i) <add> { <add> fixMaterial(material[i]); <add> } <add> } <add> else if(material !== undefined) <add> { <add> fixMaterial(material); <add> } <add> <add> editor.signals.sceneGraphChanged.dispatch(); <add> } <add> <add> function fixMaterial(material) <add> { <add> var needsUpdate = material.needsUpdate; <add> for(var i = 0; i < colorMaps.length; ++i) <add> { <add> var map = material[colorMaps[i]]; <add> if(map) <add> { <add> map.encoding = THREE.sRGBEncoding; <add> needsUpdate = true; <add> } <add> } <add> material.needsUpdate = needsUpdate; <add> } <ide> <ide> return container; <ide> <ide><path>editor/js/Strings.js <ide> var Strings = function ( config ) { <ide> 'menubar/edit/clone': 'Clone', <ide> 'menubar/edit/delete': 'Delete (Del)', <ide> 'menubar/edit/minify_shaders': 'Minify Shaders', <add> 'menubar/edit/fixcolormaps': 'Fix Color Maps', <ide> <ide> 'menubar/add': 'Add', <ide> 'menubar/add/group': 'Group',
2
PHP
PHP
add redirect exception support
d3b05f157d9eca6ee79ab045a06c0f8068e50ca8
<ide><path>src/Error/Middleware/ErrorHandlerMiddleware.php <ide> use Cake\Core\InstanceConfigTrait; <ide> use Cake\Error\ErrorHandler; <ide> use Cake\Error\ExceptionRenderer; <add>use Cake\Http\Exception\RedirectException; <ide> use Cake\Http\Response; <ide> use InvalidArgumentException; <add>use Laminas\Diactoros\Response\RedirectResponse; <ide> use Psr\Http\Message\ResponseInterface; <ide> use Psr\Http\Message\ServerRequestInterface; <ide> use Psr\Http\Server\MiddlewareInterface; <ide> public function process(ServerRequestInterface $request, RequestHandlerInterface <ide> { <ide> try { <ide> return $handler->handle($request); <add> } catch (RedirectException $exception) { <add> return $this->handleRedirect($exception); <ide> } catch (Throwable $exception) { <ide> return $this->handleException($exception, $request); <ide> } <ide> public function handleException(Throwable $exception, ServerRequestInterface $re <ide> return $response; <ide> } <ide> <add> /** <add> * Convert a redirect exception into a response. <add> * <add> * @param \Cake\Http\Exception\RedirectException $exception The exception to handle <add> * @return \Psr\Http\Message\ResponseInterface Response created from the redirect. <add> */ <add> public function handleRedirect(RedirectException $exception): ResponseInterface <add> { <add> return new RedirectResponse( <add> $exception->getMessage(), <add> $exception->getCode(), <add> $exception->getHeaders() <add> ); <add> } <add> <ide> /** <ide> * Handle internal errors. <ide> * <ide><path>src/Http/Exception/RedirectException.php <add><?php <add>declare(strict_types=1); <add> <add>/** <add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * <add> * Licensed under The MIT License <add> * For full copyright and license information, please see the LICENSE.txt <add> * Redistributions of files must retain the above copyright notice. <add> * <add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * @link https://cakephp.org CakePHP(tm) Project <add> * @since 4.1.0 <add> * @license https://opensource.org/licenses/mit-license.php MIT License <add> */ <add>namespace Cake\Http\Exception; <add> <add>use Cake\Core\Exception\Exception; <add> <add>/** <add> * An exception subclass used by routing and application code to <add> * trigger a redirect. <add> * <add> * The URL and status code are provided as constructor arguments. <add> * <add> * ``` <add> * throw new RedirectException('http://example.com/some/path', 301); <add> * ``` <add> * <add> * Additional headers can also be provided in the constructor, or <add> * using the addHeaders() method. <add> */ <add>class RedirectException extends Exception <add>{ <add> <add> /** <add> * Headers to include in the response. <add> * <add> * @var array <add> */ <add> protected $headers = []; <add> <add> /** <add> * Constructor <add> * <add> * @param string $target The URL to redirect to. <add> * @param int $code The exception code that will be used as a HTTP status code <add> * @param array $headers The headers that should be sent in the unauthorized challenge response. <add> */ <add> public function __construct(string $target, int $code = 302, array $headers = []) <add> { <add> parent::__construct($target, $code); <add> $this->addHeaders($headers); <add> } <add> <add> /** <add> * Add headers to be included in the response generated from this exception <add> * <add> * @param array $headers An array of `header => value` to append to the exception. <add> * If a header already exists, the new values will be appended to the existing ones. <add> * @return $this <add> */ <add> public function addHeaders(array $headers) <add> { <add> foreach ($headers as $key => $value) { <add> $this->headers[$key][] = $value; <add> } <add> <add> return $this; <add> } <add> <add> /** <add> * Remove a header from the exception. <add> * <add> * @param string $key The header to remove. <add> * @return $this <add> */ <add> public function removeHeader(string $key) <add> { <add> unset($this->headers[$key]); <add> <add> return $this; <add> } <add> <add> /** <add> * Get the headers from the exception. <add> * <add> * @return array <add> */ <add> public function getHeaders(): array <add> { <add> return $this->headers; <add> } <add>} <ide><path>src/Routing/Exception/RedirectException.php <ide> * ``` <ide> * throw new RedirectException('http://example.com/some/path', 301); <ide> * ``` <add> * <add> * If you need a more general purpose redirect exception use <add> * Cake\Http\Exception\RedirectException instead of this class. <ide> */ <ide> class RedirectException extends Exception <ide> { <ide><path>tests/TestCase/Error/Middleware/ErrorHandlerMiddlewareTest.php <ide> use Cake\Error\ExceptionRendererInterface; <ide> use Cake\Error\Middleware\ErrorHandlerMiddleware; <ide> use Cake\Http\Exception\MissingControllerException; <add>use Cake\Http\Exception\RedirectException; <ide> use Cake\Http\Response; <ide> use Cake\Http\ServerRequestFactory; <ide> use Cake\Log\Log; <ide> use Cake\TestSuite\TestCase; <ide> use Error; <ide> use InvalidArgumentException; <ide> use LogicException; <add>use Psr\Http\Message\ResponseInterface; <ide> use TestApp\Http\TestRequestHandler; <ide> <ide> /** <ide> public function testHandleException() <ide> $this->assertStringContainsString('was not found', '' . $result->getBody()); <ide> } <ide> <add> /** <add> * Test creating a redirect response <add> * <add> * @return void <add> */ <add> public function testHandleRedirectException() <add> { <add> $request = ServerRequestFactory::fromGlobals(); <add> $middleware = new ErrorHandlerMiddleware(); <add> $handler = new TestRequestHandler(function () { <add> throw new RedirectException('http://example.org/login'); <add> }); <add> $result = $middleware->process($request, $handler); <add> $this->assertInstanceOf(ResponseInterface::class, $result); <add> $this->assertEquals(302, $result->getStatusCode()); <add> $this->assertEmpty('' . $result->getBody()); <add> $expected = [ <add> 'location' => ['http://example.org/login'], <add> ]; <add> $this->assertSame($expected, $result->getHeaders()); <add> } <add> <add> /** <add> * Test creating a redirect response <add> * <add> * @return void <add> */ <add> public function testHandleRedirectExceptionHeaders() <add> { <add> $request = ServerRequestFactory::fromGlobals(); <add> $middleware = new ErrorHandlerMiddleware(); <add> $handler = new TestRequestHandler(function () { <add> $err = new RedirectException('http://example.org/login', 301, ['Constructor' => 'yes']); <add> $err->addHeaders(['Constructor' => 'no', 'Method' => 'yes']); <add> throw $err; <add> }); <add> <add> $result = $middleware->process($request, $handler); <add> $this->assertInstanceOf(ResponseInterface::class, $result); <add> $this->assertEquals(301, $result->getStatusCode()); <add> $this->assertEmpty('' . $result->getBody()); <add> $expected = [ <add> 'location' => ['http://example.org/login'], <add> 'Constructor' => ['yes', 'no'], <add> 'Method' => ['yes'], <add> ]; <add> $this->assertEquals($expected, $result->getHeaders()); <add> } <add> <ide> /** <ide> * Test rendering an error page holds onto the original request. <ide> *
4
PHP
PHP
enable further clickability in ide
c91bd6301d5479bdcb48d2df5114f21ce2a9de24
<ide><path>src/Routing/Router.php <ide> public static function plugin($name, $options = [], $callback = null) <ide> /** <ide> * Get the route scopes and their connected routes. <ide> * <del> * @return array <add> * @return \Cake\Routing\Route\Route[] <ide> */ <ide> public static function routes() <ide> { <ide><path>src/Shell/CommandListShell.php <ide> <ide> /** <ide> * Shows a list of commands available from the console. <add> * <add> * @property \Cake\Shell\Task\CommandTask $Command <ide> */ <ide> class CommandListShell extends Shell <ide> { <ide><path>src/Shell/CompletionShell.php <ide> <ide> /** <ide> * Provide command completion shells such as bash. <add> * <add> * @property \Cake\Shell\Task\CommandTask $Command <ide> */ <ide> class CompletionShell extends Shell <ide> { <ide><path>src/Shell/I18nShell.php <ide> <ide> /** <ide> * Shell for I18N management. <add> * <add> * @property \Cake\Shell\Task\ExtractTask $Extract <ide> */ <ide> class I18nShell extends Shell <ide> { <ide><path>src/Shell/OrmCacheShell.php <ide> public function clear($name = null) <ide> /** <ide> * Helper method to get the schema collection. <ide> * <del> * @return false|\Cake\Database\Schema\Collection <add> * @return false|\Cake\Database\Schema\Collection|\Cake\Database\Schema\CachedCollection <ide> */ <ide> protected function _getSchema() <ide> { <add> /* @var \Cake\Database\Connection $source */ <ide> $source = ConnectionManager::get($this->params['connection']); <ide> if (!method_exists($source, 'schemaCollection')) { <ide> $msg = sprintf( <ide><path>src/Shell/Task/CommandTask.php <ide> public function getShell($commandName) <ide> return false; <ide> } <ide> <add> /* @var \Cake\Console\Shell $Shell */ <ide> $Shell = new $class(); <ide> $Shell->plugin = trim($pluginDot, '.'); <ide> $Shell->initialize(); <ide> public function options($commandName, $subCommandName = '') <ide> <ide> $options = []; <ide> $array = $parser->options(); <add> /* @var \Cake\Console\ConsoleInputOption $obj */ <ide> foreach ($array as $name => $obj) { <ide> $options[] = "--$name"; <ide> $short = $obj->short(); <ide><path>src/Shell/Task/ExtractTask.php <ide> public function getOptionParser() <ide> */ <ide> protected function _extractTokens() <ide> { <add> /* @var \Cake\Shell\Helper\ProgressHelper $progress */ <ide> $progress = $this->helper('progress'); <ide> $progress->init(['total' => count($this->_files)]); <ide> $isVerbose = $this->param('verbose');
7
Go
Go
use raw strings for regexes (gosimple)
a0d58b22483e7d1638e459514dac4b34105ba9f7
<ide><path>integration-cli/docker_cli_build_test.go <ide> func (s *DockerSuite) TestBuildLabelsCache(c *testing.T) { <ide> func (s *DockerSuite) TestBuildNotVerboseSuccess(c *testing.T) { <ide> // This test makes sure that -q works correctly when build is successful: <ide> // stdout has only the image ID (long image ID) and stderr is empty. <del> outRegexp := regexp.MustCompile("^(sha256:|)[a-z0-9]{64}\\n$") <add> outRegexp := regexp.MustCompile(`^(sha256:|)[a-z0-9]{64}\n$`) <ide> buildFlags := cli.WithFlags("-q") <ide> <ide> tt := []struct { <ide><path>integration-cli/docker_cli_by_digest_test.go <ide> import ( <ide> var ( <ide> remoteRepoName = "dockercli/busybox-by-dgst" <ide> repoName = fmt.Sprintf("%s/%s", privateRegistryURL, remoteRepoName) <del> pushDigestRegex = regexp.MustCompile("[\\S]+: digest: ([\\S]+) size: [0-9]+") <del> digestRegex = regexp.MustCompile("Digest: ([\\S]+)") <add> pushDigestRegex = regexp.MustCompile(`[\S]+: digest: ([\S]+) size: [0-9]+`) <add> digestRegex = regexp.MustCompile(`Digest: ([\S]+)`) <ide> ) <ide> <ide> func setupImage(c *testing.T) (digest.Digest, error) { <ide><path>integration-cli/docker_cli_import_test.go <ide> func (s *DockerSuite) TestImportFileWithMessage(c *testing.T) { <ide> split := strings.Split(out, "\n") <ide> <ide> assert.Equal(c, len(split), 3, "expected 3 lines from image history") <del> r := regexp.MustCompile("[\\s]{2,}") <add> r := regexp.MustCompile(`[\s]{2,}`) <ide> split = r.Split(split[1], -1) <ide> <ide> assert.Equal(c, message, split[3], "didn't get expected value in commit message") <ide><path>integration-cli/docker_cli_registry_user_agent_test.go <ide> func regexpCheckUA(c *testing.T, ua string) { <ide> // check upstreamUA looks correct <ide> // Expecting something like: Docker-Client/1.11.0-dev (linux) <ide> upstreamUA := unescapeBackslashSemicolonParens(upstreamUAEscaped) <del> reUpstreamUA := regexp.MustCompile("^\\(Docker-Client/[0-9A-Za-z+]") <add> reUpstreamUA := regexp.MustCompile(`^\(Docker-Client/[0-9A-Za-z+]`) <ide> bMatchUpstreamUA := reUpstreamUA.MatchString(upstreamUA) <ide> assert.Assert(c, bMatchUpstreamUA, "(Upstream) Docker Client User-Agent malformed") <ide> } <ide><path>integration-cli/docker_cli_save_load_test.go <ide> func (s *DockerSuite) TestSaveRepoWithMultipleImages(c *testing.T) { <ide> lines := strings.Split(strings.TrimSpace(out), "\n") <ide> var actual []string <ide> for _, l := range lines { <del> if regexp.MustCompile("^[a-f0-9]{64}\\.json$").Match([]byte(l)) { <add> if regexp.MustCompile(`^[a-f0-9]{64}\.json$`).Match([]byte(l)) { <ide> actual = append(actual, strings.TrimSuffix(l, ".json")) <ide> } <ide> }
5
Python
Python
remove explanation of exception due to out
bcc77f9229707714db43e8b69c5dacaa494aa184
<ide><path>numpy/core/code_generators/ufunc_docstrings.py <ide> def add_newdoc(place, name, doc): <ide> y : ndarray <ide> The corresponding cosine values. <ide> <del> Raises <del> ------ <del> ValueError: invalid return array shape <del> if `out` is provided and `out.shape` != `x.shape` (See Examples) <del> <ide> Notes <ide> ----- <ide> If `out` is provided, the function writes the result into it, <ide> def add_newdoc(place, name, doc): <ide> y : ndarray <ide> The corresponding hyperbolic sine values. <ide> <del> Raises <del> ------ <del> ValueError: invalid return array shape <del> if `out` is provided and `out.shape` != `x.shape` (See Examples) <del> <ide> Notes <ide> ----- <ide> If `out` is provided, the function writes the result into it, <ide> def add_newdoc(place, name, doc): <ide> y : ndarray <ide> The corresponding tangent values. <ide> <del> Raises <del> ------ <del> ValueError: invalid return array shape <del> if `out` is provided and `out.shape` != `x.shape` (See Examples) <del> <ide> Notes <ide> ----- <ide> If `out` is provided, the function writes the result into it, <ide> def add_newdoc(place, name, doc): <ide> y : ndarray <ide> The corresponding hyperbolic tangent values. <ide> <del> Raises <del> ------ <del> ValueError: invalid return array shape <del> if `out` is provided and `out.shape` != `x.shape` (See Examples) <del> <ide> Notes <ide> ----- <ide> If `out` is provided, the function writes the result into it,
1
Text
Text
add some focus items for atom ide
17af5933f9e4b7c7abb37f697ff950e6656cf73b
<ide><path>docs/focus/2018-02-19.md <ide> ## Highlights from the past week <ide> <ide> - Atom IDE <add> - Converted atom-languageclient to TypeScript <add> - ide-typescript updated to use TypeScript 2.7.2 <add> - Published updates to ide-typescript, ide-json, and ide-csharp to improve language server stability <ide> - @atom/watcher <ide> - GitHub Package <ide> - Teletype <ide> ## Focus for week ahead <ide> <ide> - Atom IDE <add> - Investigate new Atom IDE UI features for rename operations and workspace symbol search <ide> - @atom/watcher <ide> - GitHub Package <ide> - Teletype
1
Javascript
Javascript
remove registration code from initial markup
a2553bb46e13e171f43c0f6314879bd917a26396
<ide><path>packages/next/build/webpack/plugins/pages-plugin.js <ide> export default class PagesPlugin { <ide> routeName = `/${routeName.replace(/(^|\/)index$/, '')}` <ide> <ide> const source = new ConcatSource( <del> `__NEXT_REGISTER_PAGE('${routeName}', function() {\n`, <add> `(window.__NEXT_P=window.__NEXT_P||[]).push(['${routeName}', function() {\n`, <ide> moduleSourcePostModule, <ide> '\nreturn { page: module.exports.default }', <del> '});' <add> '}]);' <ide> ) <ide> <ide> return source <ide><path>packages/next/client/index.js <ide> envConfig.setConfig({ <ide> const asPath = getURL() <ide> <ide> const pageLoader = new PageLoader(buildId, prefix) <del>window.__NEXT_LOADED_PAGES__.forEach(([r, f]) => { <del> pageLoader.registerPage(r, f) <del>}) <del>delete window.__NEXT_LOADED_PAGES__ <del>window.__NEXT_REGISTER_PAGE = pageLoader.registerPage.bind(pageLoader) <add>const register = ([r, f]) => pageLoader.registerPage(r, f) <add>if (window.__NEXT_P) { <add> window.__NEXT_P.map(register) <add>} <add>window.__NEXT_P = [] <add>window.__NEXT_P.push = register <ide> <ide> const headManager = new HeadManager() <ide> const appContainer = document.getElementById('__next') <ide><path>packages/next/pages/_document.js <ide> export class NextScript extends Component { <ide> static getInlineScriptSource (documentProps) { <ide> const { __NEXT_DATA__ } = documentProps <ide> const { page } = __NEXT_DATA__ <del> return `__NEXT_DATA__ = ${htmlescape(__NEXT_DATA__)};__NEXT_LOADED_PAGES__=[];__NEXT_REGISTER_PAGE=function(r,f){__NEXT_LOADED_PAGES__.push([r, f])};` <add> return `__NEXT_DATA__ = ${htmlescape(__NEXT_DATA__)};` <ide> } <ide> <ide> render () {
3
Javascript
Javascript
fix method comments
2b389b43fb792cea18249f6598f4bcb81181767a
<ide><path>packages/ember-runtime/lib/controllers/array_controller.js <ide> Ember.ArrayController = Ember.ArrayProxy.extend(Ember.ControllerMixin, <ide> }); <ide> ``` <ide> <del> @method <del> @type String <del> @default null <add> @method lookupItemController <add> @param {Object} object <add> @return {String} <ide> */ <ide> lookupItemController: function(object) { <ide> return get(this, 'itemController'); <ide><path>packages/ember-runtime/lib/system/native_array.js <ide> if (ignore.length>0) { <ide> @namespace Ember <ide> @extends Ember.Mixin <ide> @uses Ember.MutableArray <del> @uses Ember.MutableEnumerable <add> @uses Ember.Observable <ide> @uses Ember.Copyable <del> @uses Ember.Freezable <ide> */ <ide> Ember.NativeArray = NativeArray; <ide>
2
Ruby
Ruby
add tests for
7487e79d4df7b05debb59e4177bc3810c29c9967
<ide><path>actionpack/test/controller/routing_test.rb <ide> def test_named_route_root_without_hash <ide> assert_equal("/", routes.send(:root_path)) <ide> end <ide> <add> def test_named_route_root_with_hash <add> rs.draw do <add> root "hello#index", as: :index <add> end <add> <add> routes = setup_for_named_route <add> assert_equal("http://test.host/", routes.send(:index_url)) <add> assert_equal("/", routes.send(:index_path)) <add> end <add> <add> def test_root_without_path_raises_argument_error <add> assert_raises ArgumentError do <add> rs.draw { root nil } <add> end <add> end <add> <ide> def test_named_route_root_with_trailing_slash <ide> rs.draw do <ide> root "hello#index"
1
Python
Python
add type hints for vilt models
46d09410eba7892a47d15eb8a7b29b5b7b598a19
<ide><path>src/transformers/models/vilt/modeling_vilt.py <ide> import collections.abc <ide> import math <ide> from dataclasses import dataclass <del>from typing import List, Optional, Tuple <add>from typing import List, Optional, Tuple, Union <ide> <ide> import torch <ide> import torch.utils.checkpoint <ide> class PreTrainedModel <ide> @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=_CONFIG_FOR_DOC) <ide> def forward( <ide> self, <del> input_ids=None, <del> attention_mask=None, <del> token_type_ids=None, <del> pixel_values=None, <del> pixel_mask=None, <del> head_mask=None, <del> inputs_embeds=None, <del> image_embeds=None, <del> image_token_type_idx=None, <del> output_attentions=None, <del> output_hidden_states=None, <del> return_dict=None, <del> ): <add> input_ids: Optional[torch.LongTensor] = None, <add> attention_mask: Optional[torch.FloatTensor] = None, <add> token_type_ids: Optional[torch.LongTensor] = None, <add> pixel_values: Optional[torch.FloatTensor] = None, <add> pixel_mask: Optional[torch.LongTensor] = None, <add> head_mask: Optional[torch.FloatTensor] = None, <add> inputs_embeds: Optional[torch.FloatTensor] = None, <add> image_embeds: Optional[torch.FloatTensor] = None, <add> image_token_type_idx: Optional[int] = None, <add> output_attentions: Optional[bool] = None, <add> output_hidden_states: Optional[bool] = None, <add> return_dict: Optional[bool] = None, <add> ) -> Union[BaseModelOutputWithPooling, Tuple[torch.FloatTensor]]: <ide> r""" <ide> Returns: <ide> <ide> def set_output_embeddings(self, new_embeddings): <ide> @replace_return_docstrings(output_type=MaskedLMOutput, config_class=_CONFIG_FOR_DOC) <ide> def forward( <ide> self, <del> input_ids=None, <del> attention_mask=None, <del> token_type_ids=None, <del> pixel_values=None, <del> pixel_mask=None, <del> head_mask=None, <del> inputs_embeds=None, <del> image_embeds=None, <del> labels=None, <del> output_attentions=None, <del> output_hidden_states=None, <del> return_dict=None, <del> ): <add> input_ids: Optional[torch.LongTensor] = None, <add> attention_mask: Optional[torch.FloatTensor] = None, <add> token_type_ids: Optional[torch.LongTensor] = None, <add> pixel_values: Optional[torch.FloatTensor] = None, <add> pixel_mask: Optional[torch.LongTensor] = None, <add> head_mask: Optional[torch.FloatTensor] = None, <add> inputs_embeds: Optional[torch.FloatTensor] = None, <add> image_embeds: Optional[torch.FloatTensor] = None, <add> labels: Optional[torch.LongTensor] = None, <add> output_attentions: Optional[bool] = None, <add> output_hidden_states: Optional[bool] = None, <add> return_dict: Optional[bool] = None, <add> ) -> Union[MaskedLMOutput, Tuple[torch.FloatTensor]]: <ide> r""" <ide> labels (*torch.LongTensor* of shape *(batch_size, sequence_length)*, *optional*): <ide> Labels for computing the masked language modeling loss. Indices should be in *[-100, 0, ..., <ide> def __init__(self, config): <ide> @replace_return_docstrings(output_type=SequenceClassifierOutput, config_class=_CONFIG_FOR_DOC) <ide> def forward( <ide> self, <del> input_ids=None, <del> attention_mask=None, <del> token_type_ids=None, <del> pixel_values=None, <del> pixel_mask=None, <del> head_mask=None, <del> inputs_embeds=None, <del> image_embeds=None, <del> labels=None, <del> output_attentions=None, <del> output_hidden_states=None, <del> return_dict=None, <del> ): <add> input_ids: Optional[torch.LongTensor] = None, <add> attention_mask: Optional[torch.FloatTensor] = None, <add> token_type_ids: Optional[torch.LongTensor] = None, <add> pixel_values: Optional[torch.FloatTensor] = None, <add> pixel_mask: Optional[torch.LongTensor] = None, <add> head_mask: Optional[torch.FloatTensor] = None, <add> inputs_embeds: Optional[torch.FloatTensor] = None, <add> image_embeds: Optional[torch.FloatTensor] = None, <add> labels: Optional[torch.LongTensor] = None, <add> output_attentions: Optional[bool] = None, <add> output_hidden_states: Optional[bool] = None, <add> return_dict: Optional[bool] = None, <add> ) -> Union[SequenceClassifierOutput, Tuple[torch.FloatTensor]]: <ide> r""" <ide> labels (`torch.FloatTensor` of shape `(batch_size, num_labels)`, *optional*): <ide> Labels for computing the visual question answering loss. This tensor must be either a one-hot encoding of <ide> def __init__(self, config): <ide> @replace_return_docstrings(output_type=SequenceClassifierOutput, config_class=_CONFIG_FOR_DOC) <ide> def forward( <ide> self, <del> input_ids=None, <del> attention_mask=None, <del> token_type_ids=None, <del> pixel_values=None, <del> pixel_mask=None, <del> head_mask=None, <del> inputs_embeds=None, <del> image_embeds=None, <del> labels=None, <del> output_attentions=None, <del> output_hidden_states=None, <del> return_dict=None, <del> ): <add> input_ids: Optional[torch.LongTensor] = None, <add> attention_mask: Optional[torch.FloatTensor] = None, <add> token_type_ids: Optional[torch.LongTensor] = None, <add> pixel_values: Optional[torch.FloatTensor] = None, <add> pixel_mask: Optional[torch.LongTensor] = None, <add> head_mask: Optional[torch.FloatTensor] = None, <add> inputs_embeds: Optional[torch.FloatTensor] = None, <add> image_embeds: Optional[torch.FloatTensor] = None, <add> labels: Optional[torch.LongTensor] = None, <add> output_attentions: Optional[bool] = None, <add> output_hidden_states: Optional[bool] = None, <add> return_dict: Optional[bool] = None, <add> ) -> Union[SequenceClassifierOutput, Tuple[torch.FloatTensor]]: <ide> r""" <ide> labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): <ide> Labels are currently not supported. <ide> def __init__(self, config): <ide> @replace_return_docstrings(output_type=ViltForImagesAndTextClassificationOutput, config_class=_CONFIG_FOR_DOC) <ide> def forward( <ide> self, <del> input_ids=None, <del> attention_mask=None, <del> token_type_ids=None, <del> pixel_values=None, <del> pixel_mask=None, <del> head_mask=None, <del> inputs_embeds=None, <del> image_embeds=None, <del> labels=None, <del> output_attentions=None, <del> output_hidden_states=None, <del> return_dict=None, <del> ): <add> input_ids: Optional[torch.LongTensor] = None, <add> attention_mask: Optional[torch.FloatTensor] = None, <add> token_type_ids: Optional[torch.LongTensor] = None, <add> pixel_values: Optional[torch.FloatTensor] = None, <add> pixel_mask: Optional[torch.LongTensor] = None, <add> head_mask: Optional[torch.FloatTensor] = None, <add> inputs_embeds: Optional[torch.FloatTensor] = None, <add> image_embeds: Optional[torch.FloatTensor] = None, <add> labels: Optional[torch.LongTensor] = None, <add> output_attentions: Optional[bool] = None, <add> output_hidden_states: Optional[bool] = None, <add> return_dict: Optional[bool] = None, <add> ) -> Union[ViltForImagesAndTextClassificationOutput, Tuple[torch.FloatTensor]]: <ide> r""" <ide> labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): <ide> Binary classification labels. <ide> def __init__(self, config): <ide> @replace_return_docstrings(output_type=TokenClassifierOutput, config_class=_CONFIG_FOR_DOC) <ide> def forward( <ide> self, <del> input_ids=None, <del> attention_mask=None, <del> token_type_ids=None, <del> pixel_values=None, <del> pixel_mask=None, <del> head_mask=None, <del> inputs_embeds=None, <del> image_embeds=None, <del> labels=None, <del> output_attentions=None, <del> output_hidden_states=None, <del> return_dict=None, <del> ): <add> input_ids: Optional[torch.LongTensor] = None, <add> attention_mask: Optional[torch.FloatTensor] = None, <add> token_type_ids: Optional[torch.LongTensor] = None, <add> pixel_values: Optional[torch.FloatTensor] = None, <add> pixel_mask: Optional[torch.LongTensor] = None, <add> head_mask: Optional[torch.FloatTensor] = None, <add> inputs_embeds: Optional[torch.FloatTensor] = None, <add> image_embeds: Optional[torch.FloatTensor] = None, <add> labels: Optional[torch.LongTensor] = None, <add> output_attentions: Optional[bool] = None, <add> output_hidden_states: Optional[bool] = None, <add> return_dict: Optional[bool] = None, <add> ) -> Union[TokenClassifierOutput, Tuple[torch.FloatTensor]]: <ide> r""" <ide> labels (`torch.LongTensor` of shape `(batch_size, text_sequence_length)`, *optional*): <ide> Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
1
Python
Python
support empty suffix (--suffix='')
50dcc1b1a813f903cd5423e0c92ff8a64e939e0b
<ide><path>celery/bin/celeryd_multi.py <ide> def splash(self): <ide> self.note(c.cyan("celeryd-multi v%s" % __version__)) <ide> <ide> def waitexec(self, argv, path=sys.executable): <del> argstr = shlex.split(" ".join([path] + list(argv))) <add> args = " ".join([path] + list(argv)) <add> argstr = shlex.split(args.encode("utf-8")) <ide> pipe = Popen(argstr) <ide> self.info(" %s" % " ".join(argstr)) <ide> retcode = pipe.wait() <ide> def multi_args(p, cmd="celeryd", append="", prefix="", suffix=""): <ide> options.pop("-n", socket.gethostname())) <ide> prefix = options.pop("--prefix", prefix) or "" <ide> suffix = options.pop("--suffix", suffix) or "." + hostname <add> if suffix in ('""', "''"): <add> suffix = "" <ide> <ide> for ns_name, ns_opts in p.namespaces.items(): <ide> if "," in ns_name or (ranges and "-" in ns_name):
1
Ruby
Ruby
add example label to active_support/configurable
e8ef58a697c4af99a7db44267cf6d975fb5d6091
<ide><path>activesupport/lib/active_support/configurable.rb <ide> def #{name}=(value); config.#{name} = value; end <ide> end <ide> <ide> # Reads and writes attributes from a configuration <tt>OrderedHash</tt>. <del> # <ide> # Example: <ide> # <ide> # require 'active_support/configurable'
1
Python
Python
drop fun_accepts_kwargs backport
b863168ac9bc0811cbf73409d4101be02fe34489
<ide><path>celery/utils/functional.py <ide> def firstmethod(method, on_call=None): <ide> The list can also contain lazy instances <ide> (:class:`~kombu.utils.functional.lazy`.) <ide> """ <add> <ide> def _matcher(it, *args, **kwargs): <ide> for obj in it: <ide> try: <ide> def _matcher(it, *args, **kwargs): <ide> else: <ide> if reply is not None: <ide> return reply <add> <ide> return _matcher <ide> <ide> <ide> def fun_takes_argument(name, fun, position=None): <ide> ) <ide> <ide> <del>if hasattr(inspect, 'signature'): <del> def fun_accepts_kwargs(fun): <del> """Return true if function accepts arbitrary keyword arguments.""" <del> return any( <del> p for p in inspect.signature(fun).parameters.values() <del> if p.kind == p.VAR_KEYWORD <del> ) <del>else: <del> def fun_accepts_kwargs(fun): # noqa <del> """Return true if function accepts arbitrary keyword arguments.""" <del> try: <del> argspec = inspect.getargspec(fun) <del> except TypeError: <del> try: <del> argspec = inspect.getargspec(fun.__call__) <del> except (TypeError, AttributeError): <del> return <del> return not argspec or argspec[2] is not None <add>def fun_accepts_kwargs(fun): <add> """Return true if function accepts arbitrary keyword arguments.""" <add> return any( <add> p for p in inspect.signature(fun).parameters.values() <add> if p.kind == p.VAR_KEYWORD <add> ) <ide> <ide> <ide> def maybe(typ, val):
1
Javascript
Javascript
fix hmr (#680)
8df7f0da57cff349e63bf4fe939a53b2de35ef1d
<ide><path>client/next-dev.js <del>import 'react-hot-loader/patch' <ide> import patch from './patch-react' <ide> <ide> // apply patch first <ide> patch((err) => { <ide> next.renderError(err) <ide> }) <ide> <add>require('react-hot-loader/patch') <add> <ide> const next = require('./next') <ide> window.next = next
1
PHP
PHP
fix missing view variables
7416c530a205cce38f070d89a12f1434eab90cbf
<ide><path>lib/Cake/Error/ExceptionRenderer.php <ide> protected function _outputMessage($template) { <ide> $this->controller->afterFilter(); <ide> $this->controller->response->send(); <ide> } catch (Exception $e) { <add> $this->controller->set(array( <add> 'error' => $e, <add> 'name' => $e->getMessage(), <add> 'code' => $e->getCode(), <add> )); <ide> $this->_outputMessageSafe('error500'); <ide> } <ide> } <ide><path>lib/Cake/Test/Case/Error/ExceptionRendererTest.php <ide> public function testMissingRenderSafe() { <ide> ->with('missingHelper') <ide> ->will($this->throwException($exception)); <ide> <del> $ExceptionRenderer->controller->expects($this->at(4)) <add> $ExceptionRenderer->controller->expects($this->at(5)) <ide> ->method('render') <ide> ->with('error500') <ide> ->will($this->returnValue(true)); <ide> public function testMissingSubdirRenderSafe() { <ide> ->with('error400') <ide> ->will($this->throwException($exception)); <ide> <del> $ExceptionRenderer->controller->expects($this->at(3)) <add> $ExceptionRenderer->controller->expects($this->at(4)) <ide> ->method('render') <ide> ->with('error500') <ide> ->will($this->returnValue(true));
2
PHP
PHP
fix $withcount binding problems
8c37b0d0c0821225b4c89a7e3b4c4aeb1f560471
<ide><path>src/Illuminate/Database/Eloquent/Builder.php <ide> public function whereKeyNot($id) <ide> public function where($column, $operator = null, $value = null, $boolean = 'and') <ide> { <ide> if ($column instanceof Closure) { <del> $query = $this->model->newQueryWithoutScopes(); <add> $query = $this->model->newUneagerQueryWithoutScopes(); <ide> <ide> $column($query); <ide> <ide><path>src/Illuminate/Database/Eloquent/Model.php <ide> public function push() <ide> */ <ide> public function save(array $options = []) <ide> { <del> $query = $this->newQueryWithoutScopes(); <add> $query = $this->newUneagerQueryWithoutScopes(); <ide> <ide> // If the "saving" event returns false we'll bail out of the save and return <ide> // false, indicating that the save failed. This provides a chance for any <ide> public function forceDelete() <ide> */ <ide> protected function performDeleteOnModel() <ide> { <del> $this->setKeysForSaveQuery($this->newQueryWithoutScopes())->delete(); <add> $this->setKeysForSaveQuery($this->newUneagerQueryWithoutScopes())->delete(); <ide> <ide> $this->exists = false; <ide> } <ide> public function registerGlobalScopes($builder) <ide> * @return \Illuminate\Database\Eloquent\Builder|static <ide> */ <ide> public function newQueryWithoutScopes() <add> { <add> return $this->newUneagerQueryWithoutScopes() <add> ->with($this->with) <add> ->withCount($this->withCount); <add> } <add> <add> /** <add> * Get a new query builder that doesn't have any global scopes or eager loading. <add> * <add> * @return \Illuminate\Database\Eloquent\Builder|static <add> */ <add> public function newUneagerQueryWithoutScopes() <ide> { <ide> $builder = $this->newEloquentBuilder($this->newBaseQueryBuilder()); <ide> <ide> // Once we have the query builders, we will set the model instances so the <ide> // builder can easily access any information it may need from the model <ide> // while it is constructing and executing various queries against it. <del> return $builder->setModel($this) <del> ->with($this->with) <del> ->withCount($this->withCount); <add> return $builder->setModel($this); <ide> } <ide> <ide> /** <ide><path>src/Illuminate/Database/Eloquent/SoftDeletes.php <ide> protected function performDeleteOnModel() <ide> if ($this->forceDeleting) { <ide> $this->exists = false; <ide> <del> return $this->newQueryWithoutScopes()->where($this->getKeyName(), $this->getKey())->forceDelete(); <add> return $this->newUneagerQueryWithoutScopes()->where($this->getKeyName(), $this->getKey())->forceDelete(); <ide> } <ide> <ide> return $this->runSoftDelete(); <ide> protected function performDeleteOnModel() <ide> */ <ide> protected function runSoftDelete() <ide> { <del> $query = $this->newQueryWithoutScopes()->where($this->getKeyName(), $this->getKey()); <add> $query = $this->newUneagerQueryWithoutScopes()->where($this->getKeyName(), $this->getKey()); <ide> <ide> $time = $this->freshTimestamp(); <ide> <ide><path>tests/Database/DatabaseEloquentBuilderTest.php <ide> public function testNestedWhere() <ide> $nestedRawQuery = $this->getMockQueryBuilder(); <ide> $nestedQuery->shouldReceive('getQuery')->once()->andReturn($nestedRawQuery); <ide> $model = $this->getMockModel()->makePartial(); <del> $model->shouldReceive('newQueryWithoutScopes')->once()->andReturn($nestedQuery); <add> $model->shouldReceive('newUneagerQueryWithoutScopes')->once()->andReturn($nestedQuery); <ide> $builder = $this->getBuilder(); <ide> $builder->getQuery()->shouldReceive('from'); <ide> $builder->setModel($model); <ide><path>tests/Database/DatabaseEloquentModelTest.php <ide> public function testWithMethodCallsQueryBuilderCorrectlyWithArray() <ide> <ide> public function testUpdateProcess() <ide> { <del> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newQueryWithoutScopes', 'updateTimestamps'])->getMock(); <add> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newUneagerQueryWithoutScopes', 'updateTimestamps'])->getMock(); <ide> $query = m::mock('Illuminate\Database\Eloquent\Builder'); <ide> $query->shouldReceive('where')->once()->with('id', '=', 1); <ide> $query->shouldReceive('update')->once()->with(['name' => 'taylor'])->andReturn(1); <del> $model->expects($this->once())->method('newQueryWithoutScopes')->will($this->returnValue($query)); <add> $model->expects($this->once())->method('newUneagerQueryWithoutScopes')->will($this->returnValue($query)); <ide> $model->expects($this->once())->method('updateTimestamps'); <ide> $model->setEventDispatcher($events = m::mock('Illuminate\Contracts\Events\Dispatcher')); <ide> $events->shouldReceive('until')->once()->with('eloquent.saving: '.get_class($model), $model)->andReturn(true); <ide> public function testUpdateProcess() <ide> <ide> public function testUpdateProcessDoesntOverrideTimestamps() <ide> { <del> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newQueryWithoutScopes'])->getMock(); <add> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newUneagerQueryWithoutScopes'])->getMock(); <ide> $query = m::mock('Illuminate\Database\Eloquent\Builder'); <ide> $query->shouldReceive('where')->once()->with('id', '=', 1); <ide> $query->shouldReceive('update')->once()->with(['created_at' => 'foo', 'updated_at' => 'bar'])->andReturn(1); <del> $model->expects($this->once())->method('newQueryWithoutScopes')->will($this->returnValue($query)); <add> $model->expects($this->once())->method('newUneagerQueryWithoutScopes')->will($this->returnValue($query)); <ide> $model->setEventDispatcher($events = m::mock('Illuminate\Contracts\Events\Dispatcher')); <ide> $events->shouldReceive('until'); <ide> $events->shouldReceive('fire'); <ide> public function testUpdateProcessDoesntOverrideTimestamps() <ide> <ide> public function testSaveIsCancelledIfSavingEventReturnsFalse() <ide> { <del> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newQueryWithoutScopes'])->getMock(); <add> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newUneagerQueryWithoutScopes'])->getMock(); <ide> $query = m::mock('Illuminate\Database\Eloquent\Builder'); <del> $model->expects($this->once())->method('newQueryWithoutScopes')->will($this->returnValue($query)); <add> $model->expects($this->once())->method('newUneagerQueryWithoutScopes')->will($this->returnValue($query)); <ide> $model->setEventDispatcher($events = m::mock('Illuminate\Contracts\Events\Dispatcher')); <ide> $events->shouldReceive('until')->once()->with('eloquent.saving: '.get_class($model), $model)->andReturn(false); <ide> $model->exists = true; <ide> public function testSaveIsCancelledIfSavingEventReturnsFalse() <ide> <ide> public function testUpdateIsCancelledIfUpdatingEventReturnsFalse() <ide> { <del> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newQueryWithoutScopes'])->getMock(); <add> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newUneagerQueryWithoutScopes'])->getMock(); <ide> $query = m::mock('Illuminate\Database\Eloquent\Builder'); <del> $model->expects($this->once())->method('newQueryWithoutScopes')->will($this->returnValue($query)); <add> $model->expects($this->once())->method('newUneagerQueryWithoutScopes')->will($this->returnValue($query)); <ide> $model->setEventDispatcher($events = m::mock('Illuminate\Contracts\Events\Dispatcher')); <ide> $events->shouldReceive('until')->once()->with('eloquent.saving: '.get_class($model), $model)->andReturn(true); <ide> $events->shouldReceive('until')->once()->with('eloquent.updating: '.get_class($model), $model)->andReturn(false); <ide> public function testUpdateIsCancelledIfUpdatingEventReturnsFalse() <ide> <ide> public function testEventsCanBeFiredWithCustomEventObjects() <ide> { <del> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelEventObjectStub')->setMethods(['newQueryWithoutScopes'])->getMock(); <add> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelEventObjectStub')->setMethods(['newUneagerQueryWithoutScopes'])->getMock(); <ide> $query = m::mock('Illuminate\Database\Eloquent\Builder'); <del> $model->expects($this->once())->method('newQueryWithoutScopes')->will($this->returnValue($query)); <add> $model->expects($this->once())->method('newUneagerQueryWithoutScopes')->will($this->returnValue($query)); <ide> $model->setEventDispatcher($events = m::mock('Illuminate\Contracts\Events\Dispatcher')); <ide> $events->shouldReceive('until')->once()->with(m::type(EloquentModelSavingEventStub::class))->andReturn(false); <ide> $model->exists = true; <ide> public function testEventsCanBeFiredWithCustomEventObjects() <ide> <ide> public function testUpdateProcessWithoutTimestamps() <ide> { <del> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelEventObjectStub')->setMethods(['newQueryWithoutScopes', 'updateTimestamps', 'fireModelEvent'])->getMock(); <add> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelEventObjectStub')->setMethods(['newUneagerQueryWithoutScopes', 'updateTimestamps', 'fireModelEvent'])->getMock(); <ide> $model->timestamps = false; <ide> $query = m::mock('Illuminate\Database\Eloquent\Builder'); <ide> $query->shouldReceive('where')->once()->with('id', '=', 1); <ide> $query->shouldReceive('update')->once()->with(['name' => 'taylor'])->andReturn(1); <del> $model->expects($this->once())->method('newQueryWithoutScopes')->will($this->returnValue($query)); <add> $model->expects($this->once())->method('newUneagerQueryWithoutScopes')->will($this->returnValue($query)); <ide> $model->expects($this->never())->method('updateTimestamps'); <ide> $model->expects($this->any())->method('fireModelEvent')->will($this->returnValue(true)); <ide> <ide> public function testUpdateProcessWithoutTimestamps() <ide> <ide> public function testUpdateUsesOldPrimaryKey() <ide> { <del> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newQueryWithoutScopes', 'updateTimestamps'])->getMock(); <add> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newUneagerQueryWithoutScopes', 'updateTimestamps'])->getMock(); <ide> $query = m::mock('Illuminate\Database\Eloquent\Builder'); <ide> $query->shouldReceive('where')->once()->with('id', '=', 1); <ide> $query->shouldReceive('update')->once()->with(['id' => 2, 'foo' => 'bar'])->andReturn(1); <del> $model->expects($this->once())->method('newQueryWithoutScopes')->will($this->returnValue($query)); <add> $model->expects($this->once())->method('newUneagerQueryWithoutScopes')->will($this->returnValue($query)); <ide> $model->expects($this->once())->method('updateTimestamps'); <ide> $model->setEventDispatcher($events = m::mock('Illuminate\Contracts\Events\Dispatcher')); <ide> $events->shouldReceive('until')->once()->with('eloquent.saving: '.get_class($model), $model)->andReturn(true); <ide> public function testFromDateTime() <ide> <ide> public function testInsertProcess() <ide> { <del> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newQueryWithoutScopes', 'updateTimestamps', 'refresh'])->getMock(); <add> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newUneagerQueryWithoutScopes', 'updateTimestamps', 'refresh'])->getMock(); <ide> $query = m::mock('Illuminate\Database\Eloquent\Builder'); <ide> $query->shouldReceive('insertGetId')->once()->with(['name' => 'taylor'], 'id')->andReturn(1); <ide> $query->shouldReceive('getConnection')->once(); <del> $model->expects($this->once())->method('newQueryWithoutScopes')->will($this->returnValue($query)); <add> $model->expects($this->once())->method('newUneagerQueryWithoutScopes')->will($this->returnValue($query)); <ide> $model->expects($this->once())->method('updateTimestamps'); <ide> <ide> $model->setEventDispatcher($events = m::mock('Illuminate\Contracts\Events\Dispatcher')); <ide> public function testInsertProcess() <ide> $this->assertEquals(1, $model->id); <ide> $this->assertTrue($model->exists); <ide> <del> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newQueryWithoutScopes', 'updateTimestamps', 'refresh'])->getMock(); <add> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newUneagerQueryWithoutScopes', 'updateTimestamps', 'refresh'])->getMock(); <ide> $query = m::mock('Illuminate\Database\Eloquent\Builder'); <ide> $query->shouldReceive('insert')->once()->with(['name' => 'taylor']); <ide> $query->shouldReceive('getConnection')->once(); <del> $model->expects($this->once())->method('newQueryWithoutScopes')->will($this->returnValue($query)); <add> $model->expects($this->once())->method('newUneagerQueryWithoutScopes')->will($this->returnValue($query)); <ide> $model->expects($this->once())->method('updateTimestamps'); <ide> $model->setIncrementing(false); <ide> <ide> public function testInsertProcess() <ide> <ide> public function testInsertIsCancelledIfCreatingEventReturnsFalse() <ide> { <del> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newQueryWithoutScopes'])->getMock(); <add> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newUneagerQueryWithoutScopes'])->getMock(); <ide> $query = m::mock('Illuminate\Database\Eloquent\Builder'); <ide> $query->shouldReceive('getConnection')->once(); <del> $model->expects($this->once())->method('newQueryWithoutScopes')->will($this->returnValue($query)); <add> $model->expects($this->once())->method('newUneagerQueryWithoutScopes')->will($this->returnValue($query)); <ide> $model->setEventDispatcher($events = m::mock('Illuminate\Contracts\Events\Dispatcher')); <ide> $events->shouldReceive('until')->once()->with('eloquent.saving: '.get_class($model), $model)->andReturn(true); <ide> $events->shouldReceive('until')->once()->with('eloquent.creating: '.get_class($model), $model)->andReturn(false); <ide> public function testInsertIsCancelledIfCreatingEventReturnsFalse() <ide> <ide> public function testDeleteProperlyDeletesModel() <ide> { <del> $model = $this->getMockBuilder('Illuminate\Database\Eloquent\Model')->setMethods(['newQueryWithoutScopes', 'updateTimestamps', 'touchOwners'])->getMock(); <add> $model = $this->getMockBuilder('Illuminate\Database\Eloquent\Model')->setMethods(['newUneagerQueryWithoutScopes', 'updateTimestamps', 'touchOwners'])->getMock(); <ide> $query = m::mock('Illuminate\Database\Eloquent\Builder'); <ide> $query->shouldReceive('where')->once()->with('id', '=', 1)->andReturn($query); <ide> $query->shouldReceive('delete')->once(); <del> $model->expects($this->once())->method('newQueryWithoutScopes')->will($this->returnValue($query)); <add> $model->expects($this->once())->method('newUneagerQueryWithoutScopes')->will($this->returnValue($query)); <ide> $model->expects($this->once())->method('touchOwners'); <ide> $model->exists = true; <ide> $model->id = 1; <ide> public function testDeleteProperlyDeletesModel() <ide> <ide> public function testPushNoRelations() <ide> { <del> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newQueryWithoutScopes', 'updateTimestamps', 'refresh'])->getMock(); <add> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newUneagerQueryWithoutScopes', 'updateTimestamps', 'refresh'])->getMock(); <ide> $query = m::mock('Illuminate\Database\Eloquent\Builder'); <ide> $query->shouldReceive('insertGetId')->once()->with(['name' => 'taylor'], 'id')->andReturn(1); <ide> $query->shouldReceive('getConnection')->once(); <del> $model->expects($this->once())->method('newQueryWithoutScopes')->will($this->returnValue($query)); <add> $model->expects($this->once())->method('newUneagerQueryWithoutScopes')->will($this->returnValue($query)); <ide> $model->expects($this->once())->method('updateTimestamps'); <ide> <ide> $model->name = 'taylor'; <ide> public function testPushNoRelations() <ide> <ide> public function testPushEmptyOneRelation() <ide> { <del> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newQueryWithoutScopes', 'updateTimestamps', 'refresh'])->getMock(); <add> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newUneagerQueryWithoutScopes', 'updateTimestamps', 'refresh'])->getMock(); <ide> $query = m::mock('Illuminate\Database\Eloquent\Builder'); <ide> $query->shouldReceive('insertGetId')->once()->with(['name' => 'taylor'], 'id')->andReturn(1); <ide> $query->shouldReceive('getConnection')->once(); <del> $model->expects($this->once())->method('newQueryWithoutScopes')->will($this->returnValue($query)); <add> $model->expects($this->once())->method('newUneagerQueryWithoutScopes')->will($this->returnValue($query)); <ide> $model->expects($this->once())->method('updateTimestamps'); <ide> <ide> $model->name = 'taylor'; <ide> public function testPushEmptyOneRelation() <ide> <ide> public function testPushOneRelation() <ide> { <del> $related1 = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newQueryWithoutScopes', 'updateTimestamps', 'refresh'])->getMock(); <add> $related1 = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newUneagerQueryWithoutScopes', 'updateTimestamps', 'refresh'])->getMock(); <ide> $query = m::mock('Illuminate\Database\Eloquent\Builder'); <ide> $query->shouldReceive('insertGetId')->once()->with(['name' => 'related1'], 'id')->andReturn(2); <ide> $query->shouldReceive('getConnection')->once(); <del> $related1->expects($this->once())->method('newQueryWithoutScopes')->will($this->returnValue($query)); <add> $related1->expects($this->once())->method('newUneagerQueryWithoutScopes')->will($this->returnValue($query)); <ide> $related1->expects($this->once())->method('updateTimestamps'); <ide> $related1->name = 'related1'; <ide> $related1->exists = false; <ide> <del> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newQueryWithoutScopes', 'updateTimestamps', 'refresh'])->getMock(); <add> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newUneagerQueryWithoutScopes', 'updateTimestamps', 'refresh'])->getMock(); <ide> $query = m::mock('Illuminate\Database\Eloquent\Builder'); <ide> $query->shouldReceive('insertGetId')->once()->with(['name' => 'taylor'], 'id')->andReturn(1); <ide> $query->shouldReceive('getConnection')->once(); <del> $model->expects($this->once())->method('newQueryWithoutScopes')->will($this->returnValue($query)); <add> $model->expects($this->once())->method('newUneagerQueryWithoutScopes')->will($this->returnValue($query)); <ide> $model->expects($this->once())->method('updateTimestamps'); <ide> <ide> $model->name = 'taylor'; <ide> public function testPushOneRelation() <ide> <ide> public function testPushEmptyManyRelation() <ide> { <del> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newQueryWithoutScopes', 'updateTimestamps', 'refresh'])->getMock(); <add> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newUneagerQueryWithoutScopes', 'updateTimestamps', 'refresh'])->getMock(); <ide> $query = m::mock('Illuminate\Database\Eloquent\Builder'); <ide> $query->shouldReceive('insertGetId')->once()->with(['name' => 'taylor'], 'id')->andReturn(1); <ide> $query->shouldReceive('getConnection')->once(); <del> $model->expects($this->once())->method('newQueryWithoutScopes')->will($this->returnValue($query)); <add> $model->expects($this->once())->method('newUneagerQueryWithoutScopes')->will($this->returnValue($query)); <ide> $model->expects($this->once())->method('updateTimestamps'); <ide> <ide> $model->name = 'taylor'; <ide> public function testPushEmptyManyRelation() <ide> <ide> public function testPushManyRelation() <ide> { <del> $related1 = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newQueryWithoutScopes', 'updateTimestamps', 'refresh'])->getMock(); <add> $related1 = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newUneagerQueryWithoutScopes', 'updateTimestamps', 'refresh'])->getMock(); <ide> $query = m::mock('Illuminate\Database\Eloquent\Builder'); <ide> $query->shouldReceive('insertGetId')->once()->with(['name' => 'related1'], 'id')->andReturn(2); <ide> $query->shouldReceive('getConnection')->once(); <del> $related1->expects($this->once())->method('newQueryWithoutScopes')->will($this->returnValue($query)); <add> $related1->expects($this->once())->method('newUneagerQueryWithoutScopes')->will($this->returnValue($query)); <ide> $related1->expects($this->once())->method('updateTimestamps'); <ide> $related1->name = 'related1'; <ide> $related1->exists = false; <ide> <del> $related2 = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newQueryWithoutScopes', 'updateTimestamps', 'refresh'])->getMock(); <add> $related2 = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newUneagerQueryWithoutScopes', 'updateTimestamps', 'refresh'])->getMock(); <ide> $query = m::mock('Illuminate\Database\Eloquent\Builder'); <ide> $query->shouldReceive('insertGetId')->once()->with(['name' => 'related2'], 'id')->andReturn(3); <ide> $query->shouldReceive('getConnection')->once(); <del> $related2->expects($this->once())->method('newQueryWithoutScopes')->will($this->returnValue($query)); <add> $related2->expects($this->once())->method('newUneagerQueryWithoutScopes')->will($this->returnValue($query)); <ide> $related2->expects($this->once())->method('updateTimestamps'); <ide> $related2->name = 'related2'; <ide> $related2->exists = false; <ide> <del> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newQueryWithoutScopes', 'updateTimestamps', 'refresh'])->getMock(); <add> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newUneagerQueryWithoutScopes', 'updateTimestamps', 'refresh'])->getMock(); <ide> $query = m::mock('Illuminate\Database\Eloquent\Builder'); <ide> $query->shouldReceive('insertGetId')->once()->with(['name' => 'taylor'], 'id')->andReturn(1); <ide> $query->shouldReceive('getConnection')->once(); <del> $model->expects($this->once())->method('newQueryWithoutScopes')->will($this->returnValue($query)); <add> $model->expects($this->once())->method('newUneagerQueryWithoutScopes')->will($this->returnValue($query)); <ide> $model->expects($this->once())->method('updateTimestamps'); <ide> <ide> $model->name = 'taylor'; <ide> public function testNonExistingAttributeWithInternalMethodNameDoesntCallMethod() <ide> <ide> public function testIntKeyTypePreserved() <ide> { <del> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newQueryWithoutScopes', 'updateTimestamps', 'refresh'])->getMock(); <add> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentModelStub')->setMethods(['newUneagerQueryWithoutScopes', 'updateTimestamps', 'refresh'])->getMock(); <ide> $query = m::mock('Illuminate\Database\Eloquent\Builder'); <ide> $query->shouldReceive('insertGetId')->once()->with([], 'id')->andReturn(1); <ide> $query->shouldReceive('getConnection')->once(); <del> $model->expects($this->once())->method('newQueryWithoutScopes')->will($this->returnValue($query)); <add> $model->expects($this->once())->method('newUneagerQueryWithoutScopes')->will($this->returnValue($query)); <ide> <ide> $this->assertTrue($model->save()); <ide> $this->assertEquals(1, $model->id); <ide> } <ide> <ide> public function testStringKeyTypePreserved() <ide> { <del> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentKeyTypeModelStub')->setMethods(['newQueryWithoutScopes', 'updateTimestamps', 'refresh'])->getMock(); <add> $model = $this->getMockBuilder('Illuminate\Tests\Database\EloquentKeyTypeModelStub')->setMethods(['newUneagerQueryWithoutScopes', 'updateTimestamps', 'refresh'])->getMock(); <ide> $query = m::mock('Illuminate\Database\Eloquent\Builder'); <ide> $query->shouldReceive('insertGetId')->once()->with([], 'id')->andReturn('string id'); <ide> $query->shouldReceive('getConnection')->once(); <del> $model->expects($this->once())->method('newQueryWithoutScopes')->will($this->returnValue($query)); <add> $model->expects($this->once())->method('newUneagerQueryWithoutScopes')->will($this->returnValue($query)); <ide> <ide> $this->assertTrue($model->save()); <ide> $this->assertEquals('string id', $model->id); <ide><path>tests/Database/DatabaseSoftDeletingTraitTest.php <ide> public function testDeleteSetsSoftDeletedColumn() <ide> $model = m::mock('Illuminate\Tests\Database\DatabaseSoftDeletingTraitStub'); <ide> $model->shouldDeferMissing(); <ide> // $model->shouldReceive('newQuery')->andReturn($query = m::mock('stdClass')); <del> $model->shouldReceive('newQueryWithoutScopes')->andReturn($query = m::mock('stdClass')); <add> $model->shouldReceive('newUneagerQueryWithoutScopes')->andReturn($query = m::mock('stdClass')); <ide> $query->shouldReceive('where')->once()->with('id', 1)->andReturn($query); <ide> $query->shouldReceive('update')->once()->with([ <ide> 'deleted_at' => 'date-time',
6
Javascript
Javascript
check the origin of the blob urls
39f7e724405c81b7e5905e003f431ac034b79cd5
<ide><path>test/fixtures/url-tests.js <ide> module.exports = <ide> "input": "non-special://[:80/", <ide> "base": "about:blank", <ide> "failure": true <add> }, <add> { <add> "input": "blob:https://example.com:443/", <add> "base": "about:blank", <add> "href": "blob:https://example.com:443/", <add> "protocol": "blob:", <add> "username": "", <add> "password": "", <add> "host": "", <add> "hostname": "", <add> "port": "", <add> "pathname": "https://example.com:443/", <add> "search": "", <add> "hash": "" <add> }, <add> { <add> "input": "blob:d3958f5c-0777-0845-9dcf-2cb28783acaf", <add> "base": "about:blank", <add> "href": "blob:d3958f5c-0777-0845-9dcf-2cb28783acaf", <add> "protocol": "blob:", <add> "username": "", <add> "password": "", <add> "host": "", <add> "hostname": "", <add> "port": "", <add> "pathname": "d3958f5c-0777-0845-9dcf-2cb28783acaf", <add> "search": "", <add> "hash": "" <ide> } <ide> ]
1
Java
Java
fix priority semantic
b78b2e9a03f5a6b7924dda0f8d709a5a9b23e24c
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java <ide> else if (candidateLocal) { <ide> } <ide> <ide> /** <del> * Determine the candidate with the highest priority in the given set of beans. <add> * Determine the candidate with the highest priority in the given set of beans. As <add> * defined by the {@link org.springframework.core.Ordered} interface, the lowest <add> * value has the highest priority. <ide> * @param candidateBeans a Map of candidate names and candidate instances <ide> * that match the required type <ide> * @param requiredType the target dependency type to match against <ide> protected String determineHighestPriorityCandidate(Map<String, Object> candidate <ide> "Multiple beans found with the same priority ('" + highestPriority + "') " + <ide> "among candidates: " + candidateBeans.keySet()); <ide> } <del> else if (candidatePriority > highestPriority) { <add> else if (candidatePriority < highestPriority) { <ide> highestPriorityBeanName = candidateBeanName; <ide> highestPriority = candidatePriority; <ide> } <ide><path>spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java <ide> public void testGetBeanByTypeWithMultiplePriority() throws Exception { <ide> lbf.registerBeanDefinition("bd2", bd2); <ide> thrown.expect(NoUniqueBeanDefinitionException.class); <ide> thrown.expectMessage(containsString("Multiple beans found with the same priority")); <del> thrown.expectMessage(containsString("500")); // conflicting priority <add> thrown.expectMessage(containsString("5")); // conflicting priority <ide> lbf.getBean(TestBean.class); <ide> } <ide> <ide> public void testAutowireBeanByTypeWithIdenticalPriorityCandidates() { <ide> // expected <ide> assertNotNull("Exception should have cause", ex.getCause()); <ide> assertEquals("Wrong cause type", NoUniqueBeanDefinitionException.class, ex.getCause().getClass()); <del> assertTrue(ex.getMessage().contains("500")); // conflicting priority <add> assertTrue(ex.getMessage().contains("5")); // conflicting priority <ide> } <ide> } <ide> <ide> public KnowsIfInstantiated() { <ide> <ide> } <ide> <del> @Priority(500) <add> @Priority(5) <ide> private static class HighPriorityTestBean extends TestBean {} <ide> <del> @Priority(5) <add> @Priority(500) <ide> private static class LowPriorityTestBean extends TestBean {} <ide> <ide>
2
Javascript
Javascript
add unit tests for .html( number ). close gh-1447
ed291938c287d34fe1183e588e12372e540eb5e7
<ide><path>test/unit/manipulation.js <ide> function testText( valueObj ) { <ide> $parentDiv = jQuery( "<div/>" ); <ide> $parentDiv.append( $childDiv ); <ide> $parentDiv.text("Dry off"); <del> <add> <ide> equal( $childDiv.data("leak"), undefined, "Check for leaks (#11809)" ); <ide> } <ide> <ide> function childNodeNames( node ) { <ide> } <ide> <ide> function testHtml( valueObj ) { <del> expect( 37 ); <add> expect( 40 ); <ide> <ide> var actual, expected, tmp, <ide> div = jQuery("<div></div>"), <ide> function testHtml( valueObj ) { <ide> <ide> equal( div.html(valueObj(5)).html(), "5", "Setting a number as html" ); <ide> equal( div.html(valueObj(0)).html(), "0", "Setting a zero as html" ); <add> equal( div.html(valueObj(Infinity)).html(), "Infinity", "Setting Infinity as html" ); <add> equal( div.html(valueObj(NaN)).html(), "", "Setting NaN as html" ); <add> equal( div.html(valueObj(1e2)).html(), "100", "Setting exponential number notation as html" ); <ide> <ide> div.html( valueObj("&#160;&amp;") ); <ide> equal( <ide> function testHtml( valueObj ) { <ide> ok( /^[^<]*[^<\s][^<]*$/.test( fixture.html() ), "Replace html with text" ); <ide> } <ide> <del>test( "html(String)", function() { <add>test( "html(String|Number)", function() { <ide> testHtml( manipulationBareObj ); <ide> }); <ide>
1
Ruby
Ruby
add retry handling to connection establishment too
02f5de1bc93407e878cf4d92e2caf46d4c6e5409
<ide><path>activerecord/lib/active_record/connection_adapters/abstract_adapter.rb <ide> def all_foreign_keys_valid? <ide> def active? <ide> end <ide> <del> # Disconnects from the database if already connected, and establishes a <del> # new connection with the database. Implementors should call super <del> # immediately after establishing the new connection (and while still <del> # holding @lock). <add> # Disconnects from the database if already connected, and establishes a new <add> # connection with the database. Implementors should define private #reconnect <add> # instead. <ide> def reconnect!(restore_transactions: false) <del> enable_lazy_transactions! <del> @raw_connection_dirty = false <del> @verified = true <add> retries_available = connection_retries <add> <add> @lock.synchronize do <add> reconnect <add> <add> enable_lazy_transactions! <add> @raw_connection_dirty = false <add> @verified = true <add> <add> reset_transaction(restore: restore_transactions) do <add> clear_cache!(new_connection: true) <add> configure_connection <add> end <add> rescue => original_exception <add> translated_exception = translate_exception_class(original_exception, nil, nil) <add> <add> if retries_available > 0 <add> retries_available -= 1 <add> <add> if retryable_connection_error?(translated_exception) <add> backoff(connection_retries - retries_available) <add> retry <add> end <add> end <ide> <del> reset_transaction(restore: restore_transactions) do <del> clear_cache!(new_connection: true) <del> configure_connection <add> @verified = false <add> <add> raise translated_exception <ide> end <ide> end <ide> <add> <ide> # Disconnects from the database if already connected. Otherwise, this <ide> # method does nothing. <ide> def disconnect! <ide> def with_raw_connection(allow_retry: false, uses_transaction: true) <ide> @lock.synchronize do <ide> materialize_transactions if uses_transaction <ide> <del> retries_available = 0 <add> retries_available = allow_retry ? connection_retries : 0 <ide> <del> if reconnect_can_restore_state? <add> if @verified <add> # Cool, we're confident the connection's ready to use. (Note this might have <add> # become true during the above #materialize_transactions.) <add> elsif reconnect_can_restore_state? <ide> if allow_retry <del> retries_available = connection_retries <del> elsif !@verified <add> # Not sure about the connection yet, but if anything goes wrong we can <add> # just reconnect and re-run our query <add> else <add> # We can reconnect if needed, but we don't trust the upcoming query to be <add> # safely re-runnable: let's verify the connection to be sure <ide> verify! <ide> end <add> else <add> # We don't know whether the connection is okay, but it also doesn't matter: <add> # we wouldn't be able to reconnect anyway. We're just going to run our query <add> # and hope for the best. <ide> end <ide> <ide> begin <ide> def with_raw_connection(allow_retry: false, uses_transaction: true) <ide> if retryable_query_error?(translated_exception) <ide> backoff(connection_retries - retries_available) <ide> retry <del> elsif retryable_connection_error?(translated_exception) <add> elsif retryable_connection_error?(translated_exception) && <add> reconnect_can_restore_state? <ide> reconnect!(restore_transactions: true) <ide> retry <ide> end <ide> def backoff(counter) <ide> sleep 0.1 * counter <ide> end <ide> <add> def reconnect <add> raise NotImplementedError <add> end <add> <ide> # Returns a raw connection for internal use with methods that are known <ide> # to both be thread-safe and not rely upon actual server communication. <ide> # This is useful for e.g. string escaping methods. <ide><path>activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb <ide> def active? <ide> @raw_connection.ping <ide> end <ide> <del> def reconnect!(restore_transactions: false) <del> @lock.synchronize do <del> @raw_connection.close <del> connect <del> super <del> end <del> end <ide> alias :reset! :reconnect! <ide> <ide> # Disconnects from the database if already connected. <ide> def connect <ide> @raw_connection = self.class.new_client(@config) <ide> end <ide> <add> def reconnect <add> @raw_connection.close <add> connect <add> end <add> <ide> def configure_connection <ide> @raw_connection.query_options[:as] = :array <ide> @raw_connection.query_options[:database_timezone] = default_timezone <ide><path>activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb <ide> def reload_type_map # :nodoc: <ide> end <ide> end <ide> <del> # Close then reopen the connection. <del> def reconnect!(restore_transactions: false) <del> @lock.synchronize do <del> begin <del> @raw_connection.reset <del> rescue PG::ConnectionBad <del> connect <del> end <del> <del> super <del> end <del> end <del> <ide> def reset! <ide> @lock.synchronize do <ide> unless @raw_connection.transaction_status == ::PG::PQTRANS_IDLE <ide> def connect <ide> @raw_connection = self.class.new_client(@connection_parameters) <ide> end <ide> <add> def reconnect <add> @raw_connection.reset <add> rescue PG::ConnectionBad <add> connect <add> end <add> <ide> # Configures the encoding, verbosity, schema search path, and time zone of the connection. <ide> # This is called by #connect and should not be called manually. <ide> def configure_connection <ide><path>activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb <ide> def active? <ide> !@raw_connection.closed? <ide> end <ide> <del> def reconnect!(restore_transactions: false) <del> @lock.synchronize do <del> if active? <del> @raw_connection.rollback rescue nil <del> else <del> connect <del> end <del> <del> super <del> end <del> end <ide> alias :reset! :reconnect! <ide> <ide> # Disconnects from the database if already connected. Otherwise, this <ide> def connect <ide> ) <ide> end <ide> <add> def reconnect <add> if active? <add> @raw_connection.rollback rescue nil <add> else <add> connect <add> end <add> end <add> <ide> def configure_connection <ide> @raw_connection.busy_timeout(self.class.type_cast_config_to_integer(@config[:timeout])) if @config[:timeout] <ide>
4
Python
Python
trap key errors in debug, not all 400 errors
b573a86977161b93152dddb5bfc43195335b3c59
<ide><path>flask/app.py <ide> def trap_http_exception(self, e): <ide> <ide> trap_bad_request = self.config['TRAP_BAD_REQUEST_ERRORS'] <ide> <del> # if unset, trap based on debug mode <del> if (trap_bad_request is None and self.debug) or trap_bad_request: <add> # if unset, trap key errors in debug mode <add> if ( <add> trap_bad_request is None and self.debug <add> and isinstance(e, BadRequestKeyError) <add> ): <add> return True <add> <add> if trap_bad_request: <ide> return isinstance(e, BadRequest) <ide> <ide> return False <ide><path>tests/test_basic.py <ide> def raise_e3(): <ide> <ide> <ide> def test_trapping_of_bad_request_key_errors(app, client): <del> @app.route('/fail') <add> @app.route('/key') <ide> def fail(): <ide> flask.request.form['missing_key'] <ide> <del> rv = client.get('/fail') <add> @app.route('/abort') <add> def allow_abort(): <add> flask.abort(400) <add> <add> rv = client.get('/key') <ide> assert rv.status_code == 400 <ide> assert b'missing_key' not in rv.data <add> rv = client.get('/abort') <add> assert rv.status_code == 400 <ide> <del> app.config['TRAP_BAD_REQUEST_ERRORS'] = True <del> <add> app.debug = True <ide> with pytest.raises(KeyError) as e: <del> client.get("/fail") <del> <add> client.get("/key") <ide> assert e.errisinstance(BadRequest) <ide> assert 'missing_key' in e.value.description <add> rv = client.get('/abort') <add> assert rv.status_code == 400 <add> <add> app.debug = False <add> app.config['TRAP_BAD_REQUEST_ERRORS'] = True <add> with pytest.raises(KeyError): <add> client.get('/key') <add> with pytest.raises(BadRequest): <add> client.get('/abort') <ide> <ide> <ide> def test_trapping_of_all_http_exceptions(app, client):
2
Javascript
Javascript
use default priority of "" rather than null
420fed15d38b4916bf0c2c4f3fece5aebb3f61dd
<ide><path>d3.js <ide> function d3_selection(groups) { <ide> }; <ide> <ide> groups.style = function(name, value, priority) { <del> if (arguments.length < 3) priority = null; <add> if (arguments.length < 3) priority = ""; <ide> <ide> // If no value is specified, return the first value. <ide> if (arguments.length < 2) { <ide><path>d3.min.js <del>(function(){function bT(){return"circle"}function bS(){return 64}function bQ(a){return[a.x,a.y]}function bP(a){return a.endAngle}function bO(a){return a.startAngle}function bN(a){return a.radius}function bM(a){return a.target}function bL(a){return a.source}function bK(){return 0}function bJ(a,b,c){a.push("C",bF(bG,b),",",bF(bG,c),",",bF(bH,b),",",bF(bH,c),",",bF(bI,b),",",bF(bI,c))}function bF(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3]}function bE(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=[bF(bI,g),",",bF(bI,h)],--c;while(++c<e)f=a[c%d],g.shift(),g.push(f[0]),h.shift(),h.push(f[1]),bJ(b,g,h);return b.join("")}function bD(a){if(a.length<3)return bw(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),bJ(b,h,i);while(++c<d)e=a[c],h.shift(),h.push(e[0]),i.shift(),i.push(e[1]),bJ(b,h,i);c=-1;while(++c<2)h.shift(),h.push(e[0]),i.shift(),i.push(e[1]),bJ(b,h,i);return b.join("")}function bC(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 bB(a,b){if(b.length<1||a.length!=b.length&&a.length!=b.length+2)return bw(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 bA(a,b,c){return a.length<3?bw(a):a[0]+bB(a,bC(a,b))}function bz(a,b){return a.length<3?bw(a):a[0]+bB((a.push(a[0]),a),bC([a[a.length-2]].concat(a,[a[1]]),b))}function by(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 bx(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 bw(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 bu(a){return a[1]}function bt(a){return a[0]}function bs(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 br(a){return a.endAngle}function bq(a){return a.startAngle}function bp(a){return a.outerRadius}function bo(a){return a.innerRadius}function bh(a){return function(b){return-Math.pow(-b,a)}}function bg(a){return function(b){return Math.pow(b,a)}}function bf(a){return-Math.log(-a)/Math.LN10}function be(a){return Math.log(a)/Math.LN10}function bc(){var a=null,b=Y;while(b)b=b.flush?a?a.next=b.next:Y=b.next:(a=b).next;a||($=0)}function bb(){var a,b=Date.now(),c=null,d=Y;while(d)a=b-d.then,a>d.delay&&(d.flush=d.callback(a)),d=(c=d).next;bc(),$&&bd(bb)}function ba(){$=1,Z=0,bd(bb)}function _(a,b){var c=Date.now(),d=!1,e=c+b,f,g=Y;if(!!isFinite(b)){while(g){if(g.callback==a)g.then=c,g.delay=b,d=!0;else{var h=g.then+g.delay;h<e&&(e=h)}f=g,g=g.next}d||(Y={callback:a,then:c,delay:b,next:Y}),$||(clearTimeout(Z),Z=setTimeout(ba,Math.max(24,e-c)))}}function X(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 W(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)),V=c,h.end.dispatch.apply(this,arguments),V=0,n.owner=r}}}});return g}var b={},c=V||++U,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})),_(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,X(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,X(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=W(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=W(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 T(a){return{__data__:a}}function S(a){arguments.length||(a=d3.ascending);return function(b,c){return a(b&&b.__data__,c&&c.__data__)}}function R(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 Q(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),N(c,b))}function d(b){return b.insertBefore(document.createElement(a),N(c,b))}a=d3.ns.qualify(a);return b(a.local?e:d)};return a}function Q(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 Q(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 Q(c)}a.select=function(a){return b(function(b){return N(a,b)})},a.selectAll=function(a){return c(function(b){return O(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 Q(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]=T(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]=T(p),l[g]=n[g]=null);for(;g<i;g++)m[g]=T(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=Q(e);k.enter=function(){return R(d)},k.exit=function(){return Q(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(){var a=f(this.className.replace(e," "));this.className=a.length?a:null}function g(){var a=this.className;e.lastIndex=0,e.test(a)||(this.className=f(a+" "+b))}var e=new RegExp("(^|\\s+)"+d3.requote(b)+"(\\s+|$)","g");if(arguments.length<2)return d(function(){e.lastIndex=0;return e.test(this.className)});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=null);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),N(c,b))}function d(b){return b.insertBefore(document.createElement(a),N(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=S.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){var d=b.indexOf("."),e=d==-1?b:b.substring(0,d),f="__on"+b;return a.each(function(a,b){function d(d){var e=d3.event;d3.event=d;try{c.call(this,a,b)}finally{d3.event=e}}this[f]&&this.removeEventListener(e,this[f],!1),c&&this.addEventListener(e,this[f]=d,!1)})},a.transition=function(){return W(a)},a.call=g;return a}function M(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 C(g(a+120),g(a),g(a-120))}function L(){return"hsl("+this.h+","+this.s*100+"%,"+this.l*100+"%)"}function K(a,b,c){return{h:a,s:b,l:c,toString:L}}function H(a){var b=parseFloat(a);return a.charAt(a.length-1)=="%"?Math.round(b*2.55):b}function G(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 K(g,h,i)}function F(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(H(h[0]),H(h[1]),H(h[2]))}}if(i=I[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 E(a){return a<16?"0"+a.toString(16):a.toString(16)}function D(){return"#"+E(this.r)+E(this.g)+E(this.b)}function C(a,b,c){return{r:a,g:b,b:c,toString:D}}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.11.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 I||/^(#|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 M(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?F(""+a,C,M):C(~~a,~~b,~~c)};var I={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 J in I)I[J]=F(I[J],C,M);d3.hsl=function(a,b,c){return arguments.length==1?F(""+a,G,K):K(+a,+b,+c)};var N=function(a,b){return b.querySelector(a)},O=function(b,c){return a(c.querySelectorAll(b))};typeof Sizzle=="function"&&(N=function(a,b){return Sizzle(a,b)[0]},O=function(a,b){return Sizzle.uniqueSort(Sizzle(a,b))});var P=Q([[document]]);P[0].parentNode=document.documentElement,d3.select=function(a){return typeof a=="string"?P.select(a):Q([[a]])},d3.selectAll=function(b){return typeof b=="string"?P.selectAll(b):Q([a(b)])},d3.transition=P.transition;var U=0,V=0,Y=null,Z=0,$;d3.timer=function(a){_(a,0)};var bd=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(a){setTimeout(a,17)};d3.scale={},d3.scale.linear=function(){function k(c){var d=Math.min(a,b),e=Math.max(a,b),f=e-d,g=Math.pow(10,Math.floor(Math.log(f/c)/Math.LN10)),h=c/(f/g);h<=.15?g*=10:h<=.35?g*=5:h<=.75&&(g*=2);return{start:Math.ceil(d/g)*g,stop:Math.floor(e/g)*g+g*.5,step:g}}function j(b){b=(b-a)*e;return h(i?Math.max(0,Math.min(1,b)):b)}var a=0,b=1,c=0,d=1,e=1,f=1,g=d3.interpolate,h=g(c,d),i=!1;j.invert=function(b){return(b-c)*f+a},j.domain=function(g){if(!arguments.length)return[a,b];a=+g[0],b=+g[1],e=1/(b-a),f=(b-a)/(d-c);return j},j.range=function(e){if(!arguments.length)return[c,d];c=e[0],d=e[1],f=(b-a)/(d-c),h=g(c,d);return j},j.rangeRound=function(a){return j.range(a).interpolate(d3.interpolateRound)},j.clamp=function(a){if(!arguments.length)return i;i=a;return j},j.interpolate=function(a){if(!arguments.length)return g;h=(g=a)(c,d);return j},j.ticks=function(a){var b=k(a);return d3.range(b.start,b.stop,b.step)},j.tickFormat=function(a){var b=Math.max(0,-Math.floor(Math.log(k(a).step)/Math.LN10+.01));return d3.format(",."+b+"f")};return j},d3.scale.log=function(){function d(c){return a(b(c))}var a=d3.scale.linear(),b=be,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?bf:be,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===bf){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},be.pow=function(a){return Math.pow(10,a)},bf.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?bh:bg;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(bi)},d3.scale.category20=function(){return d3.scale.ordinal().range(bj)},d3.scale.category20b=function(){return d3.scale.ordinal().range(bk)},d3.scale.category20c=function(){return d3.scale.ordinal().range(bl)};var bi=["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"],bj=["#1f77b4","#aec7e8","#ff7f0e","#ffbb78","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5","#8c564b","#c49c94","#e377c2","#f7b6d2","#7f7f7f","#c7c7c7","#bcbd22","#dbdb8d","#17becf","#9edae5"],bk=["#393b79","#5254a3","#6b6ecf","#9c9ede","#637939","#8ca252","#b5cf6b","#cedb9c","#8c6d31","#bd9e39","#e7ba52","#e7cb94","#843c39","#ad494a","#d6616b","#e7969c","#7b4173","#a55194","#ce6dbd","#de9ed6"],bl=["#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)+bm,h=d.apply(this,arguments)+bm,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>=bn?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=bo,b=bp,c=bq,d=br;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+bm;return[Math.cos(f)*e,Math.sin(f)*e]};return e};var bm=-Math.PI/2,bn=2*Math.PI-1e-6;d3.svg.line=function(){function f(c){return c.length<1?null:"M"+d(bs(this,c,a,b),e)}var a=bt,b=bu,c="linear",d=bv[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=bv[c=a];return f},f.tension=function(a){if(!arguments.length)return e;e=a;return f};return f};var bv={linear:bw,"step-before":bx,"step-after":by,basis:bD,"basis-closed":bE,cardinal:bA,"cardinal-closed":bz},bG=[0,2/3,1/3 <del>,0],bH=[0,1/3,2/3,0],bI=[0,1/6,2/3,1/6];d3.svg.area=function(){function g(d){return d.length<1?null:"M"+e(bs(this,d,a,c),f)+"L"+e(bs(this,d,a,b).reverse(),f)+"Z"}var a=bt,b=bK,c=bu,d="linear",e=bv[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=bv[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)+bm,k=e.call(a,h,g)+bm;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=bL,b=bM,c=bN,d=bq,e=br;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=bL,b=bM,c=bQ;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){var b=(a.ownerSVGElement||a).createSVGPoint();if(bR<0&&(window.scrollX||window.scrollY)){var c=d3.select(document.body).append("svg:svg").style("position","absolute").style("top",0).style("left",0),d=c[0][0].getScreenCTM();bR=!d.f&&!d.e,c.remove()}bR?(b.x=d3.event.pageX,b.y=d3.event.pageY):(b.x=d3.event.clientX,b.y=d3.event.clientY),b=b.matrixTransform(a.getScreenCTM().inverse());return[b.x,b.y]};var bR=/WebKit/.test(navigator.userAgent)?-1:0;d3.svg.symbol=function(){function c(c,d){return(bU[a.call(this,c,d)]||bU.circle)(b.call(this,c,d))}var a=bT,b=bS;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 bU={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*bW)),c=b*bW;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/bV),c=b*bV/2;return"M0,"+c+"L"+b+","+ -c+" "+ -b+","+ -c+"Z"},"triangle-up":function(a){var b=Math.sqrt(a/bV),c=b*bV/2;return"M0,"+ -c+"L"+b+","+c+" "+ -b+","+c+"Z"}},bV=Math.sqrt(3),bW=Math.tan(30*Math.PI/180)})() <ide>\ No newline at end of file <add>(function(){function bT(){return"circle"}function bS(){return 64}function bQ(a){return[a.x,a.y]}function bP(a){return a.endAngle}function bO(a){return a.startAngle}function bN(a){return a.radius}function bM(a){return a.target}function bL(a){return a.source}function bK(){return 0}function bJ(a,b,c){a.push("C",bF(bG,b),",",bF(bG,c),",",bF(bH,b),",",bF(bH,c),",",bF(bI,b),",",bF(bI,c))}function bF(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3]}function bE(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=[bF(bI,g),",",bF(bI,h)],--c;while(++c<e)f=a[c%d],g.shift(),g.push(f[0]),h.shift(),h.push(f[1]),bJ(b,g,h);return b.join("")}function bD(a){if(a.length<3)return bw(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),bJ(b,h,i);while(++c<d)e=a[c],h.shift(),h.push(e[0]),i.shift(),i.push(e[1]),bJ(b,h,i);c=-1;while(++c<2)h.shift(),h.push(e[0]),i.shift(),i.push(e[1]),bJ(b,h,i);return b.join("")}function bC(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 bB(a,b){if(b.length<1||a.length!=b.length&&a.length!=b.length+2)return bw(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 bA(a,b,c){return a.length<3?bw(a):a[0]+bB(a,bC(a,b))}function bz(a,b){return a.length<3?bw(a):a[0]+bB((a.push(a[0]),a),bC([a[a.length-2]].concat(a,[a[1]]),b))}function by(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 bx(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 bw(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 bu(a){return a[1]}function bt(a){return a[0]}function bs(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 br(a){return a.endAngle}function bq(a){return a.startAngle}function bp(a){return a.outerRadius}function bo(a){return a.innerRadius}function bh(a){return function(b){return-Math.pow(-b,a)}}function bg(a){return function(b){return Math.pow(b,a)}}function bf(a){return-Math.log(-a)/Math.LN10}function be(a){return Math.log(a)/Math.LN10}function bc(){var a=null,b=Y;while(b)b=b.flush?a?a.next=b.next:Y=b.next:(a=b).next;a||($=0)}function bb(){var a,b=Date.now(),c=null,d=Y;while(d)a=b-d.then,a>d.delay&&(d.flush=d.callback(a)),d=(c=d).next;bc(),$&&bd(bb)}function ba(){$=1,Z=0,bd(bb)}function _(a,b){var c=Date.now(),d=!1,e=c+b,f,g=Y;if(!!isFinite(b)){while(g){if(g.callback==a)g.then=c,g.delay=b,d=!0;else{var h=g.then+g.delay;h<e&&(e=h)}f=g,g=g.next}d||(Y={callback:a,then:c,delay:b,next:Y}),$||(clearTimeout(Z),Z=setTimeout(ba,Math.max(24,e-c)))}}function X(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 W(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)),V=c,h.end.dispatch.apply(this,arguments),V=0,n.owner=r}}}});return g}var b={},c=V||++U,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})),_(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,X(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,X(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=W(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=W(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 T(a){return{__data__:a}}function S(a){arguments.length||(a=d3.ascending);return function(b,c){return a(b&&b.__data__,c&&c.__data__)}}function R(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 Q(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),N(c,b))}function d(b){return b.insertBefore(document.createElement(a),N(c,b))}a=d3.ns.qualify(a);return b(a.local?e:d)};return a}function Q(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 Q(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 Q(c)}a.select=function(a){return b(function(b){return N(a,b)})},a.selectAll=function(a){return c(function(b){return O(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 Q(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]=T(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]=T(p),l[g]=n[g]=null);for(;g<i;g++)m[g]=T(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=Q(e);k.enter=function(){return R(d)},k.exit=function(){return Q(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(){var a=f(this.className.replace(e," "));this.className=a.length?a:null}function g(){var a=this.className;e.lastIndex=0,e.test(a)||(this.className=f(a+" "+b))}var e=new RegExp("(^|\\s+)"+d3.requote(b)+"(\\s+|$)","g");if(arguments.length<2)return d(function(){e.lastIndex=0;return e.test(this.className)});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),N(c,b))}function d(b){return b.insertBefore(document.createElement(a),N(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=S.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){var d=b.indexOf("."),e=d==-1?b:b.substring(0,d),f="__on"+b;return a.each(function(a,b){function d(d){var e=d3.event;d3.event=d;try{c.call(this,a,b)}finally{d3.event=e}}this[f]&&this.removeEventListener(e,this[f],!1),c&&this.addEventListener(e,this[f]=d,!1)})},a.transition=function(){return W(a)},a.call=g;return a}function M(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 C(g(a+120),g(a),g(a-120))}function L(){return"hsl("+this.h+","+this.s*100+"%,"+this.l*100+"%)"}function K(a,b,c){return{h:a,s:b,l:c,toString:L}}function H(a){var b=parseFloat(a);return a.charAt(a.length-1)=="%"?Math.round(b*2.55):b}function G(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 K(g,h,i)}function F(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(H(h[0]),H(h[1]),H(h[2]))}}if(i=I[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 E(a){return a<16?"0"+a.toString(16):a.toString(16)}function D(){return"#"+E(this.r)+E(this.g)+E(this.b)}function C(a,b,c){return{r:a,g:b,b:c,toString:D}}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.11.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 I||/^(#|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 M(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?F(""+a,C,M):C(~~a,~~b,~~c)};var I={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 J in I)I[J]=F(I[J],C,M);d3.hsl=function(a,b,c){return arguments.length==1?F(""+a,G,K):K(+a,+b,+c)};var N=function(a,b){return b.querySelector(a)},O=function(b,c){return a(c.querySelectorAll(b))};typeof Sizzle=="function"&&(N=function(a,b){return Sizzle(a,b)[0]},O=function(a,b){return Sizzle.uniqueSort(Sizzle(a,b))});var P=Q([[document]]);P[0].parentNode=document.documentElement,d3.select=function(a){return typeof a=="string"?P.select(a):Q([[a]])},d3.selectAll=function(b){return typeof b=="string"?P.selectAll(b):Q([a(b)])},d3.transition=P.transition;var U=0,V=0,Y=null,Z=0,$;d3.timer=function(a){_(a,0)};var bd=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(a){setTimeout(a,17)};d3.scale={},d3.scale.linear=function(){function k(c){var d=Math.min(a,b),e=Math.max(a,b),f=e-d,g=Math.pow(10,Math.floor(Math.log(f/c)/Math.LN10)),h=c/(f/g);h<=.15?g*=10:h<=.35?g*=5:h<=.75&&(g*=2);return{start:Math.ceil(d/g)*g,stop:Math.floor(e/g)*g+g*.5,step:g}}function j(b){b=(b-a)*e;return h(i?Math.max(0,Math.min(1,b)):b)}var a=0,b=1,c=0,d=1,e=1,f=1,g=d3.interpolate,h=g(c,d),i=!1;j.invert=function(b){return(b-c)*f+a},j.domain=function(g){if(!arguments.length)return[a,b];a=+g[0],b=+g[1],e=1/(b-a),f=(b-a)/(d-c);return j},j.range=function(e){if(!arguments.length)return[c,d];c=e[0],d=e[1],f=(b-a)/(d-c),h=g(c,d);return j},j.rangeRound=function(a){return j.range(a).interpolate(d3.interpolateRound)},j.clamp=function(a){if(!arguments.length)return i;i=a;return j},j.interpolate=function(a){if(!arguments.length)return g;h=(g=a)(c,d);return j},j.ticks=function(a){var b=k(a);return d3.range(b.start,b.stop,b.step)},j.tickFormat=function(a){var b=Math.max(0,-Math.floor(Math.log(k(a).step)/Math.LN10+.01));return d3.format(",."+b+"f")};return j},d3.scale.log=function(){function d(c){return a(b(c))}var a=d3.scale.linear(),b=be,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?bf:be,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===bf){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},be.pow=function(a){return Math.pow(10,a)},bf.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?bh:bg;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(bi)},d3.scale.category20=function(){return d3.scale.ordinal().range(bj)},d3.scale.category20b=function(){return d3.scale.ordinal().range(bk)},d3.scale.category20c=function(){return d3.scale.ordinal().range(bl)};var bi=["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"],bj=["#1f77b4","#aec7e8","#ff7f0e","#ffbb78","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5","#8c564b","#c49c94","#e377c2","#f7b6d2","#7f7f7f","#c7c7c7","#bcbd22","#dbdb8d","#17becf","#9edae5"],bk=["#393b79","#5254a3","#6b6ecf","#9c9ede","#637939","#8ca252","#b5cf6b","#cedb9c","#8c6d31","#bd9e39","#e7ba52","#e7cb94","#843c39","#ad494a","#d6616b","#e7969c","#7b4173","#a55194","#ce6dbd","#de9ed6"],bl=["#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)+bm,h=d.apply(this,arguments)+bm,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>=bn?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=bo,b=bp,c=bq,d=br;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+bm;return[Math.cos(f)*e,Math.sin(f)*e]};return e};var bm=-Math.PI/2,bn=2*Math.PI-1e-6;d3.svg.line=function(){function f(c){return c.length<1?null:"M"+d(bs(this,c,a,b),e)}var a=bt,b=bu,c="linear",d=bv[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=bv[c=a];return f},f.tension=function(a){if(!arguments.length)return e;e=a;return f};return f};var bv={linear:bw,"step-before":bx,"step-after":by,basis:bD,"basis-closed":bE,cardinal:bA,"cardinal-closed":bz},bG=[0,2/3,1/3,0 <add>],bH=[0,1/3,2/3,0],bI=[0,1/6,2/3,1/6];d3.svg.area=function(){function g(d){return d.length<1?null:"M"+e(bs(this,d,a,c),f)+"L"+e(bs(this,d,a,b).reverse(),f)+"Z"}var a=bt,b=bK,c=bu,d="linear",e=bv[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=bv[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)+bm,k=e.call(a,h,g)+bm;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=bL,b=bM,c=bN,d=bq,e=br;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=bL,b=bM,c=bQ;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){var b=(a.ownerSVGElement||a).createSVGPoint();if(bR<0&&(window.scrollX||window.scrollY)){var c=d3.select(document.body).append("svg:svg").style("position","absolute").style("top",0).style("left",0),d=c[0][0].getScreenCTM();bR=!d.f&&!d.e,c.remove()}bR?(b.x=d3.event.pageX,b.y=d3.event.pageY):(b.x=d3.event.clientX,b.y=d3.event.clientY),b=b.matrixTransform(a.getScreenCTM().inverse());return[b.x,b.y]};var bR=/WebKit/.test(navigator.userAgent)?-1:0;d3.svg.symbol=function(){function c(c,d){return(bU[a.call(this,c,d)]||bU.circle)(b.call(this,c,d))}var a=bT,b=bS;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 bU={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*bW)),c=b*bW;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/bV),c=b*bV/2;return"M0,"+c+"L"+b+","+ -c+" "+ -b+","+ -c+"Z"},"triangle-up":function(a){var b=Math.sqrt(a/bV),c=b*bV/2;return"M0,"+ -c+"L"+b+","+c+" "+ -b+","+c+"Z"}},bV=Math.sqrt(3),bW=Math.tan(30*Math.PI/180)})() <ide>\ No newline at end of file <ide><path>src/core/selection.js <ide> function d3_selection(groups) { <ide> }; <ide> <ide> groups.style = function(name, value, priority) { <del> if (arguments.length < 3) priority = null; <add> if (arguments.length < 3) priority = ""; <ide> <ide> // If no value is specified, return the first value. <ide> if (arguments.length < 2) {
3
PHP
PHP
user() returning void
172ef6a271af0776f9f587671d0da7ec18a25d95
<ide><path>src/Illuminate/Auth/RequestGuard.php <ide> public function user() <ide> return $this->user; <ide> } <ide> <del> $this->user = call_user_func($this->callback, $this->request); <add> return $this->user = call_user_func($this->callback, $this->request); <ide> } <ide> <ide> /**
1
Mixed
Text
add syslog driver
eaecd8b1b5871a4d17be27e3615106587eec1d3a
<ide><path>daemon/config.go <ide> func (config *Config) InstallFlags() { <ide> opts.LabelListVar(&config.Labels, []string{"-label"}, "Set key=value labels to the daemon") <ide> config.Ulimits = make(map[string]*ulimit.Ulimit) <ide> opts.UlimitMapVar(config.Ulimits, []string{"-default-ulimit"}, "Set default ulimits for containers") <del> flag.StringVar(&config.LogConfig.Type, []string{"-log-driver"}, "json-file", "Containers logging driver(json-file/none)") <add> flag.StringVar(&config.LogConfig.Type, []string{"-log-driver"}, "json-file", "Containers logging driver") <ide> } <ide> <ide> func getDefaultNetworkMtu() int { <ide><path>daemon/container.go <ide> import ( <ide> "github.com/docker/docker/daemon/execdriver" <ide> "github.com/docker/docker/daemon/logger" <ide> "github.com/docker/docker/daemon/logger/jsonfilelog" <add> "github.com/docker/docker/daemon/logger/syslog" <ide> "github.com/docker/docker/engine" <ide> "github.com/docker/docker/image" <ide> "github.com/docker/docker/links" <ide> func (container *Container) startLogging() error { <ide> return err <ide> } <ide> l = dl <add> case "syslog": <add> dl, err := syslog.New(container.ID[:12]) <add> if err != nil { <add> return err <add> } <add> l = dl <ide> case "none": <ide> return nil <ide> default: <ide><path>daemon/logger/syslog/syslog.go <add>package syslog <add> <add>import ( <add> "fmt" <add> "log/syslog" <add> "os" <add> "path" <add> "sync" <add> <add> "github.com/docker/docker/daemon/logger" <add>) <add> <add>type Syslog struct { <add> writer *syslog.Writer <add> tag string <add> mu sync.Mutex <add>} <add> <add>func New(tag string) (logger.Logger, error) { <add> log, err := syslog.New(syslog.LOG_USER, path.Base(os.Args[0])) <add> if err != nil { <add> return nil, err <add> } <add> return &Syslog{ <add> writer: log, <add> tag: tag, <add> }, nil <add>} <add> <add>func (s *Syslog) Log(msg *logger.Message) error { <add> logMessage := fmt.Sprintf("%s: %s", s.tag, string(msg.Line)) <add> if msg.Source == "stderr" { <add> if err := s.writer.Err(logMessage); err != nil { <add> return err <add> } <add> <add> } else { <add> if err := s.writer.Info(logMessage); err != nil { <add> return err <add> } <add> } <add> return nil <add>} <add> <add>func (s *Syslog) Close() error { <add> if s.writer != nil { <add> return s.writer.Close() <add> } <add> return nil <add>} <add> <add>func (s *Syslog) Name() string { <add> return "Syslog" <add>} <ide><path>docs/man/docker-create.1.md <ide> IMAGE [COMMAND] [ARG...] <ide> **--lxc-conf**=[] <ide> (lxc exec-driver only) Add custom lxc options --lxc-conf="lxc.cgroup.cpuset.cpus = 0,1" <ide> <del>**--log-driver**="|*json-file*|*none*" <add>**--log-driver**="|*json-file*|*syslog*|*none*" <ide> Logging driver for container. Default is defined by daemon `--log-driver` flag. <ide> **Warning**: `docker logs` command works only for `json-file` logging driver. <ide> <ide><path>docs/man/docker-run.1.md <ide> which interface and port to use. <ide> **--lxc-conf**=[] <ide> (lxc exec-driver only) Add custom lxc options --lxc-conf="lxc.cgroup.cpuset.cpus = 0,1" <ide> <del>**--log-driver**="|*json-file*|*none*" <add>**--log-driver**="|*json-file*|*syslog*|*none*" <ide> Logging driver for container. Default is defined by daemon `--log-driver` flag. <ide> **Warning**: `docker logs` command works only for `json-file` logging driver. <ide> <ide><path>docs/man/docker.1.md <ide> unix://[/path/to/socket] to use. <ide> **--label**="[]" <ide> Set key=value labels to the daemon (displayed in `docker info`) <ide> <del>**--log-driver**="*json-file*|*none*" <add>**--log-driver**="*json-file*|*syslog*|*none*" <ide> Container's logging driver. Default is `default`. <ide> **Warning**: `docker logs` command works only for `json-file` logging driver. <ide> <ide><path>docs/sources/reference/api/docker_remote_api_v1.18.md <ide> Json Parameters: <ide> `Ulimits: { "Name": "nofile", "Soft": 1024, "Hard", 2048 }}` <ide> - **LogConfig** - Logging configuration to container, format <ide> `{ "Type": "<driver_name>", "Config": {"key1": "val1"}} <del> Available types: `json-file`, `none`. <add> Available types: `json-file`, `syslog`, `none`. <ide> `json-file` logging driver. <ide> <ide> Query Parameters: <ide><path>docs/sources/reference/run.md <ide> this driver. <ide> Default logging driver for Docker. Writes JSON messages to file. `docker logs` <ide> command is available only for this logging driver <ide> <add>## Logging driver: syslog <add> <add>Syslog logging driver for Docker. Writes log messages to syslog. `docker logs` <add>command is not available for this logging driver <add> <ide> ## Overriding Dockerfile image defaults <ide> <ide> When a developer builds an image from a [*Dockerfile*](/reference/builder)
8
Python
Python
allow negative vertex indices for obj model format
f58c4167cdb51cebc6d74e9f41d46b8d6c638bda
<ide><path>utils/exporters/obj/convert_obj_three.py <ide> def parse_obj(fname): <ide> uv_index = [] <ide> normal_index = [] <ide> <add> <add> # Precompute vert / normal / uv lists <add> # for negative index lookup <add> vertlen = len(vertices) + 1 <add> normlen = len(normals) + 1 <add> uvlen = len(uvs) + 1 <add> <ide> for v in chunks[1:]: <ide> vertex = parse_vertex(v) <ide> if vertex['v']: <add> if vertex['v'] < 0: <add> vertex['v'] += vertlen <ide> vertex_index.append(vertex['v']) <ide> if vertex['t']: <add> if vertex['t'] < 0: <add> vertex['t'] += uvlen <ide> uv_index.append(vertex['t']) <ide> if vertex['n']: <add> if vertex['n'] < 0: <add> vertex['n'] += normlen <ide> normal_index.append(vertex['n']) <ide> <del> faces.append({ <add> d = { <ide> 'vertex':vertex_index, <ide> 'uv':uv_index, <ide> 'normal':normal_index, <ide> def parse_obj(fname): <ide> 'group':group, <ide> 'object':object, <ide> 'smooth':smooth, <del> }) <add> } <add> faces.append(d) <ide> <ide> # Group <ide> if chunks[0] == "g" and len(chunks) == 2:
1
Text
Text
add tdsmith as maintainer
f7bb5190411006ef1f8a7f6e6a4587ecd7eaf70d
<ide><path>README.md <ide> Second, read the [Troubleshooting Checklist](https://github.com/Homebrew/homebre <ide> <ide> Who Are You? <ide> ------------ <del>Homebrew's current maintainers are [Misty De Meo][mistydemeo], [Adam Vandenberg][adamv], [Jack Nagel][jacknagel], [Mike McQuaid][mikemcquaid] and [Brett Koonce][asparagui]. <add>Homebrew's current maintainers are [Misty De Meo][mistydemeo], [Adam Vandenberg][adamv], [Jack Nagel][jacknagel], [Mike McQuaid][mikemcquaid], [Brett Koonce][asparagui] and [Tim Smith][tdsmith]. <ide> <ide> Homebrew was originally created by [Max Howell][mxcl]. <ide> <ide> We accept tips through [Gittip][tip]. <ide> [jacknagel]:https://github.com/jacknagel <ide> [mikemcquaid]:https://github.com/mikemcquaid <ide> [asparagui]:https://github.com/asparagui <add>[tdsmith]:https://github.com/tdsmith <ide> [mxcl]:https://github.com/mxcl <ide> [formula]:https://github.com/Homebrew/homebrew/tree/master/Library/Formula/ <ide> [braumeister]:http://braumeister.org
1
Text
Text
add note to volume-plugins
fb893cf6568f2b0cdf500bc3ecfb231fd374ffac
<ide><path>docs/extend/plugins_volume.md <ide> storage systems, such as Amazon EBS, and enable data volumes to persist beyond <ide> the lifetime of a single Docker host. See the [plugin documentation](plugins.md) <ide> for more information. <ide> <del># Command-line changes <add>## Command-line changes <ide> <ide> A volume plugin makes use of the `-v`and `--volume-driver` flag on the `docker run` command. The `-v` flag accepts a volume name and the `--volume-driver` flag a driver type, for example: <ide> <ide> server to another. <ide> By specifying a `volumedriver` in conjunction with a `volumename`, users can use plugins such as [Flocker](https://clusterhq.com/docker-plugin/) to manage volumes external to a single host, such as those on EBS. <ide> <ide> <del># Create a VolumeDriver <add>## Create a VolumeDriver <ide> <ide> The container creation endpoint (`/containers/create`) accepts a `VolumeDriver` <ide> field of type `string` allowing to specify the name of the driver. It's default <ide> value of `"local"` (the default driver for local volumes). <ide> <del># Volume plugin protocol <add>## Volume plugin protocol <ide> <ide> If a plugin registers itself as a `VolumeDriver` when activated, then it is <ide> expected to provide writeable paths on the host filesystem for the Docker <ide> daemon to provide to containers to consume. <ide> The Docker daemon handles bind-mounting the provided paths into user <ide> containers. <ide> <add>> **Note**: Volume plugins should *not* write data to the `/var/lib/docker/` <add>> directory, including `/var/lib/docker/volumes`. The `/var/lib/docker/` <add>> directory is reserved for Docker. <add> <ide> ### /VolumeDriver.Create <ide> <ide> **Request**:
1
Mixed
Javascript
add info option to common.expectserror
3e0d40d4af6f437ecacb8b54d0d84ed0e5a4899f
<ide><path>test/common/README.md <ide> Indicates if there is more than 1gb of total memory. <ide> regular expression must match the `message` property of the expected error. <ide> * `name` [&lt;string>] <ide> expected error must have this value for its `name` property. <add> * `info` &lt;Object> expected error must have the same `info` property <add> that is deeply equal to this value. <ide> * `generatedMessage` [&lt;string>] <ide> (`AssertionError` only) expected error must have this value for its <ide> `generatedMessage` property. <ide><path>test/common/index.js <ide> exports.expectsError = function expectsError(fn, settings, exact) { <ide> } <ide> assert.strictEqual(typeName, type.name); <ide> } <add> if ('info' in settings) { <add> assert.deepStrictEqual(error.info, settings.info); <add> } <ide> if ('message' in settings) { <ide> const message = settings.message; <ide> if (typeof message === 'string') { <ide> exports.expectsError = function expectsError(fn, settings, exact) { <ide> // Check all error properties. <ide> const keys = Object.keys(settings); <ide> for (const key of keys) { <del> if (key === 'message' || key === 'type') <add> if (key === 'message' || key === 'type' || key === 'info') <ide> continue; <ide> const actual = error[key]; <ide> const expected = settings[key];
2
Go
Go
remove unused controller.taskid (unused)
bd7180fcf9efc6d0695f230cbb02b8a7ba621cfb
<ide><path>daemon/cluster/controllers/plugin/controller.go <ide> type Controller struct { <ide> <ide> pluginID string <ide> serviceID string <del> taskID string <ide> <ide> // hook used to signal tests that `Wait()` is actually ready and waiting <ide> signalWaitReady func()
1
PHP
PHP
add keyby method to collection
27d50a2f5548765df136ccd9bf77059bbe73d093
<ide><path>src/Illuminate/Support/Collection.php <ide> public function groupBy($groupBy) <ide> return new static($results); <ide> } <ide> <add> /** <add> * Key an associative array by a field. <add> * <add> * @param string $keyBy <add> * @return \Illuminate\Support\Collection <add> */ <add> public function keyBy($keyBy) <add> { <add> $results = []; <add> <add> foreach ($this->items as $item) <add> { <add> $key = data_get($item, $keyBy); <add> <add> $results[$key] = $item; <add> } <add> <add> return new static($results); <add> } <add> <ide> /** <ide> * Determine if an item exists in the collection by key. <ide> * <ide><path>tests/Support/SupportCollectionTest.php <ide> public function testGroupByAttribute() <ide> } <ide> <ide> <add> public function testKeyByAttribute() <add> { <add> $data = new Collection([['rating' => 1, 'name' => '1'], ['rating' => 2, 'name' => '2'], ['rating' => 3, 'name' => '3']]); <add> $result = $data->keyBy('rating'); <add> $this->assertEquals([1 => ['rating' => 1, 'name' => '1'], 2 => ['rating' => 2, 'name' => '2'], 3 => ['rating' => 3, 'name' => '3']], $result->all()); <add> } <add> <add> <ide> public function testGettingSumFromCollection() <ide> { <ide> $c = new Collection(array((object) array('foo' => 50), (object) array('foo' => 50)));
2
Go
Go
check the length of entrypoint before comparing
71d2ff494694d7f18310c7994daa34dce33af98b
<ide><path>utils.go <ide> func CompareConfig(a, b *Config) bool { <ide> if len(a.Cmd) != len(b.Cmd) || <ide> len(a.Dns) != len(b.Dns) || <ide> len(a.Env) != len(b.Env) || <del> len(a.PortSpecs) != len(b.PortSpecs) { <add> len(a.PortSpecs) != len(b.PortSpecs) || <add> len(a.Entrypoint) != len(b.Entrypoint) { <ide> return false <ide> } <ide>
1
Python
Python
share app instance between kerberos tests
54edbaa65db38f1b858efc461e411d880e778c1e
<ide><path>tests/api/auth/backend/test_kerberos_auth.py <ide> import json <ide> import os <ide> import socket <del>import unittest <ide> from datetime import datetime <ide> from unittest import mock <ide> <ide> import pytest <ide> <ide> from airflow.api.auth.backend.kerberos_auth import CLIENT_AUTH <ide> from airflow.models import DagBag <del>from airflow.www import app as application <add>from airflow.www import app <ide> from tests.test_utils.config import conf_vars <ide> from tests.test_utils.db import clear_db_dags <ide> <ide> KRB5_KTNAME = os.environ.get("KRB5_KTNAME") <ide> <ide> <del>@pytest.mark.integration("kerberos") <del>class TestApiKerberos(unittest.TestCase): <del> @classmethod <del> def setUpClass(cls): <del> dagbag = DagBag(include_examples=True) <del> for dag in dagbag.dags.values(): <del> dag.sync_to_db() <del> <del> @conf_vars( <add>@pytest.fixture(scope="module") <add>def app_for_kerberos(): <add> with conf_vars( <ide> { <ide> ("api", "auth_backend"): "airflow.api.auth.backend.kerberos_auth", <ide> ("kerberos", "keytab"): KRB5_KTNAME, <ide> ('api', 'enable_experimental_api'): 'true', <ide> } <del> ) <del> def setUp(self): <del> self.app = application.create_app(testing=True) <add> ): <add> yield app.create_app(testing=True) <add> <add> <add>@pytest.fixture(scope="module", autouse=True) <add>def dagbag_to_db(): <add> dagbag = DagBag(include_examples=True) <add> for dag in dagbag.dags.values(): <add> dag.sync_to_db() <add> yield <add> clear_db_dags() <ide> <del> @classmethod <del> def tearDownClass(cls) -> None: <del> clear_db_dags() <add> <add>@pytest.mark.integration("kerberos") <add>class TestApiKerberos: <add> @pytest.fixture(autouse=True) <add> def _set_attrs(self, app_for_kerberos): <add> self.app = app_for_kerberos <ide> <ide> def test_trigger_dag(self): <ide> with self.app.test_client() as client:
1
Python
Python
use permission constants
728518224b9c6469c74b66d9d2b47b13de00fc8c
<ide><path>airflow/api_connexion/endpoints/config_endpoint.py <ide> from airflow.api_connexion import security <ide> from airflow.api_connexion.schemas.config_schema import Config, ConfigOption, ConfigSection, config_schema <ide> from airflow.configuration import conf <add>from airflow.security import permissions <ide> from airflow.settings import json <ide> <ide> LINE_SEP = '\n' # `\n` cannot appear in f-strings <ide> def _config_to_json(config: Config) -> str: <ide> return json.dumps(config_schema.dump(config), indent=4) <ide> <ide> <del>@security.requires_access([("can_read", "Config")]) <add>@security.requires_access([(permissions.ACTION_CAN_READ, permissions.RESOURCE_CONFIG)]) <ide> def get_config() -> Response: <ide> """ <ide> Get current configuration. <ide><path>airflow/api_connexion/endpoints/connection_endpoint.py <ide> connection_schema, <ide> ) <ide> from airflow.models import Connection <add>from airflow.security import permissions <ide> from airflow.utils.session import provide_session <ide> <ide> <del>@security.requires_access([("can_delete", "Connection")]) <add>@security.requires_access([(permissions.ACTION_CAN_DELETE, permissions.RESOURCE_CONNECTION)]) <ide> @provide_session <ide> def delete_connection(connection_id, session): <ide> """ <ide> def delete_connection(connection_id, session): <ide> return NoContent, 204 <ide> <ide> <del>@security.requires_access([("can_read", "Connection")]) <add>@security.requires_access([(permissions.ACTION_CAN_READ, permissions.RESOURCE_CONNECTION)]) <ide> @provide_session <ide> def get_connection(connection_id, session): <ide> """ <ide> def get_connection(connection_id, session): <ide> return connection_collection_item_schema.dump(connection) <ide> <ide> <del>@security.requires_access([("can_read", "Connection")]) <add>@security.requires_access([(permissions.ACTION_CAN_READ, permissions.RESOURCE_CONNECTION)]) <ide> @format_parameters({'limit': check_limit}) <ide> @provide_session <ide> def get_connections(session, limit, offset=0): <ide> def get_connections(session, limit, offset=0): <ide> ) <ide> <ide> <del>@security.requires_access([("can_edit", "Connection")]) <add>@security.requires_access([(permissions.ACTION_CAN_EDIT, permissions.RESOURCE_CONNECTION)]) <ide> @provide_session <ide> def patch_connection(connection_id, session, update_mask=None): <ide> """ <ide> def patch_connection(connection_id, session, update_mask=None): <ide> return connection_schema.dump(connection) <ide> <ide> <del>@security.requires_access([("can_create", "Connection")]) <add>@security.requires_access([(permissions.ACTION_CAN_CREATE, permissions.RESOURCE_CONNECTION)]) <ide> @provide_session <ide> def post_connection(session): <ide> """ <ide><path>airflow/api_connexion/endpoints/dag_endpoint.py <ide> from airflow.utils.session import provide_session <ide> <ide> <del>@security.requires_access([("can_read", permissions.RESOURCE_DAGS)]) <add>@security.requires_access([(permissions.ACTION_CAN_READ, permissions.RESOURCE_DAGS)]) <ide> @provide_session <ide> def get_dag(dag_id, session): <ide> """ <ide> def get_dag(dag_id, session): <ide> return dag_schema.dump(dag) <ide> <ide> <del>@security.requires_access([("can_read", permissions.RESOURCE_DAGS)]) <add>@security.requires_access([(permissions.ACTION_CAN_READ, permissions.RESOURCE_DAGS)]) <ide> def get_dag_details(dag_id): <ide> """ <ide> Get details of DAG. <ide> def get_dag_details(dag_id): <ide> return dag_detail_schema.dump(dag) <ide> <ide> <del>@security.requires_access([("can_read", permissions.RESOURCE_DAGS)]) <add>@security.requires_access([(permissions.ACTION_CAN_READ, permissions.RESOURCE_DAGS)]) <ide> @format_parameters({'limit': check_limit}) <ide> def get_dags(limit, offset=0): <ide> """ <ide> def get_dags(limit, offset=0): <ide> return dags_collection_schema.dump(DAGCollection(dags=dags, total_entries=total_entries)) <ide> <ide> <del>@security.requires_access([("can_edit", permissions.RESOURCE_DAGS)]) <add>@security.requires_access([(permissions.ACTION_CAN_EDIT, permissions.RESOURCE_DAGS)]) <ide> @provide_session <ide> def patch_dag(session, dag_id, update_mask=None): <ide> """ <ide><path>airflow/api_connexion/endpoints/dag_run_endpoint.py <ide> from airflow.utils.types import DagRunType <ide> <ide> <del>@security.requires_access([("can_read", permissions.RESOURCE_DAGS), ("can_delete", "DagRun")]) <add>@security.requires_access( <add> [ <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_DAGS), <add> (permissions.ACTION_CAN_DELETE, permissions.RESOURCE_DAG_RUN), <add> ] <add>) <ide> @provide_session <ide> def delete_dag_run(dag_id, dag_run_id, session): <ide> """ <ide> def delete_dag_run(dag_id, dag_run_id, session): <ide> return NoContent, 204 <ide> <ide> <del>@security.requires_access([("can_read", permissions.RESOURCE_DAGS), ("can_read", "DagRun")]) <add>@security.requires_access( <add> [ <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_DAGS), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG_RUN), <add> ] <add>) <ide> @provide_session <ide> def get_dag_run(dag_id, dag_run_id, session): <ide> """ <ide> def get_dag_run(dag_id, dag_run_id, session): <ide> return dagrun_schema.dump(dag_run) <ide> <ide> <del>@security.requires_access([("can_read", permissions.RESOURCE_DAGS), ("can_read", "DagRun")]) <add>@security.requires_access( <add> [ <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_DAGS), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG_RUN), <add> ] <add>) <ide> @format_parameters( <ide> { <ide> 'start_date_gte': format_datetime, <ide> def _apply_date_filters_to_query( <ide> return query <ide> <ide> <del>@security.requires_access([("can_read", permissions.RESOURCE_DAGS), ("can_read", "DagRun")]) <add>@security.requires_access( <add> [ <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_DAGS), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG_RUN), <add> ] <add>) <ide> @provide_session <ide> def get_dag_runs_batch(session): <ide> """ <ide> def get_dag_runs_batch(session): <ide> return dagrun_collection_schema.dump(DAGRunCollection(dag_runs=dag_runs, total_entries=total_entries)) <ide> <ide> <del>@security.requires_access([("can_read", permissions.RESOURCE_DAGS), ("can_create", "DagRun")]) <add>@security.requires_access( <add> [ <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_DAGS), <add> (permissions.ACTION_CAN_CREATE, permissions.RESOURCE_DAG_RUN), <add> ] <add>) <ide> @provide_session <ide> def post_dag_run(dag_id, session): <ide> """ <ide><path>airflow/api_connexion/endpoints/dag_source_endpoint.py <ide> from airflow.api_connexion.exceptions import NotFound <ide> from airflow.api_connexion.schemas.dag_source_schema import dag_source_schema <ide> from airflow.models.dagcode import DagCode <add>from airflow.security import permissions <add> <ide> <ide> log = logging.getLogger(__name__) <ide> <ide> <del>@security.requires_access([("can_read", "DagCode")]) <add>@security.requires_access([(permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG_CODE)]) <ide> def get_dag_source(file_token: str): <ide> """ <ide> Get source code using file token <ide><path>airflow/api_connexion/endpoints/event_log_endpoint.py <ide> event_log_schema, <ide> ) <ide> from airflow.models import Log <add>from airflow.security import permissions <ide> from airflow.utils.session import provide_session <ide> <ide> <del>@security.requires_access([('can_read', 'Log')]) <add>@security.requires_access([(permissions.ACTION_CAN_READ, permissions.RESOURCE_LOG)]) <ide> @provide_session <ide> def get_event_log(event_log_id, session): <ide> """ <ide> def get_event_log(event_log_id, session): <ide> return event_log_schema.dump(event_log) <ide> <ide> <del>@security.requires_access([('can_read', 'Log')]) <add>@security.requires_access([(permissions.ACTION_CAN_READ, permissions.RESOURCE_LOG)]) <ide> @format_parameters({'limit': check_limit}) <ide> @provide_session <ide> def get_event_logs(session, limit, offset=None): <ide><path>airflow/api_connexion/endpoints/extra_link_endpoint.py <ide> <ide> @security.requires_access( <ide> [ <del> ('can_read', permissions.RESOURCE_DAGS), <del> ('can_read', 'DagRun'), <del> ('can_read', 'Task'), <del> ('can_read', 'TaskInstance'), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_DAGS), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG_RUN), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_TASK), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_TASK_INSTANCE), <ide> ] <ide> ) <ide> @provide_session <ide><path>airflow/api_connexion/endpoints/import_error_endpoint.py <ide> import_error_schema, <ide> ) <ide> from airflow.models.errors import ImportError # pylint: disable=redefined-builtin <add>from airflow.security import permissions <ide> from airflow.utils.session import provide_session <ide> <ide> <del>@security.requires_access([('can_read', 'ImportError')]) <add>@security.requires_access([(permissions.ACTION_CAN_READ, permissions.RESOURCE_IMPORT_ERROR)]) <ide> @provide_session <ide> def get_import_error(import_error_id, session): <ide> """ <ide> def get_import_error(import_error_id, session): <ide> return import_error_schema.dump(error) <ide> <ide> <del>@security.requires_access([('can_read', 'ImportError')]) <add>@security.requires_access([(permissions.ACTION_CAN_READ, permissions.RESOURCE_IMPORT_ERROR)]) <ide> @format_parameters({'limit': check_limit}) <ide> @provide_session <ide> def get_import_errors(session, limit, offset=None): <ide><path>airflow/api_connexion/endpoints/log_endpoint.py <ide> <ide> <ide> @security.requires_access( <del> [('can_read', permissions.RESOURCE_DAGS), ('can_read', 'DagRun'), ('can_read', 'Task')] <add> [ <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_DAGS), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG_RUN), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_TASK), <add> ] <ide> ) <ide> @provide_session <ide> def get_log(session, dag_id, dag_run_id, task_id, task_try_number, full_content=False, token=None): <ide><path>airflow/api_connexion/endpoints/pool_endpoint.py <ide> from airflow.api_connexion.parameters import check_limit, format_parameters <ide> from airflow.api_connexion.schemas.pool_schema import PoolCollection, pool_collection_schema, pool_schema <ide> from airflow.models.pool import Pool <add>from airflow.security import permissions <ide> from airflow.utils.session import provide_session <ide> <ide> <del>@security.requires_access([("can_delete", "Pool")]) <add>@security.requires_access([(permissions.ACTION_CAN_DELETE, permissions.RESOURCE_POOL)]) <ide> @provide_session <ide> def delete_pool(pool_name: str, session): <ide> """ <ide> def delete_pool(pool_name: str, session): <ide> return Response(status=204) <ide> <ide> <del>@security.requires_access([("can_read", "Pool")]) <add>@security.requires_access([(permissions.ACTION_CAN_READ, permissions.RESOURCE_POOL)]) <ide> @provide_session <ide> def get_pool(pool_name, session): <ide> """ <ide> def get_pool(pool_name, session): <ide> return pool_schema.dump(obj) <ide> <ide> <del>@security.requires_access([("can_read", "Pool")]) <add>@security.requires_access([(permissions.ACTION_CAN_READ, permissions.RESOURCE_POOL)]) <ide> @format_parameters({'limit': check_limit}) <ide> @provide_session <ide> def get_pools(session, limit, offset=None): <ide> def get_pools(session, limit, offset=None): <ide> return pool_collection_schema.dump(PoolCollection(pools=pools, total_entries=total_entries)) <ide> <ide> <del>@security.requires_access([("can_edit", "Pool")]) <add>@security.requires_access([(permissions.ACTION_CAN_EDIT, permissions.RESOURCE_POOL)]) <ide> @provide_session <ide> def patch_pool(pool_name, session, update_mask=None): <ide> """ <ide> def patch_pool(pool_name, session, update_mask=None): <ide> return pool_schema.dump(pool) <ide> <ide> <del>@security.requires_access([("can_create", "Pool")]) <add>@security.requires_access([(permissions.ACTION_CAN_CREATE, permissions.RESOURCE_POOL)]) <ide> @provide_session <ide> def post_pool(session): <ide> """ <ide><path>airflow/api_connexion/endpoints/task_endpoint.py <ide> from airflow.security import permissions <ide> <ide> <del>@security.requires_access([("can_read", permissions.RESOURCE_DAGS), ("can_read", "Task")]) <add>@security.requires_access( <add> [ <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_DAGS), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_TASK), <add> ] <add>) <ide> def get_task(dag_id, task_id): <ide> """ <ide> Get simplified representation of a task. <ide> def get_task(dag_id, task_id): <ide> return task_schema.dump(task) <ide> <ide> <del>@security.requires_access([("can_read", permissions.RESOURCE_DAGS), ("can_read", "Task")]) <add>@security.requires_access( <add> [ <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_DAGS), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_TASK), <add> ] <add>) <ide> def get_tasks(dag_id): <ide> """ <ide> Get tasks for DAG <ide><path>airflow/api_connexion/endpoints/task_instance_endpoint.py <ide> <ide> @security.requires_access( <ide> [ <del> ("can_read", permissions.RESOURCE_DAGS), <del> ("can_read", "DagRun"), <del> ("can_read", "Task"), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_DAGS), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG_RUN), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_TASK), <ide> ] <ide> ) <ide> @provide_session <ide> def _apply_range_filter(query, key, value_range: Tuple[Any, Any]): <ide> ) <ide> @security.requires_access( <ide> [ <del> ("can_read", permissions.RESOURCE_DAGS), <del> ("can_read", "DagRun"), <del> ("can_read", "Task"), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_DAGS), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG_RUN), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_TASK), <ide> ] <ide> ) <ide> @provide_session <ide> def get_task_instances( <ide> <ide> <ide> @security.requires_access( <del> [("can_read", permissions.RESOURCE_DAGS), ("can_read", "DagRun"), ("can_read", "Task")] <add> [ <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_DAGS), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG_RUN), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_TASK), <add> ] <ide> ) <ide> @provide_session <ide> def get_task_instances_batch(session=None): <ide> def get_task_instances_batch(session=None): <ide> <ide> <ide> @security.requires_access( <del> [("can_read", permissions.RESOURCE_DAGS), ("can_read", "DagRun"), ("can_edit", "Task")] <add> [ <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_DAGS), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG_RUN), <add> (permissions.ACTION_CAN_EDIT, permissions.RESOURCE_TASK), <add> ] <ide> ) <ide> @provide_session <ide> def post_clear_task_instances(dag_id: str, session=None): <ide> def post_clear_task_instances(dag_id: str, session=None): <ide> <ide> <ide> @security.requires_access( <del> [("can_read", permissions.RESOURCE_DAGS), ("can_read", "DagRun"), ("can_edit", "Task")] <add> [ <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_DAGS), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG_RUN), <add> (permissions.ACTION_CAN_EDIT, permissions.RESOURCE_TASK), <add> ] <ide> ) <ide> @provide_session <ide> def post_set_task_instances_state(dag_id, session): <ide><path>airflow/api_connexion/endpoints/variable_endpoint.py <ide> from airflow.api_connexion.parameters import check_limit, format_parameters <ide> from airflow.api_connexion.schemas.variable_schema import variable_collection_schema, variable_schema <ide> from airflow.models import Variable <add>from airflow.security import permissions <ide> from airflow.utils.session import provide_session <ide> <ide> <del>@security.requires_access([("can_delete", "Variable")]) <add>@security.requires_access([(permissions.ACTION_CAN_DELETE, permissions.RESOURCE_VARIABLE)]) <ide> def delete_variable(variable_key: str) -> Response: <ide> """ <ide> Delete variable <ide> def delete_variable(variable_key: str) -> Response: <ide> return Response(status=204) <ide> <ide> <del>@security.requires_access([("can_read", "Variable")]) <add>@security.requires_access([(permissions.ACTION_CAN_READ, permissions.RESOURCE_VARIABLE)]) <ide> def get_variable(variable_key: str) -> Response: <ide> """ <ide> Get a variables by key <ide> def get_variable(variable_key: str) -> Response: <ide> return variable_schema.dump({"key": variable_key, "val": var}) <ide> <ide> <del>@security.requires_access([("can_read", "Variable")]) <add>@security.requires_access([(permissions.ACTION_CAN_READ, permissions.RESOURCE_VARIABLE)]) <ide> @format_parameters({'limit': check_limit}) <ide> @provide_session <ide> def get_variables(session, limit: Optional[int], offset: Optional[int] = None) -> Response: <ide> def get_variables(session, limit: Optional[int], offset: Optional[int] = None) - <ide> ) <ide> <ide> <del>@security.requires_access([("can_edit", "Variable")]) <add>@security.requires_access([(permissions.ACTION_CAN_EDIT, permissions.RESOURCE_VARIABLE)]) <ide> def patch_variable(variable_key: str, update_mask: Optional[List[str]] = None) -> Response: <ide> """ <ide> Update a variable by key <ide> def patch_variable(variable_key: str, update_mask: Optional[List[str]] = None) - <ide> return Response(status=204) <ide> <ide> <del>@security.requires_access([("can_create", "Variable")]) <add>@security.requires_access([(permissions.ACTION_CAN_CREATE, permissions.RESOURCE_VARIABLE)]) <ide> def post_variables() -> Response: <ide> """ <ide> Create a variable <ide><path>airflow/api_connexion/endpoints/xcom_endpoint.py <ide> <ide> @security.requires_access( <ide> [ <del> ("can_read", permissions.RESOURCE_DAGS), <del> ("can_read", "DagRun"), <del> ("can_read", "Task"), <del> ("can_read", "XCom"), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_DAGS), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG_RUN), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_TASK), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_XCOM), <ide> ] <ide> ) <ide> @format_parameters({'limit': check_limit}) <ide> def get_xcom_entries( <ide> <ide> @security.requires_access( <ide> [ <del> ("can_read", permissions.RESOURCE_DAGS), <del> ("can_read", "DagRun"), <del> ("can_read", "Task"), <del> ("can_read", "XCom"), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_DAGS), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG_RUN), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_TASK), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_XCOM), <ide> ] <ide> ) <ide> @provide_session <ide><path>airflow/api_connexion/security.py <ide> <ide> from flask import Response, current_app, g <ide> <del>from airflow.security.permissions import RESOURCE_DAGS <add>import airflow.security.permissions as perms <ide> from airflow.api_connexion.exceptions import PermissionDenied, Unauthenticated <ide> <ide> T = TypeVar("T", bound=Callable) # pylint: disable=invalid-name <ide> def can_access_any_dags(action: str, dag_id: Optional[int] = None) -> bool: <ide> return appbuilder.sm.has_access(action, appbuilder.sm.prefixed_dag_id(dag_id)) <ide> <ide> user = g.user <del> if action == 'can_read': <add> if action == perms.ACTION_CAN_READ: <ide> return any(appbuilder.sm.get_readable_dags(user)) <ide> return any(appbuilder.sm.get_editable_dags(user)) <ide> <ide> def check_authorization( <ide> return <ide> appbuilder = current_app.appbuilder <ide> for permission in permissions: <del> if permission in (('can_read', RESOURCE_DAGS), ('can_edit', RESOURCE_DAGS)): <add> if permission in ( <add> (perms.ACTION_CAN_READ, perms.RESOURCE_DAGS), <add> (perms.ACTION_CAN_EDIT, perms.RESOURCE_DAGS), <add> ): <ide> can_access_all_dags = appbuilder.sm.has_access(*permission) <ide> if can_access_all_dags: <ide> continue <ide><path>airflow/security/permissions.py <ide> # Resource Constants <ide> RESOURCE_DAGS = 'Dags' <ide> RESOURCE_DAG_PREFIX = 'DAG:' <add>RESOURCE_CONFIG = 'Config' <add>RESOURCE_CONNECTION = 'Connection' <add>RESOURCE_DAG_CODE = 'DagCode' <add>RESOURCE_DAG_RUN = 'DagRun' <add>RESOURCE_IMPORT_ERROR = 'ImportError' <add>RESOURCE_LOG = 'Log' <add>RESOURCE_POOL = 'Pool' <add>RESOURCE_TASK = 'Task' <add>RESOURCE_TASK_INSTANCE = 'TaskInstance' <add>RESOURCE_VARIABLE = "Variable" <add>RESOURCE_WEBSITE = 'Website' <add>RESOURCE_XCOM = 'XCom' <ide> <ide> # Action Constants <ide> ACTION_CAN_CREATE = 'can_create' <ide><path>airflow/www/decorators.py <ide> from flask import after_this_request, flash, g, redirect, request, url_for <ide> <ide> from airflow.models import Log <add>from airflow.security import permissions <ide> from airflow.utils.session import create_session <ide> <ide> T = TypeVar("T", bound=Callable) # pylint: disable=invalid-name <ide> def decorator(f: T): <ide> @functools.wraps(f) <ide> def wrapper(self, *args, **kwargs): <ide> dag_id = request.values.get('dag_id') <del> needs_edit_access = dag_kwargs.get('can_dag_edit', False) <add> needs_edit_access = dag_kwargs.get(permissions.DEPRECATED_ACTION_CAN_DAG_EDIT, False) <ide> <ide> if needs_edit_access: <ide> if self.appbuilder.sm.can_edit_dag(dag_id): <ide><path>airflow/www/security.py <ide> class AirflowSecurityManager(SecurityManager, LoggingMixin): <ide> 'Airflow', <ide> 'DagModelView', <ide> 'Browse', <del> 'Config', <add> permissions.RESOURCE_CONFIG, <ide> 'DAG Runs', <ide> 'DagRunModelView', <ide> 'Task Instances', <ide> class AirflowSecurityManager(SecurityManager, LoggingMixin): <ide> 'can_run', <ide> 'can_trigger', <ide> 'can_add', <del> 'can_edit', <del> 'can_delete', <add> permissions.ACTION_CAN_EDIT, <add> permissions.ACTION_CAN_DELETE, <ide> 'can_failed', <ide> 'can_paused', <ide> 'can_refresh', <ide><path>airflow/www/views.py <ide> class XComModelView(AirflowModelView): <ide> <ide> datamodel = AirflowModelView.CustomSQLAInterface(XCom) <ide> <del> base_permissions = ['can_list', 'can_delete'] <add> base_permissions = ['can_list', permissions.ACTION_CAN_DELETE] <ide> <ide> search_columns = ['key', 'value', 'timestamp', 'execution_date', 'task_id', 'dag_id'] <ide> list_columns = ['key', 'value', 'timestamp', 'execution_date', 'task_id', 'dag_id'] <ide> class ConnectionModelView(AirflowModelView): <ide> <ide> datamodel = AirflowModelView.CustomSQLAInterface(Connection) # noqa # type: ignore <ide> <del> base_permissions = ['can_add', 'can_list', 'can_edit', 'can_delete'] <add> base_permissions = ['can_add', 'can_list', permissions.ACTION_CAN_EDIT, permissions.ACTION_CAN_DELETE] <ide> <ide> extra_fields = ['extra__jdbc__drv_path', 'extra__jdbc__drv_clsname', <ide> 'extra__google_cloud_platform__project', <ide> class PoolModelView(AirflowModelView): <ide> <ide> datamodel = AirflowModelView.CustomSQLAInterface(models.Pool) # noqa # type: ignore <ide> <del> base_permissions = ['can_add', 'can_list', 'can_edit', 'can_delete'] <add> base_permissions = ['can_add', 'can_list', permissions.ACTION_CAN_EDIT, permissions.ACTION_CAN_DELETE] <ide> <ide> list_columns = ['pool', 'slots', 'running_slots', 'queued_slots'] <ide> add_columns = ['pool', 'slots', 'description'] <ide> class VariableModelView(AirflowModelView): <ide> <ide> datamodel = AirflowModelView.CustomSQLAInterface(models.Variable) # noqa # type: ignore <ide> <del> base_permissions = ['can_add', 'can_list', 'can_edit', 'can_delete', 'can_varimport'] <add> base_permissions = ['can_add', 'can_list', permissions.ACTION_CAN_EDIT, <add> permissions.ACTION_CAN_DELETE, 'can_varimport'] <ide> <ide> list_columns = ['key', 'val', 'is_encrypted'] <ide> add_columns = ['key', 'val'] <ide><path>tests/api_connexion/endpoints/test_config_endpoint.py <ide> <ide> from mock import patch <ide> <add>from airflow.security import permissions <ide> from airflow.www import app <ide> from tests.test_utils.api_connexion_utils import assert_401, create_user, delete_user <ide> from tests.test_utils.config import conf_vars <ide> def setup_class(cls) -> None: <ide> with conf_vars({("api", "auth_backend"): "tests.test_utils.remote_user_api_auth_backend"}): <ide> cls.app = app.create_app(testing=True) # type:ignore <ide> create_user( <del> cls.app, username="test", role_name="Test", permissions=[('can_read', 'Config')] # type: ignore <add> cls.app, # type:ignore <add> username="test", <add> role_name="Test", <add> permissions=[(permissions.ACTION_CAN_READ, permissions.RESOURCE_CONFIG)], # type: ignore <ide> ) <ide> create_user(cls.app, username="test_no_permissions", role_name="TestNoPermissions") # type: ignore <ide> <ide><path>tests/api_connexion/endpoints/test_connection_endpoint.py <ide> <ide> from airflow.api_connexion.exceptions import EXCEPTIONS_LINK_MAP <ide> from airflow.models import Connection <add>from airflow.security import permissions <ide> from airflow.utils.session import provide_session <ide> from airflow.www import app <ide> from tests.test_utils.api_connexion_utils import assert_401, create_user, delete_user <ide> def setUpClass(cls) -> None: <ide> username="test", <ide> role_name="Test", <ide> permissions=[ <del> ("can_create", "Connection"), <del> ("can_read", "Connection"), <del> ("can_edit", "Connection"), <del> ("can_delete", "Connection"), <add> (permissions.ACTION_CAN_CREATE, permissions.RESOURCE_CONNECTION), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_CONNECTION), <add> (permissions.ACTION_CAN_EDIT, permissions.RESOURCE_CONNECTION), <add> (permissions.ACTION_CAN_DELETE, permissions.RESOURCE_CONNECTION), <ide> ], <ide> ) <ide> create_user(cls.app, username="test_no_permissions", role_name="TestNoPermissions") # type: ignore <ide><path>tests/api_connexion/endpoints/test_dag_endpoint.py <ide> def setUpClass(cls) -> None: <ide> username="test", <ide> role_name="Test", <ide> permissions=[ <del> ("can_create", permissions.RESOURCE_DAGS), <del> ("can_read", permissions.RESOURCE_DAGS), <del> ("can_edit", permissions.RESOURCE_DAGS), <del> ("can_delete", permissions.RESOURCE_DAGS), <add> (permissions.ACTION_CAN_CREATE, permissions.RESOURCE_DAGS), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_DAGS), <add> (permissions.ACTION_CAN_EDIT, permissions.RESOURCE_DAGS), <add> (permissions.ACTION_CAN_DELETE, permissions.RESOURCE_DAGS), <ide> ], <ide> ) <ide> create_user(cls.app, username="test_no_permissions", role_name="TestNoPermissions") # type: ignore <ide> create_user( <ide> cls.app, username="test_granular_permissions", role_name="TestGranularDag" # type: ignore <ide> ) <ide> cls.app.appbuilder.sm.sync_perm_for_dag( # type: ignore # pylint: disable=no-member <del> "TEST_DAG_1", access_control={'TestGranularDag': ['can_edit', 'can_read']} <add> "TEST_DAG_1", <add> access_control={'TestGranularDag': [permissions.ACTION_CAN_EDIT, permissions.ACTION_CAN_READ]}, <ide> ) <ide> <ide> with DAG(cls.dag_id, start_date=datetime(2020, 6, 15), doc_md="details") as dag: <ide><path>tests/api_connexion/endpoints/test_dag_run_endpoint.py <ide> def setUpClass(cls) -> None: <ide> username="test", <ide> role_name="Test", <ide> permissions=[ <del> ("can_read", permissions.RESOURCE_DAGS), <del> ("can_create", "DagRun"), <del> ("can_read", "DagRun"), <del> ("can_edit", "DagRun"), <del> ("can_delete", "DagRun"), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_DAGS), <add> (permissions.ACTION_CAN_CREATE, permissions.RESOURCE_DAG_RUN), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG_RUN), <add> (permissions.ACTION_CAN_EDIT, permissions.RESOURCE_DAG_RUN), <add> (permissions.ACTION_CAN_DELETE, permissions.RESOURCE_DAG_RUN), <ide> ], <ide> ) <ide> create_user( <ide> cls.app, # type: ignore <ide> username="test_granular_permissions", <ide> role_name="TestGranularDag", <del> permissions=[("can_read", "DagRun")], <add> permissions=[(permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG_RUN)], <ide> ) <ide> cls.app.appbuilder.sm.sync_perm_for_dag( # type: ignore # pylint: disable=no-member <del> "TEST_DAG_ID", access_control={'TestGranularDag': ['can_edit', 'can_read']} <add> "TEST_DAG_ID", <add> access_control={'TestGranularDag': [permissions.ACTION_CAN_EDIT, permissions.ACTION_CAN_READ]}, <ide> ) <ide> create_user(cls.app, username="test_no_permissions", role_name="TestNoPermissions") # type: ignore <ide> <ide><path>tests/api_connexion/endpoints/test_dag_source_endpoint.py <ide> from airflow import DAG <ide> from airflow.configuration import conf <ide> from airflow.models import DagBag <add>from airflow.security import permissions <ide> from airflow.www import app <ide> from tests.test_utils.api_connexion_utils import assert_401, create_user, delete_user <ide> from tests.test_utils.config import conf_vars <ide> def setUpClass(cls) -> None: <ide> with conf_vars({("api", "auth_backend"): "tests.test_utils.remote_user_api_auth_backend"}): <ide> cls.app = app.create_app(testing=True) # type:ignore <ide> create_user( <del> cls.app, username="test", role_name="Test", permissions=[("can_read", "DagCode")] # type: ignore <add> cls.app, # type:ignore <add> username="test", <add> role_name="Test", <add> permissions=[(permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG_CODE)], # type: ignore <ide> ) <ide> create_user(cls.app, username="test_no_permissions", role_name="TestNoPermissions") # type: ignore <ide> <ide><path>tests/api_connexion/endpoints/test_event_log_endpoint.py <ide> from airflow.api_connexion.exceptions import EXCEPTIONS_LINK_MAP <ide> from airflow.models import Log, TaskInstance <ide> from airflow.operators.dummy_operator import DummyOperator <add>from airflow.security import permissions <ide> from airflow.utils import timezone <ide> from airflow.utils.session import provide_session <ide> from airflow.www import app <ide> def setUpClass(cls) -> None: <ide> with conf_vars({("api", "auth_backend"): "tests.test_utils.remote_user_api_auth_backend"}): <ide> cls.app = app.create_app(testing=True) # type:ignore <ide> create_user( <del> cls.app, username="test", role_name="Test", permissions=[("can_read", "Log")] # type: ignore <add> cls.app, # type:ignore <add> username="test", <add> role_name="Test", <add> permissions=[(permissions.ACTION_CAN_READ, permissions.RESOURCE_LOG)], # type: ignore <ide> ) <ide> create_user(cls.app, username="test_no_permissions", role_name="TestNoPermissions") # type: ignore <ide> <ide><path>tests/api_connexion/endpoints/test_extra_link_endpoint.py <ide> def setUpClass(cls) -> None: <ide> username="test", <ide> role_name="Test", <ide> permissions=[ <del> ('can_read', permissions.RESOURCE_DAGS), <del> ('can_read', 'DagRun'), <del> ('can_read', 'Task'), <del> ('can_read', 'TaskInstance'), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_DAGS), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG_RUN), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_TASK), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_TASK_INSTANCE), <ide> ], <ide> ) <ide> create_user(cls.app, username="test_no_permissions", role_name="TestNoPermissions") # type: ignore <ide><path>tests/api_connexion/endpoints/test_import_error_endpoint.py <ide> <ide> from airflow.api_connexion.exceptions import EXCEPTIONS_LINK_MAP <ide> from airflow.models.errors import ImportError # pylint: disable=redefined-builtin <add>from airflow.security import permissions <ide> from airflow.utils import timezone <ide> from airflow.utils.session import provide_session <ide> from airflow.www import app <ide> def setUpClass(cls) -> None: <ide> cls.app, # type: ignore <ide> username="test", <ide> role_name="Test", <del> permissions=[('can_read', 'ImportError')], <add> permissions=[(permissions.ACTION_CAN_READ, permissions.RESOURCE_IMPORT_ERROR)], <ide> ) <ide> create_user(cls.app, username="test_no_permissions", role_name="TestNoPermissions") # type: ignore <ide> <ide><path>tests/api_connexion/endpoints/test_log_endpoint.py <ide> def setUpClass(cls): <ide> username="test", <ide> role_name="Test", <ide> permissions=[ <del> ('can_read', permissions.RESOURCE_DAGS), <del> ('can_read', 'DagRun'), <del> ('can_read', 'Task'), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_DAGS), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG_RUN), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_TASK), <ide> ], <ide> ) <ide> create_user(cls.app, username="test_no_permissions", role_name="TestNoPermissions") <ide><path>tests/api_connexion/endpoints/test_pool_endpoint.py <ide> <ide> from airflow.api_connexion.exceptions import EXCEPTIONS_LINK_MAP <ide> from airflow.models.pool import Pool <add>from airflow.security import permissions <ide> from airflow.utils.session import provide_session <ide> from airflow.www import app <ide> from tests.test_utils.api_connexion_utils import assert_401, create_user, delete_user <ide> def setUpClass(cls) -> None: <ide> username="test", <ide> role_name="Test", <ide> permissions=[ <del> ("can_create", "Pool"), <del> ("can_read", "Pool"), <del> ("can_edit", "Pool"), <del> ("can_delete", "Pool"), <add> (permissions.ACTION_CAN_CREATE, permissions.RESOURCE_POOL), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_POOL), <add> (permissions.ACTION_CAN_EDIT, permissions.RESOURCE_POOL), <add> (permissions.ACTION_CAN_DELETE, permissions.RESOURCE_POOL), <ide> ], <ide> ) <ide> create_user(cls.app, username="test_no_permissions", role_name="TestNoPermissions") # type: ignore <ide><path>tests/api_connexion/endpoints/test_task_endpoint.py <ide> def setUpClass(cls) -> None: <ide> username="test", <ide> role_name="Test", <ide> permissions=[ <del> ('can_read', permissions.RESOURCE_DAGS), <del> ('can_read', 'DagRun'), <del> ('can_read', 'Task'), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_DAGS), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG_RUN), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_TASK), <ide> ], <ide> ) <ide> create_user(cls.app, username="test_no_permissions", role_name="TestNoPermissions") # type: ignore <ide><path>tests/api_connexion/endpoints/test_task_instance_endpoint.py <ide> # under the License. <ide> import unittest <ide> import datetime as dt <add>import getpass <ide> from unittest import mock <ide> <ide> from parameterized import parameterized <ide> def setUpClass(cls) -> None: <ide> username="test", <ide> role_name="Test", <ide> permissions=[ <del> ('can_read', permissions.RESOURCE_DAGS), <del> ('can_read', 'DagRun'), <del> ('can_read', 'Task'), <del> ('can_edit', 'Task'), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_DAGS), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG_RUN), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_TASK), <add> (permissions.ACTION_CAN_EDIT, permissions.RESOURCE_TASK), <ide> ], <ide> ) <ide> create_user(cls.app, username="test_no_permissions", role_name="TestNoPermissions") # type: ignore <ide> def test_should_response_200(self, session): <ide> "state": "running", <ide> "task_id": "print_the_context", <ide> "try_number": 0, <del> "unixname": "root", <add> "unixname": getpass.getuser(), <ide> }, <ide> ) <ide> <ide> def test_should_response_200_task_instance_with_sla(self, session): <ide> "state": "running", <ide> "task_id": "print_the_context", <ide> "try_number": 0, <del> "unixname": "root", <add> "unixname": getpass.getuser(), <ide> }, <ide> ) <ide> <ide><path>tests/api_connexion/endpoints/test_variable_endpoint.py <ide> <ide> from parameterized import parameterized <ide> <add>from airflow.security import permissions <ide> from airflow.api_connexion.exceptions import EXCEPTIONS_LINK_MAP <ide> from airflow.models import Variable <ide> from airflow.www import app <ide> def setUpClass(cls) -> None: <ide> username="test", <ide> role_name="Test", <ide> permissions=[ <del> ("can_create", "Variable"), <del> ("can_read", "Variable"), <del> ("can_edit", "Variable"), <del> ("can_delete", "Variable"), <add> (permissions.ACTION_CAN_CREATE, permissions.RESOURCE_VARIABLE), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_VARIABLE), <add> (permissions.ACTION_CAN_EDIT, permissions.RESOURCE_VARIABLE), <add> (permissions.ACTION_CAN_DELETE, permissions.RESOURCE_VARIABLE), <ide> ], <ide> ) <ide> create_user(cls.app, username="test_no_permissions", role_name="TestNoPermissions") # type: ignore <ide><path>tests/api_connexion/endpoints/test_xcom_endpoint.py <ide> def setUpClass(cls) -> None: <ide> username="test", <ide> role_name="Test", <ide> permissions=[ <del> ("can_read", permissions.RESOURCE_DAGS), <del> ("can_read", "DagRun"), <del> ("can_read", "Task"), <del> ("can_read", "XCom"), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_DAGS), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG_RUN), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_TASK), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_XCOM), <ide> ], <ide> ) <ide> create_user( <ide> cls.app, # type: ignore <ide> username="test_granular_permissions", <ide> role_name="TestGranularDag", <del> permissions=[("can_read", "DagRun"), ("can_read", "Task"), ("can_read", "XCom")], <add> permissions=[ <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG_RUN), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_TASK), <add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_XCOM), <add> ], <ide> ) <ide> cls.app.appbuilder.sm.sync_perm_for_dag( # type: ignore # pylint: disable=no-member <del> "test-dag-id-1", access_control={'TestGranularDag': ['can_edit', 'can_read']} <add> "test-dag-id-1", <add> access_control={'TestGranularDag': [permissions.ACTION_CAN_EDIT, permissions.ACTION_CAN_READ]}, <ide> ) <ide> create_user(cls.app, username="test_no_permissions", role_name="TestNoPermissions") # type: ignore <ide> <ide><path>tests/api_connexion/schemas/test_task_instance_schema.py <ide> # under the License. <ide> <ide> import datetime as dt <add>import getpass <ide> import unittest <ide> <ide> from marshmallow import ValidationError <ide> def test_task_instance_schema_without_sla(self, session): <ide> "state": "running", <ide> "task_id": "TEST_TASK_ID", <ide> "try_number": 0, <del> "unixname": "root", <add> "unixname": getpass.getuser(), <ide> } <ide> self.assertDictEqual(serialized_ti, expected_json) <ide> <ide> def test_task_instance_schema_with_sla(self, session): <ide> "state": "running", <ide> "task_id": "TEST_TASK_ID", <ide> "try_number": 0, <del> "unixname": "root", <add> "unixname": getpass.getuser(), <ide> } <ide> self.assertDictEqual(serialized_ti, expected_json) <ide> <ide><path>tests/cli/commands/test_sync_perm_command.py <ide> from airflow.cli.commands import sync_perm_command <ide> from airflow.models.dag import DAG <ide> from airflow.models.dagbag import DagBag <add>from airflow.security import permissions <ide> <ide> <ide> class TestCliSyncPerm(unittest.TestCase): <ide> def test_cli_sync_perm(self, dagbag_mock, mock_cached_app): <ide> self.expect_dagbag_contains([ <ide> DAG('has_access_control', <ide> access_control={ <del> 'Public': {'can_read'} <add> 'Public': {permissions.ACTION_CAN_READ} <ide> }), <ide> DAG('no_access_control') <ide> ], dagbag_mock) <ide> def test_cli_sync_perm(self, dagbag_mock, mock_cached_app): <ide> self.assertEqual(2, len(appbuilder.sm.sync_perm_for_dag.mock_calls)) <ide> appbuilder.sm.sync_perm_for_dag.assert_any_call( <ide> 'has_access_control', <del> {'Public': {'can_read'}} <add> {'Public': {permissions.ACTION_CAN_READ}} <ide> ) <ide> appbuilder.sm.sync_perm_for_dag.assert_any_call( <ide> 'no_access_control', <ide><path>tests/models/test_dag.py <ide> from airflow.operators.bash import BashOperator <ide> from airflow.operators.dummy_operator import DummyOperator <ide> from airflow.operators.subdag_operator import SubDagOperator <add>from airflow.security import permissions <ide> from airflow.utils import timezone <ide> from airflow.utils.file import list_py_file_paths <ide> from airflow.utils.session import create_session, provide_session <ide> def subdag(parent_dag_name, child_dag_name, args): <ide> assert next_subdag_date is None, "SubDags should never have DagRuns created by the scheduler" <ide> <ide> def test_replace_outdated_access_control_actions(self): <del> outdated_permissions = {'role1': {'can_read', 'can_edit'}, 'role2': {'can_dag_read', 'can_dag_edit'}} <del> updated_permissions = {'role1': {'can_read', 'can_edit'}, 'role2': {'can_read', 'can_edit'}} <add> outdated_permissions = { <add> 'role1': {permissions.ACTION_CAN_READ, permissions.ACTION_CAN_EDIT}, <add> 'role2': {permissions.DEPRECATED_ACTION_CAN_DAG_READ, permissions.DEPRECATED_ACTION_CAN_DAG_EDIT} <add> } <add> updated_permissions = { <add> 'role1': {permissions.ACTION_CAN_READ, permissions.ACTION_CAN_EDIT}, <add> 'role2': {permissions.ACTION_CAN_READ, permissions.ACTION_CAN_EDIT} <add> } <ide> <ide> with pytest.warns(DeprecationWarning): <ide> dag = DAG(dag_id='dag_with_outdated_perms', access_control=outdated_permissions) <ide><path>tests/serialization/test_dag_serialization.py <ide> from airflow.models import DAG, Connection, DagBag, TaskInstance <ide> from airflow.models.baseoperator import BaseOperator <ide> from airflow.operators.bash import BashOperator <add>from airflow.security import permissions <ide> from airflow.serialization.json_schema import load_dag_schema_dict <ide> from airflow.serialization.serialized_objects import SerializedBaseOperator, SerializedDAG <ide> from tests.test_utils.mock_operators import CustomOperator, CustomOpLink, GoogleLink <ide> "test_role": { <ide> "__type": "set", <ide> "__var": [ <del> "can_read", <del> "can_edit" <add> permissions.ACTION_CAN_READ, <add> permissions.ACTION_CAN_EDIT <ide> ] <ide> } <ide> } <ide> def make_simple_dag(): <ide> start_date=datetime(2019, 8, 1), <ide> is_paused_upon_creation=False, <ide> access_control={ <del> "test_role": {"can_read", "can_edit"} <add> "test_role": {permissions.ACTION_CAN_READ, permissions.ACTION_CAN_EDIT} <ide> } <ide> ) as dag: <ide> CustomOperator(task_id='custom_task') <ide><path>tests/www/test_security.py <ide> from tests.test_utils.db import clear_db_dags, clear_db_runs <ide> from tests.test_utils.mock_security_manager import MockSecurityManager <ide> <del>READ_WRITE = {'can_read', 'can_edit'} <del>READ_ONLY = {'can_read'} <add>READ_WRITE = {permissions.ACTION_CAN_READ, permissions.ACTION_CAN_EDIT} <add>READ_ONLY = {permissions.ACTION_CAN_READ} <ide> <ide> logging.basicConfig(format='%(asctime)s:%(levelname)s:%(name)s:%(message)s') <ide> logging.getLogger().setLevel(logging.DEBUG) <ide> def __repr__(self): <ide> <ide> class SomeModelView(ModelView): <ide> datamodel = CustomSQLAInterface(SomeModel) <del> base_permissions = ['can_list', 'can_show', 'can_add', 'can_edit', 'can_delete'] <add> base_permissions = [ <add> 'can_list', <add> 'can_show', <add> 'can_add', <add> permissions.ACTION_CAN_EDIT, <add> permissions.ACTION_CAN_DELETE, <add> ] <ide> list_columns = ['field_string', 'field_integer', 'field_float', 'field_date'] <ide> <ide> <ide> def test_init_role_baseview(self): <ide> <ide> def test_init_role_modelview(self): <ide> role_name = 'MyRole2' <del> role_perms = ['can_list', 'can_show', 'can_add', 'can_edit', 'can_delete'] <add> role_perms = [ <add> 'can_list', <add> 'can_show', <add> 'can_add', <add> permissions.ACTION_CAN_EDIT, <add> permissions.ACTION_CAN_DELETE, <add> ] <ide> role_vms = ['SomeModelView'] <ide> self.security_manager.init_role(role_name, role_vms, role_perms) <ide> role = self.appbuilder.sm.find_role(role_name) <ide> def test_update_and_verify_permission_role(self): <ide> self.security_manager.init_role(role_name, [], []) <ide> role = self.security_manager.find_role(role_name) <ide> <del> perm = self.security_manager.find_permission_view_menu('can_edit', 'RoleModelView') <add> perm = self.security_manager.find_permission_view_menu(permissions.ACTION_CAN_EDIT, 'RoleModelView') <ide> self.security_manager.add_permission_role(role, perm) <ide> role_perms_len = len(role.permissions) <ide> <ide> def test_get_all_permissions_views(self, mock_get_user_roles): <ide> <ide> def test_get_accessible_dag_ids(self): <ide> role_name = 'MyRole1' <del> permission_action = ['can_read'] <add> permission_action = [permissions.ACTION_CAN_READ] <ide> dag_id = 'dag_id' <ide> username = "ElUser" <ide> <ide> def test_sync_perm_for_dag_creates_permissions_on_view_menus(self): <ide> prefixed_test_dag_id = f'DAG:{test_dag_id}' <ide> self.security_manager.sync_perm_for_dag(test_dag_id, access_control=None) <ide> self.assertIsNotNone( <del> self.security_manager.find_permission_view_menu('can_read', prefixed_test_dag_id) <add> self.security_manager.find_permission_view_menu(permissions.ACTION_CAN_READ, prefixed_test_dag_id) <ide> ) <ide> self.assertIsNotNone( <del> self.security_manager.find_permission_view_menu('can_edit', prefixed_test_dag_id) <add> self.security_manager.find_permission_view_menu(permissions.ACTION_CAN_EDIT, prefixed_test_dag_id) <ide> ) <ide> <ide> @mock.patch('airflow.www.security.AirflowSecurityManager._has_perm') <ide> def test_access_control_with_non_existent_role(self): <ide> with self.assertRaises(AirflowException) as context: <ide> self.security_manager.sync_perm_for_dag( <ide> dag_id='access-control-test', <del> access_control={'this-role-does-not-exist': ['can_edit', 'can_read']}, <add> access_control={ <add> 'this-role-does-not-exist': [permissions.ACTION_CAN_EDIT, permissions.ACTION_CAN_READ] <add> }, <ide> ) <ide> self.assertIn("role does not exist", str(context.exception)) <ide> <ide> def test_all_dag_access_doesnt_give_non_dag_access(self): <ide> self.assertTrue( <ide> self.security_manager.has_access(permissions.ACTION_CAN_READ, permissions.RESOURCE_DAGS, user) <ide> ) <del> self.assertFalse(self.security_manager.has_access(permissions.ACTION_CAN_READ, 'Task', user)) <add> self.assertFalse( <add> self.security_manager.has_access(permissions.ACTION_CAN_READ, permissions.RESOURCE_TASK, user) <add> ) <ide> <ide> def test_access_control_with_invalid_permission(self): <ide> invalid_permissions = [ <ide> def test_access_control_is_set_on_init(self): <ide> user = fab_utils.create_user(self.app, username, role_name, permissions=[],) <ide> self.expect_user_is_in_role(user, rolename='team-a') <ide> self.security_manager.sync_perm_for_dag( <del> 'access_control_test', access_control={'team-a': ['can_edit', 'can_read']} <add> 'access_control_test', <add> access_control={'team-a': [permissions.ACTION_CAN_EDIT, permissions.ACTION_CAN_READ]}, <ide> ) <ide> self.assert_user_has_dag_perms( <del> perms=['can_edit', 'can_read'], dag_id='access_control_test', user=user <add> perms=[permissions.ACTION_CAN_EDIT, permissions.ACTION_CAN_READ], <add> dag_id='access_control_test', <add> user=user, <ide> ) <ide> <ide> self.expect_user_is_in_role(user, rolename='NOT-team-a') <ide> self.assert_user_does_not_have_dag_perms( <del> perms=['can_edit', 'can_read'], dag_id='access_control_test', user=user <add> perms=[permissions.ACTION_CAN_EDIT, permissions.ACTION_CAN_READ], <add> dag_id='access_control_test', <add> user=user, <ide> ) <ide> <ide> def test_access_control_stale_perms_are_revoked(self): <ide> def test_access_control_stale_perms_are_revoked(self): <ide> self.security_manager.sync_perm_for_dag( <ide> 'access_control_test', access_control={'team-a': READ_ONLY} <ide> ) <del> self.assert_user_has_dag_perms(perms=['can_read'], dag_id='access_control_test', user=user) <add> self.assert_user_has_dag_perms( <add> perms=[permissions.ACTION_CAN_READ], dag_id='access_control_test', user=user <add> ) <ide> self.assert_user_does_not_have_dag_perms( <del> perms=['can_edit'], dag_id='access_control_test', user=user <add> perms=[permissions.ACTION_CAN_EDIT], dag_id='access_control_test', user=user <ide> ) <ide> <ide> def test_no_additional_dag_permission_views_created(self): <ide><path>tests/www/test_views.py <ide> def add_permission_for_role(self): <ide> password='test') <ide> dag_tester_role = self.appbuilder.sm.find_role('dag_acl_tester') <ide> edit_perm_on_dag = self.appbuilder.sm.\ <del> find_permission_view_menu('can_edit', 'DAG:example_bash_operator') <add> find_permission_view_menu(permissions.ACTION_CAN_EDIT, 'DAG:example_bash_operator') <ide> self.appbuilder.sm.add_permission_role(dag_tester_role, edit_perm_on_dag) <ide> read_perm_on_dag = self.appbuilder.sm.\ <del> find_permission_view_menu('can_read', 'DAG:example_bash_operator') <add> find_permission_view_menu(permissions.ACTION_CAN_READ, 'DAG:example_bash_operator') <ide> self.appbuilder.sm.add_permission_role(dag_tester_role, read_perm_on_dag) <ide> <ide> all_dag_role = self.appbuilder.sm.find_role('all_dag_role') <ide> edit_perm_on_all_dag = self.appbuilder.sm.\ <del> find_permission_view_menu('can_edit', permissions.RESOURCE_DAGS) <add> find_permission_view_menu(permissions.ACTION_CAN_EDIT, permissions.RESOURCE_DAGS) <ide> self.appbuilder.sm.add_permission_role(all_dag_role, edit_perm_on_all_dag) <ide> read_perm_on_all_dag = self.appbuilder.sm.\ <del> find_permission_view_menu('can_read', permissions.RESOURCE_DAGS) <add> find_permission_view_menu(permissions.ACTION_CAN_READ, permissions.RESOURCE_DAGS) <ide> self.appbuilder.sm.add_permission_role(all_dag_role, read_perm_on_all_dag) <ide> <ide> role_user = self.appbuilder.sm.find_role('User') <ide> self.appbuilder.sm.add_permission_role(role_user, read_perm_on_all_dag) <ide> self.appbuilder.sm.add_permission_role(role_user, edit_perm_on_all_dag) <ide> <ide> read_only_perm_on_dag = self.appbuilder.sm.\ <del> find_permission_view_menu('can_read', 'DAG:example_bash_operator') <add> find_permission_view_menu(permissions.ACTION_CAN_READ, 'DAG:example_bash_operator') <ide> dag_read_only_role = self.appbuilder.sm.find_role('dag_acl_read_only') <ide> self.appbuilder.sm.add_permission_role(dag_read_only_role, read_only_perm_on_dag) <ide>
39
Ruby
Ruby
expand mulasgn for enhancing readability
4ccf8319bb3b6e9f5df507b4e9b58c649a3adc34
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb <ide> module Format <ide> # It will be mapped to one of the standard Rails SQL types in the <tt>type</tt> attribute. <ide> # +null+ determines if this column allows +NULL+ values. <ide> def initialize(name, default, sql_type = nil, null = true) <del> @name, @sql_type, @null = name, sql_type, null <del> @limit, @precision, @scale = extract_limit(sql_type), extract_precision(sql_type), extract_scale(sql_type) <del> @type = simplified_type(sql_type) <del> @default = extract_default(default) <del> <del> @primary = nil <add> @name = name <add> @sql_type = sql_type <add> @null = null <add> @limit = extract_limit(sql_type) <add> @precision = extract_precision(sql_type) <add> @scale = extract_scale(sql_type) <add> @type = simplified_type(sql_type) <add> @default = extract_default(default) <add> @primary = nil <ide> end <ide> <ide> # Returns +true+ if the column is either of type string or text.
1
Ruby
Ruby
allow head in new formulas
b796174d2cfb6d912f7d349d800f5a9a77899d36
<ide><path>Library/Homebrew/dev-cmd/audit.rb <ide> def audit_specs <ide> <ide> problem "Formulae should not have a `devel` spec" if formula.devel <ide> <del> if formula.head <add> if formula.head && @versioned_formula <ide> head_spec_message = "Formulae should not have a `HEAD` spec" <del> if @new_formula <del> new_formula_problem head_spec_message <del> elsif @versioned_formula <del> versioned_head_spec = %w[ <del> bash-completion@2 <del> imagemagick@6 <del> python@2 <del> ] <del> problem head_spec_message unless versioned_head_spec.include?(formula.name) <del> end <add> versioned_head_spec = %w[ <add> bash-completion@2 <add> imagemagick@6 <add> python@2 <add> ] <add> problem head_spec_message unless versioned_head_spec.include?(formula.name) <ide> end <ide> <ide> throttled = %w[
1
Ruby
Ruby
remove hash noise
7174307bd8b7ddb0bd3ec1a5937f03e8ce80a5e4
<ide><path>activerecord/test/cases/tasks/mysql_rake_test.rb <ide> def setup <ide> $stdout.stubs(:print).returns(nil) <ide> @error.stubs(:errno).returns(1045) <ide> ActiveRecord::Base.stubs(:connection).returns(@connection) <del> ActiveRecord::Base.stubs(:establish_connection).raises(@error).then. <del> returns(true) <add> ActiveRecord::Base.stubs(:establish_connection). <add> raises(@error). <add> then.returns(true) <ide> end <ide> <ide> def test_root_password_is_requested <ide> def test_root_password_is_requested <ide> end <ide> <ide> def test_connection_established_as_root <del> ActiveRecord::Base.expects(:establish_connection).with({ <add> ActiveRecord::Base.expects(:establish_connection).with( <ide> 'adapter' => 'mysql', <ide> 'database' => nil, <ide> 'username' => 'root', <ide> 'password' => 'secret' <del> }) <add> ) <ide> <ide> ActiveRecord::Tasks::DatabaseTasks.create @configuration <ide> end <ide> def test_grant_privileges_for_normal_user <ide> <ide> def test_connection_established_as_normal_user <ide> ActiveRecord::Base.expects(:establish_connection).returns do <del> ActiveRecord::Base.expects(:establish_connection).with({ <add> ActiveRecord::Base.expects(:establish_connection).with( <ide> 'adapter' => 'mysql', <ide> 'database' => 'my-app-db', <ide> 'username' => 'pat', <ide> 'password' => 'secret' <del> }) <add> ) <ide> <ide> raise @error <ide> end <ide> def test_establishes_connection_to_test_database <ide> <ide> def test_recreates_database_with_the_default_options <ide> @connection.expects(:recreate_database). <del> with('test-db', { :charset => 'utf8', :collation => 'utf8_unicode_ci' }) <add> with('test-db', charset: 'utf8', collation: 'utf8_unicode_ci') <ide> <ide> ActiveRecord::Tasks::DatabaseTasks.purge @configuration <ide> end <ide> <ide> def test_recreates_database_with_the_given_options <ide> @connection.expects(:recreate_database). <del> with('test-db', { :charset => 'latin', :collation => 'latin_ci' }) <add> with('test-db', charset: 'latin', collation: 'latin1_swedish_ci') <ide> <ide> ActiveRecord::Tasks::DatabaseTasks.purge @configuration.merge( <del> 'encoding' => 'latin', 'collation' => 'latin_ci' <del> ) <add> 'encoding' => 'latin', 'collation' => 'latin1_swedish_ci') <ide> end <ide> end <ide>
1
Text
Text
update changelog for 2.15.0
defdd1e27472a99875ce928bc138d46b3d2a770b
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <del>### 2.15.0-beta.3 (August 8, 2017) <add>### 2.15.0 (August 31, 2017) <ide> <add>- [#15577](https://github.com/emberjs/ember.js/pull/15577) [BUGFIX] Include missing sourcemaps in vendorTree. <ide> - [#14848](https://github.com/emberjs/ember.js/pull/14848) [BUGFIX] Allow boolean values for current-when <ide> - [#15572](https://github.com/emberjs/ember.js/pull/15572) [BUGFIX] Fix issue with using negative numbers as an argument passed in from the template. <ide> - [#15535](https://github.com/emberjs/ember.js/pull/15535) [BUGFIX] Ensure that properties of functions are able to be rendered. <ide> - [#14753](https://github.com/emberjs/ember.js/pull/14753) [BUGFIX] Fix `<input type=XXX>` feature detect issue affecting Safari. <ide> - [#15176](https://github.com/emberjs/ember.js/pull/15176) [BUGFIX] Ensure `Controller.prototype.replaceRoute` considers engine's mount point. <ide> - [#15513](https://github.com/emberjs/ember.js/pull/15513) [BUGFIX] Release root components after they are destroyed. <del> <del>### 2.15.0-beta.2 (July 20, 2017) <del> <ide> - [#15511](https://github.com/emberjs/ember.js/pull/15511) [BUGFIX] Fixes `onFulfillment` being `undefined` when stepping through RSVP code. <ide> - [#15510](https://github.com/emberjs/ember.js/pull/15510) [BUGFIX] Make sure notification changes are properly triggered for firstObject/lastObject. <ide> - [#15502](https://github.com/emberjs/ember.js/pull/15502) [BUGFIX] Work around a browser bug that causes `getOwner` to sometimes return `undefined`. <del> <del>### 2.15.0-beta.1 (July 5, 2017) <del> <ide> - [#14338](https://github.com/emberjs/ember.js/pull/14338) [FEATURE] Remove explicit names from initializers. <ide> - [#15325](https://github.com/emberjs/ember.js/pull/15325) / [#15326](https://github.com/emberjs/ember.js/pull/15326) [FEATURE ember-engines-mount-params] Allow `{{mount` to accept a `model` named parameter. <ide> - [#15347](https://github.com/emberjs/ember.js/pull/15347) [BUGFIX] Make better errors for meta updates after object destruction.
1
Python
Python
resize instance masks with bilinear method
b810694eb5b155c1e199aa704155c103b6f17ece
<ide><path>official/vision/beta/projects/panoptic_maskrcnn/dataloaders/panoptic_maskrcnn_input.py <ide> def _process_mask(mask, ignore_label, image_info): <ide> panoptic_instance_mask = panoptic_instance_mask[:, :, 0] <ide> <ide> labels['groundtruths'].update({ <del> 'gt_panoptic_category_mask': panoptic_category_mask, <del> 'gt_panoptic_instance_mask': panoptic_instance_mask}) <add> 'gt_panoptic_category_mask': <add> tf.cast(panoptic_category_mask, dtype=tf.int32), <add> 'gt_panoptic_instance_mask': <add> tf.cast(panoptic_instance_mask, dtype=tf.int32)}) <ide> <ide> return image, labels <ide><path>official/vision/beta/projects/panoptic_maskrcnn/modeling/layers/panoptic_segmentation_generator.py <ide> def _paste_mask(self, box, mask): <ide> resized_mask = tf.image.resize( <ide> mask, <ide> size=(box_height, box_width), <del> method='nearest') <add> method='bilinear') <add> resized_mask = tf.cast(resized_mask, dtype=mask.dtype) <ide> <ide> # paste resized mask on a blank mask that matches image shape <ide> pasted_mask = tf.raw_ops.TensorStridedSliceUpdate(
2
Text
Text
update multi-db docs
2451a568aff34816f1df7bd92b158fb059771337
<ide><path>guides/source/active_record_multiple_databases.md <ide> The following features are not (yet) supported: <ide> <ide> * Automatic swapping for horizontal sharding <ide> * Load balancing replicas <del>* Dumping schema caches for multiple databases <ide> <ide> ## Setting up your application <ide> <ide> order from one table cannot be applied to another table. <ide> Rails can't guess this for you because association loading is lazy, to load `treats` in `@dog.treats` <ide> Rails already needs to know what SQL should be generated. <ide> <add>### Schema Caching <add> <add>If you want to load a schema cache for each database you must set a `schema_cache_path` in each database configuration and set `config.active_record.lazily_load_schema_cache = true` in your application configuration. Note that this will lazily load the cache when the database connections are established. <add> <ide> ## Caveats <ide> <ide> ### Automatic swapping for horizontal sharding <ide> Rails also doesn't support automatic load balancing of replicas. This is very <ide> dependent on your infrastructure. We may implement basic, primitive load balancing <ide> in the future, but for an application at scale this should be something your application <ide> handles outside of Rails. <del> <del>### Schema Cache <del> <del>If you use a schema cache and multiple databases, you'll need to write an initializer <del>that loads the schema cache from your app. This wasn't an issue we could resolve in <del>time for Rails 6.0 but hope to have it in a future version soon.
1
Ruby
Ruby
improve performance of rev_list
4e11656e01f4f182bf7357b2bedc2fb4f1be1fa2
<ide><path>Library/Homebrew/cmd/versions.rb <ide> def versions <ide> class Formula <ide> def versions <ide> versions = [] <del> rev_list.each do |sha| <add> rev_list do |sha| <ide> version = version_for_sha sha <ide> unless versions.include? version or version.nil? <ide> yield version, sha if block_given? <ide> def versions <ide> <ide> def bottle_version_map branch='HEAD' <ide> map = Hash.new { |h, k| h[k] = [] } <del> rev_list(branch).each do |rev| <add> rev_list(branch) do |rev| <ide> formula_for_sha(rev) do |f| <ide> bottle = f.class.send(:bottle) <ide> unless bottle.checksums.empty? <ide> def entry_name <ide> <ide> def rev_list branch='HEAD' <ide> repository.cd do <del> `git rev-list --abbrev-commit --remove-empty #{branch} -- #{entry_name}`.split <add> IO.popen("git rev-list --abbrev-commit --remove-empty #{branch} -- #{entry_name}") do |io| <add> yield io.readline.chomp until io.eof? <add> end <ide> end <ide> end <ide>
1
Java
Java
add support for multiple js contexts
872b697730291575c5c25556bc9b49f66863947c
<ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/CatalystInstance.java <ide> public interface CatalystInstance extends MemoryPressureListener { <ide> // which this prevents. <ide> @DoNotStrip <ide> void invokeCallback(ExecutorToken executorToken, final int callbackID, final NativeArray arguments); <add> @DoNotStrip <add> void callFunction( <add> ExecutorToken executorToken, <add> int moduleId, <add> int methodId, <add> NativeArray arguments, <add> String tracingName); <ide> /** <ide> * Destroys this catalyst instance, waiting for any other threads in ReactQueueConfiguration <ide> * (besides the UI thread) to finish running. Must be called from the UI thread so that we can <ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/CatalystInstanceImpl.java <ide> public Boolean call() throws Exception { <ide> } <ide> } <ide> <del> /* package */ void callFunction( <add> @Override <add> public void callFunction( <ide> ExecutorToken executorToken, <ide> int moduleId, <ide> int methodId, <ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/JavaScriptModuleRegistration.java <ide> * Registration info for a {@link JavaScriptModule}. Maps its methods to method ids. <ide> */ <ide> @Immutable <del>class JavaScriptModuleRegistration { <add>public class JavaScriptModuleRegistration { <ide> <ide> private final int mModuleId; <ide> private final Class<? extends JavaScriptModule> mModuleInterface; <ide> private final Map<Method, Integer> mMethodsToIds; <ide> private final Map<Method, String> mMethodsToTracingNames; <ide> <del> JavaScriptModuleRegistration(int moduleId, Class<? extends JavaScriptModule> moduleInterface) { <add> public JavaScriptModuleRegistration(int moduleId, Class<? extends JavaScriptModule> moduleInterface) { <ide> mModuleId = moduleId; <ide> mModuleInterface = moduleInterface; <ide> <ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/JavaScriptModuleRegistry.java <ide> * to the bridge using the corresponding module and method ids so the proper function is executed in <ide> * JavaScript. <ide> */ <del>/*package*/ class JavaScriptModuleRegistry { <add>public class JavaScriptModuleRegistry { <ide> <del> private final CatalystInstanceImpl mCatalystInstance; <add> private final CatalystInstance mCatalystInstance; <ide> private final WeakHashMap<ExecutorToken, HashMap<Class<? extends JavaScriptModule>, JavaScriptModule>> mModuleInstances; <ide> private final HashMap<Class<? extends JavaScriptModule>, JavaScriptModuleRegistration> mModuleRegistrations; <ide> <ide> public JavaScriptModuleRegistry( <del> CatalystInstanceImpl instance, <add> CatalystInstance instance, <ide> JavaScriptModulesConfig config) { <ide> mCatalystInstance = instance; <ide> mModuleInstances = new WeakHashMap<>(); <ide> public synchronized <T extends JavaScriptModule> T getJavaScriptModule(Executor <ide> private static class JavaScriptModuleInvocationHandler implements InvocationHandler { <ide> <ide> private final WeakReference<ExecutorToken> mExecutorToken; <del> private final CatalystInstanceImpl mCatalystInstance; <add> private final CatalystInstance mCatalystInstance; <ide> private final JavaScriptModuleRegistration mModuleRegistration; <ide> <ide> public JavaScriptModuleInvocationHandler( <ide> ExecutorToken executorToken, <del> CatalystInstanceImpl catalystInstance, <add> CatalystInstance catalystInstance, <ide> JavaScriptModuleRegistration moduleRegistration) { <ide> mExecutorToken = new WeakReference<>(executorToken); <ide> mCatalystInstance = catalystInstance; <ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/JavaScriptModulesConfig.java <ide> public class JavaScriptModulesConfig { <ide> <ide> private final List<JavaScriptModuleRegistration> mModules; <ide> <del> private JavaScriptModulesConfig(List<JavaScriptModuleRegistration> modules) { <add> public JavaScriptModulesConfig(List<JavaScriptModuleRegistration> modules) { <ide> mModules = modules; <ide> } <ide> <del> /*package*/ List<JavaScriptModuleRegistration> getModuleDefinitions() { <add> public List<JavaScriptModuleRegistration> getModuleDefinitions() { <ide> return mModules; <ide> } <ide> <del> /*package*/ void writeModuleDescriptions(JsonGenerator jg) throws IOException { <add> public void writeModuleDescriptions(JsonGenerator jg) throws IOException { <ide> jg.writeStartObject(); <ide> for (JavaScriptModuleRegistration registration : mModules) { <ide> jg.writeObjectFieldStart(registration.getName());
5
Javascript
Javascript
serialize the svg to a stream
9b5086d6491fa05efe8680acfe430641ddd205fd
<ide><path>examples/node/domstubs.js <ide> DOMElement.prototype = { <ide> } <ide> }, <ide> <del> toString: function DOMElement_toString() { <del> var buf = []; <del> buf.push('<' + this.nodeName); <del> if (this.nodeName === 'svg:svg') { <del> buf.push(' xmlns:xlink="http://www.w3.org/1999/xlink"' + <del> ' xmlns:svg="http://www.w3.org/2000/svg"'); <del> } <del> for (var i in this.attributes) { <del> buf.push(' ' + i + '="' + xmlEncode(this.attributes[i]) + '"'); <del> } <del> <del> buf.push('>'); <del> <del> if (this.nodeName === 'svg:tspan' || this.nodeName === 'svg:style') { <del> buf.push(xmlEncode(this.textContent)); <del> } else { <del> this.childNodes.forEach(function(childNode) { <del> buf.push(childNode.toString()); <del> }); <del> } <del> buf.push('</' + this.nodeName + '>'); <del> return buf.join(''); <del> }, <del> <ide> cloneNode: function DOMElement_cloneNode() { <ide> var newNode = new DOMElement(this.nodeName); <ide> newNode.childNodes = this.childNodes; <ide> newNode.attributes = this.attributes; <ide> newNode.textContent = this.textContent; <ide> return newNode; <ide> }, <add> <add> // This method is offered for convenience. It is recommended to directly use <add> // getSerializer because that allows you to process the chunks as they come <add> // instead of requiring the whole image to fit in memory. <add> toString: function DOMElement_toString() { <add> var buf = []; <add> var serializer = this.getSerializer(); <add> var chunk; <add> while ((chunk = serializer.getNext()) !== null) { <add> buf.push(chunk); <add> } <add> return buf.join(''); <add> }, <add> <add> getSerializer: function DOMElement_getSerializer() { <add> return new DOMElementSerializer(this); <add> } <ide> } <ide> <add>function DOMElementSerializer(node) { <add> this._node = node; <add> this._state = 0; <add> this._loopIndex = 0; <add> this._attributeKeys = null; <add> this._childSerializer = null; <add>} <add>DOMElementSerializer.prototype = { <add> /** <add> * Yields the next chunk in the serialization of the element. <add> * <add> * @returns {string|null} null if the element has fully been serialized. <add> */ <add> getNext: function DOMElementSerializer_getNext() { <add> var node = this._node; <add> switch (this._state) { <add> case 0: // Start opening tag. <add> ++this._state; <add> return '<' + node.nodeName; <add> case 1: // Add SVG namespace if this is the root element. <add> ++this._state; <add> if (node.nodeName === 'svg:svg') { <add> return ' xmlns:xlink="http://www.w3.org/1999/xlink"' + <add> ' xmlns:svg="http://www.w3.org/2000/svg"'; <add> } <add> case 2: // Initialize variables for looping over attributes. <add> ++this._state; <add> this._loopIndex = 0; <add> this._attributeKeys = Object.keys(node.attributes); <add> case 3: // Serialize any attributes and end opening tag. <add> if (this._loopIndex < this._attributeKeys.length) { <add> var name = this._attributeKeys[this._loopIndex++]; <add> return ' ' + name + '="' + xmlEncode(node.attributes[name]) + '"'; <add> } <add> ++this._state; <add> return '>'; <add> case 4: // Serialize textContent for tspan/style elements. <add> if (node.nodeName === 'svg:tspan' || node.nodeName === 'svg:style') { <add> this._state = 6; <add> return xmlEncode(node.textContent); <add> } <add> ++this._state; <add> this._loopIndex = 0; <add> case 5: // Serialize child nodes (only for non-tspan/style elements). <add> var value; <add> while (true) { <add> value = this._childSerializer && this._childSerializer.getNext(); <add> if (value !== null) { <add> return value; <add> } <add> var nextChild = node.childNodes[this._loopIndex++]; <add> if (nextChild) { <add> this._childSerializer = new DOMElementSerializer(nextChild); <add> } else { <add> this._childSerializer = null; <add> ++this._state; <add> break; <add> } <add> } <add> case 6: // Ending tag. <add> ++this._state; <add> return '</' + node.nodeName + '>'; <add> case 7: // Done. <add> return null; <add> default: <add> throw new Error('Unexpected serialization state: ' + this._state); <add> } <add> }, <add>}; <add> <ide> const document = { <ide> childNodes : [], <ide> <ide><path>examples/node/pdf2svg.js <ide> // <ide> <ide> var fs = require('fs'); <add>var util = require('util'); <add>var path = require('path'); <add>var stream = require('stream'); <ide> <ide> // HACK few hacks to let PDF.js be loaded not as a module in global space. <ide> require('./domstubs.js').setStubs(global); <ide> var pdfjsLib = require('pdfjs-dist'); <ide> var pdfPath = process.argv[2] || '../../web/compressed.tracemonkey-pldi-09.pdf'; <ide> var data = new Uint8Array(fs.readFileSync(pdfPath)); <ide> <add>var outputDirectory = './svgdump'; <add> <add>try { <add> // Note: This creates a directory only one level deep. If you want to create <add> // multiple subdirectories on the fly, use the mkdirp module from npm. <add> fs.mkdirSync(outputDirectory); <add>} catch (e) { <add> if (e.code !== 'EEXIST') { <add> throw e; <add> } <add>} <add> <ide> // Dumps svg outputs to a folder called svgdump <del>function writeToFile(svgdump, pageNum, callback) { <del> var name = getFileNameFromPath(pdfPath); <del> fs.mkdir('./svgdump/', function(err) { <del> if (!err || err.code === 'EEXIST') { <del> fs.writeFile('./svgdump/' + name + "-" + pageNum + '.svg', svgdump, <del> function(err) { <del> if (err) { <del> console.log('Error: ' + err); <del> } else { <del> console.log('Page: ' + pageNum); <del> } <del> callback(); <del> }); <del> } else { <del> callback(); <del> } <del> }); <add>function getFilePathForPage(pageNum) { <add> var name = path.basename(pdfPath, path.extname(pdfPath)); <add> return path.join(outputDirectory, name + '-' + pageNum + '.svg'); <ide> } <ide> <del>// Get filename from the path <add>/** <add> * A readable stream which offers a stream representing the serialization of a <add> * given DOM element (as defined by domstubs.js). <add> * <add> * @param {object} options <add> * @param {DOMElement} options.svgElement The element to serialize <add> */ <add>function ReadableSVGStream(options) { <add> if (!(this instanceof ReadableSVGStream)) { <add> return new ReadableSVGStream(options); <add> } <add> stream.Readable.call(this, options); <add> this.serializer = options.svgElement.getSerializer(); <add>} <add>util.inherits(ReadableSVGStream, stream.Readable); <add>// Implements https://nodejs.org/api/stream.html#stream_readable_read_size_1 <add>ReadableSVGStream.prototype._read = function() { <add> var chunk; <add> while ((chunk = this.serializer.getNext()) !== null) { <add> if (!this.push(chunk)) { <add> return; <add> } <add> } <add> this.push(null); <add>}; <ide> <del>function getFileNameFromPath(path) { <del> var index = path.lastIndexOf('/'); <del> var extIndex = path.lastIndexOf('.'); <del> return path.substring(index, extIndex); <add>// Streams the SVG element to the given file path. <add>function writeSvgToFile(svgElement, filePath) { <add> var readableSvgStream = new ReadableSVGStream({ <add> svgElement: svgElement, <add> }); <add> var writableStream = fs.createWriteStream(filePath); <add> return new Promise(function(resolve, reject) { <add> readableSvgStream.once('error', reject); <add> writableStream.once('error', reject); <add> writableStream.once('finish', resolve); <add> readableSvgStream.pipe(writableStream); <add> }).catch(function(err) { <add> readableSvgStream = null; // Explicitly null because of v8 bug 6512. <add> writableStream.end(); <add> throw err; <add> }); <ide> } <ide> <ide> // Will be using promises to load document, pages and misc data instead of <ide> pdfjsLib.getDocument({ <ide> var svgGfx = new pdfjsLib.SVGGraphics(page.commonObjs, page.objs); <ide> svgGfx.embedFonts = true; <ide> return svgGfx.getSVG(opList, viewport).then(function (svg) { <del> var svgDump = svg.toString(); <del> return new Promise(function(resolve) { <del> writeToFile(svgDump, pageNum, resolve); <add> return writeSvgToFile(svg, getFilePathForPage(pageNum)).then(function () { <add> console.log('Page: ' + pageNum); <add> }, function(err) { <add> console.log('Error: ' + err); <ide> }); <ide> }); <ide> }); <del> }) <add> }); <ide> }; <ide> <ide> for (var i = 1; i <= numPages; i++) {
2
Python
Python
improve unit test
1cd238a460ac7608654856864e8adf224a1b2a2c
<ide><path>tests/keras/test_sequential_model.py <ide> def test_clone_functional_model(): <ide> <ide> x_a = dense_1(input_a) <ide> x_a = keras.layers.Dropout(0.5)(x_a) <add> x_a = keras.layers.BatchNormalization()(x_a) <ide> x_b = dense_1(input_b) <ide> x_a = dense_2(x_a) <ide> outputs = keras.layers.add([x_a, x_b]) <ide> def test_clone_sequential_model(): <ide> <ide> model = keras.models.Sequential() <ide> model.add(keras.layers.Dense(4, input_shape=(4,))) <add> model.add(keras.layers.BatchNormalization()) <ide> model.add(keras.layers.Dropout(0.5)) <ide> model.add(keras.layers.Dense(4)) <ide>
1
Text
Text
add upcoming 16.4.0 changelog
d1be01f079ed20b06bc76a0e66eb0d2c615e3aad
<ide><path>CHANGELOG.md <ide> Changes that have landed in master but are not yet released. <ide> Click to see more. <ide> </summary> <add> <add>### React <add> <add>* Add a new experimental `React.unstable_Profiler` component for measuring performance. ([@bvaughn](https://github.com/bvaughn) in [#12745](https://github.com/facebook/react/pull/12745)) <add> <add>### React DOM <add> <add>* Add support for the Pointer Events specification. ([@philipp-spiess](https://github.com/philipp-spiess) in [#12507](https://github.com/facebook/react/pull/12507)) <add>* Call `getDerivedFromProps()` regardless of why rendering happened. ([@acdlite](https://github.com/acdlite) in [#12600](https://github.com/facebook/react/pull/12600) and [#12802](https://github.com/facebook/react/pull/12802)) <add>* Fix a bug that prevented context propagation in some cases. ([@gaearon](https://github.com/gaearon) in [#12708](https://github.com/facebook/react/pull/12708)) <add>* Fix re-rendering of components using `forwardRef()` on a deeper `setState()`. ([@gaearon](https://github.com/gaearon) in [#12690](https://github.com/facebook/react/pull/12690)) <add>* Fix some attributes incorrectly getting removed from custom element nodes. ([@airamrguez](https://github.com/airamrguez) in [#12702](https://github.com/facebook/react/pull/12702)) <add>* Fix context providers to not bail out on children if there's a legacy context provider above. ([@gaearon](https://github.com/gaearon) in [#12586](https://github.com/facebook/react/pull/12586)) <add>* Add the ability to specify `propTypes` on a context provider component. ([@nicolevy](https://github.com/nicolevy) in [#12658](https://github.com/facebook/react/pull/12658)) <add>* Fix a false positive warning when using `react-lifecycles-compat` in `<StrictMode>`. ([@bvaughn](https://github.com/bvaughn) in [#12644](https://github.com/facebook/react/pull/12644)) <add>* Warn when the `forwardRef()` render function has `propTypes` or `defaultProps`. ([@bvaughn](https://github.com/bvaughn) in [#12644](https://github.com/facebook/react/pull/12644)) <add>* Improve how `forwardRef()` and context consumers are displayed in the component stack. ([@sophiebits](https://github.com/sophiebits) in [#12777](https://github.com/facebook/react/pull/12777)) <add>* Change internal event names. This can break third-party packages that rely on React internals in unsupported ways. ([@philipp-spiess](https://github.com/philipp-spiess) in [#12629](https://github.com/facebook/react/pull/12629)) <add> <add>### React Test Renderer <add> <add>* Fix the `getDerivedStateFromProps()` support to match the new React DOM behavior. ([@koba04](https://github.com/koba04) in [#12676](https://github.com/facebook/react/pull/12676)) <add>* Fix a `testInstance.parent` crash when the parent is a fragment or another special node. ([@gaearon](https://github.com/gaearon) in [#12813](https://github.com/facebook/react/pull/12813)) <add>* `forwardRef()` components are now discoverable by the test renderer traversal methods. ([@gaearon](https://github.com/gaearon) in [#12725](https://github.com/facebook/react/pull/12725)) <add>* Shallow renderer now ignores `setState()` updaters that return `null` or `undefined`. ([@koba04](https://github.com/koba04) in [#12756](https://github.com/facebook/react/pull/12756)) <add> <add>### React ART <add> <add>* Fix reading context provided from the tree managed by React DOM. ([@acdlite](https://github.com/acdlite) in [#12779](https://github.com/facebook/react/pull/12779)) <add> <add>### React Call Return (Experimental) <add> <add>* This experiment was deleted because it was affecting the bundle size and the API wasn't good enough. It's likely to come back in the future in some other form. ([@gaearon](https://github.com/gaearon) in [#12820](https://github.com/facebook/react/pull/12820)) <add> <add>### React Reconciler (Experimental) <add> <add>* The [new host config shape](https://github.com/facebook/react/blob/c601f7a64640290af85c9f0e33c78480656b46bc/packages/react-noop-renderer/src/createReactNoop.js#L82-L285) is flat and doesn't use nested objects. ([@gaearon](https://github.com/gaearon) in [#12792](https://github.com/facebook/react/pull/12792)) <add> <ide> </details> <ide> <ide> ## 16.3.2 (April 16, 2018)
1
Text
Text
add primordials guidelines
92f8c03ce620aee28a97f19603b91dad14637064
<ide><path>doc/contributing/primordials.md <add># Usage of primordials in core <add> <add>The file `lib/internal/per_context/primordials.js` subclasses and stores the JS <add>built-ins that come from the VM so that Node.js built-in modules do not need to <add>later look these up from the global proxy, which can be mutated by users. <add> <add>Usage of primordials should be preferred for any new code, but replacing current <add>code with primordials should be <add>[done with care](#primordials-with-known-performance-issues). It is highly <add>recommended to ping the relevant team when reviewing a pull request that touches <add>one of the subsystems they "own". <add> <add>## Accessing primordials <add> <add>The primordials are meant for internal use only, and are only accessible for <add>internal core modules. User code cannot use or rely on primordials. It is <add>usually fine to rely on ECMAScript built-ins and assume that it will behave as <add>specified. <add> <add>If you would like to access the `primordials` object to help you with Node.js <add>core development or for tinkering, you can expose it on the global scope using <add>this combination of CLI flags: <add> <add>```bash <add>node --expose-internals -r internal/test/binding <add>``` <add> <add>## Contents of primordials <add> <add>### Properties of the global object <add> <add>Objects and functions on the global object can be deleted or replaced. Using <add>them from primordials makes the code more reliable: <add> <add>```js <add>globalThis.Array === primordials.Array; // true <add> <add>globalThis.Array = function() { <add> return [1, 2, 3]; <add>}; <add>globalThis.Array === primordials.Array; // false <add> <add>primordials.Array(0); // [] <add>globalThis.Array(0); // [1,2,3] <add>``` <add> <add>### Prototype methods <add> <add>ECMAScript provides a group of methods available on built-in objects that are <add>used to interact with JavaScript objects. <add> <add>```js <add>const array = [1, 2, 3]; <add>array.push(4); // Here `push` refers to %Array.prototype.push%. <add>console.log(JSON.stringify(array)); // [1,2,3,4] <add> <add>// %Array.prototype%.push is modified in userland. <add>Array.prototype.push = function push(val) { <add> return this.unshift(val); <add>}; <add> <add>array.push(5); // Now `push` refers to the modified method. <add>console.log(JSON.stringify(array)); // [5,1,2,3,4] <add>``` <add> <add>Primordials wrap the original prototype functions with new functions that take <add>the `this` value as the first argument: <add> <add>```js <add>const { <add> ArrayPrototypePush, <add>} = primordials; <add> <add>const array = [1, 2, 3]; <add>ArrayPrototypePush(array, 4); <add>console.log(JSON.stringify(array)); // [1,2,3,4] <add> <add>Array.prototype.push = function push(val) { <add> return this.unshift(val); <add>}; <add> <add>ArrayPrototypePush(array, 5); <add>console.log(JSON.stringify(array)); // [1,2,3,4,5] <add>``` <add> <add>### Safe classes <add> <add>Safe classes are classes that provide the same API as their equivalent class, <add>but whose implementation aims to avoid any reliance on user-mutable code. <add>Safe classes should not be exposed to user-land; use unsafe equivalent when <add>dealing with objects that are accessible from user-land. <add> <add>### Variadic functions <add> <add>There are some built-in functions that accept a variable number of arguments <add>(e.g.: `Math.max`, `%Array.prototype.push%`). It is sometimes useful to provide <add>the list of arguments as an array. You can use primordial function with the <add>suffix `Apply` (e.g.: `MathMaxApply`, `ArrayPrototypePushApply`) to do that. <add> <add>## Primordials with known performance issues <add> <add>One of the reasons why the current Node.js API is not completely tamper-proof is <add>performance: sometimes the use of primordials can cause performance regressions <add>with V8, which when in a hot code path, could significantly decrease the <add>performance of code in Node.js. <add> <add>* Methods that mutate the internal state of arrays: <add> * `ArrayPrototypePush` <add> * `ArrayPrototypePop` <add> * `ArrayPrototypeShift` <add> * `ArrayPrototypeUnshift` <add>* Methods of the function prototype: <add> * `FunctionPrototypeBind` <add> * `FunctionPrototypeCall`: creates performance issues when used to invoke <add> super constructors. <add> * `FunctionPrototype`: use `() => {}` instead when referencing a no-op <add> function. <add>* `SafeArrayIterator` <add>* `SafeStringIterator` <add>* `SafePromiseAll` <add>* `SafePromiseAllSettled` <add>* `SafePromiseAny` <add>* `SafePromiseRace` <add>* `SafePromisePrototypeFinally`: use `try {} finally {}` block instead. <add> <add>In general, when sending or reviewing a PR that makes changes in a hot code <add>path, use extra caution and run extensive benchmarks. <add> <add>## Implicit use of user-mutable methods <add> <add>### Unsafe array iteration <add> <add>There are many usual practices in JavaScript that rely on iteration. It's useful <add>to be aware of them when dealing with arrays (or `TypedArray`s) in core as array <add>iteration typically calls several user-mutable methods. This sections lists the <add>most common patterns in which ECMAScript code relies non-explicitly on array <add>iteration and how to avoid it. <add> <add><details> <add> <add><summary>Avoid for-of loops on arrays</summary> <add> <add>```js <add>for (const item of array) { <add> console.log(item); <add>} <add>``` <add> <add>This code is internally expanded into something that looks like: <add> <add>```js <add>{ <add> // 1. Lookup @@iterator property on `array` (user-mutable if user-provided). <add> // 2. Lookup @@iterator property on %Array.prototype% (user-mutable). <add> // 3. Call that function. <add> const iterator = array[Symbol.iterator](); <add> // 1. Lookup `next` property on `iterator` (doesn't exist). <add> // 2. Lookup `next` property on %ArrayIteratorPrototype% (user-mutable). <add> // 3. Call that function. <add> let { done, value: item } = iterator.next(); <add> while (!done) { <add> console.log(item); <add> // Repeat. <add> ({ done, value: item } = iterator.next()); <add> } <add>} <add>``` <add> <add>Instead of utilizing iterators, you can use the more traditional but still very <add>performant `for` loop: <add> <add>```js <add>for (let i = 0; i < array.length; i++) { <add> console.log(array[i]); <add>} <add>``` <add> <add>The following code snippet illustrates how user-land code could impact the <add>behavior of internal modules: <add> <add>```js <add>// User-land <add>Array.prototype[Symbol.iterator] = () => ({ <add> next: () => ({ done: true }), <add>}); <add> <add>// Core <add>let forOfLoopBlockExecuted = false; <add>let forLoopBlockExecuted = false; <add>const array = [1, 2, 3]; <add>for (const item of array) { <add> forOfLoopBlockExecuted = true; <add>} <add>for (let i = 0; i < array.length; i++) { <add> forLoopBlockExecuted = true; <add>} <add>console.log(forOfLoopBlockExecuted); // false <add>console.log(forLoopBlockExecuted); // true <add>``` <add> <add>This only applies if you are working with a genuine array (or array-like <add>object). If you are instead expecting an iterator, a for-of loop may be a better <add>choice. <add> <add></details> <add> <add><details> <add> <add><summary>Avoid array destructuring assignment on arrays</summary> <add> <add>```js <add>const [first, second] = array; <add>``` <add> <add>This is roughly equivalent to: <add> <add>```js <add>// 1. Lookup @@iterator property on `array` (user-mutable if user-provided). <add>// 2. Lookup @@iterator property on %Array.prototype% (user-mutable). <add>// 3. Call that function. <add>const iterator = array[Symbol.iterator](); <add>// 1. Lookup `next` property on `iterator` (doesn't exist). <add>// 2. Lookup `next` property on %ArrayIteratorPrototype% (user-mutable). <add>// 3. Call that function. <add>const first = iterator.next().value; <add>// Repeat. <add>const second = iterator.next().value; <add>``` <add> <add>Instead you can use object destructuring: <add> <add>```js <add>const { 0: first, 1: second } = array; <add>``` <add> <add>or <add> <add>```js <add>const first = array[0]; <add>const second = array[1]; <add>``` <add> <add>This only applies if you are working with a genuine array (or array-like <add>object). If you are instead expecting an iterator, array destructuring is the <add>best choice. <add> <add></details> <add> <add><details> <add> <add><summary>Avoid spread operator on arrays</summary> <add> <add>```js <add>// 1. Lookup @@iterator property on `array` (user-mutable if user-provided). <add>// 2. Lookup @@iterator property on %Array.prototype% (user-mutable). <add>// 3. Lookup `next` property on %ArrayIteratorPrototype% (user-mutable). <add>const arrayCopy = [...array]; <add>func(...array); <add>``` <add> <add>Instead you can use other ECMAScript features to achieve the same result: <add> <add>```js <add>const arrayCopy = ArrayPrototypeSlice(array); <add>ReflectApply(func, null, array); <add>``` <add> <add></details> <add> <add><details> <add> <add><summary><code>%Object.fromEntries%</code> iterate over an array</summary> <add> <add>```js <add>{ <add> // Unsafe code example: <add> // 1. Lookup @@iterator property on `array` (user-mutable if user-provided). <add> // 2. Lookup @@iterator property on %Array.prototype% (user-mutable). <add> // 3. Lookup `next` property on %ArrayIteratorPrototype% (user-mutable). <add> const obj = ObjectFromEntries(array); <add>} <add> <add>{ <add> // Safe example using `SafeArrayIterator`: <add> const obj = ObjectFromEntries(new SafeArrayIterator(array)); <add>} <add> <add>{ <add> // Safe example without using `SafeArrayIterator`: <add> const obj = {}; <add> for (let i = 0; i < array.length; i++) { <add> obj[array[i][0]] = array[i][1]; <add> } <add> // In a hot code path, this would be the preferred method. <add>} <add>``` <add> <add></details> <add> <add><details> <add> <add><summary><code>%Promise.all%</code>, <add> <code>%Promise.allSettled%</code>, <add> <code>%Promise.any%</code>, and <add> <code>%Promise.race%</code> iterate over an array</summary> <add> <add>```js <add>// 1. Lookup @@iterator property on `array` (user-mutable if user-provided). <add>// 2. Lookup @@iterator property on %Array.prototype% (user-mutable). <add>// 3. Lookup `next` property on %ArrayIteratorPrototype% (user-mutable). <add>PromiseAll(array); // unsafe <add> <add>PromiseAll(new SafeArrayIterator(array)); <add>SafePromiseAll(array); // safe <add>``` <add> <add></details> <add> <add><details> <add> <add><summary><code>%Map%</code>, <code>%Set%</code>, <code>%WeakMap%</code>, and <add> <code>%WeakSet%</code> constructors iterate over an array</summary> <add> <add>```js <add>// User-land <add>Array.prototype[Symbol.iterator] = () => ({ <add> next: () => ({ done: true }), <add>}); <add> <add>// Core <add> <add>// 1. Lookup @@iterator property on %Array.prototype% (user-mutable). <add>// 2. Lookup `next` property on %ArrayIteratorPrototype% (user-mutable). <add>const set = new SafeSet([1, 2, 3]); <add> <add>console.log(set.size); // 0 <add>``` <add> <add>```js <add>// User-land <add>Array.prototype[Symbol.iterator] = () => ({ <add> next: () => ({ done: true }), <add>}); <add> <add>// Core <add>const set = new SafeSet(); <add>set.add(1).add(2).add(3); <add>console.log(set.size); // 3 <add>``` <add> <add></details> <add> <add>### Promise objects <add> <add><details> <add> <add><summary><code>%Promise.prototype.finally%</code> looks up <code>then</code> <add> property of the Promise instance</summary> <add> <add>```js <add>// User-land <add>Promise.prototype.then = function then(a, b) { <add> return Promise.resolve(); <add>}; <add> <add>// Core <add>let finallyBlockExecuted = false; <add>PromisePrototypeFinally(somePromiseThatEventuallySettles, <add> () => { finallyBlockExecuted = true; }); <add>process.on('exit', () => console.log(finallyBlockExecuted)); // false <add>``` <add> <add>```js <add>// User-land <add>Promise.prototype.then = function then(a, b) { <add> return Promise.resolve(); <add>}; <add> <add>// Core <add>let finallyBlockExecuted = false; <add>(async () => { <add> try { <add> return await somePromiseThatEventuallySettles; <add> } finally { <add> finallyBlockExecuted = true; <add> } <add>})(); <add>process.on('exit', () => console.log(finallyBlockExecuted)); // true <add>``` <add> <add></details> <add> <add><details> <add> <add><summary><code>%Promise.all%</code>, <add> <code>%Promise.allSettled%</code>, <add> <code>%Promise.any%</code>, and <add> <code>%Promise.race%</code> look up <code>then</code> <add> property of the Promise instances</summary> <add> <add>You can use safe alternatives from primordials that differ slightly from the <add>original methods: <add>* It expects an array (or array-like object) instead of an iterable. <add>* It wraps each promise in `SafePromise` objects and wraps the result in a new <add> `Promise` instance – which may come with a performance penalty. <add>* Because it doesn't look up `then` property, it may not be the right tool to <add> handle user-provided promises (which may be instances of a subclass of <add> `Promise`). <add> <add>```js <add>// User-land <add>Promise.prototype.then = function then(a, b) { <add> return Promise.resolve(); <add>}; <add> <add>// Core <add>let thenBlockExecuted = false; <add>PromisePrototypeThen( <add> PromiseAll(new SafeArrayIterator([PromiseResolve()])), <add> () => { thenBlockExecuted = true; } <add>); <add>process.on('exit', () => console.log(thenBlockExecuted)); // false <add>``` <add> <add>```js <add>// User-land <add>Promise.prototype.then = function then(a, b) { <add> return Promise.resolve(); <add>}; <add> <add>// Core <add>let thenBlockExecuted = false; <add>PromisePrototypeThen( <add> SafePromiseAll([PromiseResolve()]), <add> () => { thenBlockExecuted = true; } <add>); <add>process.on('exit', () => console.log(thenBlockExecuted)); // true <add>``` <add> <add></details> <add> <add>### (Async) Generator functions <add> <add>Generators and async generators returned by generator functions and async <add>generator functions are relying on user-mutable methods; their use in core <add>should be avoided. <add> <add><details> <add> <add><summary><code>%GeneratorFunction.prototype.prototype%.next</code> is <add> user-mutable</summary> <add> <add>```js <add>// User-land <add>Object.getPrototypeOf(function* () {}).prototype.next = function next() { <add> return { done: true }; <add>}; <add> <add>// Core <add>function* someGenerator() { <add> yield 1; <add> yield 2; <add> yield 3; <add>} <add>let loopCodeExecuted = false; <add>for (const nb of someGenerator()) { <add> loopCodeExecuted = true; <add>} <add>console.log(loopCodeExecuted); // false <add>``` <add> <add></details> <add> <add><details> <add> <add><summary><code>%AsyncGeneratorFunction.prototype.prototype%.next</code> is <add> user-mutable</summary> <add> <add>```js <add>// User-land <add>Object.getPrototypeOf(async function* () {}).prototype.next = function next() { <add> return new Promise(() => {}); <add>}; <add> <add>// Core <add>async function* someGenerator() { <add> yield 1; <add> yield 2; <add> yield 3; <add>} <add>let finallyBlockExecuted = false; <add>async () => { <add> try { <add> for await (const nb of someGenerator()) { <add> // some code; <add> } <add> } finally { <add> finallyBlockExecuted = true; <add> } <add>}; <add>process.on('exit', () => console.log(finallyBlockExecuted)); // false <add>``` <add> <add></details> <add> <add>### Text processing <add> <add>#### Unsafe string methods <add> <add>| The string method | looks up the property | <add>| ----------------------------- | --------------------- | <add>| `String.prototype.match` | `Symbol.match` | <add>| `String.prototype.matchAll` | `Symbol.matchAll` | <add>| `String.prototype.replace` | `Symbol.replace` | <add>| `String.prototype.replaceAll` | `Symbol.replace` | <add>| `String.prototype.search` | `Symbol.search` | <add>| `String.prototype.split` | `Symbol.split` | <add> <add>```js <add>// User-land <add>RegExp.prototype[Symbol.replace] = () => 'foo'; <add>String.prototype[Symbol.replace] = () => 'baz'; <add> <add>// Core <add>console.log(StringPrototypeReplace('ber', /e/, 'a')); // 'foo' <add>console.log(StringPrototypeReplace('ber', 'e', 'a')); // 'baz' <add>console.log(RegExpPrototypeSymbolReplace(/e/, 'ber', 'a')); // 'bar' <add>``` <add> <add>#### Unsafe string iteration <add> <add>As with arrays, iterating over strings calls several user-mutable methods. Avoid <add>iterating over strings when possible, or use `SafeStringIterator`. <add> <add>#### Unsafe `RegExp` methods <add> <add>Functions that lookup the `exec` property on the prototype chain: <add> <add>* `RegExp.prototype[Symbol.match]` <add>* `RegExp.prototype[Symbol.matchAll]` <add>* `RegExp.prototype[Symbol.replace]` <add>* `RegExp.prototype[Symbol.search]` <add>* `RegExp.prototype[Symbol.split]` <add>* `RegExp.prototype.test` <add> <add>```js <add>// User-land <add>RegExp.prototype.exec = () => null; <add> <add>// Core <add>console.log(RegExpPrototypeTest(/o/, 'foo')); // false <add>console.log(RegExpPrototypeExec(/o/, 'foo') !== null); // true <add>``` <add> <add>#### Don't trust `RegExp` flags <add> <add>RegExp flags are not own properties of the regex instances, which means flags <add>can be reset from user-land. <add> <add><details> <add> <add><summary>List of <code>RegExp</code> methods that look up properties from <add> mutable getters</summary> <add> <add>| `RegExp` method | looks up the following flag-related properties | <add>| ------------------------------ | ------------------------------------------------------------------ | <add>| `get RegExp.prototype.flags` | `global`, `ignoreCase`, `multiline`, `dotAll`, `unicode`, `sticky` | <add>| `RegExp.prototype[@@match]` | `global`, `unicode` | <add>| `RegExp.prototype[@@matchAll]` | `flags` | <add>| `RegExp.prototype[@@replace]` | `global`, `unicode` | <add>| `RegExp.prototype[@@split]` | `flags` | <add>| `RegExp.prototype.toString` | `flags` | <add> <add></details> <add> <add>```js <add>// User-land <add>Object.defineProperty(RegExp.prototype, 'global', { value: false }); <add> <add>// Core <add>console.log(RegExpPrototypeSymbolReplace(/o/g, 'foo', 'a')); // 'fao' <add> <add>const regex = /o/g; <add>ObjectDefineProperties(regex, { <add> dotAll: { value: false }, <add> exec: { value: undefined }, <add> flags: { value: 'g' }, <add> global: { value: true }, <add> ignoreCase: { value: false }, <add> multiline: { value: false }, <add> unicode: { value: false }, <add> sticky: { value: false }, <add>}); <add>console.log(RegExpPrototypeSymbolReplace(regex, 'foo', 'a')); // 'faa' <add>```
1
Ruby
Ruby
use odie instead of onoe+exit
43dafc9859e415ac85c4a082b23ceadd5813c196
<ide><path>Library/Homebrew/brew.rb <ide> def require?(path) <ide> safe_system(*tap_commands) <ide> exec HOMEBREW_BREW_FILE, cmd, *ARGV <ide> else <del> onoe "Unknown command: #{cmd}" <del> exit 1 <add> odie "Unknown command: #{cmd}" <ide> end <ide> end <ide>
1
PHP
PHP
move mysql describe() and tests to dialect system
dc1f7662484910513e394d782bcd11dc0ebfab76
<ide><path>lib/Cake/Database/Connection.php <ide> public function lastInsertId($table) { <ide> return $this->_driver->lastInsertId($table); <ide> } <ide> <del>/** <del> * Get the schema information for a given table/collection <del> * <del> * @param string $table The table/collection you want schema information for. <del> * @return array The schema data for the requested table. <del> */ <del> public function describe($table) { <del> list($sql, $params) = $this->_driver->describeTableSql($table, $this->_config); <del> $statement = $this->execute($sql, $params); <del> $schema = []; <del> <del> $fieldParams = $this->_driver->extraSchemaColumns(); <del> $rows = $statement->fetchAll('assoc'); <del> foreach ($rows as $row) { <del> $schema += $this->_driver->convertFieldDescription($row, $fieldParams); <del> } <del> return $schema; <del> } <del> <ide> /** <ide> * Enables or disables query logging for this connection. <ide> * <ide><path>lib/Cake/Database/Schema/Collection.php <ide> namespace Cake\Database\Schema; <ide> <ide> use Cake\Database\Connection; <add>use Cake\Database\Schema\Table; <ide> use Cake\Error; <ide> <ide> /** <ide> public function listTables() { <ide> /** <ide> * Get the column metadata for a table. <ide> * <del> * <del> * @param string $name The name of the table to describe <del> * @return Cake\Schema\Table object with column metdata. <add> * @param string $name The name of the table to describe. <add> * @return Cake\Schema\Table|null Object with column metadata, or null. <ide> * @see Collection::fullDescribe() <ide> */ <ide> public function describe($name) { <add> list($sql, $params) = $this->_dialect->describeTableSql( <add> $name, <add> $this->_connection->config() <add> ); <add> $statement = $this->_connection->execute($sql, $params); <add> if (count($statement) == 0) { <add> return null; <add> } <add> <add> $columns = []; <add> $fieldParams = $this->_dialect->extraSchemaColumns(); <add> $rows = $statement->fetchAll('assoc'); <add> foreach ($rows as $row) { <add> $columns += $this->_dialect->convertFieldDescription($row, $fieldParams); <add> } <add> return new Table($name, $columns); <ide> } <ide> <ide> /** <ide><path>lib/Cake/Database/Schema/Table.php <ide> class Table { <ide> * Constructor. <ide> * <ide> * @param string $table The table name. <add> * @param array $columns The list of columns for the schema. <ide> */ <del> public function __construct($table) { <add> public function __construct($table, $columns = array()) { <ide> $this->_table = $table; <add> foreach ($columns as $field => $definition) { <add> $this->addColumn($field, $definition); <add> } <ide> } <ide> <ide> /** <ide><path>lib/Cake/Test/TestCase/Database/Schema/Dialect/MysqlTest.php <ide> public function testListTables() { <ide> * @return void <ide> */ <ide> public function testDescribeTable() { <del> $this->markTestIncomplete('Needs migration to new schema system'); <ide> $connection = new Connection(Configure::read('Datasource.test')); <ide> $this->_createTables($connection); <ide> <del> $result = $connection->describe('articles'); <add> $schema = new SchemaCollection($connection); <add> $result = $schema->describe('articles'); <add> $this->assertInstanceOf('Cake\Database\Schema\Table', $result); <ide> $expected = [ <ide> 'id' => [ <ide> 'type' => 'biginteger', <ide> 'null' => false, <ide> 'default' => null, <ide> 'length' => 20, <del> 'key' => 'primary', <add> 'fixed' => null, <add> 'comment' => null, <add> 'collate' => null, <add> 'charset' => null, <ide> ], <ide> 'title' => [ <ide> 'type' => 'string', <ide> public function testDescribeTable() { <ide> 'length' => 20, <ide> 'collate' => 'utf8_general_ci', <ide> 'comment' => 'A title', <add> 'fixed' => null, <add> 'charset' => null, <ide> ], <ide> 'body' => [ <ide> 'type' => 'text', <ide> 'null' => true, <ide> 'default' => null, <ide> 'length' => null, <ide> 'collate' => 'utf8_general_ci', <add> 'fixed' => null, <add> 'comment' => null, <add> 'charset' => null, <ide> ], <ide> 'author_id' => [ <ide> 'type' => 'integer', <ide> 'null' => false, <ide> 'default' => null, <ide> 'length' => 11, <add> 'fixed' => null, <add> 'comment' => null, <add> 'collate' => null, <add> 'charset' => null, <ide> ], <ide> 'published' => [ <ide> 'type' => 'boolean', <ide> 'null' => true, <ide> 'default' => 0, <ide> 'length' => null, <add> 'fixed' => null, <add> 'comment' => null, <add> 'collate' => null, <add> 'charset' => null, <ide> ], <ide> 'allow_comments' => [ <ide> 'type' => 'boolean', <ide> 'null' => true, <ide> 'default' => 0, <ide> 'length' => null, <add> 'fixed' => null, <add> 'comment' => null, <add> 'collate' => null, <add> 'charset' => null, <ide> ], <ide> 'created' => [ <ide> 'type' => 'datetime', <ide> 'null' => true, <ide> 'default' => null, <ide> 'length' => null, <add> 'fixed' => null, <add> 'comment' => null, <add> 'collate' => null, <add> 'charset' => null, <ide> ], <ide> ]; <del> $this->assertEquals($expected, $result); <add> foreach ($expected as $field => $definition) { <add> $this->assertEquals($definition, $result->column($field)); <add> } <ide> } <ide> <ide> } <ide><path>lib/Cake/Test/TestCase/Database/Schema/TableTest.php <ide> */ <ide> class TableTest extends TestCase { <ide> <add>/** <add> * Test construction with columns <add> * <add> * @return void <add> */ <add> public function testConstructWithColumns() { <add> $columns = [ <add> 'id' => [ <add> 'type' => 'integer', <add> 'length' => 11, <add> ], <add> 'title' => [ <add> 'type' => 'string', <add> 'length' => 255 <add> ] <add> ]; <add> $table = new Table('articles', $columns); <add> $this->assertEquals(['id', 'title'], $table->columns()); <add> } <add> <ide> /** <ide> * Test adding columns. <ide> *
5
Text
Text
fix subtitle of schemas for filtering
4632b5daaed5a71a1be3e7d412a7f9a2e5520b90
<ide><path>docs/api-guide/filtering.md <ide> Generic filters may also present an interface in the browsable API. To do so you <ide> <ide> The method should return a rendered HTML string. <ide> <del>## Pagination & schemas <add>## Filtering & schemas <ide> <ide> You can also make the filter controls available to the schema autogeneration <ide> that REST framework provides, by implementing a `get_schema_fields()` method. This method should have the following signature:
1
Text
Text
change video url for clockwise-notation challenge
9e4583b1f36a4ecaabc48b51e1445bb992692676
<ide><path>curriculum/challenges/english/01-responsive-web-design/basic-css/use-clockwise-notation-to-specify-the-margin-of-an-element.english.md <ide> id: bad87fee1348bd9afdf08726 <ide> title: Use Clockwise Notation to Specify the Margin of an Element <ide> challengeType: 0 <del>videoUrl: 'https://scrimba.com/c/cB7mBS9' <add>videoUrl: 'https://scrimba.com/c/cnpybAd' <ide> --- <ide> <ide> ## Description
1
Text
Text
specify file names using standard format
14867705e90b2b5f7e84dc7385d4ffba0c82b3e1
<ide><path>docs/tutorial/4-authentication-and-permissions.md <ide> Then, add the following property to **both** the `SnippetList` and `SnippetDetai <ide> <ide> If you open a browser and navigate to the browsable API at the moment, you'll find that you're no longer able to create new code snippets. In order to do so we'd need to be able to login as a user. <ide> <del>We can add a login view for use with the browsable API, by editing the URLconf in our project-level urls.py file. <add>We can add a login view for use with the browsable API, by editing the URLconf in our project-level `urls.py` file. <ide> <ide> Add the following import at the top of the file: <ide> <ide><path>docs/tutorial/5-relationships-and-hyperlinked-apis.md <ide> At the moment relationships within our API are represented by using primary keys <ide> <ide> ## Creating an endpoint for the root of our API <ide> <del>Right now we have endpoints for 'snippets' and 'users', but we don't have a single entry point to our API. To create one, we'll use a regular function-based view and the `@api_view` decorator we introduced earlier. <add>Right now we have endpoints for 'snippets' and 'users', but we don't have a single entry point to our API. To create one, we'll use a regular function-based view and the `@api_view` decorator we introduced earlier. In your `snippets/views.py` add: <ide> <ide> from rest_framework import renderers <ide> from rest_framework.decorators import api_view <ide> Unlike all our other API endpoints, we don't want to use JSON, but instead just <ide> <ide> The other thing we need to consider when creating the code highlight view is that there's no existing concrete generic view that we can use. We're not returning an object instance, but instead a property of an object instance. <ide> <del>Instead of using a concrete generic view, we'll use the base class for representing instances, and create our own `.get()` method. In your `snippets.views` add: <add>Instead of using a concrete generic view, we'll use the base class for representing instances, and create our own `.get()` method. In your `snippets/views.py` add: <ide> <ide> from rest_framework import renderers <ide> from rest_framework.response import Response <ide> Instead of using a concrete generic view, we'll use the base class for represent <ide> return Response(snippet.highlighted) <ide> <ide> As usual we need to add the new views that we've created in to our URLconf. <del>We'll add a url pattern for our new API root: <add>We'll add a url pattern for our new API root in `snippets/urls.py`: <ide> <ide> url(r'^$', 'api_root'), <ide> <ide> The `HyperlinkedModelSerializer` has the following differences from `ModelSerial <ide> * Relationships use `HyperlinkedRelatedField`, <ide> instead of `PrimaryKeyRelatedField`. <ide> <del>We can easily re-write our existing serializers to use hyperlinking. <add>We can easily re-write our existing serializers to use hyperlinking. In your `snippets/serializers.py` add: <ide> <ide> class SnippetSerializer(serializers.HyperlinkedModelSerializer): <ide> owner = serializers.Field(source='owner.username') <ide> If we're going to have a hyperlinked API, we need to make sure we name our URL p <ide> * Our user serializer includes a field that refers to `'snippet-detail'`. <ide> * Our snippet and user serializers include `'url'` fields that by default will refer to `'{model_name}-detail'`, which in this case will be `'snippet-detail'` and `'user-detail'`. <ide> <del>After adding all those names into our URLconf, our final `'urls.py'` file should look something like this: <add>After adding all those names into our URLconf, our final `snippets/urls.py` file should look something like this: <ide> <ide> # API endpoints <ide> urlpatterns = format_suffix_patterns(patterns('snippets.views',
2
Go
Go
add json utils for testing
e5e8669c7289959a2634bd3f66f89eef1bd4ef01
<ide><path>integration-cli/docker_utils.go <ide> func inspectField(name, field string) (string, error) { <ide> return strings.TrimSpace(out), nil <ide> } <ide> <add>func inspectFieldJSON(name, field string) (string, error) { <add> format := fmt.Sprintf("{{json .%s}}", field) <add> inspectCmd := exec.Command(dockerBinary, "inspect", "-f", format, name) <add> out, exitCode, err := runCommandWithOutput(inspectCmd) <add> if err != nil || exitCode != 0 { <add> return "", fmt.Errorf("failed to inspect %s: %s", name, out) <add> } <add> return strings.TrimSpace(out), nil <add>} <add> <ide> func getIDByName(name string) (string, error) { <ide> return inspectField(name, "Id") <ide> } <ide><path>integration-cli/utils.go <ide> package main <ide> <ide> import ( <ide> "bytes" <add> "encoding/json" <ide> "fmt" <ide> "io" <ide> "os/exec" <add> "reflect" <ide> "strings" <ide> "syscall" <ide> "testing" <ide> func errorOutOnNonNilError(err error, t *testing.T, message string) { <ide> func nLines(s string) int { <ide> return strings.Count(s, "\n") <ide> } <add> <add>func unmarshalJSON(data []byte, result interface{}) error { <add> err := json.Unmarshal(data, result) <add> if err != nil { <add> return err <add> } <add> <add> return nil <add>} <add> <add>func deepEqual(expected interface{}, result interface{}) bool { <add> return reflect.DeepEqual(result, expected) <add>} <add> <add>func convertSliceOfStringsToMap(input []string) map[string]struct{} { <add> output := make(map[string]struct{}) <add> for _, v := range input { <add> output[v] = struct{}{} <add> } <add> return output <add>}
2
Javascript
Javascript
refactor the code in test-dns-ipv4
4d3b487b791606ea965f6280ce0eeea03d79b660
<ide><path>test/internet/test-dns-ipv4.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> const assert = require('assert'); <ide> const dns = require('dns'); <ide> const net = require('net'); <ide> const isIPv4 = net.isIPv4; <ide> <del>let expected = 0; <del>let completed = 0; <ide> let running = false; <ide> const queue = []; <ide> <ide> function TEST(f) { <ide> function next() { <del> var f = queue.shift(); <add> const f = queue.shift(); <ide> if (f) { <ide> running = true; <ide> console.log(f.name); <ide> function TEST(f) { <ide> <ide> function done() { <ide> running = false; <del> completed++; <ide> process.nextTick(next); <ide> } <ide> <del> expected++; <ide> queue.push(f); <ide> <ide> if (!running) { <ide> function checkWrap(req) { <ide> } <ide> <ide> TEST(function test_resolve4(done) { <del> var req = dns.resolve4('www.google.com', function(err, ips) { <del> if (err) throw err; <add> const req = dns.resolve4('www.google.com', <add> common.mustCall((err, ips) => { <add> assert.ifError(err); <ide> <del> assert.ok(ips.length > 0); <add> assert.ok(ips.length > 0); <ide> <del> for (var i = 0; i < ips.length; i++) { <del> assert.ok(isIPv4(ips[i])); <del> } <add> for (let i = 0; i < ips.length; i++) { <add> assert.ok(isIPv4(ips[i])); <add> } <ide> <del> done(); <del> }); <add> done(); <add> })); <ide> <ide> checkWrap(req); <ide> }); <ide> <ide> TEST(function test_reverse_ipv4(done) { <del> var req = dns.reverse('8.8.8.8', function(err, domains) { <del> if (err) throw err; <add> const req = dns.reverse('8.8.8.8', <add> common.mustCall((err, domains) => { <add> assert.ifError(err); <ide> <del> assert.ok(domains.length > 0); <add> assert.ok(domains.length > 0); <ide> <del> for (var i = 0; i < domains.length; i++) { <del> assert.ok(domains[i]); <del> assert.ok(typeof domains[i] === 'string'); <del> } <add> for (let i = 0; i < domains.length; i++) { <add> assert.ok(domains[i]); <add> assert.ok(typeof domains[i] === 'string'); <add> } <ide> <del> done(); <del> }); <add> done(); <add> })); <ide> <ide> checkWrap(req); <ide> }); <ide> <ide> TEST(function test_lookup_ipv4_explicit(done) { <del> var req = dns.lookup('www.google.com', 4, function(err, ip, family) { <del> if (err) throw err; <del> assert.ok(net.isIPv4(ip)); <del> assert.strictEqual(family, 4); <add> const req = dns.lookup('www.google.com', 4, <add> common.mustCall((err, ip, family) => { <add> assert.ifError(err); <add> assert.ok(net.isIPv4(ip)); <add> assert.strictEqual(family, 4); <ide> <del> done(); <del> }); <add> done(); <add> })); <ide> <ide> checkWrap(req); <ide> }); <ide> <ide> TEST(function test_lookup_ipv4_implicit(done) { <del> var req = dns.lookup('www.google.com', function(err, ip, family) { <del> if (err) throw err; <del> assert.ok(net.isIPv4(ip)); <del> assert.strictEqual(family, 4); <add> const req = dns.lookup('www.google.com', <add> common.mustCall((err, ip, family) => { <add> assert.ifError(err); <add> assert.ok(net.isIPv4(ip)); <add> assert.strictEqual(family, 4); <ide> <del> done(); <del> }); <add> done(); <add> })); <ide> <ide> checkWrap(req); <ide> }); <ide> <ide> TEST(function test_lookup_ipv4_explicit_object(done) { <del> var req = dns.lookup('www.google.com', { <add> const req = dns.lookup('www.google.com', { <ide> family: 4 <del> }, function(err, ip, family) { <del> if (err) throw err; <add> }, common.mustCall((err, ip, family) => { <add> assert.ifError(err); <ide> assert.ok(net.isIPv4(ip)); <ide> assert.strictEqual(family, 4); <ide> <ide> done(); <del> }); <add> })); <ide> <ide> checkWrap(req); <ide> }); <ide> <ide> TEST(function test_lookup_ipv4_hint_addrconfig(done) { <del> var req = dns.lookup('www.google.com', { <add> const req = dns.lookup('www.google.com', { <ide> hints: dns.ADDRCONFIG <del> }, function(err, ip, family) { <del> if (err) throw err; <add> }, common.mustCall((err, ip, family) => { <add> assert.ifError(err); <ide> assert.ok(net.isIPv4(ip)); <ide> assert.strictEqual(family, 4); <ide> <ide> done(); <del> }); <add> })); <ide> <ide> checkWrap(req); <ide> }); <ide> <ide> TEST(function test_lookup_ip_ipv4(done) { <del> var req = dns.lookup('127.0.0.1', function(err, ip, family) { <del> if (err) throw err; <del> assert.strictEqual(ip, '127.0.0.1'); <del> assert.strictEqual(family, 4); <add> const req = dns.lookup('127.0.0.1', <add> common.mustCall((err, ip, family) => { <add> assert.ifError(err); <add> assert.strictEqual(ip, '127.0.0.1'); <add> assert.strictEqual(family, 4); <ide> <del> done(); <del> }); <add> done(); <add> })); <ide> <ide> checkWrap(req); <ide> }); <ide> <ide> TEST(function test_lookup_localhost_ipv4(done) { <del> var req = dns.lookup('localhost', 4, function(err, ip, family) { <del> if (err) throw err; <del> assert.strictEqual(ip, '127.0.0.1'); <del> assert.strictEqual(family, 4); <add> const req = dns.lookup('localhost', 4, <add> common.mustCall((err, ip, family) => { <add> assert.ifError(err); <add> assert.strictEqual(ip, '127.0.0.1'); <add> assert.strictEqual(family, 4); <ide> <del> done(); <del> }); <add> done(); <add> })); <ide> <ide> checkWrap(req); <ide> }); <ide> <ide> TEST(function test_lookup_all_ipv4(done) { <del> var req = dns.lookup( <add> const req = dns.lookup( <ide> 'www.google.com', <ide> {all: true, family: 4}, <del> function(err, ips) { <del> if (err) throw err; <add> common.mustCall((err, ips) => { <add> assert.ifError(err); <ide> assert.ok(Array.isArray(ips)); <ide> assert.ok(ips.length > 0); <ide> <del> ips.forEach(function(ip) { <add> ips.forEach((ip) => { <ide> assert.ok(isIPv4(ip.address)); <ide> assert.strictEqual(ip.family, 4); <ide> }); <ide> <ide> done(); <ide> } <del> ); <add> )); <ide> <ide> checkWrap(req); <ide> }); <ide> <ide> TEST(function test_lookupservice_ip_ipv4(done) { <del> var req = dns.lookupService('127.0.0.1', 80, function(err, host, service) { <del> if (err) throw err; <del> assert.equal(typeof host, 'string'); <del> assert(host); <del> assert(['http', 'www', '80'].includes(service)); <del> done(); <del> }); <add> const req = dns.lookupService('127.0.0.1', 80, <add> common.mustCall((err, host, service) => { <add> assert.ifError(err); <add> assert.strictEqual(typeof host, 'string'); <add> assert(host); <add> assert(['http', 'www', '80'].includes(service)); <add> done(); <add> })); <ide> <ide> checkWrap(req); <ide> }); <del> <del>process.on('exit', function() { <del> console.log(completed + ' tests completed'); <del> assert.equal(running, false); <del> assert.strictEqual(expected, completed); <del>});
1
Python
Python
fix typo in cli error
c2266aac489b126638b3403b7a1ff0d2a9368056
<ide><path>airflow/cli/commands/dag_command.py <ide> def set_is_paused(is_paused, args): <ide> dag = DagModel.get_dagmodel(args.dag_id) <ide> <ide> if not dag: <del> raise SystemExit(f"DAG: {args.dag_id} does not exit in 'dag' table") <add> raise SystemExit(f"DAG: {args.dag_id} does not exist in 'dag' table") <ide> <ide> dag.set_is_paused(is_paused=is_paused) <ide>
1
Mixed
Ruby
update instructions for os x < 10.9
81e2fbd032886a50a9550a49288e73c547b137ec
<ide><path>Library/Homebrew/extend/os/mac/diagnostic.rb <ide> def check_for_unsupported_macos <ide> You are using macOS #{MacOS.version}. <ide> #{who} do not provide support for this #{what}. <ide> You will encounter build failures and other breakages. <del> Please create pull-requests instead of asking for help on Homebrew's <add> Please create pull requests instead of asking for help on Homebrew's <ide> GitHub, Discourse, Twitter or IRC. As you are running this #{what}, <ide> you are responsible for resolving any issues you experience. <ide> EOS <ide><path>docs/Installation.md <ide> it does it too. And you have to confirm everything it will do before it starts. <ide> <ide> ## Alternative Installs <ide> <del>### OS X Lion 10.7 and below <add>### OS X Mountain Lion (10.8) and below <add>Because GitHub now only allows clients that support TLS 1.2 to access repositories over HTTPS, the Homebrew installer will use the GIT protocol when run on systems older than OS X Mavericks (10.9). This requires the availability of a `git` binary, which can be provided by pre-installing the [Command Line Tools or Xcode](https://developer.apple.com/download/more/) on Lion or Mountain Lion, or a [prepackaged installer](https://code.google.com/archive/p/git-osx-installer/downloads) on Leopard or Snow Leopard. Homebrew will also require the Command Line Tools or Xcode in order to automatically compile and install a newer `curl` and `git` with support for TLS 1.2. <ide> <del>Using the instructions on https://brew.sh or below whenever you call `curl` you must pass `--insecure` as an argument. This is because your system `curl` is too old to speak to GitHub using HTTPS. Don't worry, on the first `brew update` Homebrew will install a newer, more secure `curl` for your machine. <add>Also note that when installing on OS X Leopard (10.5), you need to bypass its outdated built-in certificates by adding `--insecure` to the [installation command](https://brew.sh/#install)'s list of `curl` flags. <ide> <ide> ### Untar anywhere <ide> Just extract (or `git clone`) Homebrew wherever you want. Just avoid:
2
Text
Text
update codepen url in bug template
77cdadb1dcb8296e43751ed2d1ea999d26ba3149
<ide><path>.github/ISSUE_TEMPLATE/BUG.md <ide> labels: 'type: bug' <ide> Head to https://stackoverflow.com/questions/tagged/chart.js <ide> <ide> Bug reports MUST be submitted with an interactive example: <del> https://codepen.io/pen?template=JXVYzq <add> https://codepen.io/pen?template=BapRepQ <ide> <ide> Chart.js versions lower then 3.x are NOT supported anymore, new issues will be disregarded. <ide> --> <ide> labels: 'type: bug' <ide> ## Steps to Reproduce <ide> <!-- <ide> Provide a link to a live example. Bug reports MUST be submitted with an <del> interactive example (https://codepen.io/pen?template=JXVYzq). <add> interactive example (https://codepen.io/pen/?template=BapRepQ). <ide> <ide> If filing a bug against `master`, you may reference the latest code via <ide> https://www.chartjs.org/dist/master/chart.min.js (changing the filename to
1
Text
Text
swap example pr title
e59d58edf1f8b691d18377be13a410b6c5943384
<ide><path>docs/how-to-open-a-pull-request.md <ide> Some examples of good PR titles would be: <ide> - `fix(a11y): improved search bar contrast` <ide> - `feat: add more tests to HTML and CSS challenges` <ide> - `fix(api,client): prevent CORS errors on form submission` <del>- `docs(i18n): Chinese translation of local setup` <add>- `docs(i18n): fix links to be relative instead of absolute` <ide> <ide> ## Proposing a Pull Request <ide>
1