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 line 11 ifconfig | c8d4aefd030fd678b7841cd77188be46d0ed0bd7 | <ide><path>guide/english/linux/10-simple-and-useful-linux-commands/index.md
<ide> more command allows quickly view file and shows details in percentage. You can p
<ide> 10. `cp` Command
<ide> Copy file from source to destination preserving same mode.
<ide>
<del>11. `systemctl` Command
<add>11. `ifconfig` to view ip and other information.
<ide>
<del>This is a command which allows operators to work with the Linux system services. The standard use of the command is `systemctl <OPTION> <SERVICE-NAME>` by providing an `OPTION` (e.g. `start`, `stop`, `status`) and than providing a specific Service Name to act on. You can use the command to get a general status of your Linux services (e.g `systemctl status`). Note that you will either need Administrator access or use `sudo` to elevate your rights to run the command successfully.
<add>12. `systemctl` Command
<add> This is a command which allows operators to work with the Linux system services. The standard use of the command is `systemctl <OPTION> <SERVICE-NAME>` by providing an `OPTION` (e.g. `start`, `stop`, `status`) and than providing a specific Service Name to act on. You can use the command to get a general status of your Linux services (e.g `systemctl status`). Note that you will either need Administrator access or use `sudo` to elevate your rights to run the command successfully.
<add> | 1 |
Go | Go | fix error string about containers feature | 31405b556f155d8f56902086c7c24efe25dd8de0 | <ide><path>daemon/daemon_windows.go
<ide> func checkSystem() error {
<ide>
<ide> vmcompute := windows.NewLazySystemDLL("vmcompute.dll")
<ide> if vmcompute.Load() != nil {
<del> return fmt.Errorf("Failed to load vmcompute.dll. Ensure that the Containers role is installed.")
<add> return fmt.Errorf("failed to load vmcompute.dll, ensure that the Containers feature is installed")
<ide> }
<ide>
<ide> return nil | 1 |
Javascript | Javascript | move config handling to a dedicated script | 6dbb7e74462d5b7dedf2124a622a3e678964dd83 | <ide><path>src/core/core.config.js
<add>/* eslint-disable import/no-namespace, import/namespace */
<add>import defaults from './core.defaults';
<add>import {mergeIf, merge, _merger} from '../helpers/helpers.core';
<add>
<add>export function getIndexAxis(type, options) {
<add> const typeDefaults = defaults[type] || {};
<add> const datasetDefaults = typeDefaults.datasets || {};
<add> const typeOptions = options[type] || {};
<add> const datasetOptions = typeOptions.datasets || {};
<add> return datasetOptions.indexAxis || options.indexAxis || datasetDefaults.indexAxis || 'x';
<add>}
<add>
<add>function getAxisFromDefaultScaleID(id, indexAxis) {
<add> let axis = id;
<add> if (id === '_index_') {
<add> axis = indexAxis;
<add> } else if (id === '_value_') {
<add> axis = indexAxis === 'x' ? 'y' : 'x';
<add> }
<add> return axis;
<add>}
<add>
<add>function getDefaultScaleIDFromAxis(axis, indexAxis) {
<add> return axis === indexAxis ? '_index_' : '_value_';
<add>}
<add>
<add>function axisFromPosition(position) {
<add> if (position === 'top' || position === 'bottom') {
<add> return 'x';
<add> }
<add> if (position === 'left' || position === 'right') {
<add> return 'y';
<add> }
<add>}
<add>
<add>export function determineAxis(id, scaleOptions) {
<add> if (id === 'x' || id === 'y' || id === 'r') {
<add> return id;
<add> }
<add> return scaleOptions.axis || axisFromPosition(scaleOptions.position) || id.charAt(0).toLowerCase();
<add>}
<add>
<add>function mergeScaleConfig(config, options) {
<add> options = options || {};
<add> const chartDefaults = defaults[config.type] || {scales: {}};
<add> const configScales = options.scales || {};
<add> const chartIndexAxis = getIndexAxis(config.type, options);
<add> const firstIDs = Object.create(null);
<add> const scales = Object.create(null);
<add>
<add> // First figure out first scale id's per axis.
<add> Object.keys(configScales).forEach(id => {
<add> const scaleConf = configScales[id];
<add> const axis = determineAxis(id, scaleConf);
<add> const defaultId = getDefaultScaleIDFromAxis(axis, chartIndexAxis);
<add> firstIDs[axis] = firstIDs[axis] || id;
<add> scales[id] = mergeIf(Object.create(null), [{axis}, scaleConf, chartDefaults.scales[axis], chartDefaults.scales[defaultId]]);
<add> });
<add>
<add> // Backward compatibility
<add> if (options.scale) {
<add> scales[options.scale.id || 'r'] = mergeIf(Object.create(null), [{axis: 'r'}, options.scale, chartDefaults.scales.r]);
<add> firstIDs.r = firstIDs.r || options.scale.id || 'r';
<add> }
<add>
<add> // Then merge dataset defaults to scale configs
<add> config.data.datasets.forEach(dataset => {
<add> const type = dataset.type || config.type;
<add> const indexAxis = dataset.indexAxis || getIndexAxis(type, options);
<add> const datasetDefaults = defaults[type] || {};
<add> const defaultScaleOptions = datasetDefaults.scales || {};
<add> Object.keys(defaultScaleOptions).forEach(defaultID => {
<add> const axis = getAxisFromDefaultScaleID(defaultID, indexAxis);
<add> const id = dataset[axis + 'AxisID'] || firstIDs[axis] || axis;
<add> scales[id] = scales[id] || Object.create(null);
<add> mergeIf(scales[id], [{axis}, configScales[id], defaultScaleOptions[defaultID]]);
<add> });
<add> });
<add>
<add> // apply scale defaults, if not overridden by dataset defaults
<add> Object.keys(scales).forEach(key => {
<add> const scale = scales[key];
<add> mergeIf(scale, [defaults.scales[scale.type], defaults.scale]);
<add> });
<add>
<add> return scales;
<add>}
<add>
<add>/**
<add> * Recursively merge the given config objects as the root options by handling
<add> * default scale options for the `scales` and `scale` properties, then returns
<add> * a deep copy of the result, thus doesn't alter inputs.
<add> */
<add>function mergeConfig(...args/* config objects ... */) {
<add> return merge(Object.create(null), args, {
<add> merger(key, target, source, options) {
<add> if (key !== 'scales' && key !== 'scale') {
<add> _merger(key, target, source, options);
<add> }
<add> }
<add> });
<add>}
<add>
<add>function includeDefaults(options, type) {
<add> return mergeConfig(
<add> defaults,
<add> defaults[type],
<add> options || {});
<add>}
<add>
<add>function initConfig(config) {
<add> config = config || {};
<add>
<add> // Do NOT use mergeConfig for the data object because this method merges arrays
<add> // and so would change references to labels and datasets, preventing data updates.
<add> const data = config.data = config.data || {datasets: [], labels: []};
<add> data.datasets = data.datasets || [];
<add> data.labels = data.labels || [];
<add>
<add> const scaleConfig = mergeScaleConfig(config, config.options);
<add>
<add> const options = config.options = includeDefaults(config.options, config.type);
<add>
<add> options.hover = merge(Object.create(null), [
<add> defaults.interaction,
<add> defaults.hover,
<add> options.interaction,
<add> options.hover
<add> ]);
<add>
<add> options.scales = scaleConfig;
<add>
<add> options.title = (options.title !== false) && merge(Object.create(null), [
<add> defaults.plugins.title,
<add> options.title
<add> ]);
<add> options.tooltips = (options.tooltips !== false) && merge(Object.create(null), [
<add> defaults.interaction,
<add> defaults.plugins.tooltip,
<add> options.interaction,
<add> options.tooltips
<add> ]);
<add>
<add> return config;
<add>}
<add>
<add>export default class Config {
<add> constructor(config) {
<add> this._config = initConfig(config);
<add> }
<add>
<add> get type() {
<add> return this._config.type;
<add> }
<add>
<add> get data() {
<add> return this._config.data;
<add> }
<add>
<add> set data(data) {
<add> this._config.data = data;
<add> }
<add>
<add> get options() {
<add> return this._config.options;
<add> }
<add>
<add> get plugins() {
<add> return this._config.plugins;
<add> }
<add>
<add> update(options) {
<add> const config = this._config;
<add> const scaleConfig = mergeScaleConfig(config, options);
<add>
<add> options = includeDefaults(options, config.type);
<add>
<add> options.scales = scaleConfig;
<add> config.options = options;
<add> }
<add>}
<ide><path>src/core/core.controller.js
<ide> import layouts from './core.layouts';
<ide> import {BasicPlatform, DomPlatform} from '../platform';
<ide> import PluginService from './core.plugins';
<ide> import registry from './core.registry';
<add>import Config, {determineAxis, getIndexAxis} from './core.config';
<ide> import {retinaScale} from '../helpers/helpers.dom';
<del>import {mergeIf, merge, _merger, each, callback as callCallback, uid, valueOrDefault, _elementsEqual} from '../helpers/helpers.core';
<add>import {each, callback as callCallback, uid, valueOrDefault, _elementsEqual} from '../helpers/helpers.core';
<ide> import {clear as canvasClear, clipArea, unclipArea, _isPointInArea} from '../helpers/helpers.canvas';
<ide> // @ts-ignore
<ide> import {version} from '../../package.json';
<ide> import {version} from '../../package.json';
<ide> * @typedef { import("../platform/platform.base").IEvent } IEvent
<ide> */
<ide>
<del>
<del>function getIndexAxis(type, options) {
<del> const typeDefaults = defaults[type] || {};
<del> const datasetDefaults = typeDefaults.datasets || {};
<del> const typeOptions = options[type] || {};
<del> const datasetOptions = typeOptions.datasets || {};
<del> return datasetOptions.indexAxis || options.indexAxis || datasetDefaults.indexAxis || 'x';
<del>}
<del>
<del>function getAxisFromDefaultScaleID(id, indexAxis) {
<del> let axis = id;
<del> if (id === '_index_') {
<del> axis = indexAxis;
<del> } else if (id === '_value_') {
<del> axis = indexAxis === 'x' ? 'y' : 'x';
<del> }
<del> return axis;
<del>}
<del>
<del>function getDefaultScaleIDFromAxis(axis, indexAxis) {
<del> return axis === indexAxis ? '_index_' : '_value_';
<del>}
<del>
<del>function mergeScaleConfig(config, options) {
<del> options = options || {};
<del> const chartDefaults = defaults[config.type] || {scales: {}};
<del> const configScales = options.scales || {};
<del> const chartIndexAxis = getIndexAxis(config.type, options);
<del> const firstIDs = Object.create(null);
<del> const scales = Object.create(null);
<del>
<del> // First figure out first scale id's per axis.
<del> Object.keys(configScales).forEach(id => {
<del> const scaleConf = configScales[id];
<del> const axis = determineAxis(id, scaleConf);
<del> const defaultId = getDefaultScaleIDFromAxis(axis, chartIndexAxis);
<del> firstIDs[axis] = firstIDs[axis] || id;
<del> scales[id] = mergeIf(Object.create(null), [{axis}, scaleConf, chartDefaults.scales[axis], chartDefaults.scales[defaultId]]);
<del> });
<del>
<del> // Backward compatibility
<del> if (options.scale) {
<del> scales[options.scale.id || 'r'] = mergeIf(Object.create(null), [{axis: 'r'}, options.scale, chartDefaults.scales.r]);
<del> firstIDs.r = firstIDs.r || options.scale.id || 'r';
<del> }
<del>
<del> // Then merge dataset defaults to scale configs
<del> config.data.datasets.forEach(dataset => {
<del> const type = dataset.type || config.type;
<del> const indexAxis = dataset.indexAxis || getIndexAxis(type, options);
<del> const datasetDefaults = defaults[type] || {};
<del> const defaultScaleOptions = datasetDefaults.scales || {};
<del> Object.keys(defaultScaleOptions).forEach(defaultID => {
<del> const axis = getAxisFromDefaultScaleID(defaultID, indexAxis);
<del> const id = dataset[axis + 'AxisID'] || firstIDs[axis] || axis;
<del> scales[id] = scales[id] || Object.create(null);
<del> mergeIf(scales[id], [{axis}, configScales[id], defaultScaleOptions[defaultID]]);
<del> });
<del> });
<del>
<del> // apply scale defaults, if not overridden by dataset defaults
<del> Object.keys(scales).forEach(key => {
<del> const scale = scales[key];
<del> mergeIf(scale, [defaults.scales[scale.type], defaults.scale]);
<del> });
<del>
<del> return scales;
<del>}
<del>
<del>/**
<del> * Recursively merge the given config objects as the root options by handling
<del> * default scale options for the `scales` and `scale` properties, then returns
<del> * a deep copy of the result, thus doesn't alter inputs.
<del> */
<del>function mergeConfig(...args/* config objects ... */) {
<del> return merge(Object.create(null), args, {
<del> merger(key, target, source, options) {
<del> if (key !== 'scales' && key !== 'scale') {
<del> _merger(key, target, source, options);
<del> }
<del> }
<del> });
<del>}
<del>
<del>function initConfig(config) {
<del> config = config || {};
<del>
<del> // Do NOT use mergeConfig for the data object because this method merges arrays
<del> // and so would change references to labels and datasets, preventing data updates.
<del> const data = config.data = config.data || {datasets: [], labels: []};
<del> data.datasets = data.datasets || [];
<del> data.labels = data.labels || [];
<del>
<del> const scaleConfig = mergeScaleConfig(config, config.options);
<del>
<del> const options = config.options = mergeConfig(
<del> defaults,
<del> defaults[config.type],
<del> config.options || {});
<del>
<del> options.hover = merge(Object.create(null), [
<del> defaults.interaction,
<del> defaults.hover,
<del> options.interaction,
<del> options.hover
<del> ]);
<del>
<del> options.scales = scaleConfig;
<del>
<del> options.title = (options.title !== false) && merge(Object.create(null), [
<del> defaults.plugins.title,
<del> options.title
<del> ]);
<del> options.tooltips = (options.tooltips !== false) && merge(Object.create(null), [
<del> defaults.interaction,
<del> defaults.plugins.tooltip,
<del> options.interaction,
<del> options.tooltips
<del> ]);
<del>
<del> return config;
<del>}
<del>
<del>function isAnimationDisabled(config) {
<del> return !config.animation;
<del>}
<del>
<del>function updateConfig(chart) {
<del> let newOptions = chart.options;
<del>
<del> each(chart.scales, (scale) => {
<del> layouts.removeBox(chart, scale);
<del> });
<del>
<del> const scaleConfig = mergeScaleConfig(chart.config, newOptions);
<del>
<del> newOptions = mergeConfig(
<del> defaults,
<del> defaults[chart.config.type],
<del> newOptions);
<del>
<del> chart.options = chart.config.options = newOptions;
<del> chart.options.scales = scaleConfig;
<del>
<del> chart._animationsDisabled = isAnimationDisabled(newOptions);
<del>}
<del>
<ide> const KNOWN_POSITIONS = ['top', 'bottom', 'left', 'right', 'chartArea'];
<ide> function positionIsHorizontal(position, axis) {
<ide> return position === 'top' || position === 'bottom' || (KNOWN_POSITIONS.indexOf(position) === -1 && axis === 'x');
<ide> }
<ide>
<del>function axisFromPosition(position) {
<del> if (position === 'top' || position === 'bottom') {
<del> return 'x';
<del> }
<del> if (position === 'left' || position === 'right') {
<del> return 'y';
<del> }
<del>}
<del>
<del>function determineAxis(id, scaleOptions) {
<del> if (id === 'x' || id === 'y' || id === 'r') {
<del> return id;
<del> }
<del> return scaleOptions.axis || axisFromPosition(scaleOptions.position) || id.charAt(0).toLowerCase();
<del>}
<del>
<ide> function compare2Level(l1, l2) {
<ide> return function(a, b) {
<ide> return a[l1] === b[l1]
<ide> class Chart {
<ide> constructor(item, config) {
<ide> const me = this;
<ide>
<del> config = initConfig(config);
<add> this.config = config = new Config(config);
<ide> const initialCanvas = getCanvas(item);
<ide> const existingChart = Chart.getChart(initialCanvas);
<ide> if (existingChart) {
<ide> class Chart {
<ide> this.id = uid();
<ide> this.ctx = context;
<ide> this.canvas = canvas;
<del> this.config = config;
<ide> this.width = width;
<ide> this.height = height;
<ide> this.aspectRatio = height ? width / height : null;
<ide> class Chart {
<ide> this.boxes = [];
<ide> this.currentDevicePixelRatio = undefined;
<ide> this.chartArea = undefined;
<del> this.data = undefined;
<ide> this._active = [];
<ide> this._lastEvent = undefined;
<ide> /** @type {{attach?: function, detach?: function, resize?: function}} */
<ide> class Chart {
<ide> this.$proxies = {};
<ide> this._hiddenIndices = {};
<ide> this.attached = false;
<add> this._animationsDisabled = undefined;
<ide>
<ide> // Add the chart instance to the global namespace
<ide> Chart.instances[me.id] = me;
<ide>
<del> // Define alias to the config data: `chart.data === chart.config.data`
<del> Object.defineProperty(me, 'data', {
<del> get() {
<del> return me.config.data;
<del> },
<del> set(value) {
<del> me.config.data = value;
<del> }
<del> });
<del>
<ide> if (!context || !canvas) {
<ide> // The given item is not a compatible context2d element, let's return before finalizing
<ide> // the chart initialization but after setting basic chart / controller properties that
<ide> class Chart {
<ide> }
<ide> }
<ide>
<add> get data() {
<add> return this.config.data;
<add> }
<add>
<add> set data(data) {
<add> this.config.data = data;
<add> }
<add>
<ide> /**
<ide> * @private
<ide> */
<ide> class Chart {
<ide>
<ide> me._updating = true;
<ide>
<del> updateConfig(me);
<add> each(me.scales, (scale) => {
<add> layouts.removeBox(me, scale);
<add> });
<add>
<add> me.config.update(me.options);
<add> me.options = me.config.options;
<add> me._animationsDisabled = !me.options.animation;
<ide>
<ide> me.ensureScalesHaveIDs();
<ide> me.buildOrUpdateScales();
<ide><path>src/core/core.plugins.js
<ide> export default class PluginService {
<ide> return this._cache;
<ide> }
<ide>
<del> const config = (chart && chart.config) || {};
<add> const config = chart && chart.config;
<ide> const options = (config.options && config.options.plugins) || {};
<ide> const plugins = allPlugins(config);
<ide> const descriptors = createDescriptors(plugins, options);
<ide> export default class PluginService {
<ide> }
<ide> }
<ide>
<add>/**
<add> * @param {import("./core.config").default} config
<add> */
<ide> function allPlugins(config) {
<ide> const plugins = [];
<ide> const keys = Object.keys(registry.plugins.items); | 3 |
Javascript | Javascript | switch the argument order for the assertion | af3992b1caff074812579a792f28eef0256190b7 | <ide><path>test/parallel/test-next-tick-errors.js
<ide> process.on('uncaughtException', function(err, errorOrigin) {
<ide> });
<ide>
<ide> process.on('exit', function() {
<del> assert.deepStrictEqual(['A', 'B', 'C'], order);
<add> assert.deepStrictEqual(order, ['A', 'B', 'C']);
<ide> }); | 1 |
Python | Python | add comment on subclasses ordering | ac2e2f3cb3c2f6fb8424abc48a9509d32011360d | <ide><path>numpy/core/overrides.py
<ide> def get_overloaded_types_and_args(relevant_args):
<ide> overloaded_types.append(arg_type)
<ide>
<ide> if array_function is not ndarray.__array_function__:
<add> # By default, insert this argument at the end, but if it is
<add> # subclass of another argument, insert it before that argument.
<add> # This ensures "subclasses before superclasses".
<ide> index = len(overloaded_args)
<ide> for i, old_arg in enumerate(overloaded_args):
<ide> if issubclass(arg_type, type(old_arg)): | 1 |
Ruby | Ruby | fix code comment to reflect its intent | 783fc29389336e83341ea24e93a0b02b14c47a49 | <ide><path>actionpack/lib/action_controller/metal/responder.rb
<ide> module ActionController #:nodoc:
<ide> #
<ide> # def create
<ide> # @project = Project.find(params[:project_id])
<del> # @task = @project.comments.build(params[:task])
<add> # @task = @project.tasks.build(params[:task])
<ide> # flash[:notice] = 'Task was successfully created.' if @task.save
<ide> # respond_with(@project, @task, :status => 201)
<ide> # end | 1 |
PHP | PHP | remove deprecated code in collection package | 761b53190639b8d91709f7783d000b9178548da4 | <ide><path>src/Collection/CollectionTrait.php
<ide> public function unwrap()
<ide> return $iterator;
<ide> }
<ide>
<del> /**
<del> * Backwards compatible wrapper for unwrap()
<del> *
<del> * @return \Traversable
<del> * @deprecated 3.0.10 Will be removed in 4.0.0
<del> */
<del> // @codingStandardsIgnoreLine
<del> public function _unwrap()
<del> {
<del> deprecationWarning('CollectionTrait::_unwrap() is deprecated. Use CollectionTrait::unwrap() instead.');
<del>
<del> return $this->unwrap();
<del> }
<del>
<ide> /**
<ide> * {@inheritDoc}
<ide> * | 1 |
Javascript | Javascript | remove `require('buffer')` from 4 test files | 256d86a155d796d5194004fa05502cd68172d1c0 | <ide><path>test/parallel/test-buffer-fakes.js
<ide>
<ide> require('../common');
<ide> const assert = require('assert');
<del>const Buffer = require('buffer').Buffer;
<ide>
<ide> function FakeBuffer() { }
<ide> Object.setPrototypeOf(FakeBuffer, Buffer);
<ide><path>test/parallel/test-buffer-includes.js
<ide> const common = require('../common');
<ide> const assert = require('assert');
<ide>
<del>const Buffer = require('buffer').Buffer;
<del>
<ide> const b = Buffer.from('abcdef');
<ide> const buf_a = Buffer.from('a');
<ide> const buf_bc = Buffer.from('bc');
<ide><path>test/parallel/test-buffer-indexof.js
<ide> require('../common');
<ide> const assert = require('assert');
<ide>
<del>const Buffer = require('buffer').Buffer;
<del>
<ide> const b = Buffer.from('abcdef');
<ide> const buf_a = Buffer.from('a');
<ide> const buf_bc = Buffer.from('bc');
<ide><path>test/parallel/test-buffer-new.js
<ide>
<ide> require('../common');
<ide> const assert = require('assert');
<del>const Buffer = require('buffer').Buffer;
<ide>
<ide> assert.throws(() => new Buffer(42, 'utf8'), /first argument must be a string/); | 4 |
Ruby | Ruby | remove surplus period from assertion messages | 8c81c9c423c0b463637976d5f00df760e2e733e1 | <ide><path>actionpack/lib/action_dispatch/testing/assertions/selector.rb
<ide> def assert_select(*args, &block)
<ide> text.strip! unless NO_STRIP.include?(match.name)
<ide> text.sub!(/\A\n/, '') if match.name == "textarea"
<ide> unless match_with.is_a?(Regexp) ? (text =~ match_with) : (text == match_with.to_s)
<del> content_mismatch ||= sprintf("<%s> expected but was\n<%s>.", match_with, text)
<add> content_mismatch ||= sprintf("<%s> expected but was\n<%s>", match_with, text)
<ide> true
<ide> end
<ide> end
<ide> def assert_select(*args, &block)
<ide> html = match.children.map(&:to_s).join
<ide> html.strip! unless NO_STRIP.include?(match.name)
<ide> unless match_with.is_a?(Regexp) ? (html =~ match_with) : (html == match_with.to_s)
<del> content_mismatch ||= sprintf("<%s> expected but was\n<%s>.", match_with, html)
<add> content_mismatch ||= sprintf("<%s> expected but was\n<%s>", match_with, html)
<ide> true
<ide> end
<ide> end
<ide> def assert_select(*args, &block)
<ide>
<ide> # FIXME: minitest provides messaging when we use assert_operator,
<ide> # so is this custom message really needed?
<del> message = message || %(Expected #{count_description(min, max, count)} matching "#{selector.to_s}", found #{matches.size}.)
<add> message = message || %(Expected #{count_description(min, max, count)} matching "#{selector.to_s}", found #{matches.size})
<ide> if count
<ide> assert_equal count, matches.size, message
<ide> else | 1 |
Go | Go | fix minor typo | eee0cfa45dd75223dec204428dc85dccb2b5abe9 | <ide><path>volume/local/local.go
<ide> func (r *Root) validateName(name string) error {
<ide> return validationError{fmt.Errorf("volume name is too short, names should be at least two alphanumeric characters")}
<ide> }
<ide> if !volumeNameRegex.MatchString(name) {
<del> return validationError{fmt.Errorf("%q includes invalid characters for a local volume name, only %q are allowed. If you intented to pass a host directory, use absolute path", name, api.RestrictedNameChars)}
<add> return validationError{fmt.Errorf("%q includes invalid characters for a local volume name, only %q are allowed. If you intended to pass a host directory, use absolute path", name, api.RestrictedNameChars)}
<ide> }
<ide> return nil
<ide> } | 1 |
Text | Text | add @pborreli for #897 | d7bf02e09ea85778c0a3fad572ad33d637c0602f | <ide><path>docs/topics/credits.md
<ide> The following people have helped make REST framework great.
<ide> * Andrew Tarzwell - [atarzwell]
<ide> * Michal Dvořák - [mikee2185]
<ide> * Markus Törnqvist - [mjtorn]
<add>* Pascal Borreli - [pborreli]
<ide>
<ide> Many thanks to everyone who's contributed to the project.
<ide>
<ide> You can also contact [@_tomchristie][twitter] directly on twitter.
<ide> [atarzwell]: https://github.com/atarzwell
<ide> [mikee2185]: https://github.com/mikee2185
<ide> [mjtorn]: https://github.com/mjtorn
<add>[pborreli]: https://github.com/pborreli | 1 |
Python | Python | remove duplicate `alltrue` | 689f1439c95b5f4fb2a147b9ff6df81fd45c8cfa | <ide><path>numpy/core/fromnumeric.py
<ide> def alltrue (a, axis=None, out=None):
<ide> return any(axis, out)
<ide>
<ide>
<del>def alltrue (a, axis=None, out=None):
<del> """Check if all of the elements of `a` are true.
<del>
<del> Performs a logical_and over the given axis and returns the result
<del>
<del> Parameters
<del> ----------
<del> a : array_like
<del> axis : {None, integer}
<del> Axis to perform the operation over.
<del> If None, perform over flattened array.
<del> out : {None, array}, optional
<del> Array into which the product can be placed. Its type is preserved
<del> and it must be of the right shape to hold the output.
<del>
<del> See Also
<del> --------
<del> ndarray.all : equivalent method
<del>
<del> """
<del> try:
<del> all = a.all
<del> except AttributeError:
<del> return _wrapit(a, 'all', axis, out)
<del> return all(axis, out)
<del>
<del>
<ide> def any(a,axis=None, out=None):
<ide> """Check if any of the elements of `a` are true.
<ide> | 1 |
Text | Text | add link from `next/image` docs to example | 9fe18e88446303d390866531bf63e33677c61c1a | <ide><path>docs/api-reference/next/image.md
<ide> description: Enable Image Optimization with the built-in Image component.
<ide>
<ide> # next/image
<ide>
<add><details open>
<add> <summary><b>Examples</b></summary>
<add> <ul>
<add> <li><a href="https://github.com/vercel/next.js/tree/canary/examples/image-component">Image Component</a></li>
<add> </ul>
<add></details>
<add>
<ide> <details>
<ide> <summary><b>Version History</b></summary>
<ide>
<ide><path>docs/api-reference/next/legacy/image.md
<ide> description: Backwards compatible Image Optimization with the Legacy Image compo
<ide>
<ide> # next/legacy/image
<ide>
<del><details>
<add><details open>
<ide> <summary><b>Examples</b></summary>
<ide> <ul>
<ide> <li><a href="https://github.com/vercel/next.js/tree/canary/examples/image-legacy-component">Legacy Image Component</a></li> | 2 |
Text | Text | add v3.10.1 to changelog.md | 25fd4829145e454ffaae02151f5511bf13b49cfd | <ide><path>CHANGELOG.md
<ide> - [#17940](https://github.com/emberjs/ember.js/pull/17940) [CLEANUP] Remove `sync` queue from @ember/runloop.
<ide> - [#18026](https://github.com/emberjs/ember.js/pull/18026) Enabling featured discussed in 2019-05-03 core team meeting.
<ide>
<add>### v3.10.1 (June 4, 2019)
<add>
<add>- [#18071](https://github.com/emberjs/ember.js/pull/18071) [BUGFIX] Ensure modifiers do not run in FastBoot modes. (#18071)
<add>- [#18064](https://github.com/emberjs/ember.js/pull/18064) [BUGFIX] Fix 'hasAttribute is not a function' when jQuery is disabled (#18064)
<ide>
<ide> ### v3.10.0 (May 13, 2019)
<ide> | 1 |
Javascript | Javascript | choose defaults by target | efb2dd483f4d360cd19ed222688316624b8e0f35 | <ide><path>lib/WebpackOptionsApply.js
<ide> var ModuleAsDirectoryPlugin = require("enhanced-resolve/lib/ModuleAsDirectoryPlu
<ide> var ModuleAliasPlugin = require("enhanced-resolve/lib/ModuleAliasPlugin");
<ide> var DirectoryDefaultFilePlugin = require("enhanced-resolve/lib/DirectoryDefaultFilePlugin");
<ide> var DirectoryDescriptionFilePlugin = require("enhanced-resolve/lib/DirectoryDescriptionFilePlugin");
<add>var DirectoryDescriptionFileFieldAliasPlugin = require("enhanced-resolve/lib/DirectoryDescriptionFileFieldAliasPlugin");
<ide> var FileAppendPlugin = require("enhanced-resolve/lib/FileAppendPlugin");
<ide> var DirectoryResultPlugin = require("enhanced-resolve/lib/DirectoryResultPlugin");
<ide>
<ide><path>lib/WebpackOptionsDefaulter.js
<ide> function WebpackOptionsDefaulter() {
<ide> this.set("resolve.fastUnsafe", []);
<ide> this.set("resolveLoader.fastUnsafe", []);
<ide>
<del> this.set("resolve.modulesDirectories", ["web_modules", "node_modules"]);
<del> this.set("resolveLoader.modulesDirectories", ["web_loaders", "web_modules", "node_loaders", "node_modules"]);
<del>
<del> this.set("resolveLoader.moduleTemplates", ["*-webpack-loader", "*-web-loader", "*-loader", "*"]);
<del>
<ide> this.set("resolve.alias", {});
<ide> this.set("resolveLoader.alias", {});
<ide>
<del> this.set("resolve.extensions", ["", ".webpack.js", ".web.js", ".js"]);
<del> this.set("resolveLoader.extensions", ["", ".webpack-loader.js", ".web-loader.js", ".loader.js", ".js"]);
<del>
<del> this.set("resolve.packageMains", ["webpack", "browser", "web", "browserify", ["jam", "main"], "main"]);
<del> this.set("resolveLoader.packageMains", ["webpackLoader", "webLoader", "loader", "main"]);
<del>
<del> this.set("resolve.packageAlias", false);
<del>
<ide> this.set("optimize.occurenceOrderPreferEntry", true);
<ide> }
<ide> module.exports = WebpackOptionsDefaulter;
<ide>
<ide> WebpackOptionsDefaulter.prototype = Object.create(OptionsDefaulter.prototype);
<add>
<add>WebpackOptionsDefaulter.prototype.constructor = WebpackOptionsDefaulter;
<add>
<add>WebpackOptionsDefaulter.prototype.process = function(options) {
<add> OptionsDefaulter.prototype.process.call(this, options);
<add>
<add> if(options.resolve.packageAlias === undefined) {
<add> if(options.target === "web" || options.target === "webworker")
<add> options.resolve.packageAlias = "browser";
<add> }
<add>
<add> function defaultByTarget(value, web, webworker, node, def) {
<add> if(value !== undefined) return value;
<add> switch(options.target) {
<add> case "web": return web;
<add> case "webworker": return webworker;
<add> case "node": case "async-node": return node;
<add> default: return def;
<add> }
<add> }
<add>
<add> options.resolve.modulesDirectories = defaultByTarget(options.resolve.modulesDirectories,
<add> ["web_modules", "node_modules"],
<add> ["webworker_modules", "web_modules", "node_modules"],
<add> ["node_modules"],
<add> ["node_modules"]);
<add>
<add> options.resolveLoader.modulesDirectories = defaultByTarget(options.resolveLoader.modulesDirectories,
<add> ["web_loaders", "web_modules", "node_loaders", "node_modules"],
<add> ["webworker_loaders", "web_loaders", "web_modules", "node_loaders", "node_modules"],
<add> ["node_loaders", "node_modules"],
<add> ["node_modules"]);
<add>
<add> options.resolve.packageMains = defaultByTarget(options.resolve.packageMains,
<add> ["webpack", "browser", "web", "browserify", ["jam", "main"], "main"],
<add> ["webpackWorker", "webworker", "webpack", "browser", "web", "browserify", ["jam", "main"], "main"],
<add> ["webpackNode", "node", "main"],
<add> ["main"]);
<add>
<add> options.resolve.packageAlias = defaultByTarget(options.resolve.packageAlias,
<add> "browser",
<add> "browser",
<add> false,
<add> false);
<add>
<add> options.resolveLoader.packageMains = defaultByTarget(options.resolveLoader.packageMains,
<add> ["webpackLoader", "webLoader", "loader", "main"],
<add> ["webpackWorkerLoader", "webworkerLoader", "webLoader", "loader", "main"],
<add> ["webpackNodeLoader", "nodeLoader", "loader", "main"],
<add> ["loader", "main"]);
<add>
<add> options.resolve.extensions = defaultByTarget(options.resolve.extensions,
<add> ["", ".webpack.js", ".web.js", ".js"],
<add> ["", ".webpack-worker.js", ".webworker.js", ".web.js", ".js"],
<add> ["", ".webpack-node.js", ".js", ".node"],
<add> ["", ".js"]);
<add>
<add> options.resolveLoader.extensions = defaultByTarget(options.resolveLoader.extensions,
<add> ["", ".webpack-loader.js", ".web-loader.js", ".loader.js", ".js"],
<add> ["", ".webpack-worker-loader.js", ".webpack-loader.js", ".webworker-loader.js", ".web-loader.js", ".loader.js", ".js"],
<add> ["", ".webpack-node-loader.js", ".loader.js", ".js"],
<add> ["", ".js"]);
<add>
<add> options.resolveLoader.moduleTemplates = defaultByTarget(options.resolveLoader.moduleTemplates,
<add> ["*-webpack-loader", "*-web-loader", "*-loader", "*"],
<add> ["*-webpack-worker-loader", "*-webworker-loader", "*-web-loader", "*-loader", "*"],
<add> ["*-webpack-node-loader", "*-node-loader", "*-loader", "*"],
<add> ["*-loader", "*"]);
<add>};
<ide>\ No newline at end of file
<ide><path>test/TestCases.test.js
<ide> describe("TestCases", function() {
<ide> path: outputDirectory,
<ide> filename: "bundle.js"
<ide> },
<add> resolve: {
<add> modulesDirectories: ["web_modules", "node_modules"],
<add> packageMains: ["webpack", "browser", "web", "browserify", ["jam", "main"], "main"],
<add> extensions: ["", ".webpack.js", ".web.js", ".js"],
<add> packageAlias: "browser"
<add> },
<add> resolveLoader: {
<add> modulesDirectories: ["web_loaders", "web_modules", "node_loaders", "node_modules"],
<add> packageMains: ["webpackLoader", "webLoader", "loader", "main"],
<add> extensions: ["", ".webpack-loader.js", ".web-loader.js", ".loader.js", ".js"]
<add> },
<ide> module: {
<ide> loaders: [
<ide> { test: /\.json$/, loader: "json" },
<ide> describe("TestCases", function() {
<ide> };
<ide> webpack(options, function(err, stats) {
<ide> if(err) return done(err);
<del> var jsonStats = stats.toJson();
<add> var jsonStats = stats.toJson({
<add> errorDetails: true
<add> });
<ide> if(checkArrayExpectation(testDirectory, jsonStats, "error", "Error", done)) return;
<ide> if(checkArrayExpectation(testDirectory, jsonStats, "warning", "Warning", done)) return;
<ide> var exportedTest = 0; | 3 |
Text | Text | add a hyperlink to create a new issue | 06375310472cc25c1e3120837480220bc9ffafd2 | <ide><path>CONTRIBUTING.md
<ide> If you are still having difficulty after looking over your configuration careful
<ide> a question to [StackOverflow with the webpack tag](http://stackoverflow.com/tags/webpack). Questions
<ide> that include your webpack.config.js and relevant files are more likely to receive responses.
<ide>
<del>**If you have discovered a bug or have a feature suggestion, feel free to create an issue on Github.**
<add>**If you have discovered a bug or have a feature suggestion, please [create an issue on GitHub](https://github.com/webpack/webpack/issues/new).**
<ide>
<ide> ## Contributing to the webpack ecosystem
<ide> | 1 |
Javascript | Javascript | remove unnecessary comma in skyshader | f81eb19ea78cbd5ce69db8ac3f51efc5a7f035b5 | <ide><path>examples/js/SkyShader.js
<ide> THREE.ShaderLib[ 'sky' ] = {
<ide> // mie coefficients
<ide> "vBetaM = totalMie(lambda, turbidity) * mieCoefficient;",
<ide>
<del> "}",
<add> "}"
<ide>
<ide> ].join( "\n" ),
<ide>
<ide> THREE.ShaderLib[ 'sky' ] = {
<ide> "gl_FragColor.rgb = retColor;",
<ide>
<ide> "gl_FragColor.a = 1.0;",
<del> "}",
<add> "}"
<ide>
<ide> ].join( "\n" )
<ide> | 1 |
PHP | PHP | add new line at the end of the file | 511c5cf409526b9cb430396c4f3fe82c038b5d21 | <ide><path>src/Illuminate/Database/Eloquent/Builder.php
<ide> public function __clone()
<ide> }
<ide>
<ide> }
<add> | 1 |
Text | Text | update tutorial language to be more explicit | 8e47082fb642b6d4db2de1656389fcf14cbefaa7 | <ide><path>docs/docs/tutorial.md
<ide> var CommentForm = React.createClass({
<ide> });
<ide> ```
<ide>
<del>Next, update the `CommentBox` component to use its new friends:
<add>Next, update the `CommentBox` component to use these new components:
<ide>
<ide> ```javascript{6-8}
<ide> // tutorial3.js | 1 |
Javascript | Javascript | remove failing test | be3551cd18cd62eda0537bded282c2e23397ca23 | <ide><path>spec/window-event-handler-spec.js
<ide> describe('WindowEventHandler', () => {
<ide> describe('window:close event', () =>
<ide> it('closes the window', () => {
<ide> spyOn(atom, 'close')
<del> spyOn(atom, 'storeWindowDimensions')
<ide> window.dispatchEvent(new CustomEvent('window:close'))
<ide> expect(atom.close).toHaveBeenCalled()
<del> expect(atom.storeWindowDimensions).toHaveBeenCalled()
<ide> })
<ide>
<ide> ) | 1 |
PHP | PHP | add missing method | 2b9be838df5369d2ff78fc26ade43775b311b701 | <ide><path>src/Illuminate/Routing/UrlGenerator.php
<ide> public function setRequest(Request $request)
<ide> $this->request = $request;
<ide> }
<ide>
<add> /**
<add> * Set the route collection.
<add> *
<add> * @param \Illuminate\Routing\RouteCollection $routes
<add> * @return $this
<add> */
<add> public function setRoutes(RouteCollection $routes)
<add> {
<add> $this->routes = $routes;
<add>
<add> return $this;
<add> }
<add>
<ide> /**
<ide> * Set the root controller namespace.
<ide> * | 1 |
Ruby | Ruby | fix failing test in railties | 6bdc04624dcc0f45aab93af42d00224f67da36d5 | <ide><path>railties/test/rails_info_controller_test.rb
<ide> def setup
<ide>
<ide> test "info controller renders with routes" do
<ide> get :routes
<del> assert_select 'pre'
<add> assert_select 'table#routeTable'
<ide> end
<del>
<ide> end | 1 |
Text | Text | add zkat to collaborators | 2cf4e388ca1d62fabca3d96d506e5321e5eb12c6 | <ide><path>README.md
<ide> information about the governance of the Node.js project, see
<ide> * [tunniclm](https://github.com/tunniclm) - **Mike Tunnicliffe** <m.j.tunnicliffe@gmail.com>
<ide> * [vkurchatkin](https://github.com/vkurchatkin) - **Vladimir Kurchatkin** <vladimir.kurchatkin@gmail.com>
<ide> * [yosuke-furukawa](https://github.com/yosuke-furukawa) - **Yosuke Furukawa** <yosuke.furukawa@gmail.com>
<add>* [zkat](https://github.com/zkat) - **Kat Marchán** <kzm@sykosomatic.org>
<ide>
<ide> Collaborators & TSC members follow the [COLLABORATOR_GUIDE.md](./COLLABORATOR_GUIDE.md) in
<ide> maintaining the Node.js project. | 1 |
Text | Text | add 1.4.0-beta.5 to changelog.md | b6c0341a863a820daac534b4a0c1dbc44e741a10 | <ide><path>CHANGELOG.md
<ide> * [BREAKING CHANGE] `Ember.run.throttle` now supports leading edge execution. To follow industry standard leading edge is the default.
<ide> * [BUGFIX] Fixed how parentController property of an itemController when nested. Breaking for apps that rely on previous broken behavior of an itemController's `parentController` property skipping its ArrayController when nested.
<ide>
<add>### Ember 1.4.0-beta.5 (February 3, 2014)
<add>
<add>* Deprecate quoteless action names.
<add>* [BUGFIX beta] Make Ember.RenderBuffer#addClass work as expected.
<add>* [DOC beta] Display Ember Inspector hint in Firefox.
<add>* [Bugfix BETA] App.destroy resets routes before destroying the container.
<add>
<ide> ### Ember 1.4.0-beta.4 (January 29, 2014)
<ide>
<ide> * [BUGFIX beta] reduceComputed fires observers when invalidating with undefined. | 1 |
Ruby | Ruby | determine remote_url using git config | 5f18f0bb03c72af19952e2573db6881eb84257f0 | <ide><path>Library/Homebrew/dev-cmd/bump-formula-pr.rb
<ide> def bump_formula_pr
<ide> odie "Unable to fork: #{e.message}!"
<ide> end
<ide>
<del> remote_url = response.fetch("clone_url")
<add> if system("git", "config", "--local", "--get-regexp", "remote\..*\.url", "git@github.com:.*")
<add> remote_url = response.fetch("ssh_url")
<add> else
<add> remote_url = response.fetch("clone_url")
<add> end
<ide> username = response.fetch("owner").fetch("login")
<ide>
<ide> safe_system "git", "fetch", "--unshallow", "origin" if shallow | 1 |
PHP | PHP | shorten variable name | 0719bad766e625f25502b695a4dcaf3b976ddcab | <ide><path>src/Illuminate/Support/Facades/Response.php
<ide> public static function stream($callback, $status = 200, array $headers = array()
<ide> * @param \SplFileInfo|string $file
<ide> * @param string $name
<ide> * @param array $headers
<del> * @param null|string $contentDisposition
<add> * @param null|string $disposition
<ide> * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
<ide> */
<del> public static function download($file, $name = null, array $headers = array(), $contentDisposition = 'attachment')
<add> public static function download($file, $name = null, array $headers = array(), $disposition = 'attachment')
<ide> {
<del> $response = new BinaryFileResponse($file, 200, $headers, true, $contentDisposition);
<add> $response = new BinaryFileResponse($file, 200, $headers, true, $disposition);
<ide>
<ide> if ( ! is_null($name))
<ide> {
<del> return $response->setContentDisposition($contentDisposition, $name, Str::ascii($name));
<add> return $response->setContentDisposition($disposition, $name, Str::ascii($name));
<ide> }
<ide>
<ide> return $response; | 1 |
Python | Python | improve accuracy of to_cpu_str converter function | ae315fa426fca0e2013e8fbcbebce37f7d424385 | <ide><path>libcloud/utils/misc.py
<ide> def to_cpu_str(n_cpus):
<ide> """Convert number of cpus to cpu string
<ide> (e.g. 0.5 -> '500m')
<ide> """
<del> millicores = int(n_cpus * 1000)
<add> if n_cpus == 0:
<add> return "0"
<add> millicores = n_cpus * 1000
<ide> if millicores % 1 == 0:
<del> return f"{millicores}m"
<del> nanocores = int(n_cpus * 1000000000)
<del> return f"{nanocores}n"
<add> return f"{int(millicores)}m"
<add> microcores = n_cpus * 1000000
<add> if microcores % 1 == 0:
<add> return f"{int(microcores)}u"
<add> nanocores = n_cpus * 1000000000
<add> return f"{int(nanocores)}n"
<ide>
<ide>
<ide> def to_n_cpus_from_cpu_str(cpu_str):
<ide> def to_n_cpus_from_cpu_str(cpu_str):
<ide> return 0
<ide>
<ide>
<del># Error message which indicates a transient SSL error upon which request
<del># can be retried
<del>TRANSIENT_SSL_ERROR = "The read operation timed out"
<del>
<del>
<ide> def find(value, predicate):
<ide> results = [x for x in value if predicate(x)]
<ide> return results[0] if len(results) > 0 else None | 1 |
Javascript | Javascript | remove event flags | b314d66a911819de88549d3f37866c3ebc191ea2 | <ide><path>packages/ember-metal/lib/events.js
<ide> import { applyStr } from 'ember-utils';
<ide> import { ENV } from 'ember-environment';
<ide> import { deprecate, assert } from 'ember-debug';
<ide> import { meta as metaFor, peekMeta } from './meta';
<del>import { ONCE } from './meta_listeners';
<ide>
<ide> /*
<ide> The event system uses a series of nested hashes to store listeners on an
<ide> import { ONCE } from './meta_listeners';
<ide> {
<ide> listeners: { // variable name: `listenerSet`
<ide> "foo": [ // variable name: `actions`
<del> target, method, flags
<add> target, method, once
<ide> ]
<ide> }
<ide> }
<ide> export function addListener(obj, eventName, target, method, once) {
<ide> target = null;
<ide> }
<ide>
<del> let flags = 0;
<del> if (once) {
<del> flags |= ONCE;
<del> }
<del>
<del> metaFor(obj).addToListeners(eventName, target, method, flags);
<add> metaFor(obj).addToListeners(eventName, target, method, once);
<ide>
<ide> if ('function' === typeof obj.didAddListener) {
<ide> obj.didAddListener(eventName, target, method);
<ide> export function sendEvent(obj, eventName, params, actions, _meta) {
<ide> for (let i = actions.length - 3; i >= 0; i -= 3) { // looping in reverse for once listeners
<ide> let target = actions[i];
<ide> let method = actions[i + 1];
<del> let flags = actions[i + 2];
<add> let once = actions[i + 2];
<ide>
<ide> if (!method) { continue; }
<del> if (flags & ONCE) { removeListener(obj, eventName, target, method); }
<add> if (once) { removeListener(obj, eventName, target, method); }
<ide> if (!target) { target = obj; }
<ide> if ('string' === typeof method) {
<ide> if (params) {
<ide><path>packages/ember-metal/lib/meta_listeners.js
<ide> save that for dispatch time, if an event actually happens.
<ide> */
<ide>
<del>/* listener flags */
<del>export const ONCE = 1;
<del>
<ide> export const protoMethods = {
<ide>
<del> addToListeners(eventName, target, method, flags) {
<add> addToListeners(eventName, target, method, once) {
<ide> if (this._listeners === undefined) { this._listeners = []; }
<del> this._listeners.push(eventName, target, method, flags);
<add> this._listeners.push(eventName, target, method, once);
<ide> },
<ide>
<ide> _finalizeListeners() { | 2 |
Text | Text | fix typo in contributing.md | 565d2ce0515495e696c52738cb177474a37d8d42 | <ide><path>CONTRIBUTING.md
<ide> You can contribute in many ways:
<ide>
<ide> ### Report Bugs
<ide>
<del>Report bugs through Gihub
<add>Report bugs through Github
<ide>
<ide> If you are reporting a bug, please include:
<ide> | 1 |
Javascript | Javascript | stabilize window ci | 02aa7b28da4a31fe51dff2ab25d7751c576a7d47 | <ide><path>test/integration/ssg-data-404/test/index.test.js
<ide> const runTests = () => {
<ide> }
<ide>
<ide> describe('SSG data 404', () => {
<add> if (process.platform === 'win32') {
<add> it('should skip this suite on Windows', () => {})
<add> return
<add> }
<add>
<ide> describe('dev mode', () => {
<ide> beforeAll(async () => {
<ide> appPort = await findPort() | 1 |
PHP | PHP | add everyminute helper to event scheduler | 166381480526e8d06a73a44032eb2a440f4bce4a | <ide><path>src/Illuminate/Console/Scheduling/Event.php
<ide> public function yearly()
<ide> return $this->cron('0 0 1 1 * *');
<ide> }
<ide>
<add> /**
<add> * Schedule the event to run every minute.
<add> *
<add> * @return $this
<add> */
<add> public function everyMinute()
<add> {
<add> return $this->cron('* * * * * *');
<add> }
<add>
<ide> /**
<ide> * Schedule the event to run every five minutes.
<ide> * | 1 |
Text | Text | add release key for bryan english | bcc523e3891ee1896b77741b2b74476d314c88ad | <ide><path>README.md
<ide> Primary GPG keys for Node.js Releasers (some Releasers sign with subkeys):
<ide>
<ide> * **Beth Griggs** <<bgriggs@redhat.com>>
<ide> `4ED778F539E3634C779C87C6D7062848A1AB005C`
<add>* **Bryan English** <<bryan@bryanenglish.com>>
<add> `141F07595B7B3FFE74309A937405533BE57C7D57`
<ide> * **Colin Ihrig** <<cjihrig@gmail.com>>
<ide> `94AE36675C464D64BAFA68DD7434390BDBE9B9C5`
<ide> * **Danielle Adams** <<adamzdanielle@gmail.com>>
<ide> to sign releases):
<ide>
<ide> ```bash
<ide> gpg --keyserver hkps://keys.openpgp.org --recv-keys 4ED778F539E3634C779C87C6D7062848A1AB005C
<add>gpg --keyserver hkps://keys.openpgp.org --recv-keys 141F07595B7B3FFE74309A937405533BE57C7D57
<ide> gpg --keyserver hkps://keys.openpgp.org --recv-keys 94AE36675C464D64BAFA68DD7434390BDBE9B9C5
<ide> gpg --keyserver hkps://keys.openpgp.org --recv-keys 74F12602B6F1C4E913FAA37AD3A89613643B6201
<ide> gpg --keyserver hkps://keys.openpgp.org --recv-keys 71DCFD284A79C3B38668286BC97EC7A07EDE3FC1 | 1 |
Text | Text | add atom.io api docs | 40b66e8eb33939ed75f37f84da3287a3880f50de | <ide><path>docs/apm-rest-api.md
<add>## Atom.io package and update API
<add>
<add>This guide describes the web API used by [apm](https://github.com/atom/apm) and
<add>Atom. The vast majority of use cases are met by the `apm` command-line tool,
<add>which does other useful things like incrementing your version in `package.json`
<add>and making sure you have pushed your git tag. In fact, Atom itself shells out to
<add>`apm` rather than hitting the API directly. If you're curious about how Atom
<add>uses `apm`, see the [PackageManager class](https://github.com/atom/settings-view/blob/master/lib/package-manager.coffee)
<add>in the `settings-view` package.
<add>
<add>### Authorization
<add>
<add>For calls to the API that require authentication, provide a valid token from your
<add>[Atom.io account page](https://atom.io/account) in the `Authorization` header.
<add>
<add>### Media type
<add>
<add>All requests that take parameters require `application/json`.
<add>
<add>## Resources
<add>
<add>### Packages
<add>
<add>**GET** /api/packages
<add>
<add>Returns a list of all packages in the following format:
<add>```json
<add> [
<add> {
<add> "releases": {
<add> "latest": "0.6.0"
<add> },
<add> "name": "thedaniel-test-package",
<add> "repository": {
<add> "type": "git",
<add> "url": "https://github.com/thedaniel/test-package"
<add> }
<add> },
<add> ...
<add> ]
<add>```
<add>
<add>**GET** /api/packages/:package_name
<add>
<add>Returns package details and versions for a single package
<add>
<add>Parameters:
<add>
<add>- **engine** (optional) - Only show packages with versions compatible with this
<add> Atom version. Must be valid [SemVer](http://semver.org).
<add>
<add>Returns:
<add>
<add>```json
<add> {
<add> "releases": {
<add> "latest": "0.6.0"
<add> },
<add> "name": "thedaniel-test-package",
<add> "repository": {
<add> "type": "git",
<add> "url": "https://github.com/thedaniel/test-package"
<add> },
<add> "versions": [
<add> (see single version output below)
<add> ...,
<add> ]
<add> }
<add>```
<add>
<add>**POST** /api/packages
<add>
<add>Create a new package; requires authentication.
<add>
<add>The name and version will be fetched from the `package.json`
<add>file in the specified repository. The authenticating user *must* have access
<add>to the indicated repository.
<add>
<add>When a package is created, a release hook is registered with GitHub for package
<add>version creation.
<add>
<add>Parameters:
<add>
<add>- **repository** - String. The repository containing the plugin, in the form "owner/repo"
<add>
<add>Returns:
<add>
<add>- **201** - Successfully created, returns created package.
<add>- **400** - Repository is inaccessible, nonexistent, not an atom package. Possible
<add> error messages include:
<add> - That repo does not exist, isn't an atom package, or atombot does not have access
<add> - The package.json at owner/repo isn't valid
<add>- **409** - A package by that name already exists
<add>
<add>
<add>**DELETE** /api/packages/:package_name
<add>
<add>Delete a package; requires authentication.
<add>
<add>Returns:
<add>
<add>- **204** - Success
<add>- **400** - Repository is inaccessible
<add>- **401** - Unauthorized
<add>
<add>### Package Versions
<add>
<add>**GET** /api/packages/:package_name/versions/:version_name
<add>
<add>Returns `package.json` with `dist` key added for e.g. tarball download:
<add>
<add>```json
<add> {
<add> "bugs": {
<add> "url": "https://github.com/thedaniel/test-package/issues"
<add> },
<add> "dependencies": {
<add> "async": "~0.2.6",
<add> "pegjs": "~0.7.0",
<add> "season": "~0.13.0"
<add> },
<add> "description": "Expand snippets matching the current prefix with `tab`.",
<add> "dist": {
<add> "tarball": "https://codeload.github.com/..."
<add> },
<add> "engines": {
<add> "atom": "*"
<add> },
<add> "main": "./lib/snippets",
<add> "name": "thedaniel-test-package",
<add> "publishConfig": {
<add> "registry": "https://...",
<add> },
<add> "repository": {
<add> "type": "git",
<add> "url": "https://github.com/thedaniel/test-package.git"
<add> },
<add> "version": "0.6.0"
<add> }
<add>```
<add>
<add>
<add>### Creating a new package version
<add>
<add>**POST** /api/packages/:package_name/versions
<add>
<add>Creates a new package version from a git tag; requires authentication.
<add>
<add>#### Parameters
<add>
<add>- **tag** - A git tag for the version you'd like to create. It's important to note
<add> that the version name will not be taken from the tag, but from the `version`
<add> key in the `package.json` file at that ref. The authenticating user *must* have
<add> access to the package repository.
<add>
<add>#### Returns
<add>
<add>- **201** - Successfully created. Returns created version.
<add>- **400** - Git tag not found / Repository inaccessible
<add>- **409** - Version exists
<add>
<add>### Delete a version
<add>
<add>**DELETE** /api/packages/:package_name/versions/:version_name
<add>
<add>Deletes a package version; requires authentication.
<add>
<add>Note that a version cannot be republished with a different tag if it is deleted.
<add>If you need to delete the latest version of a package for e.g. security reasons,
<add>you'll need to increment the version when republishing.
<add>
<add>Returns 204 No Content
<add>
<add>### Atom updates
<add>
<add>**GET** /api/updates
<add>
<add>Atom update feed, following the format expected by [Squirrel](https://github.com/Squirrel/).
<add>
<add>Returns:
<add>
<add>```
<add>{
<add> "name": "0.96.0",
<add> "notes": "[HTML release notes]"
<add> "pub_date": "2014-05-19T15:52:06.000Z",
<add> "url": "https://www.atom.io/api/updates/download"
<add>}
<add>```
<ide><path>docs/publishing-a-package.md
<ide> with a minor release.
<ide>
<ide> * Check out [semantic versioning][semver] to learn more about versioning your
<ide> package releases.
<add>* Consult the [Atom.io package API docs][apm-rest-api] to learn more about how
<add> `apm` works.
<ide>
<ide> [atomio]: https://atom.io
<ide> [github]: https://github.com
<ide> with a minor release.
<ide> [repo-guide]: http://guides.github.com/overviews/desktop
<ide> [semver]: http://semver.org
<ide> [your-first-package]: your-first-package.html
<add>[apm-rest-api]: apm-rest-api.md | 2 |
Ruby | Ruby | remove extra whitespaces | 099055de66ba400750d4cda7049c047aeb179ab7 | <ide><path>actionpack/test/dispatch/show_exceptions_test.rb
<ide> def call(env)
<ide> end
<ide> end
<ide>
<del> ProductionApp = ActionDispatch::ShowExceptions.new(Boomer.new, ActionDispatch::PublicExceptions.new("#{FIXTURE_LOAD_PATH}/public"))
<add> ProductionApp = ActionDispatch::ShowExceptions.new(Boomer.new, ActionDispatch::PublicExceptions.new("#{FIXTURE_LOAD_PATH}/public"))
<ide>
<ide> test "skip exceptions app if not showing exceptions" do
<ide> @app = ProductionApp | 1 |
Javascript | Javascript | add a basic instrumentation api | 134fc61b764ef5b464ab3ebef968716b7df5c50c | <ide><path>packages/ember-metal/lib/instrumentation.js
<add>/**
<add> @class Ember.Instrumentation
<add>
<add> The purpose of the Ember Instrumentation module is
<add> to provide efficient, general-purpose instrumentation
<add> for Ember.
<add>
<add> Subscribe to a listener by using `Ember.subscribe`:
<add>
<add> Ember.subscribe("render", {
<add> before: function(name, timestamp, payload) {
<add>
<add> },
<add>
<add> after: function(name, timestamp, payload) {
<add>
<add> }
<add> });
<add>
<add> If you return a value from the `before` callback, that same
<add> value will be passed as a fourth parameter to the `after`
<add> callback.
<add>
<add> Instrument a block of code by using `Ember.instrument`:
<add>
<add> Ember.instrument("render.handlebars", payload, function() {
<add> // rendering logic
<add> }, binding);
<add>
<add> Event names passed to `Ember.instrument` are namespaced
<add> by periods, from more general to more specific. Subscribers
<add> can listen for events by whatever level of granularity they
<add> are interested in.
<add>
<add> In the above example, the event is `render.handlebars`,
<add> and the subscriber listened for all events beginning with
<add> `render`. It would receive callbacks for events named
<add> `render`, `render.handlebars`, `render.container`, or
<add> even `render.handlebars.layout`.
<add>*/
<add>Ember.Instrumentation = {};
<add>
<add>var subscribers = [], cache = {};
<add>
<add>var populateListeners = function(name) {
<add> var listeners = [], subscriber;
<add>
<add> for (var i=0, l=subscribers.length; i<l; i++) {
<add> subscriber = subscribers[i];
<add> if (subscriber.regex.test(name)) {
<add> listeners.push(subscriber.object);
<add> }
<add> }
<add>
<add> cache[name] = listeners;
<add> return listeners;
<add>};
<add>
<add>Ember.Instrumentation.instrument = function(name, payload, callback, binding) {
<add> var listeners = cache[name];
<add>
<add> if (!listeners) {
<add> listeners = populateListeners(name);
<add> }
<add>
<add> if (listeners.length === 0) { return; }
<add>
<add> var beforeValues = [], listener, i, l;
<add>
<add> try {
<add> for (i=0, l=listeners.length; i<l; i++) {
<add> listener = listeners[i];
<add> beforeValues[i] = listener.before(name, new Date(), payload);
<add> }
<add>
<add> callback.call(binding);
<add> } catch(e) {
<add> payload = payload || {};
<add> payload.exception = e;
<add> } finally {
<add> for (i=0, l=listeners.length; i<l; i++) {
<add> listener = listeners[i];
<add> listener.after(name, new Date(), payload, beforeValues[i]);
<add> }
<add> }
<add>};
<add>
<add>Ember.Instrumentation.subscribe = function(pattern, object) {
<add> var paths = pattern.split("."), path, regex = "^";
<add>
<add> for (var i=0, l=paths.length; i<l; i++) {
<add> path = paths[i];
<add> if (path === "*") {
<add> regex = regex + "[^\\.]*";
<add> } else {
<add> regex = regex + path;
<add> }
<add> }
<add>
<add> regex = regex + "(\\..*)?";
<add>
<add> var subscriber = {
<add> pattern: pattern,
<add> regex: new RegExp(regex + "$"),
<add> object: object
<add> };
<add>
<add> subscribers.push(subscriber);
<add> cache = {};
<add>
<add> return subscriber;
<add>};
<add>
<add>Ember.Instrumentation.unsubscribe = function(subscriber) {
<add> var index;
<add>
<add> for (var i=0, l=subscribers.length; i<l; i++) {
<add> if (subscribers[i] === subscriber) {
<add> index = i;
<add> }
<add> }
<add>
<add> subscribers.splice(index, 1);
<add> cache = {};
<add>};
<add>
<add>Ember.Instrumentation.reset = function() {
<add> subscribers = [];
<add> cache = {};
<add>};
<add>
<add>Ember.instrument = Ember.Instrumentation.instrument;
<add>Ember.subscribe = Ember.Instrumentation.subscribe;
<ide><path>packages/ember-metal/lib/main.js
<ide> Ember Metal
<ide> @submodule ember-metal
<ide> */
<ide>
<add>require('ember-metal/instrumentation');
<ide> require('ember-metal/core');
<ide> require('ember-metal/map');
<ide> require('ember-metal/platform');
<ide><path>packages/ember-metal/tests/instrumentation_test.js
<add>var instrument = Ember.Instrumentation;
<add>
<add>module("Ember Instrumentation", {
<add> setup: function() {
<add>
<add> },
<add> teardown: function() {
<add> instrument.reset();
<add> }
<add>});
<add>
<add>test("subscribing to a simple path receives the listener", function() {
<add> expect(12);
<add>
<add> var sentPayload = {}, count = 0;
<add>
<add> instrument.subscribe("render", {
<add> before: function(name, timestamp, payload) {
<add> if (count === 0) {
<add> strictEqual(name, "render");
<add> } else {
<add> strictEqual(name, "render.handlebars");
<add> }
<add>
<add> ok(timestamp instanceof Date);
<add> strictEqual(payload, sentPayload);
<add> },
<add>
<add> after: function(name, timestamp, payload) {
<add> if (count === 0) {
<add> strictEqual(name, "render");
<add> } else {
<add> strictEqual(name, "render.handlebars");
<add> }
<add>
<add> ok(timestamp instanceof Date);
<add> strictEqual(payload, sentPayload);
<add>
<add> count++;
<add> }
<add> });
<add>
<add> instrument.instrument("render", sentPayload, function() {
<add>
<add> });
<add>
<add> instrument.instrument("render.handlebars", sentPayload, function() {
<add>
<add> });
<add>});
<add>
<add>test("returning a value from the before callback passes it to the after callback", function() {
<add> expect(2);
<add>
<add> var passthru1 = {}, passthru2 = {};
<add>
<add> instrument.subscribe("render", {
<add> before: function(name, timestamp, payload) {
<add> return passthru1;
<add> },
<add> after: function(name, timestamp, payload, beforeValue) {
<add> strictEqual(beforeValue, passthru1);
<add> }
<add> });
<add>
<add> instrument.subscribe("render", {
<add> before: function(name, timestamp, payload) {
<add> return passthru2;
<add> },
<add> after: function(name, timestamp, payload, beforeValue) {
<add> strictEqual(beforeValue, passthru2);
<add> }
<add> });
<add>
<add> instrument.instrument("render", null, function() {});
<add>});
<add>
<add>test("raising an exception in the instrumentation attaches it to the payload", function() {
<add> expect(2);
<add>
<add> var error = new Error("Instrumentation");
<add>
<add> instrument.subscribe("render", {
<add> before: function() {},
<add> after: function(name, timestamp, payload) {
<add> strictEqual(payload.exception, error);
<add> }
<add> });
<add>
<add> instrument.subscribe("render", {
<add> before: function() {},
<add> after: function(name, timestamp, payload) {
<add> strictEqual(payload.exception, error);
<add> }
<add> });
<add>
<add> instrument.instrument("render.handlebars", null, function() {
<add> throw error;
<add> });
<add>});
<add>
<add>test("it is possible to add a new subscriber after the first instrument", function() {
<add> instrument.instrument("render.handlebars", null, function() {});
<add>
<add> instrument.subscribe("render", {
<add> before: function() {
<add> ok(true, "Before callback was called");
<add> },
<add> after: function() {
<add> ok(true, "After callback was called");
<add> }
<add> });
<add>
<add> instrument.instrument("render.handlebars", function() {});
<add>});
<add>
<add>test("it is possible to remove a subscriber", function() {
<add> expect(4);
<add>
<add> var count = 0;
<add>
<add> var subscriber = instrument.subscribe("render", {
<add> before: function() {
<add> equal(count, 0);
<add> ok(true, "Before callback was called");
<add> },
<add> after: function() {
<add> equal(count, 0);
<add> ok(true, "After callback was called");
<add> count++;
<add> }
<add> });
<add>
<add> instrument.instrument("render.handlebars", function() {});
<add>
<add> instrument.unsubscribe(subscriber);
<add>
<add> instrument.instrument("render.handlebars", function() {});
<add>}); | 3 |
Python | Python | restore use of dtype input arg to test | 5605413eb575f1a25c24ea34a8f7c41f6702e2b4 | <ide><path>numpy/core/tests/test_multiarray.py
<ide> def __numpy_ufunc__(self, ufunc, method, pos, inputs, **kwargs):
<ide> assert_raises(TypeError, c.dot, b)
<ide>
<ide> def test_accelerate_framework_sgemv_fix(self):
<del> if sys.platform != 'darwin':
<del> return
<ide>
<ide> def aligned_array(shape, align, dtype, order='C'):
<del> d = np.dtype()
<add> d = dtype(0)
<ide> N = np.prod(shape)
<ide> tmp = np.zeros(N * d.nbytes + align, dtype=np.uint8)
<ide> address = tmp.__array_interface__["data"][0] | 1 |
Javascript | Javascript | update other uses of .confirm for new async api | 3d9f6bc6646f72411accfe7627d7cef9374db6c7 | <ide><path>src/command-installer.js
<ide> class CommandInstaller {
<ide> const showErrorDialog = (error) => {
<ide> this.applicationDelegate.confirm({
<ide> message: 'Failed to install shell commands',
<del> detailedMessage: error.message
<add> detail: error.message
<ide> }, () => {})
<ide> }
<ide>
<ide> class CommandInstaller {
<ide> if (error) return showErrorDialog(error)
<ide> this.applicationDelegate.confirm({
<ide> message: 'Commands installed.',
<del> detailedMessage: 'The shell commands `atom` and `apm` are installed.'
<add> detail: 'The shell commands `atom` and `apm` are installed.'
<ide> }, () => {})
<ide> })
<ide> })
<ide><path>src/pane.js
<ide> class Pane {
<ide> const saveDialog = (saveButtonText, saveFn, message) => {
<ide> this.applicationDelegate.confirm({
<ide> message,
<del> detailedMessage: 'Your changes will be lost if you close this item without saving.',
<add> detail: 'Your changes will be lost if you close this item without saving.',
<ide> buttons: [saveButtonText, 'Cancel', "&Don't Save"]
<ide> }, response => {
<ide> switch (response) {
<ide><path>src/workspace.js
<ide> module.exports = class Workspace extends Model {
<ide> if (fileSize >= (this.config.get('core.warnOnLargeFileLimit') * 1048576)) { // 40MB by default
<ide> this.applicationDelegate.confirm({
<ide> message: 'Atom will be unresponsive during the loading of very large files.',
<del> detailedMessage: 'Do you still want to load this file?',
<add> detail: 'Do you still want to load this file?',
<ide> buttons: ['Proceed', 'Cancel']
<ide> }, response => {
<ide> if (response === 1) {
<ide> module.exports = class Workspace extends Model {
<ide> if (this.config.get('editor.confirmCheckoutHeadRevision')) {
<ide> this.applicationDelegate.confirm({
<ide> message: 'Confirm Checkout HEAD Revision',
<del> detailedMessage: `Are you sure you want to discard all changes to "${editor.getFileName()}" since the last Git commit?`,
<add> detail: `Are you sure you want to discard all changes to "${editor.getFileName()}" since the last Git commit?`,
<ide> buttons: ['OK', 'Cancel']
<ide> }, response => {
<ide> if (response === 0) checkoutHead() | 3 |
PHP | PHP | remove the ones that should not apply | 00fb848fe9cc7fdb1c118fb522971a12fada409e | <ide><path>src/Mailer/Mailer.php
<ide> * @method Email addAttachments($attachments)
<ide> * @method Email message($type = null)
<ide> * @method Email profile($config = null)
<del> * @method Email send($content = null)
<del> * @method Email reset()
<ide> */
<ide> abstract class Mailer implements EventListenerInterface
<ide> { | 1 |
Text | Text | add 403 forbidden on post requests to faq | 4e483fb07eb7ee58e41e6f82db2905e3c15faba6 | <ide><path>README.md
<ide> would like to see original, non-minified markup, add `app.locals.pretty = true;`
<ide>
<ide> FAQ
<ide> ---
<add>### Why do I keep getting `403 Error: Forbidden` on submitting a **POST** request?
<add>You need to add this hidden input element to your form. This has been added in the
<add>pull request [#40](https://github.com/sahat/hackathon-starter/pull/40).
<add>```
<add>input(type='hidden', name='_csrf', value=token)
<add>```
<add>
<ide> ### What is cluster_app.js?
<ide> From the [Node.js Documentation](http://nodejs.org/api/cluster.html#cluster_how_it_works):
<ide> > A single instance of Node runs in a single thread. To take advantage of multi-core systems | 1 |
PHP | PHP | change exception type | b4f000516166b0694e842d64f5b2fde1167d4690 | <ide><path>src/Illuminate/Foundation/ProviderRepository.php
<ide>
<ide> namespace Illuminate\Foundation;
<ide>
<add>use Exception;
<ide> use Illuminate\Filesystem\Filesystem;
<del>use Illuminate\Contracts\Filesystem\FileNotFoundException;
<ide> use Illuminate\Contracts\Foundation\Application as ApplicationContract;
<ide>
<ide> class ProviderRepository
<ide> protected function freshManifest(array $providers)
<ide> *
<ide> * @param array $manifest
<ide> * @return array
<del> * @throws FileNotFoundException
<add> * @throws Exception
<ide> */
<ide> public function writeManifest($manifest)
<ide> {
<ide> if (! is_writable(dirname($this->manifestPath))) {
<del> throw new FileNotFoundException('The bootstrap/cache directory must be present and writable.');
<add> throw new Exception('The bootstrap/cache directory must be present and writable.');
<ide> }
<ide>
<ide> $this->files->put( | 1 |
Javascript | Javascript | use separate feature flag for reacttestrenderer | 13e05b4237819c028515d6dedec9c2d21324a198 | <ide><path>scripts/jest/test-framework-setup.js
<ide> jest.mock('ReactNativeFeatureFlags', () => {
<ide> useFiber: flags.useFiber || !!process.env.REACT_DOM_JEST_USE_FIBER,
<ide> });
<ide> });
<add>jest.mock('ReactTestRendererFeatureFlags', () => {
<add> const flags = require.requireActual('ReactTestRendererFeatureFlags');
<add> return Object.assign({}, flags, {
<add> useFiber: flags.useFiber || !!process.env.REACT_DOM_JEST_USE_FIBER,
<add> });
<add>});
<ide>
<ide> // Error logging varies between Fiber and Stack;
<ide> // Rather than fork dozens of tests, mock the error-logging file by default.
<ide><path>src/renderers/testing/ReactTestRenderer.js
<ide>
<ide> 'use strict';
<ide>
<del>const ReactDOMFeatureFlags = require('ReactDOMFeatureFlags');
<add>const ReactTestRendererFeatureFlags = require('ReactTestRendererFeatureFlags');
<ide>
<del>module.exports = ReactDOMFeatureFlags.useFiber
<add>module.exports = ReactTestRendererFeatureFlags.useFiber
<ide> ? require('ReactTestRendererFiber')
<ide> : require('ReactTestRendererStack');
<ide><path>src/renderers/testing/ReactTestRendererFeatureFlags.js
<add>/**
<add> * Copyright 2013-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> *
<add> * @providesModule ReactTestRendererFeatureFlags
<add> */
<add>
<add>'use strict';
<add>
<add>var ReactTestRendererFeatureFlags = {
<add> useFiber: false,
<add>};
<add>
<add>module.exports = ReactTestRendererFeatureFlags; | 3 |
Ruby | Ruby | remove unnecessary `pathname` check | 5e3bc855273d73d2c67704a640d0680afe059ff4 | <ide><path>Library/Homebrew/resource.rb
<ide> def unpack(target = nil)
<ide> if block_given?
<ide> yield ResourceStageContext.new(self, staging)
<ide> elsif target
<del> target = Pathname.new(target) unless target.is_a? Pathname
<add> target = Pathname(target)
<ide> target.install Pathname.pwd.children
<ide> end
<ide> end | 1 |
Javascript | Javascript | add test for hiding children after layout destroy | a10a9a6b5b891dd3ce238bf39a6147bb0f3a1d2a | <ide><path>packages/react-reconciler/src/__tests__/ReactOffscreen-test.js
<ide> describe('ReactOffscreen', () => {
<ide> expect(root).toMatchRenderedOutput(<span hidden={true} prop="Child" />);
<ide> });
<ide>
<add> // @gate experimental || www
<add> // @gate enableSuspenseLayoutEffectSemantics
<add> // @gate enableFlipOffscreenUnhideOrder
<add> it('hides children of offscreen after layout effects are destroyed', async () => {
<add> const root = ReactNoop.createRoot();
<add> function Child({text}) {
<add> useLayoutEffect(() => {
<add> Scheduler.unstable_yieldValue('Mount layout');
<add> return () => {
<add> // The child should not be hidden yet.
<add> expect(root).toMatchRenderedOutput(<span prop="Child" />);
<add> Scheduler.unstable_yieldValue('Unmount layout');
<add> };
<add> }, []);
<add> return <Text text="Child" />;
<add> }
<add>
<add> await act(async () => {
<add> root.render(
<add> <Offscreen mode="visible">
<add> <Child />
<add> </Offscreen>,
<add> );
<add> });
<add> expect(Scheduler).toHaveYielded(['Child', 'Mount layout']);
<add> expect(root).toMatchRenderedOutput(<span prop="Child" />);
<add>
<add> // Hide the tree. The layout effect is unmounted.
<add> await act(async () => {
<add> root.render(
<add> <Offscreen mode="hidden">
<add> <Child />
<add> </Offscreen>,
<add> );
<add> });
<add> expect(Scheduler).toHaveYielded(['Unmount layout', 'Child']);
<add>
<add> // After the layout effect is unmounted, the child is hidden.
<add> expect(root).toMatchRenderedOutput(<span hidden={true} prop="Child" />);
<add> });
<add>
<ide> // @gate www
<ide> it('does not toggle effects for LegacyHidden component', async () => {
<ide> // LegacyHidden is meant to be the same as offscreen except it doesn't
<ide><path>packages/shared/ReactFeatureFlags.js
<ide> export const skipUnmountedBoundaries = true;
<ide> //
<ide> // TODO: Finish rolling out in www
<ide> export const enableSuspenseLayoutEffectSemantics = true;
<del>export const enableFlipOffscreenUnhideOrder = false;
<add>export const enableFlipOffscreenUnhideOrder = true;
<ide>
<ide> // TODO: Finish rolling out in www
<ide> export const enableClientRenderFallbackOnTextMismatch = true; | 2 |
PHP | PHP | fix file_map being regenerated on every request | b6caddcf49967a3ce289178d156645a691b1dfff | <ide><path>lib/Cake/bootstrap.php
<ide> App::uses('Object', 'Core');
<ide> App::uses('Multibyte', 'I18n');
<ide>
<add>App::$bootstrapping = true;
<add>
<ide> /**
<ide> * Full URL prefix
<ide> */
<ide> Configure::write('App.cssBaseUrl', CSS_URL);
<ide> Configure::write('App.jsBaseUrl', JS_URL);
<ide>
<del>App::$bootstrapping = true;
<del>
<ide> Configure::bootstrap(isset($boot) ? $boot : true);
<ide>
<ide> if (function_exists('mb_internal_encoding')) { | 1 |
Ruby | Ruby | call puts once instead of problems.size + 2 times | b6631b9a150250c2f381912d3bd360ae1d72974c | <ide><path>Library/Homebrew/cmd/audit.rb
<ide> def audit
<ide> fa.audit
<ide>
<ide> unless fa.problems.empty?
<del> puts "#{f.name}:"
<del> fa.problems.each { |p| puts " * #{p}" }
<del> puts
<ide> formula_count += 1
<ide> problem_count += fa.problems.size
<add> puts "#{f.name}:", fa.problems.map { |p| " * #{p}" }, ""
<ide> end
<ide> end
<ide>
<ide> def audit_deps
<ide> next if dep.build? or dep.run?
<ide> problem %{#{dep} dependency should be "depends_on '#{dep}' => :build"}
<ide> when "git", "ruby", "mercurial"
<del> problem <<-EOS.undent
<del> Don't use #{dep} as a dependency. We allow non-Homebrew
<del> #{dep} installations.
<del> EOS
<add> problem "Don't use #{dep} as a dependency. We allow non-Homebrew #{dep} installations."
<ide> when 'gfortran'
<ide> problem "Use `depends_on :fortran` instead of `depends_on 'gfortran'`"
<ide> when 'open-mpi', 'mpich2' | 1 |
Java | Java | improve jetty 10 check on client-side | 94f56a2684a3f23cc0b64d93ee6e24acdbfca91f | <ide><path>spring-web/src/main/java/org/springframework/http/client/reactive/JettyClientHttpResponse.java
<ide> import org.springframework.http.ResponseCookie;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<del>import org.springframework.util.ClassUtils;
<ide> import org.springframework.util.CollectionUtils;
<ide> import org.springframework.util.LinkedMultiValueMap;
<ide> import org.springframework.util.MultiValueMap;
<ide> class JettyClientHttpResponse implements ClientHttpResponse {
<ide>
<ide> private static final ClassLoader loader = JettyClientHttpResponse.class.getClassLoader();
<ide>
<del> private static final boolean jetty10Present = ClassUtils.isPresent(
<del> "org.eclipse.jetty.websocket.server.JettyWebSocketServerContainer", loader);
<add> private static final boolean jetty10Present;
<ide>
<ide>
<ide> private final ReactiveResponse reactiveResponse;
<ide> class JettyClientHttpResponse implements ClientHttpResponse {
<ide> private final HttpHeaders headers;
<ide>
<ide>
<add> static {
<add> try {
<add> Class<?> httpFieldsClass = loader.loadClass("org.eclipse.jetty.http.HttpFields");
<add> jetty10Present = httpFieldsClass.isInterface();
<add> }
<add> catch (ClassNotFoundException ex) {
<add> throw new IllegalStateException("No compatible Jetty version found", ex);
<add> }
<add> }
<add>
<add>
<ide> public JettyClientHttpResponse(ReactiveResponse reactiveResponse, Publisher<DataBuffer> content) {
<ide> this.reactiveResponse = reactiveResponse;
<ide> this.content = Flux.from(content); | 1 |
Javascript | Javascript | fix rendertostaticmarkup invariant | 4d1bfcc8e153fec6180324fa79006bc1c351ebd9 | <ide><path>src/renderers/dom/server/ReactServerRendering.js
<ide> var invariant = require('invariant');
<ide> * @return {string} the HTML markup
<ide> */
<ide> function renderToStringImpl(element, makeStaticMarkup) {
<del> invariant(
<del> ReactElement.isValidElement(element),
<del> 'renderToString(): You must pass a valid ReactElement.'
<del> );
<del>
<ide> var transaction;
<ide> try {
<ide> ReactUpdates.injection.injectBatchingStrategy(ReactServerBatchingStrategy);
<ide> function renderToStringImpl(element, makeStaticMarkup) {
<ide> }
<ide>
<ide> function renderToString(element) {
<add> invariant(
<add> ReactElement.isValidElement(element),
<add> 'renderToString(): You must pass a valid ReactElement.'
<add> );
<ide> return renderToStringImpl(element, false);
<ide> }
<ide>
<ide> function renderToStaticMarkup(element) {
<add> invariant(
<add> ReactElement.isValidElement(element),
<add> 'renderToStaticMarkup(): You must pass a valid ReactElement.'
<add> );
<ide> return renderToStringImpl(element, true);
<ide> }
<ide>
<ide><path>src/renderers/dom/server/__tests__/ReactServerRendering-test.js
<ide> describe('ReactServerRendering', function() {
<ide> 'not a component'
<ide> )
<ide> ).toThrow(
<del> 'renderToString(): You must pass a valid ReactElement.'
<add> 'renderToStaticMarkup(): You must pass a valid ReactElement.'
<ide> );
<ide> });
<ide> | 2 |
PHP | PHP | apply fixes from styleci | 59cf9c7bf2ba8e11b8f8ba5f48646d05c2630038 | <ide><path>tests/Http/Middleware/CacheTest.php
<ide> public function testDoNotSetHeaderWhenNoContent()
<ide>
<ide> public function testSetHeaderToFileEvenWithNoContent()
<ide> {
<del> $response = (new Cache)->handle(new Request, function () {
<add> $response = (new Cache)->handle(new Request, function () {
<ide> $filePath = __DIR__.'/../fixtures/test.txt';
<add>
<ide> return new BinaryFileResponse($filePath);
<ide> }, 'max_age=120;s_maxage=60');
<ide> | 1 |
PHP | PHP | normalize test results across windows and unix | 4dcb2ee46dcc2382cb11cd28d773a0ca4582e58d | <ide><path>tests/Routing/RoutingControllerGeneratorTest.php
<ide> public function testFullControllerCanBeCreated()
<ide> {
<ide> $gen = new ControllerGenerator($files = m::mock('Illuminate\Filesystem\Filesystem[put]'));
<ide> $controller = file_get_contents(__DIR__.'/fixtures/controller.php');
<del> $files->shouldReceive('put')->once()->with(__DIR__.'/FooController.php', $controller);
<add> $files->shouldReceive('put')->once()->andReturnUsing(function($path, $actual)
<add> {
<add> $_SERVER['__controller.actual'] = $actual;
<add> });
<ide> $gen->make('FooController', __DIR__);
<add>
<add> $controller = preg_replace('/\s+/', '', $controller);
<add> $actual = preg_replace('/\s+/', '', $_SERVER['__controller.actual']);
<add> $this->assertEquals($controller, $actual);
<ide> }
<ide>
<ide>
<ide> public function testOnlyPartialControllerCanBeCreated()
<ide> {
<ide> $gen = new ControllerGenerator($files = m::mock('Illuminate\Filesystem\Filesystem[put]'));
<ide> $controller = file_get_contents(__DIR__.'/fixtures/only_controller.php');
<del> $files->shouldReceive('put')->once()->with(__DIR__.'/FooController.php', $controller);
<add> $files->shouldReceive('put')->once()->andReturnUsing(function($path, $actual)
<add> {
<add> $_SERVER['__controller.actual'] = $actual;
<add> });
<ide> $gen->make('FooController', __DIR__, array('only' => array('index', 'show')));
<add>
<add> $controller = preg_replace('/\s+/', '', $controller);
<add> $actual = preg_replace('/\s+/', '', $_SERVER['__controller.actual']);
<add> $this->assertEquals($controller, $actual);
<ide> }
<ide>
<ide>
<ide> public function testExceptPartialControllerCanBeCreated()
<ide> {
<ide> $gen = new ControllerGenerator($files = m::mock('Illuminate\Filesystem\Filesystem[put]'));
<ide> $controller = file_get_contents(__DIR__.'/fixtures/except_controller.php');
<del> $files->shouldReceive('put')->once()->with(__DIR__.'/FooController.php', $controller);
<add> $files->shouldReceive('put')->once()->andReturnUsing(function($path, $actual)
<add> {
<add> $_SERVER['__controller.actual'] = $actual;
<add> });
<ide> $gen->make('FooController', __DIR__, array('except' => array('index', 'show')));
<add>
<add> $controller = preg_replace('/\s+/', '', $controller);
<add> $actual = preg_replace('/\s+/', '', $_SERVER['__controller.actual']);
<add> $this->assertEquals($controller, $actual);
<ide> }
<ide>
<ide> }
<ide>\ No newline at end of file | 1 |
Text | Text | specify version of sprockets-rails this will be in | b6b4d6980b815555ae17da5a8006590eb53ec264 | <ide><path>guides/source/asset_pipeline.md
<ide> all requests for assets include digests.
<ide>
<ide> ### Raise an Error When an Asset is Not Found
<ide>
<del>If you are using a recent version of sprockets-rails you can configure what happens
<add>If you are using sprockets-rails >= 3.2.0 you can configure what happens
<ide> when an asset lookup is performed and nothing is found. If you turn off "asset fallback"
<ide> then an error will be raised when an asset cannot be found.
<ide> | 1 |
PHP | PHP | correct doc blocks | 6c0c82f21c33d858e1e523d223ffcae73ebcd488 | <ide><path>Cake/ORM/Behavior.php
<ide> public function implementedEvents() {
<ide> *
<ide> * provides and alias->methodname map of which finders a behavior implements. Example:
<ide> *
<del> * [
<del> * 'this' => 'findThis',
<del> * 'alias' => 'findMethodName'
<del> * ]
<add> * {{{
<add> * [
<add> * 'this' => 'findThis',
<add> * 'alias' => 'findMethodName'
<add> * ]
<add> * }}}
<ide> *
<ide> * With the above example, a call to `$Table->find('this')` will call `$Behavior->findThis()`
<ide> * and a call to `$Table->find('alias')` will call `$Behavior->findMethodName()`
<ide> public function implementedFinders() {
<ide> /**
<ide> * implementedMethods
<ide> *
<del> * provides and alias->methodname map of which methods a behavior implements. Example:
<add> * provides an alias->methodname map of which methods a behavior implements. Example:
<ide> *
<del> * [
<del> * 'method' => 'method',
<del> * 'aliasedmethod' => 'somethingElse'
<del> * ]
<add> * {{{
<add> * [
<add> * 'method' => 'method',
<add> * 'aliasedmethod' => 'somethingElse'
<add> * ]
<add> * }}}
<ide> *
<ide> * With the above example, a call to `$Table->method()` will call `$Behavior->method()`
<ide> * and a call to `$Table->aliasedmethod()` will call `$Behavior->somethingElse()` | 1 |
Ruby | Ruby | add xcode 6.4 expectation | 0d12e4e601c90a9e100aa6fd9d2ea9f8e1fdc2ab | <ide><path>Library/Homebrew/os/mac.rb
<ide> def preferred_arch
<ide> "6.3" => { :clang => "6.1", :clang_build => 602 },
<ide> "6.3.1" => { :clang => "6.1", :clang_build => 602 },
<ide> "6.3.2" => { :clang => "6.1", :clang_build => 602 },
<add> "6.4" => { :clang => "6.1", :clang_build => 602 },
<ide> "7.0" => { :clang => "7.0", :clang_build => 700 },
<ide> }
<ide> | 1 |
Text | Text | update python name in index.md | e9c01989175872975151c685570b0eaa56e36221 | <ide><path>guide/spanish/nodejs/index.md
<ide> import time
<ide>
<ide> **Node.js**
<ide>
<del>```node
<add>```js
<ide> function my_io_task() {
<ide> setTimeout(function() {
<ide> console.log('done'); | 1 |
Mixed | Ruby | fix incorrect assert_redirected_to failure message | 1dacfbabf3bb1e0a9057dd2a016b1804e7fa38c0 | <ide><path>actionpack/CHANGELOG.md
<add>* Fix incorrect `assert_redirected_to` failure message for protocol-relative
<add> URLs.
<add>
<add> *Derek Prior*
<add>
<ide> * Fix an issue where router can't recognize downcased url encoding path.
<ide>
<ide> Fixes #12269
<ide><path>actionpack/lib/action_controller/metal/redirecting.rb
<ide> def redirect_to(options = {}, response_status = {}) #:doc:
<ide> self.response_body = "<html><body>You are being <a href=\"#{ERB::Util.h(location)}\">redirected</a>.</body></html>"
<ide> end
<ide>
<add> def _compute_redirect_to_location(options) #:nodoc:
<add> case options
<add> # The scheme name consist of a letter followed by any combination of
<add> # letters, digits, and the plus ("+"), period ("."), or hyphen ("-")
<add> # characters; and is terminated by a colon (":").
<add> # See http://tools.ietf.org/html/rfc3986#section-3.1
<add> # The protocol relative scheme starts with a double slash "//".
<add> when %r{\A(\w[\w+.-]*:|//).*}
<add> options
<add> when String
<add> request.protocol + request.host_with_port + options
<add> when :back
<add> request.headers["Referer"] or raise RedirectBackError
<add> when Proc
<add> _compute_redirect_to_location options.call
<add> else
<add> url_for(options)
<add> end.delete("\0\r\n")
<add> end
<add>
<ide> private
<ide> def _extract_redirect_to_status(options, response_status)
<ide> if options.is_a?(Hash) && options.key?(:status)
<ide> def _extract_redirect_to_status(options, response_status)
<ide> 302
<ide> end
<ide> end
<del>
<del> def _compute_redirect_to_location(options)
<del> case options
<del> # The scheme name consist of a letter followed by any combination of
<del> # letters, digits, and the plus ("+"), period ("."), or hyphen ("-")
<del> # characters; and is terminated by a colon (":").
<del> # The protocol relative scheme starts with a double slash "//"
<del> when %r{\A(\w[\w+.-]*:|//).*}
<del> options
<del> when String
<del> request.protocol + request.host_with_port + options
<del> when :back
<del> request.headers["Referer"] or raise RedirectBackError
<del> when Proc
<del> _compute_redirect_to_location options.call
<del> else
<del> url_for(options)
<del> end.delete("\0\r\n")
<del> end
<ide> end
<ide> end
<ide><path>actionpack/lib/action_dispatch/testing/assertions/response.rb
<ide> def parameterize(value)
<ide> end
<ide>
<ide> def normalize_argument_to_redirection(fragment)
<del> normalized = case fragment
<del> when Regexp
<del> fragment
<del> when %r{^\w[A-Za-z\d+.-]*:.*}
<del> fragment
<del> when String
<del> @request.protocol + @request.host_with_port + fragment
<del> when :back
<del> raise RedirectBackError unless refer = @request.headers["Referer"]
<del> refer
<del> else
<del> @controller.url_for(fragment)
<del> end
<del>
<del> normalized.respond_to?(:delete) ? normalized.delete("\0\r\n") : normalized
<add> if Regexp === fragment
<add> fragment
<add> else
<add> @controller._compute_redirect_to_location(fragment)
<add> end
<ide> end
<ide> end
<ide> end
<ide><path>actionpack/test/controller/action_pack_assertions_test.rb
<ide> def redirect_to_named_route() redirect_to route_one_url end
<ide>
<ide> def redirect_external() redirect_to "http://www.rubyonrails.org"; end
<ide>
<add> def redirect_external_protocol_relative() redirect_to "//www.rubyonrails.org"; end
<add>
<ide> def response404() head '404 AWOL' end
<ide>
<ide> def response500() head '500 Sorry' end
<ide> def test_assert_redirected_to_top_level_named_route_with_same_controller_name_in
<ide> end
<ide> end
<ide>
<add> def test_assert_redirect_failure_message_with_protocol_relative_url
<add> begin
<add> process :redirect_external_protocol_relative
<add> assert_redirected_to "/foo"
<add> rescue ActiveSupport::TestCase::Assertion => ex
<add> assert_no_match(
<add> /#{request.protocol}#{request.host}\/\/www.rubyonrails.org/,
<add> ex.message,
<add> 'protocol relative url was incorrectly normalized'
<add> )
<add> end
<add> end
<add>
<ide> def test_template_objects_exist
<ide> process :assign_this
<ide> assert !@controller.instance_variable_defined?(:"@hi")
<ide> def test_redirection_location
<ide>
<ide> process :redirect_external
<ide> assert_equal 'http://www.rubyonrails.org', @response.redirect_url
<add>
<add> process :redirect_external_protocol_relative
<add> assert_equal '//www.rubyonrails.org', @response.redirect_url
<ide> end
<ide>
<ide> def test_no_redirect_url | 4 |
Ruby | Ruby | enforce https for apache.org | 02cb05f22b4e66536409cd90dd7253d8ac7cd07d | <ide><path>Library/Homebrew/cmd/audit.rb
<ide> def audit_urls
<ide> problem "Github Pages links should be https:// (URL is #{homepage})."
<ide> end
<ide>
<add> if homepage =~ %r[^http://[^/]*\.apache\.org/]
<add> problem "Apache homepages should be https:// links (URL is #{homepage})."
<add> end
<add>
<ide> # There's an auto-redirect here, but this mistake is incredibly common too.
<ide> # Only applies to the homepage and subdomains for now, not the FTP links.
<ide> if homepage =~ %r[^http://((?:build|cloud|developer|download|extensions|git|glade|help|library|live|nagios|news|people|projects|rt|static|wiki|www)\.)?gnome\.org]
<ide> def audit_urls
<ide> case p
<ide> when %r[^http://ftp\.gnu\.org/]
<ide> problem "ftp.gnu.org urls should be https://, not http:// (url is #{p})."
<del> when %r[^http://archive\.apache\.org/]
<del> problem "archive.apache.org urls should be https://, not http (url is #{p})."
<add> when %r[^http://[^/]*\.apache\.org/]
<add> problem "Apache urls should be https://, not http (url is #{p})."
<ide> when %r[^http://code\.google\.com/]
<ide> problem "code.google.com urls should be https://, not http (url is #{p})."
<ide> when %r[^http://fossies\.org/] | 1 |
Python | Python | add check for empty openssl-fips flag | f9b129ec6ba49cb3c6bfc135e470ec1008aade0f | <ide><path>configure.py
<ide> def without_ssl_error(option):
<ide> if options.openssl_no_asm and options.shared_openssl:
<ide> error('--openssl-no-asm is incompatible with --shared-openssl')
<ide>
<del> if options.openssl_fips:
<add> if options.openssl_fips or options.openssl_fips == '':
<ide> error('FIPS is not supported in this version of Node.js')
<ide>
<ide> configure_library('openssl', o) | 1 |
Text | Text | remove reference to io.js | 4079bfd462f129fc2384d1780793baf33c853a60 | <ide><path>doc/api/process.md
<ide> tarball.
<ide>
<ide> `process.release` contains the following properties:
<ide>
<del>* `name` {string} A value that will always be `'node'` for Node.js. For
<del> legacy io.js releases, this will be `'io.js'`.
<add>* `name` {string} A value that will always be `'node'`.
<ide> * `sourceUrl` {string} an absolute URL pointing to a _`.tar.gz`_ file containing
<ide> the source code of the current release.
<ide> * `headersUrl`{string} an absolute URL pointing to a _`.tar.gz`_ file containing | 1 |
Ruby | Ruby | add namespace for test_unit generators | 49c3ad7f7782274504fbe0818b9636d2b362a1a3 | <ide><path>railties/lib/rails/generators/test_unit/controller/templates/functional_test.rb
<ide> require 'test_helper'
<ide>
<add><% module_namespacing do -%>
<ide> class <%= class_name %>ControllerTest < ActionController::TestCase
<ide> <% if actions.empty? -%>
<ide> # Replace this with your real tests.
<ide> class <%= class_name %>ControllerTest < ActionController::TestCase
<ide> <% end -%>
<ide> <% end -%>
<ide> end
<add><% end -%>
<ide><path>railties/lib/rails/generators/test_unit/helper/templates/helper_test.rb
<ide> require 'test_helper'
<ide>
<add><% module_namespacing do -%>
<ide> class <%= class_name %>HelperTest < ActionView::TestCase
<ide> end
<add><% end -%>
<ide><path>railties/lib/rails/generators/test_unit/model/templates/unit_test.rb
<ide> require 'test_helper'
<ide>
<add><% module_namespacing do -%>
<ide> class <%= class_name %>Test < ActiveSupport::TestCase
<ide> # Replace this with your real tests.
<ide> test "the truth" do
<ide> assert true
<ide> end
<ide> end
<add><% end -%>
<ide><path>railties/test/generators/namespaced_generators_test.rb
<ide> class NamespacedControllerGeneratorTest < NamespacedGeneratorTestCase
<ide> def test_namespaced_controller_skeleton_is_created
<ide> run_generator
<ide> assert_file "app/controllers/test_app/account_controller.rb", /module TestApp/, / class AccountController < ApplicationController/
<del> assert_file "test/functional/test_app/account_controller_test.rb", /TestApp::AccountController/
<add> assert_file "test/functional/test_app/account_controller_test.rb", /module TestApp/, / class AccountControllerTest/
<ide> end
<ide>
<ide> def test_skipping_namespace
<ide> def test_namespaced_controller_with_additional_namespace
<ide> def test_helpr_is_also_namespaced
<ide> run_generator
<ide> assert_file "app/helpers/test_app/account_helper.rb", /module TestApp/, / module AccountHelper/
<del> assert_file "test/unit/helpers/test_app/account_helper_test.rb", /TestApp::AccountHelper/
<add> assert_file "test/unit/helpers/test_app/account_helper_test.rb", /module TestApp/, / class AccountHelperTest/
<ide> end
<ide>
<ide> def test_invokes_default_test_framework
<ide> def test_migration_with_nested_namespace_without_pluralization
<ide>
<ide> def test_invokes_default_test_framework
<ide> run_generator
<del> assert_file "test/unit/test_app/account_test.rb", /class TestApp::AccountTest < ActiveSupport::TestCase/
<add> assert_file "test/unit/test_app/account_test.rb", /module TestApp/, /class AccountTest < ActiveSupport::TestCase/
<ide> assert_file "test/fixtures/test_app/accounts.yml", /name: MyString/, /age: 1/
<ide> end
<ide> end | 4 |
Javascript | Javascript | use the expected import | 3f5737eccd801f3f76fc42582d270900f82c05dc | <ide><path>examples/api-routes-apollo-server-and-client-auth/lib/user.js
<ide> import crypto from 'crypto'
<del>import uuidv4 from 'uuid/v4'
<add>import { v4 as uuidv4 } from 'uuid'
<ide>
<ide> /**
<ide> * User methods. The example doesn't contain a DB, but for real applications you must use a | 1 |
Javascript | Javascript | remove invalid part of stream2-stderr-sync | c1bb88699058011cce8df12a5cf39354666f6ab2 | <ide><path>test/simple/test-stream2-stderr-sync.js
<ide> function parent() {
<ide> });
<ide> }
<ide>
<del>function child0() {
<del> // Just a very simple wrapper around TTY(2)
<del> // Essentially the same as stderr, but without all the net stuff.
<del> var Writable = require('stream').Writable;
<del> var util = require('util');
<del>
<del> // a lowlevel stderr writer
<del> var TTY = process.binding('tty_wrap').TTY;
<del> var handle = new TTY(2, false);
<del>
<del> util.inherits(W, Writable);
<del>
<del> function W(opts) {
<del> Writable.call(this, opts);
<del> }
<del>
<del> W.prototype._write = function(chunk, encoding, cb) {
<del> var req = { oncomplete: afterWrite };
<del> var err = handle.writeUtf8String(req, chunk.toString() + '\n');
<del> if (err) throw errnoException(err, 'write');
<del> // here's the problem.
<del> // it needs to tell the Writable machinery that it's ok to write
<del> // more, but that the current buffer length is handle.writeQueueSize
<del> if (req.writeQueueSize === 0)
<del> req.cb = cb;
<del> else
<del> cb();
<del> }
<del> function afterWrite(status, handle, req) {
<del> if (req.cb)
<del> req.cb();
<del> }
<del>
<del> var w = new W
<del> w.write('child 0');
<del> w.write('foo');
<del> w.write('bar');
<del> w.write('baz');
<del>}
<del>
<ide> // using console.error
<del>function child1() {
<del> console.error('child 1');
<add>function child0() {
<add> console.error('child 0');
<ide> console.error('foo');
<ide> console.error('bar');
<ide> console.error('baz');
<ide> }
<ide>
<ide> // using process.stderr
<del>function child2() {
<del> process.stderr.write('child 2\n');
<add>function child1() {
<add> process.stderr.write('child 1\n');
<ide> process.stderr.write('foo\n');
<ide> process.stderr.write('bar\n');
<ide> process.stderr.write('baz\n');
<ide> }
<ide>
<ide> // using a net socket
<del>function child3() {
<add>function child2() {
<ide> var net = require('net');
<ide> var socket = new net.Socket({ fd: 2 });
<del> socket.write('child 3\n');
<add> socket.write('child 2\n');
<ide> socket.write('foo\n');
<ide> socket.write('bar\n');
<ide> socket.write('baz\n');
<ide> }
<ide>
<ide>
<del>function child4() {
<del> console.error('child 4\nfoo\nbar\nbaz');
<add>function child3() {
<add> console.error('child 3\nfoo\nbar\nbaz');
<ide> }
<ide>
<del>function child5() {
<del> process.stderr.write('child 5\nfoo\nbar\nbaz\n');
<add>function child4() {
<add> process.stderr.write('child 4\nfoo\nbar\nbaz\n');
<ide> }
<ide>
<del>var children = [ child0, child1, child2, child3, child4, child5 ];
<add>var children = [ child0, child1, child2, child3, child4 ];
<ide>
<ide> if (!process.argv[2]) {
<ide> parent(); | 1 |
Text | Text | update dead jsx link to point to an extant page | 8f55d94d407a445a6f27d007f20421210757d6b8 | <ide><path>docs/docs/tutorial.md
<ide> React.renderComponent(
<ide> );
<ide> ```
<ide>
<del>Its use is optional but we've found JSX syntax easier to use than plain JavaScript. Read more on the [JSX Syntax article](syntax.html).
<add>Its use is optional but we've found JSX syntax easier to use than plain JavaScript. Read more on the [JSX Syntax article](jsx-in-depth.html).
<ide>
<ide> #### What's going on
<ide> | 1 |
Text | Text | add s390 and ppc architecture labels | c659c9d2ab7e28072a007a006b75d3e7dbfa0e89 | <ide><path>doc/onboarding-extras.md
<ide> Please use these when possible / appropriate
<ide> ### Other Labels
<ide>
<ide> * Operating system labels
<del> * `os x`, `windows`, `solaris`
<add> * `os x`, `windows`, `solaris`, `aix`
<ide> * No linux, linux is the implied default
<ide> * Architecture labels
<del> * `arm`, `mips`
<add> * `arm`, `mips`, `s390`, `ppc`
<ide> * No x86{_64}, since that is the implied default
<ide> * `lts-agenda`, `lts-watch-v*`
<ide> * tag things that should be discussed to go into LTS or should go into a specific LTS branch | 1 |
Ruby | Ruby | pass the parsed path from mapper to the strexp | 333a4d09ab8b024b3d23618e9d668bef2bab1355 | <ide><path>actionpack/lib/action_dispatch/routing/mapper.rb
<ide> def initialize(set, scope, path, options)
<ide> path_params = path_params ast
<ide> @options = normalize_options!(options, path_params, ast)
<ide> normalize_requirements!(path_params)
<del> normalize_conditions!(path_params, path)
<add> normalize_conditions!(path_params, path, ast)
<ide> normalize_defaults!
<ide> end
<ide>
<ide> def verify_callable_constraint(callable_constraint)
<ide> end
<ide> end
<ide>
<del> def normalize_conditions!(path_params, path)
<add> def normalize_conditions!(path_params, path, ast)
<ide> @conditions[:path_info] = path
<add> @conditions[:parsed_path_info] = ast
<ide>
<ide> constraints.each do |key, condition|
<ide> unless path_params.include?(key) || key == :controller
<ide><path>actionpack/lib/action_dispatch/routing/route_set.rb
<ide> def add_route(app, conditions = {}, requirements = {}, defaults = {}, name = nil
<ide> "http://guides.rubyonrails.org/routing.html#restricting-the-routes-created"
<ide> end
<ide>
<del> path = build_path(conditions.delete(:path_info), requirements, SEPARATORS, anchor)
<add> path = conditions.delete :path_info
<add> ast = conditions.delete :parsed_path_info
<add> path = build_path(path, ast, requirements, SEPARATORS, anchor)
<ide> conditions = build_conditions(conditions, path.names.map { |x| x.to_sym })
<ide>
<ide> route = @set.add_route(app, path, conditions, defaults, name)
<ide> named_routes[name] = route if name
<ide> route
<ide> end
<ide>
<del> def build_path(path, requirements, separators, anchor)
<del> strexp = Journey::Router::Strexp.build(
<add> def build_path(path, ast, requirements, separators, anchor)
<add> strexp = Journey::Router::Strexp.new(
<add> ast,
<ide> path,
<ide> requirements,
<ide> SEPARATORS, | 2 |
PHP | PHP | fix connection binding | 85e114a3a7173232078571e2a54c8c56f2e8ff5c | <ide><path>src/Illuminate/Queue/QueueServiceProvider.php
<ide> protected function registerManager()
<ide>
<ide> $this->app->bindShared('queue.driver', function($app)
<ide> {
<del> return $app['queue']->driver();
<add> return $app['queue']->connection();
<ide> });
<ide> }
<ide> | 1 |
Go | Go | add testdaemonwithwrongkey test case | ef13dcd4dcbc613a9ea1e4a8af3d0220004ec0ab | <ide><path>integration-cli/docker_cli_daemon_test.go
<ide> func TestDaemonUnixSockCleanedUp(t *testing.T) {
<ide>
<ide> logDone("daemon - unix socket is cleaned up")
<ide> }
<add>
<add>func TestDaemonwithwrongkey(t *testing.T) {
<add> type Config struct {
<add> Crv string `json:"crv"`
<add> D string `json:"d"`
<add> Kid string `json:"kid"`
<add> Kty string `json:"kty"`
<add> X string `json:"x"`
<add> Y string `json:"y"`
<add> }
<add>
<add> os.Remove("/etc/docker/key.json")
<add> d := NewDaemon(t)
<add> if err := d.Start(); err != nil {
<add> t.Fatalf("Failed to start daemon: %v", err)
<add> }
<add>
<add> if err := d.Stop(); err != nil {
<add> t.Fatalf("Could not stop daemon: %v", err)
<add> }
<add>
<add> config := &Config{}
<add> bytes, err := ioutil.ReadFile("/etc/docker/key.json")
<add> if err != nil {
<add> t.Fatalf("Error reading key.json file: %s", err)
<add> }
<add>
<add> // byte[] to Data-Struct
<add> if err := json.Unmarshal(bytes, &config); err != nil {
<add> t.Fatalf("Error Unmarshal: %s", err)
<add> }
<add>
<add> //replace config.Kid with the fake value
<add> config.Kid = "VSAJ:FUYR:X3H2:B2VZ:KZ6U:CJD5:K7BX:ZXHY:UZXT:P4FT:MJWG:HRJ4"
<add>
<add> // NEW Data-Struct to byte[]
<add> newBytes, err := json.Marshal(&config)
<add> if err != nil {
<add> t.Fatalf("Error Marshal: %s", err)
<add> }
<add>
<add> // write back
<add> if err := ioutil.WriteFile("/etc/docker/key.json", newBytes, 0400); err != nil {
<add> t.Fatalf("Error ioutil.WriteFile: %s", err)
<add> }
<add>
<add> d1 := NewDaemon(t)
<add>
<add> if err := d1.Start(); err == nil {
<add> d1.Stop()
<add> t.Fatalf("It should not be succssful to start daemon with wrong key: %v", err)
<add> }
<add>
<add> content, _ := ioutil.ReadFile(d1.logFile.Name())
<add>
<add> if !strings.Contains(string(content), "Public Key ID does not match") {
<add> t.Fatal("Missing KeyID message from daemon logs")
<add> }
<add>
<add> os.Remove("/etc/docker/key.json")
<add> logDone("daemon - it should be failed to start daemon with wrong key")
<add>} | 1 |
Ruby | Ruby | use keyword argument | e8c26e2da9a4888a801045d1681c13d434837ef7 | <ide><path>Library/Homebrew/cmd/list.rb
<ide> def list
<ide> puts full_cask_names if full_cask_names.present?
<ide> end
<ide> elsif args.cask?
<del> list_casks(args.named.to_casks, args)
<add> list_casks(args.named.to_casks, args: args)
<ide> elsif args.pinned? || args.versions?
<ide> filtered_list args: args
<ide> elsif args.no_named?
<ide> def list
<ide> formula_names, cask_names = args.named.to_formulae_to_casks(method: :default_kegs)
<ide>
<ide> formula_names.each { |keg| PrettyListing.new keg } if formula_names.present?
<del> list_casks(cask_names, args) if cask_names.present?
<add> list_casks(cask_names, args: args) if cask_names.present?
<ide> end
<ide> end
<ide>
<ide> def filtered_list(args:)
<ide> end
<ide> end
<ide>
<del> def list_casks(casks, args)
<add> def list_casks(casks, args:)
<ide> Cask::Cmd::List.list_casks(
<ide> *casks,
<ide> one: args.public_send(:"1?"), | 1 |
Javascript | Javascript | add failing test for protected attrs with no value | 32746fb694bfd70ca1f36bc6c0bdaafe78b43e36 | <ide><path>tests/node/component-rendering-test.js
<ide> QUnit.test("Component with dynamic value", function(assert) {
<ide> assert.ok(html.match(/<h1>Hello World<\/h1>/));
<ide> });
<ide>
<add>QUnit.test("Ensure undefined attributes requiring protocol sanitization do not error", function(assert) {
<add> var component = buildComponent('', {
<add> tagName: 'link',
<add> attributeBindings: ['href', 'rel'],
<add> rel: 'canonical'
<add> });
<add>
<add> var html = renderComponent(component);
<add> assert.ok(html.match(/rel="canonical"/));
<add>});
<add>
<ide> function buildComponent(template, props) {
<ide> var Component = Ember.Component.extend({
<ide> renderer: new Ember._Renderer(new DOMHelper(new SimpleDOM.Document())), | 1 |
Python | Python | prepare test/pseudo-tty/testcfg.py for python 3 | 6028f70a0a3c8b8ce527e682d9284f68dce9e091 | <ide><path>test/pseudo-tty/testcfg.py
<ide> import re
<ide> import utils
<ide>
<add>try:
<add> xrange # Python 2
<add>except NameError:
<add> xrange = range # Python 3
<add>
<ide> FLAGS_PATTERN = re.compile(r"//\s+Flags:(.*)")
<ide>
<ide> class TTYTestCase(test.TestCase):
<ide> def IgnoreLine(self, str):
<ide> else: return str.startswith('==') or str.startswith('**')
<ide>
<ide> def IsFailureOutput(self, output):
<del> f = file(self.expected)
<add> f = open(self.expected)
<ide> # Convert output lines to regexps that we can match
<ide> env = { 'basename': basename(self.file) }
<ide> patterns = [ ] | 1 |
Go | Go | remove hack for downgrading docker 1.7 to 1.6 | 0abd7ba22998e2ad00091c4ddc0f9ea28625adfe | <ide><path>volume/local/local.go
<ide> import (
<ide> "github.com/sirupsen/logrus"
<ide> )
<ide>
<del>// VolumeDataPathName is the name of the directory where the volume data is stored.
<del>// It uses a very distinctive name to avoid collisions migrating data between
<del>// Docker versions.
<ide> const (
<del> VolumeDataPathName = "_data"
<add> // volumeDataPathName is the name of the directory where the volume data is stored.
<add> // It uses a very distinctive name to avoid collisions migrating data between
<add> // Docker versions.
<add> volumeDataPathName = "_data"
<ide> volumesPathName = "volumes"
<ide> )
<ide>
<ide> func (r *Root) List() ([]volume.Volume, error) {
<ide>
<ide> // DataPath returns the constructed path of this volume.
<ide> func (r *Root) DataPath(volumeName string) string {
<del> return filepath.Join(r.path, volumeName, VolumeDataPathName)
<add> return filepath.Join(r.path, volumeName, volumeDataPathName)
<ide> }
<ide>
<ide> // Name returns the name of Root, defined in the volume package in the DefaultDriverName constant.
<ide><path>volume/local/local_unix.go
<ide> import (
<ide> )
<ide>
<ide> var (
<del> oldVfsDir = filepath.Join("vfs", "dir")
<del>
<ide> validOpts = map[string]struct{}{
<ide> "type": {}, // specify the filesystem type for mount, e.g. nfs
<ide> "o": {}, // generic mount options
<ide> func (o *optsConfig) String() string {
<ide> // scopedPath verifies that the path where the volume is located
<ide> // is under Docker's root and the valid local paths.
<ide> func (r *Root) scopedPath(realPath string) bool {
<del> // Volumes path for Docker version >= 1.7
<ide> if strings.HasPrefix(realPath, filepath.Join(r.scope, volumesPathName)) && realPath != filepath.Join(r.scope, volumesPathName) {
<ide> return true
<ide> }
<del>
<del> // Volumes path for Docker version < 1.7
<del> if strings.HasPrefix(realPath, filepath.Join(r.scope, oldVfsDir)) {
<del> return true
<del> }
<del>
<ide> return false
<ide> }
<ide> | 2 |
Ruby | Ruby | add appcast to checkable cask urls | bf03893227dd7602d14852ff4dd34325dd4840df | <ide><path>Library/Homebrew/livecheck/livecheck.rb
<ide> def checkable_formula_urls(formula)
<ide>
<ide> def checkable_cask_urls(cask)
<ide> urls = []
<add> urls << cask.appcast.to_s if cask.appcast
<ide> urls << cask.url.to_s
<ide> urls << cask.homepage if cask.homepage
<ide> urls.compact | 1 |
Javascript | Javascript | fix typo in description of selectedindex prop | 3834cb5f6819c862504515219dea3a268323af9e | <ide><path>Libraries/Components/SegmentedControlIOS/SegmentedControlIOS.ios.js
<ide> type Event = Object;
<ide> * #### Programmatically changing selected index
<ide> *
<ide> * The selected index can be changed on the fly by assigning the
<del> * selectIndex prop to a state variable, then changing that variable.
<add> * selectedIndex prop to a state variable, then changing that variable.
<ide> * Note that the state variable would need to be updated as the user
<ide> * selects a value and changes the index, as shown in the example below.
<ide> * | 1 |
Python | Python | add metric api changes | a47f5e231c51fe3f1e6212ca05a20286096bf2e0 | <ide><path>keras/backend/tensorflow_backend.py
<ide> def size(x, name=None):
<ide> ```
<ide>
<ide> """
<add> if is_symbolic(x):
<add> with get_graph().as_default():
<add> return tf.size(x)
<ide> return tf.size(x, name=name)
<ide>
<ide>
<ide><path>keras/engine/base_layer.py
<ide> def __init__(self, **kwargs):
<ide> self._per_input_updates = {}
<ide> self._built = False
<ide>
<add> # A list of metric instances corresponding to the metric tensors added using
<add> # the `add_metric` API.
<add> self._metrics = []
<add>
<ide> # These lists will be filled via successive calls
<ide> # to self._add_inbound_node().
<ide> self._inbound_nodes = []
<ide> def output_shape(self):
<ide> 'Use `get_output_shape_at(node_index)` '
<ide> 'instead.')
<ide>
<add> @property
<add> def metrics(self):
<add> return self._metrics
<add>
<add> def add_metric(self, value, name=None):
<add> """Adds metric tensor to the layer.
<add>
<add> # Arguments
<add> value: Metric tensor.
<add> name: String metric name.
<add> """
<add> match = self._get_existing_metric(name)
<add> if match:
<add> return
<add> if hasattr(value, '_metric_obj'):
<add> # We track the instance using the metadata on the result tensor.
<add> # Use case: model.add_metric(metrics.Mean(name='metric_2')(y))
<add> self._metrics.append(value._metric_obj)
<add> else:
<add> # Use cases: model.add_metric(K.sum(y), name='metric_1')
<add> metric_obj = _create_mean_metric(value, name)
<add> self._metrics.append(metric_obj)
<add>
<ide> def add_loss(self, losses, inputs=None):
<ide> """Adds losses to the layer.
<ide>
<ide> def count_params(self):
<ide> self.name + '.build(batch_input_shape)`.')
<ide> return count_params(self.weights)
<ide>
<add> def _get_existing_metric(self, name=None):
<add> match = [m for m in self._metrics if m.name == name]
<add> if not match:
<add> return
<add> if len(match) > 1:
<add> raise ValueError(
<add> 'Please provide different names for the metrics you have added. '
<add> 'We found {} metrics with the name: "{}"'.format(len(match), name))
<add> return match[0]
<add>
<add>
<add>def _create_mean_metric(value, name=None):
<add> from .. import metrics
<add> metric_obj = metrics.Mean(name=name)
<add> _call_metric(metric_obj, value)
<add> return metric_obj
<add>
<add>@K.symbolic
<add>def _call_metric(metric_obj, *args, **kwargs):
<add> update_op = metric_obj.update_state(*args, **kwargs)
<add> with K.control_dependencies(update_op): # For TF
<add> result_t = metric_obj.result()
<add>
<ide>
<ide> class InputSpec(object):
<ide> """Specifies the ndim, dtype and shape of every input to a layer.
<ide><path>keras/engine/network.py
<ide> def _base_init(self, name=None, trainable=True, dtype=None):
<ide> self._per_input_losses = {}
<ide> self._per_input_updates = {}
<ide>
<add> # A list of metric instances corresponding to the metric tensors added using
<add> # the `add_metric` API.
<add> self._metrics = []
<add>
<ide> # All layers in order of horizontal graph traversal.
<ide> # Entries are unique. Includes input and output layers.
<ide> self._layers = []
<ide> def __setattr__(self, name, value):
<ide> self._layers.append(value)
<ide> super(Network, self).__setattr__(name, value)
<ide>
<add> # Keep track of metric instance created in subclassed model/layer.
<add> # We do this so that we can maintain the correct order of metrics by adding
<add> # the instance to the `metrics` list as soon as it is created.
<add> from .. import metrics as metrics_module
<add> if isinstance(value, metrics_module.Metric):
<add> self._metrics.append(value)
<add>
<ide> @property
<ide> def layers(self):
<ide> return self._layers
<ide>
<add> @property
<add> def metrics(self):
<add> metrics = self._metrics
<add> for l in self.layers:
<add> metrics += l.metrics
<add> return metrics
<add>
<ide> def get_layer(self, name=None, index=None):
<ide> """Retrieves a layer based on either its name (unique) or index.
<ide>
<ide><path>keras/engine/training.py
<ide> def compile(self, optimizer,
<ide> self._feed_output_names = []
<ide> self._feed_output_shapes = []
<ide> self._feed_loss_fns = []
<del> self._metric_updates = []
<ide>
<ide> # if loss function is None, then this output will be skipped during total
<ide> # loss calculation and feed targets preparation.
<ide> def metrics(self):
<ide> metrics = []
<ide> if self._is_compiled:
<ide> metrics += self._compile_metric_functions
<add> metrics.extend(self._metrics)
<add> metrics.extend(_get_metrics_from_layers(self._layers))
<ide> return metrics
<ide>
<ide> @property
<ide> def metrics_names(self):
<ide>
<ide> # Add compile metrics/weighted metrics' names to the metric names list.
<ide> metrics_names.extend([m.name for m in self._compile_metric_functions])
<add>
<add> # Add metric names from layers.
<add> for layer in self.layers:
<add> metrics_names += [m.name for m in layer._metrics]
<add> metrics_names += [m.name for m in self._metrics]
<ide> return metrics_names
<ide>
<ide> def reset_metrics(self):
<ide> def _make_train_function(self):
<ide> training_updates = self.optimizer.get_updates(
<ide> params=self._collected_trainable_weights,
<ide> loss=self.total_loss)
<del> updates = (self.updates +
<del> training_updates +
<del> self._metric_updates)
<add> updates = self.updates + training_updates
<ide>
<ide> metrics = self._get_training_eval_metrics()
<ide> metrics_tensors = [
<ide> m._call_result for m in metrics if hasattr(m, '_call_result')
<ide> ]
<add> metrics_updates = []
<add> for m in metrics:
<add> metrics_updates.extend(m.updates)
<ide>
<ide> # Gets loss and metrics. Updates weights at each call.
<ide> self.train_function = K.function(
<ide> inputs,
<ide> [self.total_loss] + metrics_tensors,
<del> updates=updates,
<add> updates=updates + metrics_updates,
<ide> name='train_function',
<ide> **self._function_kwargs)
<ide>
<ide> def _make_test_function(self):
<ide> metrics_tensors = [
<ide> m._call_result for m in metrics if hasattr(m, '_call_result')
<ide> ]
<add>
<add> metrics_updates = []
<add> for m in metrics:
<add> metrics_updates.extend(m.updates)
<add>
<ide> # Return loss and metrics, no gradient updates.
<ide> # Does update the network states.
<ide> self.test_function = K.function(
<ide> inputs,
<ide> [self.total_loss] + metrics_tensors,
<del> updates=self.state_updates + self._metric_updates,
<add> updates=self.state_updates + metrics_updates,
<ide> name='test_function',
<ide> **self._function_kwargs)
<ide>
<ide> def _prepare_total_loss(self, masks=None):
<ide>
<ide> if len(self.outputs) > 1:
<ide> update_ops = self._output_loss_metrics[i].update_state(output_loss)
<del> self._metric_updates += update_ops
<del> result = self._output_loss_metrics[i].result()
<del> self._output_loss_metrics[i]._call_result = result
<del>
<add> with K.control_dependencies(update_ops): # For TF
<add> self._output_loss_metrics[i].result()
<ide> if total_loss is None:
<ide> total_loss = loss_weight * output_loss
<ide> else:
<ide> def _handle_per_output_metrics(self,
<ide>
<ide> for metric_name, metric_fn in metrics_dict.items():
<ide> with K.name_scope(metric_name):
<del> metric_result, update_ops = training_utils.call_metric_function(
<add> training_utils.call_metric_function(
<ide> metric_fn, y_true, y_pred, weights=weights, mask=mask)
<del> self._metric_updates += update_ops
<ide>
<ide> def _handle_metrics(self,
<ide> outputs,
<ide> def predict_generator(self, generator,
<ide> workers=workers,
<ide> use_multiprocessing=use_multiprocessing,
<ide> verbose=verbose)
<add>
<add>
<add>def _get_metrics_from_layers(layers):
<add> """Returns list of metrics from the given layers.
<add> This will not include the `compile` metrics of a model layer.
<add>
<add> # Arguments
<add> layers: List of layers.
<add>
<add> # Returns
<add> List of metrics.
<add> """
<add> metrics = []
<add> for layer in layers:
<add> if isinstance(layer, Model):
<add> # We cannot call 'metrics' on the model because we do not want to
<add> # include the metrics that were added in compile API of a nested model.
<add> metrics.extend(layer._metrics)
<add> metrics.extend(_get_metrics_from_layers(layer.layers))
<add> else:
<add> metrics.extend(layer.metrics)
<add> return metrics
<ide><path>keras/engine/training_utils.py
<ide> def call_metric_function(metric_fn,
<ide>
<ide> if y_pred is not None:
<ide> update_ops = metric_fn.update_state(y_true, y_pred, sample_weight=weights)
<del> with K.control_dependencies(update_ops):
<del> result = metric_fn.result()
<add> with K.control_dependencies(update_ops): # For TF
<add> metric_fn.result()
<ide> else:
<ide> # `Mean` metric only takes a single value.
<ide> update_ops = metric_fn.update_state(y_true, sample_weight=weights)
<del> with K.control_dependencies(update_ops):
<del> result = metric_fn.result()
<del> return result, update_ops
<add> with K.control_dependencies(update_ops): # For TF
<add> metric_fn.result()
<ide><path>keras/metrics.py
<ide> def __new__(cls, *args, **kwargs):
<ide> metrics_utils.result_wrapper(obj.result), obj)
<ide> return obj
<ide>
<add> @K.symbolic
<ide> def __call__(self, *args, **kwargs):
<ide> """Accumulates statistics and then computes metric result value."""
<ide> if K.backend() != 'tensorflow':
<ide> raise RuntimeError(
<ide> 'Metric calling only supported with TensorFlow backend.')
<ide> update_op = self.update_state(*args, **kwargs)
<ide> with K.control_dependencies(update_op): # For TF
<del> return self.result()
<add> result_t = self.result()
<add>
<add> # We are adding the metric object as metadata on the result tensor.
<add> # This is required when we want to use a metric with `add_metric` API on
<add> # a Model/Layer in graph mode. This metric instance will later be used
<add> # to reset variable state after each epoch of training.
<add> # Example:
<add> # model = Model()
<add> # mean = Mean()
<add> # model.add_metric(mean(values), name='mean')
<add> result_t._metric_obj = self
<add> return result_t
<ide>
<ide> def get_config(self):
<ide> """Returns the serializable config of the metric."""
<ide><path>keras/utils/losses_utils.py
<ide> def broadcast_weights(values, sample_weight):
<ide> for i in range(weights_rank):
<ide> if (weights_shape[i] is not None and
<ide> values_shape[i] is not None and
<del> weights_shape[i] != values_shape[i]):
<add> weights_shape[i] != values_shape[i]):
<ide> # Cannot be broadcasted.
<ide> if weights_shape[i] != 1:
<ide> raise ValueError(
<ide><path>tests/keras/engine/test_training.py
<ide>
<ide> import keras
<ide> from keras import losses
<add>from keras import metrics
<ide> from keras.layers import Layer, Activation, Dense, Dropout, Conv2D, Concatenate
<ide> from keras.engine import Input
<ide> from keras.engine.training import Model
<ide> def call(self, inputs):
<ide> np.allclose(history.history['loss'], [1., 0.9, 0.8, 0.7, 0.6])
<ide>
<ide>
<add>def test_model_metrics_list():
<add>
<add> class LayerWithAddMetric(Layer):
<add>
<add> def __init__(self):
<add> super(LayerWithAddMetric, self).__init__()
<add> self.dense = keras.layers.Dense(1, kernel_initializer='ones')
<add>
<add> def __call__(self, inputs):
<add> outputs = self.dense(inputs)
<add> return outputs
<add>
<add> class LayerWithNestedAddMetricLayer(Layer):
<add>
<add> def __init__(self):
<add> super(LayerWithNestedAddMetricLayer, self).__init__()
<add> self.layer = LayerWithAddMetric()
<add>
<add> def call(self, inputs):
<add> outputs = self.layer(inputs)
<add> self.add_metric(K.sum(outputs), name='metric_4')
<add> return outputs
<add>
<add> x = Input(shape=(1,))
<add> y = LayerWithNestedAddMetricLayer()(x)
<add>
<add> model = keras.models.Model(x, y)
<add> model.add_metric(K.sum(y), name='metric_2')
<add> model.add_metric(metrics.Mean(name='metric_3')(y))
<add>
<add> model.compile(
<add> 'sgd',
<add> loss='mse',
<add> metrics=[metrics.MeanSquaredError('metric_1')])
<add>
<add> # Verify that the metrics added using `compile` and `add_metric` API are
<add> # included
<add> for m1, m2 in zip([m.name for m in model._compile_metrics], ['metric_1']):
<add> assert m1 == m2
<add>
<add> for m1, m2 in zip(
<add> [m.name for m in model.metrics],
<add> ['metric_1', 'metric_2', 'metric_3', 'metric_4']):
<add> assert m1 == m2
<add>
<add>
<add>def test_model_metrics_list_in_call():
<add>
<add> class TestModel(Model):
<add>
<add> def __init__(self):
<add> super(TestModel, self).__init__(name='test_model')
<add> self.dense1 = keras.layers.Dense(2)
<add>
<add> def call(self, x):
<add> self.add_metric(K.sum(x), name='metric_2')
<add> return self.dense1(x)
<add>
<add> model = TestModel()
<add> model.compile(
<add> loss='mse',
<add> optimizer='adam',
<add> metrics=[metrics.MeanSquaredError('metric_1')])
<add> x = np.ones(shape=(10, 1))
<add> y = np.ones(shape=(10, 2))
<add> model.fit(x, y, epochs=2, batch_size=5, validation_data=(x, y))
<add>
<add> # Verify that the metrics added using `compile` and `add_metric` API are
<add> # included
<add> for m1, m2 in zip([m.name for m in model._compile_metrics], ['metric_1']):
<add> assert m1 == m2
<add>
<add> for m1, m2 in zip(
<add> [m.name for m in model.metrics],
<add> ['metric_1', 'metric_2']):
<add> assert m1 == m2
<add>
<add>
<add>def test_duplicate_metric_name_in_add_metric():
<add>
<add> class TestModel(Model):
<add>
<add> def __init__(self):
<add> super(TestModel, self).__init__(name='test_model')
<add> self.dense1 = keras.layers.Dense(2, kernel_initializer='ones')
<add> self.mean = metrics.Mean(name='metric_1')
<add> self.mean2 = metrics.Mean(name='metric_1')
<add>
<add> def call(self, x):
<add> self.add_metric(self.mean(x), name='metric_1')
<add> return self.dense1(x)
<add>
<add> model = TestModel()
<add> model.compile(loss='mse', optimizer='adam')
<add>
<add> x = np.ones(shape=(10, 1))
<add> y = np.ones(shape=(10, 2))
<add> with pytest.raises(ValueError):
<add> model.fit(x, y, epochs=2, batch_size=5, validation_data=(x, y))
<add>
<add>
<add>def test_add_metric_on_model():
<add> x = Input(shape=(1,))
<add> y = Dense(1, kernel_initializer='ones', trainable=False)(x)
<add> model = Model(x, y)
<add> model.add_metric(K.sum(y), name='metric_1')
<add> model.add_metric(metrics.Mean(name='metric_2')(y))
<add> model.compile('sgd', loss='mse', metrics=['mse'])
<add>
<add> inputs = np.ones(shape=(10, 1))
<add> targets = np.zeros(shape=(10, 1))
<add> history = model.fit(
<add> inputs,
<add> targets,
<add> epochs=2,
<add> batch_size=5,
<add> validation_data=(inputs, targets))
<add> assert history.history['metric_1'][-1] == 5
<add> assert history.history['val_metric_1'][-1] == 5
<add>
<add> assert history.history['metric_2'][-1] == 1
<add> assert history.history['val_metric_2'][-1] == 1
<add>
<add> eval_results = model.evaluate(inputs, targets, batch_size=5)
<add> assert eval_results[-2] == 5
<add> assert eval_results[-1] == 1
<add>
<add> model.predict(inputs, batch_size=5)
<add> model.train_on_batch(inputs, targets)
<add> model.test_on_batch(inputs, targets)
<add>
<add>
<add>def test_add_metric_in_model_call():
<add>
<add> class TestModel(Model):
<add>
<add> def __init__(self):
<add> super(TestModel, self).__init__(name='test_model')
<add> self.dense1 = keras.layers.Dense(2, kernel_initializer='ones')
<add> self.mean = metrics.Mean(name='metric_1')
<add>
<add> def call(self, x):
<add> self.add_metric(K.sum(x), name='metric_2')
<add> # Provide same name as in the instance created in __init__
<add> # for eager mode
<add> self.add_metric(self.mean(x), name='metric_1')
<add> return self.dense1(x)
<add>
<add> model = TestModel()
<add> model.compile(loss='mse', optimizer='sgd')
<add>
<add> x = np.ones(shape=(10, 1))
<add> y = np.ones(shape=(10, 2))
<add> history = model.fit(x, y, epochs=2, batch_size=5, validation_data=(x, y))
<add> assert np.isclose(history.history['metric_1'][-1], 1, 0)
<add> assert np.isclose(history.history['val_metric_1'][-1], 1, 0)
<add> assert np.isclose(history.history['metric_2'][-1], 5, 0)
<add> assert np.isclose(history.history['val_metric_2'][-1], 5, 0)
<add>
<add> eval_results = model.evaluate(x, y, batch_size=5)
<add> assert np.isclose(eval_results[1], 1, 0)
<add> assert np.isclose(eval_results[2], 5, 0)
<add>
<add> model.predict(x, batch_size=5)
<add> model.train_on_batch(x, y)
<add> model.test_on_batch(x, y)
<add>
<add>
<add>def test_multiple_add_metric_calls():
<add>
<add> class TestModel(Model):
<add>
<add> def __init__(self):
<add> super(TestModel, self).__init__(name='test_model')
<add> self.dense1 = keras.layers.Dense(2, kernel_initializer='ones')
<add> self.mean1 = metrics.Mean(name='metric_1')
<add> self.mean2 = metrics.Mean(name='metric_2')
<add>
<add> def call(self, x):
<add> self.add_metric(self.mean2(x), name='metric_2')
<add> self.add_metric(self.mean1(x), name='metric_1')
<add> self.add_metric(K.sum(x), name='metric_3')
<add> return self.dense1(x)
<add>
<add> model = TestModel()
<add> model.compile(loss='mse', optimizer='sgd')
<add>
<add> x = np.ones(shape=(10, 1))
<add> y = np.ones(shape=(10, 2))
<add> history = model.fit(x, y, epochs=2, batch_size=5, validation_data=(x, y))
<add> assert np.isclose(history.history['metric_1'][-1], 1, 0)
<add> assert np.isclose(history.history['metric_2'][-1], 1, 0)
<add> assert np.isclose(history.history['metric_3'][-1], 5, 0)
<add>
<add> eval_results = model.evaluate(x, y, batch_size=5)
<add> assert np.allclose(eval_results[1:4], [1, 1, 5], 0.1)
<add>
<add> model.predict(x, batch_size=5)
<add> model.train_on_batch(x, y)
<add> model.test_on_batch(x, y)
<add>
<add>
<add>def test_add_metric_in_layer_call():
<add>
<add> class TestLayer(Layer):
<add>
<add> def build(self, input_shape):
<add> self.a = self.add_weight(
<add> 'a', (1, 1), initializer='ones', trainable=False)
<add> self.built = True
<add>
<add> def call(self, inputs):
<add> self.add_metric(K.sum(inputs), name='metric_1')
<add> return inputs + 1
<add>
<add> inp = Input(shape=(1,))
<add> x = TestLayer(input_shape=(1,))(inp)
<add> x = keras.layers.Dense(2, kernel_initializer='ones')(x)
<add>
<add> model = Model(inp, x)
<add> model.compile('adam', loss='mse')
<add>
<add> x = np.ones(shape=(10, 1))
<add> y = np.ones(shape=(10, 2))
<add> history = model.fit(x, y, epochs=2, batch_size=5, validation_data=(x, y))
<add> assert np.isclose(history.history['metric_1'][-1], 5, 0)
<add> assert np.isclose(history.history['val_metric_1'][-1], 5, 0)
<add>
<add>
<ide> if __name__ == '__main__':
<ide> pytest.main([__file__]) | 8 |
PHP | PHP | fix stray whitespace error | fadebee87b7e68baf6a98a43227e544527185b55 | <ide><path>src/Controller/Component/AuthComponent.php
<ide> public function constructAuthorize() {
<ide> unset($config['className']);
<ide> } else {
<ide> $class = $alias;
<del> }
<add> }
<ide> $className = App::className($class, 'Auth', 'Authorize');
<ide> if (!class_exists($className)) {
<ide> throw new Exception(sprintf('Authorization adapter "%s" was not found.', $class)); | 1 |
Javascript | Javascript | specify exe in the metadata | 0ac07e7f32e5f855824b5cf85e86fe5f6c00862a | <ide><path>script/lib/create-windows-installer.js
<ide> module.exports = packagedAppPath => {
<ide> process.env.ATOM_UPDATE_URL_PREFIX || 'https://atom.io';
<ide> const options = {
<ide> title: CONFIG.appName,
<add> exe: CONFIG.executableName,
<ide> appDirectory: packagedAppPath,
<ide> authors: 'GitHub Inc.',
<ide> iconUrl: `https://raw.githubusercontent.com/atom/atom/master/resources/app-icons/${ | 1 |
Javascript | Javascript | maintain constructor descriptor | e0bc5a7361b1d29c3ed034155fd779ce6f44fb13 | <ide><path>lib/internal/bootstrap_node.js
<ide> const EventEmitter = NativeModule.require('events');
<ide> process._eventsCount = 0;
<ide>
<add> const origProcProto = Object.getPrototypeOf(process);
<ide> Object.setPrototypeOf(process, Object.create(EventEmitter.prototype, {
<del> constructor: {
<del> value: process.constructor
<del> }
<add> constructor: Object.getOwnPropertyDescriptor(origProcProto, 'constructor')
<ide> }));
<ide>
<ide> EventEmitter.call(process);
<ide><path>test/parallel/test-process-prototype.js
<add>'use strict';
<add>require('../common');
<add>const assert = require('assert');
<add>const EventEmitter = require('events');
<add>
<add>const proto = Object.getPrototypeOf(process);
<add>
<add>assert(proto instanceof EventEmitter);
<add>
<add>const desc = Object.getOwnPropertyDescriptor(proto, 'constructor');
<add>
<add>assert.strictEqual(desc.value, process.constructor);
<add>assert.strictEqual(desc.writable, true);
<add>assert.strictEqual(desc.enumerable, false);
<add>assert.strictEqual(desc.configurable, true); | 2 |
Ruby | Ruby | provide more info about system dupes | 63846c7a929157842c1657dedcb76ce0ceb123ee | <ide><path>Library/Homebrew/formula.rb
<ide> require 'download_strategy'
<ide> require 'fileutils'
<ide>
<del>
<add># Defines a URL and download method for a stable or HEAD build
<ide> class SoftwareSpecification
<ide> attr_reader :url, :specs, :using
<ide>
<ide> def detect_version
<ide> end
<ide>
<ide>
<add># Used to annotate formulae that duplicate OS X provided software
<add># :provided_by_osx
<add>class KegOnlyReason
<add> attr_reader :reason, :explanation
<add>
<add> def initialize reason, explanation=nil
<add> @reason = reason
<add> @explanation = explanation
<add> end
<add>
<add> def to_s
<add> if @reason == :provided_by_osx
<add> <<-EOS.chomp
<add>Mac OS X already provides this program and installing another version in
<add>parallel can cause all kinds of trouble.
<add>
<add>#{@explanation}
<add>EOS
<add> else
<add> @reason
<add> end
<add> end
<add>end
<add>
<add>
<ide> # Derive and define at least @url, see Library/Formula for examples
<ide> class Formula
<ide> include FileUtils
<ide> def aka args
<ide> puts "detected as an alias for the target formula."
<ide> end
<ide>
<del> def keg_only reason
<del> @keg_only_reason = reason
<add> def keg_only reason, explanation=nil
<add> @keg_only_reason = KegOnlyReason.new(reason, explanation.chomp)
<ide> end
<ide> end
<ide> end | 1 |
Javascript | Javascript | destroy ember views in destroy-render-node hook | 32d625b9ca0860bb29bb0bf425e9549449f814ad | <ide><path>packages/ember-htmlbars/lib/hooks/destroy-render-node.js
<ide> */
<ide>
<ide> export default function destroyRenderNode(renderNode) {
<add> if (renderNode.emberView) {
<add> renderNode.emberView.destroy();
<add> }
<add>
<ide> var state = renderNode.state;
<ide> if (!state) { return; }
<ide>
<ide><path>packages/ember-htmlbars/lib/hooks/will-cleanup-tree.js
<del>export default function willCleanupTree(env, morph) {
<add>export default function willCleanupTree(env, morph, destroySelf) {
<ide> var view = morph.emberView;
<del> if (view && view.parentView) {
<add> if (destroySelf && view && view.parentView) {
<ide> view.parentView.removeChild(view);
<ide> }
<ide>
<ide><path>packages/ember-htmlbars/lib/morphs/morph.js
<ide> proto.cleanup = function() {
<ide> view.ownerView.isDestroyingSubtree = true;
<ide> if (view.parentView) { view.parentView.removeChild(view); }
<ide> }
<del>
<del> view.destroy();
<ide> }
<ide>
<ide> var toDestroy = this.emberToDestroy;
<ide><path>packages/ember-metal-views/lib/renderer.js
<ide> Renderer.prototype.renderElementRemoval =
<ide> if (view._willRemoveElement) {
<ide> view._willRemoveElement = false;
<ide>
<del> if (view.lastResult) {
<add> if (view.renderNode) {
<ide> view.renderNode.clear();
<ide> }
<ide> this.didDestroyElement(view);
<ide><path>packages/ember-views/tests/views/view/destroy_element_test.js
<ide> QUnit.test("if it has no element, does nothing", function() {
<ide> equal(callCount, 0, 'did not invoke callback');
<ide> });
<ide>
<del>QUnit.skip("if it has a element, calls willDestroyElement on receiver and child views then deletes the element", function() {
<add>QUnit.test("if it has a element, calls willDestroyElement on receiver and child views then deletes the element", function() {
<ide> expectDeprecation("Setting `childViews` on a Container is deprecated.");
<ide>
<ide> var parentCount = 0;
<ide> QUnit.test("returns receiver", function() {
<ide> equal(ret, view, 'returns receiver');
<ide> });
<ide>
<del>QUnit.skip("removes element from parentNode if in DOM", function() {
<add>QUnit.test("removes element from parentNode if in DOM", function() {
<ide> view = EmberView.create();
<ide>
<ide> run(function() {
<ide><path>packages/ember-views/tests/views/view/remove_test.js
<ide> QUnit.module("View#removeFromParent", {
<ide> }
<ide> });
<ide>
<del>QUnit.skip("removes view from parent view", function() {
<add>QUnit.test("removes view from parent view", function() {
<ide> expectDeprecation("Setting `childViews` on a Container is deprecated.");
<ide>
<ide> parentView = ContainerView.create({ childViews: [View] });
<ide><path>packages/ember-views/tests/views/view/view_lifecycle_test.js
<ide> QUnit.skip("should replace DOM representation if rerender() is called after elem
<ide> equal(view.$().text(), "Do not taunt happy fun ball", "rerenders DOM element when rerender() is called");
<ide> });
<ide>
<del>QUnit.skip("should destroy DOM representation when destroyElement is called", function() {
<add>QUnit.test("should destroy DOM representation when destroyElement is called", function() {
<ide> run(function() {
<ide> view = EmberView.create({
<ide> template: compile("Don't fear the reaper") | 7 |
Text | Text | add article for javascript string.startswith() | c3aec1aef2c3175445bcd5e42d542b2c541b7f34 | <ide><path>guide/english/javascript/standard-objects/string/string-prototype-startswith/index.md
<ide> title: String.prototype.startsWith
<ide> ---
<ide> ## String.prototype.startsWith
<ide>
<del>This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/javascript/standard-objects/string/string-prototype-startswith/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<add>The `startsWith()` method checks if the given string begins with the characters of a specified string; if it does, `startsWith()` returns `true`, otherwise `startsWith()` returns `false`.
<ide>
<del><a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<add>**Syntax**
<add>```javascript
<add>str.startsWith(searchStr[, pos]) // pos is the position in str at which to begin searching for searchStr
<add>```
<ide>
<del><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
<del>
<del>#### More Information:
<del><!-- Please add any articles you think might be helpful to read before writing the article -->
<add>**Example**
<add>```js
<add>var x = "Hi Hilbert";
<add>console.log(x.startsWith("Hi")); // true
<add>console.log(x.startsWith("Hi", 0)); // true
<add>console.log(x.startsWith("Hi", 3)); // true
<add>console.log(x.startsWith("Hi", 4)); // false
<add>```
<ide>
<add>*Note*: if the second argument to `startsWith()` is not provided, the start position defaults to 0 (the beginning of the string).
<ide>
<add>#### More Information:
<add>- [String.prototype.startsWith() on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith) | 1 |
Javascript | Javascript | use string.charat for character by index lookup | fdffec73c36a73443182b206595b239924d294cb | <ide><path>src/browser/ui/ReactMount.js
<ide> var findComponentRootReusableArray = [];
<ide> function firstDifferenceIndex(string1, string2) {
<ide> var minLen = Math.min(string1.length, string2.length);
<ide> for (var i = 0; i < minLen; i++) {
<del> if (string1[i] !== string2[i]) {
<add> if (string1.charAt(i) !== string2.charAt(i)) {
<ide> return i;
<ide> }
<ide> } | 1 |
Python | Python | use spaces instead of tabs | 43165e87f293b52e3d4938b49124c82410afe335 | <ide><path>numpy/core/tests/test_regression.py
<ide> def check_mem_digitize(self,level=rlevel):
<ide>
<ide> def check_intp(self,level=rlevel):
<ide> """Ticket #99"""
<del> i_width = N.int_(0).nbytes*2 - 1
<del> N.intp('0x' + 'f'*i_width,16)
<add> i_width = N.int_(0).nbytes*2 - 1
<add> N.intp('0x' + 'f'*i_width,16)
<ide> self.failUnlessRaises(OverflowError,N.intp,'0x' + 'f'*(i_width+1),16)
<ide> self.failUnlessRaises(ValueError,N.intp,'0x1',32)
<ide> assert_equal(255,N.intp('0xFF',16)) | 1 |
Ruby | Ruby | kill all subprocesses on timeout | 4b369962d303ac832cbda43fbe40562375a23896 | <ide><path>Library/Homebrew/test.rb
<ide> rescue Exception => e # rubocop:disable Lint/RescueException
<ide> error_pipe.puts e.to_json
<ide> error_pipe.close
<add> pid = Process.pid.to_s
<add> if which("pgrep") && which("pkill") && system("pgrep", "-qP", pid)
<add> $stderr.puts "Killing child processes..."
<add> system "pkill", "-P", pid
<add> sleep 1
<add> system "pkill", "-9", "-P", pid
<add> end
<ide> exit! 1
<ide> end | 1 |
Text | Text | use correct variables for challenge | 5f6595b7dc8c0cabd518a64346090785ce83f5ae | <ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-to-assign-variables-from-nested-objects.english.md
<ide> challengeType: 1
<ide> We can similarly destructure <em>nested</em> objects into variables.
<ide> Consider the following code:
<ide> <blockquote>const a = {<br> start: { x: 5, y: 6},<br> end: { x: 6, y: -9 }<br>};<br>const { start : { x: startX, y: startY }} = a;<br>console.log(startX, startY); // 5, 6</blockquote>
<del>In the example above, the variable <code>start</code> is assigned the value of <code>a.start</code>, which is also an object.
<add>In the example above, the variable <code>startX</code> is assigned the value of <code>a.start.x</code>.
<ide> </section>
<ide>
<ide> ## Instructions | 1 |
Python | Python | add requirespvopskernel to test options | d214bf6323623bbcc771c8987286a4a7104a085a | <ide><path>test/test_linode.py
<ide> def _avail_linodeplans(self, method, url, body, headers):
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<ide> def _avail_distributions(self, method, url, body, headers):
<del> body = '{"ERRORARRAY":[],"ACTION":"avail.distributions","DATA":[{"IS64BIT":0,"LABEL":"Arch Linux 2007.08","MINIMAGESIZE":436,"DISTRIBUTIONID":38,"CREATE_DT":"2007-10-24 00:00:00.0"},{"IS64BIT":0,"LABEL":"Centos 5.0","MINIMAGESIZE":594,"DISTRIBUTIONID":32,"CREATE_DT":"2007-04-27 00:00:00.0"},{"IS64BIT":0,"LABEL":"Centos 5.2","MINIMAGESIZE":950,"DISTRIBUTIONID":46,"CREATE_DT":"2008-11-30 00:00:00.0"},{"IS64BIT":1,"LABEL":"Centos 5.2 64bit","MINIMAGESIZE":980,"DISTRIBUTIONID":47,"CREATE_DT":"2008-11-30 00:00:00.0"},{"IS64BIT":0,"LABEL":"Debian 4.0","MINIMAGESIZE":200,"DISTRIBUTIONID":28,"CREATE_DT":"2007-04-18 00:00:00.0"},{"IS64BIT":1,"LABEL":"Debian 4.0 64bit","MINIMAGESIZE":220,"DISTRIBUTIONID":48,"CREATE_DT":"2008-12-02 00:00:00.0"},{"IS64BIT":0,"LABEL":"Debian 5.0","MINIMAGESIZE":200,"DISTRIBUTIONID":50,"CREATE_DT":"2009-02-19 00:00:00.0"},{"IS64BIT":1,"LABEL":"Debian 5.0 64bit","MINIMAGESIZE":300,"DISTRIBUTIONID":51,"CREATE_DT":"2009-02-19 00:00:00.0"},{"IS64BIT":0,"LABEL":"Fedora 8","MINIMAGESIZE":740,"DISTRIBUTIONID":40,"CREATE_DT":"2007-11-09 00:00:00.0"},{"IS64BIT":0,"LABEL":"Fedora 9","MINIMAGESIZE":1175,"DISTRIBUTIONID":43,"CREATE_DT":"2008-06-09 15:15:21.0"},{"IS64BIT":0,"LABEL":"Gentoo 2007.0","MINIMAGESIZE":1800,"DISTRIBUTIONID":35,"CREATE_DT":"2007-08-29 00:00:00.0"},{"IS64BIT":0,"LABEL":"Gentoo 2008.0","MINIMAGESIZE":1500,"DISTRIBUTIONID":52,"CREATE_DT":"2009-03-20 00:00:00.0"},{"IS64BIT":1,"LABEL":"Gentoo 2008.0 64bit","MINIMAGESIZE":2500,"DISTRIBUTIONID":53,"CREATE_DT":"2009-04-04 00:00:00.0"},{"IS64BIT":0,"LABEL":"OpenSUSE 11.0","MINIMAGESIZE":850,"DISTRIBUTIONID":44,"CREATE_DT":"2008-08-21 08:32:16.0"},{"IS64BIT":0,"LABEL":"Slackware 12.0","MINIMAGESIZE":315,"DISTRIBUTIONID":34,"CREATE_DT":"2007-07-16 00:00:00.0"},{"IS64BIT":0,"LABEL":"Slackware 12.2","MINIMAGESIZE":500,"DISTRIBUTIONID":54,"CREATE_DT":"2009-04-04 00:00:00.0"},{"IS64BIT":0,"LABEL":"Ubuntu 8.04 LTS","MINIMAGESIZE":400,"DISTRIBUTIONID":41,"CREATE_DT":"2008-04-23 15:11:29.0"},{"IS64BIT":1,"LABEL":"Ubuntu 8.04 LTS 64bit","MINIMAGESIZE":350,"DISTRIBUTIONID":42,"CREATE_DT":"2008-06-03 12:51:11.0"},{"IS64BIT":0,"LABEL":"Ubuntu 8.10","MINIMAGESIZE":220,"DISTRIBUTIONID":45,"CREATE_DT":"2008-10-30 23:23:03.0"},{"IS64BIT":1,"LABEL":"Ubuntu 8.10 64bit","MINIMAGESIZE":230,"DISTRIBUTIONID":49,"CREATE_DT":"2008-12-02 00:00:00.0"},{"IS64BIT":0,"LABEL":"Ubuntu 9.04","MINIMAGESIZE":350,"DISTRIBUTIONID":55,"CREATE_DT":"2009-04-23 00:00:00.0"},{"IS64BIT":1,"LABEL":"Ubuntu 9.04 64bit","MINIMAGESIZE":350,"DISTRIBUTIONID":56,"CREATE_DT":"2009-04-23 00:00:00.0"}]}'
<add> body = '{"ERRORARRAY":[],"ACTION":"avail.distributions","DATA":[{"REQUIRESPVOPSKERNEL":0,"IS64BIT":0,"LABEL":"Arch Linux 2007.08","MINIMAGESIZE":436,"DISTRIBUTIONID":38,"CREATE_DT":"2007-10-24 00:00:00.0"},{"REQUIRESPVOPSKERNEL":0,"IS64BIT":0,"LABEL":"Centos 5.0","MINIMAGESIZE":594,"DISTRIBUTIONID":32,"CREATE_DT":"2007-04-27 00:00:00.0"},{"REQUIRESPVOPSKERNEL":0,"IS64BIT":0,"LABEL":"Centos 5.2","MINIMAGESIZE":950,"DISTRIBUTIONID":46,"CREATE_DT":"2008-11-30 00:00:00.0"},{"REQUIRESPVOPSKERNEL":1,"IS64BIT":1,"LABEL":"Centos 5.2 64bit","MINIMAGESIZE":980,"DISTRIBUTIONID":47,"CREATE_DT":"2008-11-30 00:00:00.0"},{"REQUIRESPVOPSKERNEL":1,"IS64BIT":0,"LABEL":"Debian 4.0","MINIMAGESIZE":200,"DISTRIBUTIONID":28,"CREATE_DT":"2007-04-18 00:00:00.0"},{"REQUIRESPVOPSKERNEL":0,"IS64BIT":1,"LABEL":"Debian 4.0 64bit","MINIMAGESIZE":220,"DISTRIBUTIONID":48,"CREATE_DT":"2008-12-02 00:00:00.0"},{"REQUIRESPVOPSKERNEL":0,"IS64BIT":0,"LABEL":"Debian 5.0","MINIMAGESIZE":200,"DISTRIBUTIONID":50,"CREATE_DT":"2009-02-19 00:00:00.0"},{"REQUIRESPVOPSKERNEL":0,"IS64BIT":1,"LABEL":"Debian 5.0 64bit","MINIMAGESIZE":300,"DISTRIBUTIONID":51,"CREATE_DT":"2009-02-19 00:00:00.0"},{"REQUIRESPVOPSKERNEL":1,"IS64BIT":0,"LABEL":"Fedora 8","MINIMAGESIZE":740,"DISTRIBUTIONID":40,"CREATE_DT":"2007-11-09 00:00:00.0"},{"REQUIRESPVOPSKERNEL":0,"IS64BIT":0,"LABEL":"Fedora 9","MINIMAGESIZE":1175,"DISTRIBUTIONID":43,"CREATE_DT":"2008-06-09 15:15:21.0"},{"REQUIRESPVOPSKERNEL":1,"IS64BIT":0,"LABEL":"Gentoo 2007.0","MINIMAGESIZE":1800,"DISTRIBUTIONID":35,"CREATE_DT":"2007-08-29 00:00:00.0"},{"REQUIRESPVOPSKERNEL":0,"IS64BIT":0,"LABEL":"Gentoo 2008.0","MINIMAGESIZE":1500,"DISTRIBUTIONID":52,"CREATE_DT":"2009-03-20 00:00:00.0"},{"REQUIRESPVOPSKERNEL":1,"IS64BIT":1,"LABEL":"Gentoo 2008.0 64bit","MINIMAGESIZE":2500,"DISTRIBUTIONID":53,"CREATE_DT":"2009-04-04 00:00:00.0"},{"REQUIRESPVOPSKERNEL":0,"IS64BIT":0,"LABEL":"OpenSUSE 11.0","MINIMAGESIZE":850,"DISTRIBUTIONID":44,"CREATE_DT":"2008-08-21 08:32:16.0"},{"REQUIRESPVOPSKERNEL":0,"IS64BIT":0,"LABEL":"Slackware 12.0","MINIMAGESIZE":315,"DISTRIBUTIONID":34,"CREATE_DT":"2007-07-16 00:00:00.0"},{"REQUIRESPVOPSKERNEL":1,"IS64BIT":0,"LABEL":"Slackware 12.2","MINIMAGESIZE":500,"DISTRIBUTIONID":54,"CREATE_DT":"2009-04-04 00:00:00.0"},{"REQUIRESPVOPSKERNEL":0,"IS64BIT":0,"LABEL":"Ubuntu 8.04 LTS","MINIMAGESIZE":400,"DISTRIBUTIONID":41,"CREATE_DT":"2008-04-23 15:11:29.0"},{"REQUIRESPVOPSKERNEL":0,"IS64BIT":1,"LABEL":"Ubuntu 8.04 LTS 64bit","MINIMAGESIZE":350,"DISTRIBUTIONID":42,"CREATE_DT":"2008-06-03 12:51:11.0"},{"REQUIRESPVOPSKERNEL":0,"IS64BIT":0,"LABEL":"Ubuntu 8.10","MINIMAGESIZE":220,"DISTRIBUTIONID":45,"CREATE_DT":"2008-10-30 23:23:03.0"},{"REQUIRESPVOPSKERNEL":1,"IS64BIT":1,"LABEL":"Ubuntu 8.10 64bit","MINIMAGESIZE":230,"DISTRIBUTIONID":49,"CREATE_DT":"2008-12-02 00:00:00.0"},{"REQUIRESPVOPSKERNEL":0,"IS64BIT":0,"LABEL":"Ubuntu 9.04","MINIMAGESIZE":350,"DISTRIBUTIONID":55,"CREATE_DT":"2009-04-23 00:00:00.0"},{"REQUIRESPVOPSKERNEL":0,"IS64BIT":1,"LABEL":"Ubuntu 9.04 64bit","MINIMAGESIZE":350,"DISTRIBUTIONID":56,"CREATE_DT":"2009-04-23 00:00:00.0"}]}'
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<ide> def _linode_create(self, method, url, body, headers): | 1 |
PHP | PHP | remove unneeded use statements | 7af1654b1d833853a5bf76462547f01039250353 | <ide><path>src/Database/Expression/CaseExpression.php
<ide> namespace Cake\Database\Expression;
<ide>
<ide> use Cake\Database\ExpressionInterface;
<del>use Cake\Database\Expression\QueryExpression;
<ide> use Cake\Database\ValueBinder;
<ide>
<ide> /**
<ide><path>src/Datasource/QueryTrait.php
<ide> use Cake\Datasource\QueryCacher;
<ide> use Cake\Datasource\RepositoryInterface;
<ide> use Cake\Datasource\ResultSetDecorator;
<del>use Cake\Event\Event;
<ide>
<ide> /**
<ide> * Contains the characteristics for an object that is attached to a repository and
<ide><path>src/Error/BaseErrorHandler.php
<ide> use Cake\Core\Configure;
<ide> use Cake\Error\Debugger;
<ide> use Cake\Log\Log;
<del>use Cake\Network\Exception\InternalErrorException;
<ide> use Cake\Routing\Router;
<ide>
<ide> /**
<ide><path>src/Error/Debugger.php
<ide> */
<ide> namespace Cake\Error;
<ide>
<del>use Cake\Core\Configure;
<ide> use Cake\Log\Log;
<ide> use Cake\Utility\Hash;
<ide> use Cake\Utility\Security;
<ide><path>src/I18n/I18n.php
<ide>
<ide> use Aura\Intl\Exception as LoadException;
<ide> use Aura\Intl\FormatterLocator;
<del>use Aura\Intl\Package;
<ide> use Aura\Intl\PackageLocator;
<ide> use Aura\Intl\TranslatorFactory;
<del>use Aura\Intl\TranslatorLocator;
<ide> use Cake\I18n\Formatter\IcuFormatter;
<ide> use Cake\I18n\Formatter\SprintfFormatter;
<ide> use Locale;
<ide><path>src/Log/Engine/ConsoleLog.php
<ide> namespace Cake\Log\Engine;
<ide>
<ide> use Cake\Console\ConsoleOutput;
<del>use Cake\Core\Exception\Exception;
<ide> use InvalidArgumentException;
<ide>
<ide> /**
<ide><path>src/Network/Response.php
<ide> use Cake\Network\Exception\NotFoundException;
<ide> use Cake\Filesystem\File;
<ide> use InvalidArgumentException;
<del>use RuntimeException;
<ide>
<ide> /**
<ide> * Cake Response is responsible for managing the response text, status and headers of a HTTP response.
<ide><path>src/Routing/Router.php
<ide> */
<ide> namespace Cake\Routing;
<ide>
<del>use Cake\Core\App;
<ide> use Cake\Core\Configure;
<ide> use Cake\Network\Request;
<ide> use Cake\Routing\RouteBuilder;
<ide><path>src/Shell/Task/SimpleBakeTask.php
<ide>
<ide> use Cake\Shell\Task\BakeTask;
<ide> use Cake\Core\Configure;
<del>use Cake\Core\Plugin;
<ide> use Cake\Utility\Inflector;
<ide>
<ide> /**
<ide><path>src/Shell/TestShell.php
<ide> */
<ide> namespace Cake\Shell;
<ide>
<del>use Cake\Console\ConsoleOptionParser;
<ide> use Cake\Console\Shell;
<del>use Cake\TestSuite\TestLoader;
<del>use Cake\TestSuite\TestSuiteCommand;
<del>use Cake\TestSuite\TestSuiteDispatcher;
<del>use Cake\Utility\Inflector;
<ide>
<ide> /**
<ide> * Stub that tells people how to run tests with PHPUnit.
<ide><path>src/TestSuite/ControllerTestCase.php
<ide> protected function _testAction($url = '', $options = array()) {
<ide> * @throws \Cake\Controller\Error\MissingControllerException When controllers could not be created.
<ide> * @throws \Cake\Controller\Error\MissingComponentException When components could not be created.
<ide> */
<del> public function generate($controller, array $mocks = array(), $request = null) {
<add> public function generate($controller, array $mocks = array(), Request $request = null) {
<ide> $className = App::className($controller, 'Controller', 'Controller');
<ide> if (!$className) {
<ide> list($plugin, $controller) = pluginSplit($controller);
<ide><path>src/TestSuite/Fixture/FixtureManager.php
<ide> namespace Cake\TestSuite\Fixture;
<ide>
<ide> use Cake\Core\Configure;
<del>use Cake\Core\Plugin;
<ide> use Cake\Database\Connection;
<ide> use Cake\Datasource\ConnectionManager;
<ide> use Cake\Core\Exception\Exception;
<ide> class FixtureManager {
<ide> /**
<ide> * Inspects the test to look for unloaded fixtures and loads them
<ide> *
<del> * @param \Cake\TestSuite\TestCase $test the test case to inspect
<add> * @param \Cake\TestSuite\TestCase $test The test case to inspect.
<ide> * @return void
<ide> */
<ide> public function fixturize($test) {
<ide> protected function _initDb() {
<ide> /**
<ide> * Looks for fixture files and instantiates the classes accordingly
<ide> *
<del> * @param \Cake\TestSuite\Testcase $test The test suite to load fixtures for.
<add> * @param \Cake\TestSuite\TestCase $test The test suite to load fixtures for.
<ide> * @return void
<ide> * @throws \UnexpectedValueException when a referenced fixture does not exist.
<ide> */
<ide> protected function _setupTable(TestFixture $fixture, Connection $db, array $sour
<ide> /**
<ide> * Creates the fixtures tables and inserts data on them.
<ide> *
<del> * @param \Cake\TestSuite\TestCase $test the test to inspect for fixture loading
<add> * @param \Cake\TestSuite\TestCase $test The test to inspect for fixture loading.
<ide> * @return void
<ide> * @throws \Cake\Core\Exception\Exception When fixture records cannot be inserted.
<ide> */
<ide> protected function _fixtureConnections($fixtures) {
<ide> /**
<ide> * Truncates the fixtures tables
<ide> *
<del> * @param \Cake\TestSuite\TestCase $test the test to inspect for fixture unloading
<add> * @param \Cake\TestSuite\TestCase $test The test to inspect for fixture unloading.
<ide> * @return void
<ide> */
<ide> public function unload($test) { | 12 |
Text | Text | add some notes on security in server-side apps | e402e60e2cf6f20ac8e9eebeb10fd80fa97f38cd | <ide><path>docs/recipes/ServerRendering.md
<ide> function handleRender(req, res) {
<ide>
<ide> Because we `res.send()` inside of the callback, the server will hold open the connection and won’t send any data until that callback executes. You’ll notice a 500ms delay is now added to each server request as a result of our new API call. A more advanced usage would handle errors in the API gracefully, such as a bad response or timeout.
<ide>
<add>### Security Considerations
<add>
<add>Because we have introduced more code that relies on user generated content (UGC) and input, we have increased our attack surface area for our application. It is important for any application that you ensure your input is properly sanitized to prevent things like cross-site scripting (XSS) attacks or code injections.
<add>
<add>In our example, we take a rudimentary approach to security. When we obtain the parameters from the request, we use `parseInt` on the `counter` parameter to ensure this value is a number. If we did not do this, you could easily get dangerous data into the rendered HTML by providing a script tag in the request. That might look like this: `?counter=</script><script>doSomethingBad();</script>`
<add>
<add>For our simplistic example, coercing our input into a number is sufficiently secure. If you're handling more complex input, such as freeform text, then you should run that input through an appropriate sanitization function, such as [validator.js](https://www.npmjs.com/package/validator).
<add>
<add>Furthermore, you can add additional layers of security by sanitizing your state output. `JSON.stringify` can be subject to script injections. To counter this, you can scrub the JSON string of HTML tags and other dangerous characters. This can be done with either a simple text replacement on the string or via more sophisticated libraries such as [serialize-javascript](https://github.com/yahoo/serialize-javascript).
<add>
<ide> ## Next Steps
<ide>
<ide> You may want to read [Async Actions](../advanced/AsyncActions.md) to learn more about expressing asynchronous flow in Redux with async primitives such Promises and thunks. Keep in mind that anything you learn there can also be applied to universal rendering. | 1 |
Ruby | Ruby | remove unnecessary test | f7fd680a6de195d78286332c6021afe068ad6bd6 | <ide><path>railties/lib/rails/commands/server/server_command.rb
<ide> def rack_server_suggestion(server)
<ide> Run `rails server --help` for more options.
<ide> MSG
<ide> else
<del> suggestions = Rails::Command::Spellchecker.suggest(server, from: RACK_SERVERS)
<add> suggestion = Rails::Command::Spellchecker.suggest(server, from: RACK_SERVERS)
<ide>
<ide> <<~MSG
<del> Could not find server "#{server}". Maybe you meant #{suggestions.inspect}?
<add> Could not find server "#{server}". Maybe you meant #{suggestion.inspect}?
<ide> Run `rails server --help` for more options.
<ide> MSG
<ide> end
<ide><path>railties/test/generators_test.rb
<ide> def test_generator_suggestions_except_en_locale
<ide> I18n.default_locale = orig_default_locale
<ide> end
<ide>
<del> def test_generator_multiple_suggestions
<del> name = :tas
<del> output = capture(:stdout) { Rails::Generators.invoke name }
<del> assert_match 'Maybe you meant "task"?', output
<del> end
<del>
<ide> def test_help_when_a_generator_with_required_arguments_is_invoked_without_arguments
<ide> output = capture(:stdout) { Rails::Generators.invoke :model, [] }
<ide> assert_match(/Description:/, output) | 2 |
Text | Text | add solutions to responsive web design principles | 9b9a96234f1eb3000f71d21264faae20f8cb9f7c | <ide><path>curriculum/challenges/english/01-responsive-web-design/responsive-web-design-principles/make-an-image-responsive.english.md
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<del>// solution required
<add>```html
<add><style>
<add> img {
<add> max-width: 100%;
<add> display: block;
<add> height: auto;
<add> }
<add></style>
<add>
<add><img src="https://s3.amazonaws.com/freecodecamp/FCCStickerPack.jpg" alt="freeCodeCamp stickers set">
<ide> ```
<ide> </section>
<ide><path>curriculum/challenges/english/01-responsive-web-design/responsive-web-design-principles/make-typography-responsive.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide>
<del>```js
<del>var code = "h2 {width: 80vw;} p {width: 75vmin;}"
<add>```html
<add><style>
<add> h2 {
<add> width: 80vw;
<add> }
<add> p {
<add> width: 75vmin;
<add> }
<add></style>
<add>
<add><h2>Importantus Ipsum</h2>
<add><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus quis tempus massa. Aenean erat nisl, gravida vel vestibulum cursus, interdum sit amet lectus. Sed sit amet quam nibh. Suspendisse quis tincidunt nulla. In hac habitasse platea dictumst. Ut sit amet pretium nisl. Vivamus vel mi sem. Aenean sit amet consectetur sem. Suspendisse pretium, purus et gravida consequat, nunc ligula ultricies diam, at aliquet velit libero a dui.</p>
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/01-responsive-web-design/responsive-web-design-principles/use-a-retina-image-for-higher-resolution-displays.english.md
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<del>// solution required
<add>```html
<add><style>
<add> img {
<add> height: 100px;
<add> width: 100px;
<add> }
<add></style>
<add>
<add><img src="https://s3.amazonaws.com/freecodecamp/FCCStickers-CamperBot200x200.jpg" alt="freeCodeCamp sticker that says 'Because CamperBot Cares'">
<ide> ```
<ide> </section> | 3 |
Mixed | Ruby | fix a bug affecting validations of enum attributes | 6e53d92498ada27cea6c7bae85708fcf5579223c | <ide><path>activerecord/CHANGELOG.md
<add>* Fixed error with validation with enum fields for records where the
<add> value for any enum attribute is always evaluated as 0 during
<add> uniqueness validation.
<add>
<add> Fixes #14172
<add>
<add> *Vilius Luneckas* *Ahmed AbouElhamayed*
<add>
<ide> * `before_add` callbacks are fired before the record is saved on
<ide> `has_and_belongs_to_many` assocations *and* on `has_many :through`
<ide> associations. Before this change, `before_add` callbacks would be fired
<ide><path>activerecord/lib/active_record/validations/uniqueness.rb
<ide> def initialize(options)
<ide> def validate_each(record, attribute, value)
<ide> finder_class = find_finder_class_for(record)
<ide> table = finder_class.arel_table
<add> value = map_enum_attribute(finder_class,attribute,value)
<ide> value = deserialize_attribute(record, attribute, value)
<ide>
<ide> relation = build_relation(finder_class, table, attribute, value)
<ide> def deserialize_attribute(record, attribute, value)
<ide> value = coder.dump value if value && coder
<ide> value
<ide> end
<add>
<add> def map_enum_attribute(klass,attribute,value)
<add> mapping = klass.enum_mapping_for(attribute.to_s)
<add> value = mapping[value] if value && mapping
<add> value
<add> end
<ide> end
<ide>
<ide> module ClassMethods
<ide><path>activerecord/test/cases/enum_test.rb
<ide> def written!
<ide> end
<ide> end
<ide> end
<add>
<add> test "validate uniqueness" do
<add> klass = Class.new(ActiveRecord::Base) do
<add> def self.name; 'Book'; end
<add> enum status: [:proposed, :written]
<add> validates_uniqueness_of :status
<add> end
<add> klass.delete_all
<add> klass.create!(status: "proposed")
<add> book = klass.new(status: "written")
<add> assert book.valid?
<add> book.status = "proposed"
<add> assert_not book.valid?
<add> end
<add>
<add> test "validate inclusion of value in array" do
<add> klass = Class.new(ActiveRecord::Base) do
<add> def self.name; 'Book'; end
<add> enum status: [:proposed, :written]
<add> validates_inclusion_of :status, in: ["written"]
<add> end
<add> klass.delete_all
<add> invalid_book = klass.new(status: "proposed")
<add> assert_not invalid_book.valid?
<add> valid_book = klass.new(status: "written")
<add> assert valid_book.valid?
<add> end
<ide> end | 3 |
Ruby | Ruby | use @app_env_config instead of @env_config | 862389c9537dbb6f65fd26c4325e07607ed437b5 | <ide><path>railties/lib/rails/application.rb
<ide> def key_generator
<ide> # * "action_dispatch.encrypted_signed_cookie_salt" => config.action_dispatch.encrypted_signed_cookie_salt
<ide> #
<ide> def env_config
<del> @env_config ||= begin
<add> @app_env_config ||= begin
<ide> if config.secret_key_base.nil?
<ide> ActiveSupport::Deprecation.warn "You didn't set config.secret_key_base in config/initializers/secret_token.rb file. " +
<ide> "This should be used instead of the old deprecated config.secret_token in order to use the new EncryptedCookieStore. " + | 1 |
Python | Python | add disable_fields to wandb_logger | 1d8c4070aae601d1161f74284f857e9bc476050a | <ide><path>spacy/gold/loggers.py
<ide> from typing import Dict, Any, Tuple, Callable
<ide>
<ide> from ..util import registry
<add>from .. import util
<ide> from ..errors import Errors
<ide> from wasabi import msg
<ide>
<ide> def finalize():
<ide>
<ide>
<ide> @registry.loggers("spacy.WandbLogger.v1")
<del>def wandb_logger(project_name: str):
<add>def wandb_logger(project_name: str, disable_fields: list = []):
<ide> import wandb
<ide>
<ide> console = console_logger()
<ide> def setup_logger(
<ide> nlp: "Language"
<ide> ) -> Tuple[Callable[[Dict[str, Any]], None], Callable]:
<ide> config = nlp.config.interpolate()
<add> config_dot = util.dict_to_dot(config)
<add> for field in disable_fields:
<add> del config_dot[field]
<add> config = util.dot_to_dict(config_dot)
<ide> wandb.init(project=project_name, config=config)
<ide> console_log_step, console_finalize = console(nlp)
<ide>
<ide> def log_step(info: Dict[str, Any]):
<ide> console_log_step(info)
<del> epoch = info["epoch"]
<ide> score = info["score"]
<ide> other_scores = info["other_scores"]
<ide> losses = info["losses"]
<del> wandb.log({"score": score, "epoch": epoch})
<add> wandb.log({"score": score})
<ide> if losses:
<ide> wandb.log({f"loss_{k}": v for k, v in losses.items()})
<ide> if isinstance(other_scores, dict): | 1 |
Javascript | Javascript | initialize instance members in class constructors | b1c3909bd766327a569c2e4279a4670454f3f9db | <ide><path>lib/internal/abort_controller.js
<ide> function abortSignal(signal) {
<ide> signal.dispatchEvent(event);
<ide> }
<ide>
<add>// TODO(joyeecheung): V8 snapshot does not support instance member
<add>// initializers for now:
<add>// https://bugs.chromium.org/p/v8/issues/detail?id=10704
<add>const kSignal = Symbol('signal');
<ide> class AbortController {
<del> #signal = new AbortSignal();
<del>
<ide> constructor() {
<add> this[kSignal] = new AbortSignal();
<ide> emitExperimentalWarning('AbortController');
<ide> }
<ide>
<del> get signal() { return this.#signal; }
<del> abort() { abortSignal(this.#signal); }
<add> get signal() { return this[kSignal]; }
<add> abort() { abortSignal(this[kSignal]); }
<ide>
<ide> [customInspectSymbol](depth, options) {
<ide> return customInspect(this, {
<ide><path>lib/internal/event_target.js
<ide> function lazyNow() {
<ide> return perf_hooks.performance.now();
<ide> }
<ide>
<add>// TODO(joyeecheung): V8 snapshot does not support instance member
<add>// initializers for now:
<add>// https://bugs.chromium.org/p/v8/issues/detail?id=10704
<add>const kType = Symbol('type');
<add>const kDefaultPrevented = Symbol('defaultPrevented');
<add>const kCancelable = Symbol('cancelable');
<add>const kTimestamp = Symbol('timestamp');
<add>const kBubbles = Symbol('bubbles');
<add>const kComposed = Symbol('composed');
<add>const kPropagationStopped = Symbol('propagationStopped');
<ide> class Event {
<del> #type = undefined;
<del> #defaultPrevented = false;
<del> #cancelable = false;
<del> #timestamp = lazyNow();
<del>
<del> // None of these are currently used in the Node.js implementation
<del> // of EventTarget because there is no concept of bubbling or
<del> // composition. We preserve their values in Event but they are
<del> // non-ops and do not carry any semantics in Node.js
<del> #bubbles = false;
<del> #composed = false;
<del> #propagationStopped = false;
<del>
<del>
<ide> constructor(type, options) {
<ide> if (arguments.length === 0)
<ide> throw new ERR_MISSING_ARGS('type');
<ide> if (options != null)
<ide> validateObject(options, 'options');
<ide> const { cancelable, bubbles, composed } = { ...options };
<del> this.#cancelable = !!cancelable;
<del> this.#bubbles = !!bubbles;
<del> this.#composed = !!composed;
<del> this.#type = `${type}`;
<del> this.#propagationStopped = false;
<add> this[kCancelable] = !!cancelable;
<add> this[kBubbles] = !!bubbles;
<add> this[kComposed] = !!composed;
<add> this[kType] = `${type}`;
<add> this[kDefaultPrevented] = false;
<add> this[kTimestamp] = lazyNow();
<add> this[kPropagationStopped] = false;
<ide> // isTrusted is special (LegacyUnforgeable)
<ide> Object.defineProperty(this, 'isTrusted', {
<ide> get() { return false; },
<ide> class Event {
<ide> });
<ide>
<ide> return `${name} ${inspect({
<del> type: this.#type,
<del> defaultPrevented: this.#defaultPrevented,
<del> cancelable: this.#cancelable,
<del> timeStamp: this.#timestamp,
<add> type: this[kType],
<add> defaultPrevented: this[kDefaultPrevented],
<add> cancelable: this[kCancelable],
<add> timeStamp: this[kTimestamp],
<ide> }, opts)}`;
<ide> }
<ide>
<ide> class Event {
<ide> }
<ide>
<ide> preventDefault() {
<del> this.#defaultPrevented = true;
<add> this[kDefaultPrevented] = true;
<ide> }
<ide>
<ide> get target() { return this[kTarget]; }
<ide> get currentTarget() { return this[kTarget]; }
<ide> get srcElement() { return this[kTarget]; }
<ide>
<del> get type() { return this.#type; }
<add> get type() { return this[kType]; }
<ide>
<del> get cancelable() { return this.#cancelable; }
<add> get cancelable() { return this[kCancelable]; }
<ide>
<del> get defaultPrevented() { return this.#cancelable && this.#defaultPrevented; }
<add> get defaultPrevented() {
<add> return this[kCancelable] && this[kDefaultPrevented];
<add> }
<ide>
<del> get timeStamp() { return this.#timestamp; }
<add> get timeStamp() { return this[kTimestamp]; }
<ide>
<ide>
<ide> // The following are non-op and unused properties/methods from Web API Event.
<ide> class Event {
<ide>
<ide> composedPath() { return this[kTarget] ? [this[kTarget]] : []; }
<ide> get returnValue() { return !this.defaultPrevented; }
<del> get bubbles() { return this.#bubbles; }
<del> get composed() { return this.#composed; }
<add> get bubbles() { return this[kBubbles]; }
<add> get composed() { return this[kComposed]; }
<ide> get eventPhase() {
<ide> return this[kTarget] ? Event.AT_TARGET : Event.NONE;
<ide> }
<del> get cancelBubble() { return this.#propagationStopped; }
<add> get cancelBubble() { return this[kPropagationStopped]; }
<ide> set cancelBubble(value) {
<ide> if (value) {
<ide> this.stopPropagation();
<ide> }
<ide> }
<ide> stopPropagation() {
<del> this.#propagationStopped = true;
<add> this[kPropagationStopped] = true;
<ide> }
<ide>
<ide> static NONE = 0;
<ide> Object.defineProperty(Event.prototype, SymbolToStringTag, {
<ide> // the linked list makes dispatching faster, even if adding/removing is
<ide> // slower.
<ide> class Listener {
<del> next;
<del> previous;
<del> listener;
<del> callback;
<del> once;
<del> capture;
<del> passive;
<del>
<ide> constructor(previous, listener, once, capture, passive) {
<add> this.next = undefined;
<ide> if (previous !== undefined)
<ide> previous.next = this;
<ide> this.previous = previous;
<ide> class EventTarget {
<ide> // symbol as EventTarget may be used cross-realm. See discussion in #33661.
<ide> static [kIsEventTarget] = true;
<ide>
<del> [kEvents] = new Map();
<add> constructor() {
<add> this[kEvents] = new Map();
<add> }
<ide>
<ide> [kNewListener](size, type, listener, once, capture, passive) {}
<ide> [kRemoveListener](size, type, listener, capture) {}
<ide> Object.defineProperty(EventTarget.prototype, SymbolToStringTag, {
<ide> value: 'EventTarget',
<ide> });
<ide>
<add>const kMaxListeners = Symbol('maxListeners');
<add>const kMaxListenersWarned = Symbol('maxListenersWarned');
<ide> class NodeEventTarget extends EventTarget {
<ide> static defaultMaxListeners = 10;
<ide>
<del> #maxListeners = NodeEventTarget.defaultMaxListeners;
<del> #maxListenersWarned = false;
<add> constructor() {
<add> super();
<add> this[kMaxListeners] = NodeEventTarget.defaultMaxListeners;
<add> this[kMaxListenersWarned] = false;
<add> }
<ide>
<ide> [kNewListener](size, type, listener, once, capture, passive) {
<del> if (this.#maxListeners > 0 &&
<del> size > this.#maxListeners &&
<del> !this.#maxListenersWarned) {
<del> this.#maxListenersWarned = true;
<add> if (this[kMaxListeners] > 0 &&
<add> size > this[kMaxListeners] &&
<add> !this[kMaxListenersWarned]) {
<add> this[kMaxListenersWarned] = true;
<ide> // No error code for this since it is a Warning
<ide> // eslint-disable-next-line no-restricted-syntax
<ide> const w = new Error('Possible EventTarget memory leak detected. ' +
<ide> class NodeEventTarget extends EventTarget {
<ide>
<ide> setMaxListeners(n) {
<ide> validateInteger(n, 'n', 0);
<del> this.#maxListeners = n;
<add> this[kMaxListeners] = n;
<ide> return this;
<ide> }
<ide>
<ide> getMaxListeners() {
<del> return this.#maxListeners;
<add> return this[kMaxListeners];
<ide> }
<ide>
<ide> eventNames() { | 2 |
Python | Python | add secrets to test_deprecated_packages | bdb83699f1f651dcf847e989227f5b6019fc1e71 | <ide><path>tests/test_project_structure.py
<ide> def test_reference_to_providers_from_core(self):
<ide> self.assert_file_not_contains(filename, "providers")
<ide>
<ide> def test_deprecated_packages(self):
<del> for directory in ["operator", "hooks", "sensors", "task_runner"]:
<add> for directory in ["hooks", "operators", "secrets", "sensors", "task_runner"]:
<ide> path_pattern = f"{ROOT_FOLDER}/airflow/contrib/{directory}/*.py"
<ide>
<ide> for filename in glob.glob(path_pattern, recursive=True): | 1 |
Javascript | Javascript | add 惠首尔(huiseoul) to showcase | 2ee910a11ae02d1aca9228cc110e24f8f1f18a92 | <ide><path>website/src/react-native/showcase.js
<ide> var featured = [
<ide> infoLink: 'https://artsy.github.io/series/react-native-at-artsy/',
<ide> infoTitle: 'React Native at Artsy',
<ide> },
<add> {
<add> name: 'Huiseoul(惠首尔)',
<add> icon: 'https://cdn.huiseoul.com/icon.png',
<add> linkAppStore: 'https://itunes.apple.com/us/app/hui-shou-er-ni-si-ren-mei/id1127150360?ls=1&mt=8',
<add> infoLink: 'https://engineering.huiseoul.com/building-a-conversational-e-commerce-app-in-6-weeks-with-react-native-c35d46637e07',
<add> infoTitle: 'Building a conversational E-commerce app in 6 weeks with React Native',
<add> },
<ide> ];
<ide>
<ide> featured.sort(function(a, b) { | 1 |
Text | Text | improve buffer() text | d74919cc1a47f4f40766ba7f37ab434db246e700 | <ide><path>doc/api/buffer.md
<ide> In versions of Node.js prior to 6.0.0, `Buffer` instances were created using the
<ide> `Buffer` constructor function, which allocates the returned `Buffer`
<ide> differently based on what arguments are provided:
<ide>
<del>* Passing a number as the first argument to `Buffer()` (e.g. `new Buffer(10)`),
<add>* Passing a number as the first argument to `Buffer()` (e.g. `new Buffer(10)`)
<ide> allocates a new `Buffer` object of the specified size. Prior to Node.js 8.0.0,
<ide> the memory allocated for such `Buffer` instances is *not* initialized and
<ide> *can contain sensitive data*. Such `Buffer` instances *must* be subsequently
<ide> initialized by using either [`buf.fill(0)`][`buf.fill()`] or by writing to the
<del> `Buffer` completely. While this behavior is *intentional* to improve
<del> performance, development experience has demonstrated that a more explicit
<del> distinction is required between creating a fast-but-uninitialized `Buffer`
<del> versus creating a slower-but-safer `Buffer`. Starting in Node.js 8.0.0,
<del> `Buffer(num)` and `new Buffer(num)` will return a `Buffer` with initialized
<del> memory.
<add> entire `Buffer`. While this behavior is *intentional* to improve performance,
<add> development experience has demonstrated that a more explicit distinction is
<add> required between creating a fast-but-uninitialized `Buffer` versus creating a
<add> slower-but-safer `Buffer`. Starting in Node.js 8.0.0, `Buffer(num)` and
<add> `new Buffer(num)` will return a `Buffer` with initialized memory.
<ide> * Passing a string, array, or `Buffer` as the first argument copies the
<ide> passed object's data into the `Buffer`.
<ide> * Passing an [`ArrayBuffer`] or a [`SharedArrayBuffer`] returns a `Buffer` that
<ide> shares allocated memory with the given array buffer.
<ide>
<ide> Because the behavior of `new Buffer()` is different depending on the type of the
<del>first argument, security and reliability issues can be inadvertantly introduced
<del>into applications when argument validation or `Buffer` initialization are not
<add>first argument, security and reliability issues can be inadvertently introduced
<add>into applications when argument validation or `Buffer` initialization is not
<ide> performed.
<ide>
<del>To make the creation of `Buffer` instances more reliable and less error prone,
<add>To make the creation of `Buffer` instances more reliable and less error-prone,
<ide> the various forms of the `new Buffer()` constructor have been **deprecated**
<ide> and replaced by separate `Buffer.from()`, [`Buffer.alloc()`], and
<ide> [`Buffer.allocUnsafe()`] methods.
<ide>
<ide> *Developers should migrate all existing uses of the `new Buffer()` constructors
<ide> to one of these new APIs.*
<ide>
<del>* [`Buffer.from(array)`] returns a new `Buffer` containing a *copy* of the provided
<del> octets.
<add>* [`Buffer.from(array)`] returns a new `Buffer` that *contains a copy* of the
<add> provided octets.
<ide> * [`Buffer.from(arrayBuffer[, byteOffset [, length]])`][`Buffer.from(arrayBuffer)`]
<del> returns a new `Buffer` that *shares* the same allocated memory as the given
<add> returns a new `Buffer` that *shares the same allocated memory* as the given
<ide> [`ArrayBuffer`].
<del>* [`Buffer.from(buffer)`] returns a new `Buffer` containing a *copy* of the
<add>* [`Buffer.from(buffer)`] returns a new `Buffer` that *contains a copy* of the
<ide> contents of the given `Buffer`.
<del>* [`Buffer.from(string[, encoding])`][`Buffer.from(string)`] returns a new `Buffer`
<del> containing a *copy* of the provided string.
<del>* [`Buffer.alloc(size[, fill[, encoding]])`][`Buffer.alloc()`] returns a "filled"
<del> `Buffer` instance of the specified size. This method can be significantly
<del> slower than [`Buffer.allocUnsafe(size)`][`Buffer.allocUnsafe()`] but ensures
<del> that newly created `Buffer` instances never contain old and potentially
<del> sensitive data.
<add>* [`Buffer.from(string[, encoding])`][`Buffer.from(string)`] returns a new
<add> `Buffer` that *contains a copy* of the provided string.
<add>* [`Buffer.alloc(size[, fill[, encoding]])`][`Buffer.alloc()`] returns a new
<add> initialized `Buffer` of the specified size. This method is slower than
<add> [`Buffer.allocUnsafe(size)`][`Buffer.allocUnsafe()`] but guarantees that newly
<add> created `Buffer` instances never contain old data that is potentially
<add> sensitive.
<ide> * [`Buffer.allocUnsafe(size)`][`Buffer.allocUnsafe()`] and
<ide> [`Buffer.allocUnsafeSlow(size)`][`Buffer.allocUnsafeSlow()`] each return a
<del> new `Buffer` of the specified `size` whose content *must* be initialized
<del> using either [`buf.fill(0)`][`buf.fill()`] or written to completely.
<add> new uninitialized `Buffer` of the specified `size`. Because the `Buffer` is
<add> uninitialized, the allocated segment of memory might contain old data that is
<add> potentially sensitive.
<ide>
<ide> `Buffer` instances returned by [`Buffer.allocUnsafe()`] *may* be allocated off
<ide> a shared internal memory pool if `size` is less than or equal to half
<ide> force all newly allocated `Buffer` instances created using either
<ide> this flag *changes the default behavior* of these methods and *can have a significant
<ide> impact* on performance. Use of the `--zero-fill-buffers` option is recommended
<ide> only when necessary to enforce that newly allocated `Buffer` instances cannot
<del>contain potentially sensitive data.
<add>contain old data that is potentially sensitive.
<ide>
<ide> ```txt
<ide> $ node --zero-fill-buffers | 1 |
Ruby | Ruby | add an asset_host accessor for consistency | 71375c8936696d8d7404e02ff84e3dbde3d57029 | <ide><path>actionpack/lib/action_controller/base.rb
<ide> def self.subclasses
<ide> @subclasses ||= []
<ide> end
<ide>
<del> # TODO Move this to the appropriate module
<del> config_accessor :asset_path
<add> config_accessor :asset_host, :asset_path
<ide>
<ide> ActiveSupport.run_load_hooks(:action_controller, self)
<ide> end | 1 |
Go | Go | fix an issue trying to pull specific tag | 49505c599b3a65196b6b6f746f4bfad3a417dd7a | <ide><path>builder_client.go
<ide> func (b *builderClient) clearTmp(containers, images map[string]struct{}) {
<ide> func (b *builderClient) CmdFrom(name string) error {
<ide> obj, statusCode, err := b.cli.call("GET", "/images/"+name+"/json", nil)
<ide> if statusCode == 404 {
<del> if err := b.cli.hijack("POST", "/images/create?fromImage="+name, false); err != nil {
<add>
<add> remote := name
<add> var tag string
<add> if strings.Contains(remote, ":") {
<add> remoteParts := strings.Split(remote, ":")
<add> tag = remoteParts[1]
<add> remote = remoteParts[0]
<add> }
<add> var out io.Writer
<add> if os.Getenv("DEBUG") != "" {
<add> out = os.Stdout
<add> } else {
<add> out = &utils.NopWriter{}
<add> }
<add> if err := b.cli.stream("POST", "/images/create?fromImage="+remote+"&tag="+tag, nil, out); err != nil {
<ide> return err
<ide> }
<ide> obj, _, err = b.cli.call("GET", "/images/"+name+"/json", nil)
<ide> func (b *builderClient) commit(id string) error {
<ide> }
<ide>
<ide> func (b *builderClient) Build(dockerfile io.Reader) (string, error) {
<del> // defer b.clearTmp(tmpContainers, tmpImages)
<add> defer b.clearTmp(b.tmpContainers, b.tmpImages)
<ide> file := bufio.NewReader(dockerfile)
<ide> for {
<ide> line, err := file.ReadString('\n')
<ide><path>server.go
<ide> func (srv *Server) pullRepository(out io.Writer, remote, askedTag string) error
<ide>
<ide> for _, img := range repoData.ImgList {
<ide> if askedTag != "" && img.Tag != askedTag {
<del> utils.Debugf("%s does not match %s, skipping", img.Tag, askedTag)
<add> utils.Debugf("(%s) does not match %s (id: %s), skipping", img.Tag, askedTag, img.Id)
<ide> continue
<ide> }
<ide> fmt.Fprintf(out, "Pulling image %s (%s) from %s\n", img.Id, img.Tag, remote)
<ide> func (srv *Server) pullRepository(out io.Writer, remote, askedTag string) error
<ide> return fmt.Errorf("Could not find repository on any of the indexed registries.")
<ide> }
<ide> }
<del> // If we asked for a specific tag, do not register the others
<del> if askedTag != "" {
<del> return nil
<del> }
<ide> for tag, id := range tagsList {
<add> if askedTag != "" && tag != askedTag {
<add> continue
<add> }
<ide> if err := srv.runtime.repositories.Set(remote, tag, id, true); err != nil {
<ide> return err
<ide> } | 2 |
Javascript | Javascript | fix eslint issues | 2bef01fc9c151931a685e2e1a4e0436f85fe8122 | <ide><path>test/unit/src/math/Quaternion.tests.js
<ide> export default QUnit.module( 'Maths', () => {
<ide>
<ide> QUnit.test( "_onChange", ( assert ) => {
<ide>
<del>
<add> var b = false;
<ide> var f = function () {
<ide>
<del> var b = true;
<add> b = true;
<ide>
<ide> };
<ide>
<ide> var a = new Quaternion( 11, 12, 13, 1 );
<ide> a._onChange( f );
<ide> assert.ok( a._onChangeCallback === f, "Passed!" );
<ide>
<add> a._onChangeCallback();
<add> assert.ok( b, "Passed!" );
<add>
<add>
<ide> } );
<ide>
<ide> QUnit.test( "_onChangeCallback", ( assert ) => {
<ide>
<add> var b = false;
<ide> var f = function () {
<ide>
<del> var b = true;
<add> b = true;
<ide>
<ide> };
<ide>
<ide> var a = new Quaternion( 11, 12, 13, 1 );
<ide> a._onChangeCallback = f;
<ide> assert.ok( a._onChangeCallback === f, "Passed!" );
<ide>
<add>
<add> a._onChangeCallback();
<add> assert.ok( b, "Passed!" );
<add>
<ide> } );
<ide>
<ide> // OTHERS | 1 |
PHP | PHP | fix failing test | c0e896016017acf30b1e531e4073b27487d2e91a | <ide><path>tests/TestCase/ORM/QueryTest.php
<ide> public function testSelectLargeNumbers()
<ide> {
<ide> $this->loadFixtures('Datatypes');
<ide>
<del> $big = '1234567890123456789';
<add> $big = 1234567890123456789.2;
<ide> $table = TableRegistry::get('Datatypes');
<del> $entity = $table->newEntity([
<del> 'cost' => $big,
<del> ]);
<add> $entity = $table->newEntity([]);
<add> $entity->cost = $big;
<ide> $table->save($entity);
<ide> $out = $table->find()->where([
<ide> 'cost' => $big
<ide> ])->first();
<add> $this->assertNotEmpty($out, 'Should get a record');
<ide> $this->assertSame(sprintf('%F', $big), sprintf('%F', $out->cost));
<ide> }
<ide> | 1 |
Python | Python | add test for m2m create | f72be7b8faf4489c904bb6df97d51274872315bb | <ide><path>rest_framework/tests/pk_relations.py
<ide> def test_reverse_many_to_many_update(self):
<ide> ]
<ide> self.assertEquals(serializer.data, expected)
<ide>
<add> def test_many_to_many_create(self):
<add> data = {'id': 4, 'name': u'source-4', 'targets': [1, 3]}
<add> serializer = ManyToManySourceSerializer(data=data)
<add> self.assertTrue(serializer.is_valid())
<add> obj = serializer.save()
<add> self.assertEquals(serializer.data, data)
<add> self.assertEqual(obj.name, u'source-4')
<add>
<add> # Ensure source 4 is added, and everything else is as expected
<add> queryset = ManyToManySource.objects.all()
<add> serializer = ManyToManySourceSerializer(queryset)
<add> expected = [
<add> {'id': 1, 'name': u'source-1', 'targets': [1]},
<add> {'id': 2, 'name': u'source-2', 'targets': [1, 2]},
<add> {'id': 3, 'name': u'source-3', 'targets': [1, 2, 3]},
<add> {'id': 4, 'name': u'source-4', 'targets': [1, 3]},
<add> ]
<add> self.assertEquals(serializer.data, expected)
<add>
<ide> def test_reverse_many_to_many_create(self):
<ide> data = {'id': 4, 'name': u'target-4', 'sources': [1, 3]}
<ide> serializer = ManyToManyTargetSerializer(data=data) | 1 |
Java | Java | add cbor codec (single value only) | 5cd67631939fb7e55e580d17601948808a03006b | <ide><path>spring-web/src/main/java/org/springframework/http/codec/cbor/Jackson2CborDecoder.java
<add>/*
<add> * Copyright 2002-2019 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.http.codec.cbor;
<add>
<add>import java.util.Map;
<add>
<add>import com.fasterxml.jackson.databind.ObjectMapper;
<add>import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
<add>import org.reactivestreams.Publisher;
<add>import reactor.core.publisher.Flux;
<add>
<add>import org.springframework.core.ResolvableType;
<add>import org.springframework.core.io.buffer.DataBuffer;
<add>import org.springframework.http.MediaType;
<add>import org.springframework.http.codec.json.AbstractJackson2Decoder;
<add>import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
<add>import org.springframework.util.Assert;
<add>import org.springframework.util.MimeType;
<add>
<add>/**
<add> * Decode bytes into CBOR and convert to Object's with Jackson.
<add> * Stream decoding is not supported yet.
<add> *
<add> * @author Sebastien Deleuze
<add> * @since 5.2
<add> * @see Jackson2CborEncoder
<add> * @see <a href="https://github.com/spring-projects/spring-framework/issues/20513">Add CBOR support to WebFlux</a>
<add> */
<add>public class Jackson2CborDecoder extends AbstractJackson2Decoder {
<add>
<add> public Jackson2CborDecoder() {
<add> this(Jackson2ObjectMapperBuilder.cbor().build(), new MediaType("application", "cbor"));
<add> }
<add>
<add> public Jackson2CborDecoder(ObjectMapper mapper, MimeType... mimeTypes) {
<add> super(mapper, mimeTypes);
<add> Assert.isAssignable(CBORFactory.class, mapper.getFactory().getClass());
<add> }
<add>
<add> @Override
<add> public Flux<Object> decode(Publisher<DataBuffer> input, ResolvableType elementType, MimeType mimeType, Map<String, Object> hints) {
<add> throw new UnsupportedOperationException("Does not support stream decoding yet");
<add> }
<add>}
<ide><path>spring-web/src/main/java/org/springframework/http/codec/cbor/Jackson2CborEncoder.java
<add>/*
<add> * Copyright 2002-2019 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.http.codec.cbor;
<add>
<add>import java.util.Map;
<add>
<add>import com.fasterxml.jackson.databind.ObjectMapper;
<add>import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
<add>import org.reactivestreams.Publisher;
<add>import reactor.core.publisher.Flux;
<add>
<add>import org.springframework.core.ResolvableType;
<add>import org.springframework.core.io.buffer.DataBuffer;
<add>import org.springframework.core.io.buffer.DataBufferFactory;
<add>import org.springframework.http.MediaType;
<add>import org.springframework.http.codec.json.AbstractJackson2Encoder;
<add>import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
<add>import org.springframework.util.Assert;
<add>import org.springframework.util.MimeType;
<add>
<add>/**
<add> * Encode from an {@code Object} to bytes of CBOR objects using Jackson.
<add> * Stream encoding is not supported yet.
<add> *
<add> * @author Sebastien Deleuze
<add> * @since 5.2
<add> * @see Jackson2CborDecoder
<add> * @see <a href="https://github.com/spring-projects/spring-framework/issues/20513">Add CBOR support to WebFlux</a>
<add> */
<add>public class Jackson2CborEncoder extends AbstractJackson2Encoder {
<add>
<add> public Jackson2CborEncoder() {
<add> this(Jackson2ObjectMapperBuilder.cbor().build(), new MediaType("application", "cbor"));
<add> }
<add>
<add> public Jackson2CborEncoder(ObjectMapper mapper, MimeType... mimeTypes) {
<add> super(mapper, mimeTypes);
<add> Assert.isAssignable(CBORFactory.class, mapper.getFactory().getClass());
<add> }
<add>
<add> @Override
<add> public Flux<DataBuffer> encode(Publisher<?> inputStream, DataBufferFactory bufferFactory, ResolvableType elementType, MimeType mimeType, Map<String, Object> hints) {
<add> throw new UnsupportedOperationException("Does not support stream encoding yet");
<add> }
<add>}
<ide><path>spring-web/src/test/java/org/springframework/http/codec/cbor/Jackson2CborDecoderTests.java
<add>/*
<add> * Copyright 2002-2019 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.http.codec.cbor;
<add>
<add>import java.util.Arrays;
<add>import java.util.List;
<add>
<add>import com.fasterxml.jackson.core.JsonProcessingException;
<add>import com.fasterxml.jackson.databind.ObjectMapper;
<add>import org.junit.Test;
<add>import reactor.core.publisher.Flux;
<add>
<add>import org.springframework.core.ResolvableType;
<add>import org.springframework.core.codec.AbstractDecoderTestCase;
<add>import org.springframework.core.io.buffer.DataBuffer;
<add>import org.springframework.http.codec.Pojo;
<add>import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
<add>import org.springframework.util.MimeType;
<add>
<add>import static org.junit.Assert.assertFalse;
<add>import static org.junit.Assert.assertTrue;
<add>import static org.springframework.core.ResolvableType.forClass;
<add>import static org.springframework.http.MediaType.APPLICATION_JSON;
<add>
<add>/**
<add> * Unit tests for {@link Jackson2CborDecoder}.
<add> *
<add> * @author Sebastien Deleuze
<add> */
<add>public class Jackson2CborDecoderTests extends AbstractDecoderTestCase<Jackson2CborDecoder> {
<add>
<add> private final static MimeType CBOR_MIME_TYPE = new MimeType("application", "cbor");
<add>
<add> private Pojo pojo1 = new Pojo("f1", "b1");
<add>
<add> private Pojo pojo2 = new Pojo("f2", "b2");
<add>
<add> private ObjectMapper mapper = Jackson2ObjectMapperBuilder.cbor().build();
<add>
<add> public Jackson2CborDecoderTests() {
<add> super(new Jackson2CborDecoder());
<add> }
<add>
<add> @Override
<add> @Test
<add> public void canDecode() {
<add> assertTrue(decoder.canDecode(forClass(Pojo.class), CBOR_MIME_TYPE));
<add> assertTrue(decoder.canDecode(forClass(Pojo.class), null));
<add>
<add> assertFalse(decoder.canDecode(forClass(String.class), null));
<add> assertFalse(decoder.canDecode(forClass(Pojo.class), APPLICATION_JSON));
<add> }
<add>
<add> @Override
<add> @Test(expected = UnsupportedOperationException.class)
<add> public void decode() {
<add> Flux<DataBuffer> input = Flux.just(this.pojo1, this.pojo2)
<add> .map(this::writeObject)
<add> .flatMap(this::dataBuffer);
<add>
<add> testDecodeAll(input, Pojo.class, step -> step
<add> .expectNext(pojo1)
<add> .expectNext(pojo2)
<add> .verifyComplete());
<add>
<add> }
<add>
<add> private byte[] writeObject(Object o) {
<add> try {
<add> return this.mapper.writer().writeValueAsBytes(o);
<add> }
<add> catch (JsonProcessingException e) {
<add> throw new AssertionError(e);
<add> }
<add>
<add> }
<add>
<add> @Override
<add> public void decodeToMono() {
<add> List<Pojo> expected = Arrays.asList(pojo1, pojo2);
<add>
<add> Flux<DataBuffer> input = Flux.just(expected)
<add> .map(this::writeObject)
<add> .flatMap(this::dataBuffer);
<add>
<add> ResolvableType elementType = ResolvableType.forClassWithGenerics(List.class, Pojo.class);
<add> testDecodeToMono(input, elementType, step -> step
<add> .expectNext(expected)
<add> .expectComplete()
<add> .verify(), null, null);
<add> }
<add>}
<ide><path>spring-web/src/test/java/org/springframework/http/codec/cbor/Jackson2CborEncoderTests.java
<add>/*
<add> * Copyright 2002-2019 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.http.codec.cbor;
<add>
<add>import java.io.IOException;
<add>import java.io.UncheckedIOException;
<add>import java.util.function.Consumer;
<add>
<add>import com.fasterxml.jackson.databind.ObjectMapper;
<add>import org.junit.Test;
<add>import reactor.core.publisher.Flux;
<add>
<add>import org.springframework.core.ResolvableType;
<add>import org.springframework.core.io.buffer.AbstractLeakCheckingTestCase;
<add>import org.springframework.core.io.buffer.DataBuffer;
<add>import org.springframework.core.io.buffer.support.DataBufferTestUtils;
<add>import org.springframework.http.codec.Pojo;
<add>import org.springframework.http.codec.ServerSentEvent;
<add>import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
<add>import org.springframework.util.MimeType;
<add>
<add>import static org.junit.Assert.assertEquals;
<add>import static org.junit.Assert.assertFalse;
<add>import static org.junit.Assert.assertTrue;
<add>import static org.springframework.core.io.buffer.DataBufferUtils.release;
<add>import static org.springframework.http.MediaType.APPLICATION_XML;
<add>
<add>/**
<add> * Unit tests for {@link Jackson2CborEncoder}.
<add> *
<add> * @author Sebastien Deleuze
<add> */
<add>public class Jackson2CborEncoderTests extends AbstractLeakCheckingTestCase {
<add>
<add> private final static MimeType CBOR_MIME_TYPE = new MimeType("application", "cbor");
<add>
<add> private final ObjectMapper mapper = Jackson2ObjectMapperBuilder.cbor().build();
<add>
<add> private final Jackson2CborEncoder encoder = new Jackson2CborEncoder();
<add>
<add> private Consumer<DataBuffer> pojoConsumer(Pojo expected) {
<add> return dataBuffer -> {
<add> try {
<add> Pojo actual = this.mapper.reader().forType(Pojo.class)
<add> .readValue(DataBufferTestUtils.dumpBytes(dataBuffer));
<add> assertEquals(expected, actual);
<add> release(dataBuffer);
<add> }
<add> catch (IOException ex) {
<add> throw new UncheckedIOException(ex);
<add> }
<add> };
<add> }
<add>
<add> @Test
<add> public void canEncode() {
<add> ResolvableType pojoType = ResolvableType.forClass(Pojo.class);
<add> assertTrue(this.encoder.canEncode(pojoType, CBOR_MIME_TYPE));
<add> assertTrue(this.encoder.canEncode(pojoType, null));
<add>
<add> // SPR-15464
<add> assertTrue(this.encoder.canEncode(ResolvableType.NONE, null));
<add> }
<add>
<add> @Test
<add> public void canNotEncode() {
<add> assertFalse(this.encoder.canEncode(ResolvableType.forClass(String.class), null));
<add> assertFalse(this.encoder.canEncode(ResolvableType.forClass(Pojo.class), APPLICATION_XML));
<add>
<add> ResolvableType sseType = ResolvableType.forClass(ServerSentEvent.class);
<add> assertFalse(this.encoder.canEncode(sseType, CBOR_MIME_TYPE));
<add> }
<add>
<add> @Test
<add> public void encode() {
<add> Pojo value = new Pojo("foo", "bar");
<add> DataBuffer result = encoder.encodeValue(value, this.bufferFactory, ResolvableType.forClass(Pojo.class), CBOR_MIME_TYPE, null);
<add> pojoConsumer(value).accept(result);
<add> }
<add>
<add> @Test(expected = UnsupportedOperationException.class)
<add> public void encodeStream() {
<add> Pojo pojo1 = new Pojo("foo", "bar");
<add> Pojo pojo2 = new Pojo("foofoo", "barbar");
<add> Pojo pojo3 = new Pojo("foofoofoo", "barbarbar");
<add> Flux<Pojo> input = Flux.just(pojo1, pojo2, pojo3);
<add> ResolvableType type = ResolvableType.forClass(Pojo.class);
<add> encoder.encode(input, this.bufferFactory, type, CBOR_MIME_TYPE, null);
<add> }
<add>} | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.