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
|
---|---|---|---|---|---|
Javascript | Javascript | hide reactelement constructor | 20af6b0a140c84f46d214cdc90a7c7aa9da1bf83 | <ide><path>src/core/ReactElement.js
<ide> var ReactElement = function(type, key, ref, owner, context, props) {
<ide> this.props = props;
<ide> };
<ide>
<add>// We intentionally don't expose the function on the constructor property.
<add>// ReactElement should be indistinguishable from a plain object.
<add>ReactElement.prototype = {
<add> _isReactElement: true
<add>};
<add>
<ide> if (__DEV__) {
<ide> defineMutationMembrane(ReactElement.prototype);
<ide> }
<ide>
<del>ReactElement.prototype._isReactElement = true;
<del>
<ide> ReactElement.createElement = function(type, config, children) {
<ide> var propName;
<ide>
<ide><path>src/core/__tests__/ReactElement-test.js
<ide> describe('ReactElement', function() {
<ide> expect(instance.getDOMNode().tagName).toBe('DIV');
<ide> });
<ide>
<add> it('is indistinguishable from a plain object', function() {
<add> var element = React.createElement('div', { className: 'foo' });
<add> var object = {};
<add> expect(element.constructor).toBe(object.constructor);
<add> });
<add>
<ide> }); | 2 |
Ruby | Ruby | fix a regression in association preloader | 830da94739830f3b509feb397e94265514f6075e | <ide><path>activerecord/lib/active_record/associations/preloader/batch.rb
<ide> class Preloader
<ide> class Batch # :nodoc:
<ide> def initialize(preloaders, available_records:)
<ide> @preloaders = preloaders.reject(&:empty?)
<del> @available_records = available_records.flatten
<add> @available_records = available_records.flatten.group_by { |r| r.class.base_class }
<ide> end
<ide>
<ide> def call
<ide> branches = @preloaders.flat_map(&:branches)
<ide> until branches.empty?
<ide> loaders = branches.flat_map(&:runnable_loaders)
<ide>
<del> loaders.each { |loader| loader.associate_records_from_unscoped(@available_records) }
<add> loaders.each { |loader| loader.associate_records_from_unscoped(@available_records[loader.klass.base_class]) }
<ide>
<ide> if loaders.any?
<ide> future_tables = branches.flat_map do |branch|
<ide><path>activerecord/test/cases/associations_test.rb
<ide> def test_preload_with_unpersisted_records_no_ops
<ide> assert_nil new_post_without_author.author
<ide> end
<ide> end
<add>
<add> def test_preload_wont_set_the_wrong_target
<add> post = posts(:welcome)
<add> post.update!(author_id: 54321)
<add> some_other_record = categories(:general)
<add> some_other_record.update!(id: 54321)
<add>
<add> assert_raises do
<add> some_other_record.association(:author)
<add> end
<add>
<add> assert_nothing_raised do
<add> ActiveRecord::Associations::Preloader.new(records: [post], associations: :author, available_records: [[some_other_record]]).call
<add> assert post.association(:author).loaded?
<add> assert_not_equal some_other_record, post.author
<add> end
<add> end
<ide> end
<ide>
<ide> class GeneratedMethodsTest < ActiveRecord::TestCase | 2 |
Python | Python | fix advanced activations | a066cf8680372f107f4da35b1518998a851e02b7 | <ide><path>keras/engine/topology.py
<ide> class Container(Layer):
<ide> def __init__(self, input, output, name=None):
<ide> # handle name argument
<ide> if not name:
<del> name = self.__class__.__name__.lower() + '_' + str(id(self))
<add> prefix = self.__class__.__name__.lower()
<add> name = prefix + '_' + str(K.get_uid(prefix))
<ide> self.name = name
<ide>
<ide> # Container-specific properties
<ide> def __init__(self, input, output, name=None):
<ide> if len(layer.inbound_nodes) > 1 or (layer.inbound_nodes and layer.inbound_nodes[0].inbound_layers):
<ide> cls_name = self.__class__.__name__
<ide> raise Exception(cls_name + ' inputs must come from '
<del> 'a Keras `Input` layer, '
<add> 'a Keras Input layer, '
<ide> 'they cannot be the output of '
<ide> 'a previous non-Input layer. '
<del> 'Here, the tensor specified as '
<del> 'input to "' + self.name +
<add> 'Here, a tensor specified as '
<add> 'input to "' + self.name +
<ide> '" was not an Input tensor, '
<ide> 'it was generated by layer ' +
<ide> layer.name + '.\n'
<ide> 'Note that input tensors are '
<del> 'instantiated via `tensor = Input(shape)`.')
<add> 'instantiated via `tensor = Input(shape)`.\n'
<add> 'The tensor that caused the issue was: ' +
<add> str(x.name))
<ide> for x in self.outputs:
<ide> if not hasattr(x, '_keras_history'):
<ide> cls_name = self.__class__.__name__
<ide><path>keras/layers/advanced_activations.py
<ide> class LeakyReLU(Layer):
<ide> '''
<ide> def __init__(self, alpha=0.3, **kwargs):
<ide> self.supports_masking = True
<del> self.alpha = alpha
<add> self.alpha = K.cast_to_floatx(alpha)
<ide> super(LeakyReLU, self).__init__(**kwargs)
<ide>
<del> def get_output(self, train):
<del> X = self.get_input(train)
<del> return K.relu(X, alpha=self.alpha)
<add> def call(self, x, mask=None):
<add> return K.relu(x, alpha=self.alpha)
<ide>
<ide> def get_config(self):
<del> config = {'name': self.__class__.__name__,
<del> 'alpha': self.alpha}
<add> config = {'alpha': self.alpha}
<ide> base_config = super(LeakyReLU, self).get_config()
<ide> return dict(list(base_config.items()) + list(config.items()))
<ide>
<ide>
<ide> class PReLU(Layer):
<del> '''
<add> '''Parametric Rectified Linear Unit.
<add>
<ide> # Input shape
<ide> Arbitrary. Use the keyword argument `input_shape`
<ide> (tuple of integers, does not include the samples axis)
<ide> def __init__(self, init='zero', weights=None, **kwargs):
<ide> self.initial_weights = weights
<ide> super(PReLU, self).__init__(**kwargs)
<ide>
<del> def build(self):
<del> input_shape = self.input_shape[1:]
<del> self.alphas = self.init(input_shape,
<add> def build(self, input_shape):
<add> self.alphas = self.init(input_shape[1:],
<ide> name='{}_alphas'.format(self.name))
<ide> self.trainable_weights = [self.alphas]
<ide>
<ide> if self.initial_weights is not None:
<ide> self.set_weights(self.initial_weights)
<ide> del self.initial_weights
<ide>
<del> def get_output(self, train):
<del> X = self.get_input(train)
<del> pos = K.relu(X)
<del> neg = self.alphas * (X - abs(X)) * 0.5
<add> def call(self, x, mask=None):
<add> pos = K.relu(x)
<add> neg = self.alphas * (x - abs(x)) * 0.5
<ide> return pos + neg
<ide>
<ide> def get_config(self):
<del> config = {'name': self.__class__.__name__,
<del> 'init': self.init.__name__}
<add> config = {'init': self.init.__name__}
<ide> base_config = super(PReLU, self).get_config()
<ide> return dict(list(base_config.items()) + list(config.items()))
<ide>
<ide>
<ide> class ELU(Layer):
<del> '''
<add> '''Exponential Linear Unit.
<add>
<ide> # Input shape
<ide> Arbitrary. Use the keyword argument `input_shape`
<ide> (tuple of integers, does not include the samples axis)
<ide> class ELU(Layer):
<ide> '''
<ide> def __init__(self, alpha=1.0, **kwargs):
<ide> self.supports_masking = True
<del> self.alpha = alpha
<add> self.alpha = K.cast_to_floatx(alpha)
<ide> super(ELU, self).__init__(**kwargs)
<ide>
<del> def get_output(self, train):
<del> X = self.get_input(train)
<del> pos = K.relu(X)
<del> neg = (X - abs(X)) * 0.5
<add> def call(self, x, mask=None):
<add> pos = K.relu(x)
<add> neg = (x - abs(x)) * 0.5
<ide> return pos + self.alpha * (K.exp(neg) - 1.)
<ide>
<ide> def get_config(self):
<del> config = {'name': self.__class__.__name__,
<del> 'alpha': self.alpha}
<add> config = {'alpha': self.alpha}
<ide> base_config = super(ELU, self).get_config()
<ide> return dict(list(base_config.items()) + list(config.items()))
<ide>
<ide> class ParametricSoftplus(Layer):
<ide> def __init__(self, alpha_init=0.2, beta_init=5.0,
<ide> weights=None, **kwargs):
<ide> self.supports_masking = True
<del> self.alpha_init = alpha_init
<del> self.beta_init = beta_init
<add> self.alpha_init = K.cast_to_floatx(alpha_init)
<add> self.beta_init = K.cast_to_floatx(beta_init)
<ide> self.initial_weights = weights
<ide> super(ParametricSoftplus, self).__init__(**kwargs)
<ide>
<del> def build(self):
<del> input_shape = self.input_shape[1:]
<add> def build(self, input_shape):
<add> input_shape = input_shape[1:]
<ide> self.alphas = K.variable(self.alpha_init * np.ones(input_shape),
<ide> name='{}_alphas'.format(self.name))
<ide> self.betas = K.variable(self.beta_init * np.ones(input_shape),
<ide> def build(self):
<ide> self.set_weights(self.initial_weights)
<ide> del self.initial_weights
<ide>
<del> def get_output(self, train):
<del> X = self.get_input(train)
<del> return K.softplus(self.betas * X) * self.alphas
<add> def call(self, x, mask=None):
<add> return K.softplus(self.betas * x) * self.alphas
<ide>
<ide> def get_config(self):
<del> config = {'name': self.__class__.__name__,
<del> 'alpha_init': self.alpha_init,
<add> config = {'alpha_init': self.alpha_init,
<ide> 'beta_init': self.beta_init}
<ide> base_config = super(ParametricSoftplus, self).get_config()
<ide> return dict(list(base_config.items()) + list(config.items()))
<ide> class ThresholdedLinear(Layer):
<ide> '''
<ide> def __init__(self, theta=1.0, **kwargs):
<ide> self.supports_masking = True
<del> self.theta = theta
<add> self.theta = K.cast_to_floatx(theta)
<ide> super(ThresholdedLinear, self).__init__(**kwargs)
<ide>
<del> def get_output(self, train):
<del> X = self.get_input(train)
<del> return K.switch(K.abs(X) < self.theta, 0, X)
<add> def call(self, x, mask=None):
<add> return x * K.cast(x > self.theta, K.floatx())
<ide>
<ide> def get_config(self):
<del> config = {'name': self.__class__.__name__,
<del> 'theta': self.theta}
<add> config = {'theta': self.theta}
<ide> base_config = super(ThresholdedLinear, self).get_config()
<ide> return dict(list(base_config.items()) + list(config.items()))
<ide>
<ide>
<ide> class ThresholdedReLU(Layer):
<del> '''Thresholded Rectified Activation.
<add> '''Thresholded Rectified Linear Unit.
<ide>
<ide> # Input shape
<ide> Arbitrary. Use the keyword argument `input_shape`
<ide> class ThresholdedReLU(Layer):
<ide> '''
<ide> def __init__(self, theta=1.0, **kwargs):
<ide> self.supports_masking = True
<del> self.theta = theta
<add> self.theta = K.cast_to_floatx(theta)
<ide> super(ThresholdedReLU, self).__init__(**kwargs)
<ide>
<del> def get_output(self, train):
<del> X = self.get_input(train)
<del> return K.switch(X > self.theta, X, 0)
<add> def call(self, x, mask=None):
<add> return x * K.cast(x > self.theta, K.floatx())
<ide>
<ide> def get_config(self):
<del> config = {'name': self.__class__.__name__,
<del> 'theta': self.theta}
<add> config = {'theta': self.theta}
<ide> base_config = super(ThresholdedReLU, self).get_config()
<ide> return dict(list(base_config.items()) + list(config.items()))
<ide>
<ide>
<ide> class SReLU(Layer):
<del> '''SReLU
<add> '''S-shaped Rectified Linear Unit.
<ide>
<ide> # Input shape
<ide> Arbitrary. Use the keyword argument `input_shape`
<ide> class SReLU(Layer):
<ide> def __init__(self, t_left_init='zero', a_left_init='glorot_uniform',
<ide> t_right_init='glorot_uniform', a_right_init='one', **kwargs):
<ide> self.supports_masking = True
<del> self.t_left_init = initializations.get(t_left_init)
<del> self.a_left_init = initializations.get(a_left_init)
<del> self.t_right_init = initializations.get(t_right_init)
<del> self.a_right_init = initializations.get(a_right_init)
<add> self.t_left_init = t_left_init
<add> self.a_left_init = a_left_init
<add> self.t_right_init = t_right_init
<add> self.a_right_init = a_right_init
<ide> super(SReLU, self).__init__(**kwargs)
<ide>
<del> def build(self):
<del> input_shape = self.input_shape[1:]
<del> self.t_left = self.t_left_init(input_shape,
<del> name='{}_t_left'.format(self.name))
<del> self.a_left = self.a_left_init(input_shape,
<del> name='{}_a_left'.format(self.name))
<del> self.t_right = self.t_right_init(input_shape,
<del> name='{}_t_right'.format(self.name))
<del> self.a_right = self.a_right_init(input_shape,
<del> name='{}_a_right'.format(self.name))
<add> def build(self, input_shape):
<add> input_shape = input_shape[1:]
<add>
<add> t_left_init = initializations.get(self.t_left_init)
<add> a_left_init = initializations.get(self.a_left_init)
<add> t_right_init = initializations.get(self.t_right_init)
<add> a_right_init = initializations.get(self.a_right_init)
<add>
<add> self.t_left = t_left_init(input_shape,
<add> name='{}_t_left'.format(self.name))
<add> self.a_left = a_left_init(input_shape,
<add> name='{}_a_left'.format(self.name))
<add> self.t_right = t_right_init(input_shape,
<add> name='{}_t_right'.format(self.name))
<add> self.a_right = a_right_init(input_shape,
<add> name='{}_a_right'.format(self.name))
<ide> # ensure the the right part is always to the right of the left
<ide> self.t_right_actual = self.t_left + abs(self.t_right)
<ide> self.trainable_weights = [self.t_left, self.a_left,
<ide> self.t_right, self.a_right]
<ide>
<del> def get_output(self, train=False):
<del> X = self.get_input(train)
<del> Y_left_and_center = self.t_left + K.relu(X - self.t_left,
<add> def call(self, x, mask=None):
<add> Y_left_and_center = self.t_left + K.relu(x - self.t_left,
<ide> self.a_left,
<ide> self.t_right_actual - self.t_left)
<del> Y_right = K.relu(X - self.t_right_actual) * self.a_right
<add> Y_right = K.relu(x - self.t_right_actual) * self.a_right
<ide> return Y_left_and_center + Y_right
<ide>
<ide> def get_config(self):
<del> return {'name': self.__class__.__name__,
<del> 'input_shape': self.input_shape,
<del> 't_left_init': self.t_left_init,
<del> 'a_left_init': self.a_left_init,
<del> 't_right_init': self.t_right_init,
<del> 'a_right_init': self.a_right_init}
<add> config = {'t_left_init': self.t_left_init,
<add> 'a_left_init': self.a_left_init,
<add> 't_right_init': self.t_right_init,
<add> 'a_right_init': self.a_right_init}
<add> base_config = super(SReLU, self).get_config()
<add> return dict(list(base_config.items()) + list(config.items()))
<ide><path>keras/utils/test_utils.py
<ide> import numpy as np
<add>from numpy.testing import assert_allclose
<add>import inspect
<add>
<ide> from ..engine import Model, Input
<del>from ..models import Sequential
<add>from ..models import Sequential, model_from_json
<add>from .. import backend as K
<ide>
<ide>
<del>def get_test_data(nb_train=1000, nb_test=500, input_shape=(10,), output_shape=(2,),
<add>def get_test_data(nb_train=1000, nb_test=500, input_shape=(10,),
<add> output_shape=(2,),
<ide> classification=True, nb_class=2):
<ide> '''
<ide> classification=True overrides output_shape
<ide> def get_test_data(nb_train=1000, nb_test=500, input_shape=(10,), output_shape=(2
<ide> return (X[:nb_train], y[:nb_train]), (X[nb_train:], y[nb_train:])
<ide>
<ide>
<del>def test_layer(layer, input_shape, input_dtype=None):
<add>def test_layer(layer_cls, kwargs={}, input_shape=None, input_dtype=None,
<add> input_data=None, expected_output=None):
<ide> '''Test routine for a layer with a single input tensor
<ide> and single output tensor.
<ide> '''
<del> if not input_dtype:
<del> input_dtype = K.float()
<del> input_data = (10 * np.random.random(input_shape)).astype(input_dtype)
<add> if input_data is None:
<add> assert input_shape
<add> if not input_dtype:
<add> input_dtype = K.floatx()
<add> input_data = (10 * np.random.random(input_shape)).astype(input_dtype)
<add> elif input_shape is None:
<add> input_shape = input_data.shape
<ide>
<del> # test basic serialization
<del> layer_config = layer.get_config()
<del> layer = layer.__class__.from_config(layer_config)
<add> # instantiation
<add> layer = layer_cls(**kwargs)
<add>
<add> # test get_weights , set_weights
<add> weights = layer.get_weights()
<add> layer.set_weights(weights)
<add>
<add> # test and instantiation from weights
<add> if 'weights' in inspect.getargspec(layer_cls.__init__):
<add> kwargs['weights'] = weights
<add> layer = layer_cls(**kwargs)
<ide>
<ide> # test in functional API
<ide> x = Input(shape=input_shape[1:], dtype=input_dtype)
<ide> y = layer(x)
<del> model = Model(x, y)
<add> model = Model(input=x, output=y)
<ide> model.compile('rmsprop', 'mse')
<ide>
<ide> expected_output_shape = layer.get_output_shape_for(input_shape)
<del> actual_output_shape = model.predict(input_data).shape
<add> actual_output = model.predict(input_data)
<add> actual_output_shape = actual_output.shape
<ide> assert expected_output_shape == actual_output_shape
<add> if expected_output is not None:
<add> assert_allclose(actual_output, expected_output, rtol=1e-3)
<ide>
<ide> # test serialization
<ide> model_config = model.get_config()
<ide> def test_layer(layer, input_shape, input_dtype=None):
<ide> outer_model = Model(x_outer, y_outer)
<ide> outer_model.compile('rmsprop', 'mse')
<ide>
<del> actual_output_shape = outer_model.predict(input_data).shape
<add> actual_output = outer_model.predict(input_data)
<add> actual_output_shape = actual_output.shape
<ide> assert expected_output_shape == actual_output_shape
<add> if expected_output is not None:
<add> assert_allclose(actual_output, expected_output, rtol=1e-3)
<ide>
<ide> outer_model_config = outer_model.get_config()
<ide> outer_model = Model.from_config(outer_model_config)
<ide> def test_layer(layer, input_shape, input_dtype=None):
<ide> model = Sequential()
<ide> model.add(layer)
<ide> model.compile('rmsprop', 'mse')
<del> actual_output_shape = model.predict(input_data).shape
<add> actual_output = model.predict(input_data)
<add> actual_output_shape = actual_output.shape
<ide> assert expected_output_shape == actual_output_shape
<add> if expected_output is not None:
<add> assert_allclose(actual_output, expected_output, rtol=1e-3)
<add>
<add> # test JSON serialization
<add> json_model = model.to_json()
<add> model = model_from_json(json_model)
<add>
<add> # for further checks in the caller function
<add> return actual_output
<ide><path>tests/keras/layers/test_advanced_activations.py
<ide> import pytest
<del>from numpy.testing import assert_allclose
<del>import numpy as np
<del>from keras import backend as K
<del>
<del>
<del>def get_standard_values():
<del> '''
<del> These are just a set of floats used for testing the activation
<del> functions, and are useful in multiple tests.
<del>
<del> The values should all be non-negative because they and their negatives
<del> are used to test the ReLU derivates in this file.
<del> '''
<del> return np.array([[0, 0.1, 0.5, 0.9, 1.0, 10, 1e2, 0.01]], dtype=K.floatx())
<add>from keras.utils.test_utils import test_layer
<ide>
<ide>
<ide> def test_leaky_relu():
<del> np.random.seed(1337)
<ide> from keras.layers.advanced_activations import LeakyReLU
<del> inp = get_standard_values()
<ide> for alpha in [0., .5, -1.]:
<del> layer = LeakyReLU(alpha=alpha)
<del> layer.input = K.variable(inp)
<del> for train in [True, False]:
<del> outp = K.eval(layer.get_output(train))
<del> assert_allclose(outp, inp)
<del>
<del> layer.input = K.variable(-inp)
<del> for train in [True, False]:
<del> outp = K.eval(layer.get_output(train))
<del> assert_allclose(outp, -inp * alpha)
<del>
<del> config = layer.get_config()
<del> assert config['alpha'] == alpha
<add> test_layer(LeakyReLU, kwargs={'alpha': alpha},
<add> input_shape=(2, 3, 4))
<ide>
<ide>
<ide> def test_prelu():
<ide> from keras.layers.advanced_activations import PReLU
<del> np.random.seed(1337)
<del> inp = get_standard_values()
<del>
<del> for train in [True, False]:
<del> # test with custom weights
<del> alphas = np.random.random(inp.shape)
<del> layer = PReLU(weights=alphas, input_shape=inp.flatten().shape)
<del> # calling build here causes an error, unclear if this is a bug
<del> # layer.build()
<del>
<del> layer.input = K.variable(inp)
<del> outp = K.eval(layer.get_output(train))
<del> assert_allclose(inp, outp)
<del>
<del> layer.input = K.variable(-inp)
<del> outp = K.eval(layer.get_output(train))
<del> assert_allclose(-alphas * inp, outp)
<del>
<del> # test with default weights
<del> layer = PReLU(input_shape=inp.flatten().shape)
<del> # layer.build()
<del> layer.input = K.variable(inp)
<del> outp = K.eval(layer.get_output(train))
<del> assert_allclose(inp, outp)
<del>
<del> layer.input = K.variable(-inp)
<del> outp = K.eval(layer.get_output(train))
<del>
<del> assert_allclose(0., alphas * outp)
<del>
<del> layer.get_config()
<add> test_layer(PReLU, kwargs={},
<add> input_shape=(2, 3, 4))
<ide>
<ide>
<ide> def test_elu():
<ide> from keras.layers.advanced_activations import ELU
<del> np.random.seed(1337)
<del> inp = get_standard_values()
<del> for alpha in [0.1, .5, -1., 1.]:
<del> layer = ELU(alpha=alpha)
<del> layer.input = K.variable(inp)
<del> for train in [True, False]:
<del> outp = K.eval(layer.get_output(train))
<del> assert_allclose(outp, inp, rtol=1e-3)
<del>
<del> layer.input = K.variable(-inp)
<del> for train in [True, False]:
<del> outp = K.eval(layer.get_output(train))
<del> assert_allclose(outp, alpha * (np.exp(-inp) - 1.), rtol=1e-3)
<del>
<del> config = layer.get_config()
<del> assert config['alpha'] == alpha
<del>
<del>
<del>@pytest.mark.skipif(K._BACKEND == 'tensorflow',
<del> reason='currently not working with TensorFlow')
<add> for alpha in [0., .5, -1.]:
<add> test_layer(ELU, kwargs={'alpha': alpha},
<add> input_shape=(2, 3, 4))
<add>
<add>
<ide> def test_parametric_softplus():
<ide> from keras.layers.advanced_activations import ParametricSoftplus
<del> np.random.seed(1337)
<del> inp = np.vstack((get_standard_values(), -get_standard_values()))
<del> # large values cause overflow in exp
<del> inp = inp[:-2]
<del> for alpha in [.5, -1., 1., 5]:
<del> for beta in [.5, -1., 1., 2]:
<del> layer = ParametricSoftplus(alpha_init=alpha,
<del> beta_init=beta,
<del> input_shape=inp.shape)
<del> layer.input = K.variable(inp)
<del> layer.build()
<del> for train in [True, False]:
<del> outp = K.eval(layer.get_output(train))
<del> assert_allclose(outp, alpha * np.log(1. + np.exp(beta * inp)),
<del> atol=1e-3)
<del>
<del> config = layer.get_config()
<del> assert config['alpha_init'] == alpha
<del> assert config['beta_init'] == beta
<del>
<del>
<del>@pytest.mark.skipif(K._BACKEND == 'tensorflow',
<del> reason='currently not working with TensorFlow')
<add> for alpha in [0., .5, -1.]:
<add> test_layer(ParametricSoftplus,
<add> kwargs={'alpha_init': 1.,
<add> 'beta_init': -1},
<add> input_shape=(2, 3, 4))
<add>
<add>
<ide> def test_thresholded_linear():
<ide> from keras.layers.advanced_activations import ThresholdedLinear
<del> np.random.seed(1337)
<del> inp = get_standard_values()
<del> for theta in [0., .5, 1.]:
<del> layer = ThresholdedLinear(theta=theta)
<del> layer.input = K.variable(inp)
<del> for train in [True, False]:
<del> outp = K.eval(layer.get_output(train))
<del> assert_allclose(outp, inp * (np.abs(inp) >= theta))
<del>
<del> layer.input = K.variable(-inp)
<del> for train in [True, False]:
<del> outp = K.eval(layer.get_output(train))
<del> assert_allclose(outp, -inp * (np.abs(inp) >= theta))
<del>
<del> config = layer.get_config()
<del> assert config['theta'] == theta
<del>
<del>
<del>@pytest.mark.skipif(K._BACKEND == 'tensorflow',
<del> reason='currently not working with TensorFlow')
<del>def test_thresholded_relu():
<del> from keras.layers.advanced_activations import ThresholdedReLU
<del> np.random.seed(1337)
<del> inp = get_standard_values()
<del> for theta in [-1, 0., .5, 1.]:
<del> layer = ThresholdedReLU(theta=theta)
<del> layer.input = K.variable(inp)
<del> for train in [True, False]:
<del> outp = K.eval(layer.get_output(train))
<del> assert_allclose(outp, inp * (inp > theta))
<add> test_layer(ThresholdedLinear, kwargs={'theta': 0.5},
<add> input_shape=(2, 3, 4))
<ide>
<del> layer.input = K.variable(-inp)
<del> for train in [True, False]:
<del> outp = K.eval(layer.get_output(train))
<del> assert_allclose(outp, -inp * (-inp > theta))
<ide>
<del> config = layer.get_config()
<del> assert config['theta'] == theta
<add>def test_thresholded_relu():
<add> from keras.layers.advanced_activations import ThresholdedReLU
<add> test_layer(ThresholdedReLU, kwargs={'theta': 0.5},
<add> input_shape=(2, 3, 4))
<ide>
<ide>
<ide> def test_srelu():
<ide> from keras.layers.advanced_activations import SReLU
<del> np.random.seed(1337)
<del> inp = np.array([-2, -1., -0.5, 0., 0.5, 1., 2.])
<del> out = np.array([-1.5, -1., -0.5, 0., 0.5, 1., 3.])
<del> input_size = len(inp)
<del> for train in [True, False]:
<del> layer = SReLU(input_shape=inp.flatten().shape)
<del> ones_proto = np.ones(input_size)
<del> layer.set_weights([ones_proto * -1., ones_proto * 0.5,
<del> ones_proto * 2., ones_proto * 2.])
<del> layer.input = K.variable(inp)
<del> outp = K.eval(layer.get_output(train))
<del> assert_allclose(out, outp)
<del>
<del> layer.get_config()
<add> test_layer(SReLU, kwargs={},
<add> input_shape=(2, 3, 4))
<ide>
<ide>
<ide> if __name__ == '__main__':
<del> pytest.main([__file__])
<add> # pytest.main([__file__])
<add> test_srelu() | 4 |
Javascript | Javascript | ensure promises resolve in webcrypto tests | dc8d54d3654ba340c542c72dd08bee82eb52e72f | <ide><path>test/parallel/test-webcrypto-digest.js
<ide> const kData = (new TextEncoder()).encode('hello');
<ide> }));
<ide> })().then(common.mustCall());
<ide>
<del>[1, [], {}, null, undefined].forEach((i) => {
<del> assert.rejects(subtle.digest(i), { message: /Unrecognized name/ });
<del>});
<add>Promise.all([1, [], {}, null, undefined].map((i) =>
<add> assert.rejects(subtle.digest(i), { message: /Unrecognized name/ })
<add>)).then(common.mustCall());
<ide>
<del>assert.rejects(subtle.digest(''), { message: /Unrecognized name/ });
<add>assert.rejects(subtle.digest(''), { message: /Unrecognized name/ }).then(common.mustCall());
<ide>
<del>[1, [], {}, null, undefined].forEach((i) => {
<add>Promise.all([1, [], {}, null, undefined].map((i) =>
<ide> assert.rejects(subtle.digest('SHA-256', i), {
<ide> code: 'ERR_INVALID_ARG_TYPE'
<del> });
<del>});
<add> })
<add>)).then(common.mustCall());
<ide>
<ide> // If there is a mismatch between length and the expected digest size for
<ide> // the selected algorithm, we fail. The length is a Node.js specific
<ide> // addition to the API, and is added as a support for future additional
<ide> // hash algorithms that support variable digest output lengths.
<ide> assert.rejects(subtle.digest({ name: 'SHA-512', length: 510 }, kData), {
<ide> message: /Digest method not supported/
<del>});
<add>}).then(common.mustCall());
<ide>
<ide> const kSourceData = {
<ide> empty: '',
<ide><path>test/parallel/test-webcrypto-ed25519-ed448.js
<ide> assert.rejects(
<ide> ['sign']),
<ide> {
<ide> message: /NODE-ED25519 raw keys must be exactly 32-bytes/
<del> });
<add> }).then(common.mustCall());
<ide>
<ide> assert.rejects(
<ide> subtle.importKey(
<ide> assert.rejects(
<ide> ['sign']),
<ide> {
<ide> message: /NODE-ED448 raw keys must be exactly 57-bytes/
<del> });
<add> }).then(common.mustCall());
<ide>
<ide> const testVectors = {
<ide> 'NODE-ED25519': [
<ide> assert.rejects(
<ide> ['sign', 'verify']),
<ide> {
<ide> message: /Unsupported named curves for ECDSA/
<del> });
<add> }).then(common.mustCall());
<ide>
<ide> assert.rejects(
<ide> subtle.generateKey(
<ide> assert.rejects(
<ide> ['sign', 'verify']),
<ide> {
<ide> message: /Unsupported named curves for ECDSA/
<del> });
<add> }).then(common.mustCall());
<ide>
<ide> assert.rejects(
<ide> subtle.generateKey(
<ide> assert.rejects(
<ide> ['sign', 'verify']),
<ide> {
<ide> message: /Unsupported named curves for ECDSA/
<del> });
<add> }).then(common.mustCall());
<ide>
<ide> assert.rejects(
<ide> subtle.generateKey(
<ide> assert.rejects(
<ide> ['sign', 'verify']),
<ide> {
<ide> message: /Unsupported named curves for ECDSA/
<del> });
<add> }).then(common.mustCall());
<ide>
<ide> {
<ide> for (const asymmetricKeyType of ['ed25519', 'ed448']) {
<ide> assert.rejects(
<ide> ),
<ide> {
<ide> message: /Invalid algorithm name/
<del> });
<add> }).then(common.mustCall());
<ide>
<ide> assert.rejects(
<ide> subtle.importKey(
<ide> assert.rejects(
<ide> ),
<ide> {
<ide> message: /Invalid algorithm name/
<del> });
<add> }).then(common.mustCall());
<ide> }
<ide> }
<ide> }
<ide><path>test/parallel/test-webcrypto-export-import.js
<ide> const assert = require('assert');
<ide> const { subtle, getRandomValues } = require('crypto').webcrypto;
<ide>
<ide> {
<del> const keyData = getRandomValues(new Uint8Array(32));
<del> [1, null, undefined, {}, []].forEach((format) => {
<del> assert.rejects(
<del> subtle.importKey(format, keyData, {}, false, ['wrapKey']), {
<del> code: 'ERR_INVALID_ARG_TYPE'
<add> async function test() {
<add> const keyData = getRandomValues(new Uint8Array(32));
<add> await Promise.all([1, null, undefined, {}, []].map((format) =>
<add> assert.rejects(
<add> subtle.importKey(format, keyData, {}, false, ['wrapKey']), {
<add> code: 'ERR_INVALID_ARG_TYPE'
<add> })
<add> ));
<add> await assert.rejects(
<add> subtle.importKey('not valid', keyData, {}, false, ['wrapKey']), {
<add> code: 'ERR_INVALID_ARG_VALUE'
<ide> });
<del> });
<del> assert.rejects(
<del> subtle.importKey('not valid', keyData, {}, false, ['wrapKey']), {
<del> code: 'ERR_INVALID_ARG_VALUE'
<del> });
<del> [1, null, undefined, {}, []].forEach((keyData) => {
<del> assert.rejects(
<del> subtle.importKey('raw', keyData, {}, false, ['deriveBits']), {
<add> await Promise.all([1, null, undefined, {}, []].map((keyData) =>
<add> assert.rejects(
<add> subtle.importKey('raw', keyData, {}, false, ['deriveBits']), {
<add> code: 'ERR_INVALID_ARG_TYPE'
<add> })
<add> ));
<add> await assert.rejects(
<add> subtle.importKey('raw', keyData, {
<add> name: 'HMAC'
<add> }, false, ['sign', 'verify']), {
<add> code: 'ERR_MISSING_OPTION'
<add> });
<add> await assert.rejects(
<add> subtle.importKey('raw', keyData, {
<add> name: 'HMAC',
<add> hash: 'SHA-256'
<add> }, false, ['deriveBits']), {
<add> name: 'SyntaxError',
<add> message: 'Unsupported key usage for an HMAC key'
<add> });
<add> await assert.rejects(
<add> subtle.importKey('node.keyObject', '', {
<add> name: 'HMAC',
<add> hash: 'SHA-256'
<add> }, false, ['sign', 'verify']), {
<ide> code: 'ERR_INVALID_ARG_TYPE'
<ide> });
<del> });
<del> assert.rejects(
<del> subtle.importKey('raw', keyData, {
<del> name: 'HMAC'
<del> }, false, ['sign', 'verify']), {
<del> code: 'ERR_MISSING_OPTION'
<del> }).then(common.mustCall());
<del> assert.rejects(
<del> subtle.importKey('raw', keyData, {
<del> name: 'HMAC',
<del> hash: 'SHA-256'
<del> }, false, ['deriveBits']), {
<del> name: 'SyntaxError',
<del> message: 'Unsupported key usage for an HMAC key'
<del> }).then(common.mustCall());
<del> assert.rejects(
<del> subtle.importKey('node.keyObject', '', {
<del> name: 'HMAC',
<del> hash: 'SHA-256'
<del> }, false, ['sign', 'verify']), {
<del> code: 'ERR_INVALID_ARG_TYPE'
<del> }).then(common.mustCall());
<del> assert.rejects(
<del> subtle.importKey('raw', keyData, {
<del> name: 'HMAC',
<del> hash: 'SHA-256',
<del> length: 0
<del> }, false, ['sign', 'verify']), {
<del> name: 'DataError',
<del> message: 'Zero-length key is not supported'
<del> }).then(common.mustCall());
<del> assert.rejects(
<del> subtle.importKey('raw', keyData, {
<del> name: 'HMAC',
<del> hash: 'SHA-256',
<del> length: 1
<del> }, false, ['sign', 'verify']), {
<del> name: 'DataError',
<del> message: 'Invalid key length'
<del> }).then(common.mustCall());
<del> assert.rejects(
<del> subtle.importKey('jwk', null, {
<del> name: 'HMAC',
<del> hash: 'SHA-256',
<del> }, false, ['sign', 'verify']), {
<del> name: 'DataError',
<del> message: 'Invalid JWK keyData'
<del> }).then(common.mustCall());
<add> await assert.rejects(
<add> subtle.importKey('raw', keyData, {
<add> name: 'HMAC',
<add> hash: 'SHA-256',
<add> length: 0
<add> }, false, ['sign', 'verify']), {
<add> name: 'DataError',
<add> message: 'Zero-length key is not supported'
<add> });
<add> await assert.rejects(
<add> subtle.importKey('raw', keyData, {
<add> name: 'HMAC',
<add> hash: 'SHA-256',
<add> length: 1
<add> }, false, ['sign', 'verify']), {
<add> name: 'DataError',
<add> message: 'Invalid key length'
<add> });
<add> await assert.rejects(
<add> subtle.importKey('jwk', null, {
<add> name: 'HMAC',
<add> hash: 'SHA-256',
<add> }, false, ['sign', 'verify']), {
<add> name: 'DataError',
<add> message: 'Invalid JWK keyData'
<add> });
<add> }
<add>
<add> test().then(common.mustCall());
<ide> }
<ide>
<ide> // Import/Export HMAC Secret Key
<ide><path>test/parallel/test-webcrypto-x25519-x448.js
<ide> async function importKey(namedCurve, keyData, isPublic = false) {
<ide>
<ide> assert.rejects(importKey('NODE-X25519', Buffer.alloc(10), true), {
<ide> message: /NODE-X25519 raw keys must be exactly 32-bytes/
<del>});
<add>}).then(common.mustCall());
<ide> assert.rejects(importKey('NODE-X448', Buffer.alloc(10), true), {
<ide> message: /NODE-X448 raw keys must be exactly 56-bytes/
<del>});
<add>}).then(common.mustCall());
<ide>
<ide> async function test1(namedCurve) {
<ide> const {
<ide> assert.rejects(
<ide> ['deriveBits']),
<ide> {
<ide> message: /Unsupported named curves for ECDH/
<del> });
<add> }).then(common.mustCall());
<ide>
<ide> assert.rejects(
<ide> subtle.generateKey(
<ide> assert.rejects(
<ide> ['deriveBits']),
<ide> {
<ide> message: /Unsupported named curves for ECDH/
<del> });
<add> }).then(common.mustCall());
<ide>
<ide> {
<ide> // Private JWK import | 4 |
Ruby | Ruby | fix formula path | db559a97dc7f1a7461b0cf1fbc4524691ac4eab4 | <ide><path>Library/Homebrew/formula.rb
<ide> def self.factory name
<ide> end
<ide>
<ide> def self.path name
<del> HOMEBREW_PREFIX+'Library'+'Formula'+"#{name.downcase}.rb"
<add> HOMEBREW_REPOSITORY+"Library/Formula/#{name.downcase}.rb"
<ide> end
<ide>
<ide> def deps | 1 |
Text | Text | add tox note | 5422eedd0a3f97c9ac9e93645b4e94cdfbe07f0d | <ide><path>README.md
<ide> To run the tests.
<ide>
<ide> ./rest_framework/runtests/runtests.py
<ide>
<add>To run the tests against all supported configurations, first install [the tox testing tool][tox] globally, using `pip install tox`, then simply run `tox`:
<add>
<add> tox
<add>
<ide> # License
<ide>
<ide> Copyright (c) 2011-2013, Tom Christie
<ide> OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
<ide> [rest-framework-2-announcement]: http://django-rest-framework.org/topics/rest-framework-2-announcement.html
<ide> [2.1.0-notes]: https://groups.google.com/d/topic/django-rest-framework/Vv2M0CMY9bg/discussion
<ide>
<add>[tox]: http://testrun.org/tox/latest/
<add>
<ide> [docs]: http://django-rest-framework.org/
<ide> [urlobject]: https://github.com/zacharyvoase/urlobject
<ide> [markdown]: http://pypi.python.org/pypi/Markdown/ | 1 |
Javascript | Javascript | add string as possible proptype for 'systemicon' | dd9c1e16ee372f419e9c4e5757dc25cb3e2dcd66 | <ide><path>Libraries/Components/TabBarIOS/TabBarItemIOS.ios.js
<ide> var TabBarItemIOS = React.createClass({
<ide> /**
<ide> * A custom icon for the tab. It is ignored when a system icon is defined.
<ide> */
<del> icon: Image.propTypes.source,
<add> icon: React.PropTypes.oneOfType([
<add> React.PropTypes.string,
<add> Image.propTypes.source,
<add> ]),
<ide> /**
<ide> * A custom icon when the tab is selected. It is ignored when a system
<ide> * icon is defined. If left empty, the icon will be tinted in blue. | 1 |
Text | Text | move mikeal to collaborator emeriti list | 72549aa9cd37585256ceb0e6215404f6fe4f7fdb | <ide><path>README.md
<ide> For more information about the governance of the Node.js project, see
<ide> **Michael Dawson** <[email protected]> (he/him)
<ide> * [micnic](https://github.com/micnic) -
<ide> **Nicu Micleușanu** <[email protected]> (he/him)
<del>* [mikeal](https://github.com/mikeal) -
<del>**Mikeal Rogers** <[email protected]>
<ide> * [misterdjules](https://github.com/misterdjules) -
<ide> **Julien Gilli** <[email protected]>
<ide> * [mmarchini](https://github.com/mmarchini) -
<ide> For more information about the governance of the Node.js project, see
<ide> **Aleksey Smolenchuk** <[email protected]>
<ide> * [matthewloring](https://github.com/matthewloring) -
<ide> **Matthew Loring** <[email protected]>
<add>* [mikeal](https://github.com/mikeal) -
<add>**Mikeal Rogers** <[email protected]>
<ide> * [monsanto](https://github.com/monsanto) -
<ide> **Christopher Monsanto** <[email protected]>
<ide> * [Olegas](https://github.com/Olegas) - | 1 |
PHP | PHP | fix helper tests | f1b7f7e5af0396f00a31c60bfdccd6b842b52c33 | <ide><path>tests/TestCase/View/Helper/HtmlHelperTest.php
<ide> public function testDocType()
<ide> public function testLink()
<ide> {
<ide> Router::reload();
<add> Router::connect('/:controller', ['action' => 'index']);
<ide> Router::connect('/:controller/:action/*');
<ide>
<ide> $this->View->setRequest($this->View->getRequest()->withAttribute('webroot', ''));
<ide> public function testLink()
<ide> $expected = ['a' => ['href' => '/home'], 'preg:/\/home/', '/a'];
<ide> $this->assertHtml($expected, $result);
<ide>
<del> $result = $this->Html->link(['action' => 'login', '<[You]>']);
<add> $result = $this->Html->link(['controller' => 'users', 'action' => 'login', '<[You]>']);
<ide> $expected = [
<del> 'a' => ['href' => '/login/%3C%5BYou%5D%3E'],
<del> 'preg:/\/login\/<\[You\]>/',
<add> 'a' => ['href' => '/users/login/%3C%5BYou%5D%3E'],
<add> 'preg:/\/users\/login\/<\[You\]>/',
<ide> '/a',
<ide> ];
<ide> $this->assertHtml($expected, $result);
<ide>
<del> Router::reload();
<del> Router::connect('/:controller', ['action' => 'index']);
<del> Router::connect('/:controller/:action/*');
<del>
<ide> $result = $this->Html->link('Posts', ['controller' => 'posts', 'action' => 'index', '_full' => true]);
<ide> $expected = ['a' => ['href' => Router::fullBaseUrl() . '/posts'], 'Posts', '/a'];
<ide> $this->assertHtml($expected, $result);
<ide><path>tests/TestCase/View/Helper/PaginatorHelperTest.php
<ide> public function setUp()
<ide> $request = new ServerRequest([
<ide> 'url' => '/',
<ide> 'params' => [
<add> 'plugin' => null,
<add> 'controller' => '',
<add> 'action' => 'index',
<ide> 'paging' => [
<ide> 'Article' => [
<ide> 'page' => 1,
<ide> public function setUp()
<ide> Router::reload();
<ide> Router::connect('/:controller/:action/*');
<ide> Router::connect('/:plugin/:controller/:action/*');
<add> Router::pushRequest($request);
<ide>
<ide> $this->locale = I18n::getLocale();
<ide> } | 2 |
Javascript | Javascript | remove the unused `util.apply3dtransform` method | 4b39b1c76b4347a817b010b9d88b4c220a02170b | <ide><path>src/shared/util.js
<ide> class Util {
<ide> ];
<ide> }
<ide>
<del> // Apply a generic 3d matrix M on a 3-vector v:
<del> // | a b c | | X |
<del> // | d e f | x | Y |
<del> // | g h i | | Z |
<del> // M is assumed to be serialized as [a,b,c,d,e,f,g,h,i],
<del> // with v as [X,Y,Z]
<del> static apply3dTransform(m, v) {
<del> return [
<del> m[0] * v[0] + m[1] * v[1] + m[2] * v[2],
<del> m[3] * v[0] + m[4] * v[1] + m[5] * v[2],
<del> m[6] * v[0] + m[7] * v[1] + m[8] * v[2],
<del> ];
<del> }
<del>
<ide> // This calculation uses Singular Value Decomposition.
<ide> // The SVD can be represented with formula A = USV. We are interested in the
<ide> // matrix S here because it represents the scale values. | 1 |
Text | Text | use new hash syntax | 4d88e85d98639b4ea6ec7e67b8c5a52422199b0f | <ide><path>guides/source/migrations.md
<ide> end
<ide> # app/models/product.rb
<ide>
<ide> class Product < ActiveRecord::Base
<del> validates :flag, :inclusion => { :in => [true, false] }
<add> validates :flag, inclusion: { in: [true, false] }
<ide> end
<ide> ```
<ide>
<ide> end
<ide> # app/models/product.rb
<ide>
<ide> class Product < ActiveRecord::Base
<del> validates :flag, :inclusion => { :in => [true, false] }
<add> validates :flag, inclusion: { in: [true, false] }
<ide> validates :fuzz, presence: true
<ide> end
<ide> ``` | 1 |
PHP | PHP | apply fixes from styleci | 471f9233037c354b541ea33dacb807b55a44cffc | <ide><path>src/Illuminate/Database/Grammar.php
<ide> public function wrap($value, $prefixAlias = false)
<ide> */
<ide> protected function wrapAliasedValue($value, $prefixAlias = false)
<ide> {
<del> $segments = preg_split( '/\s+as\s+/i', $value );
<add> $segments = preg_split('/\s+as\s+/i', $value);
<ide>
<ide> // If we are wrapping a table we need to prefix the alias with the table prefix
<ide> // as well in order to generate proper syntax. If this is a column of course
<ide><path>tests/Database/DatabaseQueryBuilderTest.php
<ide> public function testAliasWrappingAsWholeConstant()
<ide> $builder->select('x.y as foo.bar')->from('baz');
<ide> $this->assertEquals('select "x"."y" as "foo.bar" from "baz"', $builder->toSql());
<ide> }
<del>
<add>
<ide> public function testAliasWrappingWithSpacesInDatabaseName()
<ide> {
<del> $builder = $this->getBuilder();
<del> $builder->select('w x.y.z as foo.bar')->from('baz');
<del> $this->assertEquals('select "w x"."y"."z" as "foo.bar" from "baz"', $builder->toSql());
<add> $builder = $this->getBuilder();
<add> $builder->select('w x.y.z as foo.bar')->from('baz');
<add> $this->assertEquals('select "w x"."y"."z" as "foo.bar" from "baz"', $builder->toSql());
<ide> }
<ide>
<ide> public function testAddingSelects() | 2 |
Javascript | Javascript | update helpers to use new args | 6d1983c98a3210717689e22c3ac99dbcba72e7ca | <ide><path>packages/ember-glimmer/lib/helpers/-class.js
<ide> function classHelper({ positional }) {
<ide> }
<ide>
<ide> export default function(vm, args) {
<del> return new InternalHelperReference(classHelper, args);
<add> return new InternalHelperReference(classHelper, args.capture());
<ide> }
<ide><path>packages/ember-glimmer/lib/helpers/-html-safe.js
<ide> function htmlSafe({ positional }) {
<ide> }
<ide>
<ide> export default function(vm, args) {
<del> return new InternalHelperReference(htmlSafe, args);
<add> return new InternalHelperReference(htmlSafe, args.capture());
<ide> }
<ide><path>packages/ember-glimmer/lib/helpers/-input-type.js
<ide> function inputTypeHelper({ positional, named }) {
<ide> }
<ide>
<ide> export default function(vm, args) {
<del> return new InternalHelperReference(inputTypeHelper, args);
<add> return new InternalHelperReference(inputTypeHelper, args.capture());
<ide> }
<ide><path>packages/ember-glimmer/lib/helpers/-normalize-class.js
<ide> function normalizeClass({ positional, named }) {
<ide> }
<ide>
<ide> export default function(vm, args) {
<del> return new InternalHelperReference(normalizeClass, args);
<add> return new InternalHelperReference(normalizeClass, args.capture());
<ide> }
<ide><path>packages/ember-glimmer/lib/helpers/component.js
<ide> function curryArgs(definition, newArgs) {
<ide> return mergedArgs;
<ide> }
<ide>
<del>export default function(vm, args, symbolTable) {
<del> return ClosureComponentReference.create(args, symbolTable, vm.env);
<add>export default function(vm, args, meta) {
<add> return ClosureComponentReference.create(args.capture(), meta, vm.env);
<ide> }
<ide><path>packages/ember-glimmer/lib/helpers/concat.js
<ide> function concat({ positional }) {
<ide> }
<ide>
<ide> export default function(vm, args) {
<del> return new InternalHelperReference(concat, args);
<add> return new InternalHelperReference(concat, args.capture());
<ide> }
<ide><path>packages/ember-glimmer/lib/helpers/loc.js
<ide> function locHelper({ positional }) {
<ide> }
<ide>
<ide> export default function(vm, args) {
<del> return new InternalHelperReference(locHelper, args);
<add> return new InternalHelperReference(locHelper, args.capture());
<ide> }
<ide><path>packages/ember-glimmer/lib/helpers/log.js
<ide> function log({ positional }) {
<ide> }
<ide>
<ide> export default function(vm, args) {
<del> return new InternalHelperReference(log, args);
<add> return new InternalHelperReference(log, args.capture());
<ide> }
<ide><path>packages/ember-glimmer/lib/helpers/query-param.js
<ide> function queryParams({ positional, named }) {
<ide> }
<ide>
<ide> export default function(vm, args) {
<del> return new InternalHelperReference(queryParams, args);
<add> return new InternalHelperReference(queryParams, args.capture());
<ide> }
<ide><path>packages/ember-glimmer/lib/helpers/unbound.js
<ide> import { UnboundReference } from '../utils/references';
<ide> export default function(vm, args) {
<ide> assert(
<ide> 'unbound helper cannot be called with multiple params or hash params',
<del> args.positional.values.length === 1 && args.named.keys.length === 0
<add> args.positional.length === 1 && args.named.length === 0
<ide> );
<ide>
<ide> return UnboundReference.create(args.positional.at(0).value()); | 10 |
Ruby | Ruby | drop conditionals in conversion logic | 5046d5179e9627bb84962f7ebf2153bfac6db254 | <ide><path>actionpack/lib/action_controller/metal/strong_parameters.rb
<ide> def []=(key, value)
<ide> # params.fetch(:none, 'Francesco') # => "Francesco"
<ide> # params.fetch(:none) { 'Francesco' } # => "Francesco"
<ide> def fetch(key, *args, &block)
<del> convert_hashes_to_parameters(
<del> key,
<add> convert_value_to_parameters(
<ide> @parameters.fetch(key) {
<ide> if block_given?
<ide> yield
<ide> else
<ide> args.fetch(0) { raise ActionController::ParameterMissing.new(key) }
<ide> end
<del> },
<del> false
<add> }
<ide> )
<ide> end
<ide>
<ide> def transform_keys!(&block)
<ide> # optional code block is given and the key is not found, pass in the key
<ide> # and return the result of block.
<ide> def delete(key, &block)
<del> convert_hashes_to_parameters(key, @parameters.delete(key), false)
<add> convert_value_to_parameters(@parameters.delete(key))
<ide> end
<ide>
<ide> # Returns a new instance of <tt>ActionController::Parameters</tt> with only
<ide> def new_instance_with_inherited_permitted_status(hash)
<ide> end
<ide> end
<ide>
<del> def convert_hashes_to_parameters(key, value, assign_if_converted=true)
<add> def convert_hashes_to_parameters(key, value)
<ide> converted = convert_value_to_parameters(value)
<del> @parameters[key] = converted if assign_if_converted && !converted.equal?(value)
<add> @parameters[key] = converted unless converted.equal?(value)
<ide> converted
<ide> end
<ide> | 1 |
Text | Text | add a note about manual tagging | af6da3d8db6186199f0d6fbfc0a4d1c540aeb4f2 | <ide><path>docs/rfcs/xxx-pretranspile.md
<ide> Transpiling packages on _publish_ rather than _load_ will have great benefits fo
<ide>
<ide> During the `apm publish` call, apm will invoke [`npm pack`](https://docs.npmjs.com/cli/pack) to run all standard npm lifecycle hooks and prepare a `.tar.gz` file. apm then uploads the `.tar.gz` file to atom.io, which uploads it to an S3 bucket.
<ide>
<add>The `npm version` call will still be skipped if the `--tag` is provided, so manual publishing with `apm publish --tag` will still work as it does today.
<add>
<ide> ### Package installation
<ide>
<ide> When a user installs a package from atom.io, atom.io first checks to see if it has a precompiled tarball in its S3 bucket. If one is found, the artifact's public URL is returned as the `dist` field in the [API response](https://flight-manual.atom.io/atom-server-side-apis/sections/atom-package-server-api/#get-apipackagespackage_nameversionsversion_name). Otherwise, the existing logic is used to return the GitHub tag tarball URL that's returned now. | 1 |
Go | Go | move strslice to types | f9b857a200696b07b67e6a7f94ede32487f5649d | <add><path>api/types/strslice/strslice.go
<del><path>pkg/stringutils/strslice.go
<del>package stringutils
<add>package strslice
<ide>
<ide> import (
<ide> "encoding/json"
<ide> func (e *StrSlice) ToString() string {
<ide> return strings.Join(s, " ")
<ide> }
<ide>
<del>// NewStrSlice creates an StrSlice based on the specified parts (as strings).
<del>func NewStrSlice(parts ...string) *StrSlice {
<add>// New creates an StrSlice based on the specified parts (as strings).
<add>func New(parts ...string) *StrSlice {
<ide> return &StrSlice{parts}
<ide> }
<add><path>api/types/strslice/strslice_test.go
<del><path>pkg/stringutils/strslice_test.go
<del>package stringutils
<add>package strslice
<ide>
<ide> import (
<ide> "encoding/json"
<ide> func TestStrSliceUnmarshalSlice(t *testing.T) {
<ide>
<ide> func TestStrSliceToString(t *testing.T) {
<ide> slices := map[*StrSlice]string{
<del> NewStrSlice(""): "",
<del> NewStrSlice("one"): "one",
<del> NewStrSlice("one", "two"): "one two",
<add> New(""): "",
<add> New("one"): "one",
<add> New("one", "two"): "one two",
<ide> }
<ide> for s, expected := range slices {
<ide> toString := s.ToString()
<ide> func TestStrSliceToString(t *testing.T) {
<ide> func TestStrSliceLen(t *testing.T) {
<ide> var emptyStrSlice *StrSlice
<ide> slices := map[*StrSlice]int{
<del> NewStrSlice(""): 1,
<del> NewStrSlice("one"): 1,
<del> NewStrSlice("one", "two"): 2,
<del> emptyStrSlice: 0,
<add> New(""): 1,
<add> New("one"): 1,
<add> New("one", "two"): 2,
<add> emptyStrSlice: 0,
<ide> }
<ide> for s, expected := range slices {
<ide> if s.Len() != expected {
<ide> func TestStrSliceLen(t *testing.T) {
<ide> func TestStrSliceSlice(t *testing.T) {
<ide> var emptyStrSlice *StrSlice
<ide> slices := map[*StrSlice][]string{
<del> NewStrSlice("one"): {"one"},
<del> NewStrSlice("one", "two"): {"one", "two"},
<del> emptyStrSlice: nil,
<add> New("one"): {"one"},
<add> New("one", "two"): {"one", "two"},
<add> emptyStrSlice: nil,
<ide> }
<ide> for s, expected := range slices {
<ide> if !reflect.DeepEqual(s.Slice(), expected) {
<ide><path>builder/dockerfile/dispatchers.go
<ide> import (
<ide> "strings"
<ide>
<ide> "github.com/Sirupsen/logrus"
<add> "github.com/docker/docker/api/types/strslice"
<ide> "github.com/docker/docker/builder"
<ide> derr "github.com/docker/docker/errors"
<ide> flag "github.com/docker/docker/pkg/mflag"
<ide> "github.com/docker/docker/pkg/nat"
<ide> "github.com/docker/docker/pkg/signal"
<del> "github.com/docker/docker/pkg/stringutils"
<ide> "github.com/docker/docker/pkg/system"
<ide> "github.com/docker/docker/runconfig"
<ide> )
<ide> func run(b *Builder, args []string, attributes map[string]bool, original string)
<ide> // stash the config environment
<ide> env := b.runConfig.Env
<ide>
<del> defer func(cmd *stringutils.StrSlice) { b.runConfig.Cmd = cmd }(cmd)
<add> defer func(cmd *strslice.StrSlice) { b.runConfig.Cmd = cmd }(cmd)
<ide> defer func(env []string) { b.runConfig.Env = env }(env)
<ide>
<ide> // derive the net build-time environment for this run. We let config
<ide> func run(b *Builder, args []string, attributes map[string]bool, original string)
<ide> if len(cmdBuildEnv) > 0 {
<ide> sort.Strings(cmdBuildEnv)
<ide> tmpEnv := append([]string{fmt.Sprintf("|%d", len(cmdBuildEnv))}, cmdBuildEnv...)
<del> saveCmd = stringutils.NewStrSlice(append(tmpEnv, saveCmd.Slice()...)...)
<add> saveCmd = strslice.New(append(tmpEnv, saveCmd.Slice()...)...)
<ide> }
<ide>
<ide> b.runConfig.Cmd = saveCmd
<ide> func cmd(b *Builder, args []string, attributes map[string]bool, original string)
<ide> }
<ide> }
<ide>
<del> b.runConfig.Cmd = stringutils.NewStrSlice(cmdSlice...)
<add> b.runConfig.Cmd = strslice.New(cmdSlice...)
<ide>
<ide> if err := b.commit("", b.runConfig.Cmd, fmt.Sprintf("CMD %q", cmdSlice)); err != nil {
<ide> return err
<ide> func entrypoint(b *Builder, args []string, attributes map[string]bool, original
<ide> switch {
<ide> case attributes["json"]:
<ide> // ENTRYPOINT ["echo", "hi"]
<del> b.runConfig.Entrypoint = stringutils.NewStrSlice(parsed...)
<add> b.runConfig.Entrypoint = strslice.New(parsed...)
<ide> case len(parsed) == 0:
<ide> // ENTRYPOINT []
<ide> b.runConfig.Entrypoint = nil
<ide> default:
<ide> // ENTRYPOINT echo hi
<ide> if runtime.GOOS != "windows" {
<del> b.runConfig.Entrypoint = stringutils.NewStrSlice("/bin/sh", "-c", parsed[0])
<add> b.runConfig.Entrypoint = strslice.New("/bin/sh", "-c", parsed[0])
<ide> } else {
<del> b.runConfig.Entrypoint = stringutils.NewStrSlice("cmd", "/S", "/C", parsed[0])
<add> b.runConfig.Entrypoint = strslice.New("cmd", "/S", "/C", parsed[0])
<ide> }
<ide> }
<ide>
<ide><path>builder/dockerfile/internals.go
<ide> import (
<ide> "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/api"
<ide> "github.com/docker/docker/api/types"
<add> "github.com/docker/docker/api/types/strslice"
<ide> "github.com/docker/docker/builder"
<ide> "github.com/docker/docker/builder/dockerfile/parser"
<ide> "github.com/docker/docker/pkg/archive"
<ide> import (
<ide> "github.com/docker/docker/pkg/progress"
<ide> "github.com/docker/docker/pkg/streamformatter"
<ide> "github.com/docker/docker/pkg/stringid"
<del> "github.com/docker/docker/pkg/stringutils"
<ide> "github.com/docker/docker/pkg/system"
<ide> "github.com/docker/docker/pkg/tarsum"
<ide> "github.com/docker/docker/pkg/urlutil"
<ide> "github.com/docker/docker/runconfig"
<ide> )
<ide>
<del>func (b *Builder) commit(id string, autoCmd *stringutils.StrSlice, comment string) error {
<add>func (b *Builder) commit(id string, autoCmd *strslice.StrSlice, comment string) error {
<ide> if b.disableCommit {
<ide> return nil
<ide> }
<ide> func (b *Builder) commit(id string, autoCmd *stringutils.StrSlice, comment strin
<ide> if id == "" {
<ide> cmd := b.runConfig.Cmd
<ide> if runtime.GOOS != "windows" {
<del> b.runConfig.Cmd = stringutils.NewStrSlice("/bin/sh", "-c", "#(nop) "+comment)
<add> b.runConfig.Cmd = strslice.New("/bin/sh", "-c", "#(nop) "+comment)
<ide> } else {
<del> b.runConfig.Cmd = stringutils.NewStrSlice("cmd", "/S /C", "REM (nop) "+comment)
<add> b.runConfig.Cmd = strslice.New("cmd", "/S /C", "REM (nop) "+comment)
<ide> }
<del> defer func(cmd *stringutils.StrSlice) { b.runConfig.Cmd = cmd }(cmd)
<add> defer func(cmd *strslice.StrSlice) { b.runConfig.Cmd = cmd }(cmd)
<ide>
<ide> hit, err := b.probeCache()
<ide> if err != nil {
<ide> func (b *Builder) runContextCommand(args []string, allowRemote bool, allowLocalD
<ide>
<ide> cmd := b.runConfig.Cmd
<ide> if runtime.GOOS != "windows" {
<del> b.runConfig.Cmd = stringutils.NewStrSlice("/bin/sh", "-c", fmt.Sprintf("#(nop) %s %s in %s", cmdName, srcHash, dest))
<add> b.runConfig.Cmd = strslice.New("/bin/sh", "-c", fmt.Sprintf("#(nop) %s %s in %s", cmdName, srcHash, dest))
<ide> } else {
<del> b.runConfig.Cmd = stringutils.NewStrSlice("cmd", "/S", "/C", fmt.Sprintf("REM (nop) %s %s in %s", cmdName, srcHash, dest))
<add> b.runConfig.Cmd = strslice.New("cmd", "/S", "/C", fmt.Sprintf("REM (nop) %s %s in %s", cmdName, srcHash, dest))
<ide> }
<del> defer func(cmd *stringutils.StrSlice) { b.runConfig.Cmd = cmd }(cmd)
<add> defer func(cmd *strslice.StrSlice) { b.runConfig.Cmd = cmd }(cmd)
<ide>
<ide> if hit, err := b.probeCache(); err != nil {
<ide> return err
<ide><path>daemon/daemon.go
<ide> import (
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/api/types/filters"
<ide> registrytypes "github.com/docker/docker/api/types/registry"
<add> "github.com/docker/docker/api/types/strslice"
<ide> "github.com/docker/docker/container"
<ide> "github.com/docker/docker/daemon/events"
<ide> "github.com/docker/docker/daemon/exec"
<ide> import (
<ide> "github.com/docker/docker/pkg/signal"
<ide> "github.com/docker/docker/pkg/streamformatter"
<ide> "github.com/docker/docker/pkg/stringid"
<del> "github.com/docker/docker/pkg/stringutils"
<ide> "github.com/docker/docker/pkg/sysinfo"
<ide> "github.com/docker/docker/pkg/system"
<ide> "github.com/docker/docker/pkg/truncindex"
<ide> func (daemon *Daemon) generateHostname(id string, config *runconfig.Config) {
<ide> }
<ide> }
<ide>
<del>func (daemon *Daemon) getEntrypointAndArgs(configEntrypoint *stringutils.StrSlice, configCmd *stringutils.StrSlice) (string, []string) {
<add>func (daemon *Daemon) getEntrypointAndArgs(configEntrypoint *strslice.StrSlice, configCmd *strslice.StrSlice) (string, []string) {
<ide> cmdSlice := configCmd.Slice()
<ide> if configEntrypoint.Len() != 0 {
<ide> eSlice := configEntrypoint.Slice()
<ide><path>daemon/exec.go
<ide> import (
<ide> "time"
<ide>
<ide> "github.com/Sirupsen/logrus"
<add> "github.com/docker/docker/api/types/strslice"
<ide> "github.com/docker/docker/container"
<ide> "github.com/docker/docker/daemon/exec"
<ide> "github.com/docker/docker/daemon/execdriver"
<ide> derr "github.com/docker/docker/errors"
<ide> "github.com/docker/docker/pkg/pools"
<ide> "github.com/docker/docker/pkg/promise"
<del> "github.com/docker/docker/pkg/stringutils"
<ide> "github.com/docker/docker/runconfig"
<ide> )
<ide>
<ide> func (d *Daemon) ContainerExecCreate(config *runconfig.ExecConfig) (string, erro
<ide> return "", err
<ide> }
<ide>
<del> cmd := stringutils.NewStrSlice(config.Cmd...)
<del> entrypoint, args := d.getEntrypointAndArgs(stringutils.NewStrSlice(), cmd)
<add> cmd := strslice.New(config.Cmd...)
<add> entrypoint, args := d.getEntrypointAndArgs(strslice.New(), cmd)
<ide>
<ide> processConfig := &execdriver.ProcessConfig{
<ide> CommonProcessConfig: execdriver.CommonProcessConfig{
<ide><path>runconfig/compare_test.go
<ide> package runconfig
<ide> import (
<ide> "testing"
<ide>
<add> "github.com/docker/docker/api/types/strslice"
<ide> "github.com/docker/docker/pkg/nat"
<del> "github.com/docker/docker/pkg/stringutils"
<ide> )
<ide>
<ide> // Just to make life easier
<ide> func TestCompare(t *testing.T) {
<ide> volumes3["/test3"] = struct{}{}
<ide> envs1 := []string{"ENV1=value1", "ENV2=value2"}
<ide> envs2 := []string{"ENV1=value1", "ENV3=value3"}
<del> entrypoint1 := stringutils.NewStrSlice("/bin/sh", "-c")
<del> entrypoint2 := stringutils.NewStrSlice("/bin/sh", "-d")
<del> entrypoint3 := stringutils.NewStrSlice("/bin/sh", "-c", "echo")
<del> cmd1 := stringutils.NewStrSlice("/bin/sh", "-c")
<del> cmd2 := stringutils.NewStrSlice("/bin/sh", "-d")
<del> cmd3 := stringutils.NewStrSlice("/bin/sh", "-c", "echo")
<add> entrypoint1 := strslice.New("/bin/sh", "-c")
<add> entrypoint2 := strslice.New("/bin/sh", "-d")
<add> entrypoint3 := strslice.New("/bin/sh", "-c", "echo")
<add> cmd1 := strslice.New("/bin/sh", "-c")
<add> cmd2 := strslice.New("/bin/sh", "-d")
<add> cmd3 := strslice.New("/bin/sh", "-c", "echo")
<ide> labels1 := map[string]string{"LABEL1": "value1", "LABEL2": "value2"}
<ide> labels2 := map[string]string{"LABEL1": "value1", "LABEL2": "value3"}
<ide> labels3 := map[string]string{"LABEL1": "value1", "LABEL2": "value2", "LABEL3": "value3"}
<ide><path>runconfig/config.go
<ide> import (
<ide> "fmt"
<ide> "io"
<ide>
<add> "github.com/docker/docker/api/types/strslice"
<ide> "github.com/docker/docker/pkg/nat"
<del> "github.com/docker/docker/pkg/stringutils"
<ide> "github.com/docker/docker/volume"
<ide> )
<ide>
<ide> type Config struct {
<ide> OpenStdin bool // Open stdin
<ide> StdinOnce bool // If true, close stdin after the 1 attached client disconnects.
<ide> Env []string // List of environment variable to set in the container
<del> Cmd *stringutils.StrSlice // Command to run when starting the container
<add> Cmd *strslice.StrSlice // Command to run when starting the container
<ide> ArgsEscaped bool `json:",omitempty"` // True if command is already escaped (Windows specific)
<ide> Image string // Name of the image as it was passed by the operator (eg. could be symbolic)
<ide> Volumes map[string]struct{} // List of volumes (mounts) used for the container
<ide> WorkingDir string // Current directory (PWD) in the command will be launched
<del> Entrypoint *stringutils.StrSlice // Entrypoint to run when starting the container
<add> Entrypoint *strslice.StrSlice // Entrypoint to run when starting the container
<ide> NetworkDisabled bool `json:",omitempty"` // Is network disabled
<ide> MacAddress string `json:",omitempty"` // Mac Address of the container
<ide> OnBuild []string // ONBUILD metadata that were defined on the image Dockerfile
<ide><path>runconfig/config_test.go
<ide> import (
<ide> "strings"
<ide> "testing"
<ide>
<del> "github.com/docker/docker/pkg/stringutils"
<add> "github.com/docker/docker/api/types/strslice"
<ide> )
<ide>
<ide> type f struct {
<ide> file string
<del> entrypoint *stringutils.StrSlice
<add> entrypoint *strslice.StrSlice
<ide> }
<ide>
<ide> func TestDecodeContainerConfig(t *testing.T) {
<ide> func TestDecodeContainerConfig(t *testing.T) {
<ide> if runtime.GOOS != "windows" {
<ide> image = "ubuntu"
<ide> fixtures = []f{
<del> {"fixtures/unix/container_config_1_14.json", stringutils.NewStrSlice()},
<del> {"fixtures/unix/container_config_1_17.json", stringutils.NewStrSlice("bash")},
<del> {"fixtures/unix/container_config_1_19.json", stringutils.NewStrSlice("bash")},
<add> {"fixtures/unix/container_config_1_14.json", strslice.New()},
<add> {"fixtures/unix/container_config_1_17.json", strslice.New("bash")},
<add> {"fixtures/unix/container_config_1_19.json", strslice.New("bash")},
<ide> }
<ide> } else {
<ide> image = "windows"
<ide> fixtures = []f{
<del> {"fixtures/windows/container_config_1_19.json", stringutils.NewStrSlice("cmd")},
<add> {"fixtures/windows/container_config_1_19.json", strslice.New("cmd")},
<ide> }
<ide> }
<ide>
<ide><path>runconfig/hostconfig.go
<ide> import (
<ide> "io"
<ide> "strings"
<ide>
<add> "github.com/docker/docker/api/types/strslice"
<ide> "github.com/docker/docker/pkg/blkiodev"
<ide> "github.com/docker/docker/pkg/nat"
<del> "github.com/docker/docker/pkg/stringutils"
<ide> "github.com/docker/docker/pkg/ulimit"
<ide> )
<ide>
<ide> type HostConfig struct {
<ide> VolumesFrom []string // List of volumes to take from other container
<ide>
<ide> // Applicable to UNIX platforms
<del> CapAdd *stringutils.StrSlice // List of kernel capabilities to add to the container
<del> CapDrop *stringutils.StrSlice // List of kernel capabilities to remove from the container
<del> DNS []string `json:"Dns"` // List of DNS server to lookup
<del> DNSOptions []string `json:"DnsOptions"` // List of DNSOption to look for
<del> DNSSearch []string `json:"DnsSearch"` // List of DNSSearch to look for
<del> ExtraHosts []string // List of extra hosts
<del> GroupAdd []string // List of additional groups that the container process will run as
<del> IpcMode IpcMode // IPC namespace to use for the container
<del> Links []string // List of links (in the name:alias form)
<del> OomScoreAdj int // Container preference for OOM-killing
<del> PidMode PidMode // PID namespace to use for the container
<del> Privileged bool // Is the container in privileged mode
<del> PublishAllPorts bool // Should docker publish all exposed port for the container
<del> ReadonlyRootfs bool // Is the container root filesystem in read-only
<del> SecurityOpt []string // List of string values to customize labels for MLS systems, such as SELinux.
<del> Tmpfs map[string]string `json:",omitempty"` // List of tmpfs (mounts) used for the container
<del> UTSMode UTSMode // UTS namespace to use for the container
<del> ShmSize *int64 // Total shm memory usage
<add> CapAdd *strslice.StrSlice // List of kernel capabilities to add to the container
<add> CapDrop *strslice.StrSlice // List of kernel capabilities to remove from the container
<add> DNS []string `json:"Dns"` // List of DNS server to lookup
<add> DNSOptions []string `json:"DnsOptions"` // List of DNSOption to look for
<add> DNSSearch []string `json:"DnsSearch"` // List of DNSSearch to look for
<add> ExtraHosts []string // List of extra hosts
<add> GroupAdd []string // List of additional groups that the container process will run as
<add> IpcMode IpcMode // IPC namespace to use for the container
<add> Links []string // List of links (in the name:alias form)
<add> OomScoreAdj int // Container preference for OOM-killing
<add> PidMode PidMode // PID namespace to use for the container
<add> Privileged bool // Is the container in privileged mode
<add> PublishAllPorts bool // Should docker publish all exposed port for the container
<add> ReadonlyRootfs bool // Is the container root filesystem in read-only
<add> SecurityOpt []string // List of string values to customize labels for MLS systems, such as SELinux.
<add> Tmpfs map[string]string `json:",omitempty"` // List of tmpfs (mounts) used for the container
<add> UTSMode UTSMode // UTS namespace to use for the container
<add> ShmSize *int64 // Total shm memory usage
<ide>
<ide> // Applicable to Windows
<ide> ConsoleSize [2]int // Initial console size
<ide><path>runconfig/parse.go
<ide> import (
<ide> "strconv"
<ide> "strings"
<ide>
<add> "github.com/docker/docker/api/types/strslice"
<ide> "github.com/docker/docker/opts"
<ide> flag "github.com/docker/docker/pkg/mflag"
<ide> "github.com/docker/docker/pkg/mount"
<ide> "github.com/docker/docker/pkg/nat"
<ide> "github.com/docker/docker/pkg/parsers"
<ide> "github.com/docker/docker/pkg/signal"
<del> "github.com/docker/docker/pkg/stringutils"
<ide> "github.com/docker/docker/volume"
<ide> "github.com/docker/go-units"
<ide> )
<ide> func Parse(cmd *flag.FlagSet, args []string) (*Config, *HostConfig, *flag.FlagSe
<ide>
<ide> var (
<ide> parsedArgs = cmd.Args()
<del> runCmd *stringutils.StrSlice
<del> entrypoint *stringutils.StrSlice
<add> runCmd *strslice.StrSlice
<add> entrypoint *strslice.StrSlice
<ide> image = cmd.Arg(0)
<ide> )
<ide> if len(parsedArgs) > 1 {
<del> runCmd = stringutils.NewStrSlice(parsedArgs[1:]...)
<add> runCmd = strslice.New(parsedArgs[1:]...)
<ide> }
<ide> if *flEntrypoint != "" {
<del> entrypoint = stringutils.NewStrSlice(*flEntrypoint)
<add> entrypoint = strslice.New(*flEntrypoint)
<ide> }
<ide>
<ide> var (
<ide> func Parse(cmd *flag.FlagSet, args []string) (*Config, *HostConfig, *flag.FlagSe
<ide> IpcMode: ipcMode,
<ide> PidMode: pidMode,
<ide> UTSMode: utsMode,
<del> CapAdd: stringutils.NewStrSlice(flCapAdd.GetAll()...),
<del> CapDrop: stringutils.NewStrSlice(flCapDrop.GetAll()...),
<add> CapAdd: strslice.New(flCapAdd.GetAll()...),
<add> CapDrop: strslice.New(flCapDrop.GetAll()...),
<ide> GroupAdd: flGroupAdd.GetAll(),
<ide> RestartPolicy: restartPolicy,
<ide> SecurityOpt: flSecurityOpt.GetAll(), | 11 |
Javascript | Javascript | add support for standalone months | 96c73a0672f0e46ae9285c482b057bd03ce135ba | <ide><path>i18n/spec/closureI18nExtractorSpec.js
<ide> function newTestLocaleInfo() {
<ide> DATETIME_FORMATS: {
<ide> MONTH: ['janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre',
<ide> 'octobre', 'novembre', 'décembre'],
<add> STANDALONEMONTH: ['janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre',
<add> 'octobre', 'novembre', 'décembre'],
<ide> SHORTMONTH: ['janv.', 'févr.', 'mars', 'avr.', 'mai', 'juin', 'juil.', 'août', 'sept.', 'oct.',
<ide> 'nov.', 'déc.'],
<ide> DAY: ['dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi'],
<ide> describe("extractDateTimeSymbols", function() {
<ide> DATETIME_FORMATS: {
<ide> MONTH: ['janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre',
<ide> 'octobre', 'novembre', 'décembre'],
<add> STANDALONEMONTH: ['janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet',
<add> 'août', 'septembre', 'octobre', 'novembre', 'décembre'],
<ide> SHORTMONTH: ['janv.', 'févr.', 'mars', 'avr.', 'mai', 'juin', 'juil.', 'août', 'sept.', 'oct.',
<ide> 'nov.', 'déc.'],
<ide> DAY: ['dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi'],
<ide><path>i18n/spec/converterSpec.js
<ide> describe("convertNumberData", function() {
<ide> describe("convertDatetimeData", function() {
<ide> var convert = converter.convertDatetimeData,
<ide> dataObj = { MONTHS: ['Enero', 'Pebrero'],
<add> STANDALONEMONTHS: ['Enero', 'Pebrero'],
<ide> SHORTMONTHS: ['Ene', 'Peb'],
<ide> WEEKDAYS: ['Linggo', 'Lunes'],
<ide> SHORTWEEKDAYS: ['Lin', 'Lun'],
<ide> describe("convertDatetimeData", function() {
<ide> it('should convert empty datetime obj', function() {
<ide> var processedData = convert(dataObj);
<ide> expect(processedData.MONTH).toEqual(['Enero', 'Pebrero']);
<add> expect(processedData.STANDALONEMONTH).toEqual(['Enero', 'Pebrero']);
<ide> expect(processedData.SHORTMONTH).toEqual(['Ene', 'Peb']);
<ide> expect(processedData.DAY).toEqual(['Linggo', 'Lunes']);
<ide> expect(processedData.SHORTDAY).toEqual(['Lin', 'Lun']);
<ide><path>i18n/src/converter.js
<ide> function convertDatetimeData(dataObj) {
<ide>
<ide> datetimeFormats.MONTH = dataObj.MONTHS;
<ide> datetimeFormats.SHORTMONTH = dataObj.SHORTMONTHS;
<add> datetimeFormats.STANDALONEMONTH = dataObj.STANDALONEMONTHS;
<ide> datetimeFormats.DAY = dataObj.WEEKDAYS;
<ide> datetimeFormats.SHORTDAY = dataObj.SHORTWEEKDAYS;
<ide> datetimeFormats.AMPMS = dataObj.AMPMS; | 3 |
Ruby | Ruby | fix the count test for postgres | a56518aee2258472f5f80807d733ccfa63eedb2d | <ide><path>activerecord/test/cases/relations_test.rb
<ide> def test_count_explicit_columns
<ide> Post.update_all(:comments_count => nil)
<ide> posts = Post.scoped
<ide>
<del> assert_equal 0, posts.select('comments_count').where('id is not null').order('id').count
<add> assert_equal [0], posts.select('comments_count').where('id is not null').group('id').order('id').count.values.uniq
<ide> assert_equal 0, posts.where('id is not null').select('comments_count').count
<ide>
<ide> assert_equal 7, posts.select('comments_count').count('id') | 1 |
Text | Text | fix typo guides/source/configuring.md | 612d106d5d732cc7cc0e3a6c5b8a0aa31e4fdf39 | <ide><path>guides/source/configuring.md
<ide> The schema dumper adds two additional configuration options:
<ide>
<ide> * `config.action_controller.per_form_csrf_tokens` configures whether CSRF tokens are only valid for the method/action they were generated for.
<ide>
<del>* `config.action_controller.default_protect_from_forgery` determines whether forgery protection is added on `ActionController:Base`. This is false by default.
<add>* `config.action_controller.default_protect_from_forgery` determines whether forgery protection is added on `ActionController::Base`. This is false by default.
<ide>
<ide> * `config.action_controller.relative_url_root` can be used to tell Rails that you are [deploying to a subdirectory](configuring.html#deploy-to-a-subdirectory-relative-url-root). The default is `ENV['RAILS_RELATIVE_URL_ROOT']`.
<ide> | 1 |
Ruby | Ruby | pass the mapping object to build_route | 5ba6966766e67af4ae0028c4429acbd280a100a2 | <ide><path>actionpack/lib/action_dispatch/routing/mapper.rb
<ide> class Mapping #:nodoc:
<ide>
<ide> attr_reader :requirements, :conditions, :defaults
<ide> attr_reader :to, :default_controller, :default_action
<add> attr_reader :required_defaults
<ide>
<ide> def self.build(scope, set, ast, controller, default_action, to, via, formatted, options_constraints, options)
<ide> options = scope[:options].merge(options) if scope[:options]
<ide> def initialize(set, ast, defaults, controller, default_action, modyoule, to, for
<ide> @conditions = Hash[conditions]
<ide> @defaults = formats[:defaults].merge(@defaults).merge(normalize_defaults(options))
<ide>
<del> @conditions[:required_defaults] = (split_options[:required_defaults] || []).map(&:first)
<add> @required_defaults = (split_options[:required_defaults] || []).map(&:first)
<ide> unless via == [:all]
<ide> @conditions[:request_method] = via.map { |m| m.to_s.dasherize.upcase }
<ide> end
<ide> end
<ide>
<del> def to_route
<del> [ app(@blocks), conditions, requirements, defaults ]
<add> def application
<add> app(@blocks)
<ide> end
<ide>
<ide> private
<ide> def add_route(action, controller, options, _path, to, via, formatted, anchor, op
<ide> ast = Journey::Parser.parse path
<ide>
<ide> mapping = Mapping.build(@scope, @set, ast, controller, default_action, to, via, formatted, options_constraints, options)
<del> app, conditions, requirements, defaults = mapping.to_route
<del> @set.add_route(app, conditions, ast, requirements, defaults, as, anchor)
<add> @set.add_route(mapping, ast, as, anchor)
<ide> end
<ide>
<ide> def root(path, options={})
<ide><path>actionpack/lib/action_dispatch/routing/route_set.rb
<ide> def empty?
<ide> routes.empty?
<ide> end
<ide>
<del> def add_route(app, conditions, path_ast, requirements, defaults, name, anchor)
<add> def add_route(mapping, path_ast, name, anchor)
<ide> raise ArgumentError, "Invalid route name: '#{name}'" unless name.blank? || name.to_s.match(/^[_a-z]\w*$/i)
<ide>
<ide> if name && named_routes[name]
<ide> def add_route(app, conditions, path_ast, requirements, defaults, name, anchor)
<ide> "http://guides.rubyonrails.org/routing.html#restricting-the-routes-created"
<ide> end
<ide>
<del> required_defaults = conditions.delete :required_defaults
<del> path = build_path(path_ast, requirements, anchor)
<del> conditions = build_conditions(conditions)
<add> required_defaults = mapping.required_defaults
<add> path = build_path(path_ast, mapping.requirements, anchor)
<add> conditions = build_conditions(mapping.conditions)
<ide>
<del> route = @set.add_route(app, path, conditions, required_defaults, defaults, name)
<add> route = @set.add_route(mapping.application, path, conditions, required_defaults, mapping.defaults, name)
<ide> named_routes[name] = route if name
<ide> route
<ide> end
<ide><path>actionpack/test/dispatch/mapper_test.rb
<ide> module ActionDispatch
<ide> module Routing
<ide> class MapperTest < ActiveSupport::TestCase
<ide> class FakeSet < ActionDispatch::Routing::RouteSet
<del> def initialize
<del> @my_routes = []
<del> super
<del> end
<del>
<ide> def resources_path_names
<ide> {}
<ide> end
<ide>
<del> def add_route(*args)
<del> @my_routes << args
<del> super
<del> end
<del>
<ide> def request_class
<ide> ActionDispatch::Request
<ide> end
<ide> def dispatcher_class
<ide> end
<ide>
<ide> def defaults
<del> @my_routes.map { |x| x[4] }
<add> routes.map(&:defaults)
<ide> end
<ide>
<ide> def conditions
<del> @my_routes.map { |x| x[1] }
<add> routes.map(&:constraints)
<ide> end
<ide>
<ide> def requirements
<ide> def test_random_keys
<ide> end
<ide> assert_equal({:omg=>:awesome, :controller=>"posts", :action=>"index"},
<ide> fakeset.defaults.first)
<del> assert_equal ["GET"], fakeset.conditions.first[:request_method]
<add> assert_equal(/^GET$/, fakeset.conditions.first[:request_method])
<ide> end
<ide>
<ide> def test_mapping_requirements
<ide> options = { }
<ide> scope = Mapper::Scope.new({})
<ide> ast = Journey::Parser.parse '/store/:name(*rest)'
<ide> m = Mapper::Mapping.build(scope, FakeSet.new, ast, 'foo', 'bar', nil, [:get], nil, {}, options)
<del> _, _, requirements, _ = m.to_route
<del> assert_equal(/.+?/, requirements[:rest])
<add> assert_equal(/.+?/, m.requirements[:rest])
<ide> end
<ide>
<ide> def test_via_scope
<ide> def test_via_scope
<ide> mapper.scope(via: :put) do
<ide> mapper.match '/', :to => 'posts#index', :as => :main
<ide> end
<del> assert_equal ["PUT"], fakeset.conditions.first[:request_method]
<add> assert_equal(/^PUT$/, fakeset.conditions.first[:request_method])
<ide> end
<ide>
<ide> def test_map_slash | 3 |
Python | Python | add correct uppercase variants for boolean flags | fca3907d4e761519e08b785aba958bf7846585ac | <ide><path>spacy/cli/download.py
<ide> def download_cli(
<ide> # fmt: off
<ide> ctx: typer.Context,
<ide> model: str = Arg(..., help="Model to download (shortcut or name)"),
<del> direct: bool = Opt(False, "--direct", "-d", help="Force direct download of name + version"),
<add> direct: bool = Opt(False, "--direct", "-d", "-D", help="Force direct download of name + version"),
<ide> # fmt: on
<ide> ):
<ide> """
<ide><path>spacy/cli/info.py
<ide> def info_cli(
<ide> # fmt: off
<ide> model: Optional[str] = Arg(None, help="Optional model name"),
<ide> markdown: bool = Opt(False, "--markdown", "-md", help="Generate Markdown for GitHub issues"),
<del> silent: bool = Opt(False, "--silent", "-s", help="Don't print anything (just return)"),
<add> silent: bool = Opt(False, "--silent", "-s", "-S", help="Don't print anything (just return)"),
<ide> # fmt: on
<ide> ):
<ide> """
<ide><path>spacy/cli/package.py
<ide> def package_cli(
<ide> input_dir: Path = Arg(..., help="Directory with model data", exists=True, file_okay=False),
<ide> output_dir: Path = Arg(..., help="Output parent directory", exists=True, file_okay=False),
<ide> meta_path: Optional[Path] = Opt(None, "--meta-path", "-m", help="Path to meta.json", exists=True, dir_okay=False),
<del> create_meta: bool = Opt(False, "--create-meta", "-c", help="Create meta.json, even if one exists"),
<add> create_meta: bool = Opt(False, "--create-meta", "-c", "-C", help="Create meta.json, even if one exists"),
<ide> force: bool = Opt(False, "--force", "-f", "-F", help="Force overwriting existing model in output directory"),
<ide> # fmt: on
<ide> ): | 3 |
PHP | PHP | add file class | 99cf673faea7ed8c18f534596685492b4fb615e0 | <ide><path>src/Illuminate/Filesystem/FilesystemAdapter.php
<ide> namespace Illuminate\Filesystem;
<ide>
<ide> use RuntimeException;
<add>use Illuminate\Http\File;
<ide> use Illuminate\Support\Str;
<ide> use InvalidArgumentException;
<ide> use Illuminate\Http\UploadedFile;
<ide> public function get($path)
<ide> */
<ide> public function put($path, $contents, $visibility = null)
<ide> {
<del> if ($contents instanceof UploadedFile) {
<add> if ($contents instanceof File || $contents instanceof UploadedFile) {
<ide> return $this->putFile($path, $contents, $visibility);
<ide> }
<ide>
<ide> public function putFile($path, $file, $visibility = null)
<ide> * Store the uploaded file on the disk with a given name.
<ide> *
<ide> * @param string $path
<del> * @param \Illuminate\Http\UploadedFile $file
<add> * @param \Illuminate\Http\File|\Illuminate\Http\UploadedFile $file
<ide> * @param string $name
<ide> * @param string $visibility
<ide> * @return string|false
<ide> */
<ide> public function putFileAs($path, $file, $name, $visibility = null)
<ide> {
<del> $stream = fopen($file->path(), 'r+');
<add> $stream = fopen($file->getRealPath(), 'r+');
<ide>
<ide> $result = $this->put($path = trim($path.'/'.$name, '/'), $stream, $visibility);
<ide>
<ide><path>src/Illuminate/Http/File.php
<add><?php
<add>
<add>namespace Illuminate\Http;
<add>
<add>use Symfony\Component\HttpFoundation\File\File as SymfonyFile;
<add>
<add>class File extends SymfonyFile
<add>{
<add> use HashesFileNames;
<add>}
<ide><path>src/Illuminate/Http/HashesFileNames.php
<add><?php
<add>
<add>namespace Illuminate\Http;
<add>
<add>trait HashesFileNames
<add>{
<add> /**
<add> * Get a filename for the file that is the MD5 hash of the contents.
<add> *
<add> * @param string $path
<add> * @return string
<add> */
<add> public function hashName($path = null)
<add> {
<add> if ($path) {
<add> $path = rtrim($path, '/').'/';
<add> }
<add>
<add> return $path.md5_file($this->getRealPath()).'.'.$this->guessExtension();
<add> }
<add>}
<ide><path>src/Illuminate/Http/UploadedFile.php
<ide>
<ide> class UploadedFile extends SymfonyUploadedFile
<ide> {
<del> use Macroable;
<add> use HashesFileNames, Macroable;
<ide>
<ide> /**
<ide> * Get the fully qualified path to the file.
<ide> public function clientExtension()
<ide> return $this->guessClientExtension();
<ide> }
<ide>
<del> /**
<del> * Get a filename for the file that is the MD5 hash of the contents.
<del> *
<del> * @param string $path
<del> * @return string
<del> */
<del> public function hashName($path = null)
<del> {
<del> if ($path) {
<del> $path = rtrim($path, '/').'/';
<del> }
<del>
<del> return $path.md5_file($this->path()).'.'.$this->extension();
<del> }
<del>
<ide> /**
<ide> * Store the uploaded file on a filesystem disk.
<ide> * | 4 |
Go | Go | move testrundetach to integration-cli | f7538c77efaf47fa5b82ae844b5c01887239ce65 | <ide><path>integration-cli/docker_cli_run_unix_test.go
<ide> package main
<ide>
<ide> import (
<add> "bufio"
<ide> "fmt"
<ide> "io/ioutil"
<ide> "os"
<ide> func TestRunDeviceDirectory(t *testing.T) {
<ide>
<ide> logDone("run - test --device directory mounts all internal devices")
<ide> }
<add>
<add>// TestRunDetach checks attaching and detaching with the escape sequence.
<add>func TestRunAttachDetach(t *testing.T) {
<add> defer deleteAllContainers()
<add> name := "attach-detach"
<add> cmd := exec.Command(dockerBinary, "run", "--name", name, "-it", "busybox", "cat")
<add> stdout, err := cmd.StdoutPipe()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> cpty, tty, err := pty.Open()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> defer cpty.Close()
<add> cmd.Stdin = tty
<add> if err := cmd.Start(); err != nil {
<add> t.Fatal(err)
<add> }
<add> if err := waitRun(name); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> if _, err := cpty.Write([]byte("hello\n")); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> out, err := bufio.NewReader(stdout).ReadString('\n')
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> if strings.TrimSpace(out) != "hello" {
<add> t.Fatalf("exepected 'hello', got %q", out)
<add> }
<add>
<add> // escape sequence
<add> if _, err := cpty.Write([]byte{16}); err != nil {
<add> t.Fatal(err)
<add> }
<add> time.Sleep(100 * time.Millisecond)
<add> if _, err := cpty.Write([]byte{17}); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> ch := make(chan struct{})
<add> go func() {
<add> cmd.Wait()
<add> ch <- struct{}{}
<add> }()
<add>
<add> running, err := inspectField(name, "State.Running")
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> if running != "true" {
<add> t.Fatal("exepected container to still be running")
<add> }
<add>
<add> go func() {
<add> dockerCmd(t, "kill", name)
<add> }()
<add>
<add> select {
<add> case <-ch:
<add> case <-time.After(10 * time.Millisecond):
<add> t.Fatal("timed out waiting for container to exit")
<add> }
<add>
<add> logDone("run - attach detach")
<add>}
<ide><path>integration-cli/utils.go
<ide> func waitInspect(name, expr, expected string, timeout int) error {
<ide> cmd := exec.Command(dockerBinary, "inspect", "-f", expr, name)
<ide> out, _, err := runCommandWithOutput(cmd)
<ide> if err != nil {
<del> return fmt.Errorf("error executing docker inspect: %v", err)
<add> if !strings.Contains(out, "No such") {
<add> return fmt.Errorf("error executing docker inspect: %v\n%s", err, out)
<add> }
<add> select {
<add> case <-after:
<add> return err
<add> default:
<add> time.Sleep(10 * time.Millisecond)
<add> continue
<add> }
<ide> }
<ide>
<ide> out = strings.TrimSpace(out)
<ide><path>integration/commands_test.go
<ide> func assertPipe(input, output string, r io.Reader, w io.Writer, count int) error
<ide> return nil
<ide> }
<ide>
<del>// TestRunDetach checks attaching and detaching with the escape sequence.
<del>func TestRunDetach(t *testing.T) {
<del> stdout, stdoutPipe := io.Pipe()
<del> cpty, tty, err := pty.Open()
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> cli := client.NewDockerCli(tty, stdoutPipe, ioutil.Discard, "", testDaemonProto, testDaemonAddr, nil)
<del> defer cleanup(globalEngine, t)
<del>
<del> ch := make(chan struct{})
<del> go func() {
<del> defer close(ch)
<del> cli.CmdRun("-i", "-t", unitTestImageID, "cat")
<del> }()
<del>
<del> container := waitContainerStart(t, 10*time.Second)
<del>
<del> state := setRaw(t, container)
<del> defer unsetRaw(t, container, state)
<del>
<del> setTimeout(t, "First read/write assertion timed out", 2*time.Second, func() {
<del> if err := assertPipe("hello\n", "hello", stdout, cpty, 150); err != nil {
<del> t.Fatal(err)
<del> }
<del> })
<del>
<del> setTimeout(t, "Escape sequence timeout", 5*time.Second, func() {
<del> cpty.Write([]byte{16})
<del> time.Sleep(100 * time.Millisecond)
<del> cpty.Write([]byte{17})
<del> })
<del>
<del> // wait for CmdRun to return
<del> setTimeout(t, "Waiting for CmdRun timed out", 15*time.Second, func() {
<del> <-ch
<del> })
<del> closeWrap(cpty, stdout, stdoutPipe)
<del>
<del> time.Sleep(500 * time.Millisecond)
<del> if !container.IsRunning() {
<del> t.Fatal("The detached container should be still running")
<del> }
<del>
<del> setTimeout(t, "Waiting for container to die timed out", 20*time.Second, func() {
<del> container.Kill()
<del> })
<del>}
<del>
<ide> // TestAttachDetach checks that attach in tty mode can be detached using the long container ID
<ide> func TestAttachDetach(t *testing.T) {
<ide> stdout, stdoutPipe := io.Pipe() | 3 |
PHP | PHP | fix doc block | f9db56b5576fb32c52e2963fd5927ae111938bb8 | <ide><path>tests/TestCase/ORM/TableTest.php
<ide> public function testGetWithCache($options, $cacheKey, $cacheConfig)
<ide> /**
<ide> * Tests that get() will throw an exception if the record was not found
<ide> *
<del> * @expectedException Cake\Datasource\Exception\RecordNotFoundException
<add> * @expectedException \Cake\Datasource\Exception\RecordNotFoundException
<ide> * @expectedExceptionMessage Record not found in table "articles"
<ide> * @return void
<ide> */ | 1 |
Go | Go | replace pkg/units with docker/go-units | 4fef42ba206ac90346e6e0fe25bead3f77dc4b0f | <ide><path>api/client/build.go
<ide> import (
<ide> "github.com/docker/docker/pkg/progress"
<ide> "github.com/docker/docker/pkg/streamformatter"
<ide> "github.com/docker/docker/pkg/ulimit"
<del> "github.com/docker/docker/pkg/units"
<ide> "github.com/docker/docker/pkg/urlutil"
<ide> "github.com/docker/docker/registry"
<ide> tagpkg "github.com/docker/docker/tag"
<ide> "github.com/docker/docker/utils"
<add> "github.com/docker/go-units"
<ide> )
<ide>
<ide> // CmdBuild builds a new image from the source code at a given path.
<ide><path>api/client/history.go
<ide> import (
<ide> flag "github.com/docker/docker/pkg/mflag"
<ide> "github.com/docker/docker/pkg/stringid"
<ide> "github.com/docker/docker/pkg/stringutils"
<del> "github.com/docker/docker/pkg/units"
<add> "github.com/docker/go-units"
<ide> )
<ide>
<ide> // CmdHistory shows the history of an image.
<ide><path>api/client/images.go
<ide> import (
<ide> flag "github.com/docker/docker/pkg/mflag"
<ide> "github.com/docker/docker/pkg/parsers/filters"
<ide> "github.com/docker/docker/pkg/stringid"
<del> "github.com/docker/docker/pkg/units"
<add> "github.com/docker/go-units"
<ide> )
<ide>
<ide> // CmdImages lists the images in a specified repository, or all top-level images if no repository is specified.
<ide><path>api/client/info.go
<ide> import (
<ide> Cli "github.com/docker/docker/cli"
<ide> "github.com/docker/docker/pkg/ioutils"
<ide> flag "github.com/docker/docker/pkg/mflag"
<del> "github.com/docker/docker/pkg/units"
<add> "github.com/docker/go-units"
<ide> )
<ide>
<ide> // CmdInfo displays system-wide information.
<ide><path>api/client/lib/image_build.go
<ide> import (
<ide> "strconv"
<ide>
<ide> "github.com/docker/docker/api/types"
<del> "github.com/docker/docker/pkg/units"
<ide> "github.com/docker/docker/runconfig"
<add> "github.com/docker/go-units"
<ide> )
<ide>
<ide> var headerRegexp = regexp.MustCompile(`\ADocker/.+\s\((.+)\)\z`)
<ide><path>api/client/ps/custom.go
<ide> import (
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/pkg/stringid"
<ide> "github.com/docker/docker/pkg/stringutils"
<del> "github.com/docker/docker/pkg/units"
<add> "github.com/docker/go-units"
<ide> )
<ide>
<ide> const (
<ide><path>api/client/stats.go
<ide> import (
<ide> "github.com/docker/docker/api/types"
<ide> Cli "github.com/docker/docker/cli"
<ide> "github.com/docker/docker/pkg/jsonmessage"
<del> "github.com/docker/docker/pkg/units"
<add> "github.com/docker/go-units"
<ide> )
<ide>
<ide> type containerStats struct {
<ide><path>api/common_test.go
<ide> import (
<ide> "path/filepath"
<ide> "testing"
<ide>
<del> "github.com/docker/docker/api/types"
<ide> "os"
<add>
<add> "github.com/docker/docker/api/types"
<ide> )
<ide>
<ide> type ports struct {
<ide><path>container/state.go
<ide> import (
<ide>
<ide> "github.com/docker/docker/daemon/execdriver"
<ide> derr "github.com/docker/docker/errors"
<del> "github.com/docker/docker/pkg/units"
<add> "github.com/docker/go-units"
<ide> )
<ide>
<ide> // State holds the current container state, and has methods to get and
<ide><path>daemon/graphdriver/devmapper/deviceset.go
<ide> import (
<ide> "github.com/docker/docker/pkg/idtools"
<ide> "github.com/docker/docker/pkg/mount"
<ide> "github.com/docker/docker/pkg/parsers"
<del> "github.com/docker/docker/pkg/units"
<add> "github.com/docker/go-units"
<ide>
<ide> "github.com/opencontainers/runc/libcontainer/label"
<ide> )
<ide><path>daemon/graphdriver/devmapper/driver.go
<ide> import (
<ide> "github.com/docker/docker/pkg/devicemapper"
<ide> "github.com/docker/docker/pkg/idtools"
<ide> "github.com/docker/docker/pkg/mount"
<del> "github.com/docker/docker/pkg/units"
<add> "github.com/docker/go-units"
<ide> )
<ide>
<ide> func init() {
<ide><path>daemon/logger/jsonfilelog/jsonfilelog.go
<ide> import (
<ide> "github.com/docker/docker/daemon/logger"
<ide> "github.com/docker/docker/daemon/logger/loggerutils"
<ide> "github.com/docker/docker/pkg/jsonlog"
<del> "github.com/docker/docker/pkg/units"
<add> "github.com/docker/go-units"
<ide> )
<ide>
<ide> // Name is the name of the file that the jsonlogger logs to.
<ide><path>opts/opts.go
<ide> import (
<ide>
<ide> "github.com/docker/docker/pkg/blkiodev"
<ide> "github.com/docker/docker/pkg/parsers"
<del> "github.com/docker/docker/pkg/units"
<add> "github.com/docker/go-units"
<ide> )
<ide>
<ide> var (
<ide><path>pkg/jsonmessage/jsonmessage.go
<ide> import (
<ide>
<ide> "github.com/docker/docker/pkg/jsonlog"
<ide> "github.com/docker/docker/pkg/term"
<del> "github.com/docker/docker/pkg/units"
<add> "github.com/docker/go-units"
<ide> )
<ide>
<ide> // JSONError wraps a concrete Code and Message, `Code` is
<ide><path>pkg/system/meminfo_linux.go
<ide> import (
<ide> "strconv"
<ide> "strings"
<ide>
<del> "github.com/docker/docker/pkg/units"
<add> "github.com/docker/go-units"
<ide> )
<ide>
<ide> // ReadMemInfo retrieves memory statistics of the host system and returns a
<ide><path>pkg/system/meminfo_unix_test.go
<ide> import (
<ide> "strings"
<ide> "testing"
<ide>
<del> "github.com/docker/docker/pkg/units"
<add> "github.com/docker/go-units"
<ide> )
<ide>
<ide> // TestMemInfo tests parseMemInfo with a static meminfo string
<ide><path>pkg/units/duration.go
<del>// Package units provides helper function to parse and print size and time units
<del>// in human-readable format.
<del>package units
<del>
<del>import (
<del> "fmt"
<del> "time"
<del>)
<del>
<del>// HumanDuration returns a human-readable approximation of a duration
<del>// (eg. "About a minute", "4 hours ago", etc.).
<del>func HumanDuration(d time.Duration) string {
<del> if seconds := int(d.Seconds()); seconds < 1 {
<del> return "Less than a second"
<del> } else if seconds < 60 {
<del> return fmt.Sprintf("%d seconds", seconds)
<del> } else if minutes := int(d.Minutes()); minutes == 1 {
<del> return "About a minute"
<del> } else if minutes < 60 {
<del> return fmt.Sprintf("%d minutes", minutes)
<del> } else if hours := int(d.Hours()); hours == 1 {
<del> return "About an hour"
<del> } else if hours < 48 {
<del> return fmt.Sprintf("%d hours", hours)
<del> } else if hours < 24*7*2 {
<del> return fmt.Sprintf("%d days", hours/24)
<del> } else if hours < 24*30*3 {
<del> return fmt.Sprintf("%d weeks", hours/24/7)
<del> } else if hours < 24*365*2 {
<del> return fmt.Sprintf("%d months", hours/24/30)
<del> }
<del> return fmt.Sprintf("%d years", int(d.Hours())/24/365)
<del>}
<ide><path>pkg/units/duration_test.go
<del>package units
<del>
<del>import (
<del> "testing"
<del> "time"
<del>)
<del>
<del>func TestHumanDuration(t *testing.T) {
<del> // Useful duration abstractions
<del> day := 24 * time.Hour
<del> week := 7 * day
<del> month := 30 * day
<del> year := 365 * day
<del>
<del> assertEquals(t, "Less than a second", HumanDuration(450*time.Millisecond))
<del> assertEquals(t, "47 seconds", HumanDuration(47*time.Second))
<del> assertEquals(t, "About a minute", HumanDuration(1*time.Minute))
<del> assertEquals(t, "3 minutes", HumanDuration(3*time.Minute))
<del> assertEquals(t, "35 minutes", HumanDuration(35*time.Minute))
<del> assertEquals(t, "35 minutes", HumanDuration(35*time.Minute+40*time.Second))
<del> assertEquals(t, "About an hour", HumanDuration(1*time.Hour))
<del> assertEquals(t, "About an hour", HumanDuration(1*time.Hour+45*time.Minute))
<del> assertEquals(t, "3 hours", HumanDuration(3*time.Hour))
<del> assertEquals(t, "3 hours", HumanDuration(3*time.Hour+59*time.Minute))
<del> assertEquals(t, "4 hours", HumanDuration(3*time.Hour+60*time.Minute))
<del> assertEquals(t, "24 hours", HumanDuration(24*time.Hour))
<del> assertEquals(t, "36 hours", HumanDuration(1*day+12*time.Hour))
<del> assertEquals(t, "2 days", HumanDuration(2*day))
<del> assertEquals(t, "7 days", HumanDuration(7*day))
<del> assertEquals(t, "13 days", HumanDuration(13*day+5*time.Hour))
<del> assertEquals(t, "2 weeks", HumanDuration(2*week))
<del> assertEquals(t, "2 weeks", HumanDuration(2*week+4*day))
<del> assertEquals(t, "3 weeks", HumanDuration(3*week))
<del> assertEquals(t, "4 weeks", HumanDuration(4*week))
<del> assertEquals(t, "4 weeks", HumanDuration(4*week+3*day))
<del> assertEquals(t, "4 weeks", HumanDuration(1*month))
<del> assertEquals(t, "6 weeks", HumanDuration(1*month+2*week))
<del> assertEquals(t, "8 weeks", HumanDuration(2*month))
<del> assertEquals(t, "3 months", HumanDuration(3*month+1*week))
<del> assertEquals(t, "5 months", HumanDuration(5*month+2*week))
<del> assertEquals(t, "13 months", HumanDuration(13*month))
<del> assertEquals(t, "23 months", HumanDuration(23*month))
<del> assertEquals(t, "24 months", HumanDuration(24*month))
<del> assertEquals(t, "2 years", HumanDuration(24*month+2*week))
<del> assertEquals(t, "3 years", HumanDuration(3*year+2*month))
<del>}
<ide><path>pkg/units/size.go
<del>package units
<del>
<del>import (
<del> "fmt"
<del> "regexp"
<del> "strconv"
<del> "strings"
<del>)
<del>
<del>// See: http://en.wikipedia.org/wiki/Binary_prefix
<del>const (
<del> // Decimal
<del>
<del> KB = 1000
<del> MB = 1000 * KB
<del> GB = 1000 * MB
<del> TB = 1000 * GB
<del> PB = 1000 * TB
<del>
<del> // Binary
<del>
<del> KiB = 1024
<del> MiB = 1024 * KiB
<del> GiB = 1024 * MiB
<del> TiB = 1024 * GiB
<del> PiB = 1024 * TiB
<del>)
<del>
<del>type unitMap map[string]int64
<del>
<del>var (
<del> decimalMap = unitMap{"k": KB, "m": MB, "g": GB, "t": TB, "p": PB}
<del> binaryMap = unitMap{"k": KiB, "m": MiB, "g": GiB, "t": TiB, "p": PiB}
<del> sizeRegex = regexp.MustCompile(`^(\d+)([kKmMgGtTpP])?[bB]?$`)
<del>)
<del>
<del>var decimapAbbrs = []string{"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"}
<del>var binaryAbbrs = []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"}
<del>
<del>// CustomSize returns a human-readable approximation of a size
<del>// using custom format.
<del>func CustomSize(format string, size float64, base float64, _map []string) string {
<del> i := 0
<del> for size >= base {
<del> size = size / base
<del> i++
<del> }
<del> return fmt.Sprintf(format, size, _map[i])
<del>}
<del>
<del>// HumanSize returns a human-readable approximation of a size
<del>// capped at 4 valid numbers (eg. "2.746 MB", "796 KB").
<del>func HumanSize(size float64) string {
<del> return CustomSize("%.4g %s", size, 1000.0, decimapAbbrs)
<del>}
<del>
<del>// BytesSize returns a human-readable size in bytes, kibibytes,
<del>// mebibytes, gibibytes, or tebibytes (eg. "44kiB", "17MiB").
<del>func BytesSize(size float64) string {
<del> return CustomSize("%.4g %s", size, 1024.0, binaryAbbrs)
<del>}
<del>
<del>// FromHumanSize returns an integer from a human-readable specification of a
<del>// size using SI standard (eg. "44kB", "17MB").
<del>func FromHumanSize(size string) (int64, error) {
<del> return parseSize(size, decimalMap)
<del>}
<del>
<del>// RAMInBytes parses a human-readable string representing an amount of RAM
<del>// in bytes, kibibytes, mebibytes, gibibytes, or tebibytes and
<del>// returns the number of bytes, or -1 if the string is unparseable.
<del>// Units are case-insensitive, and the 'b' suffix is optional.
<del>func RAMInBytes(size string) (int64, error) {
<del> return parseSize(size, binaryMap)
<del>}
<del>
<del>// Parses the human-readable size string into the amount it represents.
<del>func parseSize(sizeStr string, uMap unitMap) (int64, error) {
<del> matches := sizeRegex.FindStringSubmatch(sizeStr)
<del> if len(matches) != 3 {
<del> return -1, fmt.Errorf("invalid size: '%s'", sizeStr)
<del> }
<del>
<del> size, err := strconv.ParseInt(matches[1], 10, 0)
<del> if err != nil {
<del> return -1, err
<del> }
<del>
<del> unitPrefix := strings.ToLower(matches[2])
<del> if mul, ok := uMap[unitPrefix]; ok {
<del> size *= mul
<del> }
<del>
<del> return size, nil
<del>}
<ide><path>pkg/units/size_test.go
<del>package units
<del>
<del>import (
<del> "reflect"
<del> "runtime"
<del> "strings"
<del> "testing"
<del>)
<del>
<del>func TestBytesSize(t *testing.T) {
<del> assertEquals(t, "1 KiB", BytesSize(1024))
<del> assertEquals(t, "1 MiB", BytesSize(1024*1024))
<del> assertEquals(t, "1 MiB", BytesSize(1048576))
<del> assertEquals(t, "2 MiB", BytesSize(2*MiB))
<del> assertEquals(t, "3.42 GiB", BytesSize(3.42*GiB))
<del> assertEquals(t, "5.372 TiB", BytesSize(5.372*TiB))
<del> assertEquals(t, "2.22 PiB", BytesSize(2.22*PiB))
<del>}
<del>
<del>func TestHumanSize(t *testing.T) {
<del> assertEquals(t, "1 kB", HumanSize(1000))
<del> assertEquals(t, "1.024 kB", HumanSize(1024))
<del> assertEquals(t, "1 MB", HumanSize(1000000))
<del> assertEquals(t, "1.049 MB", HumanSize(1048576))
<del> assertEquals(t, "2 MB", HumanSize(2*MB))
<del> assertEquals(t, "3.42 GB", HumanSize(float64(3.42*GB)))
<del> assertEquals(t, "5.372 TB", HumanSize(float64(5.372*TB)))
<del> assertEquals(t, "2.22 PB", HumanSize(float64(2.22*PB)))
<del>}
<del>
<del>func TestFromHumanSize(t *testing.T) {
<del> assertSuccessEquals(t, 32, FromHumanSize, "32")
<del> assertSuccessEquals(t, 32, FromHumanSize, "32b")
<del> assertSuccessEquals(t, 32, FromHumanSize, "32B")
<del> assertSuccessEquals(t, 32*KB, FromHumanSize, "32k")
<del> assertSuccessEquals(t, 32*KB, FromHumanSize, "32K")
<del> assertSuccessEquals(t, 32*KB, FromHumanSize, "32kb")
<del> assertSuccessEquals(t, 32*KB, FromHumanSize, "32Kb")
<del> assertSuccessEquals(t, 32*MB, FromHumanSize, "32Mb")
<del> assertSuccessEquals(t, 32*GB, FromHumanSize, "32Gb")
<del> assertSuccessEquals(t, 32*TB, FromHumanSize, "32Tb")
<del> assertSuccessEquals(t, 32*PB, FromHumanSize, "32Pb")
<del>
<del> assertError(t, FromHumanSize, "")
<del> assertError(t, FromHumanSize, "hello")
<del> assertError(t, FromHumanSize, "-32")
<del> assertError(t, FromHumanSize, "32.3")
<del> assertError(t, FromHumanSize, " 32 ")
<del> assertError(t, FromHumanSize, "32.3Kb")
<del> assertError(t, FromHumanSize, "32 mb")
<del> assertError(t, FromHumanSize, "32m b")
<del> assertError(t, FromHumanSize, "32bm")
<del>}
<del>
<del>func TestRAMInBytes(t *testing.T) {
<del> assertSuccessEquals(t, 32, RAMInBytes, "32")
<del> assertSuccessEquals(t, 32, RAMInBytes, "32b")
<del> assertSuccessEquals(t, 32, RAMInBytes, "32B")
<del> assertSuccessEquals(t, 32*KiB, RAMInBytes, "32k")
<del> assertSuccessEquals(t, 32*KiB, RAMInBytes, "32K")
<del> assertSuccessEquals(t, 32*KiB, RAMInBytes, "32kb")
<del> assertSuccessEquals(t, 32*KiB, RAMInBytes, "32Kb")
<del> assertSuccessEquals(t, 32*MiB, RAMInBytes, "32Mb")
<del> assertSuccessEquals(t, 32*GiB, RAMInBytes, "32Gb")
<del> assertSuccessEquals(t, 32*TiB, RAMInBytes, "32Tb")
<del> assertSuccessEquals(t, 32*PiB, RAMInBytes, "32Pb")
<del> assertSuccessEquals(t, 32*PiB, RAMInBytes, "32PB")
<del> assertSuccessEquals(t, 32*PiB, RAMInBytes, "32P")
<del>
<del> assertError(t, RAMInBytes, "")
<del> assertError(t, RAMInBytes, "hello")
<del> assertError(t, RAMInBytes, "-32")
<del> assertError(t, RAMInBytes, "32.3")
<del> assertError(t, RAMInBytes, " 32 ")
<del> assertError(t, RAMInBytes, "32.3Kb")
<del> assertError(t, RAMInBytes, "32 mb")
<del> assertError(t, RAMInBytes, "32m b")
<del> assertError(t, RAMInBytes, "32bm")
<del>}
<del>
<del>func assertEquals(t *testing.T, expected, actual interface{}) {
<del> if expected != actual {
<del> t.Errorf("Expected '%v' but got '%v'", expected, actual)
<del> }
<del>}
<del>
<del>// func that maps to the parse function signatures as testing abstraction
<del>type parseFn func(string) (int64, error)
<del>
<del>// Define 'String()' for pretty-print
<del>func (fn parseFn) String() string {
<del> fnName := runtime.FuncForPC(reflect.ValueOf(fn).Pointer()).Name()
<del> return fnName[strings.LastIndex(fnName, ".")+1:]
<del>}
<del>
<del>func assertSuccessEquals(t *testing.T, expected int64, fn parseFn, arg string) {
<del> res, err := fn(arg)
<del> if err != nil || res != expected {
<del> t.Errorf("%s(\"%s\") -> expected '%d' but got '%d' with error '%v'", fn, arg, expected, res, err)
<del> }
<del>}
<del>
<del>func assertError(t *testing.T, fn parseFn, arg string) {
<del> res, err := fn(arg)
<del> if err == nil && res != -1 {
<del> t.Errorf("%s(\"%s\") -> expected error but got '%d'", fn, arg, res)
<del> }
<del>}
<ide><path>runconfig/parse.go
<ide> import (
<ide> "github.com/docker/docker/pkg/parsers"
<ide> "github.com/docker/docker/pkg/signal"
<ide> "github.com/docker/docker/pkg/stringutils"
<del> "github.com/docker/docker/pkg/units"
<ide> "github.com/docker/docker/volume"
<add> "github.com/docker/go-units"
<ide> )
<ide>
<ide> var ( | 21 |
Python | Python | fix another sorting issue in python 3 | 887c811bdec8798f8ee0948c123af1c69c5dc234 | <ide><path>glances/exports/glances_history.py
<ide> def generate_graph(self, stats):
<ide> # Find if anothers key ends with the key
<ide> # Ex: key='tx' => 'ethernet_tx'
<ide> # Add one curve per chart
<del> stats_history_filtered = [key for key in iterkeys(h) if key.endswith('_' + i['name'])]
<del> stats_history_filtered.sort()
<add> stats_history_filtered = sorted([key for key in iterkeys(h) if key.endswith('_' + i['name'])])
<ide> logger.debug("Generate graphs: %s %s" %
<ide> (p, stats_history_filtered))
<ide> if len(stats_history_filtered) > 0: | 1 |
Go | Go | fix size_test.go compilation | e59aad9cd387bf20dc0f4664afdd5c55b394cb5b | <ide><path>pkg/units/size_test.go
<ide> func TestHumanSize(t *testing.T) {
<ide> assertEquals(t, "1 MB", HumanSize(1000000))
<ide> assertEquals(t, "1.049 MB", HumanSize(1048576))
<ide> assertEquals(t, "2 MB", HumanSize(2*MB))
<del> assertEquals(t, "3.42 GB", HumanSize(int64(float64(3.42*GB))))
<del> assertEquals(t, "5.372 TB", HumanSize(int64(float64(5.372*TB))))
<del> assertEquals(t, "2.22 PB", HumanSize(int64(float64(2.22*PB))))
<add> assertEquals(t, "3.42 GB", HumanSize(float64(3.42*GB)))
<add> assertEquals(t, "5.372 TB", HumanSize(float64(5.372*TB)))
<add> assertEquals(t, "2.22 PB", HumanSize(float64(2.22*PB)))
<ide> }
<ide>
<ide> func TestFromHumanSize(t *testing.T) { | 1 |
Text | Text | specifiy the list of supported platforms | c4f57af057e1faa6d03c29c758bdb168f2870918 | <ide><path>docs/Acceptable-Formulae.md
<ide> Some formulae should not go in
<ide> additional [Interesting Taps and Forks](Interesting-Taps-and-Forks.md) and anyone can start their
<ide> own!
<ide>
<add>### Supported platforms in `homebrew/core`
<add>
<add>The formula needs to build and pass tests on the latest 3 supported macOS versions ([x86_64 and Apple Silicon/ARM](Installation.md#macos-requirements)) and on x86_64 Linux.
<add>Please have a look at the continuous integration jobs on a pull request in `homebrew/core` to see the full list of OSs.
<add>If upstream does not support one of these platforms, an exception can be made and the formula can be disabled for that platform.
<add>
<ide> ### Dupes in `homebrew/core`
<ide> We now accept stuff that comes with macOS as long as it uses `keg_only :provided_by_macos` to be keg-only by default.
<ide> | 1 |
Javascript | Javascript | add getupdatecount() to reactcomponenttreedevtool | bc241bfcfef0fb54f6b8436bcf12c402102f565e | <ide><path>src/isomorphic/ReactDebugTool.js
<ide> function resetMeasurements() {
<ide> tree[id] = {
<ide> displayName: ReactComponentTreeDevtool.getDisplayName(id),
<ide> text: ReactComponentTreeDevtool.getText(id),
<add> updateCount: ReactComponentTreeDevtool.getUpdateCount(id),
<ide> childIDs: ReactComponentTreeDevtool.getChildIDs(id),
<ide> // Text nodes don't have owners but this is close enough.
<ide> ownerID: ownerID || ReactComponentTreeDevtool.getOwnerID(parentID),
<ide><path>src/isomorphic/devtools/ReactComponentTreeDevtool.js
<ide> function updateTree(id, update) {
<ide> childIDs: [],
<ide> displayName: 'Unknown',
<ide> isMounted: false,
<add> updateCount: 0,
<ide> };
<ide> }
<ide> update(tree[id]);
<ide> var ReactComponentTreeDevtool = {
<ide> rootIDs.push(id);
<ide> },
<ide>
<add> onUpdateComponent(id) {
<add> updateTree(id, item => item.updateCount++);
<add> },
<add>
<ide> onUnmountComponent(id) {
<ide> updateTree(id, item => item.isMounted = false);
<ide> rootIDs = rootIDs.filter(rootID => rootID !== id);
<ide> var ReactComponentTreeDevtool = {
<ide> return item ? item.text : null;
<ide> },
<ide>
<add> getUpdateCount(id) {
<add> var item = tree[id];
<add> return item ? item.updateCount : 0;
<add> },
<add>
<ide> getRootIDs() {
<ide> return rootIDs;
<ide> },
<ide><path>src/isomorphic/devtools/__tests__/ReactComponentTreeDevtool-test.js
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> });
<ide> });
<ide>
<add> it('reports update counts', () => {
<add> var node = document.createElement('div');
<add>
<add> ReactDOM.render(<div className="a" />, node);
<add> var divID = ReactComponentTreeDevtool.getRootIDs()[0];
<add> expect(ReactComponentTreeDevtool.getUpdateCount(divID)).toEqual(0);
<add>
<add> ReactDOM.render(<span className="a" />, node);
<add> var spanID = ReactComponentTreeDevtool.getRootIDs()[0];
<add> expect(ReactComponentTreeDevtool.getUpdateCount(divID)).toEqual(0);
<add> expect(ReactComponentTreeDevtool.getUpdateCount(spanID)).toEqual(0);
<add>
<add> ReactDOM.render(<span className="b" />, node);
<add> expect(ReactComponentTreeDevtool.getUpdateCount(divID)).toEqual(0);
<add> expect(ReactComponentTreeDevtool.getUpdateCount(spanID)).toEqual(1);
<add>
<add> ReactDOM.render(<span className="c" />, node);
<add> expect(ReactComponentTreeDevtool.getUpdateCount(divID)).toEqual(0);
<add> expect(ReactComponentTreeDevtool.getUpdateCount(spanID)).toEqual(2);
<add>
<add> ReactDOM.unmountComponentAtNode(node);
<add> expect(ReactComponentTreeDevtool.getUpdateCount(divID)).toEqual(0);
<add> expect(ReactComponentTreeDevtool.getUpdateCount(spanID)).toEqual(2);
<add> });
<add>
<ide> it('does not report top-level wrapper as a root', () => {
<ide> var node = document.createElement('div');
<ide>
<ide><path>src/isomorphic/devtools/__tests__/ReactComponentTreeDevtool-test.native.js
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> });
<ide> });
<ide>
<add> it('reports update counts', () => {
<add> ReactNative.render(<View />, 1);
<add> var viewID = ReactComponentTreeDevtool.getRootIDs()[0];
<add> expect(ReactComponentTreeDevtool.getUpdateCount(viewID)).toEqual(0);
<add>
<add> ReactNative.render(<Image />, 1);
<add> var imageID = ReactComponentTreeDevtool.getRootIDs()[0];
<add> expect(ReactComponentTreeDevtool.getUpdateCount(viewID)).toEqual(0);
<add> expect(ReactComponentTreeDevtool.getUpdateCount(imageID)).toEqual(0);
<add>
<add> ReactNative.render(<Image />, 1);
<add> expect(ReactComponentTreeDevtool.getUpdateCount(viewID)).toEqual(0);
<add> expect(ReactComponentTreeDevtool.getUpdateCount(imageID)).toEqual(1);
<add>
<add> ReactNative.render(<Image />, 1);
<add> expect(ReactComponentTreeDevtool.getUpdateCount(viewID)).toEqual(0);
<add> expect(ReactComponentTreeDevtool.getUpdateCount(imageID)).toEqual(2);
<add>
<add> ReactNative.unmountComponentAtNode(1);
<add> expect(ReactComponentTreeDevtool.getUpdateCount(viewID)).toEqual(0);
<add> expect(ReactComponentTreeDevtool.getUpdateCount(imageID)).toEqual(2);
<add> });
<add>
<ide> it('does not report top-level wrapper as a root', () => {
<ide> ReactNative.render(<View><Image /></View>, 1);
<ide> expect(getRootDisplayNames()).toEqual(['View']); | 4 |
PHP | PHP | change 419 error title | 9b6f69be67ef03977aa2d25469b3853796529817 | <ide><path>src/Illuminate/Foundation/Exceptions/views/419.blade.php
<ide> @extends('errors::layout')
<ide>
<del>@section('title', 'Logged out')
<add>@section('title', 'Page Expired')
<ide>
<ide> @section('message')
<ide> The page has expired due to inactivity. | 1 |
Javascript | Javascript | add rwpodplayer as showcase for react native apps | c91f9ce5764482ddd32e5805e12858ae9a6ed091 | <ide><path>website/src/react-native/showcase.js
<ide> var apps = [
<ide> link: 'https://itunes.apple.com/us/app/rota-worker-shifts-on-demand/id1042111289?mt=8',
<ide> author: 'Rota',
<ide> },
<add> {
<add> name: 'RWpodPlayer - audio player for RWpod podcast',
<add> icon: 'http://a1.mzstatic.com/us/r30/Purple69/v4/a8/c0/b1/a8c0b130-e44b-742d-6458-0c89fcc15b6b/icon175x175.png',
<add> link: 'https://itunes.apple.com/us/app/rwpodplayer/id1053885042?mt=8',
<add> author: 'Alexey Vasiliev aka leopard',
<add> },
<ide> {
<ide> name: 'SG Toto 4d',
<ide> icon: 'http://a4.mzstatic.com/us/r30/Purple7/v4/d2/bc/46/d2bc4696-84d6-9681-a49f-7f660d6b04a7/icon175x175.jpeg', | 1 |
Javascript | Javascript | remove focus from previous node on click | 204d540af29536a2aee9b3758ce020df41902f00 | <ide><path>web/grab_to_pan.js
<ide> var GrabToPan = (function GrabToPanClosure() {
<ide> event.preventDefault();
<ide> event.stopPropagation();
<ide> this.document.documentElement.classList.add(this.CSS_CLASS_GRABBING);
<add>
<add> var focusedElement = document.activeElement;
<add> if (focusedElement && !focusedElement.contains(event.target)) {
<add> focusedElement.blur();
<add> }
<ide> },
<ide>
<ide> /** | 1 |
Javascript | Javascript | add tounicodemap class | 9576047f0daec1d8a6ae27fd8337b90da73eebc5 | <ide><path>src/core/evaluator.js
<ide> isNum, isStream, isString, JpegStream, Lexer, Metrics,
<ide> MurmurHash3_64, Name, Parser, Pattern, PDFImage, PDFJS, serifFonts,
<ide> stdFontMap, symbolsFonts, getTilingPatternIR, warn, Util, Promise,
<del> RefSetCache, isRef, TextRenderingMode, CMapFactory, OPS,
<del> UNSUPPORTED_FEATURES, UnsupportedManager, NormalizedUnicodes,
<add> RefSetCache, isRef, TextRenderingMode, ToUnicodeMap, CMapFactory,
<add> OPS, UNSUPPORTED_FEATURES, UnsupportedManager, NormalizedUnicodes,
<ide> IDENTITY_MATRIX, reverseIfRtl, createPromiseCapability,
<ide> getFontType */
<ide>
<ide> var PartialEvaluator = (function PartialEvaluatorClosure() {
<ide> },
<ide>
<ide> readToUnicode: function PartialEvaluator_readToUnicode(toUnicode) {
<del> var cmapObj = toUnicode;
<add> var cmap, cmapObj = toUnicode;
<ide> if (isName(cmapObj)) {
<del> return CMapFactory.create(cmapObj,
<add> cmap = CMapFactory.create(cmapObj,
<ide> { url: PDFJS.cMapUrl, packed: PDFJS.cMapPacked }, null).getMap();
<add> return new ToUnicodeMap(cmap);
<ide> } else if (isStream(cmapObj)) {
<del> var cmap = CMapFactory.create(cmapObj,
<add> cmap = CMapFactory.create(cmapObj,
<ide> { url: PDFJS.cMapUrl, packed: PDFJS.cMapPacked }, null).getMap();
<ide> // Convert UTF-16BE
<ide> // NOTE: cmap can be a sparse array, so use forEach instead of for(;;)
<ide> var PartialEvaluator = (function PartialEvaluatorClosure() {
<ide> }
<ide> cmap[i] = String.fromCharCode.apply(String, str);
<ide> });
<del> return cmap;
<add> return new ToUnicodeMap(cmap);
<ide> }
<ide> return null;
<ide> },
<ide><path>src/core/fonts.js
<ide> var Glyph = (function GlyphClosure() {
<ide> return Glyph;
<ide> })();
<ide>
<add>var ToUnicodeMap = (function ToUnicodeMapClosure() {
<add> function ToUnicodeMap(cmap) {
<add> // The elements of this._map can be integers or strings, depending on how
<add> // |cmap| was created.
<add> this._map = cmap;
<add> }
<add>
<add> ToUnicodeMap.prototype = {
<add> get length() {
<add> return this._map.length;
<add> },
<add>
<add> forEach: function(callback) {
<add> for (var charCode in this._map) {
<add> callback(charCode, this._map[charCode].charCodeAt(0));
<add> }
<add> },
<add>
<add> get: function(i) {
<add> return this._map[i];
<add> },
<add>
<add> charCodeOf: function(v) {
<add> return this._map.indexOf(v);
<add> }
<add> };
<add>
<add> return ToUnicodeMap;
<add>})();
<add>
<ide> /**
<ide> * 'Font' is the class the outside world should use, it encapsulate all the font
<ide> * decoding logics whatever type it is (assuming the font type is supported).
<ide> var Font = (function FontClosure() {
<ide> map[+code] = GlyphMapForStandardFonts[code];
<ide> }
<ide> this.toFontChar = map;
<del> this.toUnicode = map;
<add> this.toUnicode = new ToUnicodeMap(map);
<ide> } else if (/Symbol/i.test(fontName)) {
<ide> var symbols = Encodings.SymbolSetEncoding;
<ide> for (charCode in symbols) {
<ide> var Font = (function FontClosure() {
<ide> }
<ide> } else {
<ide> var unicodeCharCode, notCidFont = (type.indexOf('CIDFontType') === -1);
<del> for (charCode in this.toUnicode) {
<del> unicodeCharCode = this.toUnicode[charCode].charCodeAt(0);
<add> this.toUnicode.forEach(function(charCode, unicodeCharCode) {
<ide> if (notCidFont) {
<ide> glyphName = (properties.differences[charCode] ||
<ide> properties.defaultEncoding[charCode]);
<ide> unicodeCharCode = (GlyphsUnicode[glyphName] || unicodeCharCode);
<ide> }
<ide> this.toFontChar[charCode] = unicodeCharCode;
<del> }
<add> }.bind(this));
<ide> }
<ide> this.loadedName = fontName.split('-')[0];
<ide> this.loading = false;
<ide> var Font = (function FontClosure() {
<ide> // First try to map the value to a unicode position if a non identity map
<ide> // was created.
<ide> if (!isIdentityUnicode) {
<del> if (toUnicode[originalCharCode] !== undefined) {
<del> var unicode = toUnicode[fontCharCode];
<add> if (toUnicode.get(originalCharCode) !== undefined) {
<add> var unicode = toUnicode.get(fontCharCode);
<ide> // TODO: Try to map ligatures to the correct spot.
<ide> if (unicode.length === 1) {
<ide> fontCharCode = unicode.charCodeAt(0);
<ide> var Font = (function FontClosure() {
<ide>
<ide> var dupFirstEntry = false;
<ide> if (properties.type === 'CIDFontType2' && properties.toUnicode &&
<del> properties.toUnicode[0] > '\u0000') {
<add> properties.toUnicode.get(0) > '\u0000') {
<ide> // oracle's defect (see 3427), duplicating first entry
<ide> dupFirstEntry = true;
<ide> numGlyphs++;
<ide> var Font = (function FontClosure() {
<ide> }
<ide> toUnicode[charcode] = String.fromCharCode(GlyphsUnicode[glyphName]);
<ide> }
<del> map.toUnicode = toUnicode;
<add> map.toUnicode = new ToUnicodeMap(toUnicode);
<ide> return map;
<ide> }
<ide> // If the font is a composite font that uses one of the predefined CMaps
<ide> var Font = (function FontClosure() {
<ide> ucs2.charCodeAt(1));
<ide> }
<ide> });
<del> map.toUnicode = toUnicode;
<add> map.toUnicode = new ToUnicodeMap(toUnicode);
<ide> return map;
<ide> }
<ide>
<ide> var Font = (function FontClosure() {
<ide> toUnicode[i] = String.fromCharCode(i);
<ide> }
<ide> map.isIdentity = true;
<del> map.toUnicode = toUnicode;
<add> map.toUnicode = new ToUnicodeMap(toUnicode);
<ide> return map;
<ide> },
<ide>
<ide> var Font = (function FontClosure() {
<ide> }
<ide> // ... via toUnicode map
<ide> if (!charcode && 'toUnicode' in this) {
<del> charcode = this.toUnicode.indexOf(glyphUnicode);
<add> charcode = this.toUnicode.charCodeOf(glyphUnicode);
<ide> }
<ide> // setting it to unicode if negative or undefined
<ide> if (charcode <= 0) {
<ide> var Font = (function FontClosure() {
<ide> width = isNum(width) ? width : this.defaultWidth;
<ide> var vmetric = this.vmetrics && this.vmetrics[widthCode];
<ide>
<del> var unicode = this.toUnicode[charcode] || charcode;
<add> var unicode = this.toUnicode.get(charcode) || charcode;
<ide> if (typeof unicode === 'number') {
<ide> unicode = String.fromCharCode(unicode);
<ide> } | 2 |
Python | Python | add a builderror hook to url_for, #456 | bb31188ec3882e9a6c6035b7a65ca257d424e31a | <ide><path>flask/app.py
<ide> def __init__(self, import_name, static_path=None, static_url_path=None,
<ide> #: decorator.
<ide> self.error_handler_spec = {None: self._error_handlers}
<ide>
<add> #: If not `None`, this function is called when :meth:`url_for` raises
<add> #: :exc:`~werkzeug.routing.BuildError`, with the call signature::
<add> #:
<add> #: self.build_error_handler(error, endpoint, **values)
<add> #:
<add> #: Here, `error` is the instance of `BuildError`, and `endpoint` and
<add> #: `**values` are the arguments passed into :meth:`url_for`.
<add> #:
<add> #: .. versionadded:: 0.9
<add> self.build_error_handler = None
<add>
<ide> #: A dictionary with lists of functions that should be called at the
<ide> #: beginning of the request. The key of the dictionary is the name of
<ide> #: the blueprint this function is active for, `None` for all requests.
<ide> def inject_url_defaults(self, endpoint, values):
<ide> for func in funcs:
<ide> func(endpoint, values)
<ide>
<add> def handle_build_error(self, error, endpoint, **values):
<add> """Handle :class:`~werkzeug.routing.BuildError` on :meth:`url_for`.
<add>
<add> Calls :attr:`build_error_handler` if it is not `None`.
<add> """
<add> if self.build_error_handler is None:
<add> raise error
<add> return self.build_error_handler(error, endpoint, **values)
<add>
<ide> def preprocess_request(self):
<ide> """Called before the actual request dispatching and will
<ide> call every as :meth:`before_request` decorated function.
<ide><path>flask/helpers.py
<ide> from time import time
<ide> from zlib import adler32
<ide> from threading import RLock
<add>from werkzeug.routing import BuildError
<ide> from werkzeug.urls import url_quote
<ide>
<ide> # try to load the best simplejson implementation available. If JSON
<ide> def url_for(endpoint, **values):
<ide> .. versionadded:: 0.9
<ide> The `_anchor` and `_method` parameters were added.
<ide>
<add> .. versionadded:: 0.9
<add> Calls :meth:`Flask.handle_build_error` on
<add> :exc:`~werkzeug.routing.BuildError`.
<add>
<ide> :param endpoint: the endpoint of the URL (name of the function)
<ide> :param values: the variable arguments of the URL rule
<ide> :param _external: if set to `True`, an absolute URL is generated.
<ide> def url_for(endpoint, **values):
<ide> anchor = values.pop('_anchor', None)
<ide> method = values.pop('_method', None)
<ide> appctx.app.inject_url_defaults(endpoint, values)
<add> try:
<add> rv = url_adapter.build(endpoint, values, method=method,
<add> force_external=external)
<add> except BuildError, error:
<add> values['_external'] = external
<add> values['_anchor'] = anchor
<add> values['_method'] = method
<add> return appctx.app.handle_build_error(error, endpoint, **values)
<add>
<ide> rv = url_adapter.build(endpoint, values, method=method,
<ide> force_external=external)
<ide> if anchor is not None:
<ide><path>flask/testsuite/basic.py
<ide> from flask.testsuite import FlaskTestCase, emits_module_deprecation_warning
<ide> from werkzeug.exceptions import BadRequest, NotFound
<ide> from werkzeug.http import parse_date
<add>from werkzeug.routing import BuildError
<ide>
<ide>
<ide> class BasicFunctionalityTestCase(FlaskTestCase):
<ide> def hello():
<ide> self.assert_equal(flask.url_for('hello', name='test x', _external=True),
<ide> 'http://localhost/hello/test%20x')
<ide>
<add> def test_build_error_handler(self):
<add> app = flask.Flask(__name__)
<add> with app.test_request_context():
<add> self.assertRaises(BuildError, flask.url_for, 'spam')
<add> def handler(error, endpoint, **values):
<add> # Just a test.
<add> return '/test_handler/'
<add> app.build_error_handler = handler
<add> with app.test_request_context():
<add> self.assert_equal(flask.url_for('spam'), '/test_handler/')
<add>
<ide> def test_custom_converters(self):
<ide> from werkzeug.routing import BaseConverter
<ide> class ListConverter(BaseConverter): | 3 |
Javascript | Javascript | use faster check for $$ prefix | cb29632a5802e930262919b3db64ca4806c5cfc7 | <ide><path>src/Angular.js
<ide> function shallowCopy(src, dst) {
<ide> for(var key in src) {
<ide> // shallowCopy is only ever called by $compile nodeLinkFn, which has control over src
<ide> // so we don't need to worry about using our custom hasOwnProperty here
<del> if (src.hasOwnProperty(key) && key.substr(0, 2) !== '$$') {
<add> if (src.hasOwnProperty(key) && key.charAt(0) !== '$' && key.charAt(1) !== '$') {
<ide> dst[key] = src[key];
<ide> }
<ide> }
<ide><path>src/ngResource/resource.js
<ide> function shallowClearAndCopy(src, dst) {
<ide> });
<ide>
<ide> for (var key in src) {
<del> if (src.hasOwnProperty(key) && key.substr(0, 2) !== '$$') {
<add> if (src.hasOwnProperty(key) && key.charAt(0) !== '$' && key.charAt(1) !== '$') {
<ide> dst[key] = src[key];
<ide> }
<ide> } | 2 |
Text | Text | update security section | 8e705d29fbcba39b7dbf5ff018a84f3fb59c3134 | <ide><path>README.md
<ide> If you're confident it's a new bug and have confirmed that someone else is facin
<ide>
<ide> ### Reporting Security Issues and Responsible Disclosure
<ide>
<del>[Our security policy is available here.](https://contribute.freecodecamp.org/#/security)
<add>We appreciate responsible disclosure of vulnerabilities that might impact the integrity of our platforms and users.
<add>
<add>> #### [Read our security policy and follow these steps to report a vulnerability](https://contribute.freecodecamp.org/#/security).
<ide>
<ide> ### Contributing
<ide> | 1 |
Mixed | Python | add sequential.pop() method | b6a776b24278bebaec721c3cfead33bfc01e32cf | <ide><path>docs/templates/getting-started/faq.md
<ide> - [How can I record the training / validation loss / accuracy at each epoch?](#how-can-i-record-the-training-validation-loss-accuracy-at-each-epoch)
<ide> - [How can I "freeze" layers?](#how-can-i-freeze-keras-layers)
<ide> - [How can I use stateful RNNs?](#how-can-i-use-stateful-rnns)
<add>- [How can I remove a layer from a Sequential model?](#how-can-i-remove-a-layer-from-a-sequential-model)
<ide>
<ide> ---
<ide>
<ide> model.layers[0].reset_states()
<ide>
<ide> Notes that the methods `predict`, `fit`, `train_on_batch`, `predict_classes`, etc. will *all* update the states of the stateful layers in a model. This allows you to do not only stateful training, but also stateful prediction.
<ide>
<add>
<add>### How can I remove a layer from a Sequential model?
<add>
<add>You can remove the last added layer in a Sequential model by calling `.pop()`:
<add>
<add>```python
<add>model = Sequential()
<add>model.add(Dense(32, activation='relu', input_dim=784))
<add>model.add(Dense(32, activation='relu'))
<add>
<add>print(len(model.layers)) # "2"
<add>
<add>model.pop()
<add>print(len(model.layers)) # "1"
<add>```
<ide><path>keras/models.py
<ide> def add(self, layer):
<ide> self.built = False
<ide> self._flattened_layers = None
<ide>
<add> def pop(self):
<add> '''Removes the last layer in the model.
<add> '''
<add> if not self.layers:
<add> raise Exception('There are no layers in the model.')
<add>
<add> self.layers.pop()
<add> if not self.layers:
<add> self.outputs = []
<add> self.inbound_nodes = []
<add> self.outbound_nodes = []
<add> else:
<add> self.layers[-1].outbound_nodes = []
<add> self.outputs = [self.layers[-1].output]
<add> self.built = False
<add>
<ide> def call(self, x, mask=None):
<ide> if not self.built:
<ide> self.build()
<ide><path>tests/keras/test_sequential_model.py
<ide> def data_generator(train):
<ide> model.add(Dense(nb_hidden, input_shape=(input_dim,)))
<ide> model.add(Activation('relu'))
<ide> model.add(Dense(nb_class))
<add> model.pop()
<add> model.add(Dense(nb_class))
<ide> model.add(Activation('softmax'))
<ide> model.compile(loss='categorical_crossentropy', optimizer='rmsprop')
<ide> | 3 |
Ruby | Ruby | add backtrace on failure | 6eb80c67a43a908883ceb9303806c910c48b04d5 | <ide><path>Library/Homebrew/cmd/install.rb
<ide> def install
<ide> # Need to rescue before `FormulaUnavailableError` (superclass of this)
<ide> # is handled, as searching for a formula doesn't make sense here (the
<ide> # formula was found, but there's a problem with its implementation).
<add> $stderr.puts e.backtrace if Homebrew::EnvConfig.developer?
<ide> ofail e.message
<ide> rescue FormulaUnavailableError => e
<ide> if e.name == "updog"
<ide><path>Library/Homebrew/formulary.rb
<ide> def self.load_formula(name, path, contents, namespace)
<ide> begin
<ide> mod.module_eval(contents, path)
<ide> rescue NameError, ArgumentError, ScriptError => e
<add> $stderr.puts e.backtrace if Homebrew::EnvConfig.developer?
<ide> raise FormulaUnreadableError.new(name, e)
<ide> end
<ide> class_name = class_s(name) | 2 |
Go | Go | replace newclient() with newclientt() | 2cb7b73a1bdbf2e7ea6da7d0c050b303c2c4f5dc | <ide><path>integration-cli/daemon/daemon_swarm.go
<ide> func (d *Daemon) CheckServiceUpdateState(service string) func(*check.C) (interfa
<ide> // CheckPluginRunning returns the runtime state of the plugin
<ide> func (d *Daemon) CheckPluginRunning(plugin string) func(c *check.C) (interface{}, check.CommentInterface) {
<ide> return func(c *check.C) (interface{}, check.CommentInterface) {
<del> apiclient, err := d.NewClient()
<del> assert.NilError(c, err)
<add> apiclient := d.NewClientT(c)
<ide> resp, _, err := apiclient.PluginInspectWithRaw(context.Background(), plugin)
<ide> if client.IsErrNotFound(err) {
<ide> return false, check.Commentf("%v", err)
<ide> func (d *Daemon) CheckPluginRunning(plugin string) func(c *check.C) (interface{}
<ide> // CheckPluginImage returns the runtime state of the plugin
<ide> func (d *Daemon) CheckPluginImage(plugin string) func(c *check.C) (interface{}, check.CommentInterface) {
<ide> return func(c *check.C) (interface{}, check.CommentInterface) {
<del> apiclient, err := d.NewClient()
<del> assert.NilError(c, err)
<add> apiclient := d.NewClientT(c)
<ide> resp, _, err := apiclient.PluginInspectWithRaw(context.Background(), plugin)
<ide> if client.IsErrNotFound(err) {
<ide> return false, check.Commentf("%v", err)
<ide> func (d *Daemon) CheckServiceTasks(service string) func(*check.C) (interface{},
<ide>
<ide> // CheckRunningTaskNetworks returns the number of times each network is referenced from a task.
<ide> func (d *Daemon) CheckRunningTaskNetworks(c *check.C) (interface{}, check.CommentInterface) {
<del> cli, err := d.NewClient()
<del> c.Assert(err, checker.IsNil)
<add> cli := d.NewClientT(c)
<ide> defer cli.Close()
<ide>
<ide> filterArgs := filters.NewArgs()
<ide> func (d *Daemon) CheckRunningTaskNetworks(c *check.C) (interface{}, check.Commen
<ide>
<ide> // CheckRunningTaskImages returns the times each image is running as a task.
<ide> func (d *Daemon) CheckRunningTaskImages(c *check.C) (interface{}, check.CommentInterface) {
<del> cli, err := d.NewClient()
<del> c.Assert(err, checker.IsNil)
<add> cli := d.NewClientT(c)
<ide> defer cli.Close()
<ide>
<ide> filterArgs := filters.NewArgs()
<ide> func (d *Daemon) CheckControlAvailable(c *check.C) (interface{}, check.CommentIn
<ide>
<ide> // CheckLeader returns whether there is a leader on the swarm or not
<ide> func (d *Daemon) CheckLeader(c *check.C) (interface{}, check.CommentInterface) {
<del> cli, err := d.NewClient()
<del> c.Assert(err, checker.IsNil)
<add> cli := d.NewClientT(c)
<ide> defer cli.Close()
<ide>
<ide> errList := check.Commentf("could not get node list")
<ide><path>integration-cli/docker_api_swarm_service_test.go
<ide> func (s *DockerSwarmSuite) TestAPISwarmServicesCreate(c *check.C) {
<ide> id := d.CreateService(c, simpleTestService, setInstances(instances))
<ide> waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, instances)
<ide>
<del> cli, err := d.NewClient()
<del> c.Assert(err, checker.IsNil)
<del> defer cli.Close()
<add> client := d.NewClientT(c)
<add> defer client.Close()
<ide>
<ide> options := types.ServiceInspectOptions{InsertDefaults: true}
<ide>
<ide> // insertDefaults inserts UpdateConfig when service is fetched by ID
<del> resp, _, err := cli.ServiceInspectWithRaw(context.Background(), id, options)
<add> resp, _, err := client.ServiceInspectWithRaw(context.Background(), id, options)
<ide> out := fmt.Sprintf("%+v", resp)
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(out, checker.Contains, "UpdateConfig")
<ide>
<ide> // insertDefaults inserts UpdateConfig when service is fetched by ID
<del> resp, _, err = cli.ServiceInspectWithRaw(context.Background(), "top", options)
<add> resp, _, err = client.ServiceInspectWithRaw(context.Background(), "top", options)
<ide> out = fmt.Sprintf("%+v", resp)
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(string(out), checker.Contains, "UpdateConfig")
<ide><path>integration-cli/docker_api_swarm_test.go
<ide> func (s *DockerSwarmSuite) TestAPISwarmRaftQuorum(c *check.C) {
<ide> var service swarm.Service
<ide> simpleTestService(&service)
<ide> service.Spec.Name = "top2"
<del> cli, err := d1.NewClient()
<del> c.Assert(err, checker.IsNil)
<add> cli := d1.NewClientT(c)
<ide> defer cli.Close()
<ide>
<ide> // d1 will eventually step down from leader because there is no longer an active quorum, wait for that to happen
<ide> waitAndAssert(c, defaultReconciliationTimeout, func(c *check.C) (interface{}, check.CommentInterface) {
<del> _, err = cli.ServiceCreate(context.Background(), service.Spec, types.ServiceCreateOptions{})
<add> _, err := cli.ServiceCreate(context.Background(), service.Spec, types.ServiceCreateOptions{})
<ide> return err.Error(), nil
<ide> }, checker.Contains, "Make sure more than half of the managers are online.")
<ide>
<ide> func (s *DockerSwarmSuite) TestAPISwarmServicesUpdateWithName(c *check.C) {
<ide> instances = 5
<ide>
<ide> setInstances(instances)(service)
<del> cli, err := d.NewClient()
<del> c.Assert(err, checker.IsNil)
<add> cli := d.NewClientT(c)
<ide> defer cli.Close()
<del> _, err = cli.ServiceUpdate(context.Background(), service.Spec.Name, service.Version, service.Spec, types.ServiceUpdateOptions{})
<add> _, err := cli.ServiceUpdate(context.Background(), service.Spec.Name, service.Version, service.Spec, types.ServiceUpdateOptions{})
<ide> c.Assert(err, checker.IsNil)
<ide> waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, instances)
<ide> }
<ide> func (s *DockerSwarmSuite) TestAPISwarmErrorHandling(c *check.C) {
<ide> // This test makes sure the fixes correctly output scopes instead.
<ide> func (s *DockerSwarmSuite) TestAPIDuplicateNetworks(c *check.C) {
<ide> d := s.AddDaemon(c, true, true)
<del> cli, err := d.NewClient()
<del> c.Assert(err, checker.IsNil)
<add> cli := d.NewClientT(c)
<ide> defer cli.Close()
<ide>
<ide> name := "foo"
<ide> func (s *DockerSwarmSuite) TestAPINetworkInspectWithScope(c *check.C) {
<ide>
<ide> name := "test-scoped-network"
<ide> ctx := context.Background()
<del> apiclient, err := d.NewClient()
<del> assert.NilError(c, err)
<add> apiclient := d.NewClientT(c)
<ide>
<ide> resp, err := apiclient.NetworkCreate(ctx, name, types.NetworkCreate{Driver: "overlay"})
<ide> assert.NilError(c, err)
<ide><path>integration-cli/docker_cli_swarm_test.go
<ide> func (s *DockerSwarmSuite) TestOverlayAttachableOnSwarmLeave(c *check.C) {
<ide> c.Assert(err, checker.IsNil, check.Commentf("%s", out))
<ide>
<ide> // Leave the swarm
<del> err = d.SwarmLeave(true)
<del> c.Assert(err, checker.IsNil)
<add> c.Assert(d.SwarmLeave(true), checker.IsNil)
<ide>
<ide> // Check the container is disconnected
<ide> out, err = d.Cmd("inspect", "c1", "--format", "{{.NetworkSettings.Networks."+nwName+"}}")
<ide> func (s *DockerSwarmSuite) TestNetworkInspectWithDuplicateNames(c *check.C) {
<ide> Driver: "bridge",
<ide> }
<ide>
<del> cli, err := d.NewClient()
<del> c.Assert(err, checker.IsNil)
<add> cli := d.NewClientT(c)
<ide> defer cli.Close()
<ide>
<ide> n1, err := cli.NetworkCreate(context.Background(), name, options)
<ide><path>integration/container/daemon_linux_test.go
<ide> func TestContainerStartOnDaemonRestart(t *testing.T) {
<ide> d.StartWithBusybox(t, "--iptables=false")
<ide> defer d.Stop(t)
<ide>
<del> client, err := d.NewClient()
<del> assert.Check(t, err, "error creating client")
<add> c := d.NewClientT(t)
<ide>
<ide> ctx := context.Background()
<ide>
<del> cID := container.Create(t, ctx, client)
<del> defer client.ContainerRemove(ctx, cID, types.ContainerRemoveOptions{Force: true})
<add> cID := container.Create(t, ctx, c)
<add> defer c.ContainerRemove(ctx, cID, types.ContainerRemoveOptions{Force: true})
<ide>
<del> err = client.ContainerStart(ctx, cID, types.ContainerStartOptions{})
<add> err := c.ContainerStart(ctx, cID, types.ContainerStartOptions{})
<ide> assert.Check(t, err, "error starting test container")
<ide>
<del> inspect, err := client.ContainerInspect(ctx, cID)
<add> inspect, err := c.ContainerInspect(ctx, cID)
<ide> assert.Check(t, err, "error getting inspect data")
<ide>
<ide> ppid := getContainerdShimPid(t, inspect)
<ide> func TestContainerStartOnDaemonRestart(t *testing.T) {
<ide>
<ide> d.Start(t, "--iptables=false")
<ide>
<del> err = client.ContainerStart(ctx, cID, types.ContainerStartOptions{})
<add> err = c.ContainerStart(ctx, cID, types.ContainerStartOptions{})
<ide> assert.Check(t, err, "failed to start test container")
<ide> }
<ide>
<ide><path>integration/container/export_test.go
<ide> func TestExportContainerAfterDaemonRestart(t *testing.T) {
<ide> skip.If(t, testEnv.IsRemoteDaemon())
<ide>
<ide> d := daemon.New(t)
<del> client, err := d.NewClient()
<del> assert.NilError(t, err)
<add> c := d.NewClientT(t)
<ide>
<ide> d.StartWithBusybox(t)
<ide> defer d.Stop(t)
<ide>
<ide> ctx := context.Background()
<del> ctrID := container.Create(t, ctx, client)
<add> ctrID := container.Create(t, ctx, c)
<ide>
<ide> d.Restart(t)
<ide>
<del> _, err = client.ContainerExport(ctx, ctrID)
<add> _, err := c.ContainerExport(ctx, ctrID)
<ide> assert.NilError(t, err)
<ide> }
<ide><path>integration/container/ipcmode_test.go
<ide> func testDaemonIpcPrivateShareable(t *testing.T, mustBeShared bool, arg ...strin
<ide> d.StartWithBusybox(t, arg...)
<ide> defer d.Stop(t)
<ide>
<del> client, err := d.NewClient()
<del> assert.Check(t, err, "error creating client")
<add> c := d.NewClientT(t)
<ide>
<ide> cfg := containertypes.Config{
<ide> Image: "busybox",
<ide> Cmd: []string{"top"},
<ide> }
<ide> ctx := context.Background()
<ide>
<del> resp, err := client.ContainerCreate(ctx, &cfg, &containertypes.HostConfig{}, nil, "")
<add> resp, err := c.ContainerCreate(ctx, &cfg, &containertypes.HostConfig{}, nil, "")
<ide> assert.NilError(t, err)
<ide> assert.Check(t, is.Equal(len(resp.Warnings), 0))
<ide>
<del> err = client.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{})
<add> err = c.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{})
<ide> assert.NilError(t, err)
<ide>
<ide> // get major:minor pair for /dev/shm from container's /proc/self/mountinfo
<ide> cmd := "awk '($5 == \"/dev/shm\") {printf $3}' /proc/self/mountinfo"
<del> result, err := container.Exec(ctx, client, resp.ID, []string{"sh", "-c", cmd})
<add> result, err := container.Exec(ctx, c, resp.ID, []string{"sh", "-c", cmd})
<ide> assert.NilError(t, err)
<ide> mm := result.Combined()
<ide> assert.Check(t, is.Equal(true, regexp.MustCompile("^[0-9]+:[0-9]+$").MatchString(mm)))
<ide><path>integration/container/restart_test.go
<ide> func TestDaemonRestartKillContainers(t *testing.T) {
<ide> xStart bool
<ide> }
<ide>
<del> for _, c := range []testCase{
<add> for _, tc := range []testCase{
<ide> {
<ide> desc: "container without restart policy",
<ide> config: &container.Config{Image: "busybox", Cmd: []string{"top"}},
<ide> func TestDaemonRestartKillContainers(t *testing.T) {
<ide> d.Stop(t)
<ide> },
<ide> } {
<del> t.Run(fmt.Sprintf("live-restore=%v/%s/%s", liveRestoreEnabled, c.desc, fnName), func(t *testing.T) {
<del> c := c
<add> t.Run(fmt.Sprintf("live-restore=%v/%s/%s", liveRestoreEnabled, tc.desc, fnName), func(t *testing.T) {
<add> c := tc
<ide> liveRestoreEnabled := liveRestoreEnabled
<ide> stopDaemon := stopDaemon
<ide>
<ide> t.Parallel()
<ide>
<ide> d := daemon.New(t)
<del> client, err := d.NewClient()
<del> assert.NilError(t, err)
<add> client := d.NewClientT(t)
<ide>
<ide> args := []string{"--iptables=false"}
<ide> if liveRestoreEnabled {
<ide><path>integration/network/ipvlan/ipvlan_test.go
<ide> func TestDockerNetworkIpvlanPersistance(t *testing.T) {
<ide> n.CreateMasterDummy(t, master)
<ide> defer n.DeleteInterface(t, master)
<ide>
<del> client, err := d.NewClient()
<del> assert.NilError(t, err)
<add> c := d.NewClientT(t)
<ide>
<ide> // create a network specifying the desired sub-interface name
<ide> netName := "di-persist"
<del> net.CreateNoError(t, context.Background(), client, netName,
<add> net.CreateNoError(t, context.Background(), c, netName,
<ide> net.WithIPvlan("di-dummy0.70", ""),
<ide> )
<ide>
<del> assert.Check(t, n.IsNetworkAvailable(client, netName))
<add> assert.Check(t, n.IsNetworkAvailable(c, netName))
<ide> // Restart docker daemon to test the config has persisted to disk
<ide> d.Restart(t)
<del> assert.Check(t, n.IsNetworkAvailable(client, netName))
<add> assert.Check(t, n.IsNetworkAvailable(c, netName))
<ide> }
<ide>
<ide> func TestDockerNetworkIpvlan(t *testing.T) {
<ide> func TestDockerNetworkIpvlan(t *testing.T) {
<ide> } {
<ide> d := daemon.New(t, daemon.WithExperimental)
<ide> d.StartWithBusybox(t)
<add> c := d.NewClientT(t)
<ide>
<del> client, err := d.NewClient()
<del> assert.NilError(t, err)
<del>
<del> t.Run(tc.name, tc.test(client))
<add> t.Run(tc.name, tc.test(c))
<ide>
<ide> d.Stop(t)
<ide> // FIXME(vdemeester) clean network
<ide><path>integration/network/macvlan/macvlan_test.go
<ide> func TestDockerNetworkMacvlanPersistance(t *testing.T) {
<ide> n.CreateMasterDummy(t, master)
<ide> defer n.DeleteInterface(t, master)
<ide>
<del> client, err := d.NewClient()
<del> assert.NilError(t, err)
<add> c := d.NewClientT(t)
<ide>
<ide> netName := "dm-persist"
<del> net.CreateNoError(t, context.Background(), client, netName,
<add> net.CreateNoError(t, context.Background(), c, netName,
<ide> net.WithMacvlan("dm-dummy0.60"),
<ide> )
<del> assert.Check(t, n.IsNetworkAvailable(client, netName))
<add> assert.Check(t, n.IsNetworkAvailable(c, netName))
<ide> d.Restart(t)
<del> assert.Check(t, n.IsNetworkAvailable(client, netName))
<add> assert.Check(t, n.IsNetworkAvailable(c, netName))
<ide> }
<ide>
<ide> func TestDockerNetworkMacvlan(t *testing.T) {
<ide> func TestDockerNetworkMacvlan(t *testing.T) {
<ide> } {
<ide> d := daemon.New(t)
<ide> d.StartWithBusybox(t)
<add> c := d.NewClientT(t)
<ide>
<del> client, err := d.NewClient()
<del> assert.NilError(t, err)
<del>
<del> t.Run(tc.name, tc.test(client))
<add> t.Run(tc.name, tc.test(c))
<ide>
<ide> d.Stop(t)
<ide> // FIXME(vdemeester) clean network
<ide><path>integration/network/network_test.go
<ide> func TestRunContainerWithBridgeNone(t *testing.T) {
<ide> d.StartWithBusybox(t, "-b", "none")
<ide> defer d.Stop(t)
<ide>
<del> client, err := d.NewClient()
<del> assert.Check(t, err, "error creating client")
<del>
<add> c := d.NewClientT(t)
<ide> ctx := context.Background()
<del> id1 := container.Run(t, ctx, client)
<del> defer client.ContainerRemove(ctx, id1, types.ContainerRemoveOptions{Force: true})
<ide>
<del> result, err := container.Exec(ctx, client, id1, []string{"ip", "l"})
<add> id1 := container.Run(t, ctx, c)
<add> defer c.ContainerRemove(ctx, id1, types.ContainerRemoveOptions{Force: true})
<add>
<add> result, err := container.Exec(ctx, c, id1, []string{"ip", "l"})
<ide> assert.NilError(t, err)
<ide> assert.Check(t, is.Equal(false, strings.Contains(result.Combined(), "eth0")), "There shouldn't be eth0 in container in default(bridge) mode when bridge network is disabled")
<ide>
<del> id2 := container.Run(t, ctx, client, container.WithNetworkMode("bridge"))
<del> defer client.ContainerRemove(ctx, id2, types.ContainerRemoveOptions{Force: true})
<add> id2 := container.Run(t, ctx, c, container.WithNetworkMode("bridge"))
<add> defer c.ContainerRemove(ctx, id2, types.ContainerRemoveOptions{Force: true})
<ide>
<del> result, err = container.Exec(ctx, client, id2, []string{"ip", "l"})
<add> result, err = container.Exec(ctx, c, id2, []string{"ip", "l"})
<ide> assert.NilError(t, err)
<ide> assert.Check(t, is.Equal(false, strings.Contains(result.Combined(), "eth0")), "There shouldn't be eth0 in container in bridge mode when bridge network is disabled")
<ide>
<ide> func TestRunContainerWithBridgeNone(t *testing.T) {
<ide> err = cmd.Run()
<ide> assert.NilError(t, err, "Failed to get current process network namespace: %+v", err)
<ide>
<del> id3 := container.Run(t, ctx, client, container.WithNetworkMode("host"))
<del> defer client.ContainerRemove(ctx, id3, types.ContainerRemoveOptions{Force: true})
<add> id3 := container.Run(t, ctx, c, container.WithNetworkMode("host"))
<add> defer c.ContainerRemove(ctx, id3, types.ContainerRemoveOptions{Force: true})
<ide>
<del> result, err = container.Exec(ctx, client, id3, []string{"sh", "-c", nsCommand})
<add> result, err = container.Exec(ctx, c, id3, []string{"sh", "-c", nsCommand})
<ide> assert.NilError(t, err)
<ide> assert.Check(t, is.Equal(stdout.String(), result.Combined()), "The network namspace of container should be the same with host when --net=host and bridge network is disabled")
<ide> }
<ide><path>integration/network/service_test.go
<ide> func TestDaemonRestartWithLiveRestore(t *testing.T) {
<ide> d := daemon.New(t)
<ide> defer d.Stop(t)
<ide> d.Start(t)
<del> d.Restart(t, "--live-restore=true",
<add> d.Restart(t,
<add> "--live-restore=true",
<ide> "--default-address-pool", "base=175.30.0.0/16,size=16",
<del> "--default-address-pool", "base=175.33.0.0/16,size=24")
<add> "--default-address-pool", "base=175.33.0.0/16,size=24",
<add> )
<ide>
<ide> // Verify bridge network's subnet
<del> cli, err := d.NewClient()
<del> assert.Assert(t, err)
<del> defer cli.Close()
<del> out, err := cli.NetworkInspect(context.Background(), "bridge", types.NetworkInspectOptions{})
<add> c := d.NewClientT(t)
<add> defer c.Close()
<add> out, err := c.NetworkInspect(context.Background(), "bridge", types.NetworkInspectOptions{})
<ide> assert.NilError(t, err)
<ide> // Make sure docker0 doesn't get override with new IP in live restore case
<ide> assert.Equal(t, out.IPAM.Config[0].Subnet, "172.18.0.0/16")
<ide> func TestDaemonDefaultNetworkPools(t *testing.T) {
<ide> defer d.Stop(t)
<ide> d.Start(t,
<ide> "--default-address-pool", "base=175.30.0.0/16,size=16",
<del> "--default-address-pool", "base=175.33.0.0/16,size=24")
<add> "--default-address-pool", "base=175.33.0.0/16,size=24",
<add> )
<add>
<add> c := d.NewClientT(t)
<add> defer c.Close()
<ide>
<ide> // Verify bridge network's subnet
<del> cli, err := d.NewClient()
<del> assert.Assert(t, err)
<del> defer cli.Close()
<del> out, err := cli.NetworkInspect(context.Background(), "bridge", types.NetworkInspectOptions{})
<add> out, err := c.NetworkInspect(context.Background(), "bridge", types.NetworkInspectOptions{})
<ide> assert.NilError(t, err)
<ide> assert.Equal(t, out.IPAM.Config[0].Subnet, "175.30.0.0/16")
<ide>
<ide> // Create a bridge network and verify its subnet is the second default pool
<ide> name := "elango" + t.Name()
<del> network.CreateNoError(t, context.Background(), cli, name,
<add> network.CreateNoError(t, context.Background(), c, name,
<ide> network.WithDriver("bridge"),
<ide> )
<del> out, err = cli.NetworkInspect(context.Background(), name, types.NetworkInspectOptions{})
<add> out, err = c.NetworkInspect(context.Background(), name, types.NetworkInspectOptions{})
<ide> assert.NilError(t, err)
<ide> assert.Equal(t, out.IPAM.Config[0].Subnet, "175.33.0.0/24")
<ide>
<ide> // Create a bridge network and verify its subnet is the third default pool
<ide> name = "saanvi" + t.Name()
<del> network.CreateNoError(t, context.Background(), cli, name,
<add> network.CreateNoError(t, context.Background(), c, name,
<ide> network.WithDriver("bridge"),
<ide> )
<del> out, err = cli.NetworkInspect(context.Background(), name, types.NetworkInspectOptions{})
<add> out, err = c.NetworkInspect(context.Background(), name, types.NetworkInspectOptions{})
<ide> assert.NilError(t, err)
<ide> assert.Equal(t, out.IPAM.Config[0].Subnet, "175.33.1.0/24")
<ide> delInterface(t, defaultNetworkBridge)
<ide> func TestDaemonRestartWithExistingNetwork(t *testing.T) {
<ide> d := daemon.New(t)
<ide> d.Start(t)
<ide> defer d.Stop(t)
<del> // Verify bridge network's subnet
<del> cli, err := d.NewClient()
<del> assert.Assert(t, err)
<del> defer cli.Close()
<add> c := d.NewClientT(t)
<add> defer c.Close()
<ide>
<ide> // Create a bridge network
<ide> name := "elango" + t.Name()
<del> network.CreateNoError(t, context.Background(), cli, name,
<add> network.CreateNoError(t, context.Background(), c, name,
<ide> network.WithDriver("bridge"),
<ide> )
<del> out, err := cli.NetworkInspect(context.Background(), name, types.NetworkInspectOptions{})
<add>
<add> // Verify bridge network's subnet
<add> out, err := c.NetworkInspect(context.Background(), name, types.NetworkInspectOptions{})
<ide> assert.NilError(t, err)
<ide> networkip := out.IPAM.Config[0].Subnet
<ide>
<ide> func TestDaemonRestartWithExistingNetwork(t *testing.T) {
<ide> "--default-address-pool", "base=175.30.0.0/16,size=16",
<ide> "--default-address-pool", "base=175.33.0.0/16,size=24")
<ide>
<del> out1, err := cli.NetworkInspect(context.Background(), name, types.NetworkInspectOptions{})
<add> out1, err := c.NetworkInspect(context.Background(), name, types.NetworkInspectOptions{})
<ide> assert.NilError(t, err)
<ide> assert.Equal(t, out1.IPAM.Config[0].Subnet, networkip)
<ide> delInterface(t, defaultNetworkBridge)
<ide> func TestDaemonRestartWithExistingNetworkWithDefaultPoolRange(t *testing.T) {
<ide> d := daemon.New(t)
<ide> d.Start(t)
<ide> defer d.Stop(t)
<del> // Verify bridge network's subnet
<del> cli, err := d.NewClient()
<del> assert.Assert(t, err)
<del> defer cli.Close()
<add> c := d.NewClientT(t)
<add> defer c.Close()
<ide>
<ide> // Create a bridge network
<ide> name := "elango" + t.Name()
<del> network.CreateNoError(t, context.Background(), cli, name,
<add> network.CreateNoError(t, context.Background(), c, name,
<ide> network.WithDriver("bridge"),
<ide> )
<del> out, err := cli.NetworkInspect(context.Background(), name, types.NetworkInspectOptions{})
<add>
<add> // Verify bridge network's subnet
<add> out, err := c.NetworkInspect(context.Background(), name, types.NetworkInspectOptions{})
<ide> assert.NilError(t, err)
<ide> networkip := out.IPAM.Config[0].Subnet
<ide>
<ide> // Create a bridge network
<ide> name = "sthira" + t.Name()
<del> network.CreateNoError(t, context.Background(), cli, name,
<add> network.CreateNoError(t, context.Background(), c, name,
<ide> network.WithDriver("bridge"),
<ide> )
<del> out, err = cli.NetworkInspect(context.Background(), name, types.NetworkInspectOptions{})
<add> out, err = c.NetworkInspect(context.Background(), name, types.NetworkInspectOptions{})
<ide> assert.NilError(t, err)
<ide> networkip2 := out.IPAM.Config[0].Subnet
<ide>
<ide> // Restart daemon with default address pool option
<ide> d.Restart(t,
<ide> "--default-address-pool", "base=175.18.0.0/16,size=16",
<del> "--default-address-pool", "base=175.19.0.0/16,size=24")
<add> "--default-address-pool", "base=175.19.0.0/16,size=24",
<add> )
<ide>
<ide> // Create a bridge network
<ide> name = "saanvi" + t.Name()
<del> network.CreateNoError(t, context.Background(), cli, name,
<add> network.CreateNoError(t, context.Background(), c, name,
<ide> network.WithDriver("bridge"),
<ide> )
<del> out1, err := cli.NetworkInspect(context.Background(), name, types.NetworkInspectOptions{})
<add> out1, err := c.NetworkInspect(context.Background(), name, types.NetworkInspectOptions{})
<ide> assert.NilError(t, err)
<ide>
<ide> assert.Check(t, out1.IPAM.Config[0].Subnet != networkip)
<ide> func TestDaemonWithBipAndDefaultNetworkPool(t *testing.T) {
<ide> defaultNetworkBridge := "docker0"
<ide> d := daemon.New(t)
<ide> defer d.Stop(t)
<del> d.Start(t, "--bip=172.60.0.1/16",
<add> d.Start(t,
<add> "--bip=172.60.0.1/16",
<ide> "--default-address-pool", "base=175.30.0.0/16,size=16",
<del> "--default-address-pool", "base=175.33.0.0/16,size=24")
<add> "--default-address-pool", "base=175.33.0.0/16,size=24",
<add> )
<add>
<add> c := d.NewClientT(t)
<add> defer c.Close()
<ide>
<ide> // Verify bridge network's subnet
<del> cli, err := d.NewClient()
<del> assert.Assert(t, err)
<del> defer cli.Close()
<del> out, err := cli.NetworkInspect(context.Background(), "bridge", types.NetworkInspectOptions{})
<add> out, err := c.NetworkInspect(context.Background(), "bridge", types.NetworkInspectOptions{})
<ide> assert.NilError(t, err)
<ide> // Make sure BIP IP doesn't get override with new default address pool .
<ide> assert.Equal(t, out.IPAM.Config[0].Subnet, "172.60.0.1/16")
<ide> func TestServiceWithPredefinedNetwork(t *testing.T) {
<ide> defer setupTest(t)()
<ide> d := swarm.NewSwarm(t, testEnv)
<ide> defer d.Stop(t)
<del> client := d.NewClientT(t)
<del> defer client.Close()
<add> c := d.NewClientT(t)
<add> defer c.Close()
<ide>
<ide> hostName := "host"
<ide> var instances uint64 = 1
<ide> func TestServiceWithPredefinedNetwork(t *testing.T) {
<ide> swarm.ServiceWithNetwork(hostName),
<ide> )
<ide>
<del> poll.WaitOn(t, serviceRunningCount(client, serviceID, instances), swarm.ServicePoll)
<add> poll.WaitOn(t, serviceRunningCount(c, serviceID, instances), swarm.ServicePoll)
<ide>
<del> _, _, err := client.ServiceInspectWithRaw(context.Background(), serviceID, types.ServiceInspectOptions{})
<add> _, _, err := c.ServiceInspectWithRaw(context.Background(), serviceID, types.ServiceInspectOptions{})
<ide> assert.NilError(t, err)
<ide>
<del> err = client.ServiceRemove(context.Background(), serviceID)
<add> err = c.ServiceRemove(context.Background(), serviceID)
<ide> assert.NilError(t, err)
<ide> }
<ide>
<ide> func TestServiceRemoveKeepsIngressNetwork(t *testing.T) {
<ide> defer setupTest(t)()
<ide> d := swarm.NewSwarm(t, testEnv)
<ide> defer d.Stop(t)
<del> client := d.NewClientT(t)
<del> defer client.Close()
<add> c := d.NewClientT(t)
<add> defer c.Close()
<ide>
<del> poll.WaitOn(t, swarmIngressReady(client), swarm.NetworkPoll)
<add> poll.WaitOn(t, swarmIngressReady(c), swarm.NetworkPoll)
<ide>
<ide> var instances uint64 = 1
<ide>
<ide> func TestServiceRemoveKeepsIngressNetwork(t *testing.T) {
<ide> }),
<ide> )
<ide>
<del> poll.WaitOn(t, serviceRunningCount(client, serviceID, instances), swarm.ServicePoll)
<add> poll.WaitOn(t, serviceRunningCount(c, serviceID, instances), swarm.ServicePoll)
<ide>
<del> _, _, err := client.ServiceInspectWithRaw(context.Background(), serviceID, types.ServiceInspectOptions{})
<add> _, _, err := c.ServiceInspectWithRaw(context.Background(), serviceID, types.ServiceInspectOptions{})
<ide> assert.NilError(t, err)
<ide>
<del> err = client.ServiceRemove(context.Background(), serviceID)
<add> err = c.ServiceRemove(context.Background(), serviceID)
<ide> assert.NilError(t, err)
<ide>
<del> poll.WaitOn(t, serviceIsRemoved(client, serviceID), swarm.ServicePoll)
<del> poll.WaitOn(t, noServices(client), swarm.ServicePoll)
<add> poll.WaitOn(t, serviceIsRemoved(c, serviceID), swarm.ServicePoll)
<add> poll.WaitOn(t, noServices(c), swarm.ServicePoll)
<ide>
<ide> // Ensure that "ingress" is not removed or corrupted
<ide> time.Sleep(10 * time.Second)
<del> netInfo, err := client.NetworkInspect(context.Background(), ingressNet, types.NetworkInspectOptions{
<add> netInfo, err := c.NetworkInspect(context.Background(), ingressNet, types.NetworkInspectOptions{
<ide> Verbose: true,
<ide> Scope: "swarm",
<ide> })
<ide> func TestServiceWithDataPathPortInit(t *testing.T) {
<ide> ops = append(ops, daemon.WithSwarmDataPathPort(datapathPort))
<ide> d := swarm.NewSwarm(t, testEnv, ops...)
<ide>
<del> cli := d.NewClientT(t)
<del> defer cli.Close()
<add> c := d.NewClientT(t)
<add> defer c.Close()
<ide>
<ide> // Create a overlay network
<ide> name := "saanvisthira" + t.Name()
<del> network.CreateNoError(t, context.Background(), cli, name,
<add> network.CreateNoError(t, context.Background(), c, name,
<ide> network.WithDriver("overlay"))
<ide>
<ide> var instances uint64 = 1
<ide> func TestServiceWithDataPathPortInit(t *testing.T) {
<ide> swarm.ServiceWithNetwork(name),
<ide> )
<ide>
<del> poll.WaitOn(t, serviceRunningCount(cli, serviceID, instances), swarm.ServicePoll)
<add> poll.WaitOn(t, serviceRunningCount(c, serviceID, instances), swarm.ServicePoll)
<ide>
<ide> info := d.Info(t)
<ide> assert.Equal(t, info.Swarm.Cluster.DataPathPort, datapathPort)
<del> err := cli.ServiceRemove(context.Background(), serviceID)
<add> err := c.ServiceRemove(context.Background(), serviceID)
<ide> assert.NilError(t, err)
<ide> d.SwarmLeave(true)
<ide> d.Stop(t)
<ide> func TestServiceWithDataPathPortInit(t *testing.T) {
<ide> // call without datapath port option.
<ide> ops = []func(*daemon.Daemon){}
<ide> d = swarm.NewSwarm(t, testEnv, ops...)
<del> cli = d.NewClientT(t)
<add> c = d.NewClientT(t)
<ide>
<ide> // Create a overlay network
<ide> name = "saanvisthira" + t.Name()
<del> network.CreateNoError(t, context.Background(), cli, name,
<add> network.CreateNoError(t, context.Background(), c, name,
<ide> network.WithDriver("overlay"))
<ide>
<ide> serviceID = swarm.CreateService(t, d,
<ide> swarm.ServiceWithReplicas(instances),
<ide> swarm.ServiceWithNetwork(name),
<ide> )
<ide>
<del> poll.WaitOn(t, serviceRunningCount(cli, serviceID, instances), swarm.ServicePoll)
<add> poll.WaitOn(t, serviceRunningCount(c, serviceID, instances), swarm.ServicePoll)
<ide>
<ide> info = d.Info(t)
<ide> var defaultDataPathPort uint32 = 4789
<ide> assert.Equal(t, info.Swarm.Cluster.DataPathPort, defaultDataPathPort)
<del> err = cli.ServiceRemove(context.Background(), serviceID)
<add> err = c.ServiceRemove(context.Background(), serviceID)
<ide> assert.NilError(t, err)
<ide> d.SwarmLeave(true)
<ide> defer d.Stop(t)
<ide><path>integration/plugin/authz/authz_plugin_test.go
<ide> func TestAuthZPluginAllowRequest(t *testing.T) {
<ide> ctrl.resRes.Allow = true
<ide> d.StartWithBusybox(t, "--authorization-plugin="+testAuthZPlugin)
<ide>
<del> client, err := d.NewClient()
<del> assert.NilError(t, err)
<del>
<add> c := d.NewClientT(t)
<ide> ctx := context.Background()
<ide>
<ide> // Ensure command successful
<del> cID := container.Run(t, ctx, client)
<add> cID := container.Run(t, ctx, c)
<ide>
<ide> assertURIRecorded(t, ctrl.requestsURIs, "/containers/create")
<ide> assertURIRecorded(t, ctrl.requestsURIs, fmt.Sprintf("/containers/%s/start", cID))
<ide>
<del> _, err = client.ServerVersion(ctx)
<add> _, err := c.ServerVersion(ctx)
<ide> assert.NilError(t, err)
<ide> assert.Equal(t, 1, ctrl.versionReqCount)
<ide> assert.Equal(t, 1, ctrl.versionResCount)
<ide> func TestAuthZPluginTLS(t *testing.T) {
<ide> ctrl.reqRes.Allow = true
<ide> ctrl.resRes.Allow = true
<ide>
<del> client, err := newTLSAPIClient(testDaemonHTTPSAddr, cacertPath, clientCertPath, clientKeyPath)
<add> c, err := newTLSAPIClient(testDaemonHTTPSAddr, cacertPath, clientCertPath, clientKeyPath)
<ide> assert.NilError(t, err)
<ide>
<del> _, err = client.ServerVersion(context.Background())
<add> _, err = c.ServerVersion(context.Background())
<ide> assert.NilError(t, err)
<ide>
<ide> assert.Equal(t, "client", ctrl.reqUser)
<ide> func TestAuthZPluginDenyRequest(t *testing.T) {
<ide> ctrl.reqRes.Allow = false
<ide> ctrl.reqRes.Msg = unauthorizedMessage
<ide>
<del> client, err := d.NewClient()
<del> assert.NilError(t, err)
<add> c := d.NewClientT(t)
<ide>
<ide> // Ensure command is blocked
<del> _, err = client.ServerVersion(context.Background())
<add> _, err := c.ServerVersion(context.Background())
<ide> assert.Assert(t, err != nil)
<ide> assert.Equal(t, 1, ctrl.versionReqCount)
<ide> assert.Equal(t, 0, ctrl.versionResCount)
<ide> func TestAuthZPluginAPIDenyResponse(t *testing.T) {
<ide>
<ide> conn, err := net.DialTimeout(daemonURL.Scheme, daemonURL.Path, time.Second*10)
<ide> assert.NilError(t, err)
<del> client := httputil.NewClientConn(conn, nil)
<add> c := httputil.NewClientConn(conn, nil)
<ide> req, err := http.NewRequest("GET", "/version", nil)
<ide> assert.NilError(t, err)
<del> resp, err := client.Do(req)
<add> resp, err := c.Do(req)
<ide>
<ide> assert.NilError(t, err)
<ide> assert.DeepEqual(t, http.StatusForbidden, resp.StatusCode)
<ide> func TestAuthZPluginDenyResponse(t *testing.T) {
<ide> ctrl.resRes.Allow = false
<ide> ctrl.resRes.Msg = unauthorizedMessage
<ide>
<del> client, err := d.NewClient()
<del> assert.NilError(t, err)
<add> c := d.NewClientT(t)
<ide>
<ide> // Ensure command is blocked
<del> _, err = client.ServerVersion(context.Background())
<add> _, err := c.ServerVersion(context.Background())
<ide> assert.Assert(t, err != nil)
<ide> assert.Equal(t, 1, ctrl.versionReqCount)
<ide> assert.Equal(t, 1, ctrl.versionResCount)
<ide> func TestAuthZPluginAllowEventStream(t *testing.T) {
<ide> ctrl.resRes.Allow = true
<ide> d.StartWithBusybox(t, "--authorization-plugin="+testAuthZPlugin)
<ide>
<del> client, err := d.NewClient()
<del> assert.NilError(t, err)
<del>
<add> c := d.NewClientT(t)
<ide> ctx := context.Background()
<ide>
<del> startTime := strconv.FormatInt(systemTime(t, client, testEnv).Unix(), 10)
<del> events, errs, cancel := systemEventsSince(client, startTime)
<add> startTime := strconv.FormatInt(systemTime(t, c, testEnv).Unix(), 10)
<add> events, errs, cancel := systemEventsSince(c, startTime)
<ide> defer cancel()
<ide>
<ide> // Create a container and wait for the creation events
<del> cID := container.Run(t, ctx, client)
<add> cID := container.Run(t, ctx, c)
<ide>
<ide> for i := 0; i < 100; i++ {
<del> c, err := client.ContainerInspect(ctx, cID)
<add> c, err := c.ContainerInspect(ctx, cID)
<ide> assert.NilError(t, err)
<ide> if c.State.Running {
<ide> break
<ide> func TestAuthZPluginErrorResponse(t *testing.T) {
<ide> ctrl.reqRes.Allow = true
<ide> ctrl.resRes.Err = errorMessage
<ide>
<del> client, err := d.NewClient()
<del> assert.NilError(t, err)
<add> c := d.NewClientT(t)
<ide>
<ide> // Ensure command is blocked
<del> _, err = client.ServerVersion(context.Background())
<add> _, err := c.ServerVersion(context.Background())
<ide> assert.Assert(t, err != nil)
<ide> assert.Equal(t, fmt.Sprintf("Error response from daemon: plugin %s failed with error: %s: %s", testAuthZPlugin, authorization.AuthZApiResponse, errorMessage), err.Error())
<ide> }
<ide> func TestAuthZPluginErrorRequest(t *testing.T) {
<ide> d.Start(t, "--authorization-plugin="+testAuthZPlugin)
<ide> ctrl.reqRes.Err = errorMessage
<ide>
<del> client, err := d.NewClient()
<del> assert.NilError(t, err)
<add> c := d.NewClientT(t)
<ide>
<ide> // Ensure command is blocked
<del> _, err = client.ServerVersion(context.Background())
<add> _, err := c.ServerVersion(context.Background())
<ide> assert.Assert(t, err != nil)
<ide> assert.Equal(t, fmt.Sprintf("Error response from daemon: plugin %s failed with error: %s: %s", testAuthZPlugin, authorization.AuthZApiRequest, errorMessage), err.Error())
<ide> }
<ide> func TestAuthZPluginEnsureNoDuplicatePluginRegistration(t *testing.T) {
<ide> ctrl.reqRes.Allow = true
<ide> ctrl.resRes.Allow = true
<ide>
<del> client, err := d.NewClient()
<del> assert.NilError(t, err)
<add> c := d.NewClientT(t)
<ide>
<del> _, err = client.ServerVersion(context.Background())
<add> _, err := c.ServerVersion(context.Background())
<ide> assert.NilError(t, err)
<ide>
<ide> // assert plugin is only called once..
<ide> func TestAuthZPluginEnsureLoadImportWorking(t *testing.T) {
<ide> ctrl.resRes.Allow = true
<ide> d.StartWithBusybox(t, "--authorization-plugin="+testAuthZPlugin, "--authorization-plugin="+testAuthZPlugin)
<ide>
<del> client, err := d.NewClient()
<del> assert.NilError(t, err)
<del>
<add> c := d.NewClientT(t)
<ide> ctx := context.Background()
<ide>
<ide> tmp, err := ioutil.TempDir("", "test-authz-load-import")
<ide> func TestAuthZPluginEnsureLoadImportWorking(t *testing.T) {
<ide>
<ide> savedImagePath := filepath.Join(tmp, "save.tar")
<ide>
<del> err = imageSave(client, savedImagePath, "busybox")
<add> err = imageSave(c, savedImagePath, "busybox")
<ide> assert.NilError(t, err)
<del> err = imageLoad(client, savedImagePath)
<add> err = imageLoad(c, savedImagePath)
<ide> assert.NilError(t, err)
<ide>
<ide> exportedImagePath := filepath.Join(tmp, "export.tar")
<ide>
<del> cID := container.Run(t, ctx, client)
<add> cID := container.Run(t, ctx, c)
<ide>
<del> responseReader, err := client.ContainerExport(context.Background(), cID)
<add> responseReader, err := c.ContainerExport(context.Background(), cID)
<ide> assert.NilError(t, err)
<ide> defer responseReader.Close()
<ide> file, err := os.Create(exportedImagePath)
<ide> func TestAuthZPluginEnsureLoadImportWorking(t *testing.T) {
<ide> _, err = io.Copy(file, responseReader)
<ide> assert.NilError(t, err)
<ide>
<del> err = imageImport(client, exportedImagePath)
<add> err = imageImport(c, exportedImagePath)
<ide> assert.NilError(t, err)
<ide> }
<ide>
<ide> func TestAuthzPluginEnsureContainerCopyToFrom(t *testing.T) {
<ide> written += n
<ide> }
<ide>
<add> c := d.NewClientT(t)
<ide> ctx := context.Background()
<del> client, err := d.NewClient()
<del> assert.Assert(t, err)
<ide>
<del> cID := container.Run(t, ctx, client)
<del> defer client.ContainerRemove(ctx, cID, types.ContainerRemoveOptions{Force: true})
<add> cID := container.Run(t, ctx, c)
<add> defer c.ContainerRemove(ctx, cID, types.ContainerRemoveOptions{Force: true})
<ide>
<ide> _, err = f.Seek(0, io.SeekStart)
<ide> assert.Assert(t, err)
<ide> func TestAuthzPluginEnsureContainerCopyToFrom(t *testing.T) {
<ide> dstDir, preparedArchive, err := archive.PrepareArchiveCopy(srcArchive, srcInfo, archive.CopyInfo{Path: "/test"})
<ide> assert.Assert(t, err)
<ide>
<del> err = client.CopyToContainer(ctx, cID, dstDir, preparedArchive, types.CopyToContainerOptions{})
<add> err = c.CopyToContainer(ctx, cID, dstDir, preparedArchive, types.CopyToContainerOptions{})
<ide> assert.Assert(t, err)
<ide>
<del> rdr, _, err := client.CopyFromContainer(ctx, cID, "/test")
<add> rdr, _, err := c.CopyFromContainer(ctx, cID, "/test")
<ide> assert.Assert(t, err)
<ide> _, err = io.Copy(ioutil.Discard, rdr)
<ide> assert.Assert(t, err)
<ide><path>integration/plugin/authz/authz_plugin_v2_test.go
<ide> func TestAuthZPluginV2AllowNonVolumeRequest(t *testing.T) {
<ide> skip.If(t, os.Getenv("DOCKER_ENGINE_GOARCH") != "amd64")
<ide> defer setupTestV2(t)()
<ide>
<del> client, err := d.NewClient()
<del> assert.NilError(t, err)
<del>
<add> c := d.NewClientT(t)
<ide> ctx := context.Background()
<ide>
<ide> // Install authz plugin
<del> err = pluginInstallGrantAllPermissions(client, authzPluginNameWithTag)
<add> err := pluginInstallGrantAllPermissions(c, authzPluginNameWithTag)
<ide> assert.NilError(t, err)
<ide> // start the daemon with the plugin and load busybox, --net=none build fails otherwise
<ide> // because it needs to pull busybox
<ide> d.Restart(t, "--authorization-plugin="+authzPluginNameWithTag)
<ide> d.LoadBusybox(t)
<ide>
<ide> // Ensure docker run command and accompanying docker ps are successful
<del> cID := container.Run(t, ctx, client)
<add> cID := container.Run(t, ctx, c)
<ide>
<del> _, err = client.ContainerInspect(ctx, cID)
<add> _, err = c.ContainerInspect(ctx, cID)
<ide> assert.NilError(t, err)
<ide> }
<ide>
<ide> func TestAuthZPluginV2Disable(t *testing.T) {
<ide> skip.If(t, os.Getenv("DOCKER_ENGINE_GOARCH") != "amd64")
<ide> defer setupTestV2(t)()
<ide>
<del> client, err := d.NewClient()
<del> assert.NilError(t, err)
<add> c := d.NewClientT(t)
<ide>
<ide> // Install authz plugin
<del> err = pluginInstallGrantAllPermissions(client, authzPluginNameWithTag)
<add> err := pluginInstallGrantAllPermissions(c, authzPluginNameWithTag)
<ide> assert.NilError(t, err)
<ide>
<ide> d.Restart(t, "--authorization-plugin="+authzPluginNameWithTag)
<ide> d.LoadBusybox(t)
<ide>
<del> _, err = client.VolumeCreate(context.Background(), volumetypes.VolumeCreateBody{Driver: "local"})
<add> _, err = c.VolumeCreate(context.Background(), volumetypes.VolumeCreateBody{Driver: "local"})
<ide> assert.Assert(t, err != nil)
<ide> assert.Assert(t, strings.Contains(err.Error(), fmt.Sprintf("Error response from daemon: plugin %s failed with error:", authzPluginNameWithTag)))
<ide>
<ide> // disable the plugin
<del> err = client.PluginDisable(context.Background(), authzPluginNameWithTag, types.PluginDisableOptions{})
<add> err = c.PluginDisable(context.Background(), authzPluginNameWithTag, types.PluginDisableOptions{})
<ide> assert.NilError(t, err)
<ide>
<ide> // now test to see if the docker api works.
<del> _, err = client.VolumeCreate(context.Background(), volumetypes.VolumeCreateBody{Driver: "local"})
<add> _, err = c.VolumeCreate(context.Background(), volumetypes.VolumeCreateBody{Driver: "local"})
<ide> assert.NilError(t, err)
<ide> }
<ide>
<ide> func TestAuthZPluginV2RejectVolumeRequests(t *testing.T) {
<ide> skip.If(t, os.Getenv("DOCKER_ENGINE_GOARCH") != "amd64")
<ide> defer setupTestV2(t)()
<ide>
<del> client, err := d.NewClient()
<del> assert.NilError(t, err)
<add> c := d.NewClientT(t)
<ide>
<ide> // Install authz plugin
<del> err = pluginInstallGrantAllPermissions(client, authzPluginNameWithTag)
<add> err := pluginInstallGrantAllPermissions(c, authzPluginNameWithTag)
<ide> assert.NilError(t, err)
<ide>
<ide> // restart the daemon with the plugin
<ide> d.Restart(t, "--authorization-plugin="+authzPluginNameWithTag)
<ide>
<del> _, err = client.VolumeCreate(context.Background(), volumetypes.VolumeCreateBody{Driver: "local"})
<add> _, err = c.VolumeCreate(context.Background(), volumetypes.VolumeCreateBody{Driver: "local"})
<ide> assert.Assert(t, err != nil)
<ide> assert.Assert(t, strings.Contains(err.Error(), fmt.Sprintf("Error response from daemon: plugin %s failed with error:", authzPluginNameWithTag)))
<ide>
<del> _, err = client.VolumeList(context.Background(), filters.Args{})
<add> _, err = c.VolumeList(context.Background(), filters.Args{})
<ide> assert.Assert(t, err != nil)
<ide> assert.Assert(t, strings.Contains(err.Error(), fmt.Sprintf("Error response from daemon: plugin %s failed with error:", authzPluginNameWithTag)))
<ide>
<ide> // The plugin will block the command before it can determine the volume does not exist
<del> err = client.VolumeRemove(context.Background(), "test", false)
<add> err = c.VolumeRemove(context.Background(), "test", false)
<ide> assert.Assert(t, err != nil)
<ide> assert.Assert(t, strings.Contains(err.Error(), fmt.Sprintf("Error response from daemon: plugin %s failed with error:", authzPluginNameWithTag)))
<ide>
<del> _, err = client.VolumeInspect(context.Background(), "test")
<add> _, err = c.VolumeInspect(context.Background(), "test")
<ide> assert.Assert(t, err != nil)
<ide> assert.Assert(t, strings.Contains(err.Error(), fmt.Sprintf("Error response from daemon: plugin %s failed with error:", authzPluginNameWithTag)))
<ide>
<del> _, err = client.VolumesPrune(context.Background(), filters.Args{})
<add> _, err = c.VolumesPrune(context.Background(), filters.Args{})
<ide> assert.Assert(t, err != nil)
<ide> assert.Assert(t, strings.Contains(err.Error(), fmt.Sprintf("Error response from daemon: plugin %s failed with error:", authzPluginNameWithTag)))
<ide> }
<ide> func TestAuthZPluginV2BadManifestFailsDaemonStart(t *testing.T) {
<ide> skip.If(t, os.Getenv("DOCKER_ENGINE_GOARCH") != "amd64")
<ide> defer setupTestV2(t)()
<ide>
<del> client, err := d.NewClient()
<del> assert.NilError(t, err)
<add> c := d.NewClientT(t)
<ide>
<ide> // Install authz plugin with bad manifest
<del> err = pluginInstallGrantAllPermissions(client, authzPluginBadManifestName)
<add> err := pluginInstallGrantAllPermissions(c, authzPluginBadManifestName)
<ide> assert.NilError(t, err)
<ide>
<ide> // start the daemon with the plugin, it will error
<ide><path>integration/plugin/logging/validation_test.go
<ide> func TestDaemonStartWithLogOpt(t *testing.T) {
<ide> d.Start(t, "--iptables=false")
<ide> defer d.Stop(t)
<ide>
<del> client, err := d.NewClient()
<del> assert.Check(t, err)
<add> c := d.NewClientT(t)
<ide> ctx := context.Background()
<ide>
<del> createPlugin(t, client, "test", "dummy", asLogDriver)
<del> err = client.PluginEnable(ctx, "test", types.PluginEnableOptions{Timeout: 30})
<add> createPlugin(t, c, "test", "dummy", asLogDriver)
<add> err := c.PluginEnable(ctx, "test", types.PluginEnableOptions{Timeout: 30})
<ide> assert.Check(t, err)
<del> defer client.PluginRemove(ctx, "test", types.PluginRemoveOptions{Force: true})
<add> defer c.PluginRemove(ctx, "test", types.PluginRemoveOptions{Force: true})
<ide>
<ide> d.Stop(t)
<ide> d.Start(t, "--iptables=false", "--log-driver=test", "--log-opt=foo=bar")
<ide><path>integration/plugin/volumes/mounts_test.go
<ide> func TestPluginWithDevMounts(t *testing.T) {
<ide> d.Start(t, "--iptables=false")
<ide> defer d.Stop(t)
<ide>
<del> client, err := d.NewClient()
<del> assert.Assert(t, err)
<add> c := d.NewClientT(t)
<ide> ctx := context.Background()
<ide>
<ide> testDir, err := ioutil.TempDir("", "test-dir")
<ide> assert.Assert(t, err)
<ide> defer os.RemoveAll(testDir)
<ide>
<del> createPlugin(t, client, "test", "dummy", asVolumeDriver, func(c *plugin.Config) {
<add> createPlugin(t, c, "test", "dummy", asVolumeDriver, func(c *plugin.Config) {
<ide> root := "/"
<ide> dev := "/dev"
<ide> mounts := []types.PluginMount{
<ide> func TestPluginWithDevMounts(t *testing.T) {
<ide> c.IpcHost = true
<ide> })
<ide>
<del> err = client.PluginEnable(ctx, "test", types.PluginEnableOptions{Timeout: 30})
<add> err = c.PluginEnable(ctx, "test", types.PluginEnableOptions{Timeout: 30})
<ide> assert.Assert(t, err)
<ide> defer func() {
<del> err := client.PluginRemove(ctx, "test", types.PluginRemoveOptions{Force: true})
<add> err := c.PluginRemove(ctx, "test", types.PluginRemoveOptions{Force: true})
<ide> assert.Check(t, err)
<ide> }()
<ide>
<del> p, _, err := client.PluginInspectWithRaw(ctx, "test")
<add> p, _, err := c.PluginInspectWithRaw(ctx, "test")
<ide> assert.Assert(t, err)
<ide> assert.Assert(t, p.Enabled)
<ide> }
<ide><path>integration/system/cgroupdriver_systemd_test.go
<ide> func TestCgroupDriverSystemdMemoryLimit(t *testing.T) {
<ide> }
<ide>
<ide> d := daemon.New(t)
<del> client, err := d.NewClient()
<del> assert.NilError(t, err)
<add> c := d.NewClientT(t)
<add>
<ide> d.StartWithBusybox(t, "--exec-opt", "native.cgroupdriver=systemd", "--iptables=false")
<ide> defer d.Stop(t)
<ide>
<ide> const mem = 64 * 1024 * 1024 // 64 MB
<ide>
<ide> ctx := context.Background()
<del> ctrID := container.Create(t, ctx, client, func(c *container.TestContainerConfig) {
<del> c.HostConfig.Resources.Memory = mem
<add> ctrID := container.Create(t, ctx, c, func(ctr *container.TestContainerConfig) {
<add> ctr.HostConfig.Resources.Memory = mem
<ide> })
<del> defer client.ContainerRemove(ctx, ctrID, types.ContainerRemoveOptions{Force: true})
<add> defer c.ContainerRemove(ctx, ctrID, types.ContainerRemoveOptions{Force: true})
<ide>
<del> err = client.ContainerStart(ctx, ctrID, types.ContainerStartOptions{})
<add> err := c.ContainerStart(ctx, ctrID, types.ContainerStartOptions{})
<ide> assert.NilError(t, err)
<ide>
<del> s, err := client.ContainerInspect(ctx, ctrID)
<add> s, err := c.ContainerInspect(ctx, ctrID)
<ide> assert.NilError(t, err)
<ide> assert.Equal(t, s.HostConfig.Memory, mem)
<ide> }
<ide><path>integration/system/info_test.go
<ide> func TestInfoAPI(t *testing.T) {
<ide> func TestInfoAPIWarnings(t *testing.T) {
<ide> skip.If(t, testEnv.DaemonInfo.OSType == "windows", "FIXME")
<ide> d := daemon.New(t)
<del>
<del> client, err := d.NewClient()
<del> assert.NilError(t, err)
<add> c := d.NewClientT(t)
<ide>
<ide> d.StartWithBusybox(t, "-H=0.0.0.0:23756", "-H="+d.Sock())
<ide> defer d.Stop(t)
<ide>
<del> info, err := client.Info(context.Background())
<add> info, err := c.Info(context.Background())
<ide> assert.NilError(t, err)
<ide>
<ide> stringsToCheck := []string{
<ide><path>internal/test/daemon/daemon.go
<ide> func (d *Daemon) LoadBusybox(t assert.TestingT) {
<ide> assert.NilError(t, err, "failed to download busybox")
<ide> defer reader.Close()
<ide>
<del> client, err := d.NewClient()
<del> assert.NilError(t, err, "failed to create client")
<del> defer client.Close()
<add> c := d.NewClientT(t)
<add> defer c.Close()
<ide>
<del> resp, err := client.ImageLoad(ctx, reader, true)
<add> resp, err := c.ImageLoad(ctx, reader, true)
<ide> assert.NilError(t, err, "failed to load busybox")
<ide> defer resp.Body.Close()
<ide> }
<ide> func (d *Daemon) queryRootDir() (string, error) {
<ide> return "", err
<ide> }
<ide>
<del> client := &http.Client{
<add> c := &http.Client{
<ide> Transport: clientConfig.transport,
<ide> }
<ide>
<ide> func (d *Daemon) queryRootDir() (string, error) {
<ide> req.URL.Host = clientConfig.addr
<ide> req.URL.Scheme = clientConfig.scheme
<ide>
<del> resp, err := client.Do(req)
<add> resp, err := c.Do(req)
<ide> if err != nil {
<ide> return "", err
<ide> }
<ide> func (d *Daemon) Info(t assert.TestingT) types.Info {
<ide> if ht, ok := t.(test.HelperT); ok {
<ide> ht.Helper()
<ide> }
<del> apiclient, err := d.NewClient()
<del> assert.NilError(t, err)
<del> info, err := apiclient.Info(context.Background())
<add> c := d.NewClientT(t)
<add> info, err := c.Info(context.Background())
<ide> assert.NilError(t, err)
<ide> return info
<ide> } | 19 |
Javascript | Javascript | fix groups in extrudebuffergeometry | 294639a8182a4b92ea410b0d094500b2eb0d9c88 | <ide><path>src/geometries/ExtrudeGeometry.js
<ide> ExtrudeBufferGeometry.prototype.addShape = function ( shape, options ) {
<ide>
<ide> }
<ide>
<del> if (options.extrudeMaterial !== undefined){
<del>
<del> scope.addGroup( start, verticesArray.length/3 -start, options.extrudeMaterial !== undefined ? options.extrudeMaterial : 1);
<del>
<del> }
<add>
<add> scope.addGroup( start, verticesArray.length/3 -start, options.extrudeMaterial !== undefined ? options.extrudeMaterial : 1);
<add>
<ide>
<ide> }
<ide> | 1 |
Python | Python | address reviewer comment | 38fe698843d8d13fcdbcdce13b186aa66623a324 | <ide><path>numpy/ma/core.py
<ide> def masked_equal(x, value, copy=True):
<ide> """
<ide> Mask an array where equal to a given value.
<ide>
<add> Return a MaskedArray, masked where the data in array `x` are
<add> equal to `value`. The fill_value of the returned MaskedArray
<add> is set to `value`.
<add>
<ide> This function is a shortcut to ``masked_where``, with
<ide> `condition` = (x == value). For floating point arrays,
<ide> consider using ``masked_values(x, value)``.
<ide>
<del> The fill_value is set to `value`.
<del>
<ide> See Also
<ide> --------
<ide> masked_where : Mask where a condition is met. | 1 |
Ruby | Ruby | remove pre_bug_report links | 7c048b6f71b031ab8ee1289a70b51cef24408dcc | <ide><path>Library/Homebrew/cask/lib/hbc/utils.rb
<ide>
<ide> require "hbc/utils/file"
<ide>
<del>PREBUG_URL = "https://github.com/caskroom/homebrew-cask/blob/master/doc/reporting_bugs/pre_bug_report.md".freeze
<del>ISSUES_URL = "https://github.com/caskroom/homebrew-cask#reporting-bugs".freeze
<add>BUG_REPORTS_URL = "https://github.com/caskroom/homebrew-cask#reporting-bugs".freeze
<ide>
<ide> # monkeypatch Object - not a great idea
<ide> class Object
<ide> def self.path_occupied?(path)
<ide> def self.error_message_with_suggestions
<ide> <<-EOS.undent
<ide> Follow the instructions here:
<del> #{Formatter.url(PREBUG_URL)}
<del>
<del> If this doesn’t fix the problem, please report this bug:
<del> #{Formatter.url(ISSUES_URL)}
<del>
<add> #{Formatter.url(BUG_REPORTS_URL)}
<ide> EOS
<ide> end
<ide>
<ide><path>Library/Homebrew/test/cask/dsl_spec.rb
<ide> .*
<ide> Unexpected method 'future_feature' called on Cask unexpected-method-cask\\.
<ide> .*
<del> https://github.com/caskroom/homebrew-cask/blob/master/doc/reporting_bugs/pre_bug_report.md
<del> .*
<ide> https://github.com/caskroom/homebrew-cask#reporting-bugs
<ide> EOS
<ide> | 2 |
Text | Text | add french translation | 22b2790d70d50f08c73a94770630b4bc6a1734d2 | <ide><path>threejs/lessons/fr/threejs-scenegraph.md
<del>Title: Graphe de scène Three.js
<del>Description: What's a scene graph?
<add>Title: Graphique de scène de Three.js
<add>Description: Qu'est-ce qu'un graphique de scène ?
<ide> TOC: Scenegraph
<ide>
<ide> Cet article fait partie d'une série consacrée à Three.js.
<ide> Le premier article s'intitule [Principes de base](threejs-fundamentals.html).
<ide> Si vous ne l'avez pas encore lu, vous voudriez peut-être commencer par là.
<ide>
<del>Le coeurs de Three.js est sans aucun doute son graphique de scène. Une scène est une représentation arborescente des objets que l’on souhaite afficher, où chaque nœud représente un espace local.
<add>Le coeurs de Three.js est sans aucun doute son graphique de scène. Un graphique de scène est une représentation arborescente des objets que l’on souhaite afficher, où chaque nœud représente un espace local.
<ide>
<ide> <img src="resources/images/scenegraph-generic.svg" align="center">
<ide> | 1 |
Text | Text | replace data urls with cdn urls for d3 projects | b730b67e1ad9764e16e911070c210f77d25c7866 | <ide><path>curriculum/challenges/chinese/04-data-visualization/data-visualization-projects/visualize-data-with-a-choropleth-map.chinese.md
<ide> localeTitle: 使用等值线图可视化数据
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> <strong>目标:</strong>构建一个功能类似于此的<a href="https://codepen.io" target="_blank">CodePen.io</a>应用程序: <a href="https://codepen.io/freeCodeCamp/full/EZKqza" target="_blank">https</a> <strong>:</strong> <a href="https://codepen.io" target="_blank">//codepen.io/freeCodeCamp/full/EZKqza</a> 。完成以下<a href="https://en.wikipedia.org/wiki/User_story" target="_blank">用户故事</a>并通过所有测试。给它你自己的个人风格。您可以使用HTML,JavaScript,CSS和基于D3 svg的可视化库。在每次测试时查询必需(非虚拟)DOM元素。如果您使用前端框架(例如Vue),则测试结果可能对动态内容不准确。我们希望最终能够容纳它们,但D3项目目前不支持这些框架。 <strong>用户故事#1:</strong>我的等值应该有一个带有相应<code>id="title"</code> 。 <strong>用户故事#2:</strong>我的等值应该有一个带有相应<code>id="description"</code>的描述元素。 <strong>用户故事#3:</strong>我的等值应该有具有代表数据的相应<code>class="county"</code> 。 <strong>用户故事#4:</strong>县应该至少使用4种不同的填充颜色。 <strong>用户故事#5:</strong>我的县应该拥有包含相应的fips和教育价值的<code>data-fips</code>和<code>data-education</code>属性。 <strong>用户故事#6:</strong>我的等值应该为每个提供的数据点设置一个县。 <strong>用户故事#7:</strong>县应具有与样本数据匹配的数据fips和数据教育值。 <strong>用户故事#8:</strong>我的等值应该有一个带有相应<code>id="legend"</code> 。 <strong>用户故事#9:</strong>图例应至少使用4种不同的填充颜色。 <strong>用户故事#10:</strong>我可以将鼠标悬停在某个区域上,并查看带有相应<code>id="tooltip"</code> ,其中显示有关该区域的更多信息。 <strong>用户故事#11:</strong>我的工具提示应该具有与活动区域的<code>data-education</code>相对应的<code>data-education</code>属性。以下是完成此项目所需的数据集: <br><ul><li> <strong>美国教育数据:</strong> <code>https://raw.githubusercontent.com/no-stack-dub-sack/testable-projects-fcc/master/src/data/choropleth_map/for_user_education.json</code> <strong>:</strong> <code>https://raw.githubusercontent.com/no-stack-dub-sack/testable-projects-fcc/master/src/data/choropleth_map/for_user_education.json</code> </li><li> <strong>美国县数据:</strong> <code>https://raw.githubusercontent.com/no-stack-dub-sack/testable-projects-fcc/master/src/data/choropleth_map/counties.json</code> <strong>:</strong> <code>https://raw.githubusercontent.com/no-stack-dub-sack/testable-projects-fcc/master/src/data/choropleth_map/counties.json</code> </li></ul>您可以通过分叉<a href="https://codepen.io/freeCodeCamp/pen/MJjpwO" target="_blank">此CodePen笔</a>来构建项目。或者您可以使用此CDN链接在您喜欢的任何环境中运行测试: <code>https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js</code> : <code>https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js</code>完成后,将URL提交给您的工作通过所有测试的项目。如果卡住,请记住使用<a href="https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask</a>方法。 </section>
<add><section id="description"> <strong>目标:</strong>构建一个功能类似于此的<a href="https://codepen.io" target="_blank">CodePen.io</a>应用程序: <a href="https://codepen.io/freeCodeCamp/full/EZKqza" target="_blank">https</a> <strong>:</strong> <a href="https://codepen.io" target="_blank">//codepen.io/freeCodeCamp/full/EZKqza</a> 。完成以下<a href="https://en.wikipedia.org/wiki/User_story" target="_blank">用户故事</a>并通过所有测试。给它你自己的个人风格。您可以使用HTML,JavaScript,CSS和基于D3 svg的可视化库。在每次测试时查询必需(非虚拟)DOM元素。如果您使用前端框架(例如Vue),则测试结果可能对动态内容不准确。我们希望最终能够容纳它们,但D3项目目前不支持这些框架。 <strong>用户故事#1:</strong>我的等值应该有一个带有相应<code>id="title"</code> 。 <strong>用户故事#2:</strong>我的等值应该有一个带有相应<code>id="description"</code>的描述元素。 <strong>用户故事#3:</strong>我的等值应该有具有代表数据的相应<code>class="county"</code> 。 <strong>用户故事#4:</strong>县应该至少使用4种不同的填充颜色。 <strong>用户故事#5:</strong>我的县应该拥有包含相应的fips和教育价值的<code>data-fips</code>和<code>data-education</code>属性。 <strong>用户故事#6:</strong>我的等值应该为每个提供的数据点设置一个县。 <strong>用户故事#7:</strong>县应具有与样本数据匹配的数据fips和数据教育值。 <strong>用户故事#8:</strong>我的等值应该有一个带有相应<code>id="legend"</code> 。 <strong>用户故事#9:</strong>图例应至少使用4种不同的填充颜色。 <strong>用户故事#10:</strong>我可以将鼠标悬停在某个区域上,并查看带有相应<code>id="tooltip"</code> ,其中显示有关该区域的更多信息。 <strong>用户故事#11:</strong>我的工具提示应该具有与活动区域的<code>data-education</code>相对应的<code>data-education</code>属性。以下是完成此项目所需的数据集: <br><ul><li> <strong>美国教育数据:</strong> <code>https://cdn.freecodecamp.org/testable-projects-fcc/data/choropleth_map/for_user_education.json</code> <strong>:</strong> <code>https://cdn.freecodecamp.org/testable-projects-fcc/data/choropleth_map/for_user_education.json</code> </li><li> <strong>美国县数据:</strong> <code>https://cdn.freecodecamp.org/testable-projects-fcc/data/choropleth_map/counties.json</code> <strong>:</strong> <code>https://cdn.freecodecamp.org/testable-projects-fcc/data/choropleth_map/counties.json</code> </li></ul>您可以通过分叉<a href="https://codepen.io/freeCodeCamp/pen/MJjpwO" target="_blank">此CodePen笔</a>来构建项目。或者您可以使用此CDN链接在您喜欢的任何环境中运行测试: <code>https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js</code> : <code>https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js</code>完成后,将URL提交给您的工作通过所有测试的项目。如果卡住,请记住使用<a href="https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask</a>方法。 </section>
<ide>
<ide> ## Instructions
<ide> <section id="instructions">
<ide><path>curriculum/challenges/chinese/04-data-visualization/data-visualization-projects/visualize-data-with-a-treemap-diagram.chinese.md
<ide> localeTitle: 使用树形图可视化数据
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> <strong>目标:</strong>构建一个功能类似于此的<a href="https://codepen.io" target="_blank">CodePen.io</a>应用程序: <a href="https://codepen.io/freeCodeCamp/full/KaNGNR" target="_blank">https</a> <strong>:</strong> <a href="https://codepen.io" target="_blank">//codepen.io/freeCodeCamp/full/KaNGNR</a> 。完成以下<a href="https://en.wikipedia.org/wiki/User_story" target="_blank">用户故事</a>并通过所有测试。给它你自己的个人风格。您可以使用HTML,JavaScript,CSS和基于D3 svg的可视化库。测试需要使用D3轴属性生成轴,该属性会自动生成沿轴的刻度。通过D3测试需要这些刻度,因为它们的位置用于确定绘制元素的对齐方式。有关生成轴的信息, <a href="https://github.com/d3/d3/blob/master/API.md#axes-d3-axis" target="_blank">请</a>访问<a href="https://github.com/d3/d3/blob/master/API.md#axes-d3-axis" target="_blank">https://github.com/d3/d3/blob/master/API.md#axes-d3-axis</a> 。在每次测试时查询必需(非虚拟)DOM元素。如果您使用前端框架(例如Vue),则测试结果可能对动态内容不准确。我们希望最终能够容纳它们,但D3项目目前不支持这些框架。 <strong>用户故事#1:</strong>我的树图应该有一个标题,对应的<code>id="title"</code> 。 <strong>用户故事#2:</strong>我的树图应该有一个对应<code>id="description"</code> 。 <strong>用户故事#3:</strong>我的树形图应该有一个<code>rect</code>元素,并且对应的<code>class="tile"</code>代表数据。 <strong>用户故事#4:</strong>瓷砖应至少有2种不同的填充颜色。 <strong>用户故事#5:</strong>每个瓷砖应具有属性<code>data-name</code> , <code>data-category</code> ,和<code>data-value</code>包含其相应的名称,类别,和值。 <strong>用户故事#6:</strong>每个图块的区域应对应于数据值量:具有较大数据值的图块应具有更大的区域。 <strong>用户故事#7:</strong>我的树形图应该有一个对应<code>id="legend"</code> 。 <strong>用户故事#8:</strong>我的图例应该有一个带有相应<code>class="legend-item"</code> <code>rect</code>元素。 <strong>用户故事#9:</strong>图例中的<code>rect</code>元素应使用至少2种不同的填充颜色。 <strong>用户故事#10:</strong>我可以将鼠标悬停在某个区域上,并查看带有相应<code>id="tooltip"</code> ,其中显示有关该区域的更多信息。 <strong>用户故事#11:</strong>我的工具提示应具有与活动区域的<code>data-value</code>对应的<code>data-value</code> <code>data-value</code>属性。对于此项目,您可以使用以下任何数据集: <br><ul><li> <strong>Kickstarter承诺:</strong> <code>https://cdn.rawgit.com/freeCodeCamp/testable-projects-fcc/a80ce8f9/src/data/tree_map/kickstarter-funding-data.json</code> <strong>:</strong> <code>https://cdn.rawgit.com/freeCodeCamp/testable-projects-fcc/a80ce8f9/src/data/tree_map/kickstarter-funding-data.json</code> </li><li> <strong>电影销售:</strong> <code>https://cdn.rawgit.com/freeCodeCamp/testable-projects-fcc/a80ce8f9/src/data/tree_map/movie-data.json</code> <strong>:</strong> <code>https://cdn.rawgit.com/freeCodeCamp/testable-projects-fcc/a80ce8f9/src/data/tree_map/movie-data.json</code> </li><li> <strong>视频游戏销售:</strong> <code>https://cdn.rawgit.com/freeCodeCamp/testable-projects-fcc/a80ce8f9/src/data/tree_map/video-game-sales-data.json</code> <strong>:</strong> <code>https://cdn.rawgit.com/freeCodeCamp/testable-projects-fcc/a80ce8f9/src/data/tree_map/video-game-sales-data.json</code> </li></ul>您可以通过分叉<a href="https://codepen.io/freeCodeCamp/pen/MJjpwO" target="_blank">此CodePen笔</a>来构建项目。或者您可以使用此CDN链接在您喜欢的任何环境中运行测试: <code>https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js</code> : <code>https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js</code>完成后,将URL提交给您的工作通过所有测试的项目。如果卡住,请记住使用<a href="https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask</a>方法。 </section>
<add><section id="description"> <strong>目标:</strong>构建一个功能类似于此的<a href="https://codepen.io" target="_blank">CodePen.io</a>应用程序: <a href="https://codepen.io/freeCodeCamp/full/KaNGNR" target="_blank">https</a> <strong>:</strong> <a href="https://codepen.io" target="_blank">//codepen.io/freeCodeCamp/full/KaNGNR</a> 。完成以下<a href="https://en.wikipedia.org/wiki/User_story" target="_blank">用户故事</a>并通过所有测试。给它你自己的个人风格。您可以使用HTML,JavaScript,CSS和基于D3 svg的可视化库。测试需要使用D3轴属性生成轴,该属性会自动生成沿轴的刻度。通过D3测试需要这些刻度,因为它们的位置用于确定绘制元素的对齐方式。有关生成轴的信息, <a href="https://github.com/d3/d3/blob/master/API.md#axes-d3-axis" target="_blank">请</a>访问<a href="https://github.com/d3/d3/blob/master/API.md#axes-d3-axis" target="_blank">https://github.com/d3/d3/blob/master/API.md#axes-d3-axis</a> 。在每次测试时查询必需(非虚拟)DOM元素。如果您使用前端框架(例如Vue),则测试结果可能对动态内容不准确。我们希望最终能够容纳它们,但D3项目目前不支持这些框架。 <strong>用户故事#1:</strong>我的树图应该有一个标题,对应的<code>id="title"</code> 。 <strong>用户故事#2:</strong>我的树图应该有一个对应<code>id="description"</code> 。 <strong>用户故事#3:</strong>我的树形图应该有一个<code>rect</code>元素,并且对应的<code>class="tile"</code>代表数据。 <strong>用户故事#4:</strong>瓷砖应至少有2种不同的填充颜色。 <strong>用户故事#5:</strong>每个瓷砖应具有属性<code>data-name</code> , <code>data-category</code> ,和<code>data-value</code>包含其相应的名称,类别,和值。 <strong>用户故事#6:</strong>每个图块的区域应对应于数据值量:具有较大数据值的图块应具有更大的区域。 <strong>用户故事#7:</strong>我的树形图应该有一个对应<code>id="legend"</code> 。 <strong>用户故事#8:</strong>我的图例应该有一个带有相应<code>class="legend-item"</code> <code>rect</code>元素。 <strong>用户故事#9:</strong>图例中的<code>rect</code>元素应使用至少2种不同的填充颜色。 <strong>用户故事#10:</strong>我可以将鼠标悬停在某个区域上,并查看带有相应<code>id="tooltip"</code> ,其中显示有关该区域的更多信息。 <strong>用户故事#11:</strong>我的工具提示应具有与活动区域的<code>data-value</code>对应的<code>data-value</code> <code>data-value</code>属性。对于此项目,您可以使用以下任何数据集: <br><ul><li> <strong>Kickstarter承诺:</strong> <code>https://cdn.freecodecamp.org/testable-projects-fcc/data/tree_map/kickstarter-funding-data.json</code> <strong>:</strong> <code>https://cdn.freecodecamp.org/testable-projects-fcc/data/tree_map/kickstarter-funding-data.json</code> </li><li> <strong>电影销售:</strong> <code>https://cdn.freecodecamp.org/testable-projects-fcc/data/tree_map/movie-data.json</code> <strong>:</strong> <code>https://cdn.freecodecamp.org/testable-projects-fcc/data/tree_map/movie-data.json</code> </li><li> <strong>视频游戏销售:</strong> <code>https://cdn.freecodecamp.org/testable-projects-fcc/data/tree_map/video-game-sales-data.json</code> <strong>:</strong> <code>https://cdn.freecodecamp.org/testable-projects-fcc/data/tree_map/video-game-sales-data.json</code> </li></ul>您可以通过分叉<a href="https://codepen.io/freeCodeCamp/pen/MJjpwO" target="_blank">此CodePen笔</a>来构建项目。或者您可以使用此CDN链接在您喜欢的任何环境中运行测试: <code>https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js</code> : <code>https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js</code>完成后,将URL提交给您的工作通过所有测试的项目。如果卡住,请记住使用<a href="https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask</a>方法。 </section>
<ide>
<ide> ## Instructions
<ide> <section id="instructions">
<ide><path>curriculum/challenges/english/04-data-visualization/data-visualization-projects/visualize-data-with-a-choropleth-map.english.md
<ide> You can use HTML, JavaScript, CSS, and the D3 svg-based visualization library. R
<ide> <strong>User Story #9:</strong> There should be at least 4 different fill colors used for the legend.
<ide> <strong>User Story #10:</strong> I can mouse over an area and see a tooltip with a corresponding <code>id="tooltip"</code> which displays more information about the area.
<ide> <strong>User Story #11:</strong> My tooltip should have a <code>data-education</code> property that corresponds to the <code>data-education</code> of the active area.
<del>Here are the datasets you will need to complete this project:<br><ul><li><strong>US Education Data: </strong><code>https://raw.githubusercontent.com/no-stack-dub-sack/testable-projects-fcc/master/src/data/choropleth_map/for_user_education.json</code></li><li><strong>US County Data: </strong><code>https://raw.githubusercontent.com/no-stack-dub-sack/testable-projects-fcc/master/src/data/choropleth_map/counties.json</code></li></ul>
<add>Here are the datasets you will need to complete this project:<br><ul><li><strong>US Education Data: </strong><code>https://cdn.freecodecamp.org/testable-projects-fcc/data/choropleth_map/for_user_education.json</code></li><li><strong>US County Data: </strong><code>https://cdn.freecodecamp.org/testable-projects-fcc/data/choropleth_map/counties.json</code></li></ul>
<ide> You can build your project by forking <a href='https://codepen.io/freeCodeCamp/pen/MJjpwO' target='_blank'>this CodePen pen</a>. Or you can use this CDN link to run the tests in any environment you like: <code>https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js</code>
<ide> Once you're done, submit the URL to your working project with all its tests passing.
<ide> Remember to use the <a href='https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514' target='_blank'>Read-Search-Ask</a> method if you get stuck.
<ide><path>curriculum/challenges/english/04-data-visualization/data-visualization-projects/visualize-data-with-a-treemap-diagram.english.md
<ide> You can use HTML, JavaScript, CSS, and the D3 svg-based visualization library. T
<ide> <strong>User Story #9:</strong> The <code>rect</code> elements in the legend should use at least 2 different fill colors.
<ide> <strong>User Story #10:</strong> I can mouse over an area and see a tooltip with a corresponding <code>id="tooltip"</code> which displays more information about the area.
<ide> <strong>User Story #11:</strong> My tooltip should have a <code>data-value</code> property that corresponds to the <code>data-value</code> of the active area.
<del>For this project you can use any of the following datasets:<br><ul><li><strong>Kickstarter Pledges:</strong> <code>https://cdn.rawgit.com/freeCodeCamp/testable-projects-fcc/a80ce8f9/src/data/tree_map/kickstarter-funding-data.json</code></li><li><strong>Movie Sales:</strong> <code>https://cdn.rawgit.com/freeCodeCamp/testable-projects-fcc/a80ce8f9/src/data/tree_map/movie-data.json</code></li><li><strong>Video Game Sales:</strong> <code>https://cdn.rawgit.com/freeCodeCamp/testable-projects-fcc/a80ce8f9/src/data/tree_map/video-game-sales-data.json</code></li></ul>
<add>For this project you can use any of the following datasets:<br><ul><li><strong>Kickstarter Pledges:</strong> <code>https://cdn.freecodecamp.org/testable-projects-fcc/data/tree_map/kickstarter-funding-data.json</code></li><li><strong>Movie Sales:</strong> <code>https://cdn.freecodecamp.org/testable-projects-fcc/data/tree_map/movie-data.json</code></li><li><strong>Video Game Sales:</strong> <code>https://cdn.freecodecamp.org/testable-projects-fcc/data/tree_map/video-game-sales-data.json</code></li></ul>
<ide> You can build your project by forking <a href='https://codepen.io/freeCodeCamp/pen/MJjpwO' target='_blank'>this CodePen pen</a>. Or you can use this CDN link to run the tests in any environment you like: <code>https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js</code>
<ide> Once you're done, submit the URL to your working project with all its tests passing.
<ide> Remember to use the <a href='https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514' target='_blank'>Read-Search-Ask</a> method if you get stuck.
<ide><path>curriculum/challenges/portuguese/04-data-visualization/data-visualization-projects/visualize-data-with-a-choropleth-map.portuguese.md
<ide> localeTitle: Visualize dados com um mapa coroplético
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> <strong>Objetivo:</strong> criar um aplicativo <a href="https://codepen.io" target="_blank">CodePen.io</a> que seja funcionalmente semelhante a este: <a href="https://codepen.io/freeCodeCamp/full/EZKqza" target="_blank">https://codepen.io/freeCodeCamp/full/EZKqza</a> . Cumpra as <a href="https://en.wikipedia.org/wiki/User_story" target="_blank">histórias de usuário</a> abaixo e faça todos os testes para passar. Dê seu estilo pessoal. Você pode usar HTML, JavaScript, CSS e a biblioteca de visualização baseada em svg D3. Elementos DOM (não virtuais) requeridos são consultados no momento de cada teste. Se você usar uma estrutura frontend (como o Vue, por exemplo), os resultados do teste podem ser imprecisos para o conteúdo dinâmico. Esperamos acomodá-los eventualmente, mas esses frameworks não são suportados atualmente para projetos D3. <strong>História do usuário nº 1:</strong> Meu choropleth deve ter um título com um <code>id="title"</code> . <strong>História do usuário nº 2:</strong> Meu choropleth deve ter um elemento de descrição com um <code>id="description"</code> . <strong>História do usuário nº 3:</strong> Meu choropleth deve ter condados com uma <code>class="county"</code> correspondente <code>class="county"</code> que represente os dados. <strong>História do usuário nº 4:</strong> deve haver pelo menos quatro cores de preenchimento diferentes usadas para os municípios. <strong>História do usuário # 5:</strong> Meus municípios devem ter propriedades de <code>data-fips</code> e <code>data-education</code> contendo seus valores de educação e fips correspondentes. <strong>História do Usuário # 6:</strong> Meu coroplópio deve ter um condado para cada ponto de dados fornecido. <strong>História do usuário nº 7:</strong> os municípios devem ter dados-fips e valores de dados-educação que correspondam aos dados da amostra. <strong>História do usuário nº 8:</strong> Meu choropleth deve ter uma legenda com um <code>id="legend"</code> . <strong>História do usuário nº 9:</strong> Deve haver pelo menos 4 cores de preenchimento diferentes usadas para a legenda. <strong>História do usuário nº 10:</strong> Eu posso passar o mouse sobre uma área e ver uma dica de ferramenta com um <code>id="tooltip"</code> que exibe mais informações sobre a área. <strong>História do usuário nº 11:</strong> Minha dica de ferramenta deve ter uma propriedade de <code>data-education</code> que corresponda à <code>data-education</code> da área ativa. Aqui estão os conjuntos de dados necessários para concluir este projeto: <br><ul><li> <strong>Dados educacionais dos EUA:</strong> <code>https://raw.githubusercontent.com/no-stack-dub-sack/testable-projects-fcc/master/src/data/choropleth_map/for_user_education.json</code> </li><li> <strong>Dados do Condado dos EUA:</strong> <code>https://raw.githubusercontent.com/no-stack-dub-sack/testable-projects-fcc/master/src/data/choropleth_map/counties.json</code> </li></ul> Você pode criar seu projeto, bifurcando <a href="https://codepen.io/freeCodeCamp/pen/MJjpwO" target="_blank">essa caneta CodePen</a> . Ou você pode usar este link CDN para executar os testes em qualquer ambiente que desejar: <code>https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js</code> Quando terminar, envie a URL para o seu trabalho. projeto com todos os seus testes passando. Lembre-se de usar o método <a href="https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask</a> se você ficar preso. </section>
<add><section id="description"> <strong>Objetivo:</strong> criar um aplicativo <a href="https://codepen.io" target="_blank">CodePen.io</a> que seja funcionalmente semelhante a este: <a href="https://codepen.io/freeCodeCamp/full/EZKqza" target="_blank">https://codepen.io/freeCodeCamp/full/EZKqza</a> . Cumpra as <a href="https://en.wikipedia.org/wiki/User_story" target="_blank">histórias de usuário</a> abaixo e faça todos os testes para passar. Dê seu estilo pessoal. Você pode usar HTML, JavaScript, CSS e a biblioteca de visualização baseada em svg D3. Elementos DOM (não virtuais) requeridos são consultados no momento de cada teste. Se você usar uma estrutura frontend (como o Vue, por exemplo), os resultados do teste podem ser imprecisos para o conteúdo dinâmico. Esperamos acomodá-los eventualmente, mas esses frameworks não são suportados atualmente para projetos D3. <strong>História do usuário nº 1:</strong> Meu choropleth deve ter um título com um <code>id="title"</code> . <strong>História do usuário nº 2:</strong> Meu choropleth deve ter um elemento de descrição com um <code>id="description"</code> . <strong>História do usuário nº 3:</strong> Meu choropleth deve ter condados com uma <code>class="county"</code> correspondente <code>class="county"</code> que represente os dados. <strong>História do usuário nº 4:</strong> deve haver pelo menos quatro cores de preenchimento diferentes usadas para os municípios. <strong>História do usuário # 5:</strong> Meus municípios devem ter propriedades de <code>data-fips</code> e <code>data-education</code> contendo seus valores de educação e fips correspondentes. <strong>História do Usuário # 6:</strong> Meu coroplópio deve ter um condado para cada ponto de dados fornecido. <strong>História do usuário nº 7:</strong> os municípios devem ter dados-fips e valores de dados-educação que correspondam aos dados da amostra. <strong>História do usuário nº 8:</strong> Meu choropleth deve ter uma legenda com um <code>id="legend"</code> . <strong>História do usuário nº 9:</strong> Deve haver pelo menos 4 cores de preenchimento diferentes usadas para a legenda. <strong>História do usuário nº 10:</strong> Eu posso passar o mouse sobre uma área e ver uma dica de ferramenta com um <code>id="tooltip"</code> que exibe mais informações sobre a área. <strong>História do usuário nº 11:</strong> Minha dica de ferramenta deve ter uma propriedade de <code>data-education</code> que corresponda à <code>data-education</code> da área ativa. Aqui estão os conjuntos de dados necessários para concluir este projeto: <br><ul><li> <strong>Dados educacionais dos EUA:</strong> <code>https://cdn.freecodecamp.org/testable-projects-fcc/data/choropleth_map/for_user_education.json</code> </li><li> <strong>Dados do Condado dos EUA:</strong> <code>https://cdn.freecodecamp.org/testable-projects-fcc/data/choropleth_map/counties.json</code> </li></ul> Você pode criar seu projeto, bifurcando <a href="https://codepen.io/freeCodeCamp/pen/MJjpwO" target="_blank">essa caneta CodePen</a> . Ou você pode usar este link CDN para executar os testes em qualquer ambiente que desejar: <code>https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js</code> Quando terminar, envie a URL para o seu trabalho. projeto com todos os seus testes passando. Lembre-se de usar o método <a href="https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask</a> se você ficar preso. </section>
<ide>
<ide> ## Instructions
<ide> <section id="instructions">
<ide><path>curriculum/challenges/portuguese/04-data-visualization/data-visualization-projects/visualize-data-with-a-treemap-diagram.portuguese.md
<ide> localeTitle: Visualize dados com um diagrama de mapa de árvore
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> <strong>Objetivo:</strong> criar um aplicativo <a href="https://codepen.io" target="_blank">CodePen.io</a> que seja funcionalmente semelhante a este: <a href="https://codepen.io/freeCodeCamp/full/KaNGNR" target="_blank">https://codepen.io/freeCodeCamp/full/KaNGNR</a> . Cumpra as <a href="https://en.wikipedia.org/wiki/User_story" target="_blank">histórias de usuário</a> abaixo e faça todos os testes para passar. Dê seu estilo pessoal. Você pode usar HTML, JavaScript, CSS e a biblioteca de visualização baseada em svg D3. Os testes exigem que os eixos sejam gerados usando a propriedade do eixo D3, que gera automaticamente marcações ao longo do eixo. Esses tiques são necessários para passar nos testes D3, porque suas posições são usadas para determinar o alinhamento dos elementos gráficos. Você encontrará informações sobre como gerar eixos em <a href="https://github.com/d3/d3/blob/master/API.md#axes-d3-axis" target="_blank">https://github.com/d3/d3/blob/master/API.md#axes-d3-axis</a> . Elementos DOM (não virtuais) requeridos são consultados no momento de cada teste. Se você usar uma estrutura frontend (como o Vue, por exemplo), os resultados do teste podem ser imprecisos para o conteúdo dinâmico. Esperamos acomodá-los eventualmente, mas esses frameworks não são suportados atualmente para projetos D3. <strong>User Story # 1:</strong> Meu mapa da árvore deve ter um título com um <code>id="title"</code> . <strong>User Story # 2:</strong> Meu mapa de árvore deve ter uma descrição com um <code>id="description"</code> . <strong>User Story # 3:</strong> Meu mapa de árvore deve ter elementos <code>rect</code> com uma <code>class="tile"</code> que representa os dados. <strong>História do usuário nº 4:</strong> deve haver pelo menos duas cores de preenchimento diferentes usadas para as peças. <strong>História do usuário nº 5:</strong> Cada bloco deve ter as propriedades <code>data-name</code> , <code>data-category</code> e <code>data-value</code> contendo seu nome, categoria e valor correspondentes. <strong>História do usuário nº 6:</strong> a área de cada bloco deve corresponder ao valor do valor dos dados: blocos com um valor de dados maior devem ter uma área maior. <strong>User Story # 7:</strong> Meu mapa da árvore deve ter uma legenda com <code>id="legend"</code> . <strong>User Story # 8:</strong> Minha legenda deve ter elementos <code>rect</code> com uma <code>class="legend-item"</code> . <strong>User Story # 9:</strong> Os elementos <code>rect</code> na legenda devem usar pelo menos 2 cores de preenchimento diferentes. <strong>User Story # 10:</strong> Eu posso passar o mouse sobre uma área e ver uma dica de ferramenta com um <code>id="tooltip"</code> que exibe mais informações sobre a área. <strong>User Story # 11:</strong> minha dica de ferramenta deve ter uma propriedade de <code>data-value</code> que corresponda ao <code>data-value</code> de <code>data-value</code> da área ativa. Para este projeto, você pode usar qualquer um dos seguintes conjuntos de dados: <br><ul><li> <strong>Promessas do Kickstarter:</strong> <code>https://cdn.rawgit.com/freeCodeCamp/testable-projects-fcc/a80ce8f9/src/data/tree_map/kickstarter-funding-data.json</code> </li><li> <strong>Vendas de filmes:</strong> <code>https://cdn.rawgit.com/freeCodeCamp/testable-projects-fcc/a80ce8f9/src/data/tree_map/movie-data.json</code> </li><li> <strong>Vendas de videogames:</strong> <code>https://cdn.rawgit.com/freeCodeCamp/testable-projects-fcc/a80ce8f9/src/data/tree_map/video-game-sales-data.json</code> </li></ul> Você pode criar seu projeto, bifurcando <a href="https://codepen.io/freeCodeCamp/pen/MJjpwO" target="_blank">essa caneta CodePen</a> . Ou você pode usar este link CDN para executar os testes em qualquer ambiente que desejar: <code>https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js</code> Quando terminar, envie a URL para o seu trabalho. projeto com todos os seus testes passando. Lembre-se de usar o método <a href="https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask</a> se você ficar preso. </section>
<add><section id="description"> <strong>Objetivo:</strong> criar um aplicativo <a href="https://codepen.io" target="_blank">CodePen.io</a> que seja funcionalmente semelhante a este: <a href="https://codepen.io/freeCodeCamp/full/KaNGNR" target="_blank">https://codepen.io/freeCodeCamp/full/KaNGNR</a> . Cumpra as <a href="https://en.wikipedia.org/wiki/User_story" target="_blank">histórias de usuário</a> abaixo e faça todos os testes para passar. Dê seu estilo pessoal. Você pode usar HTML, JavaScript, CSS e a biblioteca de visualização baseada em svg D3. Os testes exigem que os eixos sejam gerados usando a propriedade do eixo D3, que gera automaticamente marcações ao longo do eixo. Esses tiques são necessários para passar nos testes D3, porque suas posições são usadas para determinar o alinhamento dos elementos gráficos. Você encontrará informações sobre como gerar eixos em <a href="https://github.com/d3/d3/blob/master/API.md#axes-d3-axis" target="_blank">https://github.com/d3/d3/blob/master/API.md#axes-d3-axis</a> . Elementos DOM (não virtuais) requeridos são consultados no momento de cada teste. Se você usar uma estrutura frontend (como o Vue, por exemplo), os resultados do teste podem ser imprecisos para o conteúdo dinâmico. Esperamos acomodá-los eventualmente, mas esses frameworks não são suportados atualmente para projetos D3. <strong>User Story # 1:</strong> Meu mapa da árvore deve ter um título com um <code>id="title"</code> . <strong>User Story # 2:</strong> Meu mapa de árvore deve ter uma descrição com um <code>id="description"</code> . <strong>User Story # 3:</strong> Meu mapa de árvore deve ter elementos <code>rect</code> com uma <code>class="tile"</code> que representa os dados. <strong>História do usuário nº 4:</strong> deve haver pelo menos duas cores de preenchimento diferentes usadas para as peças. <strong>História do usuário nº 5:</strong> Cada bloco deve ter as propriedades <code>data-name</code> , <code>data-category</code> e <code>data-value</code> contendo seu nome, categoria e valor correspondentes. <strong>História do usuário nº 6:</strong> a área de cada bloco deve corresponder ao valor do valor dos dados: blocos com um valor de dados maior devem ter uma área maior. <strong>User Story # 7:</strong> Meu mapa da árvore deve ter uma legenda com <code>id="legend"</code> . <strong>User Story # 8:</strong> Minha legenda deve ter elementos <code>rect</code> com uma <code>class="legend-item"</code> . <strong>User Story # 9:</strong> Os elementos <code>rect</code> na legenda devem usar pelo menos 2 cores de preenchimento diferentes. <strong>User Story # 10:</strong> Eu posso passar o mouse sobre uma área e ver uma dica de ferramenta com um <code>id="tooltip"</code> que exibe mais informações sobre a área. <strong>User Story # 11:</strong> minha dica de ferramenta deve ter uma propriedade de <code>data-value</code> que corresponda ao <code>data-value</code> de <code>data-value</code> da área ativa. Para este projeto, você pode usar qualquer um dos seguintes conjuntos de dados: <br><ul><li> <strong>Promessas do Kickstarter:</strong> <code>https://cdn.freecodecamp.org/testable-projects-fcc/data/tree_map/kickstarter-funding-data.json</code> </li><li> <strong>Vendas de filmes:</strong> <code>https://cdn.freecodecamp.org/testable-projects-fcc/data/tree_map/movie-data.json</code> </li><li> <strong>Vendas de videogames:</strong> <code>https://cdn.freecodecamp.org/testable-projects-fcc/data/tree_map/video-game-sales-data.json</code> </li></ul> Você pode criar seu projeto, bifurcando <a href="https://codepen.io/freeCodeCamp/pen/MJjpwO" target="_blank">essa caneta CodePen</a> . Ou você pode usar este link CDN para executar os testes em qualquer ambiente que desejar: <code>https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js</code> Quando terminar, envie a URL para o seu trabalho. projeto com todos os seus testes passando. Lembre-se de usar o método <a href="https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask</a> se você ficar preso. </section>
<ide>
<ide> ## Instructions
<ide> <section id="instructions">
<ide><path>curriculum/challenges/russian/04-data-visualization/data-visualization-projects/visualize-data-with-a-choropleth-map.russian.md
<ide> localeTitle: Визуализация данных с помощью карты
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> <strong>Цель:</strong> создать приложение <a href="https://codepen.io" target="_blank">CodePen.io</a> , функционально похожее на это: <a href="https://codepen.io/freeCodeCamp/full/EZKqza" target="_blank">https://codepen.io/freeCodeCamp/full/EZKqza</a> . Выполните приведенные ниже <a href="https://en.wikipedia.org/wiki/User_story" target="_blank">истории пользователей</a> и получите все тесты для прохождения. Дайте ему свой личный стиль. Вы можете использовать HTML, JavaScript, CSS и D3 svg-based visualization library. Обязательные (не виртуальные) элементы DOM запрашиваются в момент каждого теста. Если вы используете фреймворк интерфейса (например, Vue), результаты теста могут быть неточными для динамического содержимого. Мы надеемся, что в конечном итоге их разместим, но эти рамки в настоящее время не поддерживаются для проектов D3. <strong>User Story # 1:</strong> Мой choropleth должен иметь заголовок с соответствующим <code>id="title"</code> . <strong>User Story # 2: У</strong> моего choropleth должен быть элемент описания с соответствующим <code>id="description"</code> . <strong>User Story # 3:</strong> Мой choropleth должен иметь графства с соответствующим <code>class="county"</code> которые представляют данные. <strong>User Story # 4:</strong> должно быть не менее 4 разных цветов заливки, используемых для округов. <strong>User Story # 5:</strong> Мои округа должны иметь характеристики <code>data-fips</code> и <code>data-education</code> имеющие соответствующие значения fips и education. <strong>User Story # 6:</strong> Мой choropleth должен иметь графство для каждой предоставленной точки данных. <strong>User Story # 7:</strong> В округах должны быть значения данных и данных, которые соответствуют данным образца. <strong>User Story # 8:</strong> Мой choropleth должен иметь легенду с соответствующим <code>id="legend"</code> . <strong>User Story # 9:</strong> Для легенды должно быть не менее 4 различных цветов заливки. <strong>User Story # 10:</strong> Я могу навести курсор мыши на область и увидеть всплывающую подсказку с соответствующей <code>id="tooltip"</code> которая отображает больше информации о области. <strong>User Story # 11:</strong> Моя подсказка должна иметь свойство <code>data-education</code> которое соответствует <code>data-education</code> данных в активной области. Вот данные, которые вам нужно будет выполнить для этого проекта: <br><ul><li> <strong>Данные об образовании в США:</strong> <code>https://raw.githubusercontent.com/no-stack-dub-sack/testable-projects-fcc/master/src/data/choropleth_map/for_user_education.json</code> </li><li> <strong>Данные графства США:</strong> <code>https://raw.githubusercontent.com/no-stack-dub-sack/testable-projects-fcc/master/src/data/choropleth_map/counties.json</code> </li></ul> Вы можете создать свой проект, <a href="https://codepen.io/freeCodeCamp/pen/MJjpwO" target="_blank">нажимая эту ручку CodePen</a> . Или вы можете использовать эту ссылку CDN для запуска тестов в любой среде: <code>https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js</code> Как только вы закончите, отправьте URL-адрес своей рабочей проект с прохождением всех его тестов. Не забудьте использовать метод <a href="https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask,</a> если вы застряли. </section>
<add><section id="description"> <strong>Цель:</strong> создать приложение <a href="https://codepen.io" target="_blank">CodePen.io</a> , функционально похожее на это: <a href="https://codepen.io/freeCodeCamp/full/EZKqza" target="_blank">https://codepen.io/freeCodeCamp/full/EZKqza</a> . Выполните приведенные ниже <a href="https://en.wikipedia.org/wiki/User_story" target="_blank">истории пользователей</a> и получите все тесты для прохождения. Дайте ему свой личный стиль. Вы можете использовать HTML, JavaScript, CSS и D3 svg-based visualization library. Обязательные (не виртуальные) элементы DOM запрашиваются в момент каждого теста. Если вы используете фреймворк интерфейса (например, Vue), результаты теста могут быть неточными для динамического содержимого. Мы надеемся, что в конечном итоге их разместим, но эти рамки в настоящее время не поддерживаются для проектов D3. <strong>User Story # 1:</strong> Мой choropleth должен иметь заголовок с соответствующим <code>id="title"</code> . <strong>User Story # 2: У</strong> моего choropleth должен быть элемент описания с соответствующим <code>id="description"</code> . <strong>User Story # 3:</strong> Мой choropleth должен иметь графства с соответствующим <code>class="county"</code> которые представляют данные. <strong>User Story # 4:</strong> должно быть не менее 4 разных цветов заливки, используемых для округов. <strong>User Story # 5:</strong> Мои округа должны иметь характеристики <code>data-fips</code> и <code>data-education</code> имеющие соответствующие значения fips и education. <strong>User Story # 6:</strong> Мой choropleth должен иметь графство для каждой предоставленной точки данных. <strong>User Story # 7:</strong> В округах должны быть значения данных и данных, которые соответствуют данным образца. <strong>User Story # 8:</strong> Мой choropleth должен иметь легенду с соответствующим <code>id="legend"</code> . <strong>User Story # 9:</strong> Для легенды должно быть не менее 4 различных цветов заливки. <strong>User Story # 10:</strong> Я могу навести курсор мыши на область и увидеть всплывающую подсказку с соответствующей <code>id="tooltip"</code> которая отображает больше информации о области. <strong>User Story # 11:</strong> Моя подсказка должна иметь свойство <code>data-education</code> которое соответствует <code>data-education</code> данных в активной области. Вот данные, которые вам нужно будет выполнить для этого проекта: <br><ul><li> <strong>Данные об образовании в США:</strong> <code>https://cdn.freecodecamp.org/testable-projects-fcc/data/choropleth_map/for_user_education.json</code> </li><li> <strong>Данные графства США:</strong> <code>https://cdn.freecodecamp.org/testable-projects-fcc/data/choropleth_map/counties.json</code> </li></ul> Вы можете создать свой проект, <a href="https://codepen.io/freeCodeCamp/pen/MJjpwO" target="_blank">нажимая эту ручку CodePen</a> . Или вы можете использовать эту ссылку CDN для запуска тестов в любой среде: <code>https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js</code> Как только вы закончите, отправьте URL-адрес своей рабочей проект с прохождением всех его тестов. Не забудьте использовать метод <a href="https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask,</a> если вы застряли. </section>
<ide>
<ide> ## Instructions
<ide> <section id="instructions">
<ide><path>curriculum/challenges/russian/04-data-visualization/data-visualization-projects/visualize-data-with-a-treemap-diagram.russian.md
<ide> localeTitle: Визуализация данных с диаграммой ка
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> <strong>Цель:</strong> создать приложение <a href="https://codepen.io" target="_blank">CodePen.io</a> , функционально похожее на это: <a href="https://codepen.io/freeCodeCamp/full/KaNGNR" target="_blank">https://codepen.io/freeCodeCamp/full/KaNGNR</a> . Выполните приведенные ниже <a href="https://en.wikipedia.org/wiki/User_story" target="_blank">истории пользователей</a> и получите все тесты для прохождения. Дайте ему свой личный стиль. Вы можете использовать HTML, JavaScript, CSS и D3 svg-based visualization library. Тесты требуют создания осей с использованием свойства оси D3, которое автоматически генерирует тики вдоль оси. Эти тики необходимы для прохождения тестов D3, потому что их позиции используются для определения выравнивания графических элементов. Вы найдете информацию о генерации осей на <a href="https://github.com/d3/d3/blob/master/API.md#axes-d3-axis" target="_blank">странице https://github.com/d3/d3/blob/master/API.md#axes-d3-axis</a> . Обязательные (не виртуальные) элементы DOM запрашиваются в момент каждого теста. Если вы используете фреймворк интерфейса (например, Vue), результаты теста могут быть неточными для динамического содержимого. Мы надеемся, что в конечном итоге их разместим, но эти рамки в настоящее время не поддерживаются для проектов D3. <strong>User Story # 1:</strong> Моя карта дерева должна иметь заголовок с соответствующим <code>id="title"</code> . <strong>User Story # 2:</strong> Моя древовидная карта должна иметь описание с соответствующим <code>id="description"</code> . <strong>User Story # 3:</strong> Моя карта деревьев должна иметь <code>rect</code> элементы с соответствующим <code>class="tile"</code> которые представляют данные. <strong>User Story # 4:</strong> Для плиток должно быть не менее двух разных цветов заливки. <strong>User Story # 5:</strong> Каждая плитка должна иметь свойства <code>data-name</code> , <code>data-category</code> и <code>data-value</code> содержащие их соответствующее имя, категорию и значение. <strong>User Story # 6:</strong> Площадь каждой плитки должна соответствовать размеру данных: плитки с большим значением данных должны иметь большую площадь. <strong>User Story # 7:</strong> Моя карта деревьев должна иметь легенду с соответствующим <code>id="legend"</code> . <strong>User Story # 8:</strong> Моя легенда должна иметь <code>rect</code> элементы с соответствующим <code>class="legend-item"</code> . <strong>User Story # 9:</strong> <code>rect</code> элементы в легенде должны использовать как минимум 2 разных цвета заливки. <strong>User Story # 10:</strong> Я могу навести курсор мыши на область и увидеть всплывающую подсказку с соответствующей <code>id="tooltip"</code> которая отображает больше информации о области. <strong>User Story # 11:</strong> Моя подсказка должна иметь свойство <code>data-value</code> , соответствующее <code>data-value</code> данных активной области. Для этого проекта вы можете использовать любой из следующих наборов данных: <br><ul><li> <strong>Kickstarter Pledges:</strong> <code>https://cdn.rawgit.com/freeCodeCamp/testable-projects-fcc/a80ce8f9/src/data/tree_map/kickstarter-funding-data.json</code> </li><li> <strong>Продажа фильмов:</strong> <code>https://cdn.rawgit.com/freeCodeCamp/testable-projects-fcc/a80ce8f9/src/data/tree_map/movie-data.json</code> </li><li> <strong>Продажа видеоигр:</strong> <code>https://cdn.rawgit.com/freeCodeCamp/testable-projects-fcc/a80ce8f9/src/data/tree_map/video-game-sales-data.json</code> </li></ul> Вы можете создать свой проект, <a href="https://codepen.io/freeCodeCamp/pen/MJjpwO" target="_blank">нажимая эту ручку CodePen</a> . Или вы можете использовать эту ссылку CDN для запуска тестов в любой среде: <code>https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js</code> Как только вы закончите, отправьте URL-адрес своей рабочей проект с прохождением всех его тестов. Не забудьте использовать метод <a href="https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask,</a> если вы застряли. </section>
<add><section id="description"> <strong>Цель:</strong> создать приложение <a href="https://codepen.io" target="_blank">CodePen.io</a> , функционально похожее на это: <a href="https://codepen.io/freeCodeCamp/full/KaNGNR" target="_blank">https://codepen.io/freeCodeCamp/full/KaNGNR</a> . Выполните приведенные ниже <a href="https://en.wikipedia.org/wiki/User_story" target="_blank">истории пользователей</a> и получите все тесты для прохождения. Дайте ему свой личный стиль. Вы можете использовать HTML, JavaScript, CSS и D3 svg-based visualization library. Тесты требуют создания осей с использованием свойства оси D3, которое автоматически генерирует тики вдоль оси. Эти тики необходимы для прохождения тестов D3, потому что их позиции используются для определения выравнивания графических элементов. Вы найдете информацию о генерации осей на <a href="https://github.com/d3/d3/blob/master/API.md#axes-d3-axis" target="_blank">странице https://github.com/d3/d3/blob/master/API.md#axes-d3-axis</a> . Обязательные (не виртуальные) элементы DOM запрашиваются в момент каждого теста. Если вы используете фреймворк интерфейса (например, Vue), результаты теста могут быть неточными для динамического содержимого. Мы надеемся, что в конечном итоге их разместим, но эти рамки в настоящее время не поддерживаются для проектов D3. <strong>User Story # 1:</strong> Моя карта дерева должна иметь заголовок с соответствующим <code>id="title"</code> . <strong>User Story # 2:</strong> Моя древовидная карта должна иметь описание с соответствующим <code>id="description"</code> . <strong>User Story # 3:</strong> Моя карта деревьев должна иметь <code>rect</code> элементы с соответствующим <code>class="tile"</code> которые представляют данные. <strong>User Story # 4:</strong> Для плиток должно быть не менее двух разных цветов заливки. <strong>User Story # 5:</strong> Каждая плитка должна иметь свойства <code>data-name</code> , <code>data-category</code> и <code>data-value</code> содержащие их соответствующее имя, категорию и значение. <strong>User Story # 6:</strong> Площадь каждой плитки должна соответствовать размеру данных: плитки с большим значением данных должны иметь большую площадь. <strong>User Story # 7:</strong> Моя карта деревьев должна иметь легенду с соответствующим <code>id="legend"</code> . <strong>User Story # 8:</strong> Моя легенда должна иметь <code>rect</code> элементы с соответствующим <code>class="legend-item"</code> . <strong>User Story # 9:</strong> <code>rect</code> элементы в легенде должны использовать как минимум 2 разных цвета заливки. <strong>User Story # 10:</strong> Я могу навести курсор мыши на область и увидеть всплывающую подсказку с соответствующей <code>id="tooltip"</code> которая отображает больше информации о области. <strong>User Story # 11:</strong> Моя подсказка должна иметь свойство <code>data-value</code> , соответствующее <code>data-value</code> данных активной области. Для этого проекта вы можете использовать любой из следующих наборов данных: <br><ul><li> <strong>Kickstarter Pledges:</strong> <code>https://cdn.freecodecamp.org/testable-projects-fcc/data/tree_map/kickstarter-funding-data.json</code> </li><li> <strong>Продажа фильмов:</strong> <code>https://cdn.freecodecamp.org/testable-projects-fcc/data/tree_map/movie-data.json</code> </li><li> <strong>Продажа видеоигр:</strong> <code>https://cdn.freecodecamp.org/testable-projects-fcc/data/tree_map/video-game-sales-data.json</code> </li></ul> Вы можете создать свой проект, <a href="https://codepen.io/freeCodeCamp/pen/MJjpwO" target="_blank">нажимая эту ручку CodePen</a> . Или вы можете использовать эту ссылку CDN для запуска тестов в любой среде: <code>https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js</code> Как только вы закончите, отправьте URL-адрес своей рабочей проект с прохождением всех его тестов. Не забудьте использовать метод <a href="https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask,</a> если вы застряли. </section>
<ide>
<ide> ## Instructions
<ide> undefined
<ide><path>curriculum/challenges/spanish/04-data-visualization/data-visualization-projects/visualize-data-with-a-choropleth-map.spanish.md
<ide> localeTitle: Visualice datos con un mapa de coropletas
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> <strong>Objetivo:</strong> crear una aplicación <a href="https://codepen.io" target="_blank">CodePen.io</a> que sea funcionalmente similar a esta: <a href="https://codepen.io/freeCodeCamp/full/EZKqza" target="_blank">https://codepen.io/freeCodeCamp/full/EZKqza</a> . Cumple las siguientes <a href="https://en.wikipedia.org/wiki/User_story" target="_blank">historias de usuario</a> y haz que pasen todas las pruebas. Dale tu propio estilo personal. Puede utilizar HTML, JavaScript, CSS y la biblioteca de visualización basada en svg D3. Los elementos DOM (no virtuales) requeridos se consultan en el momento de cada prueba. Si usa un marco de frontend (como Vue, por ejemplo), los resultados de la prueba pueden ser inexactos para el contenido dinámico. Esperamos acomodarlos eventualmente, pero estos marcos no están actualmente soportados para proyectos D3. <strong>Historia de usuario n. ° 1:</strong> Mi coropleta debe tener un título con una <code>id="title"</code> correspondiente <code>id="title"</code> . <strong>Historia de usuario n. ° 2:</strong> Mi choropleth debe tener un elemento de descripción con un <code>id="description"</code> . <strong>Historia de usuario n. ° 3:</strong> Mi coropleta debe tener condados con una <code>class="county"</code> correspondiente <code>class="county"</code> que represente los datos. <strong>Historia de usuario n. ° 4:</strong> Debe haber al menos 4 colores de relleno diferentes utilizados para los condados. <strong>Historia de usuario n. ° 5:</strong> Mis condados deben tener cada uno <code>data-fips</code> y propiedades de <code>data-education</code> contengan sus fips y valores de educación correspondientes. <strong>Historia de usuario n. ° 6:</strong> Mi coropleta debe tener un condado para cada punto de datos proporcionado. <strong>Historia de usuario n. ° 7:</strong> Los condados deben tener datos de fips y valores de educación de datos que coincidan con los datos de muestra. <strong>Historia de usuario n. ° 8:</strong> Mi coropleta debe tener una leyenda con su correspondiente <code>id="legend"</code> . <strong>Historia de usuario n. ° 9:</strong> Debe haber al menos 4 colores de relleno diferentes utilizados para la leyenda. <strong>Historia de usuario n. ° 10:</strong> puedo pasar el mouse sobre un área y ver una información sobre herramientas con la correspondiente <code>id="tooltip"</code> que muestra más información sobre el área. <strong>Historia de usuario n. ° 11:</strong> Mi información sobre herramientas debe tener una propiedad de <code>data-education</code> que corresponda a la <code>data-education</code> de <code>data-education</code> del área activa. Aquí están los conjuntos de datos que necesitará para completar este proyecto: <br><ul><li> <strong>Datos de educación de los Estados Unidos:</strong> <code>https://raw.githubusercontent.com/no-stack-dub-sack/testable-projects-fcc/master/src/data/choropleth_map/for_user_education.json</code> </li><li> <strong>Datos del condado de EE. UU .:</strong> <code>https://raw.githubusercontent.com/no-stack-dub-sack/testable-projects-fcc/master/src/data/choropleth_map/counties.json</code> </li></ul> Puedes construir tu proyecto por medio de <a href="https://codepen.io/freeCodeCamp/pen/MJjpwO" target="_blank">este bolígrafo CodePen</a> . O puede usar este enlace CDN para ejecutar las pruebas en el entorno que desee: <code>https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js</code> Una vez que haya terminado, envíe la URL a su cuenta Proyecto con todas sus pruebas aprobadas. Recuerda usar el método de <a href="https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">lectura-búsqueda-pregunta</a> si te atascas. </section>
<add><section id="description"> <strong>Objetivo:</strong> crear una aplicación <a href="https://codepen.io" target="_blank">CodePen.io</a> que sea funcionalmente similar a esta: <a href="https://codepen.io/freeCodeCamp/full/EZKqza" target="_blank">https://codepen.io/freeCodeCamp/full/EZKqza</a> . Cumple las siguientes <a href="https://en.wikipedia.org/wiki/User_story" target="_blank">historias de usuario</a> y haz que pasen todas las pruebas. Dale tu propio estilo personal. Puede utilizar HTML, JavaScript, CSS y la biblioteca de visualización basada en svg D3. Los elementos DOM (no virtuales) requeridos se consultan en el momento de cada prueba. Si usa un marco de frontend (como Vue, por ejemplo), los resultados de la prueba pueden ser inexactos para el contenido dinámico. Esperamos acomodarlos eventualmente, pero estos marcos no están actualmente soportados para proyectos D3. <strong>Historia de usuario n. ° 1:</strong> Mi coropleta debe tener un título con una <code>id="title"</code> correspondiente <code>id="title"</code> . <strong>Historia de usuario n. ° 2:</strong> Mi choropleth debe tener un elemento de descripción con un <code>id="description"</code> . <strong>Historia de usuario n. ° 3:</strong> Mi coropleta debe tener condados con una <code>class="county"</code> correspondiente <code>class="county"</code> que represente los datos. <strong>Historia de usuario n. ° 4:</strong> Debe haber al menos 4 colores de relleno diferentes utilizados para los condados. <strong>Historia de usuario n. ° 5:</strong> Mis condados deben tener cada uno <code>data-fips</code> y propiedades de <code>data-education</code> contengan sus fips y valores de educación correspondientes. <strong>Historia de usuario n. ° 6:</strong> Mi coropleta debe tener un condado para cada punto de datos proporcionado. <strong>Historia de usuario n. ° 7:</strong> Los condados deben tener datos de fips y valores de educación de datos que coincidan con los datos de muestra. <strong>Historia de usuario n. ° 8:</strong> Mi coropleta debe tener una leyenda con su correspondiente <code>id="legend"</code> . <strong>Historia de usuario n. ° 9:</strong> Debe haber al menos 4 colores de relleno diferentes utilizados para la leyenda. <strong>Historia de usuario n. ° 10:</strong> puedo pasar el mouse sobre un área y ver una información sobre herramientas con la correspondiente <code>id="tooltip"</code> que muestra más información sobre el área. <strong>Historia de usuario n. ° 11:</strong> Mi información sobre herramientas debe tener una propiedad de <code>data-education</code> que corresponda a la <code>data-education</code> de <code>data-education</code> del área activa. Aquí están los conjuntos de datos que necesitará para completar este proyecto: <br><ul><li> <strong>Datos de educación de los Estados Unidos:</strong> <code>https://cdn.freecodecamp.org/testable-projects-fcc/data/choropleth_map/for_user_education.json</code> </li><li> <strong>Datos del condado de EE. UU .:</strong> <code>https://cdn.freecodecamp.org/testable-projects-fcc/data/choropleth_map/counties.json</code> </li></ul> Puedes construir tu proyecto por medio de <a href="https://codepen.io/freeCodeCamp/pen/MJjpwO" target="_blank">este bolígrafo CodePen</a> . O puede usar este enlace CDN para ejecutar las pruebas en el entorno que desee: <code>https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js</code> Una vez que haya terminado, envíe la URL a su cuenta Proyecto con todas sus pruebas aprobadas. Recuerda usar el método de <a href="https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">lectura-búsqueda-pregunta</a> si te atascas. </section>
<ide>
<ide> ## Instructions
<ide> <section id="instructions">
<ide><path>curriculum/challenges/spanish/04-data-visualization/data-visualization-projects/visualize-data-with-a-treemap-diagram.spanish.md
<ide> localeTitle: Visualice datos con un diagrama de treemap
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> <strong>Objetivo:</strong> crear una aplicación <a href="https://codepen.io" target="_blank">CodePen.io</a> que sea funcionalmente similar a esta: <a href="https://codepen.io/freeCodeCamp/full/KaNGNR" target="_blank">https://codepen.io/freeCodeCamp/full/KaNGNR</a> . Cumple las siguientes <a href="https://en.wikipedia.org/wiki/User_story" target="_blank">historias de usuario</a> y haz que pasen todas las pruebas. Dale tu propio estilo personal. Puede utilizar HTML, JavaScript, CSS y la biblioteca de visualización basada en svg D3. Las pruebas requieren que se generen ejes utilizando la propiedad del eje D3, que genera automáticamente tics a lo largo del eje. Estas marcas son necesarias para pasar las pruebas D3 porque sus posiciones se usan para determinar la alineación de los elementos graficados. Encontrará información sobre la generación de ejes en <a href="https://github.com/d3/d3/blob/master/API.md#axes-d3-axis" target="_blank">https://github.com/d3/d3/blob/master/API.md#axes-d3-axis</a> . Los elementos DOM (no virtuales) requeridos se consultan en el momento de cada prueba. Si usa un marco de frontend (como Vue, por ejemplo), los resultados de la prueba pueden ser inexactos para el contenido dinámico. Esperamos acomodarlos eventualmente, pero estos marcos no están actualmente soportados para proyectos D3. <strong>Historia de usuario n. ° 1: el</strong> mapa de mi árbol debe tener un título con una <code>id="title"</code> correspondiente <code>id="title"</code> . <strong>Historia de usuario n. ° 2: el</strong> mapa de mi árbol debe tener una descripción con una <code>id="description"</code> correspondiente <code>id="description"</code> . <strong>Historia de usuario n. ° 3:</strong> Mi mapa de árbol debe tener elementos <code>rect</code> con una <code>class="tile"</code> correspondiente <code>class="tile"</code> que representa los datos. <strong>Historia de usuario n. ° 4:</strong> Debe haber al menos 2 colores de relleno diferentes utilizados para los azulejos. <strong>Historia de usuario n. ° 5:</strong> Cada mosaico debe tener las propiedades <code>data-name</code> <code>data-category</code> <code>data-value</code> contengan su nombre, categoría y valor correspondientes. <strong>Historia de usuario n. ° 6:</strong> El área de cada mosaico debe corresponder a la cantidad del valor de los datos: los mosaicos con un valor de datos más grande deben tener un área más grande. <strong>Historia de usuario n. ° 7:</strong> Mi mapa de árbol debe tener una leyenda con el <code>id="legend"</code> correspondiente <code>id="legend"</code> . <strong>Historia de usuario n. ° 8:</strong> Mi leyenda debe tener elementos <code>rect</code> con una <code>class="legend-item"</code> correspondiente <code>class="legend-item"</code> . <strong>Historia de usuario n. ° 9:</strong> Los elementos <code>rect</code> en la leyenda deben usar al menos 2 colores de relleno diferentes. <strong>Historia de usuario n. ° 10:</strong> puedo pasar el mouse sobre un área y ver una información sobre herramientas con la correspondiente <code>id="tooltip"</code> que muestra más información sobre el área. <strong>Historia de usuario n. ° 11:</strong> Mi información sobre herramientas debe tener una propiedad de <code>data-value</code> que corresponda al <code>data-value</code> de <code>data-value</code> del área activa. Para este proyecto puedes usar cualquiera de los siguientes conjuntos de datos: <br><ul><li> <strong>Compromisos de Kickstarter:</strong> <code>https://cdn.rawgit.com/freeCodeCamp/testable-projects-fcc/a80ce8f9/src/data/tree_map/kickstarter-funding-data.json</code> </li><li> <strong>Ventas de películas:</strong> <code>https://cdn.rawgit.com/freeCodeCamp/testable-projects-fcc/a80ce8f9/src/data/tree_map/movie-data.json</code> </li><li> <strong>Ventas de videojuegos:</strong> <code>https://cdn.rawgit.com/freeCodeCamp/testable-projects-fcc/a80ce8f9/src/data/tree_map/video-game-sales-data.json</code> </li></ul> Puedes construir tu proyecto por medio de <a href="https://codepen.io/freeCodeCamp/pen/MJjpwO" target="_blank">este bolígrafo CodePen</a> . O puede usar este enlace CDN para ejecutar las pruebas en el entorno que desee: <code>https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js</code> Una vez que haya terminado, envíe la URL a su cuenta Proyecto con todas sus pruebas aprobadas. Recuerda usar el método de <a href="https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">lectura-búsqueda-pregunta</a> si te atascas. </section>
<add><section id="description"> <strong>Objetivo:</strong> crear una aplicación <a href="https://codepen.io" target="_blank">CodePen.io</a> que sea funcionalmente similar a esta: <a href="https://codepen.io/freeCodeCamp/full/KaNGNR" target="_blank">https://codepen.io/freeCodeCamp/full/KaNGNR</a> . Cumple las siguientes <a href="https://en.wikipedia.org/wiki/User_story" target="_blank">historias de usuario</a> y haz que pasen todas las pruebas. Dale tu propio estilo personal. Puede utilizar HTML, JavaScript, CSS y la biblioteca de visualización basada en svg D3. Las pruebas requieren que se generen ejes utilizando la propiedad del eje D3, que genera automáticamente tics a lo largo del eje. Estas marcas son necesarias para pasar las pruebas D3 porque sus posiciones se usan para determinar la alineación de los elementos graficados. Encontrará información sobre la generación de ejes en <a href="https://github.com/d3/d3/blob/master/API.md#axes-d3-axis" target="_blank">https://github.com/d3/d3/blob/master/API.md#axes-d3-axis</a> . Los elementos DOM (no virtuales) requeridos se consultan en el momento de cada prueba. Si usa un marco de frontend (como Vue, por ejemplo), los resultados de la prueba pueden ser inexactos para el contenido dinámico. Esperamos acomodarlos eventualmente, pero estos marcos no están actualmente soportados para proyectos D3. <strong>Historia de usuario n. ° 1: el</strong> mapa de mi árbol debe tener un título con una <code>id="title"</code> correspondiente <code>id="title"</code> . <strong>Historia de usuario n. ° 2: el</strong> mapa de mi árbol debe tener una descripción con una <code>id="description"</code> correspondiente <code>id="description"</code> . <strong>Historia de usuario n. ° 3:</strong> Mi mapa de árbol debe tener elementos <code>rect</code> con una <code>class="tile"</code> correspondiente <code>class="tile"</code> que representa los datos. <strong>Historia de usuario n. ° 4:</strong> Debe haber al menos 2 colores de relleno diferentes utilizados para los azulejos. <strong>Historia de usuario n. ° 5:</strong> Cada mosaico debe tener las propiedades <code>data-name</code> <code>data-category</code> <code>data-value</code> contengan su nombre, categoría y valor correspondientes. <strong>Historia de usuario n. ° 6:</strong> El área de cada mosaico debe corresponder a la cantidad del valor de los datos: los mosaicos con un valor de datos más grande deben tener un área más grande. <strong>Historia de usuario n. ° 7:</strong> Mi mapa de árbol debe tener una leyenda con el <code>id="legend"</code> correspondiente <code>id="legend"</code> . <strong>Historia de usuario n. ° 8:</strong> Mi leyenda debe tener elementos <code>rect</code> con una <code>class="legend-item"</code> correspondiente <code>class="legend-item"</code> . <strong>Historia de usuario n. ° 9:</strong> Los elementos <code>rect</code> en la leyenda deben usar al menos 2 colores de relleno diferentes. <strong>Historia de usuario n. ° 10:</strong> puedo pasar el mouse sobre un área y ver una información sobre herramientas con la correspondiente <code>id="tooltip"</code> que muestra más información sobre el área. <strong>Historia de usuario n. ° 11:</strong> Mi información sobre herramientas debe tener una propiedad de <code>data-value</code> que corresponda al <code>data-value</code> de <code>data-value</code> del área activa. Para este proyecto puedes usar cualquiera de los siguientes conjuntos de datos: <br><ul><li> <strong>Compromisos de Kickstarter:</strong> <code>https://cdn.freecodecamp.org/testable-projects-fcc/data/tree_map/kickstarter-funding-data.json</code> </li><li> <strong>Ventas de películas:</strong> <code>https://cdn.freecodecamp.org/testable-projects-fcc/data/tree_map/movie-data.json</code> </li><li> <strong>Ventas de videojuegos:</strong> <code>https://cdn.freecodecamp.org/testable-projects-fcc/data/tree_map/video-game-sales-data.json</code> </li></ul> Puedes construir tu proyecto por medio de <a href="https://codepen.io/freeCodeCamp/pen/MJjpwO" target="_blank">este bolígrafo CodePen</a> . O puede usar este enlace CDN para ejecutar las pruebas en el entorno que desee: <code>https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js</code> Una vez que haya terminado, envíe la URL a su cuenta Proyecto con todas sus pruebas aprobadas. Recuerda usar el método de <a href="https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">lectura-búsqueda-pregunta</a> si te atascas. </section>
<ide>
<ide> ## Instructions
<ide> <section id="instructions"> | 10 |
Go | Go | use prefix naming for links tests | b6325907e9de4020381ad1d016614f819da58cc6 | <ide><path>integration-cli/docker_cli_links_test.go
<ide> import (
<ide> "github.com/docker/docker/pkg/iptables"
<ide> )
<ide>
<del>func TestEtcHostsRegularFile(t *testing.T) {
<add>func TestLinksEtcHostsRegularFile(t *testing.T) {
<ide> runCmd := exec.Command(dockerBinary, "run", "--net=host", "busybox", "ls", "-la", "/etc/hosts")
<ide> out, _, _, err := runCommandWithStdoutStderr(runCmd)
<ide> errorOut(err, t, out)
<ide> func TestEtcHostsRegularFile(t *testing.T) {
<ide> logDone("link - /etc/hosts is a regular file")
<ide> }
<ide>
<del>func TestEtcHostsContentMatch(t *testing.T) {
<add>func TestLinksEtcHostsContentMatch(t *testing.T) {
<ide> runCmd := exec.Command(dockerBinary, "run", "--net=host", "busybox", "cat", "/etc/hosts")
<ide> out, _, _, err := runCommandWithStdoutStderr(runCmd)
<ide> errorOut(err, t, out)
<ide> func TestEtcHostsContentMatch(t *testing.T) {
<ide> logDone("link - /etc/hosts matches hosts copy")
<ide> }
<ide>
<del>func TestPingUnlinkedContainers(t *testing.T) {
<add>func TestLinksPingUnlinkedContainers(t *testing.T) {
<ide> runCmd := exec.Command(dockerBinary, "run", "--rm", "busybox", "sh", "-c", "ping -c 1 alias1 -W 1 && ping -c 1 alias2 -W 1")
<ide> exitCode, err := runCommand(runCmd)
<ide>
<ide> func TestPingUnlinkedContainers(t *testing.T) {
<ide> logDone("links - ping unlinked container")
<ide> }
<ide>
<del>func TestPingLinkedContainers(t *testing.T) {
<add>func TestLinksPingLinkedContainers(t *testing.T) {
<ide> var out string
<ide> out, _, _ = cmd(t, "run", "-d", "--name", "container1", "busybox", "sleep", "10")
<ide> idA := stripTrailingCharacters(out)
<ide> func TestPingLinkedContainers(t *testing.T) {
<ide> logDone("links - ping linked container")
<ide> }
<ide>
<del>func TestIpTablesRulesWhenLinkAndUnlink(t *testing.T) {
<add>func TestLinksIpTablesRulesWhenLinkAndUnlink(t *testing.T) {
<ide> cmd(t, "run", "-d", "--name", "child", "--publish", "8080:80", "busybox", "sleep", "10")
<ide> cmd(t, "run", "-d", "--name", "parent", "--link", "child:http", "busybox", "sleep", "10")
<ide>
<ide> func TestIpTablesRulesWhenLinkAndUnlink(t *testing.T) {
<ide> logDone("link - verify iptables when link and unlink")
<ide> }
<ide>
<del>func TestInspectLinksStarted(t *testing.T) {
<add>func TestLinksInspectLinksStarted(t *testing.T) {
<ide> var (
<ide> expected = map[string]struct{}{"/container1:/testinspectlink/alias1": {}, "/container2:/testinspectlink/alias2": {}}
<ide> result []string
<ide> func TestInspectLinksStarted(t *testing.T) {
<ide> logDone("link - links in started container inspect")
<ide> }
<ide>
<del>func TestInspectLinksStopped(t *testing.T) {
<add>func TestLinksInspectLinksStopped(t *testing.T) {
<ide> var (
<ide> expected = map[string]struct{}{"/container1:/testinspectlink/alias1": {}, "/container2:/testinspectlink/alias2": {}}
<ide> result []string | 1 |
PHP | PHP | return array from ucsplit | 498fdd2b40644bb48529c2530978555cf4b0766c | <ide><path>src/Illuminate/Support/Stringable.php
<ide> public function ucfirst()
<ide> /**
<ide> * Split a string by uppercase characters.
<ide> *
<del> * @return static
<add> * @return array
<ide> */
<ide> public function ucsplit()
<ide> {
<del> return new static(Str::ucsplit($this->value));
<add> return Str::ucsplit($this->value);
<ide> }
<ide>
<ide> /** | 1 |
Python | Python | add __init__.py for modeling sub-directories | 65dc825dad6f30205ce7cc5553e608c179ba9808 | <ide><path>official/projects/qat/nlp/modeling/models/__init__.py
<add># Copyright 2022 The TensorFlow Authors. All Rights Reserved.
<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># http://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>
<ide><path>official/projects/qat/nlp/modeling/networks/__init__.py
<add># Copyright 2022 The TensorFlow Authors. All Rights Reserved.
<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># http://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> | 2 |
Python | Python | add slow_pypy support | 9df2c98537b72c74f4e996ad840f1fe5a5f003df | <ide><path>numpy/_pytesttester.py
<ide> def __call__(self, label='fast', verbose=1, extra_argv=None,
<ide> pytest_args += ["--cov=" + module_path]
<ide>
<ide> if label == "fast":
<del> pytest_args += ["-m", "not slow"]
<add> # not importing at the top level to avoid circular import of module
<add> from numpy.testing import IS_PYPY
<add> pytest_args += ["-m", "not slow and not slow_pypy"] \
<add> if IS_PYPY else ["-m", "not slow"]
<ide> elif label != "full":
<ide> pytest_args += ["-m", label]
<ide>
<ide><path>numpy/conftest.py
<ide> def pytest_configure(config):
<ide> "leaks_references: Tests that are known to leak references.")
<ide> config.addinivalue_line("markers",
<ide> "slow: Tests that are very slow.")
<add> config.addinivalue_line("markers",
<add> "slow_pypy: Tests that are very slow on pypy.")
<ide>
<ide>
<ide> def pytest_addoption(parser):
<ide><path>numpy/core/tests/test_regression.py
<ide> def test_assign_obj_listoflists(self):
<ide> a[...] = [[1, 2]]
<ide> assert_equal(a, [[1, 2], [1, 2]])
<ide>
<add> @pytest.mark.slow_pypy
<ide> def test_memoryleak(self):
<ide> # Ticket #1917 - ensure that array data doesn't leak
<ide> for i in range(1000):
<ide><path>numpy/lib/tests/test_io.py
<ide> def test_not_closing_opened_fid(self):
<ide> fp.seek(0)
<ide> assert_(not fp.closed)
<ide>
<add> @pytest.mark.slow_pypy
<ide> def test_closing_fid(self):
<ide> # Test that issue #1517 (too many opened files) remains closed
<ide> # It might be a "weak" test since failed to get triggered on | 4 |
Javascript | Javascript | propagate bind errors" | a2851b62345c59ab5d41d8e3d0da1bad8a9c59d3 | <ide><path>lib/net.js
<ide> Server.prototype._listen2 = function(address, port, addressType) {
<ide>
<ide>
<ide> function listen(self, address, port, addressType) {
<del> if (!process.env.NODE_WORKER_ID) {
<add> if (process.env.NODE_WORKER_ID) {
<add> require('cluster')._getServer(address, port, addressType, function(handle) {
<add> self._handle = handle;
<add> self._listen2(address, port, addressType);
<add> });
<add> } else {
<ide> self._listen2(address, port, addressType);
<del> return;
<ide> }
<del>
<del> require('cluster')._getServer(address, port, addressType, function(handle) {
<del> // OS X doesn't necessarily signal EADDRINUSE from bind(), it may defer
<del> // the error until later. libuv mimics this behaviour to provide
<del> // consistent behaviour across platforms but that means we could very
<del> // well have a socket that is not actually bound... that's why we do
<del> // this ghetto port check and raise EADDRINUSE if the requested and the
<del> // actual port differ except if port == 0 because that means "any port".
<del> if (port && port != handle.getsockname().port) {
<del> self.emit('error', errnoException('EADDRINUSE', 'bind'));
<del> return;
<del> }
<del>
<del> self._handle = handle;
<del> self._listen2(address, port, addressType);
<del> });
<ide> }
<ide>
<ide>
<ide><path>test/simple/test-cluster-bind-twice-v1.js
<del>// Copyright Joyent, Inc. and other Node contributors.
<del>//
<del>// Permission is hereby granted, free of charge, to any person obtaining a
<del>// copy of this software and associated documentation files (the
<del>// "Software"), to deal in the Software without restriction, including
<del>// without limitation the rights to use, copy, modify, merge, publish,
<del>// distribute, sublicense, and/or sell copies of the Software, and to permit
<del>// persons to whom the Software is furnished to do so, subject to the
<del>// following conditions:
<del>//
<del>// The above copyright notice and this permission notice shall be included
<del>// in all copies or substantial portions of the Software.
<del>//
<del>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
<del>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
<del>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
<del>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
<del>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
<del>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
<del>// USE OR OTHER DEALINGS IN THE SOFTWARE.
<del>
<del>// This test starts two clustered HTTP servers on the same port. It expects the
<del>// first cluster to succeed and the second cluster to fail with EADDRINUSE.
<del>
<del>var common = require('../common');
<del>var assert = require('assert');
<del>var cluster = require('cluster');
<del>var fork = require('child_process').fork;
<del>var http = require('http');
<del>
<del>var id = process.argv[2];
<del>
<del>if (!id) {
<del> var a = fork(__filename, ['one']);
<del> var b = fork(__filename, ['two']);
<del>
<del> a.on('message', function(m) {
<del> assert.equal(m, 'READY');
<del> b.send('START');
<del> });
<del>
<del> var ok = false;
<del>
<del> b.on('message', function(m) {
<del> assert.equal(m, 'EADDRINUSE');
<del> a.kill();
<del> b.kill();
<del> ok = true;
<del> });
<del>
<del> process.on('exit', function() {
<del> a.kill();
<del> b.kill();
<del> assert(ok);
<del> });
<del>}
<del>else if (id === 'one') {
<del> if (cluster.isMaster) cluster.fork();
<del> http.createServer(assert.fail).listen(common.PORT, function() {
<del> process.send('READY');
<del> });
<del>}
<del>else if (id === 'two') {
<del> if (cluster.isMaster) cluster.fork();
<del> process.on('message', function(m) {
<del> assert.equal(m, 'START');
<del> var server = http.createServer(assert.fail);
<del> server.listen(common.PORT, assert.fail);
<del> server.on('error', function(e) {
<del> assert.equal(e.code, 'EADDRINUSE');
<del> process.send(e.code);
<del> });
<del> });
<del>}
<del>else {
<del> assert(0); // bad command line argument
<del>}
<ide><path>test/simple/test-cluster-bind-twice-v2.js
<del>// Copyright Joyent, Inc. and other Node contributors.
<del>//
<del>// Permission is hereby granted, free of charge, to any person obtaining a
<del>// copy of this software and associated documentation files (the
<del>// "Software"), to deal in the Software without restriction, including
<del>// without limitation the rights to use, copy, modify, merge, publish,
<del>// distribute, sublicense, and/or sell copies of the Software, and to permit
<del>// persons to whom the Software is furnished to do so, subject to the
<del>// following conditions:
<del>//
<del>// The above copyright notice and this permission notice shall be included
<del>// in all copies or substantial portions of the Software.
<del>//
<del>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
<del>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
<del>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
<del>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
<del>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
<del>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
<del>// USE OR OTHER DEALINGS IN THE SOFTWARE.
<del>
<del>// This test starts two clustered HTTP servers on the same port. It expects the
<del>// first cluster to succeed and the second cluster to fail with EADDRINUSE.
<del>//
<del>// The test may seem complex but most of it is plumbing that routes messages
<del>// from the child processes back to the "super" master. As a tree it looks
<del>// something like this:
<del>//
<del>// <super master>
<del>// / \
<del>// <master 1> <master 2>
<del>// / \
<del>// <worker 1> <worker 2>
<del>//
<del>// The first worker starts a server on a fixed port and fires a ready message
<del>// that is routed to the second worker. When it tries to bind, it expects to
<del>// see an EADDRINUSE error.
<del>//
<del>// See https://github.com/joyent/node/issues/2721 for more details.
<del>
<del>var common = require('../common');
<del>var assert = require('assert');
<del>var cluster = require('cluster');
<del>var fork = require('child_process').fork;
<del>var http = require('http');
<del>
<del>var id = process.argv[2];
<del>
<del>if (!id) {
<del> var a = fork(__filename, ['one']);
<del> var b = fork(__filename, ['two']);
<del>
<del> a.on('message', function(m) {
<del> if (typeof m === 'object') return;
<del> assert.equal(m, 'READY');
<del> b.send('START');
<del> });
<del>
<del> var ok = false;
<del>
<del> b.on('message', function(m) {
<del> if (typeof m === 'object') return; // ignore system messages
<del> assert.equal(m, 'EADDRINUSE');
<del> a.kill();
<del> b.kill();
<del> ok = true;
<del> });
<del>
<del> process.on('exit', function() {
<del> a.kill();
<del> b.kill();
<del> assert(ok);
<del> });
<del>}
<del>else if (id === 'one') {
<del> if (cluster.isMaster) return startWorker();
<del>
<del> http.createServer(assert.fail).listen(common.PORT, function() {
<del> process.send('READY');
<del> });
<del>}
<del>else if (id === 'two') {
<del> if (cluster.isMaster) return startWorker();
<del>
<del> var ok = false;
<del> process.on('SIGTERM', process.exit);
<del> process.on('exit', function() {
<del> assert(ok);
<del> });
<del>
<del> process.on('message', function(m) {
<del> if (typeof m === 'object') return; // ignore system messages
<del> assert.equal(m, 'START');
<del> var server = http.createServer(assert.fail);
<del> server.listen(common.PORT, assert.fail);
<del> server.on('error', function(e) {
<del> assert.equal(e.code, 'EADDRINUSE');
<del> process.send(e.code);
<del> ok = true;
<del> });
<del> });
<del>}
<del>else {
<del> assert(0); // bad command line argument
<del>}
<del>
<del>function startWorker() {
<del> var worker = cluster.fork();
<del> worker.on('message', process.send);
<del> process.on('message', worker.send.bind(worker));
<del> process.on('SIGTERM', function() {
<del> worker.kill();
<del> process.exit();
<del> });
<del>} | 3 |
Python | Python | add new getproducttype api in outscale ec2 driver | d277e988f1f6c078e79cfb2e6848d465ceb24f26 | <ide><path>libcloud/compute/drivers/ec2.py
<ide> def ex_describe_quota(self, dry_run=False, filters=None,
<ide>
<ide> return is_truncated, quota
<ide>
<add> def _to_product_type(self, elem):
<add>
<add> productTypeId = findtext(element=elem, xpath='productTypeId',
<add> namespace=OUTSCALE_NAMESPACE)
<add> description = findtext(element=elem, xpath='description',
<add> namespace=OUTSCALE_NAMESPACE)
<add>
<add> return {'productTypeId': productTypeId,
<add> 'description': description}
<add>
<add> def ex_get_product_type(self, image_id, snapshot_id=None):
<add> """
<add> Get the product type of a specified OMI or snapshot.
<add>
<add> :param image_id: The ID of the OMI
<add> :type image_id: ``string``
<add>
<add> :param snapshot_id: The ID of the snapshot
<add> :type snapshot_id: ``string``
<add>
<add> :return: A product type
<add> :rtype: ``dict``
<add> """
<add>
<add> params = {'Action': 'GetProductType'}
<add>
<add> params.update({'ImageId': image_id})
<add> if snapshot_id is not None:
<add> params.update({'SnapshotId': snapshot_id})
<add>
<add> response = self.connection.request(self.path, params=params,
<add> method='GET').object
<add>
<add> product_type = self._to_product_type(response)
<add>
<add> return product_type
<add>
<ide> def _to_product_types(self, elem):
<ide>
<ide> product_types = [] | 1 |
Ruby | Ruby | increase `ar#cache_key` precision to nanoseconds | 900dbc54f17500e14e481eab2ebf88acfc5448aa | <ide><path>activerecord/lib/active_record/integration.rb
<ide> def cache_key
<ide> when new_record?
<ide> "#{self.class.model_name.cache_key}/new"
<ide> when timestamp = self[:updated_at]
<del> timestamp = timestamp.utc.to_s(:number)
<add> timestamp = timestamp.utc.to_s(:nsec)
<ide> "#{self.class.model_name.cache_key}/#{id}-#{timestamp}"
<ide> else
<ide> "#{self.class.model_name.cache_key}/#{id}"
<ide><path>activerecord/test/cases/base_test.rb
<ide> def test_cache_key_for_existing_record_is_not_timezone_dependent
<ide>
<ide> def test_cache_key_format_for_existing_record_with_updated_at
<ide> dev = Developer.first
<del> assert_equal "developers/#{dev.id}-#{dev.updated_at.utc.to_s(:number)}", dev.cache_key
<add> assert_equal "developers/#{dev.id}-#{dev.updated_at.utc.to_s(:nsec)}", dev.cache_key
<ide> end
<ide>
<ide> def test_cache_key_format_for_existing_record_with_nil_updated_at
<ide><path>activesupport/lib/active_support/core_ext/time/conversions.rb
<ide> class Time
<ide> DATE_FORMATS = {
<ide> :db => '%Y-%m-%d %H:%M:%S',
<ide> :number => '%Y%m%d%H%M%S',
<add> :nsec => '%Y%m%d%H%M%S%9N',
<ide> :time => '%H:%M',
<ide> :short => '%d %b %H:%M',
<ide> :long => '%B %d, %Y %H:%M',
<ide><path>activesupport/test/core_ext/time_ext_test.rb
<ide> def test_next_week_near_daylight_end
<ide> end
<ide>
<ide> def test_to_s
<del> time = Time.utc(2005, 2, 21, 17, 44, 30)
<add> time = Time.utc(2005, 2, 21, 17, 44, 30.12345678901)
<ide> assert_equal time.to_default_s, time.to_s
<ide> assert_equal time.to_default_s, time.to_s(:doesnt_exist)
<ide> assert_equal "2005-02-21 17:44:30", time.to_s(:db)
<ide> assert_equal "21 Feb 17:44", time.to_s(:short)
<ide> assert_equal "17:44", time.to_s(:time)
<add> assert_equal "20050221174430", time.to_s(:number)
<add> assert_equal "20050221174430123456789", time.to_s(:nsec)
<ide> assert_equal "February 21, 2005 17:44", time.to_s(:long)
<ide> assert_equal "February 21st, 2005 17:44", time.to_s(:long_ordinal)
<ide> with_env_tz "UTC" do | 4 |
Ruby | Ruby | remove a stray process2 require | 85f2f34d5ec8ccdea4755740b810ac514d9f3dd9 | <ide><path>railties/test/rails_info_controller_test.rb
<ide> require 'abstract_unit'
<ide> require 'action_controller'
<del>require 'action_controller/testing/process2'
<add>require 'action_controller/testing/process'
<ide>
<ide> require 'rails/info'
<ide> require 'rails/info_controller' | 1 |
Mixed | Javascript | support boxed strings and toprimitive | 22cf25cf2d251371590ea35c740793a5f19d4623 | <ide><path>doc/api/buffer.md
<ide> console.log(buf2.toString());
<ide>
<ide> A `TypeError` will be thrown if `str` is not a string.
<ide>
<add>### Class Method: Buffer.from(object[, offsetOrEncoding[, length]])
<add><!-- YAML
<add>added: REPLACEME
<add>-->
<add>
<add>* `object` {Object} An object supporting `Symbol.toPrimitive` or `valueOf()`
<add>* `offsetOrEncoding` {number|string} A byte-offset or encoding, depending on
<add> the value returned either by `object.valueOf()` or
<add> `object[Symbol.toPrimitive]()`.
<add>* `length` {number} A length, depending on the value returned either by
<add> `object.valueOf()` or `object[Symbol.toPrimitive]()`.
<add>
<add>For objects whose `valueOf()` function returns a value not strictly equal to
<add>`object`, returns `Buffer.from(object.valueOf(), offsetOrEncoding, length)`.
<add>
<add>For example:
<add>
<add>```js
<add>const buf = Buffer.from(new String('this is a test'));
<add>// <Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74>
<add>```
<add>
<add>For objects that support `Symbol.toPrimitive`, returns
<add>`Buffer.from(object[Symbol.toPrimitive](), offsetOrEncoding, length)`.
<add>
<add>For example:
<add>
<add>```js
<add>class Foo {
<add> [Symbol.toPrimitive]() {
<add> return 'this is a test';
<add> }
<add>}
<add>
<add>const buf = Buffer.from(new Foo(), 'utf8');
<add>// <Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74>
<add>```
<add>
<ide> ### Class Method: Buffer.isBuffer(obj)
<ide> <!-- YAML
<ide> added: v0.1.101
<ide><path>lib/buffer.js
<ide> Buffer.from = function(value, encodingOrOffset, length) {
<ide> if (isAnyArrayBuffer(value))
<ide> return fromArrayBuffer(value, encodingOrOffset, length);
<ide>
<add> if (value == null)
<add> throw new TypeError(kFromErrorMsg);
<add>
<add> if (typeof value === 'number')
<add> throw new TypeError('"value" argument must not be a number');
<add>
<add> const valueOf = value.valueOf && value.valueOf();
<add> if (valueOf != null && valueOf !== value)
<add> return Buffer.from(valueOf, encodingOrOffset, length);
<add>
<ide> var b = fromObject(value);
<ide> if (b)
<ide> return b;
<ide>
<del> if (typeof value === 'number')
<del> throw new TypeError('"value" argument must not be a number');
<add> if (typeof value[Symbol.toPrimitive] === 'function') {
<add> return Buffer.from(value[Symbol.toPrimitive]('string'),
<add> encodingOrOffset,
<add> length);
<add> }
<add>
<ide> throw new TypeError(kFromErrorMsg);
<ide> };
<ide>
<ide><path>test/parallel/test-buffer-from.js
<add>'use strict';
<add>
<add>require('../common');
<add>const { deepStrictEqual, throws } = require('assert');
<add>const { Buffer } = require('buffer');
<add>const { runInNewContext } = require('vm');
<add>
<add>const checkString = 'test';
<add>
<add>const check = Buffer.from(checkString);
<add>
<add>class MyString extends String {
<add> constructor() {
<add> super(checkString);
<add> }
<add>}
<add>
<add>class MyPrimitive {
<add> [Symbol.toPrimitive]() {
<add> return checkString;
<add> }
<add>}
<add>
<add>class MyBadPrimitive {
<add> [Symbol.toPrimitive]() {
<add> return 1;
<add> }
<add>}
<add>
<add>deepStrictEqual(Buffer.from(new String(checkString)), check);
<add>deepStrictEqual(Buffer.from(new MyString()), check);
<add>deepStrictEqual(Buffer.from(new MyPrimitive()), check);
<add>deepStrictEqual(Buffer.from(
<add> runInNewContext('new String(checkString)', {checkString})),
<add> check);
<add>
<add>const err = new RegExp('^TypeError: First argument must be a string, Buffer, ' +
<add> 'ArrayBuffer, Array, or array-like object\\.$');
<add>
<add>[
<add> {},
<add> new Boolean(true),
<add> { valueOf() { return null; } },
<add> { valueOf() { return undefined; } },
<add> { valueOf: null },
<add> Object.create(null)
<add>].forEach((input) => {
<add> throws(() => Buffer.from(input), err);
<add>});
<add>
<add>[
<add> new Number(true),
<add> new MyBadPrimitive()
<add>].forEach((input) => {
<add> throws(() => Buffer.from(input),
<add> /^TypeError: "value" argument must not be a number$/);
<add>}); | 3 |
Javascript | Javascript | update amp example to amp-first wording | 549965282045beda0cf0b31823b35a13014a0d6b | <ide><path>examples/amp/pages/dog.js
<ide> export default withAmp(
<ide> return (
<ide> <div>
<ide> <Head>
<del> <title>The Dog (Hybrid AMP Page)</title>
<add> <title>The Dog</title>
<ide> </Head>
<del> <h1>The Dog</h1>
<add> <h1>The Dog (Hybrid AMP Page)</h1>
<ide> <Byline author='Meow Meow Fuzzyface' />
<ide> <p>
<ide> <a href={isAmp ? '/dog' : '/dog?amp=1'}>
<ide><path>examples/amp/pages/index.js
<ide> export default withAmp(() => {
<ide> return (
<ide> <Layout>
<ide> <Head>
<del> <title>The Cat (AMP-only Page)</title>
<add> <title>The Cat</title>
<ide> </Head>
<del> <h1>The Cat</h1>
<add> <h1>The Cat (AMP-first Page)</h1>
<ide> <Byline author='Dan Zajdband' />
<ide> <p className='caption'>Meowwwwwwww</p>
<ide> <p> | 2 |
Python | Python | add timeout option to gcs hook methods. | 323084e97ddacbc5512709bf0cad8f53082d16b0 | <ide><path>airflow/providers/google/cloud/hooks/gcs.py
<ide> RT = TypeVar('RT') # pylint: disable=invalid-name
<ide> T = TypeVar("T", bound=Callable) # pylint: disable=invalid-name
<ide>
<add># Use default timeout from google-cloud-storage
<add>DEFAULT_TIMEOUT = 60
<add>
<ide>
<ide> def _fallback_object_url_to_object_name_and_bucket_name(
<ide> object_url_keyword_arg_name='object_url',
<ide> def rewrite(
<ide> )
<ide>
<ide> def download(
<del> self, object_name: str, bucket_name: Optional[str], filename: Optional[str] = None
<add> self,
<add> object_name: str,
<add> bucket_name: Optional[str],
<add> filename: Optional[str] = None,
<add> chunk_size: Optional[int] = None,
<add> timeout: Optional[int] = DEFAULT_TIMEOUT,
<ide> ) -> Union[str, bytes]:
<ide> """
<ide> Downloads a file from Google Cloud Storage.
<ide> def download(
<ide> :type object_name: str
<ide> :param filename: If set, a local file path where the file should be written to.
<ide> :type filename: str
<add> :param chunk_size: Blob chunk size.
<add> :type chunk_size: int
<add> :param timeout: Request timeout in seconds.
<add> :type timeout: int
<ide> """
<ide> # TODO: future improvement check file size before downloading,
<ide> # to check for local space availability
<ide>
<ide> client = self.get_conn()
<ide> bucket = client.bucket(bucket_name)
<del> blob = bucket.blob(blob_name=object_name)
<add> blob = bucket.blob(blob_name=object_name, chunk_size=chunk_size)
<ide>
<ide> if filename:
<del> blob.download_to_filename(filename)
<add> blob.download_to_filename(filename, timeout=timeout)
<ide> self.log.info('File downloaded to %s', filename)
<ide> return filename
<ide> else:
<ide> def upload(
<ide> mime_type: Optional[str] = None,
<ide> gzip: bool = False,
<ide> encoding: str = 'utf-8',
<add> chunk_size: Optional[int] = None,
<add> timeout: Optional[int] = DEFAULT_TIMEOUT,
<ide> ) -> None:
<ide> """
<ide> Uploads a local file or file data as string or bytes to Google Cloud Storage.
<ide> def upload(
<ide> :type gzip: bool
<ide> :param encoding: bytes encoding for file data if provided as string
<ide> :type encoding: str
<add> :param chunk_size: Blob chunk size.
<add> :type chunk_size: int
<add> :param timeout: Request timeout in seconds.
<add> :type timeout: int
<ide> """
<ide> client = self.get_conn()
<ide> bucket = client.bucket(bucket_name)
<del> blob = bucket.blob(blob_name=object_name)
<add> blob = bucket.blob(blob_name=object_name, chunk_size=chunk_size)
<ide> if filename and data:
<ide> raise ValueError(
<ide> "'filename' and 'data' parameter provided. Please "
<ide> def upload(
<ide> shutil.copyfileobj(f_in, f_out)
<ide> filename = filename_gz
<ide>
<del> blob.upload_from_filename(filename=filename, content_type=mime_type)
<add> blob.upload_from_filename(filename=filename, content_type=mime_type, timeout=timeout)
<ide> if gzip:
<ide> os.remove(filename)
<ide> self.log.info('File %s uploaded to %s in %s bucket', filename, object_name, bucket_name)
<ide> def upload(
<ide> with gz.GzipFile(fileobj=out, mode="w") as f:
<ide> f.write(data)
<ide> data = out.getvalue()
<del> blob.upload_from_string(data, content_type=mime_type)
<add> blob.upload_from_string(data, content_type=mime_type, timeout=timeout)
<ide> self.log.info('Data stream uploaded to %s in %s bucket', object_name, bucket_name)
<ide> else:
<ide> raise ValueError("'filename' and 'data' parameter missing. One is required to upload to gcs.")
<ide><path>setup.py
<ide> def write_version(filename: str = os.path.join(*[my_dir, "airflow", "git_version
<ide> 'google-cloud-secret-manager>=0.2.0,<2.0.0',
<ide> 'google-cloud-spanner>=1.10.0,<2.0.0',
<ide> 'google-cloud-speech>=0.36.3,<2.0.0',
<del> 'google-cloud-storage>=1.16,<2.0.0',
<add> 'google-cloud-storage>=1.30,<2.0.0',
<ide> 'google-cloud-tasks>=1.2.1,<2.0.0',
<ide> 'google-cloud-texttospeech>=0.4.0,<2.0.0',
<ide> 'google-cloud-translate>=1.5.0,<2.0.0',
<ide><path>tests/providers/google/cloud/hooks/test_gcs.py
<ide> def test_download_to_file(self, mock_service):
<ide> )
<ide>
<ide> self.assertEqual(response, test_file)
<del> download_filename_method.assert_called_once_with(test_file)
<add> download_filename_method.assert_called_once_with(test_file, timeout=60)
<ide>
<ide> @mock.patch(GCS_STRING.format('NamedTemporaryFile'))
<ide> @mock.patch(GCS_STRING.format('GCSHook.get_conn'))
<ide> def test_provide_file(self, mock_service, mock_temp_file):
<ide> with self.gcs_hook.provide_file(bucket_name=test_bucket, object_name=test_object) as response:
<ide>
<ide> self.assertEqual(test_file, response.name)
<del> download_filename_method.assert_called_once_with(test_file)
<add> download_filename_method.assert_called_once_with(test_file, timeout=60)
<ide> mock_temp_file.assert_has_calls(
<ide> [
<ide> mock.call(suffix='test_object'),
<ide> def test_upload_file(self, mock_service):
<ide> self.gcs_hook.upload(test_bucket, test_object, filename=self.testfile.name)
<ide>
<ide> upload_method.assert_called_once_with(
<del> filename=self.testfile.name, content_type='application/octet-stream'
<add> filename=self.testfile.name, content_type='application/octet-stream', timeout=60
<ide> )
<ide>
<ide> @mock.patch(GCS_STRING.format('GCSHook.get_conn'))
<ide> def test_upload_data_str(self, mock_service):
<ide>
<ide> self.gcs_hook.upload(test_bucket, test_object, data=self.testdata_str)
<ide>
<del> upload_method.assert_called_once_with(self.testdata_str, content_type='text/plain')
<add> upload_method.assert_called_once_with(self.testdata_str, content_type='text/plain', timeout=60)
<ide>
<ide> @mock.patch(GCS_STRING.format('GCSHook.get_conn'))
<ide> def test_upload_data_bytes(self, mock_service):
<ide> def test_upload_data_bytes(self, mock_service):
<ide>
<ide> self.gcs_hook.upload(test_bucket, test_object, data=self.testdata_bytes)
<ide>
<del> upload_method.assert_called_once_with(self.testdata_bytes, content_type='text/plain')
<add> upload_method.assert_called_once_with(self.testdata_bytes, content_type='text/plain', timeout=60)
<ide>
<ide> @mock.patch(GCS_STRING.format('BytesIO'))
<ide> @mock.patch(GCS_STRING.format('gz.GzipFile'))
<ide> def test_upload_data_str_gzip(self, mock_service, mock_gzip, mock_bytes_io):
<ide> byte_str = bytes(self.testdata_str, encoding)
<ide> mock_gzip.assert_called_once_with(fileobj=mock_bytes_io.return_value, mode="w")
<ide> gzip_ctx.write.assert_called_once_with(byte_str)
<del> upload_method.assert_called_once_with(data, content_type='text/plain')
<add> upload_method.assert_called_once_with(data, content_type='text/plain', timeout=60)
<ide>
<ide> @mock.patch(GCS_STRING.format('BytesIO'))
<ide> @mock.patch(GCS_STRING.format('gz.GzipFile'))
<ide> def test_upload_data_bytes_gzip(self, mock_service, mock_gzip, mock_bytes_io):
<ide>
<ide> mock_gzip.assert_called_once_with(fileobj=mock_bytes_io.return_value, mode="w")
<ide> gzip_ctx.write.assert_called_once_with(self.testdata_bytes)
<del> upload_method.assert_called_once_with(data, content_type='text/plain')
<add> upload_method.assert_called_once_with(data, content_type='text/plain', timeout=60)
<ide>
<ide> @mock.patch(GCS_STRING.format('GCSHook.get_conn'))
<ide> def test_upload_exceptions(self, mock_service): | 3 |
Text | Text | update cloud tpu readme to include efficientnet | f2dcb8d4bf76192f3cb0730c29cf25a9b1f92a31 | <ide><path>official/README-TPU.md
<ide>
<ide> ## Computer Vision
<ide>
<add>* [efficientnet](vision/image_classification): A family of convolutional
<add> neural networks that scale by balancing network depth, width, and
<add> resolution and can be used to classify ImageNet's dataset of 1000 classes.
<add> See [Tensorboard.dev training metrics](https://tensorboard.dev/experiment/KnaWjrq5TXGfv0NW5m7rpg/#scalars).
<ide> * [mnist](vision/image_classification): A basic model to classify digits
<ide> from the MNIST dataset. See [Running MNIST on Cloud TPU](https://cloud.google.com/tpu/docs/tutorials/mnist-2.x) tutorial and [Tensorboard.dev metrics](https://tensorboard.dev/experiment/mIah5lppTASvrHqWrdr6NA).
<ide> * [resnet](vision/image_classification): A deep residual network that can | 1 |
Python | Python | use neq instead of xor in diff | 47242a25920e72366e906a7ffaa2fb41144623d3 | <ide><path>numpy/lib/function_base.py
<ide> def diff(a, n=1, axis=-1):
<ide> slice2 = tuple(slice2)
<ide>
<ide> if a.dtype == np.bool_:
<del> da = a[slice1] ^ a[slice2]
<add> da = a[slice1] != a[slice2]
<ide> else:
<ide> da = a[slice1] - a[slice2]
<ide> | 1 |
Ruby | Ruby | add an assertion to the regression test | 097e4afcbacfe50abd97679adcf5fcf9a0dd87f1 | <ide><path>activerecord/test/cases/filter_attributes_test.rb
<ide> class FilterAttributesTest < ActiveRecord::TestCase
<ide>
<ide> test "proc filter_attributes don't prevent marshal dump" do
<ide> ActiveRecord::Base.filter_attributes = [ lambda { |key, value| value.reverse! if key == "name" } ]
<del> account = Admin::Account.new(name: "37signals")
<add> account = Admin::Account.new(id: 123, name: "37signals")
<ide> account.inspect
<del> Marshal.dump(account)
<add> assert_equal account, Marshal.load(Marshal.dump(account))
<ide> end
<ide>
<ide> test "filter_attributes could be overwritten by models" do | 1 |
Javascript | Javascript | fix upgradehead bounds | 6ad18a27a0bf9a8f0c6d618c0011f2264239af04 | <ide><path>lib/http.js
<ide> function connectionListener (socket) {
<ide> socket.ondata = function (d, start, end) {
<ide> var bytesParsed = parser.execute(d, start, end - start);
<ide> if (parser.incoming && parser.incoming.upgrade) {
<del> var upgradeHead = d.slice(start + bytesParsed, end - start);
<add> var upgradeHead = d.slice(start + bytesParsed, end);
<ide> parser.incoming.upgradeHead = upgradeHead;
<ide> socket.ondata = null;
<ide> socket.onend = null; | 1 |
Go | Go | fix vet errors in aufs.go about lock by value | 2540765ddc8889e2757f9ccfbfe852074b61601c | <ide><path>daemon/graphdriver/aufs/aufs.go
<ide> func supportsAufs() error {
<ide> return ErrAufsNotSupported
<ide> }
<ide>
<del>func (a Driver) rootPath() string {
<add>func (a *Driver) rootPath() string {
<ide> return a.root
<ide> }
<ide>
<del>func (Driver) String() string {
<add>func (*Driver) String() string {
<ide> return "aufs"
<ide> }
<ide>
<del>func (a Driver) Status() [][2]string {
<add>func (a *Driver) Status() [][2]string {
<ide> ids, _ := loadIds(path.Join(a.rootPath(), "layers"))
<ide> return [][2]string{
<ide> {"Root Dir", a.rootPath()},
<ide> func (a Driver) Status() [][2]string {
<ide>
<ide> // Exists returns true if the given id is registered with
<ide> // this driver
<del>func (a Driver) Exists(id string) bool {
<add>func (a *Driver) Exists(id string) bool {
<ide> if _, err := os.Lstat(path.Join(a.rootPath(), "layers", id)); err != nil {
<ide> return false
<ide> } | 1 |
PHP | PHP | apply fixes from styleci | 76af3fbf3c67889506ebbb1e94bd1060a20e9e5c | <ide><path>tests/Notifications/NotificationMailMessageTest.php
<ide> public function testTemplate()
<ide>
<ide> $this->assertSame('notifications::foo', $message->markdown);
<ide> }
<add>
<ide> public function testHtmlView()
<ide> {
<ide> $message = new MailMessage;
<ide> public function testPlainView()
<ide> $this->assertSame(['foo' => 'bar'], $message->viewData);
<ide> }
<ide>
<del>
<ide> public function testCcIsSetCorrectly()
<ide> {
<ide> $message = new MailMessage; | 1 |
Ruby | Ruby | centralize definition of `rack` in formula.rb | 94dba21f7d5c3a1c6d935b62dd965c491a158e40 | <ide><path>Library/Homebrew/build.rb
<ide> def install f
<ide> rescue Exception
<ide> if f.prefix.directory?
<ide> f.prefix.rmtree
<del> f.prefix.parent.rmdir_if_possible
<add> f.rack.rmdir_if_possible
<ide> end
<ide> raise
<ide> end
<ide><path>Library/Homebrew/cmd/cleanup.rb
<ide> def cleanup
<ide>
<ide> def cleanup_formula f
<ide> f = Formula.factory f
<del> rack = f.prefix.parent
<ide>
<ide> # Don't clean up keg-only brews for now.
<ide> # Formulae link directly to them, so cleaning up old
<ide> # ones will break already compiled software.
<ide> if f.keg_only? and not ARGV.force?
<del> opoo "Skipping keg-only #{f.name}" if rack.children.length > 1
<add> opoo "Skipping keg-only #{f.name}" if f.rack.children.length > 1
<ide> return
<ide> end
<ide>
<del> if f.installed? and rack.directory?
<del> rack.children.each do |keg|
<add> if f.installed? and f.rack.directory?
<add> f.rack.children.each do |keg|
<ide> if f.installed_prefix != keg
<ide> print "Removing #{keg}..."
<ide> rm_rf keg
<ide> puts
<ide> end
<ide> end
<del> elsif rack.children.length > 1
<add> elsif f.rack.children.length > 1
<ide> # If the cellar only has one version installed, don't complain
<ide> # that we can't tell which one to keep.
<ide> opoo "Skipping #{f.name}: most recent version #{f.version} not installed"
<ide><path>Library/Homebrew/cmd/info.rb
<ide> def info_formula f
<ide>
<ide> puts "Depends on: #{f.deps*', '}" unless f.deps.empty?
<ide>
<del> rack = f.prefix.parent
<del> if rack.directory?
<del> kegs = rack.children
<add> if f.rack.directory?
<add> kegs = f.rack.children
<ide> kegs.each do |keg|
<ide> next if keg.basename.to_s == '.DS_Store'
<ide> print "#{keg} (#{keg.abv})"
<ide><path>Library/Homebrew/cmd/uninstall.rb
<ide> def uninstall
<ide> end
<ide> else
<ide> ARGV.formulae.each do |f|
<del> rack = f.prefix.parent
<del> if rack.directory?
<add> if f.rack.directory?
<ide> puts "Uninstalling #{f}..."
<del> rack.children.each do |keg|
<add> f.rack.children.each do |keg|
<ide> if keg.directory?
<ide> keg = Keg.new(keg)
<ide> keg.unlink
<ide> keg.rmtree
<ide> end
<ide> end
<del> rack.rmtree
<add> f.rack.rmtree
<ide> end
<ide> end
<ide> end
<ide><path>Library/Homebrew/cmd/upgrade.rb
<ide> def plural_s
<ide> end
<ide> end
<ide>
<del>class Formula
<del> def rack
<del> HOMEBREW_CELLAR/name
<del> end
<del>end
<del>
<ide> module Homebrew extend self
<ide> def upgrade
<ide> Homebrew.perform_preinstall_checks
<ide> def upgrade
<ide> ARGV.formulae.map do |f|
<ide> raise "#{f} already upgraded" if f.installed?
<ide> raise "#{f} not installed" unless f.rack.exist? and not f.rack.children.empty?
<del> [f.prefix.parent, f.name, f.version]
<add> [f.rack, f.name, f.version]
<ide> end
<ide> end
<ide>
<ide><path>Library/Homebrew/formula.rb
<ide> def prefix
<ide> validate_variable :version
<ide> HOMEBREW_CELLAR+@name+@version
<ide> end
<add> def rack; prefix.parent end
<ide>
<ide> def bin; prefix+'bin' end
<ide> def doc; prefix+'share/doc'+name end | 6 |
Javascript | Javascript | remove multimaterial from outlineeffect | 8f319e4a2c7af16435d0bbe6ae90f2a7e34af631 | <ide><path>examples/js/effects/OutlineEffect.js
<ide> *
<ide> * // How to set outline parameters for each material
<ide> * material.outlineParameters = {
<del> * thickNess: 0.01, // this paremeter won't work for MultiMaterial
<del> * color: new THREE.Color( 0x888888 ), // this paremeter won't work for MultiMaterial
<del> * alpha: 0.8, // this paremeter won't work for MultiMaterial
<add> * thickNess: 0.01,
<add> * color: new THREE.Color( 0x888888 ),
<add> * alpha: 0.8,
<ide> * visible: true,
<del> * keepAlive: true // this paremeter won't work for Material in materials of MultiMaterial
<add> * keepAlive: true
<ide> * };
<ide> *
<ide> * TODO
<ide> THREE.OutlineEffect = function ( renderer, parameters ) {
<ide> var defaultAlpha = parameters.defaultAlpha !== undefined ? parameters.defaultAlpha : 1.0;
<ide> var defaultKeepAlive = parameters.defaultKeepAlive !== undefined ? parameters.defaultKeepAlive : false;
<ide>
<del> // object.material.uuid -> outlineMaterial
<del> // (no mapping from children of MultiMaterial)
<add> // object.material.uuid -> outlineMaterial or
<add> // object.material[ n ].uuid -> outlineMaterial
<ide> // save at the outline material creation and release
<ide> // if it's unused removeThresholdCount frames
<ide> // unless keepAlive is true.
<ide> var cache = {};
<ide>
<ide> var removeThresholdCount = 60;
<ide>
<del> // outlineMaterial.uuid (or object.uuid for invisibleMaterial) -> originalMaterial
<del> // including children of MultiMaterial.
<add> // outlineMaterial.uuid -> object.material or
<add> // outlineMaterial.uuid -> object.material[ n ]
<ide> // save before render and release after render.
<ide> var originalMaterials = {};
<ide>
<ide> THREE.OutlineEffect = function ( renderer, parameters ) {
<ide>
<ide> //this.cache = cache; // for debug
<ide>
<del> var invisibleMaterial = new THREE.ShaderMaterial( { visible: false } );
<del>
<ide> // copied from WebGLPrograms and removed some materials
<ide> var shaderIDs = {
<ide> MeshBasicMaterial: 'basic',
<ide> THREE.OutlineEffect = function ( renderer, parameters ) {
<ide>
<ide> ].join( "\n" );
<ide>
<add> function createInvisibleMaterial() {
<add>
<add> return new THREE.ShaderMaterial( { name: 'invisible', visible: false } );
<add>
<add> }
<add>
<ide> function createMaterial( originalMaterial ) {
<ide>
<ide> var shaderID = shaderIDs[ originalMaterial.type ];
<ide> THREE.OutlineEffect = function ( renderer, parameters ) {
<ide> console.warn( 'THREE.OutlineEffect requires both vec3 position and normal attributes in vertex shader, ' +
<ide> 'does not draw outline for ' + originalMaterial.name + '(uuid:' + originalMaterial.uuid + ') material.' );
<ide>
<del> return invisibleMaterial;
<add> return createInvisibleMaterial();
<ide>
<ide> }
<ide>
<ide> THREE.OutlineEffect = function ( renderer, parameters ) {
<ide>
<ide> } else {
<ide>
<del> return invisibleMaterial;
<add> return createInvisibleMaterial();
<ide>
<ide> }
<ide>
<ide> THREE.OutlineEffect = function ( renderer, parameters ) {
<ide> if ( ! /vec3\s+transformed\s*=/.test( originalVertexShader ) &&
<ide> ! /#include\s+<begin_vertex>/.test( originalVertexShader ) ) defines.DECLARE_TRANSFORMED = true;
<ide>
<del> var material = new THREE.ShaderMaterial( {
<add> return new THREE.ShaderMaterial( {
<ide> defines: defines,
<ide> uniforms: uniforms,
<ide> vertexShader: vertexShader,
<ide> THREE.OutlineEffect = function ( renderer, parameters ) {
<ide> fog: false
<ide> } );
<ide>
<del> return material;
<del>
<del> }
<del>
<del> function createMultiMaterial( originalMaterial ) {
<del>
<del> var materials = [];
<del>
<del> for ( var i = 0, il = originalMaterial.materials.length; i < il; i ++ ) {
<del>
<del> materials.push( createMaterial( originalMaterial.materials[ i ] ) );
<del>
<del> }
<del>
<del> return new THREE.MultiMaterial( materials );
<del>
<ide> }
<ide>
<del> function setOutlineMaterial( object ) {
<del>
<del> if ( object.material === undefined ) return;
<add> function getOutlineMaterialFromCache( originalMaterial ) {
<ide>
<del> var data = cache[ object.material.uuid ];
<add> var data = cache[ originalMaterial.uuid ];
<ide>
<ide> if ( data === undefined ) {
<ide>
<ide> data = {
<del> material: object.material.isMultiMaterial === true ? createMultiMaterial( object.material ) : createMaterial( object.material ),
<add> material: createMaterial( originalMaterial ),
<ide> used: true,
<ide> keepAlive: defaultKeepAlive,
<ide> count: 0
<ide> };
<ide>
<del> cache[ object.material.uuid ] = data;
<add> cache[ originalMaterial.uuid ] = data;
<ide>
<ide> }
<ide>
<del> var outlineMaterial = data.material;
<ide> data.used = true;
<ide>
<del> var uuid = outlineMaterial !== invisibleMaterial ? outlineMaterial.uuid : object.uuid;
<del> originalMaterials[ uuid ] = object.material;
<add> return data.material;
<ide>
<del> if ( object.material.isMultiMaterial === true ) {
<add> }
<ide>
<del> for ( var i = 0, il = object.material.materials.length; i < il; i ++ ) {
<add> function getOutlineMaterial( originalMaterial ) {
<ide>
<del> // originalMaterial of leaf material of MultiMaterial is used only for
<del> // updating outlineMaterial. so need not to save for invisibleMaterial.
<del> if ( outlineMaterial.materials[ i ] !== invisibleMaterial ) {
<add> var outlineMaterial = getOutlineMaterialFromCache( originalMaterial );
<ide>
<del> originalMaterials[ outlineMaterial.materials[ i ].uuid ] = object.material.materials[ i ];
<add> originalMaterials[ outlineMaterial.uuid ] = originalMaterial;
<ide>
<del> }
<add> updateOutlineMaterial( outlineMaterial, originalMaterial );
<ide>
<del> }
<add> return outlineMaterial;
<add>
<add> }
<add>
<add> function setOutlineMaterial( object ) {
<add>
<add> if ( object.material === undefined ) return;
<ide>
<del> updateOutlineMultiMaterial( outlineMaterial, object.material );
<add> if ( Array.isArray( object.material ) ) {
<add>
<add> for ( var i = 0, il = object.material.length; i < il; i ++ ) {
<add>
<add> object.material[ i ] = getOutlineMaterial( object.material[ i ] );
<add>
<add> }
<ide>
<ide> } else {
<ide>
<del> updateOutlineMaterial( outlineMaterial, object.material );
<add> object.material = getOutlineMaterial( object.material );
<ide>
<ide> }
<ide>
<del> object.material = outlineMaterial;
<del>
<ide> originalOnBeforeRenders[ object.uuid ] = object.onBeforeRender;
<ide> object.onBeforeRender = onBeforeRender;
<ide>
<ide> THREE.OutlineEffect = function ( renderer, parameters ) {
<ide>
<ide> if ( object.material === undefined ) return;
<ide>
<del> var originalMaterial = originalMaterials[ object.material.uuid ];
<add> if ( Array.isArray( object.material ) ) {
<add>
<add> for ( var i = 0, il = object.material.length; i < il; i ++ ) {
<ide>
<del> if ( originalMaterial === undefined ) {
<add> object.material[ i ] = originalMaterials[ object.material[ i ].uuid ];
<add>
<add> }
<ide>
<del> originalMaterial = originalMaterials[ object.uuid ];
<add> } else {
<ide>
<del> if ( originalMaterial === undefined ) return;
<add> object.material = originalMaterials[ object.material.uuid ];
<ide>
<ide> }
<ide>
<del> object.material = originalMaterial;
<ide> object.onBeforeRender = originalOnBeforeRenders[ object.uuid ];
<ide>
<ide> }
<ide>
<ide> function onBeforeRender( renderer, scene, camera, geometry, material, group ) {
<ide>
<del> // check some things before updating just in case
<del>
<del> if ( material === invisibleMaterial ) return;
<del>
<del> if ( material.isMultiMaterial === true ) return;
<del>
<ide> var originalMaterial = originalMaterials[ material.uuid ];
<ide>
<add> // just in case
<ide> if ( originalMaterial === undefined ) return;
<ide>
<ide> updateUniforms( material, originalMaterial );
<ide> THREE.OutlineEffect = function ( renderer, parameters ) {
<ide>
<ide> function updateOutlineMaterial( material, originalMaterial ) {
<ide>
<del> if ( material === invisibleMaterial ) return;
<add> if ( material.name === 'invisible' ) return;
<ide>
<ide> var outlineParameters = originalMaterial.outlineParameters;
<ide>
<ide> THREE.OutlineEffect = function ( renderer, parameters ) {
<ide>
<ide> material.transparent = ( outlineParameters.alpha !== undefined && outlineParameters.alpha < 1.0 ) ? true : originalMaterial.transparent;
<ide>
<del> // cache[ originalMaterial.uuid ] is undefined if originalMaterial is in materials of MultiMaterial
<del> if ( outlineParameters.keepAlive !== undefined && cache[ originalMaterial.uuid ] !== undefined ) cache[ originalMaterial.uuid ].keepAlive = outlineParameters.keepAlive;
<add> if ( outlineParameters.keepAlive !== undefined ) cache[ originalMaterial.uuid ].keepAlive = outlineParameters.keepAlive;
<ide>
<ide> } else {
<ide>
<ide> THREE.OutlineEffect = function ( renderer, parameters ) {
<ide>
<ide> }
<ide>
<del> function updateOutlineMultiMaterial( material, originalMaterial ) {
<del>
<del> if ( material === invisibleMaterial ) return;
<del>
<del> var outlineParameters = originalMaterial.outlineParameters;
<del>
<del> if ( outlineParameters !== undefined ) {
<del>
<del> if ( originalMaterial.visible === false ) {
<del>
<del> material.visible = false;
<del>
<del> } else {
<del>
<del> material.visible = ( outlineParameters.visible !== undefined ) ? outlineParameters.visible : true;
<del>
<del> }
<del>
<del> if ( outlineParameters.keepAlive !== undefined ) cache[ originalMaterial.uuid ].keepAlive = outlineParameters.keepAlive;
<del>
<del> } else {
<del>
<del> material.visible = originalMaterial.visible;
<del>
<del> }
<del>
<del> for ( var i = 0, il = material.materials.length; i < il; i ++ ) {
<del>
<del> updateOutlineMaterial( material.materials[ i ], originalMaterial.materials[ i ] );
<del>
<del> }
<del>
<del> }
<del>
<ide> function cleanupCache() {
<ide>
<ide> var keys; | 1 |
PHP | PHP | add joiningtablesegment to model | a43562b6a139887b421d1d3f3fdfc110c9a8df2b | <ide><path>src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php
<ide> public function belongsToMany($related, $table = null, $foreignPivotKey = null,
<ide> // models using underscores in alphabetical order. The two model names
<ide> // are transformed to snake case from their default CamelCase also.
<ide> if (is_null($table)) {
<del> $table = $this->joiningTable($related);
<add> $table = $this->joiningTable($related, $instance);
<ide> }
<ide>
<ide> return $this->newBelongsToMany(
<ide> protected function guessBelongsToManyRelation()
<ide> * Get the joining table name for a many-to-many relation.
<ide> *
<ide> * @param string $related
<add> * @param \Illuminate\Database\Eloquent\Model|null $instance
<ide> * @return string
<ide> */
<del> public function joiningTable($related)
<add> public function joiningTable($related, $instance = null)
<ide> {
<ide> // The joining table name, by convention, is simply the snake cased models
<ide> // sorted alphabetically and concatenated with an underscore, so we can
<ide> // just sort the models and join them together to get the table name.
<del> $models = [
<del> Str::snake(class_basename($related)),
<del> Str::snake(class_basename($this)),
<add> $segments = [
<add> $instance ? $instance->joiningTableSegment()
<add> : Str::snake(class_basename($related)),
<add> $this->joiningTableSegment(),
<ide> ];
<ide>
<ide> // Now that we have the model names in an array we can just sort them and
<ide> // use the implode function to join them together with an underscores,
<ide> // which is typically used by convention within the database system.
<del> sort($models);
<add> sort($segments);
<ide>
<del> return strtolower(implode('_', $models));
<add> return strtolower(implode('_', $segments));
<add> }
<add>
<add> /**
<add> * Get this model's half of the intermediate table name for belongsToMany relationships.
<add> *
<add> * @return string
<add> */
<add> public function joiningTableSegment()
<add> {
<add> return Str::snake(class_basename($this));
<ide> }
<ide>
<ide> /** | 1 |
Python | Python | add convert command | 789ce8a45eb56c6103757a5731fc0f6ee0f02aff | <ide><path>spacy/__main__.py
<ide> from spacy.cli import package as cli_package
<ide> from spacy.cli import train as cli_train
<ide> from spacy.cli import model as cli_model
<add>from spacy.cli import convert as cli_convert
<ide>
<ide>
<ide> class CLI(object):
<ide> """Command-line interface for spaCy"""
<ide>
<del> commands = ('download', 'link', 'info', 'package', 'train', 'model')
<add> commands = ('download', 'link', 'info', 'package', 'train', 'model', 'convert')
<ide>
<ide> @plac.annotations(
<ide> model=("model to download (shortcut or model name)", "positional", None, str),
<ide> def model(self, lang, model_dir, freqs_data, clusters_data=None, vectors_data=No
<ide>
<ide> cli_model(lang, model_dir, freqs_data, clusters_data, vectors_data)
<ide>
<add> @plac.annotations(
<add> input_file=("input file", "positional", None, str),
<add> output_dir=("output directory for converted file", "positional", None, str),
<add> n_sents=("Number of sentences per doc", "option", "n", float),
<add> morphology=("Enable appending morphology to tags", "flag", "m", bool)
<add> )
<add> def convert(self, input_file, output_dir, n_sents=10, morphology=False):
<add> """
<add> Convert files into JSON format for use with train command and other
<add> experiment management functions.
<add> """
<add>
<add> cli_convert(input_file, output_dir, n_sents, morphology)
<add>
<ide>
<ide> def __missing__(self, name):
<ide> print("\n Command %r does not exist."
<ide><path>spacy/cli/__init__.py
<ide> from .package import package
<ide> from .train import train, train_config
<ide> from .model import model
<add>from .convert import convert
<ide><path>spacy/cli/convert.py
<add># coding: utf8
<add>from __future__ import unicode_literals, division, print_function
<add>
<add>import io
<add>from pathlib import Path, PurePosixPath
<add>
<add>from .converters import conllu2json
<add>from .. import util
<add>
<add>
<add># Converters are matched by file extension. To add a converter, add a new entry
<add># to this dict with the file extension mapped to the converter function imported
<add># from /converters.
<add>
<add>CONVERTERS = {
<add> '.conllu': conllu2json
<add>}
<add>
<add>
<add>def convert(input_file, output_dir, *args):
<add> input_path = Path(input_file)
<add> output_path = Path(output_dir)
<add> check_dirs(input_path, output_path)
<add> file_ext = input_path.suffix
<add>
<add> if file_ext in CONVERTERS:
<add> CONVERTERS[file_ext](input_path, output_path, *args)
<add> else:
<add> util.sys_exit("Can't find converter for {}".format(input_path.parts[-1]),
<add> title="Unknown format")
<add>
<add>
<add>def check_dirs(input_file, output_path):
<add> if not input_file.exists():
<add> util.sys_exit(input_file.as_posix(), title="Input file not found")
<add> if not output_path.exists():
<add> util.sys_exit(output_path.as_posix(), title="Output directory not found") | 3 |
Ruby | Ruby | remove unknown yard tags | 65f17664971391895d8167963e07517742730309 | <ide><path>Library/Homebrew/extend/ENV/super.rb
<ide> def self.extended(base)
<ide> end
<ide>
<ide> # The location of Homebrew's shims on this OS.
<del> # @public
<ide> sig { returns(Pathname) }
<ide> def self.shims_path
<ide> HOMEBREW_SHIMS_PATH/"super"
<ide><path>Library/Homebrew/extend/os/linux/extend/ENV/super.rb
<ide> module Superenv
<ide> extend T::Sig
<ide>
<ide> # The location of Homebrew's shims on Linux.
<del> # @public
<ide> def self.shims_path
<ide> HOMEBREW_SHIMS_PATH/"linux/super"
<ide> end
<ide><path>Library/Homebrew/extend/os/mac/extend/ENV/super.rb
<ide> module Superenv
<ide>
<ide> class << self
<ide> # The location of Homebrew's shims on macOS.
<del> # @public
<ide> def shims_path
<ide> HOMEBREW_SHIMS_PATH/"mac/super"
<ide> end | 3 |
PHP | PHP | improve handling of arrayobject instances | fbaae50200851ee89d3eca52bf42f1f54f0d7d39 | <ide><path>src/Log/Engine/BaseLog.php
<ide> */
<ide> namespace Cake\Log\Engine;
<ide>
<add>use ArrayObject;
<ide> use Cake\Core\InstanceConfigTrait;
<ide> use JsonSerializable;
<ide> use Psr\Log\AbstractLogger;
<ide> protected function _format(string $message, array $context = []): string
<ide> continue;
<ide> }
<ide>
<add> if ($value instanceof ArrayObject) {
<add> $replacements['{' . $key . '}'] = print_r($value->getArrayCopy(), true);
<add> continue;
<add> }
<add>
<ide> if ($value instanceof Serializable) {
<ide> $replacements['{' . $key . '}'] = $value->serialize();
<ide> continue;
<ide><path>tests/TestCase/Log/Engine/BaseLogTest.php
<ide> public function testPlaceHoldersInMessage()
<ide> 'bool' => true,
<ide> 'json' => new Entity(['foo' => 'bar']),
<ide> 'array' => ['arr'],
<del> 'serializable' => new ArrayObject(['x' => 'y']),
<add> 'array-obj' => new ArrayObject(['x' => 'y']),
<ide> 'debug-info' => ConnectionManager::get('test'),
<ide> 'obj' => function () {
<ide> },
<ide> ];
<ide> $this->logger->log(
<ide> LogLevel::INFO,
<ide> '1: {string}, 2: {bool}, 3: {json}, 4: {not a placeholder}, 5: {array}, '
<del> . '6: {serializable} 7: {obj}, 8: {debug-info} 9: {valid-ph-not-in-context}',
<add> . '6: {array-obj} 7: {obj}, 8: {debug-info} 9: {valid-ph-not-in-context}',
<ide> $context
<ide> );
<ide>
<ide> public function testPlaceHoldersInMessage()
<ide> $this->assertStringContainsString('3: {"foo":"bar"}', $message);
<ide> $this->assertStringContainsString('4: {not a placeholder}', $message);
<ide> $this->assertStringContainsString("5: Array\n(\n [0] => arr\n)", $message);
<del> $this->assertStringContainsString('6: x:i:0;a:1:{s:1:"x";s:1:"y";};m:a:0:{}', $message);
<add> $this->assertStringContainsString("6: Array\n(\n [x] => y\n)", $message);
<ide> $this->assertStringContainsString('7: [unhandled value of type Closure]', $message);
<ide> $this->assertStringContainsString("8: Array\n(\n [config] => Array\n", $message);
<ide> $this->assertStringContainsString('9: {valid-ph-not-in-context}', $message); | 2 |
Go | Go | add push fallback to v1 for the official registry | 7d62943178e803663b4939666377b75a21d3e537 | <ide><path>graph/push.go
<ide> package graph
<ide>
<ide> import (
<ide> "bytes"
<add> "errors"
<ide> "fmt"
<ide> "io"
<ide> "io/ioutil"
<ide> import (
<ide> "github.com/docker/libtrust"
<ide> )
<ide>
<add>var ErrV2RegistryUnavailable = errors.New("error v2 registry unavailable")
<add>
<ide> // Retrieve the all the images to be uploaded in the correct order
<ide> func (s *TagStore) getImageList(localRepo map[string]string, requestedTag string) ([]string, map[string][]string, error) {
<ide> var (
<ide> func (s *TagStore) pushV2Repository(r *registry.Session, eng *engine.Engine, out
<ide>
<ide> endpoint, err := r.V2RegistryEndpoint(repoInfo.Index)
<ide> if err != nil {
<add> if repoInfo.Index.Official {
<add> log.Infof("Unable to push to V2 registry, falling back to v1: %s", err)
<add> return ErrV2RegistryUnavailable
<add> }
<ide> return fmt.Errorf("error getting registry endpoint: %s", err)
<ide> }
<ide> auth, err := r.GetV2Authorization(endpoint, repoInfo.RemoteName, false)
<ide> func (s *TagStore) CmdPush(job *engine.Job) engine.Status {
<ide> return engine.StatusOK
<ide> }
<ide>
<del> // error out, no fallback to V1
<del> return job.Errorf("Error pushing to registry: %s", err)
<add> if err != ErrV2RegistryUnavailable {
<add> return job.Errorf("Error pushing to registry: %s", err)
<add> }
<ide> }
<ide>
<ide> if err != nil { | 1 |
Python | Python | fix lint errors | 9d9cb200cb2d8c24d648f342ecc67b90efcf1f48 | <ide><path>numpy/lib/function_base.py
<ide> def _parse_gufunc_signature(signature):
<ide> if not re.match(_SIGNATURE, signature):
<ide> raise ValueError(
<ide> 'not a valid gufunc signature: {}'.format(signature))
<del> return tuple([tuple([dim.strip() for dim in re.findall(_DIMENSION_NAME, arg)])
<add> return tuple([tuple([dim.strip()
<add> for dim in re.findall(_DIMENSION_NAME, arg)])
<ide> for arg in re.findall(_ARGUMENT, arg_list)]
<ide> for arg_list in signature.split('->'))
<ide>
<ide><path>numpy/lib/tests/test_function_base.py
<ide> def test_parse_gufunc_signature(self):
<ide> ([('x',)], [('y',)]))
<ide> assert_equal(nfb._parse_gufunc_signature(' (x)->( y),( )'),
<ide> ([('x',)], [('y',), ()]))
<del> assert_equal(nfb._parse_gufunc_signature('( ), ( a, b,c ) ,( d) -> (d , e)'),
<add> assert_equal(nfb._parse_gufunc_signature(
<add> '( ), ( a, b,c ) ,( d) -> (d , e)'),
<ide> ([(), ('a', 'b', 'c'), ('d',)], [('d', 'e')]))
<ide>
<ide> with assert_raises(ValueError): | 2 |
Python | Python | remove parametrization in pickle_utils_test.py | f1c5826dbfdbc62ae6eea599d939b9da2f70f1ab | <ide><path>keras/saving/pickle_utils_test.py
<ide> class TestPickleProtocol(keras_parameterized.TestCase):
<ide> """Tests pickle protoocol support.
<ide> """
<ide>
<del> @keras_parameterized.run_all_keras_modes
<ide> def test_pickle_model(self):
<ide> """Test copy.copy, copy.deepcopy and pickle on Functional Model."""
<ide> | 1 |
Javascript | Javascript | mutate the children array | 2993b168e55cd83d4bcf9265cad32bbe37e8a87e | <ide><path>src/devtools/store.js
<ide> export default class Store extends EventEmitter {
<ide> const parentElement = ((this._idToElement.get(
<ide> parentID
<ide> ): any): Element);
<del> parentElement.children = parentElement.children.concat(id);
<add> parentElement.children.push(id);
<ide>
<ide> const element: Element = {
<ide> children: [],
<ide> export default class Store extends EventEmitter {
<ide> `Cannot remove node ${id} from parent ${parentID} because no matching node was found in the Store.`
<ide> );
<ide> }
<del> parentElement.children = parentElement.children.filter(
<del> childID => childID !== id
<del> );
<add> const index = parentElement.children.indexOf(id);
<add> parentElement.children.splice(index, 1);
<ide> }
<ide>
<ide> this._adjustParentTreeWeight(parentElement, -element.weight);
<ide> export default class Store extends EventEmitter {
<ide> case TREE_OPERATION_REORDER_CHILDREN: {
<ide> const id = ((operations[i + 1]: any): number);
<ide> const numChildren = ((operations[i + 2]: any): number);
<del> const nextChildren = ((operations.slice(
<del> i + 3,
<del> i + 3 + numChildren
<del> ): any): Array<number>);
<del>
<del> i = i + 3 + numChildren;
<del>
<del> if (__DEBUG__) {
<del> debug('Re-order', `Node ${id} children ${nextChildren.join(',')}`);
<del> }
<add> i = i + 3;
<ide>
<ide> if (!this._idToElement.has(id)) {
<ide> throw Error(
<ide> export default class Store extends EventEmitter {
<ide> }
<ide>
<ide> const element = ((this._idToElement.get(id): any): Element);
<del> const prevChildren = element.children;
<del> if (nextChildren.length !== prevChildren.length) {
<add> const children = element.children;
<add> if (children.length !== numChildren) {
<ide> throw Error(
<ide> `Children cannot be added or removed during a reorder operation.`
<ide> );
<ide> }
<del> // This check is more expensive so it's gated
<del> if (__DEV__) {
<del> if (
<del> nextChildren.find(childID => {
<del> const childElement = this._idToElement.get(childID);
<del> return childElement == null || childElement.parentID !== id;
<del> }) != null
<del> ) {
<del> console.error(
<del> `Children cannot be added or removed during a reorder operation.`
<del> );
<add>
<add> for (let j = 0; j < numChildren; j++) {
<add> const childID = operations[i + j];
<add> children[j] = childID;
<add> if (__DEV__) {
<add> // This check is more expensive so it's gated by __DEV__.
<add> const childElement = this._idToElement.get(childID);
<add> if (childElement == null || childElement.parentID !== id) {
<add> console.error(
<add> `Children cannot be added or removed during a reorder operation.`
<add> );
<add> }
<ide> }
<ide> }
<del> element.children = Array.from(nextChildren);
<add> i = i + numChildren;
<add>
<add> if (__DEBUG__) {
<add> debug('Re-order', `Node ${id} children ${children.join(',')}`);
<add> }
<ide> break;
<ide> }
<ide> case TREE_OPERATION_UPDATE_TREE_BASE_DURATION: | 1 |
Javascript | Javascript | increase coverage for _http_incoming.js | 19291351bb13381818a033ae22aa9c6a28fd6e95 | <ide><path>test/parallel/test-http-incoming-message-connection-setter.js
<add>'use strict';
<add>
<add>// Test that the setter for http.IncomingMessage,prototype.connection sets the
<add>// socket property too.
<add>require('../common');
<add>
<add>const assert = require('assert');
<add>const http = require('http');
<add>
<add>const incomingMessage = new http.IncomingMessage();
<add>
<add>assert.strictEqual(incomingMessage.connection, undefined);
<add>assert.strictEqual(incomingMessage.socket, undefined);
<add>
<add>incomingMessage.connection = 'fhqwhgads';
<add>
<add>assert.strictEqual(incomingMessage.connection, 'fhqwhgads');
<add>assert.strictEqual(incomingMessage.socket, 'fhqwhgads'); | 1 |
PHP | PHP | add trailing ds | 0f278b84f7771539d8ea9f0ea97e6d8b5adb9025 | <ide><path>tests/TestCase/Cache/CacheTest.php
<ide> public function testCacheFallbackIntegration()
<ide> ]);
<ide> Cache::setConfig('tests_fallback_final', [
<ide> 'engine' => 'File',
<del> 'path' => TMP . 'cake_test',
<add> 'path' => TMP . 'cake_test' . DS,
<ide> 'groups' => ['integration_group_3'],
<ide> ]);
<ide> | 1 |
Python | Python | add disable retry flag on backfill | ada0f13a2a738e67433070f2ecba4114065136d2 | <ide><path>airflow/cli/cli_parser.py
<ide> def string_lower_type(val):
<ide> help=("if set, the backfill will keep going even if some of the tasks failed"),
<ide> action="store_true",
<ide> )
<add>ARG_DISABLE_RETRY = Arg(
<add> ("--disable-retry",),
<add> help=("if set, the backfill will set tasks as failed without retrying."),
<add> action="store_true",
<add>)
<ide> ARG_RUN_BACKWARDS = Arg(
<ide> (
<ide> "-B",
<ide> class GroupCommand(NamedTuple):
<ide> ARG_DONOT_PICKLE,
<ide> ARG_YES,
<ide> ARG_CONTINUE_ON_FAILURES,
<add> ARG_DISABLE_RETRY,
<ide> ARG_BF_IGNORE_DEPENDENCIES,
<ide> ARG_BF_IGNORE_FIRST_DEPENDS_ON_PAST,
<ide> ARG_SUBDIR,
<ide><path>airflow/cli/commands/dag_command.py
<ide> def dag_backfill(args, dag=None):
<ide> rerun_failed_tasks=args.rerun_failed_tasks,
<ide> run_backwards=args.run_backwards,
<ide> continue_on_failures=args.continue_on_failures,
<add> disable_retry=args.disable_retry,
<ide> )
<ide> except ValueError as vr:
<ide> print(str(vr))
<ide><path>airflow/jobs/backfill_job.py
<ide> def __init__(
<ide> run_backwards=False,
<ide> run_at_least_once=False,
<ide> continue_on_failures=False,
<add> disable_retry=False,
<ide> *args,
<ide> **kwargs,
<ide> ):
<ide> def __init__(
<ide> self.run_backwards = run_backwards
<ide> self.run_at_least_once = run_at_least_once
<ide> self.continue_on_failures = continue_on_failures
<add> self.disable_retry = disable_retry
<ide> super().__init__(*args, **kwargs)
<ide>
<ide> def _update_counters(self, ti_status, session=None):
<ide> def to_keep(key: TaskInstanceKey) -> bool:
<ide> for new_ti in new_mapped_tis:
<ide> new_ti.set_state(TaskInstanceState.SCHEDULED, session=session)
<ide>
<add> # Set state to failed for running TIs that are set up for retry if disable-retry flag is set
<add> for ti in ti_status.running.values():
<add> if self.disable_retry and ti.state == TaskInstanceState.UP_FOR_RETRY:
<add> ti.set_state(TaskInstanceState.FAILED, session=session)
<add>
<ide> # update the task counters
<ide> self._update_counters(ti_status=ti_status, session=session)
<ide> session.commit()
<ide><path>airflow/models/dag.py
<ide> def run(
<ide> run_backwards=False,
<ide> run_at_least_once=False,
<ide> continue_on_failures=False,
<add> disable_retry=False,
<ide> ):
<ide> """
<ide> Runs the DAG.
<ide> def run(
<ide> run_backwards=run_backwards,
<ide> run_at_least_once=run_at_least_once,
<ide> continue_on_failures=continue_on_failures,
<add> disable_retry=disable_retry,
<ide> )
<ide> job.run()
<ide>
<ide><path>tests/cli/commands/test_dag_command.py
<ide> def test_backfill(self, mock_run):
<ide> run_backwards=False,
<ide> verbose=False,
<ide> continue_on_failures=False,
<add> disable_retry=False,
<ide> )
<ide> mock_run.reset_mock()
<ide> dag = self.dagbag.get_dag("example_bash_operator")
<ide> def test_backfill(self, mock_run):
<ide> run_backwards=False,
<ide> verbose=False,
<ide> continue_on_failures=False,
<add> disable_retry=False,
<ide> )
<ide> mock_run.reset_mock()
<ide>
<ide> def test_cli_backfill_depends_on_past(self, mock_run):
<ide> run_backwards=False,
<ide> verbose=False,
<ide> continue_on_failures=False,
<add> disable_retry=False,
<ide> )
<ide>
<ide> @mock.patch("airflow.cli.commands.dag_command.DAG.run")
<ide> def test_cli_backfill_depends_on_past_backwards(self, mock_run):
<ide> run_backwards=True,
<ide> verbose=False,
<ide> continue_on_failures=False,
<add> disable_retry=False,
<ide> )
<ide>
<ide> def test_next_execution(self):
<ide><path>tests/jobs/test_backfill_job.py
<ide> def test_task_instances_are_not_set_to_scheduled_when_dagrun_reset(self, dag_mak
<ide> states = [ti.state for _, ti in tasks_to_run.items()]
<ide> assert TaskInstanceState.SCHEDULED in states
<ide> assert State.NONE in states
<add>
<add> @pytest.mark.parametrize(
<add> ["disable_retry", "try_number", "exception"],
<add> (
<add> (True, 1, BackfillUnfinished),
<add> (False, 2, AirflowException),
<add> ),
<add> )
<add> def test_backfill_disable_retry(self, dag_maker, disable_retry, try_number, exception):
<add> with dag_maker(
<add> dag_id="test_disable_retry",
<add> schedule_interval="@daily",
<add> default_args={
<add> "retries": 2,
<add> "retry_delay": datetime.timedelta(seconds=3),
<add> },
<add> ) as dag:
<add> task1 = EmptyOperator(task_id="task1")
<add> dag_run = dag_maker.create_dagrun(state=None)
<add>
<add> executor = MockExecutor(parallelism=16)
<add> executor.mock_task_results[
<add> TaskInstanceKey(dag.dag_id, task1.task_id, dag_run.run_id, try_number=1)
<add> ] = TaskInstanceState.UP_FOR_RETRY
<add> executor.mock_task_results[
<add> TaskInstanceKey(dag.dag_id, task1.task_id, dag_run.run_id, try_number=2)
<add> ] = TaskInstanceState.FAILED
<add>
<add> job = BackfillJob(
<add> dag=dag,
<add> executor=executor,
<add> start_date=DEFAULT_DATE,
<add> end_date=DEFAULT_DATE,
<add> disable_retry=disable_retry,
<add> )
<add> with pytest.raises(exception):
<add> job.run()
<add> ti = dag_run.get_task_instance(task_id=task1.task_id)
<add>
<add> assert ti._try_number == try_number
<add>
<add> dag_run.refresh_from_db()
<add>
<add> assert dag_run.state == DagRunState.FAILED
<add>
<add> dag.clear() | 6 |
Python | Python | replace requests with urllib | 7fbc9e587439bc63feb30e2ff1852fbed7f89d83 | <ide><path>spacy/cli/download.py
<ide> from __future__ import unicode_literals
<ide>
<ide> import plac
<del>import requests
<ide> import os
<ide> import subprocess
<ide> import sys
<add>import ujson
<ide>
<ide> from .link import link
<ide> from ..util import prints, get_package_path
<add>from ..compat import url_open, url_error
<ide> from .. import about
<ide>
<ide>
<ide> def download(model, direct=False):
<ide>
<ide>
<ide> def get_json(url, desc):
<del> r = requests.get(url)
<del> if r.status_code != 200:
<add> try:
<add> r = url_open(url)
<add> except url_error as e:
<ide> msg = ("Couldn't fetch %s. Please find a model for your spaCy "
<ide> "installation (v%s), and download it manually.")
<ide> prints(msg % (desc, about.__version__), about.__docs_models__,
<del> title="Server error (%d)" % r.status_code, exits=1)
<del> return r.json()
<add> title="Server error (%d: %s)" % (e.code, e.reason), exits=1)
<add> return ujson.load(r)
<ide>
<ide>
<ide> def get_compatibility():
<ide><path>spacy/cli/validate.py
<ide> # coding: utf8
<ide> from __future__ import unicode_literals, print_function
<ide>
<del>import requests
<ide> import pkg_resources
<ide> from pathlib import Path
<ide> import sys
<add>import ujson
<ide>
<del>from ..compat import path2str, locale_escape
<add>from ..compat import path2str, locale_escape, url_open, url_error
<ide> from ..util import prints, get_data_path, read_json
<ide> from .. import about
<ide>
<ide> def validate():
<ide> """Validate that the currently installed version of spaCy is compatible
<ide> with the installed models. Should be run after `pip install -U spacy`.
<ide> """
<del> r = requests.get(about.__compatibility__)
<del> if r.status_code != 200:
<add> try:
<add> r = url_open(about.__compatibility__)
<add> except url_error as e:
<ide> prints("Couldn't fetch compatibility table.",
<del> title="Server error (%d)" % r.status_code, exits=1)
<del> compat = r.json()['spacy']
<add> title="Server error (%d: %s)" % (e.code, e.reason), exits=1)
<add> compat = ujson.load(r)['spacy']
<ide> current_compat = compat.get(about.__version__)
<ide> if not current_compat:
<ide> prints(about.__compatibility__, exits=1, | 2 |
Go | Go | handle error from getdevice early | 17b95ecb08f1705bd74d6c94c8bcfd4c87ccfca6 | <ide><path>daemon/container.go
<ide> func populateCommand(c *Container, env []string) error {
<ide> userSpecifiedDevices := make([]*devices.Device, len(c.hostConfig.Devices))
<ide> for i, deviceMapping := range c.hostConfig.Devices {
<ide> device, err := devices.GetDevice(deviceMapping.PathOnHost, deviceMapping.CgroupPermissions)
<del> device.Path = deviceMapping.PathInContainer
<ide> if err != nil {
<del> return fmt.Errorf("error gathering device information while adding custom device %s", err)
<add> return fmt.Errorf("error gathering device information while adding custom device %q: %s", deviceMapping.PathOnHost, err)
<ide> }
<add> device.Path = deviceMapping.PathInContainer
<ide> userSpecifiedDevices[i] = device
<ide> }
<ide> allowedDevices := append(devices.DefaultAllowedDevices, userSpecifiedDevices...)
<ide><path>integration-cli/docker_cli_run_test.go
<ide> func TestWriteResolvFileAndNotCommit(t *testing.T) {
<ide>
<ide> logDone("run - write to /etc/resolv.conf and not commited")
<ide> }
<add>
<add>func TestRunWithBadDevice(t *testing.T) {
<add> name := "baddevice"
<add> cmd := exec.Command(dockerBinary, "run", "--name", name, "--device", "/etc", "busybox", "true")
<add> out, _, err := runCommandWithOutput(cmd)
<add> if err == nil {
<add> t.Fatal("Run should fail with bad device")
<add> }
<add> expected := `"/etc": not a device node`
<add> if !strings.Contains(out, expected) {
<add> t.Fatalf("Output should contain %q, actual out: %q", expected, out)
<add> }
<add> logDone("run - error with bad device")
<add>} | 2 |
Javascript | Javascript | improve grammar of apollo.js comments | 1c64c1e93c5e6e0855b1cff987889886b155e34a | <ide><path>examples/with-apollo/lib/apollo.js
<ide> import App from 'next/app'
<ide> import { ApolloProvider } from '@apollo/react-hooks'
<ide> import createApolloClient from '../apolloClient'
<ide>
<del>// On the client we store the apollo client in the following variable
<del>// this prevents the client from reinitializing between page transitions.
<add>// On the client, we store the Apollo Client in the following variable.
<add>// This prevents the client from reinitializing between page transitions.
<ide> let globalApolloClient = null
<ide>
<ide> /**
<del> * Installes the apollo client on NextPageContext
<add> * Installs the Apollo Client on NextPageContext
<ide> * or NextAppContext. Useful if you want to use apolloClient
<ide> * inside getStaticProps, getStaticPaths or getServerProps
<ide> * @param {NextPageContext | NextAppContext} ctx
<ide> export const initOnContext = ctx => {
<ide> ctx.apolloClient ||
<ide> initApolloClient(ctx.apolloState || {}, inAppContext ? ctx.ctx : ctx)
<ide>
<del> // To avoid calling initApollo() twice in the server we send the Apollo Client as a prop
<del> // to the component, otherwise the component would have to call initApollo() again but this
<del> // time without the context, once that happens the following code will make sure we send
<del> // the prop as `null` to the browser
<add> // We send the Apollo Client as a prop to the component to avoid calling initApollo() twice in the server.
<add> // Otherwise, the component would have to call initApollo() again but this
<add> // time without the context. Once that happens, the following code will make sure we send
<add> // the prop as `null` to the browser.
<ide> apolloClient.toJSON = () => null
<ide>
<del> // Add apolloClient to NextPageContext & NextAppContext
<add> // Add apolloClient to NextPageContext & NextAppContext.
<ide> // This allows us to consume the apolloClient inside our
<ide> // custom `getInitialProps({ apolloClient })`.
<ide> ctx.apolloClient = apolloClient | 1 |
Javascript | Javascript | reduce function calls | 7dc707042692398392bd910b01f3a6aab81a90a0 | <ide><path>src/effects.js
<ide> jQuery.fn.extend({
<ide> jQuery._mark( this );
<ide> }
<ide>
<del> var opt = jQuery.extend({}, optall), p,
<add> var opt = jQuery.extend({}, optall),
<ide> isElement = this.nodeType === 1,
<ide> hidden = isElement && jQuery(this).is(":hidden"),
<del> self = this;
<add> self = this,
<add> name, val, p,
<add> easing, display, e,
<add> parts, start, end, unit;
<add>
<add> // will store per property easing and be used to determine when an animation is complete
<add> opt.animatedProperties = {};
<ide>
<ide> for ( p in prop ) {
<del> var name = jQuery.camelCase( p );
<ide>
<add> // property name normalization
<add> name = jQuery.camelCase( p );
<ide> if ( p !== name ) {
<ide> prop[ name ] = prop[ p ];
<ide> delete prop[ p ];
<ide> p = name;
<ide> }
<ide>
<add> val = prop[p];
<add>
<add> if ( val === "hide" && hidden || val === "show" && !hidden ) {
<add> return opt.complete.call(self);
<add> }
<add>
<ide> if ( prop[p] === "hide" && hidden || prop[p] === "show" && !hidden ) {
<ide> return opt.complete.call(this);
<ide> }
<ide> jQuery.fn.extend({
<ide> }
<ide> }
<ide>
<del> if ( jQuery.isArray( prop[p] ) ) {
<del> // Create (if needed) and add to specialEasing
<del> (opt.specialEasing = opt.specialEasing || {})[p] = prop[p][1];
<del> prop[p] = prop[p][0];
<add> // easing resolution: per property > opt.specialEasing > opt.easing > 'swing' (default)
<add> if ( jQuery.isArray( val ) ) {
<add> easing = val[1];
<add> val = val[0];
<add> } else {
<add> easing = opt.specialEasing && opt.specialEasing[p] || opt.easing || 'swing';
<ide> }
<add> opt.animatedProperties[p] = easing;
<ide> }
<ide>
<ide> if ( opt.overflow != null ) {
<ide> this.style.overflow = "hidden";
<ide> }
<ide>
<del> opt.curAnim = jQuery.extend({}, prop);
<add> for ( p in prop ) {
<add> e = new jQuery.fx( self, opt, p );
<ide>
<del> jQuery.each( prop, function( name, val ) {
<del> var e = new jQuery.fx( self, opt, name );
<add> val = prop[p];
<ide>
<ide> if ( rfxtypes.test(val) ) {
<del> e[ val === "toggle" ? hidden ? "show" : "hide" : val ]( prop );
<add> e[ val === "toggle" ? hidden ? "show" : "hide" : val ]();
<ide>
<ide> } else {
<del> var parts = rfxnum.exec(val),
<del> start = e.cur();
<add> parts = rfxnum.exec(val);
<add> start = e.cur();
<ide>
<ide> if ( parts ) {
<del> var end = parseFloat( parts[2] ),
<del> unit = parts[3] || ( jQuery.cssNumber[ name ] ? "" : "px" );
<add> end = parseFloat( parts[2] );
<add> unit = parts[3] || ( jQuery.cssNumber[ name ] ? "" : "px" );
<ide>
<ide> // We need to compute starting value
<ide> if ( unit !== "px" ) {
<del> jQuery.style( self, name, (end || 1) + unit);
<add> jQuery.style( self, p, (end || 1) + unit);
<ide> start = ((end || 1) / e.cur()) * start;
<del> jQuery.style( self, name, start + unit);
<add> jQuery.style( self, p, start + unit);
<ide> }
<ide>
<ide> // If a +=/-= token was provided, we're doing a relative animation
<ide> jQuery.fn.extend({
<ide> e.custom( start, val, "" );
<ide> }
<ide> }
<del> });
<add> }
<ide>
<ide> // For JS strict compliance
<ide> return true;
<ide> });
<ide> },
<ide>
<ide> stop: function( clearQueue, gotoEnd ) {
<del> var timers = jQuery.timers;
<del>
<ide> if ( clearQueue ) {
<ide> this.queue([]);
<ide> }
<ide>
<ide> this.each(function() {
<add> var timers = jQuery.timers,
<add> i = timers.length;
<ide> // clear marker counters if we know they won't be
<ide> if ( !gotoEnd ) {
<ide> jQuery._unmark( true, this );
<ide> }
<ide> // go in reverse order so anything added to the queue during the loop is ignored
<del> for ( var i = timers.length - 1; i >= 0; i-- ) {
<add> while ( i-- ) {
<ide> if ( timers[i].elem === this ) {
<ide> if (gotoEnd) {
<ide> // force the next step to be the last
<ide> jQuery.extend({
<ide> this.elem = elem;
<ide> this.prop = prop;
<ide>
<del> if ( !options.orig ) {
<del> options.orig = {};
<del> }
<add> options.orig = options.orig || {};
<ide> }
<ide>
<ide> });
<ide> jQuery.fx.prototype = {
<ide> // Each step of an animation
<ide> step: function( gotoEnd ) {
<ide> var t = fxNow || createFxNow(),
<del> done = true;
<add> done = true,
<add> elem = this.elem,
<add> options = this.options;
<ide>
<del> if ( gotoEnd || t >= this.options.duration + this.startTime ) {
<add> if ( gotoEnd || t >= options.duration + this.startTime ) {
<ide> this.now = this.end;
<ide> this.pos = this.state = 1;
<ide> this.update();
<ide>
<del> this.options.curAnim[ this.prop ] = true;
<add> options.animatedProperties[ this.prop ] = true;
<ide>
<del> for ( var i in this.options.curAnim ) {
<del> if ( this.options.curAnim[i] !== true ) {
<add> for ( var i in options.animatedProperties ) {
<add> if ( options.animatedProperties[i] !== true ) {
<ide> done = false;
<ide> }
<ide> }
<ide>
<ide> if ( done ) {
<ide> // Reset the overflow
<del> if ( this.options.overflow != null && !jQuery.support.shrinkWrapBlocks ) {
<del> var elem = this.elem,
<del> options = this.options;
<add> if ( options.overflow != null && !jQuery.support.shrinkWrapBlocks ) {
<ide>
<ide> jQuery.each( [ "", "X", "Y" ], function (index, value) {
<ide> elem.style[ "overflow" + value ] = options.overflow[index];
<ide> });
<ide> }
<ide>
<ide> // Hide the element if the "hide" operation was done
<del> if ( this.options.hide ) {
<del> jQuery(this.elem).hide();
<add> if ( options.hide ) {
<add> jQuery(elem).hide();
<ide> }
<ide>
<ide> // Reset the properties, if the item has been hidden or shown
<del> if ( this.options.hide || this.options.show ) {
<del> for ( var p in this.options.curAnim ) {
<del> jQuery.style( this.elem, p, this.options.orig[p] );
<add> if ( options.hide || options.show ) {
<add> for ( var p in options.animatedProperties ) {
<add> jQuery.style( elem, p, options.orig[p] );
<ide> }
<ide> }
<ide>
<ide> // Execute the complete function
<del> this.options.complete.call( this.elem );
<add> options.complete.call( elem );
<ide> }
<ide>
<ide> return false;
<ide>
<ide> } else {
<del> var n = t - this.startTime;
<del> this.state = n / this.options.duration;
<del>
<del> // Perform the easing function, defaults to swing
<del> var specialEasing = this.options.specialEasing && this.options.specialEasing[this.prop];
<del> var defaultEasing = this.options.easing || (jQuery.easing.swing ? "swing" : "linear");
<del> this.pos = jQuery.easing[specialEasing || defaultEasing](this.state, n, 0, 1, this.options.duration);
<del> this.now = this.start + ((this.end - this.start) * this.pos);
<add> // classical easing cannot be used with an Infinity duration
<add> if ( options.duration == Infinity ) {
<add> this.now = t;
<add> } else {
<add> var n = t - this.startTime;
<ide>
<add> this.state = n / options.duration;
<add> // Perform the easing function, defaults to swing
<add> this.pos = jQuery.easing[options.animatedProperties[this.prop]](this.state, n, 0, 1, options.duration);
<add> this.now = this.start + ((this.end - this.start) * this.pos);
<add> }
<ide> // Perform the next step of the animation
<ide> this.update();
<ide> } | 1 |
PHP | PHP | return collection | b12f44c37bc057e98757743cd67ba47e934dac2a | <ide><path>src/Illuminate/Support/Stringable.php
<ide> public function ucfirst()
<ide> /**
<ide> * Split a string by uppercase characters.
<ide> *
<del> * @return array
<add> * @return \Illuminate\Support\Collection
<ide> */
<ide> public function ucsplit()
<ide> {
<del> return Str::ucsplit($this->value);
<add> return collect(Str::ucsplit($this->value));
<ide> }
<ide>
<ide> /** | 1 |
Ruby | Ruby | fix merge conflicts for | 5c32f41d5258743500345db34839a21139676f8e | <ide><path>activerecord/lib/active_record/associations/join_dependency.rb
<ide> def aliases
<ide> def instantiate(result_set, aliases)
<ide> primary_key = aliases.column_alias(join_root, join_root.primary_key)
<ide>
<del> seen = Hash.new { |h,parent_klass|
<del> h[parent_klass] = Hash.new { |i,parent_id|
<del> i[parent_id] = Hash.new { |j,child_klass| j[child_klass] = {} }
<add> seen = Hash.new { |i, object_id|
<add> i[object_id] = Hash.new { |j, child_class|
<add> j[child_class] = {}
<ide> }
<ide> }
<ide>
<ide> def build(associations, base_klass)
<ide>
<ide> def construct(ar_parent, parent, row, rs, seen, model_cache, aliases)
<ide> return if ar_parent.nil?
<del> primary_id = ar_parent.id
<ide>
<ide> parent.children.each do |node|
<ide> if node.reflection.collection?
<ide> def construct(ar_parent, parent, row, rs, seen, model_cache, aliases)
<ide> next
<ide> end
<ide>
<del> model = seen[parent.base_klass][primary_id][node.base_klass][id]
<add> model = seen[ar_parent.object_id][node.base_klass][id]
<ide>
<ide> if model
<ide> construct(model, node, row, rs, seen, model_cache, aliases)
<ide> else
<ide> model = construct_model(ar_parent, node, row, model_cache, id, aliases)
<ide> model.readonly!
<del> seen[parent.base_klass][primary_id][node.base_klass][id] = model
<add> seen[ar_parent.object_id][node.base_klass][id] = model
<ide> construct(model, node, row, rs, seen, model_cache, aliases)
<ide> end
<ide> end
<ide><path>activerecord/test/cases/associations/eager_test.rb
<ide> require 'models/club'
<ide> require 'models/categorization'
<ide> require 'models/sponsor'
<add>require 'models/mentor'
<add>require 'models/contract'
<ide>
<ide> class EagerAssociationTest < ActiveRecord::TestCase
<ide> fixtures :posts, :comments, :authors, :essays, :author_addresses, :categories, :categories_posts,
<ide> def test_deep_including_through_habtm
<ide> assert_no_queries { assert_equal 2, posts[1].categories[0].categorizations.length }
<ide> end
<ide>
<add> def test_eager_load_multiple_associations_with_references
<add> mentor = Mentor.create!(name: "Barış Can DAYLIK")
<add> developer = Developer.create!(name: "Mehmet Emin İNAÇ", mentor: mentor)
<add> Contract.create!(developer: developer)
<add> project = Project.create!(name: "VNGRS", mentor: mentor)
<add> project.developers << developer
<add> projects = Project.references(:mentors).includes(mentor: { developers: :contracts }, developers: :contracts)
<add> assert_equal projects.last.mentor.developers.first.contracts, projects.last.developers.last.contracts
<add> end
<add>
<ide> test "scoping with a circular preload" do
<ide> assert_equal Comment.find(1), Comment.preload(:post => :comments).scoping { Comment.find(1) }
<ide> end
<ide><path>activerecord/test/models/developer.rb
<ide> def find_most_recent
<ide> end
<ide> end
<ide>
<add> belongs_to :mentor
<add>
<ide> accepts_nested_attributes_for :projects
<ide>
<ide> has_and_belongs_to_many :shared_computers, class_name: "Computer"
<ide><path>activerecord/test/models/mentor.rb
<add>class Mentor < ActiveRecord::Base
<add> has_many :developers
<add>end
<ide>\ No newline at end of file
<ide><path>activerecord/test/models/project.rb
<ide> class Project < ActiveRecord::Base
<add> belongs_to :mentor
<ide> has_and_belongs_to_many :developers, -> { distinct.order 'developers.name desc, developers.id desc' }
<ide> has_and_belongs_to_many :readonly_developers, -> { readonly }, :class_name => "Developer"
<ide> has_and_belongs_to_many :non_unique_developers, -> { order 'developers.name desc, developers.id desc' }, :class_name => 'Developer'
<ide><path>activerecord/test/schema/schema.rb
<ide> def except(adapter_names_to_exclude)
<ide> t.string :first_name
<ide> t.integer :salary, default: 70000
<ide> t.integer :firm_id
<add> t.integer :mentor_id
<ide> if subsecond_precision_supported?
<ide> t.datetime :created_at, precision: 6
<ide> t.datetime :updated_at, precision: 6
<ide> def except(adapter_names_to_exclude)
<ide> t.string :name
<ide> end
<ide>
<add> create_table :mentors, force: true do |t|
<add> t.string :name
<add> end
<add>
<ide> create_table :minivans, force: true, id: false do |t|
<ide> t.string :minivan_id
<ide> t.string :name
<ide> def except(adapter_names_to_exclude)
<ide> t.string :name
<ide> t.string :type
<ide> t.integer :firm_id
<add> t.integer :mentor_id
<ide> end
<ide>
<ide> create_table :randomly_named_table1, force: true do |t| | 6 |
Java | Java | remove bodyinserters.fromserversentevent variants | 0b3ea405ab8a93610286c1de1a393c3fa9cbe071 | <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/BodyInserters.java
<ide> private static HttpMessageWriter<Resource> resourceHttpMessageWriter(BodyInserte
<ide>
<ide> /**
<ide> * Return a {@code BodyInserter} that writes the given {@code ServerSentEvent} publisher.
<add> * <p>Note that a SSE {@code BodyInserter} can also be obtained by passing a stream of strings
<add> * or POJOs (to be encoded as JSON) to {@link #fromPublisher(Publisher, Class)}, and specifying a
<add> * {@link MediaType#TEXT_EVENT_STREAM text/event-stream} Content-Type.
<ide> * @param eventsPublisher the {@code ServerSentEvent} publisher to write to the response body
<ide> * @param <T> the type of the elements contained in the {@link ServerSentEvent}
<ide> * @return a {@code BodyInserter} that writes a {@code ServerSentEvent} publisher
<ide> public static <T, S extends Publisher<ServerSentEvent<T>>> BodyInserter<S, Serve
<ide> };
<ide> }
<ide>
<del> /**
<del> * Return a {@code BodyInserter} that writes the given {@code Publisher} publisher as
<del> * Server-Sent Events.
<del> * @param eventsPublisher the publisher to write to the response body as Server-Sent Events
<del> * @param eventClass the class of event contained in the publisher
<del> * @param <T> the type of the elements contained in the publisher
<del> * @return a {@code BodyInserter} that writes the given {@code Publisher} publisher as
<del> * Server-Sent Events
<del> * @see <a href="https://www.w3.org/TR/eventsource/">Server-Sent Events W3C recommendation</a>
<del> */
<del> // Note that the returned BodyInserter is parameterized to ServerHttpResponse, not
<del> // ReactiveHttpOutputMessage like other methods, since sending SSEs only typically happens on
<del> // the server-side
<del> public static <T, S extends Publisher<T>> BodyInserter<S, ServerHttpResponse> fromServerSentEvents(S eventsPublisher,
<del> Class<T> eventClass) {
<del>
<del> Assert.notNull(eventsPublisher, "'eventsPublisher' must not be null");
<del> Assert.notNull(eventClass, "'eventClass' must not be null");
<del> return fromServerSentEvents(eventsPublisher, ResolvableType.forClass(eventClass));
<del> }
<del>
<del> /**
<del> * Return a {@code BodyInserter} that writes the given {@code Publisher} publisher as
<del> * Server-Sent Events.
<del> * @param eventsPublisher the publisher to write to the response body as Server-Sent Events
<del> * @param typeReference the type of event contained in the publisher
<del> * @param <T> the type of the elements contained in the publisher
<del> * @return a {@code BodyInserter} that writes the given {@code Publisher} publisher as
<del> * Server-Sent Events
<del> * @see <a href="https://www.w3.org/TR/eventsource/">Server-Sent Events W3C recommendation</a>
<del> */
<del> // Note that the returned BodyInserter is parameterized to ServerHttpResponse, not
<del> // ReactiveHttpOutputMessage like other methods, since sending SSEs only typically happens on
<del> // the server-side
<del> public static <T, S extends Publisher<T>> BodyInserter<S, ServerHttpResponse> fromServerSentEvents(S eventsPublisher,
<del> ParameterizedTypeReference<T> typeReference) {
<del>
<del> Assert.notNull(eventsPublisher, "'eventsPublisher' must not be null");
<del> Assert.notNull(typeReference, "'typeReference' must not be null");
<del> return fromServerSentEvents(eventsPublisher,
<del> ResolvableType.forType(typeReference.getType()));
<del> }
<del>
<del> static <T, S extends Publisher<T>> BodyInserter<S, ServerHttpResponse> fromServerSentEvents(S eventsPublisher,
<del> ResolvableType eventType) {
<del>
<del> Assert.notNull(eventsPublisher, "'eventsPublisher' must not be null");
<del> Assert.notNull(eventType, "'eventType' must not be null");
<del> return (serverResponse, context) -> {
<del> HttpMessageWriter<T> messageWriter =
<del> findMessageWriter(context, SERVER_SIDE_EVENT_TYPE, MediaType.TEXT_EVENT_STREAM);
<del> return context.serverRequest()
<del> .map(serverRequest -> messageWriter.write(eventsPublisher, eventType,
<del> eventType, MediaType.TEXT_EVENT_STREAM, serverRequest,
<del> serverResponse, context.hints()))
<del> .orElseGet(() -> messageWriter.write(eventsPublisher, eventType,
<del> MediaType.TEXT_EVENT_STREAM, serverResponse, context.hints()));
<del> };
<del> }
<del>
<ide> /**
<ide> * Return a {@code BodyInserter} that writes the given {@code MultiValueMap} as URL-encoded
<ide> * form data.
<ide> static <T, S extends Publisher<T>> BodyInserter<S, ServerHttpResponse> fromServe
<ide> */
<ide> // Note that the returned BodyInserter is parameterized to ClientHttpRequest, not
<ide> // ReactiveHttpOutputMessage like other methods, since sending form data only typically happens
<del> // on the server-side
<add> // on the client-side
<ide> public static BodyInserter<MultiValueMap<String, String>, ClientHttpRequest> fromFormData(
<ide> MultiValueMap<String, String> formData) {
<ide>
<ide> public static BodyInserter<MultiValueMap<String, String>, ClientHttpRequest> fro
<ide> */
<ide> // Note that the returned BodyInserter is parameterized to ClientHttpRequest, not
<ide> // ReactiveHttpOutputMessage like other methods, since sending form data only typically happens
<del> // on the server-side
<add> // on the client-side
<ide> public static BodyInserter<MultiValueMap<String, ?>, ClientHttpRequest> fromMultipartData(
<ide> MultiValueMap<String, ?> multipartData) {
<ide>
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/function/BodyInsertersTests.java
<ide> public void ofServerSentEventFlux() throws Exception {
<ide> StepVerifier.create(result).expectNextCount(0).expectComplete().verify();
<ide> }
<ide>
<del> @Test
<del> public void ofServerSentEventClass() throws Exception {
<del> Flux<String> body = Flux.just("foo");
<del> BodyInserter<Flux<String>, ServerHttpResponse> inserter =
<del> BodyInserters.fromServerSentEvents(body, String.class);
<del>
<del> MockServerHttpResponse response = new MockServerHttpResponse();
<del> Mono<Void> result = inserter.insert(response, this.context);
<del> StepVerifier.create(result).expectNextCount(0).expectComplete().verify();
<del> }
<del>
<ide> @Test
<ide> public void ofFormData() throws Exception {
<ide> MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/function/server/SseHandlerFunctionIntegrationTests.java
<ide> import reactor.test.StepVerifier;
<ide>
<ide> import org.springframework.core.ParameterizedTypeReference;
<add>import org.springframework.http.MediaType;
<ide> import org.springframework.http.codec.ServerSentEvent;
<ide> import org.springframework.web.reactive.function.client.WebClient;
<ide>
<ide> private static class SseHandler {
<ide>
<ide> public Mono<ServerResponse> string(ServerRequest request) {
<ide> Flux<String> flux = Flux.interval(Duration.ofMillis(100)).map(l -> "foo " + l).take(2);
<del> return ServerResponse.ok().body(fromServerSentEvents(flux, String.class));
<add> return ServerResponse.ok()
<add> .contentType(MediaType.TEXT_EVENT_STREAM)
<add> .body(flux, String.class);
<ide> }
<ide>
<ide> public Mono<ServerResponse> person(ServerRequest request) {
<ide> Flux<Person> flux = Flux.interval(Duration.ofMillis(100))
<ide> .map(l -> new Person("foo " + l)).take(2);
<del> return ServerResponse.ok().body(fromServerSentEvents(flux, Person.class));
<add> return ServerResponse.ok()
<add> .contentType(MediaType.TEXT_EVENT_STREAM)
<add> .body(flux, Person.class);
<ide> }
<ide>
<ide> public Mono<ServerResponse> sse(ServerRequest request) { | 3 |
Python | Python | add support for the new amazon region (tokyo) | 5dc2ea314c85fe5e6b8b8541a8e296286597f70a | <ide><path>libcloud/drivers/ec2.py
<ide> EC2_US_WEST_HOST = 'ec2.us-west-1.amazonaws.com'
<ide> EC2_EU_WEST_HOST = 'ec2.eu-west-1.amazonaws.com'
<ide> EC2_AP_SOUTHEAST_HOST = 'ec2.ap-southeast-1.amazonaws.com'
<add>EC2_AP_NORTHEAST_HOST = 'ec2.ap-northeast-1.amazonaws.com'
<ide>
<ide> API_VERSION = '2010-08-31'
<ide>
<ide> EC2_US_WEST_INSTANCE_TYPES = dict(EC2_INSTANCE_TYPES)
<ide> EC2_EU_WEST_INSTANCE_TYPES = dict(EC2_INSTANCE_TYPES)
<ide> EC2_AP_SOUTHEAST_INSTANCE_TYPES = dict(EC2_INSTANCE_TYPES)
<add>EC2_AP_NORTHEAST_INSTANCE_TYPES = dict(EC2_INSTANCE_TYPES)
<ide>
<ide> #
<ide> # On demand prices must also be hardcoded, because Amazon doesn't provide an
<ide> # prices are the same
<ide> EC2_AP_SOUTHEAST_INSTANCE_TYPES = dict(EC2_EU_WEST_INSTANCE_TYPES)
<ide>
<add>EC2_AP_NORTHEAST_INSTANCE_TYPES['t1.micro']['price'] = '.027'
<add>EC2_AP_NORTHEAST_INSTANCE_TYPES['m1.small']['price'] = '.10'
<add>EC2_AP_NORTHEAST_INSTANCE_TYPES['m1.large']['price'] = '.40'
<add>EC2_AP_NORTHEAST_INSTANCE_TYPES['m1.xlarge']['price'] = '.80'
<add>EC2_AP_NORTHEAST_INSTANCE_TYPES['c1.medium']['price'] = '.20'
<add>EC2_AP_NORTHEAST_INSTANCE_TYPES['c1.xlarge']['price'] = '.80'
<add>EC2_AP_NORTHEAST_INSTANCE_TYPES['m2.xlarge']['price'] = '.60'
<add>EC2_AP_NORTHEAST_INSTANCE_TYPES['m2.2xlarge']['price'] = '1.20'
<add>EC2_AP_NORTHEAST_INSTANCE_TYPES['m2.4xlarge']['price'] = '2.39'
<ide>
<ide> class EC2NodeLocation(NodeLocation):
<ide> def __init__(self, id, name, country, driver, availability_zone):
<ide> class EC2APSEConnection(EC2Connection):
<ide>
<ide> host = EC2_AP_SOUTHEAST_HOST
<ide>
<add>class EC2APNEConnection(EC2Connection):
<add> """
<add> Connection class for EC2 in the Northeast Asia Pacific Region
<add> """
<add>
<add> host = EC2_AP_NORTHEAST_HOST
<add>
<ide> class EC2APSENodeDriver(EC2NodeDriver):
<ide> """
<ide> Driver class for EC2 in the Southeast Asia Pacific Region
<ide> class EC2APSENodeDriver(EC2NodeDriver):
<ide> connectionCls = EC2APSEConnection
<ide> _instance_types = EC2_AP_SOUTHEAST_INSTANCE_TYPES
<ide>
<add>class EC2APNENodeDriver(EC2NodeDriver):
<add> """
<add> Driver class for EC2 in the Northeast Asia Pacific Region
<add> """
<add>
<add> name = 'Amazon EC2 (ap-northeast-1)'
<add> friendly_name = 'Amazon Asia-Pacific Tokyo'
<add> country = 'JP'
<add> region_name = 'ap-northeast-1'
<add> connectionCls = EC2APNEConnection
<add> _instance_types = EC2_AP_NORTHEAST_INSTANCE_TYPES
<add>
<ide> class EucConnection(EC2Connection):
<ide> """
<ide> Connection class for Eucalyptus
<ide><path>libcloud/providers.py
<ide> ('libcloud.drivers.ec2', 'EC2USWestNodeDriver'),
<ide> Provider.EC2_AP_SOUTHEAST:
<ide> ('libcloud.drivers.ec2', 'EC2APSENodeDriver'),
<add> Provider.EC2_AP_NORTHEAST:
<add> ('libcloud.drivers.ec2', 'EC2APNENodeDriver'),
<ide> Provider.ECP:
<ide> ('libcloud.drivers.ecp', 'ECPNodeDriver'),
<ide> Provider.ELASTICHOSTS_UK1:
<ide><path>libcloud/types.py
<ide> class Provider(object):
<ide> RACKSPACE_UK = 23
<ide> BRIGHTBOX = 24
<ide> CLOUDSIGMA = 25
<add> EC2_AP_NORTHEAST = 26
<ide>
<ide> class NodeState(object):
<ide> """
<ide><path>test/test_ec2.py
<ide> import unittest
<ide>
<ide> from libcloud.drivers.ec2 import EC2NodeDriver, EC2APSENodeDriver, IdempotentParamError
<add>from libcloud.drivers.ec2 import EC2APNENodeDriver
<ide> from libcloud.base import Node, NodeImage, NodeSize, NodeLocation
<ide>
<ide> from test import MockHttp, TestCaseMixin
<ide> def setUp(self):
<ide> EC2MockHttp.type = None
<ide> self.driver = EC2APSENodeDriver(EC2_ACCESS_ID, EC2_SECRET)
<ide>
<add>class EC2APNETests(EC2Tests):
<add> def setUp(self):
<add> EC2APNENodeDriver.connectionCls.conn_classes = (None, EC2MockHttp)
<add> EC2MockHttp.use_param = 'Action'
<add> EC2MockHttp.type = None
<add> self.driver = EC2APNENodeDriver(EC2_ACCESS_ID, EC2_SECRET)
<add>
<ide> if __name__ == '__main__':
<ide> sys.exit(unittest.main()) | 4 |
Ruby | Ruby | fix protection against overriding formula#brew | 9614301be4f2647de6a0395b125c3a2ca69e3889 | <ide><path>Library/Homebrew/formula.rb
<ide> def set_instance_variable(type)
<ide> instance_variable_set("@#{type}", class_value) if class_value
<ide> end
<ide>
<del> def method_added method
<del> raise 'You cannot override Formula.brew' if method == 'brew'
<add> def self.method_added method
<add> raise 'You cannot override Formula.brew' if method == :brew
<ide> end
<ide>
<ide> class << self
<ide><path>Library/Homebrew/test/test_formula.rb
<ide> class MostlyAbstractFormula <Formula
<ide> @homepage = 'http://example.com/'
<ide> end
<ide>
<del>class TestBallOverrideBrew <Formula
<del> def initialize
<del> super "foo"
<del> end
<del> def brew
<del> end
<del>end
<del>
<del>
<ide> class FormulaTests < Test::Unit::TestCase
<ide>
<ide> def test_prefix
<ide> def test_class_naming
<ide> end
<ide>
<ide> def test_cant_override_brew
<del> assert_raises(RuntimeError) { TestBallOverrideBrew.new }
<add> assert_raises(RuntimeError) do
<add> eval <<-EOS
<add> class TestBallOverrideBrew <Formula
<add> def initialize
<add> super "foo"
<add> end
<add> def brew
<add> end
<add> end
<add> EOS
<add> end
<ide> end
<ide>
<ide> def test_abstract_formula | 2 |
Ruby | Ruby | use namespaces in notifications | 6fbe9ef2ffb1858027130789246f3ae24a0a182f | <ide><path>actionmailer/lib/action_mailer/base.rb
<ide> def deliver!(mail = @mail)
<ide> logger.debug "\n#{mail.encoded}"
<ide> end
<ide>
<del> ActiveSupport::Notifications.instrument(:deliver_mail, :mail => mail) do
<add> ActiveSupport::Notifications.instrument("actionmailer.deliver", :mail => mail) do
<ide> begin
<ide> self.delivery_method.perform_delivery(mail) if perform_deliveries
<ide> rescue Exception => e # Net::SMTP errors or sendmail pipe errors
<ide><path>actionpack/lib/action_controller/caching.rb
<ide> def cache_configured?
<ide> end
<ide>
<ide> def log_event(name, before, after, instrumenter_id, payload)
<del> if name.to_s =~ /(read|write|cache|expire|exist)_(fragment|page)\??/
<add> if name.to_s =~ /actioncontroller\.((read|write|expire|exist)_(fragment|page)\??)/
<ide> key_or_path = payload[:key] || payload[:path]
<del> human_name = name.to_s.humanize
<add> human_name = $1.humanize
<ide> duration = (after - before) * 1000
<ide> logger.info("#{human_name} #{key_or_path.inspect} (%.1fms)" % duration)
<ide> else
<ide><path>actionpack/lib/action_controller/caching/fragments.rb
<ide> def write_fragment(key, content, options = nil)
<ide> return content unless cache_configured?
<ide> key = fragment_cache_key(key)
<ide>
<del> ActiveSupport::Notifications.instrument(:write_fragment, :key => key) do
<add> instrument_fragment_cache :write_fragment, key do
<ide> cache_store.write(key, content, options)
<ide> end
<ide> content
<ide> def read_fragment(key, options = nil)
<ide> return unless cache_configured?
<ide> key = fragment_cache_key(key)
<ide>
<del> ActiveSupport::Notifications.instrument(:read_fragment, :key => key) do
<add> instrument_fragment_cache :read_fragment, key do
<ide> cache_store.read(key, options)
<ide> end
<ide> end
<ide> def fragment_exist?(key, options = nil)
<ide> return unless cache_configured?
<ide> key = fragment_cache_key(key)
<ide>
<del> ActiveSupport::Notifications.instrument(:exist_fragment?, :key => key) do
<add> instrument_fragment_cache :exist_fragment?, key do
<ide> cache_store.exist?(key, options)
<ide> end
<ide> end
<ide> def expire_fragment(key, options = nil)
<ide> key = fragment_cache_key(key) unless key.is_a?(Regexp)
<ide> message = nil
<ide>
<del> ActiveSupport::Notifications.instrument(:expire_fragment, :key => key) do
<add> instrument_fragment_cache :expire_fragment, key do
<ide> if key.is_a?(Regexp)
<del> message = "Expired fragments matching: #{key.source}"
<ide> cache_store.delete_matched(key, options)
<ide> else
<del> message = "Expired fragment: #{key}"
<ide> cache_store.delete(key, options)
<ide> end
<ide> end
<ide> end
<add>
<add> def instrument_fragment_cache(name, key)
<add> ActiveSupport::Notifications.instrument("actioncontroller.#{name}", :key => key){ yield }
<add> end
<ide> end
<ide> end
<ide> end
<ide><path>actionpack/lib/action_controller/caching/pages.rb
<ide> def expire_page(path)
<ide> return unless perform_caching
<ide> path = page_cache_path(path)
<ide>
<del> ActiveSupport::Notifications.instrument(:expire_page, :path => path) do
<add> instrument_page_cache :expire_page, path do
<ide> File.delete(path) if File.exist?(path)
<ide> end
<ide> end
<ide> def cache_page(content, path)
<ide> return unless perform_caching
<ide> path = page_cache_path(path)
<ide>
<del> ActiveSupport::Notifications.instrument(:cache_page, :path => path) do
<add> instrument_page_cache :write_page, path do
<ide> FileUtils.makedirs(File.dirname(path))
<ide> File.open(path, "wb+") { |f| f.write(content) }
<ide> end
<ide> def page_cache_file(path)
<ide> def page_cache_path(path)
<ide> page_cache_directory + page_cache_file(path)
<ide> end
<add>
<add> def instrument_page_cache(name, path)
<add> ActiveSupport::Notifications.instrument("actioncontroller.#{name}", :path => path){ yield }
<add> end
<ide> end
<ide>
<ide> # Expires the page that was cached with the +options+ as a key. Example:
<ide><path>actionpack/lib/action_controller/metal/logger.rb
<ide> module Logger
<ide> attr_internal :view_runtime
<ide>
<ide> def process_action(action)
<del> ActiveSupport::Notifications.instrument(:process_action, :controller => self, :action => action) do
<add> ActiveSupport::Notifications.instrument("actioncontroller.process_action",
<add> :controller => self, :action => action) do
<ide> super
<ide> end
<ide> end
<ide> module ClassMethods
<ide> # This is the hook invoked by ActiveSupport::Notifications.subscribe.
<ide> # If you need to log any event, overwrite the method and do it here.
<ide> def log_event(name, before, after, instrumenter_id, payload) #:nodoc:
<del> if name == :process_action
<add> if name == "actioncontroller.process_action"
<ide> duration = [(after - before) * 1000, 0.01].max
<ide> controller = payload[:controller]
<ide> request = controller.request
<ide> def log_event(name, before, after, instrumenter_id, payload) #:nodoc:
<ide> message << " [#{request.request_uri rescue "unknown"}]"
<ide>
<ide> logger.info(message)
<del> elsif name == :render_template
<add> elsif name == "actionview.render_template"
<ide> # TODO Make render_template logging work if you are using just ActionView
<ide> duration = (after - before) * 1000
<ide> message = "Rendered #{payload[:identifier]}"
<ide><path>actionpack/lib/action_view/render/partials.rb
<ide> def render
<ide> options = @options
<ide>
<ide> if @collection
<del> ActiveSupport::Notifications.instrument(:render_collection, :path => @path,
<del> :count => @collection.size) do
<add> ActiveSupport::Notifications.instrument("actionview.render_collection",
<add> :path => @path, :count => @collection.size) do
<ide> render_collection
<ide> end
<ide> else
<del> content = ActiveSupport::Notifications.instrument(:render_partial, :path => @path) do
<add> content = ActiveSupport::Notifications.instrument("actionview.render_partial",
<add> :path => @path) do
<ide> render_partial
<ide> end
<ide>
<ide><path>actionpack/lib/action_view/render/rendering.rb
<ide> def render_template(options)
<ide> def _render_template(template, layout = nil, options = {})
<ide> locals = options[:locals] || {}
<ide>
<del> content = ActiveSupport::Notifications.instrument(:render_template,
<add> content = ActiveSupport::Notifications.instrument("actionview.render_template",
<ide> :identifier => template.identifier, :layout => (layout ? layout.identifier : nil)) do
<ide> template.render(self, locals)
<ide> end
<ide> def _render_template(template, layout = nil, options = {})
<ide> end
<ide>
<ide> def _render_layout(layout, locals, &block)
<del> ActiveSupport::Notifications.instrument(:render_layout, :identifier => layout.identifier) do
<add> ActiveSupport::Notifications.instrument("actionview.render_layout",
<add> :identifier => layout.identifier) do
<ide> layout.render(self, locals){ |*name| _layout_for(*name, &block) }
<ide> end
<ide> end
<ide><path>actionpack/test/abstract_unit.rb
<ide> class ActiveSupport::TestCase
<ide> end
<ide>
<ide> class MockLogger
<del> attr_reader :logged
<ide> attr_accessor :level
<ide>
<ide> def initialize
<ide> def method_missing(method, *args, &blk)
<ide> @logged << args.first
<ide> @logged << blk.call if block_given?
<ide> end
<add>
<add> def logged
<add> @logged.compact.map { |l| l.to_s.strip }
<add> end
<ide> end
<ide>
<ide> class ActionController::IntegrationTest < ActiveSupport::TestCase
<ide><path>actionpack/test/activerecord/controller_runtime_test.rb
<ide> def wait
<ide> def test_log_with_active_record
<ide> get :show
<ide> wait
<del> assert_match /ActiveRecord runtime/, logs[3]
<add> assert_match /ActiveRecord runtime/, @controller.logger.logged[3]
<ide> end
<ide>
<ide> private
<ide> def set_logger
<ide> @controller.logger = MockLogger.new
<ide> end
<ide>
<del> def logs
<del> @logs ||= @controller.logger.logged.compact.map {|l| l.to_s.strip}
<del> end
<ide> end
<ide><path>actionpack/test/controller/caching_test.rb
<ide> def test_fragment_for
<ide> end
<ide>
<ide> def test_fragment_for_logging
<del> fragment_computed = false
<del> events = []
<del> ActiveSupport::Notifications.subscribe { |*args| events << args }
<add> @controller.logger = MockLogger.new
<ide>
<del> buffer = 'generated till now -> '
<del> @controller.fragment_for(buffer, 'expensive') { fragment_computed = true }
<add> fragment_computed = false
<add> @controller.fragment_for('buffer', 'expensive') { fragment_computed = true }
<add> ActiveSupport::Notifications.notifier.wait
<ide>
<ide> assert fragment_computed
<del> assert_equal 'generated till now -> ', buffer
<del> ActiveSupport::Notifications.notifier.wait
<del> assert_equal [:exist_fragment?, :write_fragment], events.map(&:first)
<add> assert_match /Exist fragment\? "views\/expensive"/, @controller.logger.logged[0]
<add> assert_match /Write fragment "views\/expensive"/, @controller.logger.logged[1]
<ide> end
<ide>
<ide> end
<ide><path>actionpack/test/controller/logging_test.rb
<ide> def set_logger
<ide> end
<ide>
<ide> def logs
<del> @logs ||= @controller.logger.logged.compact.map {|l| l.to_s.strip}
<add> @logs ||= @controller.logger.logged
<ide> end
<ide> end
<ide><path>activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
<ide> def log_info(sql, name, ms)
<ide> protected
<ide> def log(sql, name)
<ide> result = nil
<del> ActiveSupport::Notifications.instrument(:sql, :sql => sql, :name => name) do
<add> ActiveSupport::Notifications.instrument("activerecord.sql", :sql => sql, :name => name) do
<ide> @runtime += Benchmark.ms { result = yield }
<ide> end
<ide> result
<ide><path>activerecord/lib/active_record/railtie.rb
<ide> class Railtie < Rails::Railtie
<ide> initializer "active_record.notifications" do
<ide> require 'active_support/notifications'
<ide>
<del> ActiveSupport::Notifications.subscribe("sql") do |name, before, after, instrumenter_id, payload|
<add> ActiveSupport::Notifications.subscribe("activerecord.sql") do |name, before, after, instrumenter_id, payload|
<ide> ActiveRecord::Base.connection.log_info(payload[:sql], payload[:name], (after - before) * 1000)
<ide> end
<ide> end
<ide><path>activesupport/lib/active_support/cache.rb
<ide> def expires_in(options)
<ide> expires_in || 0
<ide> end
<ide>
<del> def instrument(operation, key, options, &block)
<add> def instrument(operation, key, options)
<ide> log(operation, key, options)
<ide>
<ide> if self.class.instrument
<ide> payload = { :key => key }
<ide> payload.merge!(options) if options.is_a?(Hash)
<del> ActiveSupport::Notifications.instrument(:"cache_#{operation}", payload, &block)
<add> ActiveSupport::Notifications.instrument("activesupport.cache_#{operation}", payload){ yield }
<ide> else
<ide> yield
<ide> end | 14 |
Javascript | Javascript | add test case | 17e8eed735ed3aabfa40b4e52c577f00fcd17f1c | <ide><path>lib/dependencies/ImportMetaPlugin.js
<ide> class ImportMetaPlugin {
<ide> const parserHandler = (parser, { importMeta }) => {
<ide> if (importMeta === false) {
<ide> const { importMetaName } = compilation.outputOptions;
<add> if (importMetaName === "import.meta") return;
<ide>
<ide> parser.hooks.expression
<ide> .for("import.meta")
<ide><path>test/configCases/output/import-meta-name/a.js
<add>export const url = import.meta.url;
<ide><path>test/configCases/output/import-meta-name/index.js
<add>import { url } from "./a";
<add>
<add>it("should evaluate import.meta to pseudoImport.meta", () => {
<add> expect(url).toBe("http://test.co/path/index.js");
<add>});
<add>
<add>it("should evaluate import.meta in runtime", () => {
<add> expect(url).toBe(import.meta.url);
<add>});
<ide><path>test/configCases/output/import-meta-name/test.config.js
<add>module.exports = {
<add> moduleScope(scope) {
<add> scope.pseudoImport = { meta: { url: "http://test.co/path/index.js" } };
<add> }
<add>};
<ide><path>test/configCases/output/import-meta-name/webpack.config.js
<add>/** @type {import("../../../../").Configuration} */
<add>module.exports = {
<add> output: {
<add> importMetaName: "pseudoImport.meta"
<add> },
<add> module: {
<add> parser: {
<add> javascript: {
<add> importMeta: false
<add> }
<add> }
<add> }
<add>}; | 5 |
Ruby | Ruby | restrict audit to homebrew/core | 1b95059c2b1db0e45e9a10fb2040a90311bbdd3d | <ide><path>Library/Homebrew/rubocops/lines.rb
<ide> def audit_formula(_node, _class_node, _parent_class_node, body_node)
<ide> # This cop ensures that new formulae depending on Requirements are not introduced in homebrew/core.
<ide> class CoreRequirements < FormulaCop
<ide> def audit_formula(_node, _class_node, _parent_class_node, _body_node)
<add> return if formula_tap != "homebrew-core"
<add>
<ide> if depends_on? :java
<ide> problem "Formulae in homebrew/core should depend on a versioned `openjdk` instead of :java"
<ide> end | 1 |
Text | Text | resolve merge conflict | 8afc9875f6bc273c63cc555d0606db1329455af5 | <ide><path>guides/source/contributing_to_ruby_on_rails.md
<ide> Then, don't get your hopes up! Unless you have a "Code Red, Mission Critical, th
<ide>
<ide> Having a way to reproduce your issue will be very helpful for others to help confirm, investigate, and ultimately fix your issue. You can do this by providing an executable test case. To make this process easier, we have prepared several bug report templates for you to use as a starting point:
<ide>
<del><<<<<<< HEAD
<ide> * Template for Active Record (models, database) issues: [gem](https://github.com/rails/rails/blob/main/guides/bug_report_templates/active_record_gem.rb) / [main](https://github.com/rails/rails/blob/main/guides/bug_report_templates/active_record_master.rb)
<ide> * Template for testing Active Record (migration) issues: [gem](https://github.com/rails/rails/blob/main/guides/bug_report_templates/active_record_migrations_gem.rb) / [main](https://github.com/rails/rails/blob/main/guides/bug_report_templates/active_record_migrations_master.rb)
<ide> * Template for Action Pack (controllers, routing) issues: [gem](https://github.com/rails/rails/blob/main/guides/bug_report_templates/action_controller_gem.rb) / [main](https://github.com/rails/rails/blob/main/guides/bug_report_templates/action_controller_master.rb)
<ide> * Template for Active Job issues: [gem](https://github.com/rails/rails/blob/main/guides/bug_report_templates/active_job_gem.rb) / [main](https://github.com/rails/rails/blob/main/guides/bug_report_templates/active_job_master.rb)
<ide> * Template for Active Storage issues: [gem](https://github.com/rails/rails/blob/main/guides/bug_report_templates/active_storage_gem.rb) / [main](https://github.com/rails/rails/blob/main/guides/bug_report_templates/active_storage_master.rb)
<ide> * Template for Action Mailbox issues: [gem](https://github.com/rails/rails/blob/main/guides/bug_report_templates/action_mailbox_gem.rb) / [main](https://github.com/rails/rails/blob/main/guides/bug_report_templates/action_mailbox_master.rb)
<ide> * Generic template for other issues: [gem](https://github.com/rails/rails/blob/main/guides/bug_report_templates/generic_gem.rb) / [main](https://github.com/rails/rails/blob/main/guides/bug_report_templates/generic_master.rb)
<del>=======
<del>* Template for Active Record (models, database) issues: [gem](https://github.com/rails/rails/blob/main/guides/bug_report_templates/active_record_gem.rb) / [master](https://github.com/rails/rails/blob/main/guides/bug_report_templates/active_record_master.rb)
<del>* Template for testing Active Record (migration) issues: [gem](https://github.com/rails/rails/blob/main/guides/bug_report_templates/active_record_migrations_gem.rb) / [master](https://github.com/rails/rails/blob/main/guides/bug_report_templates/active_record_migrations_master.rb)
<del>* Template for Action Pack (controllers, routing) issues: [gem](https://github.com/rails/rails/blob/main/guides/bug_report_templates/action_controller_gem.rb) / [master](https://github.com/rails/rails/blob/main/guides/bug_report_templates/action_controller_master.rb)
<del>* Template for Active Job issues: [gem](https://github.com/rails/rails/blob/main/guides/bug_report_templates/active_job_gem.rb) / [master](https://github.com/rails/rails/blob/main/guides/bug_report_templates/active_job_master.rb)
<del>* Template for Active Storage issues: [gem](https://github.com/rails/rails/blob/main/guides/bug_report_templates/active_storage_gem.rb) / [master](https://github.com/rails/rails/blob/main/guides/bug_report_templates/active_storage_master.rb)
<del>* Template for Action Mailbox issues: [gem](https://github.com/rails/rails/blob/main/guides/bug_report_templates/action_mailbox_gem.rb) / [master](https://github.com/rails/rails/blob/main/guides/bug_report_templates/action_mailbox_master.rb)
<del>* Generic template for other issues: [gem](https://github.com/rails/rails/blob/main/guides/bug_report_templates/generic_gem.rb) / [master](https://github.com/rails/rails/blob/main/guides/bug_report_templates/generic_master.rb)
<del>>>>>>>> otherrep/bug/references-to-master-branch
<ide>
<ide> These templates include the boilerplate code to set up a test case against either a released version of Rails (`*_gem.rb`) or edge Rails (`*_master.rb`).
<ide> | 1 |
Javascript | Javascript | remove addons path deleted in | 35ae38db2fa92d5f49a6a028762c0618be8a368b | <ide><path>scripts/rollup/bundles.js
<ide> const bundles = [
<ide> name: 'react',
<ide> paths: [
<ide> 'src/isomorphic/**/*.js',
<del> 'src/addons/**/*.js',
<ide>
<ide> 'src/ReactVersion.js',
<ide> 'src/shared/**/*.js', | 1 |
PHP | PHP | fix psr-16 ttl conformity | eb6087c370a3584a1f1e232d564194e551694349 | <ide><path>src/Illuminate/Cache/RedisTaggedCache.php
<ide> class RedisTaggedCache extends TaggedCache
<ide> *
<ide> * @param string $key
<ide> * @param mixed $value
<del> * @param \DateTime|float|int|null $minutes
<add> * @param \DateTimeInterface|\DateInterval|float|int|null $minutes
<ide> * @return bool
<ide> */
<ide> public function put($key, $value, $minutes = null)
<ide> {
<add> if ($minutes === null) {
<add> return $this->forever($key, $value);
<add> }
<add>
<ide> $this->pushStandardKeys($this->tags->getNamespace(), $key);
<ide>
<ide> return parent::put($key, $value, $minutes);
<ide><path>src/Illuminate/Cache/Repository.php
<ide> class Repository implements CacheContract, ArrayAccess
<ide> /**
<ide> * The default number of minutes to store items.
<ide> *
<del> * @var float|int
<add> * @var float|int|null
<ide> */
<ide> protected $default = 60;
<ide>
<ide> public function pull($key, $default = null)
<ide> public function put($key, $value, $minutes = null)
<ide> {
<ide> if (is_array($key)) {
<del> $result = $this->putMany($key, $value);
<add> return $this->putMany($key, $value);
<add> }
<ide>
<del> return $result;
<add> if ($minutes === null) {
<add> return $this->forever($key, $value);
<ide> }
<ide>
<del> if (! is_null($minutes = $this->getMinutes($minutes))) {
<del> $result = $this->store->put($this->itemKey($key), $value, $minutes);
<add> $minutes = $this->getMinutes($minutes);
<ide>
<del> if ($result) {
<del> $this->event(new KeyWritten($key, $value, $minutes));
<del> }
<add> if ($minutes <= 0) {
<add> return $this->delete($key);
<add> }
<add>
<add> $result = $this->store->put($this->itemKey($key), $value, $minutes);
<ide>
<del> return $result;
<add> if ($result) {
<add> $this->event(new KeyWritten($key, $value, $minutes));
<ide> }
<ide>
<del> return false;
<add> return $result;
<ide> }
<ide>
<ide> /**
<ide> public function set($key, $value, $ttl = null)
<ide> * Store multiple items in the cache for a given number of minutes.
<ide> *
<ide> * @param array $values
<del> * @param \DateTimeInterface|\DateInterval|float|int $minutes
<add> * @param \DateTimeInterface|\DateInterval|float|int|null $minutes
<ide> * @return bool
<ide> */
<del> public function putMany(array $values, $minutes)
<add> public function putMany(array $values, $minutes = null)
<ide> {
<del> if (! is_null($minutes = $this->getMinutes($minutes))) {
<del> $result = $this->store->putMany($values, $minutes);
<add> if ($minutes === null) {
<add> return $this->putManyForever($values);
<add> }
<ide>
<del> if ($result) {
<del> foreach ($values as $key => $value) {
<del> $this->event(new KeyWritten($key, $value, $minutes));
<del> }
<add> $minutes = $this->getMinutes($minutes);
<add>
<add> if ($minutes <= 0) {
<add> return $this->deleteMultiple(array_keys($values));
<add> }
<add>
<add> $result = $this->store->putMany($values, $minutes);
<add>
<add> if ($result) {
<add> foreach ($values as $key => $value) {
<add> $this->event(new KeyWritten($key, $value, $minutes));
<ide> }
<add> }
<add>
<add> return $result;
<add> }
<ide>
<del> return $result;
<add> /**
<add> * Store multiple items in the cache indefinitely.
<add> *
<add> * @param array $values
<add> * @return bool
<add> */
<add> protected function putManyForever(array $values)
<add> {
<add> $result = true;
<add>
<add> // We'll loop over every item and attempt to store it indefinitely.
<add> // If we notice that one of the items can't be stored forever we
<add> // will return false. Otherwise we'll return a success result.
<add> foreach ($values as $key => $value) {
<add> if (! $this->forever($key, $value)) {
<add> $result = false;
<add> }
<ide> }
<ide>
<del> return false;
<add> return $result;
<ide> }
<ide>
<ide> /**
<ide> public function setMultiple($values, $ttl = null)
<ide> *
<ide> * @param string $key
<ide> * @param mixed $value
<del> * @param \DateTimeInterface|\DateInterval|float|int $minutes
<add> * @param \DateTimeInterface|\DateInterval|float|int|null $minutes
<ide> * @return bool
<ide> */
<del> public function add($key, $value, $minutes)
<add> public function add($key, $value, $minutes = null)
<ide> {
<del> if (is_null($minutes = $this->getMinutes($minutes))) {
<del> return false;
<del> }
<add> if ($minutes !== null) {
<add> if ($this->getMinutes($minutes) <= 0) {
<add> return false;
<add> }
<add>
<add> // If the store has an "add" method we will call the method on the store so it
<add> // has a chance to override this logic. Some drivers better support the way
<add> // this operation should work with a total "atomic" implementation of it.
<add> if (method_exists($this->store, 'add')) {
<add> $minutes = $this->getMinutes($minutes);
<ide>
<del> // If the store has an "add" method we will call the method on the store so it
<del> // has a chance to override this logic. Some drivers better support the way
<del> // this operation should work with a total "atomic" implementation of it.
<del> if (method_exists($this->store, 'add')) {
<del> return $this->store->add(
<del> $this->itemKey($key), $value, $minutes
<del> );
<add> return $this->store->add(
<add> $this->itemKey($key), $value, $minutes
<add> );
<add> }
<ide> }
<ide>
<ide> // If the value did not exist in the cache, we will put the value in the cache
<ide> public function forever($key, $value)
<ide> * Get an item from the cache, or execute the given Closure and store the result.
<ide> *
<ide> * @param string $key
<del> * @param \DateTimeInterface|\DateInterval|float|int $minutes
<add> * @param \DateTimeInterface|\DateInterval|float|int|null $minutes
<ide> * @param \Closure $callback
<ide> * @return mixed
<ide> */
<ide> public function getDefaultCacheTime()
<ide> /**
<ide> * Set the default cache time in minutes.
<ide> *
<del> * @param float|int $minutes
<add> * @param float|int|null $minutes
<ide> * @return $this
<ide> */
<ide> public function setDefaultCacheTime($minutes)
<ide> public function offsetUnset($key)
<ide> /**
<ide> * Calculate the number of minutes with the given duration.
<ide> *
<del> * @param \DateTimeInterface|\DateInterval|float|int $duration
<del> * @return float|int|null
<add> * @param \DateTimeInterface|\DateInterval|float|int $minutes
<add> * @return float|int
<ide> */
<del> protected function getMinutes($duration)
<add> protected function getMinutes($minutes)
<ide> {
<del> $duration = $this->parseDateInterval($duration);
<add> $duration = $this->parseDateInterval($minutes);
<ide>
<ide> if ($duration instanceof DateTimeInterface) {
<ide> $duration = Carbon::now()->diffInRealSeconds($duration, false) / 60;
<ide> }
<ide>
<del> return (int) ($duration * 60) > 0 ? $duration : null;
<add> return (int) ($duration * 60) > 0 ? $duration : 0;
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Cache/TaggedCache.php
<ide>
<ide> class TaggedCache extends Repository
<ide> {
<del> use RetrievesMultipleKeys;
<add> use RetrievesMultipleKeys {
<add> putMany as putManyAlias;
<add> }
<ide>
<ide> /**
<ide> * The tag set instance.
<ide> public function __construct(Store $store, TagSet $tags)
<ide> $this->tags = $tags;
<ide> }
<ide>
<add> /**
<add> * Store multiple items in the cache for a given number of minutes.
<add> *
<add> * @param array $values
<add> * @param float|int|null $minutes
<add> * @return bool
<add> */
<add> public function putMany(array $values, $minutes = null)
<add> {
<add> if ($minutes === null) {
<add> return $this->putManyForever($values);
<add> }
<add>
<add> return $this->putManyAlias($values, $minutes);
<add> }
<add>
<ide> /**
<ide> * Increment the value of an item in the cache.
<ide> *
<ide><path>src/Illuminate/Contracts/Cache/Repository.php
<ide> public function pull($key, $default = null);
<ide> *
<ide> * @param string $key
<ide> * @param mixed $value
<del> * @param \DateTimeInterface|\DateInterval|float|int $minutes
<add> * @param \DateTimeInterface|\DateInterval|float|int|null $minutes
<ide> * @return bool
<ide> */
<ide> public function put($key, $value, $minutes);
<ide> public function put($key, $value, $minutes);
<ide> *
<ide> * @param string $key
<ide> * @param mixed $value
<del> * @param \DateTimeInterface|\DateInterval|float|int $minutes
<add> * @param \DateTimeInterface|\DateInterval|float|int|null $minutes
<ide> * @return bool
<ide> */
<del> public function add($key, $value, $minutes);
<add> public function add($key, $value, $minutes = null);
<ide>
<ide> /**
<ide> * Increment the value of an item in the cache.
<ide> public function forever($key, $value);
<ide> * Get an item from the cache, or execute the given Closure and store the result.
<ide> *
<ide> * @param string $key
<del> * @param \DateTimeInterface|\DateInterval|float|int $minutes
<add> * @param \DateTimeInterface|\DateInterval|float|int|null $minutes
<ide> * @param \Closure $callback
<ide> * @return mixed
<ide> */
<ide><path>tests/Cache/CacheRepositoryTest.php
<ide> public function testSettingMultipleItemsInCache()
<ide> $this->assertTrue($result);
<ide> }
<ide>
<del> public function testPutWithDatetimeInPastOrZeroSecondsDoesntSaveItem()
<add> public function testPutWithNullTTLRemembersItemForever()
<add> {
<add> $repo = $this->getRepository();
<add> $repo->getStore()->shouldReceive('forever')->once()->with('foo', 'bar')->andReturn(true);
<add> $this->assertTrue($repo->put('foo', 'bar'));
<add> }
<add>
<add> public function testPutWithDatetimeInPastOrZeroSecondsRemovesOldItem()
<ide> {
<ide> $repo = $this->getRepository();
<ide> $repo->getStore()->shouldReceive('put')->never();
<add> $repo->getStore()->shouldReceive('forget')->twice()->andReturn(true);
<ide> $result = $repo->put('foo', 'bar', Carbon::now()->subMinutes(10));
<del> $this->assertFalse($result);
<add> $this->assertTrue($result);
<ide> $result = $repo->put('foo', 'bar', Carbon::now());
<del> $this->assertFalse($result);
<add> $this->assertTrue($result);
<ide> }
<ide>
<del> public function testAddWithDatetimeInPastOrZeroSecondsReturnsImmediately()
<add> public function testPutManyWithNullTTLRemembersItemsForever()
<ide> {
<ide> $repo = $this->getRepository();
<del> $repo->getStore()->shouldReceive('add', 'get', 'put')->never();
<del> $result = $repo->add('foo', 'bar', Carbon::now()->subMinutes(10));
<del> $this->assertFalse($result);
<del> $result = $repo->add('foo', 'bar', Carbon::now());
<del> $this->assertFalse($result);
<add> $repo->getStore()->shouldReceive('forever')->with('foo', 'bar')->andReturn(true);
<add> $repo->getStore()->shouldReceive('forever')->with('bar', 'baz')->andReturn(true);
<add> $this->assertTrue($repo->putMany(['foo' => 'bar', 'bar' => 'baz']));
<ide> }
<ide>
<ide> public function testAddWithStoreFailureReturnsFalse()
<ide> public function testCacheAddCallsRedisStoreAdd()
<ide> $this->assertTrue($repository->add('k', 'v', 60));
<ide> }
<ide>
<add> public function testAddWithNullTTLRemembersItemForever()
<add> {
<add> $repo = $this->getRepository();
<add> $repo->getStore()->shouldReceive('get')->once()->with('foo')->andReturn(null);
<add> $repo->getStore()->shouldReceive('forever')->once()->with('foo', 'bar')->andReturn(true);
<add> $this->assertTrue($repo->add('foo', 'bar'));
<add> }
<add>
<add> public function testAddWithDatetimeInPastOrZeroSecondsReturnsImmediately()
<add> {
<add> $repo = $this->getRepository();
<add> $repo->getStore()->shouldReceive('add', 'get', 'put')->never();
<add> $result = $repo->add('foo', 'bar', Carbon::now()->subMinutes(10));
<add> $this->assertFalse($result);
<add> $result = $repo->add('foo', 'bar', Carbon::now());
<add> $this->assertFalse($result);
<add> }
<add>
<ide> public function dataProviderTestGetMinutes()
<ide> {
<ide> Carbon::setTestNow(Carbon::parse($this->getTestDate()));
<ide><path>tests/Cache/CacheTaggedCacheTest.php
<ide> public function testRedisCacheTagsPushStandardKeysCorrectly()
<ide> $conn->shouldReceive('sadd')->once()->with('prefix:foo:standard_ref', 'prefix:'.sha1('foo|bar').':key1');
<ide> $conn->shouldReceive('sadd')->once()->with('prefix:bar:standard_ref', 'prefix:'.sha1('foo|bar').':key1');
<ide> $store->shouldReceive('push')->with(sha1('foo|bar').':key1', 'key1:value');
<add> $store->shouldReceive('put')->andReturn(true);
<add>
<add> $redis->put('key1', 'key1:value', 60);
<add> }
<add>
<add> public function testRedisCacheTagsPushForeverKeysCorrectlyWithNullTTL()
<add> {
<add> $store = m::mock(Store::class);
<add> $tagSet = m::mock(TagSet::class, [$store, ['foo', 'bar']]);
<add> $tagSet->shouldReceive('getNamespace')->andReturn('foo|bar');
<add> $tagSet->shouldReceive('getNames')->andReturn(['foo', 'bar']);
<add> $redis = new RedisTaggedCache($store, $tagSet);
<add> $store->shouldReceive('getPrefix')->andReturn('prefix:');
<add> $store->shouldReceive('connection')->andReturn($conn = m::mock(stdClass::class));
<add> $conn->shouldReceive('sadd')->once()->with('prefix:foo:forever_ref', 'prefix:'.sha1('foo|bar').':key1');
<add> $conn->shouldReceive('sadd')->once()->with('prefix:bar:forever_ref', 'prefix:'.sha1('foo|bar').':key1');
<add> $store->shouldReceive('forever')->with(sha1('foo|bar').':key1', 'key1:value');
<ide>
<ide> $redis->put('key1', 'key1:value');
<ide> } | 6 |
Ruby | Ruby | allow python symlinks based on keg-only status | 6e82f77108c326ede038d11a81fc6e9d9c229886 | <ide><path>Library/Homebrew/formula_cellar_checks.rb
<ide> def check_plist(prefix, plist)
<ide> EOS
<ide> end
<ide>
<del> PYTHON_SYMLINK_ALLOWED_FORMULA = "[email protected]"
<del>
<del> def check_python_symlinks(name)
<add> def check_python_symlinks(name, keg_only)
<add> return unless keg_only
<ide> return unless name.start_with? "python"
<del> return if name == PYTHON_SYMLINK_ALLOWED_FORMULA
<ide>
<ide> return if %w[pip3 wheel3].none? do |l|
<ide> link = HOMEBREW_PREFIX/"bin"/l
<ide> link.exist? && File.realpath(link).start_with?(HOMEBREW_CELLAR/name)
<ide> end
<ide>
<del> "Only `#{PYTHON_SYMLINK_ALLOWED_FORMULA}` should create symlinks for `pip3` and `wheel3`"
<add> "Python formulae that are keg-only should not create `pip3` and `wheel3` symlinks"
<ide> end
<ide>
<ide> def audit_installed
<ide> def audit_installed
<ide> problem_if_output(check_python_packages(formula.lib, formula.deps))
<ide> problem_if_output(check_shim_references(formula.prefix))
<ide> problem_if_output(check_plist(formula.prefix, formula.plist))
<del> problem_if_output(check_python_symlinks(formula.name))
<add> problem_if_output(check_python_symlinks(formula.name, formula.keg_only?))
<ide> end
<ide> alias generic_audit_installed audit_installed
<ide> | 1 |
Python | Python | register most stuff only once | f7e71b518f30923f494750e476f30d91c415723e | <ide><path>flask/app.py
<ide> def register_blueprint(self, blueprint, **options):
<ide>
<ide> .. versionadded:: 0.7
<ide> """
<add> first_registration = False
<ide> if blueprint.name in self.blueprints:
<ide> assert self.blueprints[blueprint.name] is blueprint, \
<ide> 'A blueprint\'s name collision ocurred between %r and ' \
<ide> '%r. Both share the same name "%s"' % \
<ide> (blueprint, self.blueprints[blueprint.name], blueprint.name)
<ide> else:
<ide> self.blueprints[blueprint.name] = blueprint
<del> blueprint.register(self, options)
<add> first_registration = True
<add> blueprint.register(self, options, first_registration)
<ide>
<ide> def add_url_rule(self, rule, endpoint=None, view_func=None, **options):
<ide> """Connects a URL rule. Works exactly like the :meth:`route`
<ide><path>flask/blueprints.py
<ide> :license: BSD, see LICENSE for more details.
<ide> """
<ide> import os
<add>from functools import update_wrapper
<ide>
<ide> from .helpers import _PackageBoundObject, _endpoint_from_view_func
<ide>
<ide> class BlueprintSetupState(object):
<ide> application.
<ide> """
<ide>
<del> def __init__(self, blueprint, app, options):
<add> def __init__(self, blueprint, app, options, first_registration):
<ide> self.app = app
<ide> self.blueprint = blueprint
<ide> self.options = options
<add> self.first_registration = first_registration
<ide>
<ide> subdomain = self.options.get('subdomain')
<ide> if subdomain is None:
<ide> def __init__(self, name, import_name, static_folder=None,
<ide> def _record(self, func):
<ide> self.deferred_functions.append(func)
<ide>
<del> def make_setup_state(self, app, options):
<del> return BlueprintSetupState(self, app, options)
<add> def _record_once(self, func):
<add> def wrapper(state):
<add> if state.first_registration:
<add> func(state)
<add> return self._record(update_wrapper(wrapper, func))
<ide>
<del> def register(self, app, options):
<add> def make_setup_state(self, app, options, first_registration=False):
<add> return BlueprintSetupState(self, app, options, first_registration)
<add>
<add> def register(self, app, options, first_registration=False):
<ide> """Called by :meth:`Flask.register_blueprint` to register a blueprint
<ide> on the application. This can be overridden to customize the register
<ide> behavior. Keyword arguments from
<ide> :func:`~flask.Flask.register_blueprint` are directly forwarded to this
<ide> method in the `options` dictionary.
<ide> """
<del> state = self.make_setup_state(app, options)
<add> state = self.make_setup_state(app, options, first_registration)
<ide> if self.has_static_folder:
<ide> state.add_url_rule(self.static_url_path + '/<path:filename>',
<ide> view_func=self.send_static_file,
<ide> def add_url_rule(self, rule, endpoint=None, view_func=None, **options):
<ide> """Like :meth:`Flask.add_url_rule` but for a module. The endpoint for
<ide> the :func:`url_for` function is prefixed with the name of the module.
<ide> """
<del> def register_rule(state):
<del> state.add_url_rule(rule, endpoint, view_func, **options)
<del> self._record(register_rule)
<add> self._record(lambda s:
<add> s.add_url_rule(rule, endpoint, view_func, **options))
<ide>
<ide> def endpoint(self, endpoint):
<ide> """Like :meth:`Flask.endpoint` but for a module. This does not
<ide> def endpoint(self, endpoint):
<ide> def decorator(f):
<ide> def register_endpoint(state):
<ide> state.app.view_functions[endpoint] = f
<del> self._record(register_endpoint)
<add> self._record_once(register_endpoint)
<ide> return f
<ide> return decorator
<ide>
<ide> def before_request(self, f):
<ide> is only executed before each request that is handled by a function of
<ide> that module.
<ide> """
<del> self._record(lambda s: s.app.before_request_funcs
<add> self._record_once(lambda s: s.app.before_request_funcs
<ide> .setdefault(self.name, []).append(f))
<ide> return f
<ide>
<ide> def before_app_request(self, f):
<ide> """Like :meth:`Flask.before_request`. Such a function is executed
<ide> before each request, even if outside of a module.
<ide> """
<del> self._record(lambda s: s.app.before_request_funcs
<add> self._record_once(lambda s: s.app.before_request_funcs
<ide> .setdefault(None, []).append(f))
<ide> return f
<ide>
<ide> def after_request(self, f):
<ide> is only executed after each request that is handled by a function of
<ide> that module.
<ide> """
<del> self._record(lambda s: s.app.after_request_funcs
<add> self._record_once(lambda s: s.app.after_request_funcs
<ide> .setdefault(self.name, []).append(f))
<ide> return f
<ide>
<ide> def after_app_request(self, f):
<ide> """Like :meth:`Flask.after_request` but for a module. Such a function
<ide> is executed after each request, even if outside of the module.
<ide> """
<del> self._record(lambda s: s.app.after_request_funcs
<add> self._record_once(lambda s: s.app.after_request_funcs
<ide> .setdefault(None, []).append(f))
<ide> return f
<ide>
<ide> def context_processor(self, f):
<ide> """Like :meth:`Flask.context_processor` but for a module. This
<ide> function is only executed for requests handled by a module.
<ide> """
<del> self._record(lambda s: s.app.template_context_processors
<add> self._record_once(lambda s: s.app.template_context_processors
<ide> .setdefault(self.name, []).append(f))
<ide> return f
<ide>
<ide> def app_context_processor(self, f):
<ide> """Like :meth:`Flask.context_processor` but for a module. Such a
<ide> function is executed each request, even if outside of the module.
<ide> """
<del> self._record(lambda s: s.app.template_context_processors
<add> self._record_once(lambda s: s.app.template_context_processors
<ide> .setdefault(None, []).append(f))
<ide> return f
<ide>
<ide> def app_errorhandler(self, code):
<ide> handler is used for all requests, even if outside of the module.
<ide> """
<ide> def decorator(f):
<del> self._record(lambda s: s.app.errorhandler(code)(f))
<add> self._record_once(lambda s: s.app.errorhandler(code)(f))
<ide> return f
<ide> return decorator | 2 |
Go | Go | remove the unneeded deprecation markup | d9c257732e435cecdcc1ec8452f35e7614e4713f | <ide><path>runconfig/parse.go
<ide> func parseRun(cmd *flag.FlagSet, args []string, sysInfo *sysinfo.SysInfo) (*Conf
<ide> cmd.Var(&flVolumes, []string{"v", "-volume"}, "Bind mount a volume (e.g. from the host: -v /host:/container, from docker: -v /container)")
<ide> cmd.Var(&flLinks, []string{"#link", "-link"}, "Add link to another container (name:alias)")
<ide> cmd.Var(&flEnv, []string{"e", "-env"}, "Set environment variables")
<del> cmd.Var(&flEnvFile, []string{"#env-file", "-env-file"}, "Read in a line delimited file of ENV variables")
<add> cmd.Var(&flEnvFile, []string{"-env-file"}, "Read in a line delimited file of ENV variables")
<ide>
<ide> cmd.Var(&flPublish, []string{"p", "-publish"}, fmt.Sprintf("Publish a container's port to the host (format: %s) (use 'docker port' to see the actual mapping)", nat.PortSpecTemplateFormat))
<ide> cmd.Var(&flExpose, []string{"#expose", "-expose"}, "Expose a port from the container without publishing it to your host") | 1 |
Mixed | Text | add changelog entry for [ci skip] | f141919974806568f480cf2c670f990322308044 | <ide><path>activerecord/CHANGELOG.md
<add>* Fix presence validator for association when the associated record responds to `to_a`.
<add>
<add> *gmarik*
<add>
<ide> * Fixed regression on preload/includes with multiple arguments failing in certain conditions,
<ide> raising a NoMethodError internally by calling `reflect_on_association` for `NilClass:Class`.
<ide>
<ide><path>activerecord/test/cases/validations/presence_validation_test.rb
<ide> def test_validates_presence_of_has_many_marked_for_destruction
<ide> assert b.invalid?
<ide> end
<ide>
<del>
<ide> def test_validates_presence_doesnt_convert_to_array
<ide> Speedometer.validates_presence_of :dashboard
<ide> | 2 |
Go | Go | avoid unset credentials in containerd | effb2bd9d23cc05305c4772338b9eb39423e92c6 | <ide><path>builder/builder-next/adapters/containerimage/pull.go
<ide> func (is *imageSource) getResolver(ctx context.Context, rfn resolver.ResolveOpti
<ide> func (is *imageSource) getCredentialsFromSession(ctx context.Context) func(string) (string, string, error) {
<ide> id := session.FromContext(ctx)
<ide> if id == "" {
<del> return nil
<add> // can be removed after containerd/containerd#2812
<add> return func(string) (string, string, error) {
<add> return "", "", nil
<add> }
<ide> }
<ide> return func(host string) (string, string, error) {
<ide> timeoutCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) | 1 |
Java | Java | fix build failures | 4ed581cdd723e232935a277d092ea6ec981909b6 | <ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ResponseBodyResultHandlerTests.java
<ide> private void testProblemDetailMediaType(MockServerWebExchange exchange, MediaTyp
<ide> "\"title\":\"Bad Request\"," +
<ide> "\"status\":400," +
<ide> "\"detail\":null," +
<del> "\"instance\":\"/path\"}");
<add> "\"instance\":\"/path\"," +
<add> "\"properties\":null}");
<ide> }
<ide>
<ide> @Test
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ResponseEntityResultHandlerTests.java
<ide> public void handleErrorResponse() {
<ide> "\"title\":\"Bad Request\"," +
<ide> "\"status\":400," +
<ide> "\"detail\":null," +
<del> "\"instance\":\"/path\"}");
<add> "\"instance\":\"/path\"," +
<add> "\"properties\":null}");
<ide> }
<ide>
<ide> @Test
<ide> public void handleProblemDetail() {
<ide> "\"title\":\"Bad Request\"," +
<ide> "\"status\":400," +
<ide> "\"detail\":null," +
<del> "\"instance\":\"/path\"}");
<add> "\"instance\":\"/path\"," +
<add> "\"properties\":null}");
<ide> }
<ide>
<ide> @Test | 2 |
Python | Python | add unit tests for bert_models.py | c25c3e882e398d287240f619d7f56ac5b2973b6e | <ide><path>official/nlp/bert/bert_models_test.py
<add># Copyright 2020 The TensorFlow Authors. All Rights Reserved.
<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># http://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>from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<add>
<add>import tensorflow as tf
<add>
<add>from official.nlp.bert import bert_models
<add>from official.nlp.bert import configs as bert_configs
<add>from official.nlp.modeling import networks
<add>
<add>
<add>class BertModelsTest(tf.test.TestCase):
<add>
<add> def setUp(self):
<add> super(BertModelsTest, self).setUp()
<add> self._bert_test_config = bert_configs.BertConfig(
<add> attention_probs_dropout_prob=0.0,
<add> hidden_act='gelu',
<add> hidden_dropout_prob=0.0,
<add> hidden_size=16,
<add> initializer_range=0.02,
<add> intermediate_size=32,
<add> max_position_embeddings=128,
<add> num_attention_heads=2,
<add> num_hidden_layers=2,
<add> type_vocab_size=2,
<add> vocab_size=30522)
<add>
<add> def test_pretrain_model(self):
<add> model, encoder = bert_models.pretrain_model(
<add> self._bert_test_config,
<add> seq_length=5,
<add> max_predictions_per_seq=2,
<add> initializer=None,
<add> use_next_sentence_label=True)
<add> self.assertIsInstance(model, tf.keras.Model)
<add> self.assertIsInstance(encoder, networks.TransformerEncoder)
<add>
<add> # model has one scalar output: loss value.
<add> self.assertEqual(model.output.shape.as_list(), [None,])
<add>
<add> # Expect two output from encoder: sequence and classification output.
<add> self.assertIsInstance(encoder.output, list)
<add> self.assertLen(encoder.output, 2)
<add> # shape should be [batch size, seq_length, hidden_size]
<add> self.assertEqual(encoder.output[0].shape.as_list(), [None, 5, 16])
<add> # shape should be [batch size, hidden_size]
<add> self.assertEqual(encoder.output[1].shape.as_list(), [None, 16])
<add>
<add> def test_squad_model(self):
<add> model, core_model = bert_models.squad_model(
<add> self._bert_test_config,
<add> max_seq_length=5,
<add> initializer=None,
<add> hub_module_url=None,
<add> hub_module_trainable=None)
<add> self.assertIsInstance(model, tf.keras.Model)
<add> self.assertIsInstance(core_model, tf.keras.Model)
<add>
<add> # Expect two output from model: start positions and end positions
<add> self.assertIsInstance(model.output, list)
<add> self.assertLen(model.output, 2)
<add> # shape should be [batch size, seq_length]
<add> self.assertEqual(model.output[0].shape.as_list(), [None, 5])
<add> # shape should be [batch size, seq_length]
<add> self.assertEqual(model.output[1].shape.as_list(), [None, 5])
<add>
<add> # Expect two output from core_model: sequence and classification output.
<add> self.assertIsInstance(core_model.output, list)
<add> self.assertLen(core_model.output, 2)
<add> # shape should be [batch size, seq_length, hidden_size]
<add> self.assertEqual(core_model.output[0].shape.as_list(), [None, 5, 16])
<add> # shape should be [batch size, hidden_size]
<add> self.assertEqual(core_model.output[1].shape.as_list(), [None, 16])
<add>
<add> def test_classifier_model(self):
<add> model, core_model = bert_models.classifier_model(
<add> self._bert_test_config,
<add> num_labels=3,
<add> max_seq_length=5,
<add> final_layer_initializer=None,
<add> hub_module_url=None,
<add> hub_module_trainable=None)
<add> self.assertIsInstance(model, tf.keras.Model)
<add> self.assertIsInstance(core_model, tf.keras.Model)
<add>
<add> # model has one classification output with num_labels=3.
<add> self.assertEqual(model.output.shape.as_list(), [None, 3])
<add>
<add> # Expect two output from core_model: sequence and classification output.
<add> self.assertIsInstance(core_model.output, list)
<add> self.assertLen(core_model.output, 2)
<add> # shape should be [batch size, 1, hidden_size]
<add> self.assertEqual(core_model.output[0].shape.as_list(), [None, 1, 16])
<add> # shape should be [batch size, hidden_size]
<add> self.assertEqual(core_model.output[1].shape.as_list(), [None, 16])
<add>
<add>
<add>if __name__ == '__main__':
<add> tf.test.main() | 1 |
Javascript | Javascript | move suspenselist to experimental package | c47f59331ee94b1d04f974f075373d368a8c8ab3 | <ide><path>packages/react-dom/src/__tests__/ReactDOMServerPartialHydration-test.internal.js
<ide> describe('ReactDOMServerPartialHydration', () => {
<ide> ReactDOMServer = require('react-dom/server');
<ide> Scheduler = require('scheduler');
<ide> Suspense = React.Suspense;
<del> SuspenseList = React.unstable_SuspenseList;
<add> SuspenseList = React.SuspenseList;
<ide>
<ide> useHover = require('react-interactions/events/hover').useHover;
<ide> });
<ide><path>packages/react-dom/src/__tests__/ReactDOMServerSuspense-test.internal.js
<ide> describe('ReactDOMServerSuspense', () => {
<ide>
<ide> it('server renders a SuspenseList component and its children', async () => {
<ide> const example = (
<del> <React.unstable_SuspenseList>
<add> <React.SuspenseList>
<ide> <React.Suspense fallback="Loading A">
<ide> <div>A</div>
<ide> </React.Suspense>
<ide> <React.Suspense fallback="Loading B">
<ide> <div>B</div>
<ide> </React.Suspense>
<del> </React.unstable_SuspenseList>
<add> </React.SuspenseList>
<ide> );
<ide> const element = await serverRender(example);
<ide> const parent = element.parentNode;
<ide><path>packages/react-dom/src/__tests__/ReactTestUtilsAct-test.js
<ide> function runActTests(label, render, unmount, rerender) {
<ide> });
<ide>
<ide> describe('suspense', () => {
<del> if (__DEV__) {
<add> if (__DEV__ && __EXPERIMENTAL__) {
<ide> it('triggers fallbacks if available', async () => {
<ide> let resolved = false;
<ide> let resolve;
<ide><path>packages/react-reconciler/src/__tests__/ReactSuspenseList-test.internal.js
<ide> let Suspense;
<ide> let SuspenseList;
<ide>
<ide> describe('ReactSuspenseList', () => {
<add> if (!__EXPERIMENTAL__) {
<add> it("empty test so Jest doesn't complain", () => {});
<add> return;
<add> }
<add>
<ide> beforeEach(() => {
<ide> jest.resetModules();
<ide> ReactFeatureFlags = require('shared/ReactFeatureFlags');
<ide> describe('ReactSuspenseList', () => {
<ide> ReactNoop = require('react-noop-renderer');
<ide> Scheduler = require('scheduler');
<ide> Suspense = React.Suspense;
<del> SuspenseList = React.unstable_SuspenseList;
<add> SuspenseList = React.SuspenseList;
<ide> });
<ide>
<ide> function Text(props) {
<ide><path>packages/react-reconciler/src/__tests__/ReactSuspenseWithNoopRenderer-test.internal.js
<ide> let TextResource;
<ide> let textResourceShouldFail;
<ide>
<ide> describe('ReactSuspenseWithNoopRenderer', () => {
<add> if (!__EXPERIMENTAL__) {
<add> it("empty test so Jest doesn't complain", () => {});
<add> return;
<add> }
<add>
<ide> beforeEach(() => {
<ide> jest.resetModules();
<ide> ReactFeatureFlags = require('shared/ReactFeatureFlags');
<ide><path>packages/react/index.fb.js
<add>/**
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> */
<add>
<add>'use strict';
<add>
<add>const ReactFB = require('./src/ReactFB');
<add>
<add>// TODO: decide on the top-level export form.
<add>// This is hacky but makes it work with both Rollup and Jest.
<add>module.exports = ReactFB.default || ReactFB;
<ide><path>packages/react/src/React.js
<ide> const React = {
<ide> Profiler: REACT_PROFILER_TYPE,
<ide> StrictMode: REACT_STRICT_MODE_TYPE,
<ide> Suspense: REACT_SUSPENSE_TYPE,
<del> unstable_SuspenseList: REACT_SUSPENSE_LIST_TYPE,
<ide>
<ide> createElement: __DEV__ ? createElementWithValidation : createElement,
<ide> cloneElement: __DEV__ ? cloneElementWithValidation : cloneElement,
<ide> const React = {
<ide>
<ide> version: ReactVersion,
<ide>
<del> unstable_withSuspenseConfig: withSuspenseConfig,
<del>
<ide> __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: ReactSharedInternals,
<ide> };
<ide>
<ide> if (exposeConcurrentModeAPIs) {
<ide> React.useTransition = useTransition;
<ide> React.useDeferredValue = useDeferredValue;
<add> React.SuspenseList = REACT_SUSPENSE_LIST_TYPE;
<add> React.unstable_withSuspenseConfig = withSuspenseConfig;
<ide> }
<ide>
<ide> if (enableFlareAPI) {
<ide><path>packages/react/src/ReactFB.js
<add>/**
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> *
<add> * @flow
<add> */
<add>
<add>import React from './React';
<add>
<add>// TODO: Temporary alias until we update the callers downstream.
<add>React.unstable_SuspenseList = React.SuspenseList;
<add>
<add>export default React;
<ide><path>packages/react/src/__tests__/ReactDOMTracing-test.internal.js
<ide> describe('ReactDOMTracing', () => {
<ide> });
<ide>
<ide> it('should properly trace interactions through a multi-pass SuspenseList render', () => {
<del> const SuspenseList = React.unstable_SuspenseList;
<add> const SuspenseList = React.SuspenseList;
<ide> const Suspense = React.Suspense;
<ide> function Text({text}) {
<ide> Scheduler.unstable_yieldValue(text); | 9 |
Python | Python | replace function calls to set litteral | b17d6c82b3200f095381298fa6af9cbe27129521 | <ide><path>libcloud/test/compute/test_azure_arm.py
<ide> def test_sizes_returned_successfully(self):
<ide> def test_ex_get_ratecard(self):
<ide> ratecard = self.driver.ex_get_ratecard('0026P')
<ide> self.assertEqual(set(ratecard.keys()),
<del> set(['Currency',
<del> 'Locale',
<del> 'IsTaxIncluded',
<del> 'OfferTerms',
<del> 'Meters']))
<add> {'Currency', 'Locale', 'IsTaxIncluded',
<add> 'OfferTerms', 'Meters'})
<ide>
<ide> def test_create_node(self):
<ide> location = NodeLocation('any_location', '', '', self.driver)
<ide> def test_attach_volume(self):
<ide> data_disks = node.extra['properties']['storageProfile']['dataDisks']
<ide> luns = [disk['lun'] for disk in data_disks]
<ide> self.assertTrue(len(data_disks), len(volumes))
<del> self.assertTrue(set(luns), set([0, 1, 15]))
<add> self.assertTrue(set(luns), {0, 1, 15})
<ide>
<ide> def test_detach_volume(self):
<ide> volumes = self.driver.list_volumes()
<ide><path>libcloud/test/loadbalancer/test_gogrid.py
<ide> def test_balancer_list_members(self):
<ide> members1 = self.driver.balancer_list_members(balancer=balancer)
<ide> members2 = balancer.list_members()
<ide>
<del> expected_members = set(['10.0.0.78:80', '10.0.0.77:80',
<del> '10.0.0.76:80'])
<add> expected_members = {'10.0.0.78:80', '10.0.0.77:80', '10.0.0.76:80'}
<ide>
<ide> self.assertEqual(len(members1), 3)
<ide> self.assertEqual(len(members2), 3)
<ide><path>libcloud/test/loadbalancer/test_rackspace.py
<ide> def test_ex_disable_balancer_custom_error_page(self):
<ide> self.assertEqual(default_error_page, error_page_content)
<ide>
<ide> def test_balancer_list_members(self):
<del> expected = set(['10.1.0.10:80', '10.1.0.11:80', '10.1.0.9:8080'])
<add> expected = {'10.1.0.10:80', '10.1.0.11:80', '10.1.0.9:8080'}
<ide> balancer = self.driver.get_balancer(balancer_id='8290')
<ide> members = balancer.list_members()
<ide> | 3 |
Python | Python | fix failing 'default' on modelserializer | 67f1265e493adc35239d90aeb3bfeb8492fbd741 | <ide><path>rest_framework/serializers.py
<ide> def get_field(self, model_field):
<ide> kwargs = {}
<ide> if model_field.has_default():
<ide> kwargs['required'] = False
<del> kwargs['default'] = model_field.default
<add> kwargs['default'] = model_field.get_default()
<ide>
<ide> if model_field.__class__ == models.TextField:
<ide> kwargs['widget'] = widgets.Textarea
<ide><path>rest_framework/tests/models.py
<ide> class CallableDefaultValueModel(RESTFrameworkModel):
<ide>
<ide> class ManyToManyModel(RESTFrameworkModel):
<ide> rel = models.ManyToManyField(Anchor)
<del>
<add>
<ide>
<ide> class ReadOnlyManyToManyModel(RESTFrameworkModel):
<ide> text = models.CharField(max_length=100, default='anchor')
<ide> rel = models.ManyToManyField(Anchor)
<del>
<add>
<ide> # Models to test generic relations
<ide>
<ide>
<ide><path>rest_framework/tests/serializer.py
<ide> class SubComment(object):
<ide> def __init__(self, sub_comment):
<ide> self.sub_comment = sub_comment
<del>
<add>
<ide>
<ide> class Comment(object):
<ide> def __init__(self, email, content, created):
<ide> def __init__(self, email, content, created):
<ide> def __eq__(self, other):
<ide> return all([getattr(self, attr) == getattr(other, attr)
<ide> for attr in ('email', 'content', 'created')])
<del>
<add>
<ide> def get_sub_comment(self):
<ide> sub_comment = SubComment('And Merry Christmas!')
<ide> return sub_comment
<ide> class CommentSerializer(serializers.Serializer):
<ide> content = serializers.CharField(max_length=1000)
<ide> created = serializers.DateTimeField()
<ide> sub_comment = serializers.Field(source='get_sub_comment.sub_comment')
<del>
<add>
<ide> def restore_object(self, data, instance=None):
<ide> if instance is None:
<ide> return Comment(**data)
<ide> class ActionItemSerializer(serializers.ModelSerializer):
<ide> class Meta:
<ide> model = ActionItem
<ide>
<add>
<ide> class BasicTests(TestCase):
<ide> def setUp(self):
<ide> self.comment = Comment(
<ide> def test_empty(self):
<ide> self.assertEquals(serializer.data, expected)
<ide>
<ide> def test_retrieve(self):
<del> serializer = CommentSerializer(instance=self.comment)
<add> serializer = CommentSerializer(instance=self.comment)
<ide> self.assertEquals(serializer.data, self.expected)
<ide>
<ide> def test_create(self):
<ide> def setUp(self):
<ide> 'email': '[email protected]',
<ide> 'content': 'x' * 1001,
<ide> 'created': datetime.datetime(2012, 1, 1)
<del> }
<add> }
<ide> self.actionitem = ActionItem('Some to do item',
<ide> )
<ide>
<ide> def test_missing_bool_with_default(self):
<ide> """Make sure that a boolean value with a 'False' value is not
<ide> mistaken for not having a default."""
<ide> data = {
<del> 'title':'Some action item',
<add> 'title': 'Some action item',
<ide> #No 'done' value.
<ide> }
<ide> serializer = ActionItemSerializer(data, instance=self.actionitem)
<ide> def test_create_empty_relationship_flat_data(self):
<ide> self.assertEquals(len(ManyToManyModel.objects.all()), 2)
<ide> self.assertEquals(instance.pk, 2)
<ide> self.assertEquals(list(instance.rel.all()), [])
<del>
<add>
<add>
<ide> class ReadOnlyManyToManyTests(TestCase):
<ide> def setUp(self):
<ide> class ReadOnlyManyToManySerializer(serializers.ModelSerializer):
<del> rel = serializers.ManyRelatedField(readonly=True)
<add> rel = serializers.ManyRelatedField(readonly=True)
<add>
<ide> class Meta:
<ide> model = ReadOnlyManyToManyModel
<ide>
<ide> class Meta:
<ide> # A serialized representation of the model instance
<ide> self.data = {'rel': [self.anchor.id], 'id': 1, 'text': 'anchor'}
<ide>
<del>
<ide> def test_update(self):
<ide> """
<ide> Attempt to update an instance of a model with a ManyToMany | 3 |
Javascript | Javascript | fix navigation widget to work without jquery | 00ea08e0ab2a0154e168e63f2505d885bbca9096 | <ide><path>docs/src/templates/doc_widgets.js
<ide> this.descend(true);
<ide>
<ide> var tabs = angular.element(HTML_TPL.replace('{show}', element.attr('show') || 'false')),
<del> nav = tabs.find('.tabs-nav ul'),
<del> content = tabs.find('.tabs-content-inner'),
<add> nav = tabs.find('ul'),
<add> // use simple selectors because jqLite find() supports getElementsByTagName only
<add> content = tabs.find('div').find('div'),
<ide> children = element.children();
<ide>
<ide> if (children.length) { | 1 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.