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
PHP
PHP
return the object when is set method
f4f3bfe2fc7c74cf97a362acb8901b6d77181379
<ide><path>lib/Cake/Network/CakeEmail.php <ide> public function from($email = null, $name = null) { <ide> if ($email === null) { <ide> return $this->_from; <ide> } <del> $this->_setEmailSingle('_from', $email, $name, __d('cake', 'From requires only 1 email address.')); <add> return $this->_setEmailSingle('_from', $email, $name, __d('cake', 'From requires only 1 email address.')); <ide> } <ide> <ide> /** <ide> public function replyTo($email = null, $name = null) { <ide> if ($email === null) { <ide> return $this->_replyTo; <ide> } <del> $this->_setEmailSingle('_replyTo', $email, $name, __d('cake', 'Reply-To requires only 1 email address.')); <add> return $this->_setEmailSingle('_replyTo', $email, $name, __d('cake', 'Reply-To requires only 1 email address.')); <ide> } <ide> <ide> /** <ide> public function readReceipt($email = null, $name = null) { <ide> if ($email === null) { <ide> return $this->_readReceipt; <ide> } <del> $this->_setEmailSingle('_readReceipt', $email, $name, __d('cake', 'Disposition-Notification-To requires only 1 email address.')); <add> return $this->_setEmailSingle('_readReceipt', $email, $name, __d('cake', 'Disposition-Notification-To requires only 1 email address.')); <ide> } <ide> <ide> /** <ide> public function returnPath($email = null, $name = null) { <ide> if ($email === null) { <ide> return $this->_returnPath; <ide> } <del> $this->_setEmailSingle('_returnPath', $email, $name, __d('cake', 'Return-Path requires only 1 email address.')); <add> return $this->_setEmailSingle('_returnPath', $email, $name, __d('cake', 'Return-Path requires only 1 email address.')); <ide> } <ide> <ide> /** <ide> public function to($email = null, $name = null) { <ide> if ($email === null) { <ide> return $this->_to; <ide> } <del> $this->_setEmail('_to', $email, $name); <add> return $this->_setEmail('_to', $email, $name); <ide> } <ide> <ide> /** <ide> * Add To <ide> * <ide> * @param mixed $email String with email, Array with email as key, name as value or email as value (without name) <ide> * @param string $name <del> * @return void <add> * @return object $this <ide> */ <ide> public function addTo($email, $name = null) { <del> $this->_addEmail('_to', $email, $name); <add> return $this->_addEmail('_to', $email, $name); <ide> } <ide> <ide> /** <ide> public function cc($email = null, $name = null) { <ide> if ($email === null) { <ide> return $this->_cc; <ide> } <del> $this->_setEmail('_cc', $email, $name); <add> return $this->_setEmail('_cc', $email, $name); <ide> } <ide> <ide> /** <ide> * Add Cc <ide> * <ide> * @param mixed $email String with email, Array with email as key, name as value or email as value (without name) <ide> * @param string $name <del> * @return void <add> * @return object $this <ide> */ <ide> public function addCc($email, $name = null) { <del> $this->_addEmail('_cc', $email, $name); <add> return $this->_addEmail('_cc', $email, $name); <ide> } <ide> <ide> /** <ide> * Bcc <ide> * <ide> * @param mixed $email String with email, Array with email as key, name as value or email as value (without name) <ide> * @param string $name <del> * @return void <add> * @return mixed <ide> */ <ide> public function bcc($email = null, $name = null) { <ide> if ($email === null) { <ide> return $this->_bcc; <ide> } <del> $this->_setEmail('_bcc', $email, $name); <add> return $this->_setEmail('_bcc', $email, $name); <ide> } <ide> <ide> /** <ide> * Add Bcc <ide> * <ide> * @param mixed $email String with email, Array with email as key, name as value or email as value (without name) <ide> * @param string $name <del> * @return void <add> * @return object $this <ide> */ <ide> public function addBcc($email, $name = null) { <del> $this->_addEmail('_bcc', $email, $name); <add> return $this->_addEmail('_bcc', $email, $name); <ide> } <ide> <ide> /** <ide> public function addBcc($email, $name = null) { <ide> * @param string $varName <ide> * @param mixed $email <ide> * @param mixed $name <del> * @return void <add> * @return object $this <ide> * @thrown SocketException <ide> */ <ide> protected function _setEmail($varName, $email, $name) { <ide> protected function _setEmail($varName, $email, $name) { <ide> $name = $email; <ide> } <ide> $this->{$varName} = array($email => $name); <del> return; <add> return $this; <ide> } <ide> $list = array(); <ide> foreach ($email as $key => $value) { <ide> protected function _setEmail($varName, $email, $name) { <ide> $list[$key] = $value; <ide> } <ide> $this->{$varName} = $list; <add> return $this; <ide> } <ide> <ide> /** <ide> protected function _setEmail($varName, $email, $name) { <ide> * @param mixed $email <ide> * @param string $name <ide> * @param string $throwMessage <del> * @return void <add> * @return object $this <ide> * @thrown SocketExpceiton <ide> */ <ide> protected function _setEmailSingle($varName, $email, $name, $throwMessage) { <ide> protected function _setEmailSingle($varName, $email, $name, $throwMessage) { <ide> $this->{$varName} = $current; <ide> throw new SocketException($throwMessage); <ide> } <add> return $this; <ide> } <ide> <ide> /** <ide> protected function _setEmailSingle($varName, $email, $name, $throwMessage) { <ide> * @param string $varName <ide> * @param mixed $email <ide> * @param mixed $name <del> * @return void <add> * @return object $this <ide> */ <ide> protected function _addEmail($varName, $email, $name) { <ide> if (!is_array($email)) { <ide> protected function _addEmail($varName, $email, $name) { <ide> $name = $email; <ide> } <ide> $this->{$varName}[$email] = $name; <del> return; <add> return $this; <ide> } <ide> $list = array(); <ide> foreach ($email as $key => $value) { <ide> protected function _addEmail($varName, $email, $name) { <ide> $list[$key] = $value; <ide> } <ide> $this->{$varName} = array_merge($this->{$varName}, $list); <add> return $this; <ide> } <ide> <ide> /** <ide> public function subject($subject = null) { <ide> return $this->_subject; <ide> } <ide> $this->_subject = (string)$subject; <add> return $this; <ide> } <ide> <ide> /** <ide> * Sets eaders for the message <ide> * <ide> * @param array Associative array containing headers to be set. <del> * @return void <add> * @return object $this <ide> * @thrown SocketException <ide> */ <ide> public function setHeaders($headers) { <ide> if (!is_array($headers)) { <ide> throw new SocketException(__d('cake', '$headers should be an array.')); <ide> } <ide> $this->_headers = $headers; <add> return $this; <ide> } <ide> <ide> /** <ide> * Add header for the message <ide> * <ide> * @param array $headers <del> * @return void <add> * @return mixed $this <ide> * @thrown SocketException <ide> */ <ide> public function addHeaders($headers) { <ide> if (!is_array($headers)) { <ide> throw new SocketException(__d('cake', '$headers should be an array.')); <ide> } <ide> $this->_headers = array_merge($this->_headers, $headers); <add> return $this; <ide> } <ide> <ide> /** <ide> public function layout($layout = null, $template = null) { <ide> if ($template !== null) { <ide> $this->_template = (string)$template; <ide> } <add> return $this; <ide> } <ide> <ide> /** <ide> public function viewRender($viewClass = null) { <ide> return $this->_viewRender; <ide> } <ide> $this->_viewRender = $viewClass; <add> return $this; <ide> } <ide> <ide> /** <ide> public function emailFormat($format = null) { <ide> throw new SocketException(__d('cake', 'Format not available.')); <ide> } <ide> $this->_emailFormat = $format; <add> return $this; <ide> } <ide> <ide> /** <ide> public function transport($name = null) { <ide> return $this->_transportName; <ide> } <ide> $this->_transportName = (string)$name; <add> return $this; <ide> } <ide> <ide> /** <ide> public function messageID($message = null) { <ide> } <ide> $this->_messageId = $message; <ide> } <add> return $this; <ide> } <ide> <ide> /** <ide> public function attachments($attachments = null) { <ide> $attach[$name] = $path; <ide> } <ide> $this->_attachments = $attach; <add> return $this; <ide> } <ide> <ide> /** <ide> * Add attachments <ide> * <ide> * @param mixed $attachments String with the filename or array with filenames <del> * @return void <add> * @return object $this <ide> * @thrown SocketException <ide> */ <ide> public function addAttachments($attachments) { <ide> $current = $this->_attachments; <ide> $this->attachments($attachments); <ide> $this->_attachments = array_merge($current, $this->_attachments); <add> return $this; <ide> } <ide> <ide> /** <ide> public function message() { <ide> * Configuration to use when send email <ide> * <ide> * @param mixed $config String with configuration name (from email.php), array with config or null to return current config <del> * @return string <add> * @return mixed <ide> */ <ide> public function config($config = null) { <del> if (!empty($config)) { <del> if (is_array($config)) { <del> $this->_config = $config; <del> } else { <del> $this->_config = (string)$config; <del> } <add> if (empty($config)) { <add> return $this->_config; <add> } <add> if (is_array($config)) { <add> $this->_config = $config; <add> } else { <add> $this->_config = (string)$config; <ide> } <del> return $this->_config; <add> return $this; <ide> } <ide> <ide> /** <ide> public function send($content = null) { <ide> /** <ide> * Reset all EmailComponent internal variables to be able to send out a new email. <ide> * <del> * @return void <add> * @return object $this <ide> */ <ide> public function reset() { <ide> $this->_to = array(); <ide> public function reset() { <ide> $this->_transportName = 'mail'; <ide> $this->_attachments = array(); <ide> $this->_config = 'default'; <add> return $this; <ide> } <ide> <ide> /**
1
Python
Python
resolve line-too-long in dtensor
cf199f341bd2c179c1737dde75ec55d07422f69e
<ide><path>keras/dtensor/__init__.py <ide> if _DTENSOR_API_ENABLED: <ide> from tensorflow.compat.v2.experimental import dtensor as dtensor_api <ide> else: <del> # Leave it with a placeholder, so that the import line from other python file <del> # will not break. <add> # Leave it with a placeholder, so that the import line from other python <add> # file will not break. <ide> dtensor_api = None <ide><path>keras/dtensor/initializers_test.py <ide> def test_random_value_initializer(self, initializer_cls, init_args): <ide> new_value = initializer(shape=shape, layout=layout) <ide> self.assertAllClose(value, new_value) <ide> finally: <del> # Unset the keras global generator so that it doesn't affect other tests <del> # that need to verify the existence of global generator. <add> # Unset the keras global generator so that it doesn't affect other <add> # tests that need to verify the existence of global generator. <ide> backend._SEED_GENERATOR.generator = None <ide> <ide> @parameterized.named_parameters( <ide><path>keras/dtensor/layout_map.py <ide> def get_current_layout_map(): <ide> class LayoutMap(collections.abc.MutableMapping): <ide> """A dict-like object that maps string to `Layout` instances. <ide> <del> `LayoutMap` uses a string as key and a `Layout` as value. There is a behavior <del> difference between a normal Python dict and this class. The string key will be <del> treated as a regex when retrieving the value. See the docstring of <del> `get` for more details. <add> `LayoutMap` uses a string as key and a `Layout` as value. There is a <add> behavior difference between a normal Python dict and this class. The string <add> key will be treated as a regex when retrieving the value. See the docstring <add> of `get` for more details. <ide> <ide> See below for a usage example. You can define the naming schema <ide> of the `Layout`, and then retrieve the corresponding `Layout` instance. <ide> def __getitem__(self, key): <ide> """Retrieve the corresponding layout by the string key. <ide> <ide> When there isn't an exact match, all the existing keys in the layout map <del> will be treated as a regex and map against the input key again. The first <del> match will be returned, based on the key insertion order. Return None if <del> there isn't any match found. <add> will be treated as a regex and map against the input key again. The <add> first match will be returned, based on the key insertion order. Return <add> None if there isn't any match found. <ide> <ide> Args: <ide> key: the string key as the query for the layout. <ide> def layout_map_scope(layout_map): <ide> to map the variable against the layout. <ide> <ide> For subclassed models, the full object/attribute name is used as the key. <del> For Functional/Sequential models, since the layers within the model do not get <del> assigned to a meaningful attribute, we use `layer.name` as the key <del> for the layer, followed by the attribute name. Keras ensures <del> name uniqueness among the layers in all Functional/Sequential models. <add> For Functional/Sequential models, since the layers within the model do not <add> get assigned to a meaningful attribute, we use `layer.name` as the key for <add> the layer, followed by the attribute name. Keras ensures name uniqueness <add> among the layers in all Functional/Sequential models. <ide> <ide> See the following examples that show the variable object names <ide> for different Keras model types: <ide> def call(self, inputs): <ide> ``` <ide> <ide> Args: <del> layout_map: a LayoutMap which contains the variable_object_path (string) -> <del> Layout. When a layout is not found for the variable, a default all <add> layout_map: a LayoutMap which contains the variable_object_path (string) <add> -> Layout. When a layout is not found for the variable, a default all <ide> replicated layout will be created for the variable. <ide> <ide> Yields: <ide> def _map_functional_model_variable(model, layout_map): <ide> # name based on the class name. <ide> layer_name = layer.name <ide> for path, variable in layer._flatten( <del> predicate=_is_lazy_init_variable, # pylint: disable=protected-access <add> predicate=_is_lazy_init_variable, <ide> with_path=True, <ide> ): <ide> # Note that path is a tuple that contains string and ints, eg: <del> # ('d1', '_trainable_weights', 0) maps to model.d1._trainable_weights[0] <add> # ('d1', '_trainable_weights', 0) maps to <add> # model.d1._trainable_weights[0] <ide> if [a for a in _KERAS_ATTRIBUTES_TO_SKIP if a in path]: <ide> continue <ide> # Convert all the ints to string and join with . <ide> def _map_functional_model_variable(model, layout_map): <ide> layer, lazy_init_variable_to_tf_variable_map <ide> ) <ide> <del> # After we replaced all the variables, we want to make sure all the cached <del> # attributes are having the new variable, rather than old LazyInitVariable. <add> # After we replaced all the variables, we want to make sure all the <add> # cached attributes are having the new variable, rather than old <add> # LazyInitVariable. <ide> for path, variable in layer._flatten( <del> predicate=_is_lazy_init_variable, # pylint: disable=protected-access <add> predicate=_is_lazy_init_variable, <ide> with_path=True, <ide> ): <ide> tf_variable = lazy_init_variable_to_tf_variable_map[id(variable)] <ide> def _map_functional_model_variable(model, layout_map): <ide> def _init_state_variable_for_rng(model, layout_map): <ide> """Init the state variable in tf.ranodm.Generator. <ide> <del> Since the BaseRandomLayer in keras explicitly untrack the tf.random.Generator, <del> the variable in it will stay as LazyInitVariable, which cause runtime error if <del> we don't replace them with proper DVariable. Since user usually are not <del> aware the existence of those variable, we will just give them replicated <del> layout since they are tiny. <add> Since the BaseRandomLayer in keras explicitly untrack the <add> tf.random.Generator, the variable in it will stay as LazyInitVariable, which <add> cause runtime error if we don't replace them with proper DVariable. Since <add> user usually are not aware the existence of those variable, we will just <add> give them replicated layout since they are tiny. <ide> <ide> Args: <del> model: the model whose layers will be checked to find the BaseRandomLayers. <add> model: the model whose layers will be checked to find the <add> BaseRandomLayers. <ide> layout_map: used to get the default mesh information to create DVariable. <ide> """ <ide> # pylint: disable=protected-access <ide> def _init_state_variable_for_rng(model, layout_map): <ide> keras_generator = l._random_generator <ide> if keras_generator._built and keras_generator._generator is None: <ide> raise ValueError( <del> "Keras is expected to use tf.random.Generator when using DTensor API." <del> "Please call " <del> "`tf.keras.backend.experimental.enable_tf_random_generator` at the " <del> "beginning of your program." <add> "Keras is expected to use tf.random.Generator when using " <add> "DTensor API. Please call " <add> "`tf.keras.backend.experimental.enable_tf_random_generator` at " <add> "the beginning of your program." <ide> ) <ide> if hasattr(keras_generator, "_generator") and _is_lazy_init_variable( <ide> keras_generator._generator._state_var <ide> def _init_state_variable_for_rng(model, layout_map): <ide> layout_map, "", keras_generator._generator._state_var <ide> ) <ide> else: <del> # When the keras_generator is not built yet. Call the init function with <del> # DTensor device to init all the variable with default replicated layout. <add> # When the keras_generator is not built yet. Call the init function <add> # with DTensor device to init all the variable with default <add> # replicated layout. <ide> with dtensor.run_on(layout_map.get_default_mesh()): <ide> keras_generator._maybe_init() <ide> <ide> def _config_dvariable_regularization( <ide> ): <ide> """Update the weights regularizer for newly created `DVariable`. <ide> <del> The weight regularization usually happens when `layer.add_weight()` is called, <del> at which point the library will first create a `LazyInitVariable`, and then <del> replace it with a `DVariable`. We will defer the creation of those losses, <del> until the DVariable is created. <add> The weight regularization usually happens when `layer.add_weight()` is <add> called, at which point the library will first create a `LazyInitVariable`, <add> and then replace it with a `DVariable`. We will defer the creation of those <add> losses, until the DVariable is created. <ide> <ide> See `layer._captured_weight_regularizer` for more details. <ide> <ide> Args: <ide> layer: the layer instance for DVariable regularization config. <del> lazy_init_variable_to_tf_variable_map: the dict between LazyInitVariable ID <del> and newly created DVariable. <add> lazy_init_variable_to_tf_variable_map: the dict between LazyInitVariable <add> ID and newly created DVariable. <ide> """ <ide> # pylint: disable=protected-access <ide> for (name, variable, regualarizer) in layer._captured_weight_regularizer: <ide> def _create_dvariable(layout_map, object_path, variable): <ide> find any variables. <ide> <ide> Args: <del> layout_map: a LayoutMap which contains the variable_object_path (string) -> <del> Layout. <add> layout_map: a LayoutMap which contains the variable_object_path (string) <add> -> Layout. <ide> object_path: string, the object attribute path for the variable. <ide> variable: LazyInitVariable which will be replaced by the newly created <ide> tf.Variable. <ide> def _create_dvariable(layout_map, object_path, variable): <ide> with lazy_variable.disable_init_variable_creator(): <ide> init_val = utils.call_with_layout(init_val, layout) <ide> else: <del> # The init value is probably already created as a tensor, we will just copy <del> # it to mesh and give it a proper layout. <add> # The init value is probably already created as a tensor, we will just <add> # copy it to mesh and give it a proper layout. <ide> init_val = dtensor.copy_to_mesh(init_val, layout) <ide> # Use the original variable name for new DVariable creation. TF was adding <ide> # ":0" suffix to it. <ide> def _set_object_by_path(object_to_set, path, value): <ide> if i == len(path) - 1: <ide> # We found the actual attribute to set <ide> if isinstance(attr_name, int): <del> # This means we are trying to set an element in the array, make sure the <del> # instance is array like object. <add> # This means we are trying to set an element in the array, make <add> # sure the instance is array like object. <ide> object_to_set[attr_name] = value <ide> else: <ide> setattr(object_to_set, attr_name, value) <ide><path>keras/dtensor/layout_map_test.py <ide> def test_get(self): <ide> self.assertEqual(layout_map["dense/kernel"], self.sharded_2d) <ide> self.assertEqual(layout_map["dense/bias"], self.sharded_1d) <ide> <del> # Map against the wildcard bias rule for dense, and based on the order of <del> # insertion, it will not use .*bias. <add> # Map against the wildcard bias rule for dense, and based on the order <add> # of insertion, it will not use .*bias. <ide> self.assertEqual(layout_map["dense_2/kernel"], self.layout_2d) <ide> self.assertEqual(layout_map["dense_2/bias"], self.layout_1d) <ide> <ide> def test_init_subclass_model_variable_with_layout(self): <ide> with layout_map_lib.layout_map_scope(layout_map): <ide> model = SubclassModel(name="model") <ide> <del> # Init the model with eager tensor, make sure the model weights have correct <del> # layout, as well as produce correct result. <add> # Init the model with eager tensor, make sure the model weights have <add> # correct layout, as well as produce correct result. <ide> inputs = tf.zeros((10, 10)) <ide> inputs = dtensor.copy_to_mesh(inputs, layout=self.layout_2d) <ide> result = model(inputs) <ide> def test_init_subclass_model_variable_with_layout(self): <ide> <ide> def test_init_functional_model_variable_with_layout(self): <ide> # Note that the functional model is using layers name + attribute name <del> # the layer name are unique among the functional model, and when the layer <del> # doesn't have a name, keras will give it a unique name based on the layer <del> # class. <add> # the layer name are unique among the functional model, and when the <add> # layer doesn't have a name, keras will give it a unique name based on <add> # the layer class. <ide> layout_map = layout_map_lib.LayoutMap(mesh=self.mesh) <ide> layout_map["d1.kernel"] = self.layout_2d <ide> layout_map["d1.bias"] = self.layout_1d <ide> def test_init_functional_model_variable_with_layout(self): <ide> <ide> def test_init_sequential_model_variable_with_layout(self): <ide> # Note that the sequential model is using layers name + attribute name <del> # the layer name are unique among the functional model, and when the layer <del> # doesn't have a name, keras will give it a unique name based on the layer <del> # class. <add> # the layer name are unique among the functional model, and when the <add> # layer doesn't have a name, keras will give it a unique name based on <add> # the layer class. <ide> layout_map = layout_map_lib.LayoutMap(mesh=self.mesh) <ide> layout_map["d1.kernel"] = self.layout_2d <ide> layout_map["d1.bias"] = self.layout_1d <ide><path>keras/dtensor/lazy_variable.py <ide> def _infer_shape_dtype_and_create_handle(initial_value, shape, dtype, name): <ide> initial_value, trackable.CheckpointInitialValue <ide> ): <ide> raise NotImplementedError( <del> "CheckpointInitialValue is not supported to be the initial " <del> "value of a lazy variable." <add> "CheckpointInitialValue is not supported to be the " <add> "initial value of a lazy variable." <ide> ) <ide> initial_value = ops.convert_to_tensor( <ide> initial_value, name="initial_value", dtype=dtype <ide> def _infer_shape_dtype_and_create_handle(initial_value, shape, dtype, name): <ide> <ide> assert dtype <ide> assert shape <del> handle = resource_variable_ops._variable_handle_from_shape_and_dtype( # pylint: disable=protected-access <del> shape=shape, <del> dtype=dtype, <del> shared_name=None, # Never shared <del> name=name, <del> graph_mode=False, <del> initial_value=None, <add> handle = ( <add> resource_variable_ops._variable_handle_from_shape_and_dtype( <add> shape=shape, <add> dtype=dtype, <add> shared_name=None, # Never shared <add> name=name, <add> graph_mode=False, <add> initial_value=None, <add> ) <ide> ) <del> # initial_value=initial_value if not callable(initial_value) else None) <add> # initial_value=initial_value if not callable(initial_value) else <add> # None) <ide> return initial_value, shape, dtype, handle, handle_name, unique_id <ide> <ide> <ide> def initialize(self): <ide> <ide> if not initial_value.shape.is_compatible_with(self._shape): <ide> raise ValueError( <del> f"In this `tf.Variable` creation, the initial value's shape " <del> f"({initial_value.shape}) is not compatible with " <del> f"the explicitly supplied `shape` argument ({self._shape})." <add> f"In this `tf.Variable` creation, the initial value's " <add> f"shape ({initial_value.shape}) is not compatible with " <add> f"the explicitly supplied `shape` " <add> f"argument ({self._shape})." <ide> ) <ide> assert self._dtype is initial_value.dtype.base_dtype <ide> gen_resource_variable_ops.assign_variable_op( <ide><path>keras/dtensor/mnist_model_test.py <ide> def test_mnist_training_cpu(self): <ide> self.assertEqual(train_losses, sorted(train_losses, reverse=True)) <ide> <ide> def DISABLED_test_mnist_training_tpu(self): <del> # TODO(scottzhu): Enable TPU test once the dtensor_test rule is migrated out <del> # of learning/brain <add> # TODO(scottzhu): Enable TPU test once the dtensor_test rule is migrated <add> # out of learning/brain <ide> tpu_util.dtensor_initialize_tpu_system() <ide> total_tpu_device_count = dtensor.num_global_devices("TPU") <ide> mesh_shape = [total_tpu_device_count] <ide><path>keras/dtensor/optimizers.py <ide> def __init__(self, name, mesh=None): <ide> state variables created by this optimizer. <ide> mesh: dtensor.Mesh. The optional Mesh which will be used to create <ide> the states. Note that usually the state variable will use the layout <del> from the corresponding model variables. This mesh only used for global <del> variables like globle steps, learning rate, etc. <add> from the corresponding model variables. This mesh only used for <add> global variables like globle steps, learning rate, etc. <ide> """ <del> # TODO(scottzhu): Skip the gradients_clip_option and ema_option for now, and <del> # will cover them in future if really needed. <add> # TODO(scottzhu): Skip the gradients_clip_option and ema_option for now, <add> # and will cover them in future if really needed. <ide> # TODO(scottzhu): We might want to make mesh to be required in future. <ide> self._mesh = mesh <ide> super().__init__(name=name) <ide> def _create_iteration_variable(self): <ide> init_val, dtensor.Layout.replicated(self._mesh, rank=0) <ide> ) <ide> with tf.init_scope(): <del> # Lift the variable creation to init scope to avoid environment issue. <add> # Lift the variable creation to init scope to avoid environment <add> # issue. <ide> self._iterations = dtensor.DVariable(init_val, name="iteration") <ide> <ide> ################## Override methods from keras.Optimizer ################ <ide> def add_variable_from_reference( <ide> corresponding momemtum variable is created of the same shape and dtype. <ide> <ide> Args: <del> model_variable: The corresponding model variable to the optimizer variable <del> to be created. <del> variable_name: The name prefix of the optimizer variable to be created. <del> The create variables name will follow the pattern <add> model_variable: The corresponding model variable to the optimizer <add> variable to be created. <add> variable_name: The name prefix of the optimizer variable to be <add> created. The create variables name will follow the pattern <ide> `{variable_name}/{model_variable.name}`, e.g., `momemtum/dense_1`. <del> initial_value: The initial value of the optimizer variable, if None, the <del> value will be default to 0. <add> initial_value: The initial value of the optimizer variable, if None, <add> the value will be default to 0. <ide> <ide> Returns: <ide> An optimizer variable. <ide> """ <ide> if initial_value is None: <del> # Use tf.zeros_like which will propagate the layout information from the <del> # model weights if any. <add> # Use tf.zeros_like which will propagate the layout information from <add> # the model weights if any. <ide> initial_value = tf.zeros_like(model_variable) <ide> elif isinstance(initial_value, tf.Tensor): <ide> initial_value = dtensor.copy_to_mesh( <ide> def _build_learning_rate(self, learning_rate): <ide> learning_rate, learning_rate_schedule.LearningRateSchedule <ide> ): <ide> # Create a variable to hold the current learning rate. <del> # Note that the init value `learning_rate(self.iterations)` should have <del> # the correct layout information from self.iterations. <add> # Note that the init value `learning_rate(self.iterations)` should <add> # have the correct layout information from self.iterations. <ide> self._current_learning_rate = dtensor.DVariable( <ide> learning_rate(self.iterations), <ide> name="learning_rate", <ide><path>keras/dtensor/test_util.py <ide> def configTestMesh(device_type_mesh_map): # pylint: disable=invalid-name <ide> """Configs corresponding mesh given test context. <ide> <ide> If runs on a CPU mesh, set virtual device on CPU. <del> If runs on a GPU mesh, sets virtual device on GPU with proper memory limits. <add> If runs on a GPU mesh, sets virtual device on GPU with proper memory <add> limits. <ide> if runs on a TPU mesh, initializes TPU system. <ide> <ide> Args: <del> device_type_mesh_map: A dictionary containing device_type -> mesh mapping. <add> device_type_mesh_map: A dictionary containing device_type -> mesh <add> mapping. <ide> <ide> Returns: <ide> A properly configured mesh for use in test. <ide><path>keras/dtensor/utils.py <ide> def __init__(self, units, <ide> <ide> By adding this annotation, it will: <ide> <del> 1. Filter out the kwargs based on some keywords, eg if the 'kernel_initialzer' <del> appears in method signature, then it will try to pop the 'kernel_layout' if <del> it presents. Same for "bias" and "recurrent_kernel", etc. This will make <del> sure the layout related param is not passed to `BaseLayer.__init__`, which <del> will raise error about unexpect keyword args. <add> 1. Filter out the kwargs based on some keywords, eg if the <add> 'kernel_initialzer' appears in method signature, then it will try to pop <add> the 'kernel_layout' if it presents. Same for "bias" and <add> "recurrent_kernel", etc. This will make sure the layout related param is <add> not passed to `BaseLayer.__init__`, which will raise error about unexpect <add> keyword args. <ide> 2. Set the self.kernel/bias_layout attribute after the `__init__` method is <ide> called. Keras framework will use those fields to create weights down the <ide> stream. <ide> def inject_mesh(init_method): <ide> DTensor mesh to create the weights, but doesn't want to change the current <ide> public API interface. <ide> <del> This is for temporary usage and eventually the mesh/layout information will be <del> public arguments in the `__init__` method <add> This is for temporary usage and eventually the mesh/layout information will <add> be public arguments in the `__init__` method. <ide> <ide> Sample usage: <ide> ```python <ide> def __init__(self, name='accuracy', dtype=None): <ide> <ide> def _wrap_function(instance, *args, **kwargs): <ide> mesh = kwargs.pop("mesh", None) <del> # Note that the injection of _mesh need to happen before the invocation of <del> # __init__, since the class might need the mesh to create weights in the <del> # __init__. <add> # Note that the injection of _mesh need to happen before the invocation <add> # of __init__, since the class might need the mesh to create weights in <add> # the __init__. <ide> if mesh is not None: <ide> instance._mesh = mesh # pylint: disable=protected-access <ide> init_method(instance, *args, **kwargs)
9
Python
Python
fix mypy errors for google.cloud.example_dags
632bd0133e0920c036f1cd83d100f477726fcb41
<ide><path>airflow/providers/google/cloud/example_dags/example_bigquery_operations.py <ide> task_id="update_table", <ide> dataset_id=DATASET_NAME, <ide> table_id="test_table", <del> fields=[ <del> {"name": "emp_name", "type": "STRING", "mode": "REQUIRED"}, <del> {"name": "salary", "type": "INTEGER", "mode": "NULLABLE"}, <del> ], <add> fields=["emp_name", "salary"], <ide> table_resource={ <ide> "friendlyName": "Updated Table", <ide> "description": "Updated Table", <ide><path>airflow/providers/google/cloud/example_dags/example_cloud_build.py <ide> import os <ide> from datetime import datetime <ide> from pathlib import Path <add>from typing import Any, Dict <ide> <ide> from future.backports.urllib.parse import urlparse <ide> <ide> # [END howto_operator_gcp_create_build_from_storage_body] <ide> <ide> # [START howto_operator_create_build_from_repo_body] <del>create_build_from_repo_body = { <add>create_build_from_repo_body: Dict[str, Any] = { <ide> "source": {"repo_source": {"repo_name": GCP_SOURCE_REPOSITORY_NAME, "branch_name": "main"}}, <ide> "steps": [ <ide> { <ide><path>airflow/providers/google/cloud/example_dags/example_cloud_memorystore.py <ide> task_id="failover-instance", <ide> location="europe-north1", <ide> instance=MEMORYSTORE_REDIS_INSTANCE_NAME_2, <del> data_protection_mode=FailoverInstanceRequest.DataProtectionMode.LIMITED_DATA_LOSS, <add> data_protection_mode=FailoverInstanceRequest.DataProtectionMode( <add> FailoverInstanceRequest.DataProtectionMode.LIMITED_DATA_LOSS <add> ), <ide> project_id=GCP_PROJECT_ID, <ide> ) <ide> # [END howto_operator_failover_instance] <ide><path>airflow/providers/google/cloud/example_dags/example_functions.py <ide> <ide> import os <ide> from datetime import datetime <add>from typing import Any, Dict <ide> <ide> from airflow import models <ide> from airflow.providers.google.cloud.operators.functions import ( <ide> # [END howto_operator_gcf_deploy_body] <ide> <ide> # [START howto_operator_gcf_default_args] <del>default_args = {'retries': 3} <add>default_args: Dict[str, Any] = {'retries': 3} <ide> # [END howto_operator_gcf_default_args] <ide> <ide> # [START howto_operator_gcf_deploy_variants] <ide><path>airflow/providers/google/cloud/example_dags/example_mlengine.py <ide> """ <ide> import os <ide> from datetime import datetime <del>from typing import Dict <add>from typing import Any, Dict <ide> <ide> from airflow import models <ide> from airflow.operators.bash import BashOperator <ide> tags=['example'], <ide> params={"model_name": MODEL_NAME}, <ide> ) as dag: <del> hyperparams = { <add> hyperparams: Dict[str, Any] = { <ide> 'goal': 'MAXIMIZE', <ide> 'hyperparameterMetricTag': 'metric1', <ide> 'maxTrials': 30, <ide><path>airflow/providers/google/cloud/operators/dataproc_metastore.py <ide> """This module contains Google Dataproc Metastore operators.""" <ide> <ide> from time import sleep <del>from typing import Dict, Optional, Sequence, Tuple, Union <add>from typing import Collection, Dict, Optional, Sequence, Tuple, Union <ide> <ide> from google.api_core.retry import Retry, exponential_sleep_generator <ide> from google.cloud.metastore_v1 import MetadataExport, MetadataManagementActivity <ide> def __init__( <ide> project_id: str, <ide> region: str, <ide> service_id: str, <del> metadata_import: MetadataImport, <add> metadata_import: Union[MetadataImport, Dict[str, Collection[str]]], <ide> metadata_import_id: str, <ide> request_id: Optional[str] = None, <ide> retry: Optional[Retry] = None, <ide><path>airflow/providers/google/cloud/operators/workflows.py <ide> import re <ide> import uuid <ide> from datetime import datetime, timedelta <del>from typing import Dict, Optional, Sequence, Tuple, Union <add>from typing import Dict, List, Optional, Sequence, Tuple, Union <ide> <ide> import pytz <ide> from google.api_core.exceptions import AlreadyExists <ide> def __init__( <ide> workflow_id: str, <ide> location: str, <ide> project_id: Optional[str] = None, <del> update_mask: Optional[FieldMask] = None, <add> update_mask: Optional[Union[FieldMask, Dict[str, List[str]]]] = None, <ide> retry: Optional[Retry] = None, <ide> timeout: Optional[float] = None, <ide> metadata: Optional[Sequence[Tuple[str, str]]] = None, <ide><path>airflow/providers/google/cloud/sensors/datafusion.py <ide> # specific language governing permissions and limitations <ide> # under the License. <ide> """This module contains a Google Cloud Data Fusion sensors.""" <del>from typing import Optional, Sequence, Set, Union <add>from typing import Iterable, Optional, Sequence, Union <ide> <ide> from airflow.exceptions import AirflowException <ide> from airflow.providers.google.cloud.hooks.datafusion import DataFusionHook <ide> def __init__( <ide> self, <ide> pipeline_name: str, <ide> pipeline_id: str, <del> expected_statuses: Set[str], <add> expected_statuses: Iterable[str], <ide> instance_name: str, <ide> location: str, <del> failure_statuses: Optional[Set[str]] = None, <add> failure_statuses: Optional[Iterable[str]] = None, <ide> project_id: Optional[str] = None, <ide> namespace: str = "default", <ide> gcp_conn_id: str = 'google_cloud_default',
8
Javascript
Javascript
set dependency categories for all dependencies
2abcfc0058edf2f98410df9921452e0cb4684cc0
<ide><path>lib/ContextModule.js <ide> const makeSerializable = require("./util/makeSerializable"); <ide> * @property {RegExp=} include <ide> * @property {RegExp=} exclude <ide> * @property {RawChunkGroupOptions=} groupOptions <add> * @property {string} category <ide> * @property {string[][]=} referencedExports exports referenced from modules (won't be mangled) <ide> */ <ide> <ide> class ContextModule extends Module { <ide> exclude: options.exclude, <ide> chunkName: options.chunkName, <ide> groupOptions: options.groupOptions, <add> category: options.category, <ide> referencedExports: options.referencedExports, <ide> namespaceObject: options.namespaceObject <ide> }; <ide><path>lib/ContextModuleFactory.js <ide> module.exports = class ContextModuleFactory extends ModuleFactory { <ide> regExp, <ide> include, <ide> exclude, <del> referencedExports <add> referencedExports, <add> category <ide> } = options; <ide> if (!regExp || !resource) return callback(null, []); <ide> <ide> module.exports = class ContextModuleFactory extends ModuleFactory { <ide> const dep = new ContextElementDependency( <ide> obj.request + resourceQuery, <ide> obj.request, <add> category, <ide> referencedExports <ide> ); <ide> dep.optional = true; <ide><path>lib/ContextReplacementPlugin.js <ide> const createResolveDependenciesFromContextMap = createContextMap => { <ide> const dependencies = Object.keys(map).map(key => { <ide> return new ContextElementDependency( <ide> map[key] + options.resourceQuery, <del> key <add> key, <add> options.category, <add> options.referencedExports <ide> ); <ide> }); <ide> callback(null, dependencies); <ide><path>lib/container/ContainerExposedDependency.js <ide> class ContainerExposedDependency extends ModuleDependency { <ide> return "container exposed"; <ide> } <ide> <add> get category() { <add> return "esm"; <add> } <add> <ide> /** <ide> * @returns {string | null} an identifier to merge equal requests <ide> */ <ide><path>lib/container/FallbackItemDependency.js <ide> class FallbackItemDependency extends ModuleDependency { <ide> get type() { <ide> return "fallback item"; <ide> } <add> <add> get category() { <add> return "esm"; <add> } <ide> } <ide> <ide> makeSerializable( <ide><path>lib/container/RemoteToExternalDependency.js <ide> class RemoteToExternalDependency extends ModuleDependency { <ide> get type() { <ide> return "remote to external"; <ide> } <add> <add> get category() { <add> return "esm"; <add> } <ide> } <ide> <ide> makeSerializable( <ide><path>lib/dependencies/AMDDefineDependencyParserPlugin.js <ide> class AMDDefineDependencyParserPlugin { <ide> param, <ide> expr, <ide> this.options, <del> {}, <add> { <add> category: "amd" <add> }, <ide> parser <ide> ); <ide> if (!dep) return; <ide><path>lib/dependencies/AMDRequireDependenciesBlockParserPlugin.js <ide> class AMDRequireDependenciesBlockParserPlugin { <ide> param, <ide> expr, <ide> this.options, <del> {}, <add> { <add> category: "amd" <add> }, <ide> parser <ide> ); <ide> if (!dep) return; <ide><path>lib/dependencies/CommonJsFullRequireDependency.js <ide> class CommonJsFullRequireDependency extends ModuleDependency { <ide> get type() { <ide> return "cjs full require"; <ide> } <add> <add> get category() { <add> return "commonjs"; <add> } <ide> } <ide> <ide> CommonJsFullRequireDependency.Template = class CommonJsFullRequireDependencyTemplate extends ModuleDependency.Template { <ide><path>lib/dependencies/CommonJsImportsParserPlugin.js <ide> class CommonJsImportsParserPlugin { <ide> param, <ide> expr, <ide> options, <del> {}, <add> { <add> category: "commonjs" <add> }, <ide> parser <ide> ); <ide> if (!dep) return; <ide> class CommonJsImportsParserPlugin { <ide> expr, <ide> options, <ide> { <add> category: "commonjs", <ide> mode: weak ? "weak" : "sync" <ide> }, <ide> parser <ide><path>lib/dependencies/CommonJsRequireDependency.js <ide> class CommonJsRequireDependency extends ModuleDependency { <ide> get type() { <ide> return "cjs require"; <ide> } <add> <add> get category() { <add> return "commonjs"; <add> } <ide> } <ide> <ide> CommonJsRequireDependency.Template = ModuleDependencyTemplateAsId; <ide><path>lib/dependencies/CommonJsSelfReferenceDependency.js <ide> class CommonJsSelfReferenceDependency extends NullDependency { <ide> return "cjs self exports reference"; <ide> } <ide> <add> get category() { <add> return "self"; <add> } <add> <ide> /** <ide> * @returns {string | null} an identifier to merge equal requests <ide> */ <ide><path>lib/dependencies/ContextElementDependency.js <ide> const ModuleDependency = require("./ModuleDependency"); <ide> /** @typedef {import("../ModuleGraph")} ModuleGraph */ <ide> <ide> class ContextElementDependency extends ModuleDependency { <del> constructor(request, userRequest, referencedExports) { <add> constructor(request, userRequest, category, referencedExports) { <ide> super(request); <ide> this.referencedExports = referencedExports; <add> this._category = category; <ide> <ide> if (userRequest) { <ide> this.userRequest = userRequest; <ide> class ContextElementDependency extends ModuleDependency { <ide> return "context element"; <ide> } <ide> <add> get category() { <add> return this._category; <add> } <add> <ide> /** <ide> * Returns list of exports referenced by this dependency <ide> * @param {ModuleGraph} moduleGraph module graph <ide><path>lib/dependencies/DelegatedSourceDependency.js <ide> class DelegatedSourceDependency extends ModuleDependency { <ide> get type() { <ide> return "delegated source"; <ide> } <add> <add> get category() { <add> return "esm"; <add> } <ide> } <ide> <ide> makeSerializable( <ide><path>lib/dependencies/EntryDependency.js <ide> class EntryDependency extends ModuleDependency { <ide> get type() { <ide> return "entry"; <ide> } <add> <add> get category() { <add> return "esm"; <add> } <ide> } <ide> <ide> makeSerializable(EntryDependency, "webpack/lib/dependencies/EntryDependency"); <ide><path>lib/dependencies/ImportParserPlugin.js <ide> class ImportParserPlugin { <ide> namespaceObject: parser.state.module.buildMeta.strictHarmonyModule <ide> ? "strict" <ide> : true, <add> category: "esm", <ide> referencedExports: exports <ide> }, <ide> parser <ide><path>lib/dependencies/LoaderDependency.js <ide> class LoaderDependency extends ModuleDependency { <ide> get type() { <ide> return "loader"; <ide> } <add> <add> get category() { <add> return "loader"; <add> } <ide> } <ide> <ide> module.exports = LoaderDependency; <ide><path>lib/dependencies/ModuleDecoratorDependency.js <ide> class ModuleDecoratorDependency extends NullDependency { <ide> return "module decorator"; <ide> } <ide> <add> get category() { <add> return "self"; <add> } <add> <ide> /** <ide> * @returns {string | null} an identifier to merge equal requests <ide> */ <ide><path>lib/dependencies/ModuleDependency.js <ide> class ModuleDependency extends Dependency { <ide> return `module${this.request}`; <ide> } <ide> <del> get category() { <del> return "commonjs"; <del> } <del> <ide> serialize(context) { <ide> const { write } = context; <ide> write(this.request); <ide><path>lib/dependencies/ModuleHotAcceptDependency.js <ide> class ModuleHotAcceptDependency extends ModuleDependency { <ide> get type() { <ide> return "module.hot.accept"; <ide> } <add> <add> get category() { <add> return "commonjs"; <add> } <ide> } <ide> <ide> makeSerializable( <ide><path>lib/dependencies/ModuleHotDeclineDependency.js <ide> class ModuleHotDeclineDependency extends ModuleDependency { <ide> get type() { <ide> return "module.hot.decline"; <ide> } <add> <add> get category() { <add> return "commonjs"; <add> } <ide> } <ide> <ide> makeSerializable( <ide><path>lib/dependencies/PrefetchDependency.js <ide> class PrefetchDependency extends ModuleDependency { <ide> get type() { <ide> return "prefetch"; <ide> } <add> <add> get category() { <add> return "esm"; <add> } <ide> } <ide> <ide> module.exports = PrefetchDependency; <ide><path>lib/dependencies/ProvidedDependency.js <ide> class ProvidedDependency extends ModuleDependency { <ide> this.range = range; <ide> } <ide> <add> get type() { <add> return "provided"; <add> } <add> <add> get category() { <add> return "esm"; <add> } <add> <ide> /** <ide> * Update the hash <ide> * @param {Hash} hash hash to be updated <ide><path>lib/dependencies/RequireEnsureItemDependency.js <ide> class RequireEnsureItemDependency extends ModuleDependency { <ide> get type() { <ide> return "require.ensure item"; <ide> } <add> <add> get category() { <add> return "commonjs"; <add> } <ide> } <ide> <ide> makeSerializable( <ide><path>lib/dependencies/RequireIncludeDependency.js <ide> class RequireIncludeDependency extends ModuleDependency { <ide> get type() { <ide> return "require.include"; <ide> } <add> <add> get category() { <add> return "commonjs"; <add> } <ide> } <ide> <ide> makeSerializable( <ide><path>lib/dependencies/WebAssemblyImportDependency.js <ide> class WebAssemblyImportDependency extends ModuleDependency { <ide> this.onlyDirectImport = onlyDirectImport; <ide> } <ide> <add> get type() { <add> return "wasm import"; <add> } <add> <add> get category() { <add> return "wasm"; <add> } <add> <ide> /** <ide> * Returns list of exports referenced by this dependency <ide> * @param {ModuleGraph} moduleGraph module graph <ide> class WebAssemblyImportDependency extends ModuleDependency { <ide> } <ide> } <ide> <del> get type() { <del> return "wasm import"; <del> } <del> <del> get category() { <del> return "wasm"; <del> } <del> <ide> serialize(context) { <ide> const { write } = context; <ide> <ide><path>lib/sharing/ConsumeFallbackDependency.js <ide> class ConsumeFallbackDependency extends ModuleDependency { <ide> get type() { <ide> return "consume fallback"; <ide> } <add> <add> get category() { <add> return "esm"; <add> } <ide> } <ide> <ide> makeSerializable( <ide><path>lib/sharing/ProvidedDependency.js <ide> class ProvidedDependency extends ModuleDependency { <ide> } <ide> <ide> get type() { <del> return "provided"; <add> return "provide shared"; <add> } <add> <add> get category() { <add> return "esm"; <ide> } <ide> } <ide>
28
Go
Go
remove hijack from api when not necessary
f29e5dc8a15d0ab8e9c6084e41ee373376051659
<ide><path>api.go <ide> func postImagesCreate(srv *Server, w http.ResponseWriter, r *http.Request, vars <ide> <ide> src := r.Form.Get("fromSrc") <ide> image := r.Form.Get("fromImage") <del> repo := r.Form.Get("repo") <ide> tag := r.Form.Get("tag") <add> repo := r.Form.Get("repo") <ide> <del> in, out, err := hijackServer(w) <del> if err != nil { <del> return err <del> } <del> defer in.Close() <del> fmt.Fprintf(out, "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n") <ide> if image != "" { //pull <ide> registry := r.Form.Get("registry") <del> if err := srv.ImagePull(image, tag, registry, out); err != nil { <del> fmt.Fprintf(out, "Error: %s\n", err) <add> if err := srv.ImagePull(image, tag, registry, w); err != nil { <add> return err <ide> } <ide> } else { //import <del> if err := srv.ImageImport(src, repo, tag, in, out); err != nil { <del> fmt.Fprintf(out, "Error: %s\n", err) <add> if err := srv.ImageImport(src, repo, tag, r.Body, w); err != nil { <add> return err <ide> } <ide> } <ide> return nil <ide> func postImagesInsert(srv *Server, w http.ResponseWriter, r *http.Request, vars <ide> } <ide> name := vars["name"] <ide> <del> in, out, err := hijackServer(w) <del> if err != nil { <add> if err := srv.ImageInsert(name, url, path, w); err != nil { <ide> return err <ide> } <del> defer in.Close() <del> fmt.Fprintf(out, "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n") <del> if err := srv.ImageInsert(name, url, path, out); err != nil { <del> fmt.Fprintf(out, "Error: %s\n", err) <del> } <ide> return nil <ide> } <ide> <ide> func postImagesPush(srv *Server, w http.ResponseWriter, r *http.Request, vars ma <ide> } <ide> name := vars["name"] <ide> <del> in, out, err := hijackServer(w) <del> if err != nil { <add> if err := srv.ImagePush(name, registry, w); err != nil { <ide> return err <ide> } <del> defer in.Close() <del> fmt.Fprintf(out, "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n") <del> if err := srv.ImagePush(name, registry, out); err != nil { <del> fmt.Fprintf(out, "Error: %s\n", err) <del> } <ide> return nil <ide> } <ide> <ide> func postBuild(srv *Server, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <del> in, out, err := hijackServer(w) <del> if err != nil { <add> if err := srv.ImageCreateFromFile(r.Body, w); err != nil { <ide> return err <ide> } <del> defer in.Close() <del> fmt.Fprintf(out, "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n") <del> if err := srv.ImageCreateFromFile(in, out); err != nil { <del> fmt.Fprintf(out, "Error: %s\n", err) <del> } <ide> return nil <ide> } <ide> <ide><path>commands.go <ide> func (cli *DockerCli) CmdInsert(args ...string) error { <ide> v.Set("url", cmd.Arg(1)) <ide> v.Set("path", cmd.Arg(2)) <ide> <del> err := cli.hijack("POST", "/images/"+cmd.Arg(0)+"?"+v.Encode(), false) <add> err := cli.stream("POST", "/images/"+cmd.Arg(0)+"?"+v.Encode(), nil, os.Stdout) <ide> if err != nil { <ide> return err <ide> } <ide> func (cli *DockerCli) CmdBuild(args ...string) error { <ide> return nil <ide> } <ide> <del> err := cli.hijack("POST", "/build", false) <add> err := cli.stream("POST", "/build", nil, os.Stdout) <ide> if err != nil { <ide> return err <ide> } <ide> func (cli *DockerCli) CmdImport(args ...string) error { <ide> v.Set("tag", tag) <ide> v.Set("fromSrc", src) <ide> <del> err := cli.hijack("POST", "/images/create?"+v.Encode(), false) <add> err := cli.stream("POST", "/images/create?"+v.Encode(), os.Stdin, os.Stdout) <ide> if err != nil { <ide> return err <ide> } <ide> func (cli *DockerCli) CmdPush(args ...string) error { <ide> <ide> v := url.Values{} <ide> v.Set("registry", *registry) <del> if err := cli.hijack("POST", "/images/"+name+"/push?"+v.Encode(), false); err != nil { <add> if err := cli.stream("POST", "/images/"+name+"/push?"+v.Encode(), nil, os.Stdout); err != nil { <ide> return err <ide> } <ide> return nil <ide> func (cli *DockerCli) CmdPull(args ...string) error { <ide> v.Set("tag", *tag) <ide> v.Set("registry", *registry) <ide> <del> if err := cli.hijack("POST", "/images/create?"+v.Encode(), false); err != nil { <add> if err := cli.stream("POST", "/images/create?"+v.Encode(), nil, os.Stdout); err != nil { <ide> return err <ide> } <ide> <ide> func (cli *DockerCli) CmdExport(args ...string) error { <ide> return nil <ide> } <ide> <del> if err := cli.stream("GET", "/containers/"+cmd.Arg(0)+"/export"); err != nil { <add> if err := cli.stream("GET", "/containers/"+cmd.Arg(0)+"/export", nil, os.Stdout); err != nil { <ide> return err <ide> } <ide> return nil <ide> func (cli *DockerCli) CmdRun(args ...string) error { <ide> if statusCode == 404 { <ide> v := url.Values{} <ide> v.Set("fromImage", config.Image) <del> err = cli.hijack("POST", "/images/create?"+v.Encode(), false) <add> err = cli.stream("POST", "/images/create?"+v.Encode(), nil, os.Stderr) <ide> if err != nil { <ide> return err <ide> } <ide> func (cli *DockerCli) call(method, path string, data interface{}) ([]byte, int, <ide> return body, resp.StatusCode, nil <ide> } <ide> <del>func (cli *DockerCli) stream(method, path string) error { <del> req, err := http.NewRequest(method, fmt.Sprintf("http://%s:%d%s", cli.host, cli.port, path), nil) <add>func (cli *DockerCli) stream(method, path string, in io.Reader, out io.Writer) error { <add> if (method == "POST" || method == "PUT") && in == nil { <add> in = bytes.NewReader([]byte{}) <add> } <add> req, err := http.NewRequest(method, fmt.Sprintf("http://%s:%d%s", cli.host, cli.port, path), in) <ide> if err != nil { <ide> return err <ide> } <ide> func (cli *DockerCli) stream(method, path string) error { <ide> return fmt.Errorf("error: %s", body) <ide> } <ide> <del> if _, err := io.Copy(os.Stdout, resp.Body); err != nil { <add> if _, err := io.Copy(out, resp.Body); err != nil { <ide> return err <ide> } <ide> return nil <ide><path>registry/registry.go <ide> func (r *Registry) GetRemoteTags(registries []string, repository string, token [ <ide> } <ide> <ide> func (r *Registry) GetRepositoryData(remote string) (*RepositoryData, error) { <del> utils.Debugf("Pulling repository %s from %s\r\n", remote, auth.IndexServerAddress()) <ide> repositoryTarget := auth.IndexServerAddress() + "/repositories/" + remote + "/images" <ide> <ide> req, err := http.NewRequest("GET", repositoryTarget, nil) <ide><path>server.go <ide> package docker <ide> <ide> import ( <ide> "fmt" <add> "github.com/dotcloud/docker/auth" <ide> "github.com/dotcloud/docker/registry" <ide> "github.com/dotcloud/docker/utils" <ide> "io" <ide> func (srv *Server) pullImage(out io.Writer, imgId, registry string, token []stri <ide> return nil <ide> } <ide> <del>func (srv *Server) pullRepository(stdout io.Writer, remote, askedTag string) error { <del> utils.Debugf("Retrieving repository data") <add>func (srv *Server) pullRepository(out io.Writer, remote, askedTag string) error { <add> fmt.Fprintf(out, "Pulling repository %s from %s\r\n", remote, auth.IndexServerAddress()) <ide> repoData, err := srv.registry.GetRepositoryData(remote) <ide> if err != nil { <ide> return err <ide> func (srv *Server) pullRepository(stdout io.Writer, remote, askedTag string) err <ide> if askedTag != "" && askedTag != img.Tag { <ide> continue <ide> } <del> fmt.Fprintf(stdout, "Pulling image %s (%s) from %s\n", img.Id, img.Tag, remote) <add> fmt.Fprintf(out, "Pulling image %s (%s) from %s\n", img.Id, img.Tag, remote) <ide> success := false <ide> for _, ep := range repoData.Endpoints { <del> if err := srv.pullImage(stdout, img.Id, "https://"+ep+"/v1", repoData.Tokens); err != nil { <del> fmt.Fprintf(stdout, "Error while retrieving image for tag: %s (%s); checking next endpoint\n", askedTag, err) <add> if err := srv.pullImage(out, img.Id, "https://"+ep+"/v1", repoData.Tokens); err != nil { <add> fmt.Fprintf(out, "Error while retrieving image for tag: %s (%s); checking next endpoint\n", askedTag, err) <ide> continue <ide> } <ide> if err := srv.runtime.repositories.Set(remote, img.Tag, img.Id, true); err != nil {
4
PHP
PHP
add sync without detaching method
33aee31523b9fc280aced35a5eb5f6b627263b45
<ide><path>src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php <ide> public function createMany(array $records, array $joinings = []) <ide> return $instances; <ide> } <ide> <add> /** <add> * Sync the intermediate tables with a list of IDs without detaching. <add> * <add> * @param \Illuminate\Database\Eloquent\Collection|array $ids <add> * @return array <add> */ <add> public function syncWithoutDetaching($ids) <add> { <add> return $this->sync($ids, false); <add> } <add> <ide> /** <ide> * Sync the intermediate tables with a list of IDs or collection of models. <ide> *
1
Ruby
Ruby
simplify postgres query for column_definitions()
f9c6cbd55c56de7994b74630acd141c324411719
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb <ide> def column_definitions(table_name) <ide> query(<<-end_sql, "SCHEMA") <ide> SELECT a.attname, format_type(a.atttypid, a.atttypmod), <ide> pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid, a.atttypmod, <del> (SELECT c.collname FROM pg_collation c, pg_type t <del> WHERE c.oid = a.attcollation AND t.oid = a.atttypid AND a.attcollation <> t.typcollation), <del> col_description(a.attrelid, a.attnum) AS comment <del> FROM pg_attribute a LEFT JOIN pg_attrdef d <del> ON a.attrelid = d.adrelid AND a.attnum = d.adnum <add> c.collname, col_description(a.attrelid, a.attnum) AS comment <add> FROM pg_attribute a <add> LEFT JOIN pg_attrdef d ON a.attrelid = d.adrelid AND a.attnum = d.adnum <add> LEFT JOIN pg_type t ON a.atttypid = t.oid <add> LEFT JOIN pg_collation c ON a.attcollation = c.oid AND a.attcollation <> t.typcollation <ide> WHERE a.attrelid = #{quote(quote_table_name(table_name))}::regclass <ide> AND a.attnum > 0 AND NOT a.attisdropped <ide> ORDER BY a.attnum
1
Text
Text
improve article on https
02a793c6a133f46129d0fc83ce218d3a92f1e644
<ide><path>docs/sources/articles/https.md <ide> First generate CA private and public keys: <ide> Verifying - Enter pass phrase for ca-key.pem: <ide> $ openssl req -new -x509 -days 365 -key ca-key.pem -sha256 -out ca.pem <ide> Enter pass phrase for ca-key.pem: <del> You are about to be asked to enter information that will be incorporated <del> into your certificate request. <del> What you are about to enter is what is called a Distinguished Name or a DN. <del> There are quite a few fields but you can leave some blank <del> For some fields there will be a default value, <del> If you enter '.', the field will be left blank. <del> ----- <del> Country Name (2 letter code) [AU]: <del> State or Province Name (full name) [Some-State]:Queensland <del> Locality Name (eg, city) []:Brisbane <del> Organization Name (eg, company) [Internet Widgits Pty Ltd]:Docker Inc <del> Organizational Unit Name (eg, section) []:Boot2Docker <del> Common Name (e.g. server FQDN or YOUR name) []:$HOST <del> Email Address []:Sven@home.org.au <add> You are about to be asked to enter information that will be incorporated <add> into your certificate request. <add> What you are about to enter is what is called a Distinguished Name or a DN. <add> There are quite a few fields but you can leave some blank <add> For some fields there will be a default value, <add> If you enter '.', the field will be left blank. <add> ----- <add> Country Name (2 letter code) [AU]: <add> State or Province Name (full name) [Some-State]:Queensland <add> Locality Name (eg, city) []:Brisbane <add> Organization Name (eg, company) [Internet Widgits Pty Ltd]:Docker Inc <add> Organizational Unit Name (eg, section) []:Boot2Docker <add> Common Name (e.g. server FQDN or YOUR name) []:$HOST <add> Email Address []:Sven@home.org.au <ide> <ide> Now that we have a CA, you can create a server key and certificate <ide> signing request (CSR). Make sure that "Common Name" (i.e., server FQDN or YOUR <ide> name) matches the hostname you will use to connect to Docker: <ide> e is 65537 (0x10001) <ide> $ openssl req -subj "/CN=$HOST" -new -key server-key.pem -out server.csr <ide> <del>Next, we're going to sign the key with our CA: <add>Next, we're going to sign the public key with our CA: <ide> <ide> $ openssl x509 -req -days 365 -in server.csr -CA ca.pem -CAkey ca-key.pem \ <ide> -CAcreateserial -out server-cert.pem <ide> config file: <ide> <ide> $ echo extendedKeyUsage = clientAuth > extfile.cnf <ide> <del>Now sign the key: <add>Now sign the public key: <ide> <ide> $ openssl x509 -req -days 365 -in client.csr -CA ca.pem -CAkey ca-key.pem \ <ide> -CAcreateserial -out cert.pem -extfile extfile.cnf <ide> Now sign the key: <ide> Getting CA Private Key <ide> Enter pass phrase for ca-key.pem: <ide> <add>After generating `cert.pem` and `server-cert.pem` you can safely remove the <add>two certificate signing requests: <add> <add> $ rm -v client.csr server.csr <add> <add>With a default `umask` of 022 your secret keys will be *world-readable* and <add>writable for you and your group. <add> <add>To remove write permissions for your keys in order to protect them from accidental <add>damage and make them only readable to you issue the following file mode changes: <add> <add> $ chmod -v 0400 ca-key.pem key.pem server-key.pem <add> <add>Certificates can be world-readable, but you might want to remove write access to <add>prevent accidental damage: <add> <add> $ chmod -v 0444 ca.pem server-cert.pem cert.pem <add> <ide> Now you can make the Docker daemon only accept connections from clients <ide> providing a certificate trusted by our CA: <ide> <ide> need to provide your client keys, certificates and trusted CA: <ide> ## Secure by default <ide> <ide> If you want to secure your Docker client connections by default, you can move <del>the files to the `.docker` directory in your home directory - and set the <add>the files to the `.docker` directory in your home directory -- and set the <ide> `DOCKER_HOST` and `DOCKER_TLS_VERIFY` variables as well (instead of passing <ide> `-H=tcp://:2376` and `--tlsverify` on every call). <ide> <del> $ mkdir -p ~/.docker <del> $ cp ca.pem ~/.docker/ca.pem <del> $ cp cert.pem ~/.docker/cert.pem <del> $ cp key.pem ~/.docker/key.pem <del> $ export DOCKER_HOST=tcp://:2376 <del> $ export DOCKER_TLS_VERIFY=1 <add> $ mkdir -pv ~/.docker <add> $ cp -v {ca,cert,key}.pem ~/.docker <add> $ export DOCKER_HOST=tcp://:2376 DOCKER_TLS_VERIFY=1 <ide> <ide> Docker will now connect securely by default: <ide> <ide> Docker in various other modes by mixing the flags. <ide> certificate and authenticate server based on given CA <ide> <ide> If found, the client will send its client certificate, so you just need <del>to drop your keys into `~/.docker/<ca, cert or key>.pem`. Alternatively, <add>to drop your keys into `~/.docker/{ca,cert,key}.pem`. Alternatively, <ide> if you want to store your keys in another location, you can specify that <ide> location using the environment variable `DOCKER_CERT_PATH`. <ide> <del> $ export DOCKER_CERT_PATH=${HOME}/.docker/zone1/ <add> $ export DOCKER_CERT_PATH=~/.docker/zone1/ <ide> $ docker --tlsverify ps <ide> <ide> ### Connecting to the Secure Docker port using `curl`
1
Python
Python
add nn.module as superclass
adab7f8332f2027a2f5ec62e8e8bee25fb59765f
<ide><path>src/transformers/modeling_mmbt.py <ide> def forward(self, input_modal, start_token=None, end_token=None, position_ids=No <ide> MMBT_START_DOCSTRING, <ide> MMBT_INPUTS_DOCSTRING, <ide> ) <del>class MMBTModel(ModuleUtilsMixin): <add>class MMBTModel(nn.Module, ModuleUtilsMixin): <ide> r""" <ide> Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs: <ide> **last_hidden_state**: ``torch.FloatTensor`` of shape ``(batch_size, sequence_length, hidden_size)``
1
Javascript
Javascript
fix a bug in gltfexporter
c191afb0e1ff7fb8666fb61777d62569744a1a21
<ide><path>examples/js/exporters/GLTFExporter.js <ide> THREE.GLTFExporter.prototype = { <ide> <ide> var key = getUID( geometry.index ); <ide> <del> if ( groups[ i ].start !== undefined || groups[ i ] !== undefined ) { <add> if ( groups[ i ].start !== undefined || groups[ i ].count !== undefined ) { <ide> <ide> key += ':' + groups[ i ].start + ':' + groups[ i ].count; <ide>
1
Ruby
Ruby
form helper test
5c4469f3a820f0e4475d4a6496539e3c96f82258
<ide><path>actionpack/lib/action_view/helpers/active_record_helper.rb <ide> def error_messages_for(*params) <ide> options[:object_name] ||= params.first <ide> options[:header_message] = "#{pluralize(count, 'error')} prohibited this #{options[:object_name].to_s.gsub('_', ' ')} from being saved" unless options.include?(:header_message) <ide> options[:message] ||= 'There were problems with the following fields:' unless options.include?(:message) <del> error_messages = objects.map {|object| object.errors.full_messages.map {|msg| content_tag(:li, msg) } } <add> error_messages = objects.sum {|object| object.errors.full_messages.map {|msg| content_tag(:li, msg) } }.join <ide> <ide> contents = '' <ide> contents << content_tag(options[:header_tag] || :h2, options[:header_message]) unless options[:header_message].blank?
1
Javascript
Javascript
improve assertion in test-performance
42a4a606457e01df51943c9c1e68ceaf9cafa0fe
<ide><path>test/sequential/test-performance.js <ide> function checkNodeTiming(props) { <ide> const delta = performance.nodeTiming[prop] - props[prop].around; <ide> assert(Math.abs(delta) < 1000); <ide> } else { <del> assert.strictEqual(performance.nodeTiming[prop], props[prop]); <add> assert.strictEqual(performance.nodeTiming[prop], props[prop], <add> `mismatch for performance property ${prop}: ` + <add> `${performance.nodeTiming[prop]} vs ${props[prop]}`); <ide> } <ide> } <ide> }
1
Text
Text
add @pzinovkin for #995 thanks!
c23412b51c5d8abbe1c103d7e177606644f9f0b7
<ide><path>docs/topics/credits.md <ide> The following people have helped make REST framework great. <ide> * Rudolf Olah - [omouse] <ide> * Gertjan Oude Lohuis - [gertjanol] <ide> * Matthias Jacob - [cyroxx] <add>* Pavel Zinovkin - [pzinovkin] <ide> <ide> Many thanks to everyone who's contributed to the project. <ide> <ide> You can also contact [@_tomchristie][twitter] directly on twitter. <ide> [omouse]: https://github.com/omouse <ide> [gertjanol]: https://github.com/gertjanol <ide> [cyroxx]: https://github.com/cyroxx <add>[pzinovkin]: https://github.com/pzinovkin
1
Text
Text
add initial doc on how to update cjs-module-lexer
cc82f6f8a68e8dd618ed58c7a2432544587d9872
<ide><path>doc/contributing/maintaining-cjs-module-lexer.md <add># Maintaining cjs-module-lexer <add> <add>The [cjs-module-lexer](https://github.com/nodejs/node/tree/HEAD/deps/cjs-module-lexer) <add>dependency is used within the Node.js ESM implementation to detect the <add>named exports of a CommonJS module. <add> <add>It is used within <add>[`node:internal/modules/esm/translators`](https://github.com/nodejs/node/blob/HEAD/lib/internal/modules/esm/translators.js) <add>in which both `internal/deps/cjs-module-lexer/lexer` and <add>`internal/deps/cjs-module-lexer/dist/lexer` are required and used. <add> <add>`internal/deps/cjs-module-lexer/lexer` <add>is a regular JavaScript implementation that is <add>used when WebAssembly is not available on a platform. <add>`internal/deps/cjs-module-lexer/dist/lexer` is a faster <add>implementation using WebAssembly which is generated from a <add>C based implementation. These two paths <add>resolve to the files in `deps/cjs-module-lexer` due to their <add>inclusion in the `deps_files` entry in <add>[node.gyp](https://github.com/nodejs/node/blob/master/node.gyp). <add> <add>The two different versions of lexer.js are maintained in the <add>[nodejs/cjs-module-lexer][] project. <add> <add>In order to update the Node.js dependencies to use to a newer verion <add>of cjs-module-lexer, complete the following steps: <add> <add>* Clone [nodejs/cjs-module-lexer][] <add> and check out the version that you want Node.js to use. <add>* Follow the WASM build steps outlined in <add> [wasm-build-steps](https://github.com/nodejs/cjs-module-lexer#wasm-build-steps). <add> This will generate the WASM based dist/lexer.js file. <add>* Preserving the same directory structure, copy the following files over <add> to `deps/cjs-module-lexer` directory where you have checked out Node.js. <add> <add>```text <add>├── CHANGELOG.md <add>├── dist <add>│   ├── lexer.js <add>│   └── lexer.mjs <add>├── lexer.js <add>├── LICENSE <add>├── package.json <add>└── README.md <add>``` <add> <add>* Update the link to the cjs-module-lexer in the list at the end of <add> [doc/api/esm.md](../api/esm.md) <add> to point to the updated version. <add> <add>* Create a PR, adding the files in the deps/cjs-module-lexer that <add> were modified. <add> <add>If updates are needed to cjs-module-lexer for Node.js, first PR <add>those updates into <add>[nodejs/cjs-module-lexer][], <add>request a release and then pull in the updated version once available. <add> <add>[nodejs/cjs-module-lexer]: https://github.com/nodejs/cjs-module-lexer
1
PHP
PHP
remove additional test stubs that are not required
73210d710d789a60acfff49931783761c019d3b2
<ide><path>src/ORM/AssociationCollection.php <ide> */ <ide> namespace Cake\ORM; <ide> <del>use Cake\Collection\Collection; <ide> use Cake\ORM\Association; <ide> use Cake\ORM\AssociationsNormalizerTrait; <ide> use Cake\ORM\Entity; <ide> protected function _save($association, $entity, $nested, $options) <ide> */ <ide> public function cascadeDelete(Entity $entity, array $options) <ide> { <del> $assocs = new Collection($this->_items); <del> $assocs = $assocs->filter(function ($assoc) use ($entity, $options) { <del> if ($assoc->cascadeCallbacks()) { <del> $assoc->cascadeDelete($entity, $options); <del> return false; <add> $noCascade = []; <add> foreach ($this->_items as $assoc) { <add> if (!$assoc->cascadeCallbacks()) { <add> $noCascade[] = $assoc; <add> continue; <ide> } <del> return true; <del> })->toArray(); <del> foreach ($assocs as $assoc) { <add> $assoc->cascadeDelete($entity, $options); <add> } <add> foreach ($noCascade as $assoc) { <ide> $assoc->cascadeDelete($entity, $options); <ide> } <ide> } <ide><path>tests/Fixture/GroupsFixture.php <ide> * <ide> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests <del> * @since 1.2.0 <add> * @since 3.0.2 <ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License <ide> */ <ide> namespace Cake\Test\Fixture; <ide><path>tests/Fixture/GroupsMembersFixture.php <ide> * <ide> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests <del> * @since 1.2.0 <add> * @since 3.0.2 <ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License <ide> */ <ide> namespace Cake\Test\Fixture; <ide><path>tests/Fixture/MembersFixture.php <ide> * <ide> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests <del> * @since 1.2.0 <add> * @since 3.0.2 <ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License <ide> */ <ide> namespace Cake\Test\Fixture; <ide><path>tests/TestCase/ORM/TableTest.php <ide> public function testDeleteBelongsToMany() <ide> $this->assertNull($query->all()->first(), 'Should not find any rows.'); <ide> } <ide> <add> /** <add> * Test that cascading associations are deleted first. <add> * <add> * @return void <add> */ <ide> public function testDeleteAssociationsCascadingCallbacksOrder() <ide> { <del> $Members = TableRegistry::get('Members'); <add> $groups = TableRegistry::get('Groups'); <add> $members = TableRegistry::get('Members'); <add> $groupsMembers = TableRegistry::get('GroupsMembers'); <add> <add> $groups->belongsToMany('Members'); <add> $groups->hasMany('GroupsMembers', [ <add> 'dependent' => true, <add> 'cascadeCallbacks' => true, <add> ]); <add> $groupsMembers->belongsTo('Members'); <add> $groupsMembers->addBehavior('CounterCache', [ <add> 'Members' => ['group_count'] <add> ]); <ide> <del> $member = $Members->get(1); <add> $member = $members->get(1); <ide> $this->assertEquals(2, $member->group_count); <ide> <del> $group = $Members->Groups->get(1); <del> $Members->Groups->delete($group); <add> $group = $groups->get(1); <add> $groups->delete($group); <ide> <del> $member = $Members->get(1); <add> $member = $members->get(1); <ide> $this->assertEquals(1, $member->group_count); <ide> } <ide> <ide><path>tests/test_app/TestApp/Model/Table/GroupsMembersTable.php <del><?php <del>/** <del> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <del> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <del> * <del> * Licensed under The MIT License <del> * Redistributions of files must retain the above copyright notice <del> * <del> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <del> * @since 3.0.0 <del> * @license http://www.opensource.org/licenses/mit-license.php MIT License <del> */ <del>namespace TestApp\Model\Table; <del> <del>use Cake\ORM\Table; <del> <del>/** <del> * Article table class <del> * <del> */ <del>class GroupsMembersTable extends Table <del>{ <del> <del> public function initialize(array $config) <del> { <del> $this->belongsTo('Members'); <del> <del> $this->addBehavior('CounterCache', ['Members' => ['group_count']]); <del> } <del>} <ide><path>tests/test_app/TestApp/Model/Table/GroupsTable.php <del><?php <del>/** <del> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <del> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <del> * <del> * Licensed under The MIT License <del> * Redistributions of files must retain the above copyright notice <del> * <del> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <del> * @since 3.0.0 <del> * @license http://www.opensource.org/licenses/mit-license.php MIT License <del> */ <del>namespace TestApp\Model\Table; <del> <del>use Cake\ORM\Table; <del> <del>/** <del> * Article table class <del> * <del> */ <del>class GroupsTable extends Table <del>{ <del> <del> public function initialize(array $config) <del> { <del> $this->belongsToMany('Members'); <del> <del> $this->hasMany('GroupsMembers', [ <del> 'dependent' => true, <del> 'cascadeCallbacks' => true <del> ]); <del> } <del>} <ide><path>tests/test_app/TestApp/Model/Table/MembersTable.php <del><?php <del>/** <del> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <del> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <del> * <del> * Licensed under The MIT License <del> * Redistributions of files must retain the above copyright notice <del> * <del> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <del> * @since 3.0.0 <del> * @license http://www.opensource.org/licenses/mit-license.php MIT License <del> */ <del>namespace TestApp\Model\Table; <del> <del>use Cake\ORM\Table; <del> <del>/** <del> * Article table class <del> * <del> */ <del>class MembersTable extends Table <del>{ <del> <del> public function initialize(array $config) <del> { <del> $this->belongsToMany('Groups'); <del> } <del>}
8
Go
Go
get libnetwork to build on solaris
c7684b5ff724d2eb63f447b55d0ac7319c4828b6
<ide><path>libnetwork/default_gateway_solaris.go <add>package libnetwork <add> <add>import "github.com/docker/libnetwork/types" <add> <add>func (c *controller) createGWNetwork() (Network, error) { <add> return nil, types.NotImplementedErrorf("default gateway functionality is not implemented in solaris") <add>} <ide><path>libnetwork/drivers_solaris.go <add>package libnetwork <add> <add>func getInitializers() []initializer { <add> return []initializer{} <add>} <ide><path>libnetwork/ipams/builtin/builtin_unix.go <del>// +build linux freebsd <add>// +build linux freebsd solaris <ide> <ide> package builtin <ide> <ide><path>libnetwork/ipamutils/utils_solaris.go <add>// Package ipamutils provides utililty functions for ipam management <add>package ipamutils <add> <add>// Solaris: TODO <add> <add>import ( <add> "net" <add>) <add> <add>// ElectInterfaceAddresses looks for an interface on the OS with the specified name <add>// and returns its IPv4 and IPv6 addresses in CIDR form. If the interface does not exist, <add>// it chooses from a predifined list the first IPv4 address which does not conflict <add>// with other interfaces on the system. <add>func ElectInterfaceAddresses(name string) (*net.IPNet, []*net.IPNet, error) { <add> var ( <add> v4Net *net.IPNet <add> err error <add> ) <add> <add> v4Net, err = FindAvailableNetwork(PredefinedBroadNetworks) <add> if err != nil { <add> return nil, nil, err <add> } <add> return v4Net, nil, nil <add>} <add> <add>// FindAvailableNetwork returns a network from the passed list which does not <add>// overlap with existing interfaces in the system <add>func FindAvailableNetwork(list []*net.IPNet) (*net.IPNet, error) { <add> return list[0], nil <add>} <ide><path>libnetwork/osl/interface_solaris.go <add>package osl <add> <add>// IfaceOption is a function option type to set interface options <add>type IfaceOption func() <ide><path>libnetwork/osl/neigh_solaris.go <add>package osl <add> <add>// NeighOption is a function option type to set interface options <add>type NeighOption func() <ide><path>libnetwork/sandbox_externalkey_solaris.go <add>// +build solaris <add> <add>package libnetwork <add> <add>import ( <add> "io" <add> "net" <add> <add> "github.com/docker/libnetwork/types" <add>) <add> <add>// processSetKeyReexec is a private function that must be called only on an reexec path <add>// It expects 3 args { [0] = "libnetwork-setkey", [1] = <container-id>, [2] = <controller-id> } <add>// It also expects libcontainer.State as a json string in <stdin> <add>// Refer to https://github.com/opencontainers/runc/pull/160/ for more information <add>func processSetKeyReexec() { <add>} <add> <add>// SetExternalKey provides a convenient way to set an External key to a sandbox <add>func SetExternalKey(controllerID string, containerID string, key string) error { <add> return types.NotImplementedErrorf("SetExternalKey isn't supported on non linux systems") <add>} <add> <add>func sendKey(c net.Conn, data setKeyData) error { <add> return types.NotImplementedErrorf("sendKey isn't supported on non linux systems") <add>} <add> <add>func processReturn(r io.Reader) error { <add> return types.NotImplementedErrorf("processReturn isn't supported on non linux systems") <add>} <add> <add>// no-op on non linux systems <add>func (c *controller) startExternalKeyListener() error { <add> return nil <add>} <add> <add>func (c *controller) acceptClientConnections(sock string, l net.Listener) { <add>} <add> <add>func (c *controller) processExternalKey(conn net.Conn) error { <add> return types.NotImplementedErrorf("processExternalKey isn't supported on non linux systems") <add>} <add> <add>func (c *controller) stopExternalKeyListener() { <add>}
7
Ruby
Ruby
build bottle with verbose
60600c824cb07b36bc74b7a7f363069f8c29a8ca
<ide><path>Library/Homebrew/cmd/test-bot.rb <ide> def formula formula_name <ide> test "brew", "audit", *audit_args <ide> if install_passed <ide> if formula.stable? && !ARGV.include?('--no-bottle') <del> bottle_args = ["--rb", canonical_formula_name] <add> bottle_args = ["--verbose", "--rb", canonical_formula_name] <ide> bottle_args << { :puts_output_on_success => true } <ide> test "brew", "bottle", *bottle_args <ide> bottle_step = steps.last
1
Python
Python
delete a blank
5ee9158d86fdd0c68d007a75b7e71909d2ee7037
<ide><path>example_aliyun_ecs.py <ide> image = images[0] <ide> print('Use image %s' % image) <ide> <del> <ide> sgs = ecs.ex_list_security_groups() <ide> print('Found %d security groups' % len(sgs)) <ide> if len(sgs) == 0:
1
Text
Text
update links to point to more accurate docs
8f023992a2072209be8db1345fbbbcc293eee13a
<ide><path>docs/api-reference/next.config.js/redirects.md <ide> In some rare cases, you might need to assign a custom status code for older HTTP <ide> ## Other Redirects <ide> <ide> - Inside [API Routes](/docs/api-routes/response-helpers.md), you can use `res.redirect()`. <del>- Inside [`getStaticProps`](/docs/basic-features/data-fetching/get-static-props.md) and [`getServerSideProps`](/docs/basic-features/data-fetching/get-server-side-props.md), you can redirect specific pages at request-time. <add>- Inside [`getStaticProps`](/docs/api-reference/data-fetching/get-static-props.md) and [`getServerSideProps`](/docs/api-reference/data-fetching/get-server-side-props.md), you can redirect specific pages at request-time.
1
Mixed
Python
add contributor agreement for emulbreh
012e874d094bbf13ed18547eb3d13e197399e955
<ide><path>.github/contributors/emulbreh.md <add># spaCy contributor agreement <add> <add>This spaCy Contributor Agreement (**"SCA"**) is based on the <add>[Oracle Contributor Agreement](http://www.oracle.com/technetwork/oca-405177.pdf). <add>The SCA applies to any contribution that you make to any product or project <add>managed by us (the **"project"**), and sets out the intellectual property rights <add>you grant to us in the contributed materials. The term **"us"** shall mean <add>[ExplosionAI UG (haftungsbeschränkt)](https://explosion.ai/legal). The term <add>**"you"** shall mean the person or entity identified below. <add> <add>If you agree to be bound by these terms, fill in the information requested <add>below and include the filled-in version with your first pull request, under the <add>folder [`.github/contributors/`](/.github/contributors/). The name of the file <add>should be your GitHub username, with the extension `.md`. For example, the user <add>example_user would create the file `.github/contributors/example_user.md`. <add> <add>Read this agreement carefully before signing. These terms and conditions <add>constitute a binding legal agreement. <add> <add>## Contributor Agreement <add> <add>1. The term "contribution" or "contributed materials" means any source code, <add>object code, patch, tool, sample, graphic, specification, manual, <add>documentation, or any other material posted or submitted by you to the project. <add> <add>2. With respect to any worldwide copyrights, or copyright applications and <add>registrations, in your contribution: <add> <add> * you hereby assign to us joint ownership, and to the extent that such <add> assignment is or becomes invalid, ineffective or unenforceable, you hereby <add> grant to us a perpetual, irrevocable, non-exclusive, worldwide, no-charge, <add> royalty-free, unrestricted license to exercise all rights under those <add> copyrights. This includes, at our option, the right to sublicense these same <add> rights to third parties through multiple levels of sublicensees or other <add> licensing arrangements; <add> <add> * you agree that each of us can do all things in relation to your <add> contribution as if each of us were the sole owners, and if one of us makes <add> a derivative work of your contribution, the one who makes the derivative <add> work (or has it made will be the sole owner of that derivative work; <add> <add> * you agree that you will not assert any moral rights in your contribution <add> against us, our licensees or transferees; <add> <add> * you agree that we may register a copyright in your contribution and <add> exercise all ownership rights associated with it; and <add> <add> * you agree that neither of us has any duty to consult with, obtain the <add> consent of, pay or render an accounting to the other for any use or <add> distribution of your contribution. <add> <add>3. With respect to any patents you own, or that you can license without payment <add>to any third party, you hereby grant to us a perpetual, irrevocable, <add>non-exclusive, worldwide, no-charge, royalty-free license to: <add> <add> * make, have made, use, sell, offer to sell, import, and otherwise transfer <add> your contribution in whole or in part, alone or in combination with or <add> included in any product, work or materials arising out of the project to <add> which your contribution was submitted, and <add> <add> * at our option, to sublicense these same rights to third parties through <add> multiple levels of sublicensees or other licensing arrangements. <add> <add>4. Except as set out above, you keep all right, title, and interest in your <add>contribution. The rights that you grant to us under these terms are effective <add>on the date you first submitted a contribution to us, even if your submission <add>took place before the date you sign these terms. <add> <add>5. You covenant, represent, warrant and agree that: <add> <add> * Each contribution that you submit is and shall be an original work of <add> authorship and you can legally grant the rights set out in this SCA; <add> <add> * to the best of your knowledge, each contribution will not violate any <add> third party's copyrights, trademarks, patents, or other intellectual <add> property rights; and <add> <add> * each contribution shall be in compliance with U.S. export control laws and <add> other applicable export and import laws. You agree to notify us if you <add> become aware of any circumstance which would make any of the foregoing <add> representations inaccurate in any respect. We may publicly disclose your <add> participation in the project, including the fact that you have signed the SCA. <add> <add>6. This SCA is governed by the laws of the State of California and applicable <add>U.S. Federal law. Any choice of law rules will not apply. <add> <add>7. Please place an “x” on one of the applicable statement below. Please do NOT <add>mark both statements: <add> <add> * [x] I am signing on behalf of myself as an individual and no other person <add> or entity, including my employer, has or will have rights with respect to my <add> contributions. <add> <add> * [ ] I am signing on behalf of my employer or a legal entity and I have the <add> actual authority to contractually bind that entity. <add> <add>## Contributor Details <add> <add>| Field | Entry | <add>|------------------------------- | -------------------- | <add>| Name | Johannes Dollinger | <add>| Company name (if applicable) | | <add>| Title or role (if applicable) | | <add>| Date | 2018-02-13 | <add>| GitHub username | emulbreh | <add>| Website (optional) | | <ide><path>spacy/util.py <ide> import functools <ide> import cytoolz <ide> import itertools <del>import numpy as np <add>import numpy.random <ide> <ide> from .symbols import ORTH <ide> from .compat import cupy, CudaStream, path2str, basestring_, input_, unicode_ <ide> def use_gpu(gpu_id): <ide> <ide> <ide> def fix_random_seed(seed=0): <del> random.seed(0) <del> np.random.seed(0) <add> random.seed(seed) <add> numpy.random.seed(seed)
2
Javascript
Javascript
fix typos in core.js
8b8620d580314050175983402dfddf2674e8e22a
<ide><path>lib/internal/http2/core.js <ide> class Http2Session extends EventEmitter { <ide> } <ide> <ide> // If ping is called while we are still connecting, or after close() has <del> // been called, the ping callback will be invoked immediately will a ping <add> // been called, the ping callback will be invoked immediately with a ping <ide> // cancelled error and a duration of 0.0. <ide> ping(payload, callback) { <ide> if (this.destroyed) <ide> class Http2Session extends EventEmitter { <ide> settingsFn(); <ide> } <ide> <del> // Sumits a GOAWAY frame to be sent to the remote peer. Note that this <add> // Submits a GOAWAY frame to be sent to the remote peer. Note that this <ide> // is only a notification, and does not affect the usable state of the <ide> // session with the notable exception that new incoming streams will <ide> // be rejected automatically.
1
Python
Python
add det_lemma constant
920fa0fed2febcf2e044f2248267b7e6a3abcc60
<ide><path>spacy/language_data/util.py <ide> <ide> <ide> PRON_LEMMA = "-PRON-" <add>DET_LEMMA = "-DET-" <ide> ENT_ID = "ent_id" <ide> <ide>
1
Javascript
Javascript
attach location info to syntax errors
459b106d6cbee05661dee7b3929610d7d06bede0
<ide><path>lib/repl.js <ide> function REPLServer(prompt, <ide> self._domain.on('error', function(e) { <ide> debug('domain error'); <ide> const top = replMap.get(self); <add> util.decorateErrorStack(e); <ide> top.outputStream.write((e.stack || e) + '\n'); <ide> top.lineParser.reset(); <ide> top.bufferedCommand = ''; <ide><path>test/parallel/test-repl-syntax-error-stack.js <add>'use strict'; <add> <add>const common = require('../common'); <add>const assert = require('assert'); <add>const path = require('path'); <add>const repl = require('repl'); <add>const util = require('util'); <add>let found = false; <add> <add>process.on('exit', () => { <add> assert.strictEqual(found, true); <add>}); <add> <add>// A stream to push an array into a REPL <add>function ArrayStream() { <add> this.run = function(data) { <add> data.forEach(line => { <add> this.emit('data', line + '\n'); <add> }); <add> }; <add>} <add>util.inherits(ArrayStream, require('stream').Stream); <add>ArrayStream.prototype.readable = true; <add>ArrayStream.prototype.writable = true; <add>ArrayStream.prototype.resume = function() {}; <add>ArrayStream.prototype.write = function(output) { <add> if (/var foo bar;/.test(output)) <add> found = true; <add>}; <add> <add>const putIn = new ArrayStream(); <add>const testMe = repl.start('', putIn); <add>let file = path.resolve(__dirname, '../fixtures/syntax/bad_syntax'); <add> <add>if (common.isWindows) <add> file = file.replace(/\\/g, '\\\\'); <add> <add>putIn.run(['.clear']); <add>putIn.run([`require('${file}');`]);
2
Python
Python
add round_robin scheduling algorithm
e274863cda5514b22196942d3a55887499166fcf
<ide><path>scheduling/round_robin.py <add>""" <add>Round Robin is a scheduling algorithm. <add>In Round Robin each process is assigned a fixed time slot in a cyclic way. <add>https://en.wikipedia.org/wiki/Round-robin_scheduling <add>""" <add>from statistics import mean <add>from typing import List <add> <add> <add>def calculate_waiting_times(burst_times: List[int]) -> List[int]: <add> """ <add> Calculate the waiting times of a list of processes that have a specified duration. <add> <add> Return: The waiting time for each process. <add> >>> calculate_waiting_times([10, 5, 8]) <add> [13, 10, 13] <add> >>> calculate_waiting_times([4, 6, 3, 1]) <add> [5, 8, 9, 6] <add> >>> calculate_waiting_times([12, 2, 10]) <add> [12, 2, 12] <add> """ <add> quantum = 2 <add> rem_burst_times = list(burst_times) <add> waiting_times = [0] * len(burst_times) <add> t = 0 <add> while 1: <add> done = True <add> for i, burst_time in enumerate(burst_times): <add> if rem_burst_times[i] > 0: <add> done = False <add> if rem_burst_times[i] > quantum: <add> t += quantum <add> rem_burst_times[i] -= quantum <add> else: <add> t += rem_burst_times[i] <add> waiting_times[i] = t - burst_times[i] <add> rem_burst_times[i] = 0 <add> if done is True: <add> return waiting_times <add> <add> <add>def calculate_turn_around_times( <add> burst_times: List[int], waiting_times: List[int] <add>) -> List[int]: <add> """ <add> >>> calculate_turn_around_times([1, 2, 3, 4], [0, 1, 3]) <add> [1, 3, 6] <add> >>> calculate_turn_around_times([10, 3, 7], [10, 6, 11]) <add> [20, 9, 18] <add> """ <add> return [burst + waiting for burst, waiting in zip(burst_times, waiting_times)] <add> <add> <add>if __name__ == "__main__": <add> burst_times = [3, 5, 7] <add> waiting_times = calculate_waiting_times(burst_times) <add> turn_around_times = calculate_turn_around_times(burst_times, waiting_times) <add> print("Process ID \tBurst Time \tWaiting Time \tTurnaround Time") <add> for i, burst_time in enumerate(burst_times): <add> print( <add> f" {i + 1}\t\t {burst_time}\t\t {waiting_times[i]}\t\t " <add> f"{turn_around_times[i]}" <add> ) <add> print(f"\nAverage waiting time = {mean(waiting_times):.5f}") <add> print(f"Average turn around time = {mean(turn_around_times):.5f}")
1
Text
Text
translate doc 11-advanced-performance to chinese
4c365ea9573f2f4b0af6ddebc9397fc778b65712
<ide><path>docs/docs/11-advanced-performance.zh-CN.md <add>--- <add>id: advanced-performance-zh-CN <add>title: 提高性能 <add>permalink: docs/advanced-performance-zh-CN.html <add>prev: shallow-compare-zh-CN.html <add>next: context-zh-CN.html <add>--- <add> <add>当人们考虑将React应用到自己的系统里时,都会想知道React是否可以和非React的应用一样可以快速的响应各种用户的操作。改变组件的state时,它会重新渲染组件的所有子节点,有人会怀疑这种重新渲染会带来很大的性能开销。但是React使用很多技术来最小化的减少DOM操作的开销达到更新UI的效果。 <add> <add>## 使用生产构建版本 <add> <add>如果你在开发React应用中,遇到了一些性能上的问题,你可以使用了[minified production build](/react/downloads.html)进行测试。这个开发构建版本包括了额外的一些警告信息,可以帮助你更好的调试你的应用。由于它做了很多额外的开销,所以它运行起来会相对要慢一点。 <add> <add>## 避免调整真实DOM树 <add> <add>React利用*虚拟DOM*,来描述在浏览器上显示的真实DOM树。这种并行的表示方法,可以让React避免直接去操作DOM节点,毕竟操作DOM节点的开销要远远大于直接去操作Javascript的对象。当组件的state或者props更新的时候,React会根据新生成的虚拟DOM和之前的虚拟DOM进行比较,来判断是否需要去更新真实DOM上的内容。只有在前后虚拟DOM不相等的情况下,React才会去[调整](/react/docs/reconciliation.html)真实DOM的结构。 <add> <add>在此之上,React提供了一个组件生命周期函数`shouldComponentUpdate`,它会在组件进行重渲染过程开始的时候(虚拟DOM和真实DOM进行对比)进行调用。让开发者可以短接这个过程。该函数默认会返回`true`,让React去执行更新。 <add> <add>```javascript <add>shouldComponentUpdate: function(nextProps, nextState) { <add> return true; <add>} <add>``` <add> <add>记住一点,在React中,这个函数调用的非常频繁,所以里面的操作不能太复杂,一定要快。 <add> <add>你有几个聊天对话的消息应用程序。假设只有一个对话改变了。如果你在`ChatThread`组件中实现了`shouldComponentUpdate`函数,React可以跳过对其他线程的重渲染的步骤。 <add> <add>```javascript <add>shouldComponentUpdate: function(nextProps, nextState) { <add> // TODO: return whether or not current chat thread is <add> // different to former one. <add>} <add>``` <add> <add>所以,总而言之,React可以让开发者使用`shouldComponentUpdate`函数来减少对DOM子树的调整,对于那些需要更新的组件,再进行虚拟DOMs的对比。 <add> <add>## shouldComponentUpdate 实战 <add> <add>这个一个组件的子树的结构。每一个节点表示`shouldComponentUpdate` return了什么,以及是否虚拟DOMs是相等的。最后,圆的颜色代表这个节点是否需要被重新调整。 <add> <add><figure><img src="/react/img/docs/should-component-update.png" /></figure> <add> <add>在上述例子中,C2节点的`shouldComponentUpdate`函数返回了`false`,所以React就不需要在这里产生新的虚拟DOM,也就不需要重新调整DOM。由于父节点C2已经在`shouldComponentUpdate`函数中返回`false`,所以它的所有子节点也就不会执行该函数。 <add> <add>对于C1和C3,`shouldComponentUpdate`函数返回了`true`,React会从上往下对子节点进行检查。对于C6节点,它返回了`true`;由于前后的虚拟DOMs不相等,所以它不得不调整真实DOM。最后在C8这个有趣的节点上。React会去对比前后虚拟DOM,由于前后是相等的,所以它不是对真实DOM进行调整。 <add> <add>请注意,React只会对C6进行DOM操作。对于C8,它通过对比虚拟DOMs的方式,避免重新渲染。对于C2的子节点以及C7,通过`shouldComponentUpdate`函数,直接忽略了虚拟DOM比较的过程,提高性能。 <add> <add>所以,我们应该怎么样来实现`shouldComponentUpdate`方法?举个例子,你有个组件仅仅只渲染一个string的文案: <add> <add>```javascript <add>React.createClass({ <add> propTypes: { <add> value: React.PropTypes.string.isRequired <add> }, <add> <add> render: function() { <add> return <div>{this.props.value}</div>; <add> } <add>}); <add>``` <add> <add>我们可以简单的像下面一样实现`shouldComponentUpdate` <add> <add>```javascript <add>shouldComponentUpdate: function(nextProps, nextState) { <add> return this.props.value !== nextProps.value; <add>} <add>``` <add> <add>目前为止,在props/state上处理简单的的数据结构是非常容易的。基于这种数据类型,我们可以通过mixin的方式把该函数引入到你的所有组件中去。事实上,React官方已经提供了这种方法:[PureRenderMixin](/react/docs/pure-render-mixin.html)。 <add> <add>但是,如果你的组件使用的在state或者props上使用的是可变的数据结构怎么办?组件里的prop不是以一个string的形式`'bar'`存在,而是以一种Javascript对象的形式包含了一个字符串,类似这样`{ foo: 'bar' }`: <add> <add>```javascript <add>React.createClass({ <add> propTypes: { <add> value: React.PropTypes.object.isRequired <add> }, <add> <add> render: function() { <add> return <div>{this.props.value.foo}</div>; <add> } <add>}); <add>``` <add> <add>如果是这种情况,按照我们刚才的在`shouldComponentUpdate`的实现的话,是不能达到我们的预期: <add> <add>```javascript <add>// assume this.props.value is { foo: 'bar' } <add>// assume nextProps.value is { foo: 'bar' }, <add>// but this reference is different to this.props.value <add>this.props.value !== nextProps.value; // true <add>``` <add> <add>因为props实际上是没有改变的,所以`shouldComponentUpdate`始终会返回`true`。为了解决这个问题,我们也有一个可选的解决方案: <add> <add>```javascript <add>shouldComponentUpdate: function(nextProps, nextState) { <add> return this.props.value.foo !== nextProps.value.foo; <add>} <add>``` <add> <add>基本上,我们是不会利用这种深度比较去判断是否有属性改变。这样的操作十分损耗性能的,并且非常难扩展。最重要的是,如果我们没有仔细管理对象的引用关系,很可能导致对比不出结果。让我们来看看下面这个组件: <add> <add>```javascript <add>React.createClass({ <add> getInitialState: function() { <add> return { value: { foo: 'bar' } }; <add> }, <add> <add> onClick: function() { <add> var value = this.state.value; <add> value.foo += 'bar'; // ANTI-PATTERN! <add> this.setState({ value: value }); <add> }, <add> <add> render: function() { <add> return ( <add> <div> <add> <InnerComponent value={this.state.value} /> <add> <a onClick={this.onClick}>Click me</a> <add> </div> <add> ); <add> } <add>}); <add>``` <add> <add>子组件第一次渲染的时候,组件会收到`{ foo: 'bar' }`作为prop中的value的值。如果用户进行了点击的操作,父组件为更新state,变为`{ value: { foo: 'barbar' } }`,之后会触发子组件的重渲染的过程,子组件会收到新的prop中value的值`{ foo: 'barbar' }`。 <add> <add>问题在与,因为父子组件共同分享了一个对象的引用,当这个对象在`onClick`函数中进行修改后,子组件的prop也已经改变。所以,当重渲染的过程开始,`shouldComponentUpdate`函数就会被触发,`this.props.value.foo` 与`nextProps.value.foo`会是相等的。因为`this.props.value`和`nextProps.value`指向的是同一个对象。 <add> <add>因此,我们直接阻止了子组件进行重新渲染,整个UI也就不会把`'bar'`更新为`'barbar'`。 <add> <add>## 使用Immutable-js <add> <add>[Immutable-js](https://github.com/facebook/immutable-js)是一个由Lee Byron编写的Javascript的数据类型库,现在已经被Facebook开源了。它通过 *结构共享* 的方式提供了一个 *持久不可变的* 的集合。让我们来看看这个到底是什么东西。 <add> <add>* *不可变*:一旦被创建,一个集合不能被其他内容所改变 <add>* *持久性*:新的集合可以由之前的集合创建出来,或者由一个可变的数据创建。当新的集合被创建出来,原始的集合依然有效。 <add>* *结构共享*:新的集合会尽可能的复用之前集合内的内容。减少重复复制来提高性能。如果新集合和原来的集合是相等的,则会直接把之前的集合返回给新集合。 <add> <add>不可变的特性让跟踪变化变得简单;每次改变总是会产生新的一个对象,所以。我们只需要判断一下它们引用是否相同即可。举个例子,下面是常规的Javascript的写法: <add> <add>```javascript <add>var x = { foo: "bar" }; <add>var y = x; <add>y.foo = "baz"; <add>x === y; // true <add>``` <add> <add>尽管`y`已经被更改了,但是它的引用还是和`x`是一致的。所以他们两个进行对比,始终会返回`true`。所以,这样的操作应该要用`immutable-js `来完成: <add> <add>```javascript <add>var SomeRecord = Immutable.Record({ foo: null }); <add>var x = new SomeRecord({ foo: 'bar' }); <add>var y = x.set('foo', 'baz'); <add>x === y; // false <add>``` <add> <add>在这样的情况中,当我们改变了x里的内容,会返回给我们一个新的引用,我们可以安全地假定`x`已经改变。 <add> <add>另一种来跟踪数据变化的方法,是通过 setter 来设置标识符来做脏检查 (dirty checking)。这种方法的问题在于它强迫你使用 setter;你需要多写很多额外代码或者跟踪分析 class 中的数据。另外一种方式是,你可以在更改一个对象之前对它进行一次深复制,之后再进行深比较,来判断这次操作是否造成了数据改变:这种方案的问题在于深复制与深比较都是很昂贵的操作。 <add> <add>所以,Immutable的数据结构给你提供了一个很方便的方式去跟踪一个对象是否被修改了,我们只需要简单的实现`shouldComponentUpdate`即可。因此,如果我们的props和state模型使用了immutable-js方式,我们可以引入`PureRenderMixin`,从而提高我们的应用的性能。 <add> <add>## Immutable-js 结合 Flux <add> <add>如果你正在使用[Flux](https://facebook.github.io/flux/),你应该在你的stores里使用immutable-js。可以来看下[full API](https://facebook.github.io/immutable-js/docs/#/)。 <add> <add>让我们看看一种使用Immutable数据结构来处理的方式。首先,我们为每一个入口定义一个`Record`去处理模型。`Record`是一个保存各个字段的一个容器。 <add> <add>```javascript <add>var User = Immutable.Record({ <add> id: undefined, <add> name: undefined, <add> email: undefined <add>}); <add> <add>var Message = Immutable.Record({ <add> timestamp: new Date(), <add> sender: undefined, <add> text: '' <add>}); <add>``` <add> <add>Record 函数接受一个对象作为参数;这个对象定义了 Record 中的键值与默认值 <add> <add>*store*可以用两个list来记录users和messages <add> <add> <add>```javascript <add>this.users = Immutable.List(); <add>this.messages = Immutable.List(); <add>``` <add> <add>它可以很方便的实现处理*payload*数据类型。例如,当一个store收到了新的信息,我们可以直接创建一个新的record,然后把它加到我们message的list中去。 <add> <add>```javascript <add>this.messages = this.messages.push(new Message({ <add> timestamp: payload.timestamp, <add> sender: payload.sender, <add> text: payload.text <add>}); <add>``` <add> <add>注意,因为data的数据结构是不可变的,我们需要重新对`this.message`进行赋值。 <add> <add>在React方面,如果我们用了 `immutable-js`的数据结构去保存组件的state,我们就可以引入`PureRenderMixin`到所有你的组件中,做一个快速的判断是否需要重新渲染的操作。 <ide><path>docs/tips/15-expose-component-functions.zh-CN.md <add>--- <add>id: expose-component-functions-zh-CN <add>title: 暴露组件函数 <add>layout: tips <add>permalink: tips/expose-component-functions-zh-CN.html <add>prev: communicate-between-components-zh-CN.html <add>next: children-undefined-zh-CN.html <add>--- <add> <add> <add>这是另外一种组件[通信的方法](/react/tips/communicate-between-components.html):在子组件中暴露出一个方法,可以让父组件去调。 <add> <add>让我们看看这个todos的列表,在点击的时候就会被移除。如果只剩下最后一个未完成的待办事项,就执行animate函数: <add> <add>```js <add>var Todo = React.createClass({ <add> render: function() { <add> return <div onClick={this.props.onClick}>{this.props.title}</div>; <add> }, <add> <add> //this component will be accessed by the parent through the `ref` attribute <add> animate: function() { <add> console.log('Pretend %s is animating', this.props.title); <add> } <add>}); <add> <add>var Todos = React.createClass({ <add> getInitialState: function() { <add> return {items: ['Apple', 'Banana', 'Cranberry']}; <add> }, <add> <add> handleClick: function(index) { <add> var items = this.state.items.filter(function(item, i) { <add> return index !== i; <add> }); <add> this.setState({items: items}, function() { <add> if (items.length === 1) { <add> this.refs.item0.animate(); <add> } <add> }.bind(this)); <add> }, <add> <add> render: function() { <add> return ( <add> <div> <add> {this.state.items.map(function(item, i) { <add> var boundClick = this.handleClick.bind(this, i); <add> return ( <add> <Todo onClick={boundClick} key={i} title={item} ref={'item' + i} /> <add> ); <add> }, this)} <add> </div> <add> ); <add> } <add>}); <add> <add>ReactDOM.render(<Todos />, mountNode); <add>``` <add> <add>当然,你也可以通过在`todo`组件中的prop传递`isLastUnfinishedItem`,来让子组件在 `componentDidUpdate`中判断是否它是最后一个,来执行animate函数;但是,如果你通过不同的props值来控制的不同的动画,到最后可能会变得很混乱。 <ide>\ No newline at end of file
2
Javascript
Javascript
fix fouc issue on with-fela example
5782651e92ef07845e9d251981ac3ba2ced27e11
<ide><path>examples/with-ant-design-less/next.config.js <ide> if (typeof require !== 'undefined') { <ide> module.exports = withLess({ <ide> lessLoaderOptions: { <ide> javascriptEnabled: true, <del> modifyVars: themeVariables // make your antd custom effective <del> } <add> modifyVars: themeVariables, // make your antd custom effective <add> }, <ide> }) <ide><path>examples/with-fela/FelaProvider.js <ide> /* eslint-disable */ <ide> import { Component } from 'react' <del>import PropTypes from 'prop-types' <del> <ide> import { RendererProvider } from 'react-fela' <ide> import getFelaRenderer from './getFelaRenderer' <ide> <del>const clientRenderer = getFelaRenderer() <add>const fallbackRenderer = getFelaRenderer() <ide> <ide> export default class FelaProvider extends Component { <del> static contextTypes = { <del> renderer: PropTypes.object, <del> } <del> <ide> render() { <del> if (this.context.renderer) { <del> return this.props.children <del> } <del> <del> const renderer = this.props.renderer || clientRenderer <add> const renderer = this.props.renderer || fallbackRenderer <ide> return ( <ide> <RendererProvider renderer={renderer}> <ide> {this.props.children} <ide><path>examples/with-fela/pages/_app.js <add>import App, { Container } from 'next/app' <add>import React from 'react' <add>import FelaProvider from '../FelaProvider' <add> <add>export default class MyApp extends App { <add> static async getInitialProps ({ Component, ctx }) { <add> let pageProps = {} <add> <add> if (Component.getInitialProps) { <add> pageProps = await Component.getInitialProps(ctx) <add> } <add> <add> return { pageProps } <add> } <add> <add> render () { <add> const { Component, pageProps, renderer } = this.props <add> return ( <add> <Container> <add> <FelaProvider renderer={renderer}> <add> <Component {...pageProps} /> <add> </FelaProvider> <add> </Container> <add> ) <add> } <add>} <ide><path>examples/with-fela/pages/_document.js <ide> import Document, { Head, Main, NextScript } from 'next/document' <ide> import { renderToSheetList } from 'fela-dom' <del> <del>import FelaProvider from '../FelaProvider' <ide> import getFelaRenderer from '../getFelaRenderer' <ide> <ide> export default class MyDocument extends Document { <del> static getInitialProps ({ renderPage }) { <del> const serverRenderer = getFelaRenderer() <del> <del> const page = renderPage(App => props => ( <del> <FelaProvider renderer={serverRenderer}> <del> <App {...props} /> <del> </FelaProvider> <del> )) <add> static async getInitialProps (ctx) { <add> const renderer = getFelaRenderer() <add> const originalRenderPage = ctx.renderPage <ide> <del> const sheetList = renderToSheetList(serverRenderer) <add> ctx.renderPage = () => <add> originalRenderPage({ <add> enhanceApp: App => props => <App {...props} renderer={renderer} /> <add> }) <ide> <add> const initialProps = await Document.getInitialProps(ctx) <add> const sheetList = renderToSheetList(renderer) <ide> return { <del> ...page, <add> ...initialProps, <ide> sheetList <ide> } <ide> } <ide><path>examples/with-fela/pages/index.js <ide> import { useFela, FelaComponent } from 'react-fela' <ide> <del>import FelaProvider from '../FelaProvider' <del> <ide> const Container = ({ children }) => ( <ide> <FelaComponent <ide> style={{ <ide> function Title ({ children, size = 24 }) { <ide> } <ide> <ide> export default () => ( <del> <FelaProvider> <del> <Container> <del> <Title size={50}>My Title</Title> <del> <Text>Hi, I am Fela.</Text> <del> </Container> <del> </FelaProvider> <add> <Container> <add> <Title size={50}>My Title</Title> <add> <Text>Hi, I am Fela.</Text> <add> </Container> <ide> ) <ide><path>examples/with-ioc/jest.config.js <ide> module.exports = { <ide> setupFiles: ['<rootDir>/jest.setup.js'], <del> testPathIgnorePatterns: ['<rootDir>/.next/', '<rootDir>/node_modules/'] <add> testPathIgnorePatterns: ['<rootDir>/.next/', '<rootDir>/node_modules/'], <ide> } <ide><path>examples/with-kea/store.js <ide> import { keaReducer } from 'kea' <ide> import { createStore, compose, combineReducers } from 'redux' <ide> <ide> const reducers = combineReducers({ <del> kea: keaReducer('kea') <add> kea: keaReducer('kea'), <ide> }) <ide> <ide> const reduxDevTools =
7
PHP
PHP
update app tests
4701a5a7aab18b96306cd2f6db2e2b62e19c27aa
<ide><path>lib/Cake/Core/App.php <ide> use Cake\Utility\Inflector; <ide> <ide> /** <del> * App is responsible for path management, class location and class loading. <add> * App is responsible for resource location, and path management. <ide> * <del> * ### Adding paths <del> * <del> * You can add paths to the search indexes App uses to find classes using `App::build()`. Adding <del> * additional controller paths for example would alter where CakePHP looks for controllers. <del> * This allows you to split your application up across the filesystem. <ide> * <del> * ### Packages <del> * <del> * CakePHP is organized around the idea of packages, each class belongs to a package or folder where other <del> * classes reside. You can configure each package location in your application using `App::build('APackage/SubPackage', $paths)` <del> * to inform the framework where should each class be loaded. Almost every class in the CakePHP framework can be swapped <del> * by your own compatible implementation. If you wish to use you own class instead of the classes the framework provides, <del> * just add the class to your libs folder mocking the directory location of where CakePHP expects to find it. <add> * ### Adding paths <ide> * <del> * For instance if you'd like to use your own HttpSocket class, put it under <add> * You can add paths to the search indexes App uses to find resources using `App::build()`. Adding <add> * additional view paths for example would alter where CakePHP looks for view files. <ide> * <del> * App/Network/Http/HttpSocket.php <add> * You can only add paths for Views and Locale files. All class based resources should be mapped <add> * using your application's autoloader. <ide> * <ide> * ### Inspecting loaded paths <ide> * <ide> public static function objects($type, $path = null, $cache = true) { <ide> if (empty($path)) { <ide> $path = static::path($type, $plugin); <ide> } <add> // TODO write tests and fix objects(Plugin) with plugins <add> // on unique paths. Perhaps use Plugin::loaded()? <ide> <ide> foreach ((array)$path as $dir) { <ide> if ($dir != APP && is_dir($dir)) { <ide> protected static function _packageFormat() { <ide> if (empty(static::$_packageFormat)) { <ide> static::$_packageFormat = array( <ide> 'View' => array( <del> '%s' . 'View' . DS <add> '%s' . 'View' . DS, <ide> ), <ide> 'Locale' => array( <ide> '%s' . 'Locale' . DS <ide><path>lib/Cake/Test/TestCase/Core/AppTest.php <ide> public function testClassname() { <ide> $this->assertFalse(App::classname('Unknown', 'Controller', 'Controller')); <ide> <ide> // Test plugin <del> App::build(array( <del> 'Plugin' => array(CAKE . 'Test' . DS . 'TestApp' . DS . 'Plugin' . DS) <del> ), App::RESET); <ide> Plugin::load('TestPlugin'); <ide> $this->assertEquals('TestPlugin\Utility\TestPluginEngine', App::classname('TestPlugin.TestPlugin', 'Utility', 'Engine')); <ide> $this->assertFalse(App::classname('TestPlugin.Unknown', 'Utility')); <ide> public function testClassnameUnknownPlugin() { <ide> public function testBuild() { <ide> $old = App::path('View'); <ide> $expected = array( <del> APP . 'View' . DS <add> APP . 'View' . DS, <ide> ); <ide> $this->assertEquals($expected, $old); <ide> <ide> public function testBuild() { <ide> $new = App::path('View'); <ide> $expected = array( <ide> '/path/to/views/', <del> APP . 'View' . DS <add> APP . 'View' . DS, <ide> ); <ide> $this->assertEquals($expected, $new); <ide> <ide> public function testBuild() { <ide> */ <ide> public function testPathWithPlugins() { <ide> $basepath = CAKE . 'Test' . DS . 'TestApp' . DS . 'Plugin' . DS; <del> App::build(array( <del> 'Plugin' => array($basepath), <del> )); <ide> Plugin::load('TestPlugin'); <ide> <ide> $result = App::path('Controller', 'TestPlugin'); <ide> public function testPathWithPlugins() { <ide> * @return void <ide> */ <ide> public function testBuildWithReset() { <del> $old = App::path('Model'); <add> $old = App::path('View'); <ide> $expected = array( <del> APP . 'Model' . DS <add> APP . 'View' . DS, <ide> ); <ide> $this->assertEquals($expected, $old); <ide> <del> App::build(array('Model' => array('/path/to/models/')), App::RESET); <add> App::build(array('View' => array('/path/to/views/')), App::RESET); <ide> <del> $new = App::path('Model'); <add> $new = App::path('View'); <ide> <ide> $expected = array( <del> '/path/to/models/' <add> '/path/to/views/' <ide> ); <ide> $this->assertEquals($expected, $new); <ide> <ide> App::build(); //reset defaults <del> $defaults = App::path('Model'); <add> $defaults = App::path('View'); <ide> $this->assertEquals($old, $defaults); <ide> } <ide> <ide> public function testListObjects() { <ide> $this->assertTrue(in_array('Dispatcher', $result)); <ide> $this->assertTrue(in_array('Router', $result)); <ide> <del> App::build(array( <del> 'Model/Behavior' => App::core('Model/Behavior'), <del> 'Controller' => App::core('Controller'), <del> 'Controller/Component' => App::core('Controller/Component'), <del> 'View' => App::core('View'), <del> 'Model' => App::core('Model'), <del> 'View/Helper' => App::core('View/Helper'), <del> ), App::RESET); <ide> $result = App::objects('Model/Behavior', null, false); <del> $this->assertTrue(in_array('TreeBehavior', $result)); <add> $this->assertContains('PersisterOneBehaviorBehavior', $result); <ide> <ide> $result = App::objects('Controller/Component', null, false); <del> $this->assertTrue(in_array('AuthComponent', $result)); <add> $this->assertContains('AppleComponent', $result); <ide> <ide> $result = App::objects('View', null, false); <del> $this->assertTrue(in_array('JsonView', $result)); <add> $this->assertContains('CustomJsonView', $result); <ide> <ide> $result = App::objects('View/Helper', null, false); <del> $this->assertTrue(in_array('HtmlHelper', $result)); <add> $this->assertContains('BananaHelper', $result); <ide> <ide> $result = App::objects('Model', null, false); <del> $this->assertTrue(in_array('AcoAction', $result)); <add> $this->assertContains('Article', $result); <ide> <ide> $result = App::objects('file'); <ide> $this->assertFalse($result); <ide> public function testListObjects() { <ide> <ide> $result = App::objects('NonExistingType'); <ide> $this->assertSame(array(), $result); <del> } <ide> <del> function testMe() { <del> App::build(array( <del> 'Plugin' => array( <del> CAKE . 'Test/TestApp/Plugin/' <del> ) <del> )); <ide> $result = App::objects('Plugin', null, false); <ide> $this->assertContains('TestPlugin', $result); <ide> $this->assertContains('TestPluginTwo', $result); <ide> public function testThemePath() { <ide> */ <ide> public function testPaths() { <ide> $result = App::paths(); <del> $this->assertArrayHasKey('Plugin', $result); <del> $this->assertArrayHasKey('Controller', $result); <del> $this->assertArrayHasKey('Controller/Component', $result); <add> $this->assertArrayHasKey('View', $result); <add> $this->assertArrayHasKey('Locale', $result); <ide> } <ide> <ide> }
2
Javascript
Javascript
simplify coroutines by making yields stateless
fd8d5f7a8acadda78238c612311c9bd7bde4cf66
<ide><path>src/isomorphic/classic/element/ReactElementValidator.js <ide> var ReactElementValidator = { <ide> createElement: function(type, props, children) { <ide> var validType = <ide> typeof type === 'string' || <del> typeof type === 'function' || <del> type !== null && typeof type === 'object' && typeof type.tag === 'number'; <add> typeof type === 'function'; <ide> // We warn in this case but don't throw. We expect the element creation to <ide> // succeed and there will likely be errors in render. <ide> if (!validType) { <ide><path>src/renderers/shared/fiber/ReactChildFiber.js <ide> var { <ide> } = require('ReactPortal'); <ide> <ide> var ReactFiber = require('ReactFiber'); <del>var ReactReifiedYield = require('ReactReifiedYield'); <ide> var ReactTypeOfSideEffect = require('ReactTypeOfSideEffect'); <ide> var ReactTypeOfWork = require('ReactTypeOfWork'); <ide> <ide> const { <ide> createFiberFromPortal, <ide> } = ReactFiber; <ide> <del>const { <del> createReifiedYield, <del> createUpdatedReifiedYield, <del>} = ReactReifiedYield; <del> <ide> const isArray = Array.isArray; <ide> <ide> const { <ide> function ChildReconciler(shouldClone, shouldTrackSideEffects) { <ide> yieldNode : ReactYield, <ide> priority : PriorityLevel <ide> ) : Fiber { <del> // TODO: Should this also compare continuation to determine whether to reuse? <ide> if (current == null || current.tag !== YieldComponent) { <ide> // Insert <del> const reifiedYield = createReifiedYield(yieldNode); <ide> const created = createFiberFromYield(yieldNode, priority); <del> created.type = reifiedYield; <add> created.type = yieldNode.value; <ide> created.return = returnFiber; <ide> return created; <ide> } else { <ide> // Move based on index <ide> const existing = useFiber(current, priority); <del> existing.type = createUpdatedReifiedYield( <del> current.type, <del> yieldNode <del> ); <add> existing.type = yieldNode.value; <ide> existing.return = returnFiber; <ide> return existing; <ide> } <ide> function ChildReconciler(shouldClone, shouldTrackSideEffects) { <ide> } <ide> <ide> case REACT_YIELD_TYPE: { <del> const reifiedYield = createReifiedYield(newChild); <ide> const created = createFiberFromYield(newChild, priority); <del> created.type = reifiedYield; <add> created.type = newChild.value; <ide> created.return = returnFiber; <ide> return created; <ide> } <ide> function ChildReconciler(shouldClone, shouldTrackSideEffects) { <ide> } <ide> <ide> case REACT_YIELD_TYPE: { <del> if (newChild.key === key) { <add> // Yields doesn't have keys. If the previous node is implicitly keyed <add> // we can continue to replace it without aborting even if it is not a <add> // yield. <add> if (key === null) { <ide> return updateYield(returnFiber, oldFiber, newChild, priority); <ide> } else { <ide> return null; <ide> function ChildReconciler(shouldClone, shouldTrackSideEffects) { <ide> } <ide> <ide> case REACT_YIELD_TYPE: { <del> const matchedFiber = existingChildren.get( <del> newChild.key === null ? newIdx : newChild.key <del> ) || null; <add> // Yields doesn't have keys, so we neither have to check the old nor <add> // new node for the key. If both are yields, they match. <add> const matchedFiber = existingChildren.get(newIdx) || null; <ide> return updateYield(returnFiber, matchedFiber, newChild, priority); <ide> } <ide> <ide> function ChildReconciler(shouldClone, shouldTrackSideEffects) { <ide> switch (child.$$typeof) { <ide> case REACT_ELEMENT_TYPE: <ide> case REACT_COROUTINE_TYPE: <del> case REACT_YIELD_TYPE: <ide> case REACT_PORTAL_TYPE: <ide> const key = child.key; <ide> if (typeof key !== 'string') { <ide> function ChildReconciler(shouldClone, shouldTrackSideEffects) { <ide> yieldNode : ReactYield, <ide> priority : PriorityLevel <ide> ) : Fiber { <del> const key = yieldNode.key; <add> // There's no need to check for keys on yields since they're stateless. <ide> let child = currentFirstChild; <del> while (child) { <del> // TODO: If key === null and child.key === null, then this only applies to <del> // the first item in the list. <del> if (child.key === key) { <del> if (child.tag === YieldComponent) { <del> deleteRemainingChildren(returnFiber, child.sibling); <del> const existing = useFiber(child, priority); <del> existing.type = createUpdatedReifiedYield( <del> child.type, <del> yieldNode <del> ); <del> existing.return = returnFiber; <del> return existing; <del> } else { <del> deleteRemainingChildren(returnFiber, child); <del> break; <del> } <add> if (child) { <add> if (child.tag === YieldComponent) { <add> deleteRemainingChildren(returnFiber, child.sibling); <add> const existing = useFiber(child, priority); <add> existing.type = yieldNode.value; <add> existing.return = returnFiber; <add> return existing; <ide> } else { <del> deleteChild(returnFiber, child); <add> deleteRemainingChildren(returnFiber, child); <ide> } <del> child = child.sibling; <ide> } <ide> <del> const reifiedYield = createReifiedYield(yieldNode); <ide> const created = createFiberFromYield(yieldNode, priority); <del> created.type = reifiedYield; <add> created.type = yieldNode.value; <ide> created.return = returnFiber; <ide> return created; <ide> } <ide><path>src/renderers/shared/fiber/ReactFiber.js <ide> exports.createFiberFromCoroutine = function(coroutine : ReactCoroutine, priority <ide> }; <ide> <ide> exports.createFiberFromYield = function(yieldNode : ReactYield, priorityLevel : PriorityLevel) : Fiber { <del> const fiber = createFiber(YieldComponent, yieldNode.key); <del> fiber.pendingProps = {}; <add> const fiber = createFiber(YieldComponent, null); <ide> return fiber; <ide> }; <ide> <ide><path>src/renderers/shared/fiber/ReactFiberCompleteWork.js <ide> import type { Fiber } from 'ReactFiber'; <ide> import type { HostContext } from 'ReactFiberHostContext'; <ide> import type { FiberRoot } from 'ReactFiberRoot'; <ide> import type { HostConfig } from 'ReactFiberReconciler'; <del>import type { ReifiedYield } from 'ReactReifiedYield'; <ide> <ide> var { reconcileChildFibers } = require('ReactChildFiber'); <ide> var { <ide> module.exports = function<T, P, I, TI, PI, C, CX, PL>( <ide> workInProgress.effectTag |= Update; <ide> } <ide> <del> function appendAllYields(yields : Array<ReifiedYield>, workInProgress : Fiber) { <add> function appendAllYields(yields : Array<mixed>, workInProgress : Fiber) { <ide> let node = workInProgress.stateNode; <ide> while (node) { <ide> if (node.tag === HostComponent || node.tag === HostText || <ide> module.exports = function<T, P, I, TI, PI, C, CX, PL>( <ide> <ide> // Build up the yields. <ide> // TODO: Compare this to a generator or opaque helpers like Children. <del> var yields : Array<ReifiedYield> = []; <add> var yields : Array<mixed> = []; <ide> appendAllYields(yields, workInProgress); <ide> var fn = coroutine.handler; <ide> var props = coroutine.props; <ide><path>src/renderers/shared/fiber/ReactReifiedYield.js <del>/** <del> * Copyright 2013-present, Facebook, Inc. <del> * All rights reserved. <del> * <del> * This source code is licensed under the BSD-style license found in the <del> * LICENSE file in the root directory of this source tree. An additional grant <del> * of patent rights can be found in the PATENTS file in the same directory. <del> * <del> * @providesModule ReactReifiedYield <del> * @flow <del> */ <del> <del>'use strict'; <del> <del>import type { ReactYield } from 'ReactCoroutine'; <del>import type { Fiber } from 'ReactFiber'; <del> <del>var { createFiberFromElementType } = require('ReactFiber'); <del> <del>export type ReifiedYield = { continuation: Fiber, props: Object }; <del> <del>exports.createReifiedYield = function(yieldNode : ReactYield) : ReifiedYield { <del> var fiber = createFiberFromElementType( <del> yieldNode.continuation, <del> yieldNode.key, <del> null // debugOwner <del> ); <del> return { <del> continuation: fiber, <del> props: yieldNode.props, <del> }; <del>}; <del> <del>exports.createUpdatedReifiedYield = function(previousYield : ReifiedYield, yieldNode : ReactYield) : ReifiedYield { <del> var fiber = previousYield.continuation; <del> if (fiber.type !== yieldNode.continuation) { <del> fiber = createFiberFromElementType( <del> yieldNode.continuation, <del> yieldNode.key, <del> null // debugOwner <del> ); <del> } <del> return { <del> continuation: fiber, <del> props: yieldNode.props, <del> }; <del>}; <ide><path>src/renderers/shared/fiber/__tests__/ReactCoroutine-test.js <ide> describe('ReactCoroutine', () => { <ide> function Child({ bar }) { <ide> ops.push(['Child', bar]); <ide> return ReactCoroutine.createYield({ <del> bar: bar, <del> }, Continuation, null); <add> props: { <add> bar: bar, <add> }, <add> continuation: Continuation, <add> }); <ide> } <ide> <ide> function Indirection() { <ide> describe('ReactCoroutine', () => { <ide> class Child extends React.Component { <ide> render() { <ide> ops.push('Child'); <del> return ReactCoroutine.createYield({}, Continuation, null); <add> return ReactCoroutine.createYield(Continuation); <ide> } <ide> componentWillUnmount() { <ide> ops.push('Unmount Child'); <ide> describe('ReactCoroutine', () => { <ide> <ide> function HandleYields(props, yields) { <ide> ops.push('HandleYields'); <del> return yields.map(y => <y.continuation />); <add> return yields.map(ContinuationComponent => <ContinuationComponent />); <ide> } <ide> <ide> class Parent extends React.Component { <ide><path>src/renderers/shared/fiber/isomorphic/ReactCoroutine.js <ide> import type { ReactNodeList } from 'ReactTypes'; <ide> <ide> // The Symbol used to tag the special React types. If there is no native Symbol <ide> // nor polyfill, then a plain number is used for performance. <del>var REACT_COROUTINE_TYPE = <del> (typeof Symbol === 'function' && Symbol.for && Symbol.for('react.coroutine')) || <del> 0xeac8; <add>var REACT_COROUTINE_TYPE; <add>var REACT_YIELD_TYPE; <add>if (typeof Symbol === 'function' && Symbol.for) { <add> REACT_COROUTINE_TYPE = Symbol.for('react.coroutine'); <add> REACT_YIELD_TYPE = Symbol.for('react.yield'); <add>} else { <add> REACT_COROUTINE_TYPE = 0xeac8; <add> REACT_YIELD_TYPE = 0xeac9; <add>} <ide> <del>var REACT_YIELD_TYPE = <del> (typeof Symbol === 'function' && Symbol.for && Symbol.for('react.yield')) || <del> 0xeac9; <del> <del>type ReifiedYield = { continuation: Object, props: Object }; <del>type CoroutineHandler<T> = (props: T, yields: Array<ReifiedYield>) => ReactNodeList; <add>type CoroutineHandler<T> = (props: T, yields: Array<mixed>) => ReactNodeList; <ide> <ide> export type ReactCoroutine = { <ide> $$typeof: Symbol | number, <ide> key: null | string, <ide> children: any, <ide> // This should be a more specific CoroutineHandler <del> handler: (props: any, yields: Array<ReifiedYield>) => ReactNodeList, <add> handler: (props: any, yields: Array<mixed>) => ReactNodeList, <ide> props: any, <ide> }; <ide> export type ReactYield = { <ide> $$typeof: Symbol | number, <del> key: null | string, <del> props: Object, <del> continuation: mixed <add> value: mixed, <ide> }; <ide> <ide> exports.createCoroutine = function<T>( <ide> exports.createCoroutine = function<T>( <ide> return coroutine; <ide> }; <ide> <del>exports.createYield = function(props : mixed, continuation : mixed, key : ?string = null) { <add>exports.createYield = function(value : mixed) : ReactYield { <ide> var yieldNode = { <ide> // This tag allow us to uniquely identify this as a React Yield <ide> $$typeof: REACT_YIELD_TYPE, <del> key: key == null ? null : '' + key, <del> props: props, <del> continuation: continuation, <add> value: value, <ide> }; <ide> <ide> if (__DEV__) { <ide> // TODO: Add _store property for marking this as validated. <ide> if (Object.freeze) { <del> Object.freeze(yieldNode.props); <ide> Object.freeze(yieldNode); <ide> } <ide> }
7
Javascript
Javascript
use innerhtml not innertext in test
633125fd0d219311da20d1429186e8b4ba8c77ce
<ide><path>src/core/__tests__/ReactMount-test.js <ide> describe('ReactMount', function() { <ide> expect(mockUnmount.mock.calls.length).toBe(0); <ide> <ide> ReactMount.renderComponent(<Component text="orange" key="A" />, container); <del> expect(container.firstChild.innerText).toBe('orange'); <add> expect(container.firstChild.innerHTML).toBe('orange'); <ide> expect(mockMount.mock.calls.length).toBe(1); <ide> expect(mockUnmount.mock.calls.length).toBe(0); <ide> <ide> // If we change the key, the component is unmounted and remounted <ide> ReactMount.renderComponent(<Component text="green" key="B" />, container); <del> expect(container.firstChild.innerText).toBe('green'); <add> expect(container.firstChild.innerHTML).toBe('green'); <ide> expect(mockMount.mock.calls.length).toBe(2); <ide> expect(mockUnmount.mock.calls.length).toBe(1); <ide> <ide> // But if we don't change the key, the component instance is reused <ide> ReactMount.renderComponent(<Component text="blue" key="B" />, container); <del> expect(container.firstChild.innerText).toBe('blue'); <add> expect(container.firstChild.innerHTML).toBe('blue'); <ide> expect(mockMount.mock.calls.length).toBe(2); <ide> expect(mockUnmount.mock.calls.length).toBe(1); <ide> });
1
Ruby
Ruby
improve compatibility for old formula
b36dcc4ffde9a4f7419e9f876eac6ee77aaf3338
<ide><path>Library/Homebrew/compat/brewkit.rb <add># here so that formula from the repo that are very old can still be installed <add> <add>require 'formula' <add><path>Library/Homebrew/compat/compatibility.rb <del><path>Library/Homebrew/compatibility.rb <ide> def self.resolve_alias name <ide> def fails_with_llvm msg=nil, data=nil <ide> handle_llvm_failure FailsWithLLVM.new(msg, data) <ide> end <add>end <ide> <add>class UnidentifiedFormula < Formula <ide> end <ide><path>Library/Homebrew/global.rb <ide> require 'extend/string' <ide> require 'utils' <ide> require 'exceptions' <del>require 'compatibility' <ide> <ide> ARGV.extend(HomebrewArgvExtension) <ide> <ide> module Homebrew extend self <ide> <ide> FORMULA_META_FILES = %w[README README.md ChangeLog COPYING LICENSE LICENCE COPYRIGHT AUTHORS] <ide> PLEASE_REPORT_BUG = "#{Tty.white}Please report this bug: #{Tty.em}https://github.com/mxcl/homebrew/wiki/Checklist-before-filing-a-new-issue#{Tty.reset}" <add> <add>unless ARGV.include? "--no-compat" or ENV['HOMEBREW_NO_COMPAT'] <add> $:.unshift(File.expand_path("#{__FILE__}/../compat")) <add> require 'compatibility' <add>end
3
Text
Text
enrich the introduction for debug gem
5292486aa08439dd523df7155c9a5b339a5c2adc
<ide><path>guides/source/debugging_rails_applications.md <ide> Rails 7 includes the `debug` gem in the `Gemfile` of new applications generated <ide> by CRuby. By default, it is ready in the `development` and `test` environments. <ide> Please check its [documentation](https://github.com/ruby/debug) for usage. <ide> <add>### Entering a Debugging Session <add> <add>By default, a debugging session will start after the `debug` library is required, which happens when your app boots. But don't worry, the session won't interfere your program. <add> <add> To enter the debugging session, you can use `binding.break` and its aliases: `binding.b` and `debugger`. The following examples will use `debugger`: <add> <add>```rb <add>class PostsController < ApplicationController <add> before_action :set_post, only: %i[ show edit update destroy ] <add> <add> # GET /posts or /posts.json <add> def index <add> @posts = Post.all <add> debugger <add> end <add> # ... <add>end <add>``` <add> <add>Once your app evaluates the debugging statement, it'll enter the debugging session: <add> <add>```rb <add>Processing by PostsController#index as HTML <add>[2, 11] in ~/projects/rails-guide-example/app/controllers/posts_controller.rb <add> 2| before_action :set_post, only: %i[ show edit update destroy ] <add> 3| <add> 4| # GET /posts or /posts.json <add> 5| def index <add> 6| @posts = Post.all <add>=> 7| debugger <add> 8| end <add> 9| <add> 10| # GET /posts/1 or /posts/1.json <add> 11| def show <add>=>#0 PostsController#index at ~/projects/rails-guide-example/app/controllers/posts_controller.rb:7 <add> #1 ActionController::BasicImplicitRender#send_action(method="index", args=[]) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/actionpack-7.0.0.alpha2/lib/action_controller/metal/basic_implicit_render.rb:6 <add> # and 72 frames (use `bt' command for all frames) <add>(rdbg) <add>``` <add> <add>### The Context <add> <add>After entering the debugging session, you can type in Ruby code as you're in a Rails console or IRB. <add> <add>```rb <add>(rdbg) @posts # ruby <add>[] <add>(rdbg) self <add>#<PostsController:0x0000000000aeb0> <add>(rdbg) <add>``` <add> <add>You can also use `p` or `pp` command to evaluate Ruby expressions (e.g. when a variable name conflicts with a debugger command). <add> <add>```rb <add>(rdbg) p headers # command <add>=> {"X-Frame-Options"=>"SAMEORIGIN", "X-XSS-Protection"=>"1; mode=block", "X-Content-Type-Options"=>"nosniff", "X-Download-Options"=>"noopen", "X-Permitted-Cross-Domain-Policies"=>"none", "Referrer-Policy"=>"strict-origin-when-cross-origin"} <add>(rdbg) pp headers # command <add>{"X-Frame-Options"=>"SAMEORIGIN", <add> "X-XSS-Protection"=>"1; mode=block", <add> "X-Content-Type-Options"=>"nosniff", <add> "X-Download-Options"=>"noopen", <add> "X-Permitted-Cross-Domain-Policies"=>"none", <add> "Referrer-Policy"=>"strict-origin-when-cross-origin"} <add>(rdbg) <add>``` <add> <add>Besides direct evaluation, debugger also helps you collect rich amount of information through different commands. Just to name a few here: <add> <add>- `info` (or `i`) - Information about current frame. <add>- `backtrace` (or `bt`) - Backtrace (with additional information). <add>- `outline` (or `o`, `ls`) - Available methods, constants, local variables, and instance variables in the current scope. <add> <add>#### The info command <add> <add>It'll give you an overview of the values of local and instance variables that are visible from the current frame. <add> <add>```rb <add>(rdbg) info # command <add>%self = #<PostsController:0x0000000000af78> <add>@_action_has_layout = true <add>@_action_name = "index" <add>@_config = {} <add>@_lookup_context = #<ActionView::LookupContext:0x00007fd91a037e38 @details_key=nil, @digest_cache=... <add>@_request = #<ActionDispatch::Request GET "http://localhost:3000/posts" for 127.0.0.1> <add>@_response = #<ActionDispatch::Response:0x00007fd91a03ea08 @mon_data=#<Monitor:0x00007fd91a03e8c8>... <add>@_response_body = nil <add>@_routes = nil <add>@marked_for_same_origin_verification = true <add>@posts = [] <add>@rendered_format = nil <add>``` <add> <add>#### The backtrace command <add> <add>When used without any options, it lists all the frames on the stack: <add> <add>```rb <add>=>#0 PostsController#index at ~/projects/rails-guide-example/app/controllers/posts_controller.rb:7 <add> #1 ActionController::BasicImplicitRender#send_action(method="index", args=[]) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/actionpack-7.0.0.alpha2/lib/action_controller/metal/basic_implicit_render.rb:6 <add> #2 AbstractController::Base#process_action(method_name="index", args=[]) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/actionpack-7.0.0.alpha2/lib/abstract_controller/base.rb:214 <add> #3 ActionController::Rendering#process_action(#arg_rest=nil) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/actionpack-7.0.0.alpha2/lib/action_controller/metal/rendering.rb:53 <add> #4 block in process_action at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/actionpack-7.0.0.alpha2/lib/abstract_controller/callbacks.rb:221 <add> #5 block in run_callbacks at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/activesupport-7.0.0.alpha2/lib/active_support/callbacks.rb:118 <add> #6 ActionText::Rendering::ClassMethods#with_renderer(renderer=#<PostsController:0x0000000000af78>) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/actiontext-7.0.0.alpha2/lib/action_text/rendering.rb:20 <add> #7 block {|controller=#<PostsController:0x0000000000af78>, action=#<Proc:0x00007fd91985f1c0 /Users/st0012/...|} in <class:Engine> (4 levels) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/actiontext-7.0.0.alpha2/lib/action_text/engine.rb:69 <add> #8 [C] BasicObject#instance_exec at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/activesupport-7.0.0.alpha2/lib/active_support/callbacks.rb:127 <add> ..... and more <add>``` <add> <add>Every frame comes with: <add> <add>- Frame identifier <add>- Call location <add>- Additional information (e.g. block or method arguments) <add> <add>This will give you a great sense about what's happening in your app. However, you probably will notice that: <add> <add>- There are too many frames (usually 50+ in a Rails app). <add>- Most of the frames are from Rails or other libraries you use. <add> <add>Don't worry, the `backtrace` command provides 2 options to help you filter frames: <add> <add>- `backtrace [num]` - only show `num` numbers of frames, e.g. `backtrace 10` . <add>- `backtrace /pattern/` - only show frames with identifier or location that matches the pattern, e.g. `backtrace /MyModel/`. <add> <add>It's also possible to use these options together: `backtrace [num] /pattern/`. <add> <add>#### The outline command <add> <add>This command is similar to `pry` and `irb`'s `ls` command. It will show you what's accessible from you current scope, including: <add> <add>- Local variables <add>- Instance variables <add>- Class variables <add>- Methods & their sources <add>- ...etc. <add> <add>```rb <add>ActiveSupport::Configurable#methods: config <add>AbstractController::Base#methods: <add> action_methods action_name action_name= available_action? controller_path inspect <add> response_body <add>ActionController::Metal#methods: <add> content_type content_type= controller_name dispatch headers <add> location location= media_type middleware_stack middleware_stack= <add> middleware_stack? performed? request request= reset_session <add> response response= response_body= response_code session <add> set_request! set_response! status status= to_a <add>ActionView::ViewPaths#methods: <add> _prefixes any_templates? append_view_path details_for_lookup formats formats= locale <add> locale= lookup_context prepend_view_path template_exists? view_paths <add>AbstractController::Rendering#methods: view_assigns <add> <add># ..... <add> <add>PostsController#methods: create destroy edit index new show update <add>instance variables: <add> @_action_has_layout @_action_name @_config @_lookup_context @_request <add> @_response @_response_body @_routes @marked_for_same_origin_verification @posts <add> @rendered_format <add>class variables: raise_on_open_redirects <add>``` <add> <add>You can find more commands and configuration options from its [documentation](https://github.com/ruby/debug). <add> <add> <ide> Debugging with the `web-console` gem <ide> ------------------------------------ <ide> <ide> References <ide> ---------- <ide> <ide> * [web-console Homepage](https://github.com/rails/web-console) <add>* [debug homepage](https://github.com/ruby/debug)
1
Python
Python
handle empty deque on errorhandler lookup
348bf52188b9f7bef1096d8fe70edf2e62ea04a8
<ide><path>flask/app.py <ide> def find_handler(handler_map): <ide> # __mro__ <ide> done = set() <ide> <del> while True: <add> while queue: <ide> cls = queue.popleft() <ide> if cls in done: <ide> continue <ide><path>tests/test_user_error_handler.py <ide> import flask <ide> <ide> <add>def test_error_handler_no_match(): <add> app = flask.Flask(__name__) <add> <add> class CustomException(Exception): <add> pass <add> <add> @app.errorhandler(CustomException) <add> def custom_exception_handler(e): <add> assert isinstance(e, CustomException) <add> return 'custom' <add> <add> @app.errorhandler(500) <add> def handle_500(e): <add> return type(e).__name__ <add> <add> @app.route('/custom') <add> def custom_test(): <add> raise CustomException() <add> <add> @app.route('/keyerror') <add> def key_error(): <add> raise KeyError() <add> <add> c = app.test_client() <add> <add> assert c.get('/custom').data == b'custom' <add> assert c.get('/keyerror').data == b'KeyError' <add> <add> <ide> def test_error_handler_subclass(): <ide> app = flask.Flask(__name__) <ide>
2
Ruby
Ruby
apply suggestions from code review
8ddf9b37bdbf36c8c13941b343c53f86aac9b861
<ide><path>Library/Homebrew/dev-cmd/bump.rb <ide> def bump <ide> raise UsageError, "`--limit` must be used with either `--formula` or `--cask`." <ide> end <ide> <del> formulae_and_casks = <del> if args.formula? <del> args.named.to_formulae <del> elsif args.cask? <del> args.named.to_casks <del> else <del> args.named.to_formulae_and_casks <del> end&.sort_by do |formula_or_cask| <del> formula_or_cask.respond_to?(:token) ? formula_or_cask.token : formula_or_cask.name <del> end <add> formulae_and_casks = if args.formula? <add> args.named.to_formulae <add> elsif args.cask? <add> args.named.to_casks <add> else <add> args.named.to_formulae_and_casks <add> end <add> formulae_and_casks = formulae_and_casks&.sort_by do |formula_or_cask| <add> formula_or_cask.respond_to?(:token) ? formula_or_cask.token : formula_or_cask.name <add> end <ide> <ide> limit = args.limit.to_i if args.limit.present? <ide> <ide> def bump <ide> <ide> ambiguous_casks = [] <ide> if !args.formula? && !args.cask? <del> ambiguous_casks = formulae_and_casks <del> .group_by { |item| Livecheck.formula_or_cask_name(item, full_name: true) } <del> .select { |_name, items| items.length > 1 } <del> .values.flatten <del> .select { |item| item.is_a?(Cask::Cask) } <add> ambiguous_casks = formulae_and_casks.group_by { |item| Livecheck.formula_or_cask_name(item, full_name: true) } <add> .values <add> .select { |items| items.length > 1 } <add> .flatten <add> .select { |item| item.is_a?(Cask::Cask) } <ide> end <ide> <ide> ambiguous_names = [] <ide> unless args.full_name? <del> ambiguous_names = (formulae_and_casks - ambiguous_casks) <del> .group_by { |item| Livecheck.formula_or_cask_name(item) } <del> .select { |_name, items| items.length > 1 } <del> .values.flatten <add> ambiguous_names = <add> (formulae_and_casks - ambiguous_casks).group_by { |item| Livecheck.formula_or_cask_name(item) } <add> .values <add> .select { |items| items.length > 1 } <add> .flatten <ide> end <ide> <ide> formulae_and_casks.each_with_index do |formula_or_cask, i| <ide> def bump <ide> end <ide> name = Livecheck.formula_or_cask_name(formula_or_cask) <ide> ambiguous_cask = begin <del> formula_or_cask.is_a?(Cask::Cask) && !args.cask? && Formula[name] ? true : false <add> formula_or_cask.is_a?(Cask::Cask) && !args.cask? && Formula[name] <ide> rescue FormulaUnavailableError <ide> false <ide> end <ide><path>Library/Homebrew/dev-cmd/livecheck.rb <ide> def livecheck <ide> puts ENV["HOMEBREW_LIVECHECK_WATCHLIST"] if ENV["HOMEBREW_LIVECHECK_WATCHLIST"].present? <ide> end <ide> <del> formulae_and_casks_to_check = <del> if args.tap <del> tap = Tap.fetch(args.tap) <del> formulae = args.cask? ? [] : tap.formula_files.map { |path| Formulary.factory(path) } <del> casks = args.formula? ? [] : tap.cask_files.map { |path| Cask::CaskLoader.load(path) } <del> formulae + casks <del> elsif args.installed? <del> formulae = args.cask? ? [] : Formula.installed <del> casks = args.formula? ? [] : Cask::Caskroom.casks <del> formulae + casks <del> elsif args.all? <del> formulae = args.cask? ? [] : Formula.to_a <del> casks = args.formula? ? [] : Cask::Cask.to_a <del> formulae + casks <del> elsif args.named.present? <del> if args.formula? <del> args.named.to_formulae <del> elsif args.cask? <del> args.named.to_casks <del> else <del> args.named.to_formulae_and_casks <del> end <del> elsif File.exist?(WATCHLIST_PATH) <del> begin <del> names = Pathname.new(WATCHLIST_PATH).read.lines <del> .reject { |line| line.start_with?("#") || line.blank? } <del> .map(&:strip) <del> <del> named_args = T.unsafe(CLI::NamedArgs).new(*names, parent: args) <del> named_args.to_formulae_and_casks(ignore_unavailable: true) <del> rescue Errno::ENOENT => e <del> onoe e <del> end <add> formulae_and_casks_to_check = if args.tap <add> tap = Tap.fetch(args.tap) <add> formulae = args.cask? ? [] : tap.formula_files.map { |path| Formulary.factory(path) } <add> casks = args.formula? ? [] : tap.cask_files.map { |path| Cask::CaskLoader.load(path) } <add> formulae + casks <add> elsif args.installed? <add> formulae = args.cask? ? [] : Formula.installed <add> casks = args.formula? ? [] : Cask::Caskroom.casks <add> formulae + casks <add> elsif args.all? <add> formulae = args.cask? ? [] : Formula.to_a <add> casks = args.formula? ? [] : Cask::Cask.to_a <add> formulae + casks <add> elsif args.named.present? <add> if args.formula? <add> args.named.to_formulae <add> elsif args.cask? <add> args.named.to_casks <ide> else <del> raise UsageError, "A watchlist file is required when no arguments are given." <del> end&.sort_by do |formula_or_cask| <del> formula_or_cask.respond_to?(:token) ? formula_or_cask.token : formula_or_cask.name <add> args.named.to_formulae_and_casks <add> end <add> elsif File.exist?(WATCHLIST_PATH) <add> begin <add> names = Pathname.new(WATCHLIST_PATH).read.lines <add> .reject { |line| line.start_with?("#") || line.blank? } <add> .map(&:strip) <add> <add> named_args = T.unsafe(CLI::NamedArgs).new(*names, parent: args) <add> named_args.to_formulae_and_casks(ignore_unavailable: true) <add> rescue Errno::ENOENT => e <add> onoe e <ide> end <add> else <add> raise UsageError, "A watchlist file is required when no arguments are given." <add> end <add> formulae_and_casks_to_check = formulae_and_casks_to_check.sort_by do |formula_or_cask| <add> formula_or_cask.respond_to?(:token) ? formula_or_cask.token : formula_or_cask.name <add> end <ide> <ide> raise UsageError, "No formulae or casks to check." if formulae_and_casks_to_check.blank? <ide> <ide><path>Library/Homebrew/livecheck/livecheck.rb <ide> def run_checks( <ide> <ide> ambiguous_casks = [] <ide> if handle_name_conflict <del> ambiguous_casks = formulae_and_casks_to_check <del> .group_by { |item| formula_or_cask_name(item, full_name: true) } <del> .select { |_name, items| items.length > 1 } <del> .values.flatten <del> .select { |item| item.is_a?(Cask::Cask) } <add> ambiguous_casks = formulae_and_casks_to_check.group_by { |item| formula_or_cask_name(item, full_name: true) } <add> .values <add> .select { |items| items.length > 1 } <add> .flatten <add> .select { |item| item.is_a?(Cask::Cask) } <ide> end <ide> <ide> ambiguous_names = [] <ide> unless full_name <del> ambiguous_names = (formulae_and_casks_to_check - ambiguous_casks) <del> .group_by { |item| formula_or_cask_name(item) } <del> .select { |_name, items| items.length > 1 } <del> .values.flatten <add> ambiguous_names = <add> (formulae_and_casks_to_check - ambiguous_casks).group_by { |item| formula_or_cask_name(item) } <add> .values <add> .select { |items| items.length > 1 } <add> .flatten <ide> end <ide> <ide> has_a_newer_upstream_version = T.let(false, T::Boolean)
3
Go
Go
use object-literal for some structs
f0be4d126dacb19a35046536b041a5989ff0dc95
<ide><path>libnetwork/drivers/overlay/ov_network.go <ide> func checkOverlap(nw *net.IPNet) error { <ide> } <ide> <ide> func (n *network) restoreSubnetSandbox(s *subnet, brName, vxlanName string) error { <del> sbox := n.sbox <del> <ide> // restore overlay osl sandbox <del> Ifaces := make(map[string][]osl.IfaceOption) <del> brIfaceOption := make([]osl.IfaceOption, 2) <del> brIfaceOption = append(brIfaceOption, sbox.InterfaceOptions().Address(s.gwIP)) <del> brIfaceOption = append(brIfaceOption, sbox.InterfaceOptions().Bridge(true)) <del> Ifaces[brName+"+br"] = brIfaceOption <del> <del> err := sbox.Restore(Ifaces, nil, nil, nil) <del> if err != nil { <add> ifaces := map[string][]osl.IfaceOption{ <add> brName + "+br": { <add> n.sbox.InterfaceOptions().Address(s.gwIP), <add> n.sbox.InterfaceOptions().Bridge(true), <add> }, <add> } <add> if err := n.sbox.Restore(ifaces, nil, nil, nil); err != nil { <ide> return err <ide> } <ide> <del> Ifaces = make(map[string][]osl.IfaceOption) <del> vxlanIfaceOption := make([]osl.IfaceOption, 1) <del> vxlanIfaceOption = append(vxlanIfaceOption, sbox.InterfaceOptions().Master(brName)) <del> Ifaces[vxlanName+"+vxlan"] = vxlanIfaceOption <del> return sbox.Restore(Ifaces, nil, nil, nil) <add> ifaces = map[string][]osl.IfaceOption{ <add> vxlanName + "+vxlan": { <add> n.sbox.InterfaceOptions().Master(brName), <add> }, <add> } <add> return n.sbox.Restore(ifaces, nil, nil, nil) <ide> } <ide> <ide> func (n *network) setupSubnetSandbox(s *subnet, brName, vxlanName string) error { <ide><path>libnetwork/sandbox.go <ide> func (sb *sandbox) restoreOslSandbox() error { <ide> // restore osl sandbox <ide> Ifaces := make(map[string][]osl.IfaceOption) <ide> for _, ep := range sb.endpoints { <del> var ifaceOptions []osl.IfaceOption <ide> ep.Lock() <ide> joinInfo := ep.joinInfo <ide> i := ep.iface <ide> func (sb *sandbox) restoreOslSandbox() error { <ide> continue <ide> } <ide> <del> ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().Address(i.addr), sb.osSbox.InterfaceOptions().Routes(i.routes)) <add> ifaceOptions := []osl.IfaceOption{ <add> sb.osSbox.InterfaceOptions().Address(i.addr), <add> sb.osSbox.InterfaceOptions().Routes(i.routes), <add> } <ide> if i.addrv6 != nil && i.addrv6.IP.To16() != nil { <ide> ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().AddressIPv6(i.addrv6)) <ide> } <ide> func (sb *sandbox) restoreOslSandbox() error { <ide> if len(i.llAddrs) != 0 { <ide> ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().LinkLocalAddresses(i.llAddrs)) <ide> } <del> Ifaces[fmt.Sprintf("%s+%s", i.srcName, i.dstPrefix)] = ifaceOptions <add> Ifaces[i.srcName+i.dstPrefix] = ifaceOptions <ide> if joinInfo != nil { <ide> routes = append(routes, joinInfo.StaticRoutes...) <ide> } <ide> func (sb *sandbox) restoreOslSandbox() error { <ide> } <ide> <ide> // restore osl sandbox <del> err := sb.osSbox.Restore(Ifaces, routes, gwep.joinInfo.gw, gwep.joinInfo.gw6) <del> return err <add> return sb.osSbox.Restore(Ifaces, routes, gwep.joinInfo.gw, gwep.joinInfo.gw6) <ide> } <ide> <ide> func (sb *sandbox) populateNetworkResources(ep *endpoint) error {
2
Java
Java
add an alwaysinclude property to tilesviewresolver
cfa3d358d5836bcfaad1f6ce9287ccf78ad7740f
<ide><path>spring-webmvc-tiles2/src/main/java/org/springframework/web/servlet/view/tiles2/TilesView.java <ide> /* <del> * Copyright 2002-2013 the original author or authors. <add> * Copyright 2002-2014 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * {@link TilesConfigurer} bean definition in the application context. <ide> * <ide> * @author Juergen Hoeller <add> * @author Sebastien Deleuze <ide> * @since 2.5 <ide> * @see #setUrl <ide> * @see TilesConfigurer <ide> */ <ide> public class TilesView extends AbstractUrlBasedView { <ide> <add> private boolean alwaysInclude = false; <add> <add> <add> /** <add> * Specify whether to always include the view rather than forward to it. <add> * <p>Default is "false". Switch this flag on to enforce the use of a <add> * Servlet include, even if a forward would be possible. <add> * @see TilesViewResolver#setAlwaysInclude(Boolean) <add> * @since 4.1.2 <add> */ <add> public void setAlwaysInclude(boolean alwaysInclude) { <add> this.alwaysInclude = alwaysInclude; <add> } <add> <ide> @Override <ide> public boolean checkResource(final Locale locale) throws Exception { <ide> TilesContainer container = ServletUtil.getContainer(getServletContext()); <ide> protected void renderMergedOutputModel( <ide> <ide> exposeModelAsRequestAttributes(model, request); <ide> JstlUtils.exposeLocalizationContext(new RequestContext(request, servletContext)); <add> if (this.alwaysInclude) { <add> ServletUtil.setForceInclude(request, true); <add> } <ide> container.render(getUrl(), request, response); <ide> } <ide> <ide><path>spring-webmvc-tiles2/src/main/java/org/springframework/web/servlet/view/tiles2/TilesViewResolver.java <ide> /* <del> * Copyright 2002-2009 the original author or authors. <add> * Copyright 2002-2014 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> <ide> package org.springframework.web.servlet.view.tiles2; <ide> <add>import org.springframework.web.servlet.view.AbstractUrlBasedView; <ide> import org.springframework.web.servlet.view.UrlBasedViewResolver; <ide> <ide> /** <ide> * a non-null View object if the template was actually found. <ide> * <ide> * @author Juergen Hoeller <add> * @author Sebastien Deleuze <ide> * @since 3.0 <ide> * @see #setViewClass <ide> * @see #setPrefix <ide> */ <ide> public class TilesViewResolver extends UrlBasedViewResolver { <ide> <add> private Boolean alwaysInclude; <add> <add> <ide> public TilesViewResolver() { <ide> setViewClass(requiredViewClass()); <ide> } <ide> <add> /** <add> * Specify whether to always include the view rather than forward to it. <add> * <p>Default is "false". Switch this flag on to enforce the use of a <add> * Servlet include, even if a forward would be possible. <add> * @see TilesView#setAlwaysInclude <add> * @since 4.1.2 <add> */ <add> public void setAlwaysInclude(Boolean alwaysInclude) { <add> this.alwaysInclude = alwaysInclude; <add> } <add> <ide> /** <ide> * Requires {@link TilesView}. <ide> */ <ide> protected Class<?> requiredViewClass() { <ide> return TilesView.class; <ide> } <ide> <add> @Override <add> protected AbstractUrlBasedView buildView(String viewName) throws Exception { <add> TilesView view = (TilesView) super.buildView(viewName); <add> if (this.alwaysInclude != null) { <add> view.setAlwaysInclude(this.alwaysInclude); <add> } <add> return view; <add> } <add> <ide> } <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/view/tiles3/TilesView.java <ide> /* <del> * Copyright 2002-2013 the original author or authors. <add> * Copyright 2002-2014 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import org.apache.tiles.TilesContainer; <ide> import org.apache.tiles.access.TilesAccess; <ide> import org.apache.tiles.renderer.DefinitionRenderer; <add>import org.apache.tiles.request.AbstractRequest; <ide> import org.apache.tiles.request.ApplicationContext; <ide> import org.apache.tiles.request.Request; <ide> import org.apache.tiles.request.render.Renderer; <ide> * @author Nicolas Le Bas <ide> * @author mick semb wever <ide> * @author Rossen Stoyanchev <add> * @author Sebastien Deleuze <ide> * @since 3.2 <ide> */ <ide> public class TilesView extends AbstractUrlBasedView { <ide> public class TilesView extends AbstractUrlBasedView { <ide> <ide> private boolean exposeJstlAttributes = true; <ide> <add> private boolean alwaysInclude = false; <add> <ide> private ApplicationContext applicationContext; <ide> <ide> <ide> protected void setExposeJstlAttributes(boolean exposeJstlAttributes) { <ide> this.exposeJstlAttributes = exposeJstlAttributes; <ide> } <ide> <add> /** <add> * Specify whether to always include the view rather than forward to it. <add> * <p>Default is "false". Switch this flag on to enforce the use of a <add> * Servlet include, even if a forward would be possible. <add> * @see TilesViewResolver#setAlwaysInclude(Boolean) <add> * @since 4.1.2 <add> */ <add> public void setAlwaysInclude(boolean alwaysInclude) { <add> this.alwaysInclude = alwaysInclude; <add> } <add> <ide> @Override <ide> public void afterPropertiesSet() throws Exception { <ide> super.afterPropertiesSet(); <ide> public void afterPropertiesSet() throws Exception { <ide> } <ide> } <ide> <del> <ide> @Override <ide> public boolean checkResource(final Locale locale) throws Exception { <ide> HttpServletRequest servletRequest = null; <ide> protected void renderMergedOutputModel(Map<String, Object> model, HttpServletReq <ide> if (this.exposeJstlAttributes) { <ide> JstlUtils.exposeLocalizationContext(new RequestContext(request, getServletContext())); <ide> } <add> if (this.alwaysInclude) { <add> request.setAttribute(AbstractRequest.FORCE_INCLUDE_ATTRIBUTE_NAME, true); <add> } <ide> <ide> Request tilesRequest = createTilesRequest(request, response); <ide> this.renderer.render(getUrl(), tilesRequest); <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/view/tiles3/TilesViewResolver.java <ide> * @author Nicolas Le Bas <ide> * @author Rossen Stoyanchev <ide> * @author Juergen Hoeller <add> * @author Sebastien Deleuze <ide> * @since 3.2 <ide> */ <ide> public class TilesViewResolver extends UrlBasedViewResolver { <ide> <ide> private Renderer renderer; <ide> <add> private Boolean alwaysInclude; <add> <ide> <ide> public TilesViewResolver() { <ide> setViewClass(requiredViewClass()); <ide> } <ide> <del> <del> /** <del> * Requires {@link TilesView}. <del> */ <del> @Override <del> protected Class<?> requiredViewClass() { <del> return TilesView.class; <del> } <del> <ide> /** <ide> * Set the {@link Renderer} to use. If not specified, a default <ide> * {@link org.apache.tiles.renderer.DefinitionRenderer} will be used. <ide> public void setRenderer(Renderer renderer) { <ide> this.renderer = renderer; <ide> } <ide> <add> /** <add> * Specify whether to always include the view rather than forward to it. <add> * <p>Default is "false". Switch this flag on to enforce the use of a <add> * Servlet include, even if a forward would be possible. <add> * @see TilesView#setAlwaysInclude <add> * @since 4.1.2 <add> */ <add> public void setAlwaysInclude(Boolean alwaysInclude) { <add> this.alwaysInclude = alwaysInclude; <add> } <add> <add> /** <add> * Requires {@link TilesView}. <add> */ <add> @Override <add> protected Class<?> requiredViewClass() { <add> return TilesView.class; <add> } <ide> <ide> @Override <ide> protected TilesView buildView(String viewName) throws Exception { <ide> TilesView view = (TilesView) super.buildView(viewName); <ide> if (this.renderer != null) { <ide> view.setRenderer(this.renderer); <ide> } <add> if (this.alwaysInclude != null) { <add> view.setAlwaysInclude(this.alwaysInclude); <add> } <ide> return view; <ide> } <ide> <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/view/tiles3/TilesViewTests.java <ide> /* <del> * Copyright 2002-2013 the original author or authors. <add> * Copyright 2002-2014 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import java.util.HashMap; <ide> import java.util.Map; <ide> <add>import org.apache.tiles.request.AbstractRequest; <ide> import org.apache.tiles.request.Request; <ide> import org.apache.tiles.request.render.Renderer; <ide> import org.junit.Before; <ide> * Test fixture for {@link TilesView}. <ide> * <ide> * @author mick semb wever <add> * @author Sebastien Deleuze <ide> */ <ide> public class TilesViewTests { <ide> <ide> public void setUp() throws Exception { <ide> } <ide> <ide> @Test <del> public void testRender() throws Exception { <add> public void render() throws Exception { <ide> Map<String, Object> model = new HashMap<String, Object>(); <ide> model.put("modelAttribute", "modelValue"); <ide> view.render(model, request, response); <ide> assertEquals("modelValue", request.getAttribute("modelAttribute")); <ide> verify(renderer).render(eq(VIEW_PATH), isA(Request.class)); <ide> } <ide> <add> @Test <add> public void alwaysIncludeDefaults() throws Exception { <add> view.render(new HashMap<String, Object>(), request, response); <add> assertNull(request.getAttribute(AbstractRequest.FORCE_INCLUDE_ATTRIBUTE_NAME)); <add> } <add> <add> @Test <add> public void alwaysIncludeEnabled() throws Exception { <add> view.setAlwaysInclude(true); <add> view.render(new HashMap<String, Object>(), request, response); <add> assertTrue((Boolean)request.getAttribute(AbstractRequest.FORCE_INCLUDE_ATTRIBUTE_NAME)); <add> } <add> <ide> }
5
Javascript
Javascript
add doc for refreshcontrol on the website
f5062d0840edff52c6a4c96ab14bb950a9bea018
<ide><path>Libraries/Components/ScrollView/ScrollView.js <ide> var ScrollView = React.createClass({ <ide> /** <ide> * A RefreshControl component, used to provide pull-to-refresh <ide> * functionality for the ScrollView. <add> * <add> * See [RefreshControl](http://facebook.github.io/react-native/docs/refreshcontrol.html). <ide> */ <ide> refreshControl: PropTypes.element, <ide>
1
Python
Python
add cygwin to the x86 feature tests
e61028b7aa33872b9aa2259961eca2f888b301ce
<ide><path>numpy/core/tests/test_cpu_features.py <ide> def load_flags_auxv(self): <ide> ) <ide> <ide> is_linux = sys.platform.startswith('linux') <add>is_cygwin = sys.platform.startswith('cygwin') <ide> machine = platform.machine() <ide> is_x86 = re.match("^(amd64|x86|i386|i686)", machine, re.IGNORECASE) <del>@pytest.mark.skipif(not is_linux or not is_x86, reason="Only for Linux and x86") <add>@pytest.mark.skipif( <add> not (is_linux or is_cygwin) or not is_x86, reason="Only for Linux and x86" <add>) <ide> class Test_X86_Features(AbstractTest): <ide> features = [ <ide> "MMX", "SSE", "SSE2", "SSE3", "SSSE3", "SSE41", "POPCNT", "SSE42",
1
PHP
PHP
apply fixes from styleci
5cd45bf3f173740b8987895701932986253987e6
<ide><path>src/Illuminate/Database/Schema/Grammars/SqlServerGrammar.php <ide> public function compileAdd(Blueprint $blueprint, Fluent $command) <ide> */ <ide> public function compilePrimary(Blueprint $blueprint, Fluent $command) <ide> { <del> return sprintf("alter table %s add constraint %s primary key (%s)", <add> return sprintf('alter table %s add constraint %s primary key (%s)', <ide> $this->wrapTable($blueprint), <ide> $this->wrap($command->index), <ide> $this->columnize($command->columns) <ide> public function compilePrimary(Blueprint $blueprint, Fluent $command) <ide> */ <ide> public function compileUnique(Blueprint $blueprint, Fluent $command) <ide> { <del> return sprintf("create unique index %s on %s (%s)", <add> return sprintf('create unique index %s on %s (%s)', <ide> $this->wrap($command->index), <ide> $this->wrapTable($blueprint), <ide> $this->columnize($command->columns) <ide> public function compileUnique(Blueprint $blueprint, Fluent $command) <ide> */ <ide> public function compileIndex(Blueprint $blueprint, Fluent $command) <ide> { <del> return sprintf("create index %s on %s (%s)", <add> return sprintf('create index %s on %s (%s)', <ide> $this->wrap($command->index), <ide> $this->wrapTable($blueprint), <ide> $this->columnize($command->columns)
1
Text
Text
add betterment to companies list
9331db0d7c7d307b2486e30e28f2c7fd91a5a254
<ide><path>README.md <ide> Currently **officially** using Airflow: <ide> 1. [BBM](https://www.bbm.com/) <ide> 1. [Bellhops](https://github.com/bellhops) <ide> 1. [BelugaDB](https://belugadb.com) [[@fabio-nukui](https://github.com/fabio-nukui) & [@joao-sallaberry](http://github.com/joao-sallaberry) & [@lucianoviola](https://github.com/lucianoviola) & [@tmatuki](https://github.com/tmatuki)] <add>1. [Betterment](https://www.betterment.com/) [[@betterment](https://github.com/Betterment)] <ide> 1. [BlaBlaCar](https://www.blablacar.com) [[@puckel](https://github.com/puckel) & [@wmorin](https://github.com/wmorin)] <ide> 1. [Bloc](https://www.bloc.io) [[@dpaola2](https://github.com/dpaola2)] <ide> 1. [Blue Yonder](http://www.blue-yonder.com) [[@blue-yonder](https://github.com/blue-yonder)]
1
Mixed
Go
return remote api errors as json
322e2a7d059a81617b593cf6ece2cfd9f6d4ea03
<ide><path>api/server/httputils/errors.go <ide> import ( <ide> "strings" <ide> <ide> "github.com/Sirupsen/logrus" <add> "github.com/docker/engine-api/types" <add> "github.com/docker/engine-api/types/versions" <add> "github.com/gorilla/mux" <ide> ) <ide> <ide> // httpStatusError is an interface <ide> func GetHTTPErrorStatusCode(err error) int { <ide> return statusCode <ide> } <ide> <del>// WriteError decodes a specific docker error and sends it in the response. <del>func WriteError(w http.ResponseWriter, err error) { <del> if err == nil || w == nil { <del> logrus.WithFields(logrus.Fields{"error": err, "writer": w}).Error("unexpected HTTP error handling") <del> return <add>// MakeErrorHandler makes an HTTP handler that decodes a Docker error and <add>// returns it in the response. <add>func MakeErrorHandler(err error) http.HandlerFunc { <add> return func(w http.ResponseWriter, r *http.Request) { <add> statusCode := GetHTTPErrorStatusCode(err) <add> vars := mux.Vars(r) <add> if vars["version"] == "" || versions.GreaterThan(vars["version"], "1.23") { <add> response := &types.ErrorResponse{ <add> Message: err.Error(), <add> } <add> WriteJSON(w, statusCode, response) <add> } else { <add> http.Error(w, err.Error(), statusCode) <add> } <ide> } <del> <del> statusCode := GetHTTPErrorStatusCode(err) <del> http.Error(w, err.Error(), statusCode) <ide> } <ide><path>api/server/server.go <ide> package server <ide> <ide> import ( <ide> "crypto/tls" <add> "fmt" <ide> "net" <ide> "net/http" <ide> "strings" <ide> import ( <ide> "github.com/docker/docker/api/server/httputils" <ide> "github.com/docker/docker/api/server/middleware" <ide> "github.com/docker/docker/api/server/router" <add> "github.com/docker/docker/errors" <ide> "github.com/gorilla/mux" <ide> "golang.org/x/net/context" <ide> ) <ide> func (s *Server) makeHTTPHandler(handler httputils.APIFunc) http.HandlerFunc { <ide> <ide> if err := handlerFunc(ctx, w, r, vars); err != nil { <ide> logrus.Errorf("Handler for %s %s returned error: %v", r.Method, r.URL.Path, err) <del> httputils.WriteError(w, err) <add> httputils.MakeErrorHandler(err)(w, r) <ide> } <ide> } <ide> } <ide> func (s *Server) createMux() *mux.Router { <ide> } <ide> } <ide> <add> err := errors.NewRequestNotFoundError(fmt.Errorf("page not found")) <add> notFoundHandler := httputils.MakeErrorHandler(err) <add> m.HandleFunc(versionMatcher+"/{path:.*}", notFoundHandler) <add> m.NotFoundHandler = notFoundHandler <add> <ide> return m <ide> } <ide> <ide><path>docs/reference/api/docker_remote_api.md <ide> This section lists each version from latest to oldest. Each listing includes a <ide> * `POST /images/(name)/tag` no longer has a `force` query parameter. <ide> * `GET /images/search` now supports maximum returned search results `limit`. <ide> * `POST /containers/{name:.*}/copy` is now removed and errors out starting from this API version. <add>* API errors are now returned as JSON instead of plain text. <ide> <ide> ### v1.23 API changes <ide> <ide> end point now returns the new boolean fields `CpuCfsPeriod`, `CpuCfsQuota`, and <ide> * `CgroupParent` can be passed in the host config to setup container cgroups under a specific cgroup. <ide> * `POST /build` closing the HTTP request cancels the build <ide> * `POST /containers/(id)/exec` includes `Warnings` field to response. <del> <ide><path>docs/reference/api/docker_remote_api_v1.24.md <ide> weight=-5 <ide> - When the client API version is newer than the daemon's, these calls return an HTTP <ide> `400 Bad Request` error message. <ide> <del># 2. Endpoints <add># 2. Errors <ide> <del>## 2.1 Containers <add>The Remote API uses standard HTTP status codes to indicate the success or failure of the API call. The body of the response will be JSON in the following format: <add> <add> { <add> "message": "page not found" <add> } <add> <add>The status codes that are returned for each endpoint are specified in the endpoint documentation below. <add> <add># 3. Endpoints <add> <add>## 3.1 Containers <ide> <ide> ### List containers <ide> <ide> Status Codes: <ide> - no such file or directory (**path** resource does not exist) <ide> - **500** – server error <ide> <del>## 2.2 Images <add>## 3.2 Images <ide> <ide> ### List Images <ide> <ide> Status Codes: <ide> - **200** – no error <ide> - **500** – server error <ide> <del>## 2.3 Misc <add>## 3.3 Misc <ide> <ide> ### Check auth configuration <ide> <ide> Status Codes: <ide> - **404** – no such exec instance <ide> - **500** - server error <ide> <del>## 2.4 Volumes <add>## 3.4 Volumes <ide> <ide> ### List volumes <ide> <ide> Status Codes <ide> - **409** - volume is in use and cannot be removed <ide> - **500** - server error <ide> <del>## 2.5 Networks <add>## 3.5 Networks <ide> <ide> ### List networks <ide> <ide> Status Codes <ide> - **404** - no such network <ide> - **500** - server error <ide> <del># 3. Going further <add># 4. Going further <ide> <del>## 3.1 Inside `docker run` <add>## 4.1 Inside `docker run` <ide> <ide> As an example, the `docker run` command line makes the following API calls: <ide> <ide> As an example, the `docker run` command line makes the following API calls: <ide> <ide> - If in detached mode or only `stdin` is attached, display the container's id. <ide> <del>## 3.2 Hijacking <add>## 4.2 Hijacking <ide> <ide> In this version of the API, `/attach`, uses hijacking to transport `stdin`, <ide> `stdout`, and `stderr` on the same socket. <ide> When Docker daemon detects the `Upgrade` header, it switches its status code <ide> from **200 OK** to **101 UPGRADED** and resends the same headers. <ide> <ide> <del>## 3.3 CORS Requests <add>## 4.3 CORS Requests <ide> <ide> To set cross origin requests to the remote api please give values to <ide> `--api-cors-header` when running Docker in daemon mode. Set * (asterisk) allows all, <ide><path>integration-cli/docker_api_attach_test.go <ide> func (s *DockerSuite) TestGetContainersWsAttachContainerNotFound(c *check.C) { <ide> status, body, err := sockRequest("GET", "/containers/doesnotexist/attach/ws", nil) <ide> c.Assert(status, checker.Equals, http.StatusNotFound) <ide> c.Assert(err, checker.IsNil) <del> expected := "No such container: doesnotexist\n" <del> c.Assert(string(body), checker.Contains, expected) <add> expected := "No such container: doesnotexist" <add> c.Assert(getErrorMessage(c, body), checker.Contains, expected) <ide> } <ide> <ide> func (s *DockerSuite) TestPostContainersAttach(c *check.C) { <ide><path>integration-cli/docker_api_auth_test.go <ide> func (s *DockerSuite) TestAuthApi(c *check.C) { <ide> Password: "no-password", <ide> } <ide> <del> expected := "Get https://registry-1.docker.io/v2/: unauthorized: incorrect username or password\n" <add> expected := "Get https://registry-1.docker.io/v2/: unauthorized: incorrect username or password" <ide> status, body, err := sockRequest("POST", "/auth", config) <ide> c.Assert(err, check.IsNil) <ide> c.Assert(status, check.Equals, http.StatusUnauthorized) <del> c.Assert(string(body), checker.Contains, expected, check.Commentf("Expected: %v, got: %v", expected, string(body))) <add> msg := getErrorMessage(c, body) <add> c.Assert(msg, checker.Contains, expected, check.Commentf("Expected: %v, got: %v", expected, msg)) <ide> } <ide><path>integration-cli/docker_api_containers_test.go <ide> func (s *DockerSuite) TestContainerApiBadPort(c *check.C) { <ide> jsonData := bytes.NewBuffer(nil) <ide> json.NewEncoder(jsonData).Encode(config) <ide> <del> status, b, err := sockRequest("POST", "/containers/create", config) <add> status, body, err := sockRequest("POST", "/containers/create", config) <ide> c.Assert(err, checker.IsNil) <ide> c.Assert(status, checker.Equals, http.StatusInternalServerError) <del> c.Assert(strings.TrimSpace(string(b)), checker.Equals, `Invalid port specification: "aa80"`, check.Commentf("Incorrect error msg: %s", string(b))) <add> c.Assert(getErrorMessage(c, body), checker.Equals, `Invalid port specification: "aa80"`, check.Commentf("Incorrect error msg: %s", body)) <ide> } <ide> <ide> func (s *DockerSuite) TestContainerApiCreate(c *check.C) { <ide> func (s *DockerSuite) TestContainerApiCreate(c *check.C) { <ide> func (s *DockerSuite) TestContainerApiCreateEmptyConfig(c *check.C) { <ide> config := map[string]interface{}{} <ide> <del> status, b, err := sockRequest("POST", "/containers/create", config) <add> status, body, err := sockRequest("POST", "/containers/create", config) <ide> c.Assert(err, checker.IsNil) <ide> c.Assert(status, checker.Equals, http.StatusInternalServerError) <ide> <del> expected := "Config cannot be empty in order to create a container\n" <del> c.Assert(string(b), checker.Equals, expected) <add> expected := "Config cannot be empty in order to create a container" <add> c.Assert(getErrorMessage(c, body), checker.Equals, expected) <ide> } <ide> <ide> func (s *DockerSuite) TestContainerApiCreateMultipleNetworksConfig(c *check.C) { <ide> func (s *DockerSuite) TestContainerApiCreateMultipleNetworksConfig(c *check.C) { <ide> }, <ide> } <ide> <del> status, b, err := sockRequest("POST", "/containers/create", config) <add> status, body, err := sockRequest("POST", "/containers/create", config) <ide> c.Assert(err, checker.IsNil) <ide> c.Assert(status, checker.Equals, http.StatusBadRequest) <add> msg := getErrorMessage(c, body) <ide> // network name order in error message is not deterministic <del> c.Assert(string(b), checker.Contains, "Container cannot be connected to network endpoints") <del> c.Assert(string(b), checker.Contains, "net1") <del> c.Assert(string(b), checker.Contains, "net2") <del> c.Assert(string(b), checker.Contains, "net3") <add> c.Assert(msg, checker.Contains, "Container cannot be connected to network endpoints") <add> c.Assert(msg, checker.Contains, "net1") <add> c.Assert(msg, checker.Contains, "net2") <add> c.Assert(msg, checker.Contains, "net3") <ide> } <ide> <ide> func (s *DockerSuite) TestContainerApiCreateWithHostName(c *check.C) { <ide> func (s *DockerSuite) TestContainerApiDeleteNotExist(c *check.C) { <ide> status, body, err := sockRequest("DELETE", "/containers/doesnotexist", nil) <ide> c.Assert(err, checker.IsNil) <ide> c.Assert(status, checker.Equals, http.StatusNotFound) <del> c.Assert(string(body), checker.Matches, "No such container: doesnotexist\n") <add> c.Assert(getErrorMessage(c, body), checker.Matches, "No such container: doesnotexist") <ide> } <ide> <ide> func (s *DockerSuite) TestContainerApiDeleteForce(c *check.C) { <ide> func (s *DockerSuite) TestPostContainersCreateWithWrongCpusetValues(c *check.C) <ide> status, body, err := sockRequest("POST", "/containers/create?name="+name, c1) <ide> c.Assert(err, checker.IsNil) <ide> c.Assert(status, checker.Equals, http.StatusInternalServerError) <del> expected := "Invalid value 1-42,, for cpuset cpus\n" <del> c.Assert(string(body), checker.Equals, expected) <add> expected := "Invalid value 1-42,, for cpuset cpus" <add> c.Assert(getErrorMessage(c, body), checker.Equals, expected) <ide> <ide> c2 := struct { <ide> Image string <ide> func (s *DockerSuite) TestPostContainersCreateWithWrongCpusetValues(c *check.C) <ide> status, body, err = sockRequest("POST", "/containers/create?name="+name, c2) <ide> c.Assert(err, checker.IsNil) <ide> c.Assert(status, checker.Equals, http.StatusInternalServerError) <del> expected = "Invalid value 42-3,1-- for cpuset mems\n" <del> c.Assert(string(body), checker.Equals, expected) <add> expected = "Invalid value 42-3,1-- for cpuset mems" <add> c.Assert(getErrorMessage(c, body), checker.Equals, expected) <ide> } <ide> <ide> func (s *DockerSuite) TestPostContainersCreateShmSizeNegative(c *check.C) { <ide> func (s *DockerSuite) TestPostContainersCreateShmSizeNegative(c *check.C) { <ide> status, body, err := sockRequest("POST", "/containers/create", config) <ide> c.Assert(err, check.IsNil) <ide> c.Assert(status, check.Equals, http.StatusInternalServerError) <del> c.Assert(string(body), checker.Contains, "SHM size must be greater than 0") <add> c.Assert(getErrorMessage(c, body), checker.Contains, "SHM size must be greater than 0") <ide> } <ide> <ide> func (s *DockerSuite) TestPostContainersCreateShmSizeHostConfigOmitted(c *check.C) { <ide> func (s *DockerSuite) TestPostContainersCreateWithOomScoreAdjInvalidRange(c *che <ide> status, b, err := sockRequest("POST", "/containers/create?name="+name, config) <ide> c.Assert(err, check.IsNil) <ide> c.Assert(status, check.Equals, http.StatusInternalServerError) <add> <ide> expected := "Invalid value 1001, range for oom score adj is [-1000, 1000]" <del> if !strings.Contains(string(b), expected) { <del> c.Fatalf("Expected output to contain %q, got %q", expected, string(b)) <add> msg := getErrorMessage(c, b) <add> if !strings.Contains(msg, expected) { <add> c.Fatalf("Expected output to contain %q, got %q", expected, msg) <ide> } <ide> <ide> config = struct { <ide> func (s *DockerSuite) TestPostContainersCreateWithOomScoreAdjInvalidRange(c *che <ide> c.Assert(err, check.IsNil) <ide> c.Assert(status, check.Equals, http.StatusInternalServerError) <ide> expected = "Invalid value -1001, range for oom score adj is [-1000, 1000]" <del> if !strings.Contains(string(b), expected) { <del> c.Fatalf("Expected output to contain %q, got %q", expected, string(b)) <add> msg = getErrorMessage(c, b) <add> if !strings.Contains(msg, expected) { <add> c.Fatalf("Expected output to contain %q, got %q", expected, msg) <ide> } <ide> } <ide> <ide><path>integration-cli/docker_api_create_test.go <ide> package main <ide> <ide> import ( <ide> "net/http" <del> "strings" <ide> <ide> "github.com/docker/docker/pkg/integration/checker" <ide> "github.com/go-check/check" <ide> func (s *DockerSuite) TestApiCreateWithNotExistImage(c *check.C) { <ide> "Volumes": map[string]struct{}{"/tmp": {}}, <ide> } <ide> <del> status, resp, err := sockRequest("POST", "/containers/create?name="+name, config) <add> status, body, err := sockRequest("POST", "/containers/create?name="+name, config) <ide> c.Assert(err, check.IsNil) <ide> c.Assert(status, check.Equals, http.StatusNotFound) <ide> expected := "No such image: test456:v1" <del> c.Assert(strings.TrimSpace(string(resp)), checker.Contains, expected) <add> c.Assert(getErrorMessage(c, body), checker.Contains, expected) <ide> <ide> config2 := map[string]interface{}{ <ide> "Image": "test456", <ide> "Volumes": map[string]struct{}{"/tmp": {}}, <ide> } <ide> <del> status, resp, err = sockRequest("POST", "/containers/create?name="+name, config2) <add> status, body, err = sockRequest("POST", "/containers/create?name="+name, config2) <ide> c.Assert(err, check.IsNil) <ide> c.Assert(status, check.Equals, http.StatusNotFound) <ide> expected = "No such image: test456:latest" <del> c.Assert(strings.TrimSpace(string(resp)), checker.Equals, expected) <add> c.Assert(getErrorMessage(c, body), checker.Equals, expected) <ide> <ide> config3 := map[string]interface{}{ <ide> "Image": "sha256:0cb40641836c461bc97c793971d84d758371ed682042457523e4ae701efeaaaa", <ide> } <ide> <del> status, resp, err = sockRequest("POST", "/containers/create?name="+name, config3) <add> status, body, err = sockRequest("POST", "/containers/create?name="+name, config3) <ide> c.Assert(err, check.IsNil) <ide> c.Assert(status, check.Equals, http.StatusNotFound) <ide> expected = "No such image: sha256:0cb40641836c461bc97c793971d84d758371ed682042457523e4ae701efeaaaa" <del> c.Assert(strings.TrimSpace(string(resp)), checker.Equals, expected) <add> c.Assert(getErrorMessage(c, body), checker.Equals, expected) <ide> <ide> } <ide><path>integration-cli/docker_api_exec_test.go <ide> func (s *DockerSuite) TestExecApiCreateNoCmd(c *check.C) { <ide> c.Assert(status, checker.Equals, http.StatusInternalServerError) <ide> <ide> comment := check.Commentf("Expected message when creating exec command with no Cmd specified") <del> c.Assert(string(body), checker.Contains, "No exec command specified", comment) <add> c.Assert(getErrorMessage(c, body), checker.Contains, "No exec command specified", comment) <ide> } <ide> <ide> func (s *DockerSuite) TestExecApiCreateNoValidContentType(c *check.C) { <ide> func (s *DockerSuite) TestExecApiCreateNoValidContentType(c *check.C) { <ide> c.Assert(err, checker.IsNil) <ide> <ide> comment := check.Commentf("Expected message when creating exec command with invalid Content-Type specified") <del> c.Assert(string(b), checker.Contains, "Content-Type specified", comment) <add> c.Assert(getErrorMessage(c, b), checker.Contains, "Content-Type specified", comment) <ide> } <ide> <ide> func (s *DockerSuite) TestExecApiCreateContainerPaused(c *check.C) { <ide> func (s *DockerSuite) TestExecApiCreateContainerPaused(c *check.C) { <ide> c.Assert(status, checker.Equals, http.StatusConflict) <ide> <ide> comment := check.Commentf("Expected message when creating exec command with Container %s is paused", name) <del> c.Assert(string(body), checker.Contains, "Container "+name+" is paused, unpause the container before exec", comment) <add> c.Assert(getErrorMessage(c, body), checker.Contains, "Container "+name+" is paused, unpause the container before exec", comment) <ide> } <ide> <ide> func (s *DockerSuite) TestExecApiStart(c *check.C) { <ide><path>integration-cli/docker_api_logs_test.go <ide> func (s *DockerSuite) TestLogsApiNoStdoutNorStderr(c *check.C) { <ide> c.Assert(err, checker.IsNil) <ide> <ide> expected := "Bad parameters: you must choose at least one stream" <del> if !bytes.Contains(body, []byte(expected)) { <del> c.Fatalf("Expected %s, got %s", expected, string(body[:])) <del> } <add> c.Assert(getErrorMessage(c, body), checker.Contains, expected) <ide> } <ide> <ide> // Regression test for #12704 <ide><path>integration-cli/docker_api_resize_test.go <ide> func (s *DockerSuite) TestResizeApiResponseWhenContainerNotStarted(c *check.C) { <ide> c.Assert(status, check.Equals, http.StatusInternalServerError) <ide> c.Assert(err, check.IsNil) <ide> <del> c.Assert(string(body), checker.Contains, "is not running", check.Commentf("resize should fail with message 'Container is not running'")) <add> c.Assert(getErrorMessage(c, body), checker.Contains, "is not running", check.Commentf("resize should fail with message 'Container is not running'")) <ide> } <ide><path>integration-cli/docker_api_test.go <ide> func (s *DockerSuite) TestApiClientVersionNewerThanServer(c *check.C) { <ide> c.Assert(err, checker.IsNil) <ide> c.Assert(status, checker.Equals, http.StatusBadRequest) <ide> expected := fmt.Sprintf("client is newer than server (client API version: %s, server API version: %s)", version, api.DefaultVersion) <del> c.Assert(strings.TrimSpace(string(body)), checker.Equals, expected) <add> c.Assert(getErrorMessage(c, body), checker.Equals, expected) <ide> } <ide> <ide> func (s *DockerSuite) TestApiClientVersionOldNotSupported(c *check.C) { <ide> func (s *DockerSuite) TestApiDockerApiVersion(c *check.C) { <ide> c.Fatalf("Out didn't have 'xxx' for the API version, had:\n%s", out) <ide> } <ide> } <add> <add>func (s *DockerSuite) TestApiErrorJSON(c *check.C) { <add> httpResp, body, err := sockRequestRaw("POST", "/containers/create", strings.NewReader(`{}`), "application/json") <add> c.Assert(err, checker.IsNil) <add> c.Assert(httpResp.StatusCode, checker.Equals, http.StatusInternalServerError) <add> c.Assert(httpResp.Header.Get("Content-Type"), checker.Equals, "application/json") <add> b, err := readBody(body) <add> c.Assert(err, checker.IsNil) <add> c.Assert(getErrorMessage(c, b), checker.Equals, "Config cannot be empty in order to create a container") <add>} <add> <add>func (s *DockerSuite) TestApiErrorPlainText(c *check.C) { <add> httpResp, body, err := sockRequestRaw("POST", "/v1.23/containers/create", strings.NewReader(`{}`), "application/json") <add> c.Assert(err, checker.IsNil) <add> c.Assert(httpResp.StatusCode, checker.Equals, http.StatusInternalServerError) <add> c.Assert(httpResp.Header.Get("Content-Type"), checker.Contains, "text/plain") <add> b, err := readBody(body) <add> c.Assert(err, checker.IsNil) <add> c.Assert(strings.TrimSpace(string(b)), checker.Equals, "Config cannot be empty in order to create a container") <add>} <add> <add>func (s *DockerSuite) TestApiErrorNotFoundJSON(c *check.C) { <add> // 404 is a different code path to normal errors, so test separately <add> httpResp, body, err := sockRequestRaw("GET", "/notfound", nil, "application/json") <add> c.Assert(err, checker.IsNil) <add> c.Assert(httpResp.StatusCode, checker.Equals, http.StatusNotFound) <add> c.Assert(httpResp.Header.Get("Content-Type"), checker.Equals, "application/json") <add> b, err := readBody(body) <add> c.Assert(err, checker.IsNil) <add> c.Assert(getErrorMessage(c, b), checker.Equals, "page not found") <add>} <add> <add>func (s *DockerSuite) TestApiErrorNotFoundPlainText(c *check.C) { <add> httpResp, body, err := sockRequestRaw("GET", "/v1.23/notfound", nil, "application/json") <add> c.Assert(err, checker.IsNil) <add> c.Assert(httpResp.StatusCode, checker.Equals, http.StatusNotFound) <add> c.Assert(httpResp.Header.Get("Content-Type"), checker.Contains, "text/plain") <add> b, err := readBody(body) <add> c.Assert(err, checker.IsNil) <add> c.Assert(strings.TrimSpace(string(b)), checker.Equals, "page not found") <add>} <ide><path>integration-cli/docker_utils.go <ide> func waitForGoroutines(expected int) error { <ide> } <ide> } <ide> } <add> <add>// getErrorMessage returns the error message from an error API response <add>func getErrorMessage(c *check.C, body []byte) string { <add> var resp types.ErrorResponse <add> c.Assert(json.Unmarshal(body, &resp), check.IsNil) <add> return strings.TrimSpace(resp.Message) <add>}
13
PHP
PHP
adjust type hint and documentation
592b03cb6a32094402a36d289d81de5c7b901def
<ide><path>src/View/Helper/FormHelper.php <ide> protected function _csrfField() <ide> * Closes an HTML form, cleans up values set by FormHelper::create(), and writes hidden <ide> * input fields where appropriate. <ide> * <del> * @param array $secureAttributes will be passed as html attributes into the hidden input elements generated for the <del> * Security Component. <add> * @param array $secureAttributes Secure attibutes which will be passed as HTML attributes <add> * into the hidden input elements generated for the Security Component. <ide> * @return string A closing FORM tag. <ide> * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#closing-the-form <ide> */ <del> public function end($secureAttributes = []) <add> public function end(array $secureAttributes = []) <ide> { <ide> $out = ''; <ide> if ($this->requestType !== 'get' &&
1
Python
Python
add capture argument to project_run
f319d2765f99ef0d7aee49cd688e1af8757576bc
<ide><path>spacy/about.py <ide> # fmt: off <ide> __title__ = "spacy" <del>__version__ = "3.0.0" <add>__version__ = "3.0.1.dev0" <ide> __download_url__ = "https://github.com/explosion/spacy-models/releases/download" <ide> __compatibility__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json" <ide> __projects__ = "https://github.com/explosion/projects" <ide><path>spacy/cli/project/run.py <ide> def project_run_cli( <ide> <ide> <ide> def project_run( <del> project_dir: Path, subcommand: str, *, force: bool = False, dry: bool = False <add> project_dir: Path, <add> subcommand: str, <add> *, <add> force: bool = False, <add> dry: bool = False, <add> capture: bool = False, <ide> ) -> None: <ide> """Run a named script defined in the project.yml. If the script is part <ide> of the default pipeline (defined in the "run" section), DVC is used to <ide> def project_run( <ide> subcommand (str): Name of command to run. <ide> force (bool): Force re-running, even if nothing changed. <ide> dry (bool): Perform a dry run and don't execute commands. <add> capture (bool): Whether to capture the output and errors of individual commands. <add> If False, the stdout and stderr will not be redirected, and if there's an error, <add> sys.exit will be called with the return code. You should use capture=False <add> when you want to turn over execution to the command, and capture=True <add> when you want to run the command more like a function. <ide> """ <ide> config = load_project_config(project_dir) <ide> commands = {cmd["name"]: cmd for cmd in config.get("commands", [])} <ide> def project_run( <ide> if not rerun and not force: <ide> msg.info(f"Skipping '{cmd['name']}': nothing changed") <ide> else: <del> run_commands(cmd["script"], dry=dry) <add> run_commands(cmd["script"], dry=dry, capture=capture) <ide> if not dry: <ide> update_lockfile(current_dir, cmd) <ide> <ide> def run_commands( <ide> commands: Iterable[str] = SimpleFrozenList(), <ide> silent: bool = False, <ide> dry: bool = False, <add> capture: bool = False, <ide> ) -> None: <ide> """Run a sequence of commands in a subprocess, in order. <ide> <ide> commands (List[str]): The string commands. <ide> silent (bool): Don't print the commands. <ide> dry (bool): Perform a dry run and don't execut anything. <add> capture (bool): Whether to capture the output and errors of individual commands. <add> If False, the stdout and stderr will not be redirected, and if there's an error, <add> sys.exit will be called with the return code. You should use capture=False <add> when you want to turn over execution to the command, and capture=True <add> when you want to run the command more like a function. <ide> """ <ide> for command in commands: <ide> command = split_command(command) <ide> def run_commands( <ide> if not silent: <ide> print(f"Running command: {join_command(command)}") <ide> if not dry: <del> run_command(command, capture=False) <add> run_command(command, capture=capture) <ide> <ide> <ide> def validate_subcommand( <ide><path>spacy/util.py <ide> def run_command( <ide> stdin (Optional[Any]): stdin to read from or None. <ide> capture (bool): Whether to capture the output and errors. If False, <ide> the stdout and stderr will not be redirected, and if there's an error, <del> sys.exit will be called with the returncode. You should use capture=False <add> sys.exit will be called with the return code. You should use capture=False <ide> when you want to turn over execution to the command, and capture=True <ide> when you want to run the command more like a function. <ide> RETURNS (Optional[CompletedProcess]): The process object.
3
Text
Text
use kbd element in readline doc
6c4239bea786a3e231943c283fe236832987939d
<ide><path>doc/api/readline.md <ide> The `'close'` event is emitted when one of the following occur: <ide> * The `rl.close()` method is called and the `readline.Interface` instance has <ide> relinquished control over the `input` and `output` streams; <ide> * The `input` stream receives its `'end'` event; <del>* The `input` stream receives `<ctrl>-D` to signal end-of-transmission (EOT); <del>* The `input` stream receives `<ctrl>-C` to signal `SIGINT` and there is no <del> `'SIGINT'` event listener registered on the `readline.Interface` instance. <add>* The `input` stream receives <kbd>Ctrl</kbd>+<kbd>D</kbd> to signal <add> end-of-transmission (EOT); <add>* The `input` stream receives <kbd>Ctrl</kbd>+<kbd>C</kbd> to signal `SIGINT` <add> and there is no `'SIGINT'` event listener registered on the <add> `readline.Interface` instance. <ide> <ide> The listener function is called without passing any arguments. <ide> <ide> added: v0.7.5 <ide> --> <ide> <ide> The `'SIGCONT'` event is emitted when a Node.js process previously moved into <del>the background using `<ctrl>-Z` (i.e. `SIGTSTP`) is then brought back to the <del>foreground using fg(1p). <add>the background using <kbd>Ctrl</kbd>+<kbd>Z</kbd> (i.e. `SIGTSTP`) is then <add>brought back to the foreground using fg(1p). <ide> <ide> If the `input` stream was paused *before* the `SIGTSTP` request, this event will <ide> not be emitted. <ide> added: v0.3.0 <ide> --> <ide> <ide> The `'SIGINT'` event is emitted whenever the `input` stream receives a <del>`<ctrl>-C` input, known typically as `SIGINT`. If there are no `'SIGINT'` event <del>listeners registered when the `input` stream receives a `SIGINT`, the `'pause'` <del>event will be emitted. <add><kbd>Ctrl+C</kbd> input, known typically as `SIGINT`. If there are no `'SIGINT'` <add>event listeners registered when the `input` stream receives a `SIGINT`, the <add>`'pause'` event will be emitted. <ide> <ide> The listener function is invoked without passing any arguments. <ide> <ide> rl.on('SIGINT', () => { <ide> added: v0.7.5 <ide> --> <ide> <del>The `'SIGTSTP'` event is emitted when the `input` stream receives a `<ctrl>-Z` <del>input, typically known as `SIGTSTP`. If there are no `'SIGTSTP'` event listeners <del>registered when the `input` stream receives a `SIGTSTP`, the Node.js process <del>will be sent to the background. <add>The `'SIGTSTP'` event is emitted when the `input` stream receives a <add><kbd>Ctrl</kbd>+<kbd>Z</kbd> input, typically known as `SIGTSTP`. If there are <add>no `'SIGTSTP'` event listeners registered when the `input` stream receives a <add>`SIGTSTP`, the Node.js process will be sent to the background. <ide> <ide> When the program is resumed using fg(1p), the `'pause'` and `'SIGCONT'` events <ide> will be emitted. These can be used to resume the `input` stream. <ide> added: v0.1.98 <ide> <ide> * `data` {string} <ide> * `key` {Object} <del> * `ctrl` {boolean} `true` to indicate the `<ctrl>` key. <del> * `meta` {boolean} `true` to indicate the `<Meta>` key. <del> * `shift` {boolean} `true` to indicate the `<Shift>` key. <add> * `ctrl` {boolean} `true` to indicate the <kbd>Ctrl</kbd> key. <add> * `meta` {boolean} `true` to indicate the <kbd>Meta</kbd> key. <add> * `shift` {boolean} `true` to indicate the <kbd>Shift</kbd> key. <ide> * `name` {string} The name of the a key. <ide> <ide> The `rl.write()` method will write either `data` or a key sequence identified <ide> If the `readline.Interface` was created with `output` set to `null` or <ide> <ide> ```js <ide> rl.write('Delete this!'); <del>// Simulate Ctrl+u to delete the line written previously <add>// Simulate Ctrl+U to delete the line written previously <ide> rl.write(null, { ctrl: true, name: 'u' }); <ide> ``` <ide> <ide> const { createInterface } = require('readline'); <ide> <th>Notes</th> <ide> </tr> <ide> <tr> <del> <td><code>ctrl</code> + <code>shift</code> + <code>backspace</code></td> <add> <td><kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>Backspace</kbd></td> <ide> <td>Delete line left</td> <ide> <td>Doesn't work on Linux, Mac and Windows</td> <ide> </tr> <ide> <tr> <del> <td><code>ctrl</code> + <code>shift</code> + <code>delete</code></td> <add> <td><kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>Delete</kbd></td> <ide> <td>Delete line right</td> <ide> <td>Doesn't work on Mac</td> <ide> </tr> <ide> <tr> <del> <td><code>ctrl</code> + <code>c</code></td> <add> <td><kbd>Ctrl</kbd>+<kbd>C</kbd></td> <ide> <td>Emit <code>SIGINT</code> or close the readline instance</td> <ide> <td></td> <ide> </tr> <ide> <tr> <del> <td><code>ctrl</code> + <code>h</code></td> <add> <td><kbd>Ctrl</kbd>+<kbd>H</kbd></td> <ide> <td>Delete left</td> <ide> <td></td> <ide> </tr> <ide> <tr> <del> <td><code>ctrl</code> + <code>d</code></td> <add> <td><kbd>Ctrl</kbd>+<kbd>D</kbd></td> <ide> <td>Delete right or close the readline instance in case the current line is empty / EOF</td> <ide> <td>Doesn't work on Windows</td> <ide> </tr> <ide> <tr> <del> <td><code>ctrl</code> + <code>u</code></td> <add> <td><kbd>Ctrl</kbd>+<kbd>U</kbd></td> <ide> <td>Delete from the current position to the line start</td> <ide> <td></td> <ide> </tr> <ide> <tr> <del> <td><code>ctrl</code> + <code>k</code></td> <add> <td><kbd>Ctrl</kbd>+<kbd>K</kbd></td> <ide> <td>Delete from the current position to the end of line</td> <ide> <td></td> <ide> </tr> <ide> <tr> <del> <td><code>ctrl</code> + <code>a</code></td> <add> <td><kbd>Ctrl</kbd>+<kbd>A</kbd></td> <ide> <td>Go to start of line</td> <ide> <td></td> <ide> </tr> <ide> <tr> <del> <td><code>ctrl</code> + <code>e</code></td> <add> <td><kbd>Ctrl</kbd>+<kbd>E</kbd></td> <ide> <td>Go to to end of line</td> <ide> <td></td> <ide> </tr> <ide> <tr> <del> <td><code>ctrl</code> + <code>b</code></td> <add> <td><kbd>Ctrl</kbd>+<kbd>B</kbd></td> <ide> <td>Back one character</td> <ide> <td></td> <ide> </tr> <ide> <tr> <del> <td><code>ctrl</code> + <code>f</code></td> <add> <td><kbd>Ctrl</kbd>+<kbd>F</kbd></td> <ide> <td>Forward one character</td> <ide> <td></td> <ide> </tr> <ide> <tr> <del> <td><code>ctrl</code> + <code>l</code></td> <add> <td><kbd>Ctrl</kbd>+<kbd>L</kbd></td> <ide> <td>Clear screen</td> <ide> <td></td> <ide> </tr> <ide> <tr> <del> <td><code>ctrl</code> + <code>n</code></td> <add> <td><kbd>Ctrl</kbd>+<kbd>N</kbd></td> <ide> <td>Next history item</td> <ide> <td></td> <ide> </tr> <ide> <tr> <del> <td><code>ctrl</code> + <code>p</code></td> <add> <td><kbd>Ctrl</kbd>+<kbd>P</kbd></td> <ide> <td>Previous history item</td> <ide> <td></td> <ide> </tr> <ide> <tr> <del> <td><code>ctrl</code> + <code>z</code></td> <add> <td><kbd>Ctrl</kbd>+<kbd>Z</kbd></td> <ide> <td>Moves running process into background. Type <del> <code>fg</code> and press <code>enter</code> <add> <code>fg</code> and press <kbd>Enter</kbd> <ide> to return.</td> <ide> <td>Doesn't work on Windows</td> <ide> </tr> <ide> <tr> <del> <td><code>ctrl</code> + <code>w</code> or <code>ctrl</code> <del> + <code>backspace</code></td> <add> <td><kbd>Ctrl</kbd>+<kbd>W</kbd> or <kbd>Ctrl</kbd> <add> +<kbd>Backspace</kbd></td> <ide> <td>Delete backward to a word boundary</td> <del> <td><code>ctrl</code> + <code>backspace</code> Doesn't <add> <td><kbd>Ctrl</kbd>+<kbd>Backspace</kbd> Doesn't <ide> work on Linux, Mac and Windows</td> <ide> </tr> <ide> <tr> <del> <td><code>ctrl</code> + <code>delete</code></td> <add> <td><kbd>Ctrl</kbd>+<kbd>Delete</kbd></td> <ide> <td>Delete forward to a word boundary</td> <ide> <td>Doesn't work on Mac</td> <ide> </tr> <ide> <tr> <del> <td><code>ctrl</code> + <code>left</code> or <del> <code>meta</code> + <code>b</code></td> <add> <td><kbd>Ctrl</kbd>+<kbd>Left arrow</kbd> or <add> <kbd>Meta</kbd>+<kbd>B</kbd></td> <ide> <td>Word left</td> <del> <td><code>ctrl</code> + <code>left</code> Doesn't work <add> <td><kbd>Ctrl</kbd>+<kbd>Left arrow</kbd> Doesn't work <ide> on Mac</td> <ide> </tr> <ide> <tr> <del> <td><code>ctrl</code> + <code>right</code> or <del> <code>meta</code> + <code>f</code></td> <add> <td><kbd>Ctrl</kbd>+<kbd>Right arrow</kbd> or <add> <kbd>Meta</kbd>+<kbd>F</kbd></td> <ide> <td>Word right</td> <del> <td><code>ctrl</code> + <code>right</code> Doesn't work <add> <td><kbd>Ctrl</kbd>+<kbd>Right arrow</kbd> Doesn't work <ide> on Mac</td> <ide> </tr> <ide> <tr> <del> <td><code>meta</code> + <code>d</code> or <code>meta</code> <del> + <code>delete</code></td> <add> <td><kbd>Meta</kbd>+<kbd>D</kbd> or <kbd>Meta</kbd> <add> +<kbd>Delete</kbd></td> <ide> <td>Delete word right</td> <del> <td><code>meta</code> + <code>delete</code> Doesn't work <add> <td><kbd>Meta</kbd>+<kbd>Delete</kbd> Doesn't work <ide> on windows</td> <ide> </tr> <ide> <tr> <del> <td><code>meta</code> + <code>backspace</code></td> <add> <td><kbd>Meta</kbd>+<kbd>Backspace</kbd></td> <ide> <td>Delete word left</td> <ide> <td>Doesn't work on Mac</td> <ide> </tr>
1
Ruby
Ruby
replace nokogiri with rexml
2c4a7ae2cb0cf19cf1542ad7f7a985eb964e5d38
<ide><path>Library/Homebrew/livecheck/strategy/sparkle.rb <ide> # frozen_string_literal: true <ide> <ide> require "bundle_version" <del>require_relative "page_match" <ide> <ide> module Homebrew <ide> module Livecheck <ide> def self.match?(url) <ide> <ide> sig { params(content: String).returns(T.nilable(Item)) } <ide> def self.item_from_content(content) <del> Homebrew.install_bundler_gems! <del> require "nokogiri" <add> require "rexml/document" <add> <add> parsing_tries = 0 <add> xml = begin <add> REXML::Document.new(content) <add> rescue REXML::UndefinedNamespaceException => e <add> undefined_prefix = e.to_s[/Undefined prefix ([^ ]+) found/i, 1] <add> raise if undefined_prefix.blank? <add> <add> # Only retry parsing once after removing prefix from content <add> parsing_tries += 1 <add> raise if parsing_tries > 1 <add> <add> # When an XML document contains a prefix without a corresponding <add> # namespace, it's necessary to remove the the prefix from the <add> # content to be able to successfully parse it using REXML <add> content = content.gsub(%r{(</?| )#{Regexp.escape(undefined_prefix)}:}, '\1') <add> retry <add> end <ide> <del> xml = Nokogiri::XML(content) <del> xml.remove_namespaces! <add> # Remove prefixes, so we can reliably identify elements and attributes <add> xml.root&.each_recursive do |node| <add> node.prefix = "" <add> node.attributes.each_attribute do |attribute| <add> attribute.prefix = "" <add> end <add> end <ide> <del> items = xml.xpath("//rss//channel//item").map do |item| <del> enclosure = (item > "enclosure").first <add> items = xml.get_elements("//rss//channel//item").map do |item| <add> enclosure = item.elements["enclosure"] <ide> <del> url = enclosure&.attr("url") <del> short_version = enclosure&.attr("shortVersionString") <del> version = enclosure&.attr("version") <add> if enclosure <add> url = enclosure["url"] <add> short_version = enclosure["shortVersionString"] <add> version = enclosure["version"] <add> os = enclosure["os"] <add> end <ide> <del> url ||= (item > "link").first&.text <del> short_version ||= (item > "shortVersionString").first&.text&.strip <del> version ||= (item > "version").first&.text&.strip <add> url ||= item.elements["link"]&.text <add> short_version ||= item.elements["shortVersionString"]&.text&.strip <add> version ||= item.elements["version"]&.text&.strip <ide> <del> title = (item > "title").first&.text&.strip <del> pub_date = (item > "pubDate").first&.text&.strip&.presence&.yield_self do |date_string| <add> title = item.elements["title"]&.text&.strip <add> pub_date = item.elements["pubDate"]&.text&.strip&.presence&.yield_self do |date_string| <ide> Time.parse(date_string) <ide> rescue ArgumentError <ide> # Omit unparseable strings (e.g. non-English dates) <ide> def self.item_from_content(content) <ide> <ide> bundle_version = BundleVersion.new(short_version, version) if short_version || version <ide> <del> next if (os = enclosure&.attr("os")) && os != "osx" <add> next if os && os != "osx" <ide> <ide> data = { <ide> title: title,
1
Javascript
Javascript
replace soft tags with hard tabs
7208eb816b10b291540ae7905555697a4a6a1431
<ide><path>examples/jsm/loaders/GLTFLoader.js <ide> var GLTFLoader = ( function () { <ide> <ide> parser.fileLoader.setRequestHeader( this.requestHeader ); <ide> <del> for ( var i = 0; i < this.pluginCallbacks.length; i ++ ) { <add> for ( var i = 0; i < this.pluginCallbacks.length; i ++ ) { <ide> <ide> var plugin = this.pluginCallbacks[ i ]( parser ); <ide> plugins[ plugin.name ] = plugin;
1
Python
Python
change the default max_fpn_level to 6
2e13b9a71de6b1d5032c755a35cc15e4cf6f08b6
<ide><path>research/object_detection/models/faster_rcnn_resnet_v1_fpn_keras_feature_extractor.py <ide> def __init__(self, <ide> batch_norm_trainable=False, <ide> weight_decay=0.0, <ide> fpn_min_level=2, <del> fpn_max_level=7, <add> fpn_max_level=6, <ide> additional_layer_depth=256, <ide> override_base_feature_extractor_hyperparams=False): <ide> """Constructor. <ide> def __init__(self, <ide> batch_norm_trainable=False, <ide> weight_decay=0.0, <ide> fpn_min_level=2, <del> fpn_max_level=7, <add> fpn_max_level=6, <ide> additional_layer_depth=256, <ide> override_base_feature_extractor_hyperparams=False): <ide> """Constructor. <ide> def __init__(self, <ide> batch_norm_trainable=False, <ide> weight_decay=0.0, <ide> fpn_min_level=2, <del> fpn_max_level=7, <add> fpn_max_level=6, <ide> additional_layer_depth=256, <ide> override_base_feature_extractor_hyperparams=False): <ide> """Constructor. <ide> def __init__(self, <ide> batch_norm_trainable=False, <ide> weight_decay=0.0, <ide> fpn_min_level=2, <del> fpn_max_level=7, <add> fpn_max_level=6, <ide> additional_layer_depth=256, <ide> override_base_feature_extractor_hyperparams=False): <ide> """Constructor.
1
Text
Text
update aspectratio documentation
58e736a0b98e021e5ac1d340aa52d63eb3606573
<ide><path>docs/configuration/responsive.md <ide> Namespace: `options` <ide> | ---- | ---- | ------- | ----------- <ide> | `responsive` | `boolean` | `true` | Resizes the chart canvas when its container does ([important note...](#important-note)). <ide> | `maintainAspectRatio` | `boolean` | `true` | Maintain the original canvas aspect ratio `(width / height)` when resizing. <del>| `aspectRatio` | `number` | `2` | Canvas aspect ratio (i.e. `width / height`, a value of 1 representing a square canvas). Note that this option is ignored if the height is explicitly defined either as attribute or via the style. <add>| `aspectRatio` | `number` | `1`\|`2` | Canvas aspect ratio (i.e. `width / height`, a value of 1 representing a square canvas). Note that this option is ignored if the height is explicitly defined either as attribute or via the style. The default value varies by chart type; Radial charts (doughnut, pie, polarArea, radar) default to `1` and others default to `2`. <ide> | `onResize` | `function` | `null` | Called when a resize occurs. Gets passed two arguments: the chart instance and the new size. <ide> | `resizeDelay` | `number` | `0` | Delay the resize update by the given amount of milliseconds. This can ease the resize process by debouncing the update of the elements. <ide>
1
Javascript
Javascript
change webwiew to webview
5712e0c3eb7a84be15edac4c352ba5d7f895216a
<ide><path>Libraries/Components/WebView/WebView.android.js <ide> var WebView = React.createClass({ <ide> <ide> goForward: function() { <ide> UIManager.dispatchViewManagerCommand( <del> this.getWebWiewHandle(), <add> this.getWebViewHandle(), <ide> UIManager.RCTWebView.Commands.goForward, <ide> null <ide> ); <ide> }, <ide> <ide> goBack: function() { <ide> UIManager.dispatchViewManagerCommand( <del> this.getWebWiewHandle(), <add> this.getWebViewHandle(), <ide> UIManager.RCTWebView.Commands.goBack, <ide> null <ide> ); <ide> }, <ide> <ide> reload: function() { <ide> UIManager.dispatchViewManagerCommand( <del> this.getWebWiewHandle(), <add> this.getWebViewHandle(), <ide> UIManager.RCTWebView.Commands.reload, <ide> null <ide> ); <ide> var WebView = React.createClass({ <ide> } <ide> }, <ide> <del> getWebWiewHandle: function() { <add> getWebViewHandle: function() { <ide> return React.findNodeHandle(this.refs[RCT_WEBVIEW_REF]); <ide> }, <ide>
1
Text
Text
update 10.11 expectation
2e808ff2e33797247b40440e8797bd2500095d1f
<ide><path>docs/Xcode.md <ide> Tools available for your platform: <ide> 10.8 | 5.1.1 | April 2014 <ide> 10.9 | 6.2 | 6.2 <ide> 10.10 | 7.2.1 | 7.2 <del> 10.11 | 7.3.1 | 7.3 <add> 10.11 | 8.0 | 8.0 <ide> 10.12 | 8.0 | 8.0 <ide> <ide>
1
Javascript
Javascript
use const where applicable in dllmodulefactory
90aec4e155594490334eb9fac01175deeefa4dbc
<ide><path>lib/DllModuleFactory.js <ide> class DllModuleFactory extends Tapable { <ide> super(); <ide> } <ide> create(data, callback) { <del> let dependency = data.dependencies[0]; <add> const dependency = data.dependencies[0]; <ide> callback(null, new DllModule(data.context, dependency.dependencies, dependency.name, dependency.type)); <ide> } <ide> }
1
PHP
PHP
fix
afec9cda4cd292dc8a2294e72627fcb25f591d93
<ide><path>src/Illuminate/Database/Eloquent/Builder.php <ide> protected function nestWhereSlice($whereSlice) <ide> /** <ide> * Get the underlying query builder instance. <ide> * <del> * @return \Illuminate\Database\Query\Builder|static <add> * @return \Illuminate\Database\Query\Builder <ide> */ <ide> public function getQuery() <ide> {
1
Python
Python
remove duplicate code
3ccff0d400ffd1b0c5074e15afb2b1f2af0e7b44
<ide><path>src/transformers/models/t5/modeling_t5.py <ide> def forward( <ide> ) <ide> <ide> hidden_states = encoder_outputs[0] <del> if self.model_parallel: <del> torch.cuda.set_device(self.decoder.first_device) <add> <ide> # Set device for model parallelism <ide> if self.model_parallel: <ide> torch.cuda.set_device(self.decoder.first_device)
1
Text
Text
use serial comma in report docs
7f4e9ecb52690ef80fd5a67f1fc1de9ed901a3a5
<ide><path>doc/api/report.md <ide> <ide> Delivers a JSON-formatted diagnostic summary, written to a file. <ide> <del>The report is intended for development, test and production use, to capture <add>The report is intended for development, test, and production use, to capture <ide> and preserve information for problem determination. It includes JavaScript <ide> and native stack traces, heap statistics, platform information, resource <ide> usage etc. With the report option enabled, diagnostic reports can be triggered <ide> the application, in expectation of self-adjusting the resource consumption, <ide> load balancing, monitoring etc. <ide> <ide> The content of the report consists of a header section containing the event <del>type, date, time, PID and Node.js version, sections containing JavaScript and <add>type, date, time, PID, and Node.js version, sections containing JavaScript and <ide> native stack traces, a section containing V8 heap information, a section <del>containing `libuv` handle information and an OS platform information section <add>containing `libuv` handle information, and an OS platform information section <ide> showing CPU and memory usage and system limits. An example report can be <ide> triggered using the Node.js REPL: <ide>
1
Python
Python
fix lint violations
bfda9fc09527b8b8adb2c0d33462da9eee8ef537
<ide><path>libcloud/utils/misc.py <ide> from libcloud.common.providers import set_driver as _set_driver <ide> # Imported for backward compatibility <ide> # noinspection PyProtectedMember <del>from libcloud.utils.retry import (Retry, <del> DEFAULT_DELAY, DEFAULT_TIMEOUT, DEFAULT_BACKOFF, <del> TRANSIENT_SSL_ERROR, TransientSSLError) <add>from libcloud.utils.retry import Retry # flake8: noqa <add>from libcloud.utils.retry import DEFAULT_DELAY # noqa: F401 <add>from libcloud.utils.retry import DEFAULT_TIMEOUT # noqa: F401 <add>from libcloud.utils.retry import DEFAULT_BACKOFF # noqa: F401 <add>from libcloud.utils.retry import TRANSIENT_SSL_ERROR # noqa: F401 <add>from libcloud.utils.retry import TransientSSLError # noqa: F401 <ide> <ide> <ide> __all__ = [ <ide> def find(l, predicate): <ide> # been moved to "libcloud.common.providers" module <ide> get_driver = _get_driver <ide> set_driver = _set_driver <del># Note: This is an alias for backward-compatibility for a function which has been <del># moved to "libcloud.util.retry" module <add># Note: This is an alias for backward-compatibility for a function which has <add># been moved to "libcloud.util.retry" module <ide> retry = Retry <ide> <ide> <ide> def __repr__(self): <ide> <ide> def __str__(self): <ide> return str(self.__repr__()) <del> <del> <del> <ide><path>libcloud/utils/retry.py <ide> class MinimalRetry: <ide> def __init__(self, retry_delay=DEFAULT_DELAY, <ide> timeout=DEFAULT_TIMEOUT, backoff=DEFAULT_BACKOFF): <ide> """ <del> Wrapper around retrying that helps to handle common transient exceptions. <add> Wrapper around retrying that helps to handle common transient <add> exceptions. <add> <ide> This minimalistic version only retries SSL errors and rate limiting. <ide> <ide> :param retry_delay: retry delay between the attempts. <ide> def retry_loop(*args, **kwargs): <ide> last_exc = exc <ide> <ide> if isinstance(exc, RateLimitReachedError): <del> _logger.debug("You are being rate limited, backing off...") <add> _logger.debug("You are being rate limited, backing " <add> "off...") <ide> <ide> # NOTE: Retry after defaults to 0 in the <ide> # RateLimitReachedError class so we a use more <ide> def should_retry(self, exception): <ide> class Retry(MinimalRetry): <ide> <ide> def __init__(self, retry_exceptions=RETRY_EXCEPTIONS, <del> retry_delay=DEFAULT_DELAY, timeout=DEFAULT_TIMEOUT, backoff=DEFAULT_BACKOFF): <add> retry_delay=DEFAULT_DELAY, timeout=DEFAULT_TIMEOUT, <add> backoff=DEFAULT_BACKOFF): <ide> """ <del> Wrapper around retrying that helps to handle common transient exceptions. <del> This version retries the errors that `libcloud.utils.retry:MinimalRetry` retries <del> and all errors of the exception types that are given. <add> Wrapper around retrying that helps to handle common transient <add> exceptions. <add> <add> This version retries the errors that <add> `libcloud.utils.retry:MinimalRetry` retries and all errors of the <add> exception types that are given. <ide> <ide> :param retry_exceptions: types of exceptions to retry on. <ide> :param retry_delay: retry delay between the attempts. <ide> def __init__(self, retry_exceptions=RETRY_EXCEPTIONS, <ide> <ide> :Example: <ide> <del> retry_request = Retry(retry_exceptions=(httplib.NotConnected,), timeout=1, retry_delay=1, backoff=1) <add> retry_request = Retry(retry_exceptions=(httplib.NotConnected,), <add> timeout=1, retry_delay=1, backoff=1) <ide> retry_request(self.connection.request)() <ide> """ <ide> <del> super().__init__(retry_delay=retry_delay, timeout=timeout, backoff=backoff) <add> super().__init__(retry_delay=retry_delay, timeout=timeout, <add> backoff=backoff) <ide> if retry_exceptions is None: <ide> retry_exceptions = RETRY_EXCEPTIONS <ide> self.retry_exceptions = retry_exceptions <ide> <ide> def should_retry(self, exception): <ide> return type(exception) in self.retry_exceptions <del>
2
PHP
PHP
fix digestauthenticate test
417c137d1143f6faedbe7508c1a7939ad554ab6c
<ide><path>lib/Cake/Controller/Component/Auth/DigestAuthenticate.php <ide> class DigestAuthenticate extends BasicAuthenticate { <ide> * <ide> * - `fields` The fields to use to identify a user by. <ide> * - `userModel` The model name of the User, defaults to User. <add> * - `userFields` Array of fields to retrieve from User model, null to retrieve all. Defaults to null. <ide> * - `scope` Additional conditions to use when looking up and authenticating users, <ide> * i.e. `array('User.is_active' => 1).` <ide> * - `recursive` The value of the recursive key passed to find(). Defaults to 0. <ide> class DigestAuthenticate extends BasicAuthenticate { <ide> 'password' => 'password' <ide> ), <ide> 'userModel' => 'User', <add> 'userFields' => null, <ide> 'scope' => array(), <ide> 'recursive' => 0, <ide> 'contain' => null,
1
Ruby
Ruby
handle tap not found and suggest update
30e409adfd1b1b996eb3a7e6c482dd244bb84b95
<ide><path>Library/Homebrew/cmd/search.rb <ide> def search_tap user, repo, rx <ide> end <ide> end <ide> results <del> rescue GitHub::Error, Utils::JSON::Error <add> rescue OpenURI::HTTPError, GitHub::Error, Utils::JSON::Error <add> opoo <<-EOS.undent <add> Failed to search tap: #{user}/#{repo}. Please run `brew update`. <add> EOS <ide> [] <ide> end <ide>
1
Go
Go
use const for file permissions
60ace31be078834605ee318842f32a0193083ebb
<ide><path>libnetwork/sandbox_dns_unix.go <ide> import ( <ide> <ide> const ( <ide> defaultPrefix = "/var/lib/docker/network/files" <del> dirPerm = 0755 <del> filePerm = 0644 <add> dirPerm = 0o755 <add> filePerm = 0o644 <ide> ) <ide> <ide> func (sb *sandbox) startResolver(restore bool) { <ide> func (sb *sandbox) updateDNS(ipv6Enabled bool) error { <ide> if err != nil { <ide> return err <ide> } <del> err = os.WriteFile(sb.config.resolvConfPath, newRC.Content, 0644) //nolint:gosec // gosec complains about perms here, which must be 0644 in this case <add> err = os.WriteFile(sb.config.resolvConfPath, newRC.Content, filePerm) <ide> if err != nil { <ide> return err <ide> }
1
Python
Python
fix usability bugs in lookfor
94f73b1613e37e7076da12cb51b42895fda99112
<ide><path>numpy/lib/utils.py <ide> import re <ide> <ide> from numpy.core.numerictypes import issubclass_, issubsctype, issubdtype <del>from numpy.core import product, ndarray <add>from numpy.core import product, ndarray, ufunc <ide> <ide> __all__ = ['issubclass_', 'get_numpy_include', 'issubsctype', 'issubdtype', <ide> 'deprecate', 'deprecate_with_doc', 'get_numarray_include', <ide> def interp(x, xp, fp, left=None, right=None): <ide> _lookfor_caches = {} <ide> <ide> # regexp whose match indicates that the string may contain a function signature <del>_function_signature_re = re.compile(r"[a-z_]+\(.*[,=].*\)", re.I) <add>_function_signature_re = re.compile(r"[a-z0-9_]+\(.*[,=].*\)", re.I) <ide> <ide> def lookfor(what, module=None, import_modules=True, regenerate=False, <ide> output=None): <ide> def relevance_value(a): <ide> # Pretty-print <ide> s = "Search results for '%s'" % (' '.join(whats)) <ide> help_text = [s, "-"*len(s)] <del> for name in found: <add> for name in found[::-1]: <ide> doc, kind, ix = cache[name] <ide> <ide> doclines = [line.strip() for line in doc.strip().split("\n") <ide> def _lookfor_generate_cache(module, import_modules, regenerate): <ide> item_name = "%s.%s" % (mod_name, item_name) <ide> <ide> if not item_name.startswith(name + '.'): <del> # don't crawl foreign objects <del> continue <add> # don't crawl "foreign" objects <add> if isinstance(v, ufunc): <add> # ... unless they are ufuncs <add> pass <add> else: <add> continue <ide> elif not (inspect.ismodule(v) or _all is None or n in _all): <ide> continue <ide> stack.append(("%s.%s" % (name, n), v)) <ide> elif inspect.isclass(item): <ide> kind = "class" <ide> for n, v in _getmembers(item): <ide> stack.append(("%s.%s" % (name, n), v)) <del> # FIXME later: workaround python3.1 capsule callable bug <del> # by using old version of callable. <del> # elif callable(item): <ide> elif hasattr(item, "__call__"): <ide> kind = "func" <ide>
1
Text
Text
remove unneeded `async` in docs.
1fd00899c75cbff9aa9ce269d8c0a4a04a8cbff7
<ide><path>docs/api-reference/next/server.md <ide> The `waitUntil()` method can be used to prolong the execution of the function if <ide> import { NextResponse } from 'next/server' <ide> import type { NextFetchEvent, NextRequest } from 'next/server' <ide> <del>export async function middleware(req: NextRequest, event: NextFetchEvent) { <add>export function middleware(req: NextRequest, event: NextFetchEvent) { <ide> event.waitUntil( <ide> fetch('https://my-analytics-platform.com', { <ide> method: 'POST',
1
Java
Java
add handlerprovider interface
84089bf3968443e4f6bb9239dace0692734d6578
<ide><path>spring-websocket/src/main/java/org/springframework/sockjs/AbstractSockJsSession.java <ide> import org.apache.commons.logging.LogFactory; <ide> import org.springframework.util.Assert; <ide> import org.springframework.websocket.CloseStatus; <add>import org.springframework.websocket.HandlerProvider; <ide> import org.springframework.websocket.TextMessage; <ide> import org.springframework.websocket.TextMessageHandler; <ide> import org.springframework.websocket.WebSocketHandler; <ide> public abstract class AbstractSockJsSession implements WebSocketSession { <ide> <ide> private final String sessionId; <ide> <add> private final HandlerProvider<WebSocketHandler> handlerProvider; <add> <ide> private final TextMessageHandler handler; <ide> <ide> private State state = State.NEW; <ide> public abstract class AbstractSockJsSession implements WebSocketSession { <ide> /** <ide> * <ide> * @param sessionId <del> * @param handler the recipient of SockJS messages <add> * @param handlerProvider the recipient of SockJS messages <ide> */ <del> public AbstractSockJsSession(String sessionId, WebSocketHandler webSocketHandler) { <add> public AbstractSockJsSession(String sessionId, HandlerProvider<WebSocketHandler> handlerProvider) { <ide> Assert.notNull(sessionId, "sessionId is required"); <del> Assert.notNull(webSocketHandler, "webSocketHandler is required"); <del> Assert.isInstanceOf(TextMessageHandler.class, webSocketHandler, "Expected a TextMessageHandler"); <add> Assert.notNull(handlerProvider, "handlerProvider is required"); <ide> this.sessionId = sessionId; <add> <add> WebSocketHandler webSocketHandler = handlerProvider.getHandler(); <add> Assert.isInstanceOf(TextMessageHandler.class, webSocketHandler, "Expected a TextMessageHandler"); <ide> this.handler = (TextMessageHandler) webSocketHandler; <add> this.handlerProvider = handlerProvider; <ide> } <ide> <ide> public String getId() { <ide> public final void close(CloseStatus status) throws Exception { <ide> } <ide> finally { <ide> this.state = State.CLOSED; <del> this.handler.afterConnectionClosed(status, this); <add> try { <add> this.handler.afterConnectionClosed(status, this); <add> } <add> finally { <add> this.handlerProvider.destroy(this.handler); <add> } <ide> } <ide> } <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/sockjs/SockJsSessionFactory.java <ide> <ide> package org.springframework.sockjs; <ide> <add>import org.springframework.websocket.HandlerProvider; <ide> import org.springframework.websocket.WebSocketHandler; <ide> import org.springframework.websocket.WebSocketSession; <ide> <ide> */ <ide> public interface SockJsSessionFactory<S extends WebSocketSession>{ <ide> <del> S createSession(String sessionId, WebSocketHandler webSocketHandler); <add> S createSession(String sessionId, HandlerProvider<WebSocketHandler> handler); <ide> <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/AbstractServerSockJsSession.java <ide> import org.springframework.sockjs.AbstractSockJsSession; <ide> import org.springframework.util.Assert; <ide> import org.springframework.websocket.CloseStatus; <add>import org.springframework.websocket.HandlerProvider; <ide> import org.springframework.websocket.TextMessage; <ide> import org.springframework.websocket.WebSocketHandler; <ide> import org.springframework.websocket.WebSocketMessage; <ide> public abstract class AbstractServerSockJsSession extends AbstractSockJsSession <ide> <ide> <ide> public AbstractServerSockJsSession(String sessionId, SockJsConfiguration config, <del> WebSocketHandler webSocketHandler) { <add> HandlerProvider<WebSocketHandler> handler) { <ide> <del> super(sessionId, webSocketHandler); <add> super(sessionId, handler); <ide> this.sockJsConfig = config; <ide> } <ide> <ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/AbstractSockJsService.java <ide> import org.springframework.util.DigestUtils; <ide> import org.springframework.util.ObjectUtils; <ide> import org.springframework.util.StringUtils; <add>import org.springframework.websocket.HandlerProvider; <ide> import org.springframework.websocket.WebSocketHandler; <ide> <ide> <ide> public void destroy() throws Exception { <ide> * @throws Exception <ide> */ <ide> public final void handleRequest(ServerHttpRequest request, ServerHttpResponse response, <del> String sockJsPath, WebSocketHandler webSocketHandler) throws Exception { <add> String sockJsPath, HandlerProvider<WebSocketHandler> handler) throws Exception { <ide> <ide> logger.debug(request.getMethod() + " [" + sockJsPath + "]"); <ide> <ide> else if (sockJsPath.matches("/iframe[0-9-.a-z_]*.html")) { <ide> return; <ide> } <ide> else if (sockJsPath.equals("/websocket")) { <del> handleRawWebSocketRequest(request, response, webSocketHandler); <add> handleRawWebSocketRequest(request, response, handler); <ide> return; <ide> } <ide> <ide> else if (sockJsPath.equals("/websocket")) { <ide> return; <ide> } <ide> <del> handleTransportRequest(request, response, sessionId, TransportType.fromValue(transport), webSocketHandler); <add> handleTransportRequest(request, response, sessionId, TransportType.fromValue(transport), handler); <ide> } <ide> finally { <ide> response.flush(); <ide> } <ide> } <ide> <ide> protected abstract void handleRawWebSocketRequest(ServerHttpRequest request, ServerHttpResponse response, <del> WebSocketHandler webSocketHandler) throws Exception; <add> HandlerProvider<WebSocketHandler> handler) throws Exception; <ide> <ide> protected abstract void handleTransportRequest(ServerHttpRequest request, ServerHttpResponse response, <del> String sessionId, TransportType transportType, WebSocketHandler webSocketHandler) throws Exception; <add> String sessionId, TransportType transportType, HandlerProvider<WebSocketHandler> handler) throws Exception; <ide> <ide> <ide> protected boolean validateRequest(String serverId, String sessionId, String transport) { <ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/SockJsService.java <ide> <ide> import org.springframework.http.server.ServerHttpRequest; <ide> import org.springframework.http.server.ServerHttpResponse; <add>import org.springframework.websocket.HandlerProvider; <ide> import org.springframework.websocket.WebSocketHandler; <ide> <ide> <ide> public interface SockJsService { <ide> <ide> <ide> void handleRequest(ServerHttpRequest request, ServerHttpResponse response, String sockJsPath, <del> WebSocketHandler webSocketHandler) throws Exception; <add> HandlerProvider<WebSocketHandler> handler) throws Exception; <ide> <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/TransportHandler.java <ide> import org.springframework.http.server.ServerHttpRequest; <ide> import org.springframework.http.server.ServerHttpResponse; <ide> import org.springframework.sockjs.AbstractSockJsSession; <add>import org.springframework.websocket.HandlerProvider; <ide> import org.springframework.websocket.WebSocketHandler; <ide> <ide> <ide> public interface TransportHandler { <ide> TransportType getTransportType(); <ide> <ide> void handleRequest(ServerHttpRequest request, ServerHttpResponse response, <del> WebSocketHandler webSocketHandler, AbstractSockJsSession session) throws Exception; <add> HandlerProvider<WebSocketHandler> handler, AbstractSockJsSession session) throws Exception; <ide> <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/support/DefaultSockJsService.java <ide> import java.util.Map; <ide> import java.util.concurrent.ConcurrentHashMap; <ide> <del>import org.springframework.beans.factory.InitializingBean; <ide> import org.springframework.http.Cookie; <ide> import org.springframework.http.HttpMethod; <ide> import org.springframework.http.HttpStatus; <ide> import org.springframework.sockjs.server.transport.XhrStreamingTransportHandler; <ide> import org.springframework.sockjs.server.transport.XhrTransportHandler; <ide> import org.springframework.util.Assert; <add>import org.springframework.websocket.HandlerProvider; <ide> import org.springframework.websocket.WebSocketHandler; <ide> import org.springframework.websocket.server.DefaultHandshakeHandler; <ide> import org.springframework.websocket.server.HandshakeHandler; <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> */ <del>public class DefaultSockJsService extends AbstractSockJsService implements InitializingBean { <add>public class DefaultSockJsService extends AbstractSockJsService { <ide> <ide> private final Map<TransportType, TransportHandler> transportHandlers = new HashMap<TransportType, TransportHandler>(); <ide> <ide> public void destroy() throws Exception { <ide> <ide> @Override <ide> protected void handleRawWebSocketRequest(ServerHttpRequest request, ServerHttpResponse response, <del> WebSocketHandler webSocketHandler) throws Exception { <add> HandlerProvider<WebSocketHandler> handler) throws Exception { <ide> <ide> if (isWebSocketEnabled()) { <ide> TransportHandler transportHandler = this.transportHandlers.get(TransportType.WEBSOCKET); <ide> if (transportHandler != null) { <ide> if (transportHandler instanceof HandshakeHandler) { <del> ((HandshakeHandler) transportHandler).doHandshake(request, response, webSocketHandler); <add> ((HandshakeHandler) transportHandler).doHandshake(request, response, handler); <ide> return; <ide> } <ide> } <ide> protected void handleRawWebSocketRequest(ServerHttpRequest request, ServerHttpRe <ide> <ide> @Override <ide> protected void handleTransportRequest(ServerHttpRequest request, ServerHttpResponse response, <del> String sessionId, TransportType transportType, WebSocketHandler webSocketHandler) throws Exception { <add> String sessionId, TransportType transportType, HandlerProvider<WebSocketHandler> handler) throws Exception { <ide> <ide> TransportHandler transportHandler = this.transportHandlers.get(transportType); <ide> <ide> protected void handleTransportRequest(ServerHttpRequest request, ServerHttpRespo <ide> return; <ide> } <ide> <del> AbstractSockJsSession session = getSockJsSession(sessionId, webSocketHandler, transportHandler); <add> AbstractSockJsSession session = getSockJsSession(sessionId, handler, transportHandler); <ide> <ide> if (session != null) { <ide> if (transportType.setsNoCacheHeader()) { <ide> protected void handleTransportRequest(ServerHttpRequest request, ServerHttpRespo <ide> } <ide> } <ide> <del> transportHandler.handleRequest(request, response, webSocketHandler, session); <add> transportHandler.handleRequest(request, response, handler, session); <ide> } <ide> <del> public AbstractSockJsSession getSockJsSession(String sessionId, WebSocketHandler webSocketHandler, <add> public AbstractSockJsSession getSockJsSession(String sessionId, HandlerProvider<WebSocketHandler> handler, <ide> TransportHandler transportHandler) { <ide> <ide> AbstractSockJsSession session = this.sessions.get(sessionId); <ide> public AbstractSockJsSession getSockJsSession(String sessionId, WebSocketHandler <ide> return session; <ide> } <ide> logger.debug("Creating new session with session id \"" + sessionId + "\""); <del> session = (AbstractSockJsSession) sessionFactory.createSession(sessionId, webSocketHandler); <add> session = (AbstractSockJsSession) sessionFactory.createSession(sessionId, handler); <ide> this.sessions.put(sessionId, session); <ide> return session; <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/support/SockJsHttpRequestHandler.java <ide> import javax.servlet.http.HttpServletRequest; <ide> import javax.servlet.http.HttpServletResponse; <ide> <del>import org.springframework.beans.BeansException; <del>import org.springframework.beans.factory.BeanFactory; <del>import org.springframework.beans.factory.BeanFactoryAware; <ide> import org.springframework.http.server.AsyncServletServerHttpRequest; <ide> import org.springframework.http.server.ServerHttpRequest; <ide> import org.springframework.http.server.ServerHttpResponse; <ide> import org.springframework.web.util.UrlPathHelper; <ide> import org.springframework.websocket.HandlerProvider; <ide> import org.springframework.websocket.WebSocketHandler; <add>import org.springframework.websocket.support.SimpleHandlerProvider; <ide> <ide> <ide> /** <ide> * <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> */ <del>public class SockJsHttpRequestHandler implements HttpRequestHandler, BeanFactoryAware { <add>public class SockJsHttpRequestHandler implements HttpRequestHandler { <ide> <ide> private final String prefix; <ide> <ide> public class SockJsHttpRequestHandler implements HttpRequestHandler, BeanFactory <ide> * that begins with the specified prefix will be handled by this service. In a <ide> * Servlet container this is the path within the current servlet mapping. <ide> */ <del> public SockJsHttpRequestHandler(String prefix, SockJsService sockJsService, WebSocketHandler webSocketHandler) { <add> public SockJsHttpRequestHandler(String prefix, SockJsService sockJsService, WebSocketHandler handler) { <ide> <ide> Assert.hasText(prefix, "prefix is required"); <ide> Assert.notNull(sockJsService, "sockJsService is required"); <del> Assert.notNull(webSocketHandler, "webSocketHandler is required"); <add> Assert.notNull(handler, "webSocketHandler is required"); <ide> <ide> this.prefix = prefix; <ide> this.sockJsService = sockJsService; <del> this.handlerProvider = new HandlerProvider<WebSocketHandler>(webSocketHandler); <add> this.handlerProvider = new SimpleHandlerProvider<WebSocketHandler>(handler); <ide> } <ide> <ide> /** <ide> public SockJsHttpRequestHandler(String prefix, SockJsService sockJsService, WebS <ide> * Servlet container this is the path within the current servlet mapping. <ide> */ <ide> public SockJsHttpRequestHandler(String prefix, SockJsService sockJsService, <del> Class<? extends WebSocketHandler> webSocketHandlerClass) { <add> HandlerProvider<WebSocketHandler> handlerProvider) { <ide> <ide> Assert.hasText(prefix, "prefix is required"); <ide> Assert.notNull(sockJsService, "sockJsService is required"); <del> Assert.notNull(webSocketHandlerClass, "webSocketHandlerClass is required"); <add> Assert.notNull(handlerProvider, "handlerProvider is required"); <ide> <ide> this.prefix = prefix; <ide> this.sockJsService = sockJsService; <del> this.handlerProvider = new HandlerProvider<WebSocketHandler>(webSocketHandlerClass); <add> this.handlerProvider = handlerProvider; <ide> } <ide> <ide> public String getPrefix() { <ide> public String getPattern() { <ide> return this.prefix + "/**"; <ide> } <ide> <del> @Override <del> public void setBeanFactory(BeanFactory beanFactory) throws BeansException { <del> this.handlerProvider.setBeanFactory(beanFactory); <del> } <del> <ide> @Override <ide> public void handleRequest(HttpServletRequest request, HttpServletResponse response) <ide> throws ServletException, IOException { <ide> public void handleRequest(HttpServletRequest request, HttpServletResponse respon <ide> ServerHttpResponse httpResponse = new ServletServerHttpResponse(response); <ide> <ide> try { <del> WebSocketHandler webSocketHandler = this.handlerProvider.getHandler(); <del> this.sockJsService.handleRequest(httpRequest, httpResponse, sockJsPath, webSocketHandler); <add> this.sockJsService.handleRequest(httpRequest, httpResponse, sockJsPath, this.handlerProvider); <ide> } <ide> catch (Exception ex) { <ide> // TODO <ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/transport/AbstractHttpReceivingTransportHandler.java <ide> import org.springframework.http.server.ServerHttpResponse; <ide> import org.springframework.sockjs.AbstractSockJsSession; <ide> import org.springframework.sockjs.server.TransportHandler; <add>import org.springframework.websocket.HandlerProvider; <ide> import org.springframework.websocket.WebSocketHandler; <ide> <ide> import com.fasterxml.jackson.databind.JsonMappingException; <ide> public ObjectMapper getObjectMapper() { <ide> <ide> @Override <ide> public final void handleRequest(ServerHttpRequest request, ServerHttpResponse response, <del> WebSocketHandler webSocketHandler, AbstractSockJsSession session) throws Exception { <add> HandlerProvider<WebSocketHandler> webSocketHandler, AbstractSockJsSession session) throws Exception { <ide> <ide> if (session == null) { <ide> response.setStatusCode(HttpStatus.NOT_FOUND); <ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/transport/AbstractHttpSendingTransportHandler.java <ide> import org.springframework.sockjs.server.SockJsConfiguration; <ide> import org.springframework.sockjs.server.SockJsFrame; <ide> import org.springframework.sockjs.server.SockJsFrame.FrameFormat; <add>import org.springframework.websocket.HandlerProvider; <ide> import org.springframework.websocket.WebSocketHandler; <ide> <ide> /** <ide> public SockJsConfiguration getSockJsConfig() { <ide> <ide> @Override <ide> public final void handleRequest(ServerHttpRequest request, ServerHttpResponse response, <del> WebSocketHandler webSocketHandler, AbstractSockJsSession session) throws Exception { <add> HandlerProvider<WebSocketHandler> webSocketHandler, AbstractSockJsSession session) throws Exception { <ide> <ide> // Set content type before writing <ide> response.getHeaders().setContentType(getContentType()); <ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/transport/AbstractHttpServerSockJsSession.java <ide> import org.springframework.sockjs.server.TransportHandler; <ide> import org.springframework.util.Assert; <ide> import org.springframework.websocket.CloseStatus; <add>import org.springframework.websocket.HandlerProvider; <ide> import org.springframework.websocket.WebSocketHandler; <ide> <ide> /** <ide> public abstract class AbstractHttpServerSockJsSession extends AbstractServerSock <ide> <ide> <ide> public AbstractHttpServerSockJsSession(String sessionId, SockJsConfiguration sockJsConfig, <del> WebSocketHandler webSocketHandler) { <add> HandlerProvider<WebSocketHandler> handler) { <ide> <del> super(sessionId, sockJsConfig, webSocketHandler); <add> super(sessionId, sockJsConfig, handler); <ide> } <ide> <ide> public void setFrameFormat(FrameFormat frameFormat) { <ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/transport/AbstractStreamingTransportHandler.java <ide> import org.springframework.http.server.ServerHttpRequest; <ide> import org.springframework.http.server.ServerHttpResponse; <ide> import org.springframework.util.Assert; <add>import org.springframework.websocket.HandlerProvider; <ide> import org.springframework.websocket.WebSocketHandler; <ide> <ide> <ide> public abstract class AbstractStreamingTransportHandler extends AbstractHttpSend <ide> <ide> <ide> @Override <del> public StreamingServerSockJsSession createSession(String sessionId, WebSocketHandler webSocketHandler) { <add> public StreamingServerSockJsSession createSession(String sessionId, HandlerProvider<WebSocketHandler> handler) { <ide> Assert.notNull(getSockJsConfig(), "This transport requires SockJsConfiguration"); <del> return new StreamingServerSockJsSession(sessionId, getSockJsConfig(), webSocketHandler); <add> return new StreamingServerSockJsSession(sessionId, getSockJsConfig(), handler); <ide> } <ide> <ide> @Override <ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/transport/JsonpPollingTransportHandler.java <ide> import org.springframework.util.Assert; <ide> import org.springframework.util.StringUtils; <ide> import org.springframework.web.util.JavaScriptUtils; <add>import org.springframework.websocket.HandlerProvider; <ide> import org.springframework.websocket.WebSocketHandler; <ide> <ide> <ide> protected MediaType getContentType() { <ide> } <ide> <ide> @Override <del> public PollingServerSockJsSession createSession(String sessionId, WebSocketHandler webSocketHandler) { <add> public PollingServerSockJsSession createSession(String sessionId, HandlerProvider<WebSocketHandler> handler) { <ide> Assert.notNull(getSockJsConfig(), "This transport requires SockJsConfiguration"); <del> return new PollingServerSockJsSession(sessionId, getSockJsConfig(), webSocketHandler); <add> return new PollingServerSockJsSession(sessionId, getSockJsConfig(), handler); <ide> } <ide> <ide> @Override <ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/transport/PollingServerSockJsSession.java <ide> <ide> import org.springframework.sockjs.server.SockJsConfiguration; <ide> import org.springframework.sockjs.server.SockJsFrame; <add>import org.springframework.websocket.HandlerProvider; <ide> import org.springframework.websocket.WebSocketHandler; <ide> <ide> <ide> public class PollingServerSockJsSession extends AbstractHttpServerSockJsSession { <ide> <ide> public PollingServerSockJsSession(String sessionId, SockJsConfiguration sockJsConfig, <del> WebSocketHandler webSocketHandler) { <add> HandlerProvider<WebSocketHandler> handler) { <ide> <del> super(sessionId, sockJsConfig, webSocketHandler); <add> super(sessionId, sockJsConfig, handler); <ide> } <ide> <ide> @Override <ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/transport/SockJsWebSocketHandler.java <ide> package org.springframework.sockjs.server.transport; <ide> <ide> import java.io.IOException; <del>import java.util.Map; <del>import java.util.concurrent.ConcurrentHashMap; <ide> <ide> import org.apache.commons.logging.Log; <ide> import org.apache.commons.logging.LogFactory; <ide> import org.springframework.util.Assert; <ide> import org.springframework.util.StringUtils; <ide> import org.springframework.websocket.CloseStatus; <add>import org.springframework.websocket.HandlerProvider; <ide> import org.springframework.websocket.TextMessage; <ide> import org.springframework.websocket.TextMessageHandler; <ide> import org.springframework.websocket.WebSocketHandler; <ide> <ide> <ide> /** <del> * A SockJS implementation of {@link WebSocketHandler}. Delegates messages to and from a <del> * {@link SockJsHandler} and adds SockJS message framing. <add> * A wrapper around a {@link WebSocketHandler} instance that parses and adds SockJS <add> * messages frames as well as sends SockJS heartbeat messages. <ide> * <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> public class SockJsWebSocketHandler implements TextMessageHandler { <ide> <ide> private final SockJsConfiguration sockJsConfig; <ide> <del> private final WebSocketHandler webSocketHandler; <add> private final HandlerProvider<WebSocketHandler> handlerProvider; <ide> <del> private final Map<WebSocketSession, AbstractSockJsSession> sessions = <del> new ConcurrentHashMap<WebSocketSession, AbstractSockJsSession>(); <add> private AbstractSockJsSession session; <ide> <ide> // TODO: JSON library used must be configurable <ide> private final ObjectMapper objectMapper = new ObjectMapper(); <ide> <ide> <del> public SockJsWebSocketHandler(SockJsConfiguration sockJsConfig, WebSocketHandler webSocketHandler) { <del> Assert.notNull(sockJsConfig, "sockJsConfig is required"); <del> Assert.notNull(webSocketHandler, "webSocketHandler is required"); <del> this.sockJsConfig = sockJsConfig; <del> this.webSocketHandler = webSocketHandler; <add> public SockJsWebSocketHandler(SockJsConfiguration config, HandlerProvider<WebSocketHandler> handlerProvider) { <add> Assert.notNull(config, "sockJsConfig is required"); <add> Assert.notNull(handlerProvider, "handlerProvider is required"); <add> this.sockJsConfig = config; <add> this.handlerProvider = handlerProvider; <ide> } <ide> <ide> protected SockJsConfiguration getSockJsConfig() { <ide> return this.sockJsConfig; <ide> } <ide> <del> protected AbstractSockJsSession getSockJsSession(WebSocketSession wsSession) { <del> return this.sessions.get(wsSession); <del> } <del> <ide> @Override <ide> public void afterConnectionEstablished(WebSocketSession wsSession) throws Exception { <del> AbstractSockJsSession session = new WebSocketServerSockJsSession(wsSession, getSockJsConfig()); <del> this.sessions.put(wsSession, session); <add> this.session = new WebSocketServerSockJsSession(wsSession, getSockJsConfig()); <ide> } <ide> <ide> @Override <ide> public void handleTextMessage(TextMessage message, WebSocketSession wsSession) t <ide> } <ide> try { <ide> String[] messages = this.objectMapper.readValue(payload, String[].class); <del> AbstractSockJsSession session = getSockJsSession(wsSession); <del> session.delegateMessages(messages); <add> this.session.delegateMessages(messages); <ide> } <ide> catch (IOException e) { <ide> logger.error("Broken data received. Terminating WebSocket connection abruptly", e); <ide> public void handleTextMessage(TextMessage message, WebSocketSession wsSession) t <ide> <ide> @Override <ide> public void afterConnectionClosed(CloseStatus status, WebSocketSession wsSession) throws Exception { <del> AbstractSockJsSession session = this.sessions.remove(wsSession); <del> session.delegateConnectionClosed(status); <add> this.session.delegateConnectionClosed(status); <ide> } <ide> <ide> @Override <ide> public void handleError(Throwable exception, WebSocketSession webSocketSession) { <del> AbstractSockJsSession session = getSockJsSession(webSocketSession); <del> session.delegateError(exception); <add> this.session.delegateError(exception); <ide> } <ide> <ide> private static String getSockJsSessionId(WebSocketSession wsSession) { <ide> private class WebSocketServerSockJsSession extends AbstractServerSockJsSession { <ide> public WebSocketServerSockJsSession(WebSocketSession wsSession, SockJsConfiguration sockJsConfig) <ide> throws Exception { <ide> <del> super(getSockJsSessionId(wsSession), sockJsConfig, SockJsWebSocketHandler.this.webSocketHandler); <add> super(getSockJsSessionId(wsSession), sockJsConfig, SockJsWebSocketHandler.this.handlerProvider); <ide> this.wsSession = wsSession; <ide> TextMessage message = new TextMessage(SockJsFrame.openFrame().getContent()); <ide> this.wsSession.sendMessage(message); <ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/transport/StreamingServerSockJsSession.java <ide> import org.springframework.http.server.ServerHttpResponse; <ide> import org.springframework.sockjs.server.SockJsConfiguration; <ide> import org.springframework.sockjs.server.SockJsFrame; <add>import org.springframework.websocket.HandlerProvider; <ide> import org.springframework.websocket.WebSocketHandler; <ide> <ide> <ide> public class StreamingServerSockJsSession extends AbstractHttpServerSockJsSessio <ide> <ide> <ide> public StreamingServerSockJsSession(String sessionId, SockJsConfiguration sockJsConfig, <del> WebSocketHandler webSocketHandler) { <add> HandlerProvider<WebSocketHandler> handler) { <ide> <del> super(sessionId, sockJsConfig, webSocketHandler); <add> super(sessionId, sockJsConfig, handler); <ide> } <ide> <ide> protected void flushCache() throws Exception { <ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/transport/WebSocketTransportHandler.java <ide> import org.springframework.sockjs.server.TransportHandler; <ide> import org.springframework.sockjs.server.TransportType; <ide> import org.springframework.util.Assert; <add>import org.springframework.websocket.HandlerProvider; <ide> import org.springframework.websocket.WebSocketHandler; <ide> import org.springframework.websocket.server.HandshakeHandler; <add>import org.springframework.websocket.support.SimpleHandlerProvider; <ide> <ide> <ide> /** <ide> public void setSockJsConfiguration(SockJsConfiguration sockJsConfig) { <ide> <ide> @Override <ide> public void handleRequest(ServerHttpRequest request, ServerHttpResponse response, <del> WebSocketHandler webSocketHandler, AbstractSockJsSession session) throws Exception { <add> HandlerProvider<WebSocketHandler> handler, AbstractSockJsSession session) throws Exception { <ide> <del> this.handshakeHandler.doHandshake(request, response, adaptSockJsHandler(webSocketHandler)); <del> } <del> <del> /** <del> * Adapt the {@link SockJsHandler} to the {@link WebSocketHandler} contract for <del> * exchanging SockJS message over WebSocket. <del> */ <del> protected WebSocketHandler adaptSockJsHandler(WebSocketHandler handler) { <del> return new SockJsWebSocketHandler(this.sockJsConfig, handler); <add> WebSocketHandler sockJsWrapper = new SockJsWebSocketHandler(this.sockJsConfig, handler); <add> this.handshakeHandler.doHandshake(request, response, new SimpleHandlerProvider<WebSocketHandler>(sockJsWrapper)); <ide> } <ide> <ide> // HandshakeHandler methods <ide> <ide> @Override <ide> public boolean doHandshake(ServerHttpRequest request, ServerHttpResponse response, <del> WebSocketHandler webSocketHandler) throws Exception { <add> HandlerProvider<WebSocketHandler> handler) throws Exception { <ide> <del> return this.handshakeHandler.doHandshake(request, response, webSocketHandler); <add> return this.handshakeHandler.doHandshake(request, response, handler); <ide> } <ide> <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/transport/XhrPollingTransportHandler.java <ide> import org.springframework.sockjs.server.SockJsFrame.FrameFormat; <ide> import org.springframework.sockjs.server.TransportType; <ide> import org.springframework.util.Assert; <add>import org.springframework.websocket.HandlerProvider; <ide> import org.springframework.websocket.WebSocketHandler; <ide> <ide> <ide> protected FrameFormat getFrameFormat(ServerHttpRequest request) { <ide> return new DefaultFrameFormat("%s\n"); <ide> } <ide> <del> public PollingServerSockJsSession createSession(String sessionId, WebSocketHandler webSocketHandler) { <add> public PollingServerSockJsSession createSession(String sessionId, HandlerProvider<WebSocketHandler> handler) { <ide> Assert.notNull(getSockJsConfig(), "This transport requires SockJsConfiguration"); <del> return new PollingServerSockJsSession(sessionId, getSockJsConfig(), webSocketHandler); <add> return new PollingServerSockJsSession(sessionId, getSockJsConfig(), handler); <ide> } <ide> <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/websocket/HandlerProvider.java <ide> * you may not use this file except in compliance with the License. <ide> * You may obtain a copy of the License at <ide> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <add> * http://www.apache.org/licenses/LICENSE-2.0 <ide> * <ide> * Unless required by applicable law or agreed to in writing, software <ide> * distributed under the License is distributed on an "AS IS" BASIS, <ide> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <ide> * See the License for the specific language governing permissions and <ide> * limitations under the License. <ide> */ <del> <ide> package org.springframework.websocket; <ide> <del>import org.apache.commons.logging.Log; <del>import org.apache.commons.logging.LogFactory; <del>import org.springframework.beans.BeansException; <del>import org.springframework.beans.factory.BeanFactory; <del>import org.springframework.beans.factory.BeanFactoryAware; <del>import org.springframework.beans.factory.config.AutowireCapableBeanFactory; <del>import org.springframework.util.Assert; <del>import org.springframework.util.ClassUtils; <del> <ide> <ide> /** <add> * A strategy for obtaining a handler instance that is scoped to external lifecycle events <add> * such as the opening and closing of a WebSocket connection. <ide> * <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> */ <del>public class HandlerProvider<T> implements BeanFactoryAware { <del> <del> private Log logger = LogFactory.getLog(this.getClass()); <del> <del> private final T handlerBean; <del> <del> private final Class<? extends T> handlerClass; <del> <del> private AutowireCapableBeanFactory beanFactory; <del> <del> <del> public HandlerProvider(T handlerBean) { <del> Assert.notNull(handlerBean, "handlerBean is required"); <del> this.handlerBean = handlerBean; <del> this.handlerClass = null; <del> } <del> <del> public HandlerProvider(Class<? extends T> handlerClass) { <del> Assert.notNull(handlerClass, "handlerClass is required"); <del> this.handlerBean = null; <del> this.handlerClass = handlerClass; <del> } <del> <del> @Override <del> public void setBeanFactory(BeanFactory beanFactory) throws BeansException { <del> if (beanFactory instanceof AutowireCapableBeanFactory) { <del> this.beanFactory = (AutowireCapableBeanFactory) beanFactory; <del> } <del> } <del> <del> public void setLogger(Log logger) { <del> this.logger = logger; <del> } <del> <del> public boolean isSingleton() { <del> return (this.handlerBean != null); <del> } <del> <del> @SuppressWarnings("unchecked") <del> public Class<? extends T> getHandlerType() { <del> if (this.handlerClass != null) { <del> return this.handlerClass; <del> } <del> return (Class<? extends T>) ClassUtils.getUserClass(this.handlerBean.getClass()); <del> } <del> <del> public T getHandler() { <del> if (this.handlerBean != null) { <del> if (logger != null && logger.isTraceEnabled()) { <del> logger.trace("Returning handler singleton " + this.handlerBean); <del> } <del> return this.handlerBean; <del> } <del> Assert.isTrue(this.beanFactory != null, "BeanFactory is required to initialize handler instances."); <del> if (logger != null && logger.isTraceEnabled()) { <del> logger.trace("Creating handler of type " + this.handlerClass); <del> } <del> return this.beanFactory.createBean(this.handlerClass); <del> } <add>public interface HandlerProvider<T> { <add> <add> /** <add> * Whether the provided handler is a shared instance or not. <add> */ <add> boolean isSingleton(); <add> <add> /** <add> * The type of handler provided. <add> */ <add> Class<?> getHandlerType(); <add> <add> /** <add> * Obtain the handler instance, either shared or created every time. <add> */ <add> T getHandler(); <add> <add> /** <add> * Callback to destroy a previously created handler instance if it is not shared. <add> */ <add> void destroy(T handler); <ide> <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/websocket/client/WebSocketClient.java <ide> import java.net.URI; <ide> <ide> import org.springframework.http.HttpHeaders; <add>import org.springframework.websocket.HandlerProvider; <ide> import org.springframework.websocket.WebSocketHandler; <ide> import org.springframework.websocket.WebSocketSession; <ide> <ide> public interface WebSocketClient { <ide> <ide> <del> WebSocketSession doHandshake(WebSocketHandler handler, String uriTemplate, Object... uriVariables) <del> throws WebSocketConnectFailureException; <del> <del> WebSocketSession doHandshake(WebSocketHandler handler, URI uri) <del> throws WebSocketConnectFailureException; <add> WebSocketSession doHandshake(HandlerProvider<WebSocketHandler> handler, <add> String uriTemplate, Object... uriVariables) throws WebSocketConnectFailureException; <ide> <del> WebSocketSession doHandshake(WebSocketHandler handler, HttpHeaders headers, URI uri) <add> WebSocketSession doHandshake(HandlerProvider<WebSocketHandler> handler, HttpHeaders headers, URI uri) <ide> throws WebSocketConnectFailureException; <ide> <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/websocket/client/WebSocketConnectionManager.java <ide> import org.springframework.websocket.HandlerProvider; <ide> import org.springframework.websocket.WebSocketHandler; <ide> import org.springframework.websocket.WebSocketSession; <add>import org.springframework.websocket.support.SimpleHandlerProvider; <ide> <ide> <ide> /** <ide> public class WebSocketConnectionManager extends AbstractWebSocketConnectionManag <ide> <ide> private final WebSocketClient client; <ide> <del> private final HandlerProvider<WebSocketHandler> webSocketHandlerProvider; <add> private final HandlerProvider<WebSocketHandler> handlerProvider; <ide> <ide> private WebSocketSession webSocketSession; <ide> <ide> public WebSocketConnectionManager(WebSocketClient webSocketClient, <ide> WebSocketHandler webSocketHandler, String uriTemplate, Object... uriVariables) { <ide> <ide> super(uriTemplate, uriVariables); <del> this.webSocketHandlerProvider = new HandlerProvider<WebSocketHandler>(webSocketHandler); <ide> this.client = webSocketClient; <add> this.handlerProvider = new SimpleHandlerProvider<WebSocketHandler>(webSocketHandler); <add> } <add> <add> public WebSocketConnectionManager(WebSocketClient webSocketClient, <add> HandlerProvider<WebSocketHandler> handlerProvider, String uriTemplate, Object... uriVariables) { <add> <add> super(uriTemplate, uriVariables); <add> this.client = webSocketClient; <add> this.handlerProvider = handlerProvider; <ide> } <ide> <ide> public void setSubProtocols(List<String> subProtocols) { <ide> public List<String> getSubProtocols() { <ide> <ide> @Override <ide> protected void openConnection() throws Exception { <del> WebSocketHandler webSocketHandler = this.webSocketHandlerProvider.getHandler(); <ide> HttpHeaders headers = new HttpHeaders(); <ide> headers.setSecWebSocketProtocol(this.subProtocols); <del> this.webSocketSession = this.client.doHandshake(webSocketHandler, headers, getUri()); <add> this.webSocketSession = this.client.doHandshake(this.handlerProvider, headers, getUri()); <ide> } <ide> <ide> @Override <ide><path>spring-websocket/src/main/java/org/springframework/websocket/client/endpoint/AnnotatedEndpointConnectionManager.java <ide> import org.springframework.beans.factory.BeanFactory; <ide> import org.springframework.beans.factory.BeanFactoryAware; <ide> import org.springframework.websocket.HandlerProvider; <add>import org.springframework.websocket.support.BeanCreatingHandlerProvider; <add>import org.springframework.websocket.support.SimpleHandlerProvider; <ide> <ide> <ide> /** <ide> public class AnnotatedEndpointConnectionManager extends EndpointConnectionManagerSupport <ide> implements BeanFactoryAware { <ide> <del> private final HandlerProvider<Object> endpointProvider; <add> private final HandlerProvider<Object> handlerProvider; <ide> <ide> <del> public AnnotatedEndpointConnectionManager(Class<?> endpointClass, String uriTemplate, Object... uriVariables) { <add> public AnnotatedEndpointConnectionManager(Object endpointBean, String uriTemplate, Object... uriVariables) { <ide> super(uriTemplate, uriVariables); <del> this.endpointProvider = new HandlerProvider<Object>(endpointClass); <add> this.handlerProvider = new SimpleHandlerProvider<Object>(endpointBean); <ide> } <ide> <del> public AnnotatedEndpointConnectionManager(Object endpointBean, String uriTemplate, Object... uriVariables) { <add> public AnnotatedEndpointConnectionManager(Class<?> endpointClass, String uriTemplate, Object... uriVariables) { <ide> super(uriTemplate, uriVariables); <del> this.endpointProvider = new HandlerProvider<Object>(endpointBean); <add> this.handlerProvider = new BeanCreatingHandlerProvider<Object>(endpointClass); <ide> } <ide> <ide> @Override <ide> public void setBeanFactory(BeanFactory beanFactory) throws BeansException { <del> this.endpointProvider.setBeanFactory(beanFactory); <add> if (this.handlerProvider instanceof BeanFactoryAware) { <add> ((BeanFactoryAware) this.handlerProvider).setBeanFactory(beanFactory); <add> } <ide> } <ide> <del> <ide> @Override <ide> protected void openConnection() throws Exception { <del> Object endpoint = this.endpointProvider.getHandler(); <add> Object endpoint = this.handlerProvider.getHandler(); <ide> Session session = getWebSocketContainer().connectToServer(endpoint, getUri()); <ide> updateSession(session); <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/websocket/client/endpoint/EndpointConnectionManager.java <ide> import org.springframework.beans.factory.BeanFactoryAware; <ide> import org.springframework.util.Assert; <ide> import org.springframework.websocket.HandlerProvider; <add>import org.springframework.websocket.support.BeanCreatingHandlerProvider; <add>import org.springframework.websocket.support.SimpleHandlerProvider; <ide> <ide> <ide> /** <ide> public class EndpointConnectionManager extends EndpointConnectionManagerSupport <ide> <ide> private final ClientEndpointConfig.Builder configBuilder = ClientEndpointConfig.Builder.create(); <ide> <del> private final HandlerProvider<Endpoint> endpointProvider; <add> private final HandlerProvider<Endpoint> handlerProvider; <ide> <ide> <ide> public EndpointConnectionManager(Endpoint endpointBean, String uriTemplate, Object... uriVariables) { <ide> super(uriTemplate, uriVariables); <ide> Assert.notNull(endpointBean, "endpointBean is required"); <del> this.endpointProvider = new HandlerProvider<Endpoint>(endpointBean); <add> this.handlerProvider = new SimpleHandlerProvider<Endpoint>(endpointBean); <ide> } <ide> <ide> public EndpointConnectionManager(Class<? extends Endpoint> endpointClass, String uriTemplate, Object... uriVars) { <ide> super(uriTemplate, uriVars); <ide> Assert.notNull(endpointClass, "endpointClass is required"); <del> this.endpointProvider = new HandlerProvider<Endpoint>(endpointClass); <add> this.handlerProvider = new BeanCreatingHandlerProvider<Endpoint>(endpointClass); <ide> } <ide> <ide> public void setSubProtocols(String... subprotocols) { <ide> public void setConfigurator(Configurator configurator) { <ide> <ide> @Override <ide> public void setBeanFactory(BeanFactory beanFactory) throws BeansException { <del> this.endpointProvider.setBeanFactory(beanFactory); <add> if (this.handlerProvider instanceof BeanFactoryAware) { <add> ((BeanFactoryAware) this.handlerProvider).setBeanFactory(beanFactory); <add> } <ide> } <ide> <ide> @Override <ide> protected void openConnection() throws Exception { <del> Endpoint endpoint = this.endpointProvider.getHandler(); <add> Endpoint endpoint = this.handlerProvider.getHandler(); <ide> ClientEndpointConfig endpointConfig = this.configBuilder.build(); <ide> Session session = getWebSocketContainer().connectToServer(endpoint, endpointConfig, getUri()); <ide> updateSession(session); <ide><path>spring-websocket/src/main/java/org/springframework/websocket/client/endpoint/StandardWebSocketClient.java <ide> <ide> import org.springframework.http.HttpHeaders; <ide> import org.springframework.web.util.UriComponentsBuilder; <add>import org.springframework.websocket.HandlerProvider; <ide> import org.springframework.websocket.WebSocketHandler; <ide> import org.springframework.websocket.WebSocketSession; <ide> import org.springframework.websocket.client.WebSocketClient; <ide> <ide> <ide> /** <add> * A standard Java {@link WebSocketClient}. <ide> * <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> public void setWebSocketContainer(WebSocketContainer container) { <ide> this.webSocketContainer = container; <ide> } <ide> <del> public WebSocketSession doHandshake(WebSocketHandler handler, String uriTemplate, <del> Object... uriVariables) throws WebSocketConnectFailureException { <add> public WebSocketSession doHandshake(HandlerProvider<WebSocketHandler> handler, <add> String uriTemplate, Object... uriVariables) throws WebSocketConnectFailureException { <ide> <ide> URI uri = UriComponentsBuilder.fromUriString(uriTemplate).buildAndExpand(uriVariables).encode().toUri(); <del> return doHandshake(handler, uri); <del> } <del> <del> @Override <del> public WebSocketSession doHandshake(WebSocketHandler handler, URI uri) throws WebSocketConnectFailureException { <ide> return doHandshake(handler, null, uri); <ide> } <ide> <ide> @Override <del> public WebSocketSession doHandshake(WebSocketHandler handler, final HttpHeaders httpHeaders, URI uri) <del> throws WebSocketConnectFailureException { <add> public WebSocketSession doHandshake(HandlerProvider<WebSocketHandler> handler, <add> final HttpHeaders httpHeaders, URI uri) throws WebSocketConnectFailureException { <ide> <ide> Endpoint endpoint = new WebSocketHandlerEndpoint(handler); <ide> <ide><path>spring-websocket/src/main/java/org/springframework/websocket/endpoint/WebSocketHandlerEndpoint.java <ide> <ide> package org.springframework.websocket.endpoint; <ide> <del>import java.util.Map; <del>import java.util.concurrent.ConcurrentHashMap; <del> <ide> import javax.websocket.CloseReason; <ide> import javax.websocket.Endpoint; <ide> import javax.websocket.EndpointConfig; <ide> import org.apache.commons.logging.Log; <ide> import org.apache.commons.logging.LogFactory; <ide> import org.springframework.util.Assert; <del>import org.springframework.websocket.CloseStatus; <ide> import org.springframework.websocket.BinaryMessage; <ide> import org.springframework.websocket.BinaryMessageHandler; <add>import org.springframework.websocket.CloseStatus; <add>import org.springframework.websocket.HandlerProvider; <ide> import org.springframework.websocket.PartialMessageHandler; <del>import org.springframework.websocket.WebSocketHandler; <del>import org.springframework.websocket.WebSocketSession; <ide> import org.springframework.websocket.TextMessage; <ide> import org.springframework.websocket.TextMessageHandler; <add>import org.springframework.websocket.WebSocketHandler; <add>import org.springframework.websocket.WebSocketSession; <ide> <ide> <ide> /** <ide> public class WebSocketHandlerEndpoint extends Endpoint { <ide> <ide> private static Log logger = LogFactory.getLog(WebSocketHandlerEndpoint.class); <ide> <del> private final WebSocketHandler webSocketHandler; <add> private final HandlerProvider<WebSocketHandler> handlerProvider; <ide> <del> private final Map<String, WebSocketSession> sessions = new ConcurrentHashMap<String, WebSocketSession>(); <add> private final WebSocketHandler handler; <ide> <add> private WebSocketSession webSocketSession; <ide> <del> public WebSocketHandlerEndpoint(WebSocketHandler handler) { <del> Assert.notNull(handler, "webSocketHandler is required"); <del> this.webSocketHandler = handler; <add> <add> public WebSocketHandlerEndpoint(HandlerProvider<WebSocketHandler> handlerProvider) { <add> Assert.notNull(handlerProvider, "handlerProvider is required"); <add> this.handlerProvider = handlerProvider; <add> this.handler = handlerProvider.getHandler(); <ide> } <ide> <ide> @Override <ide> public void onOpen(final javax.websocket.Session session, EndpointConfig config) <ide> logger.debug("Client connected, WebSocket session id=" + session.getId() + ", uri=" + session.getRequestURI()); <ide> } <ide> try { <del> WebSocketSession webSocketSession = new StandardWebSocketSession(session); <del> this.sessions.put(session.getId(), webSocketSession); <add> this.webSocketSession = new StandardWebSocketSession(session); <ide> <del> if (this.webSocketHandler instanceof TextMessageHandler) { <add> if (this.handler instanceof TextMessageHandler) { <ide> session.addMessageHandler(new MessageHandler.Whole<String>() { <ide> @Override <ide> public void onMessage(String message) { <ide> handleTextMessage(session, message); <ide> } <ide> }); <ide> } <del> else if (this.webSocketHandler instanceof BinaryMessageHandler) { <del> if (this.webSocketHandler instanceof PartialMessageHandler) { <add> else if (this.handler instanceof BinaryMessageHandler) { <add> if (this.handler instanceof PartialMessageHandler) { <ide> session.addMessageHandler(new MessageHandler.Partial<byte[]>() { <ide> @Override <ide> public void onMessage(byte[] messagePart, boolean isLast) { <ide> public void onMessage(byte[] message) { <ide> } <ide> } <ide> else { <del> logger.warn("WebSocketHandler handles neither text nor binary messages: " + this.webSocketHandler); <add> logger.warn("WebSocketHandler handles neither text nor binary messages: " + this.handler); <ide> } <ide> <del> this.webSocketHandler.afterConnectionEstablished(webSocketSession); <add> this.handler.afterConnectionEstablished(this.webSocketSession); <ide> } <ide> catch (Throwable ex) { <ide> // TODO <ide> private void handleTextMessage(javax.websocket.Session session, String message) <ide> if (logger.isTraceEnabled()) { <ide> logger.trace("Received message for WebSocket session id=" + session.getId() + ": " + message); <ide> } <del> WebSocketSession wsSession = getWebSocketSession(session); <del> Assert.notNull(wsSession, "WebSocketSession not found"); <ide> try { <ide> TextMessage textMessage = new TextMessage(message); <del> ((TextMessageHandler) webSocketHandler).handleTextMessage(textMessage, wsSession); <add> ((TextMessageHandler) handler).handleTextMessage(textMessage, this.webSocketSession); <ide> } <ide> catch (Throwable ex) { <ide> // TODO <ide> private void handleBinaryMessage(javax.websocket.Session session, byte[] message <ide> if (logger.isTraceEnabled()) { <ide> logger.trace("Received binary data for WebSocket session id=" + session.getId()); <ide> } <del> WebSocketSession wsSession = getWebSocketSession(session); <del> Assert.notNull(wsSession, "WebSocketSession not found"); <ide> try { <ide> BinaryMessage binaryMessage = new BinaryMessage(message, isLast); <del> ((BinaryMessageHandler) webSocketHandler).handleBinaryMessage(binaryMessage, wsSession); <add> ((BinaryMessageHandler) handler).handleBinaryMessage(binaryMessage, this.webSocketSession); <ide> } <ide> catch (Throwable ex) { <ide> // TODO <ide> public void onClose(javax.websocket.Session session, CloseReason reason) { <ide> logger.debug("Client disconnected, WebSocket session id=" + session.getId() + ", " + reason); <ide> } <ide> try { <del> WebSocketSession wsSession = this.sessions.remove(session.getId()); <del> if (wsSession != null) { <del> CloseStatus closeStatus = new CloseStatus(reason.getCloseCode().getCode(), reason.getReasonPhrase()); <del> this.webSocketHandler.afterConnectionClosed(closeStatus, wsSession); <del> } <del> else { <del> Assert.notNull(wsSession, "No WebSocket session"); <del> } <add> CloseStatus closeStatus = new CloseStatus(reason.getCloseCode().getCode(), reason.getReasonPhrase()); <add> this.handler.afterConnectionClosed(closeStatus, this.webSocketSession); <ide> } <ide> catch (Throwable ex) { <ide> // TODO <ide> logger.error("Error while processing session closing", ex); <ide> } <add> finally { <add> this.handlerProvider.destroy(this.handler); <add> } <ide> } <ide> <ide> @Override <ide> public void onError(javax.websocket.Session session, Throwable exception) { <ide> logger.error("Error for WebSocket session id=" + session.getId(), exception); <ide> try { <del> WebSocketSession wsSession = getWebSocketSession(session); <del> if (wsSession != null) { <del> this.webSocketHandler.handleError(exception, wsSession); <del> } <del> else { <del> logger.warn("WebSocketSession not found. Perhaps onError was called after onClose?"); <del> } <add> this.handler.handleError(exception, this.webSocketSession); <ide> } <ide> catch (Throwable ex) { <ide> // TODO <ide> logger.error("Failed to handle error", ex); <ide> } <ide> } <ide> <del> private WebSocketSession getWebSocketSession(javax.websocket.Session session) { <del> return this.sessions.get(session.getId()); <del> } <del> <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/websocket/server/DefaultHandshakeHandler.java <ide> import org.springframework.http.server.ServerHttpResponse; <ide> import org.springframework.util.ClassUtils; <ide> import org.springframework.util.StringUtils; <add>import org.springframework.websocket.HandlerProvider; <ide> import org.springframework.websocket.WebSocketHandler; <ide> <ide> <ide> public String[] getSupportedProtocols() { <ide> <ide> @Override <ide> public final boolean doHandshake(ServerHttpRequest request, ServerHttpResponse response, <del> WebSocketHandler webSocketHandler) throws Exception { <add> HandlerProvider<WebSocketHandler> handler) throws Exception { <ide> <ide> logger.debug("Starting handshake for " + request.getURI()); <ide> <ide> public final boolean doHandshake(ServerHttpRequest request, ServerHttpResponse r <ide> response.flush(); <ide> <ide> if (logger.isTraceEnabled()) { <del> logger.trace("Upgrading with " + webSocketHandler); <add> logger.trace("Upgrading with " + handler); <ide> } <ide> <del> this.requestUpgradeStrategy.upgrade(request, response, selectedProtocol, webSocketHandler); <add> this.requestUpgradeStrategy.upgrade(request, response, selectedProtocol, handler); <ide> <ide> return true; <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/websocket/server/HandshakeHandler.java <ide> <ide> import org.springframework.http.server.ServerHttpRequest; <ide> import org.springframework.http.server.ServerHttpResponse; <add>import org.springframework.websocket.HandlerProvider; <ide> import org.springframework.websocket.WebSocketHandler; <ide> <ide> <ide> */ <ide> public interface HandshakeHandler { <ide> <del> /** <del> * <del> * @param request the HTTP request <del> * @param response the HTTP response <del> * @param webSocketMessageHandler the handler to process WebSocket messages with <del> * @return a boolean indicating whether the handshake negotiation was successful <del> * <del> * @throws Exception <del> */ <del> boolean doHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler webSocketHandler) <del> throws Exception; <add> <add> boolean doHandshake(ServerHttpRequest request, ServerHttpResponse response, <add> HandlerProvider<WebSocketHandler> handler) throws Exception; <ide> <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/websocket/server/RequestUpgradeStrategy.java <ide> <ide> import org.springframework.http.server.ServerHttpRequest; <ide> import org.springframework.http.server.ServerHttpResponse; <add>import org.springframework.websocket.HandlerProvider; <ide> import org.springframework.websocket.WebSocketHandler; <ide> <ide> <ide> public interface RequestUpgradeStrategy { <ide> * Perform runtime specific steps to complete the upgrade. <ide> * Invoked only if the handshake is successful. <ide> * <del> * @param webSocketHandler the handler for WebSocket messages <add> * @param handler the handler for WebSocket messages <ide> */ <ide> void upgrade(ServerHttpRequest request, ServerHttpResponse response, String selectedProtocol, <del> WebSocketHandler webSocketHandler) throws Exception; <add> HandlerProvider<WebSocketHandler> handler) throws Exception; <ide> <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/websocket/server/endpoint/EndpointRegistration.java <ide> import org.springframework.util.Assert; <ide> import org.springframework.websocket.HandlerProvider; <ide> import org.springframework.websocket.endpoint.WebSocketHandlerEndpoint; <add>import org.springframework.websocket.support.BeanCreatingHandlerProvider; <add>import org.springframework.websocket.support.SimpleHandlerProvider; <ide> <ide> <ide> /** <ide> */ <ide> public class EndpointRegistration implements ServerEndpointConfig, BeanFactoryAware { <ide> <del> private static Log logger = LogFactory.getLog(EndpointRegistration.class); <del> <ide> private final String path; <ide> <del> private final HandlerProvider<Endpoint> endpointProvider; <add> private final HandlerProvider<Endpoint> handlerProvider; <ide> <ide> private List<Class<? extends Encoder>> encoders = new ArrayList<Class<? extends Encoder>>(); <ide> <ide> public EndpointRegistration(String path, Class<? extends Endpoint> endpointClass <ide> Assert.hasText(path, "path must not be empty"); <ide> Assert.notNull(endpointClass, "endpointClass is required"); <ide> this.path = path; <del> this.endpointProvider = new HandlerProvider<Endpoint>(endpointClass); <del> this.endpointProvider.setLogger(logger); <add> this.handlerProvider = new BeanCreatingHandlerProvider<Endpoint>(endpointClass); <ide> } <ide> <ide> public EndpointRegistration(String path, Endpoint endpointBean) { <ide> Assert.hasText(path, "path must not be empty"); <ide> Assert.notNull(endpointBean, "endpointBean is required"); <ide> this.path = path; <del> this.endpointProvider = new HandlerProvider<Endpoint>(endpointBean); <del> this.endpointProvider.setLogger(logger); <add> this.handlerProvider = new SimpleHandlerProvider<Endpoint>(endpointBean); <ide> } <ide> <ide> @Override <ide> public String getPath() { <ide> } <ide> <ide> @Override <add> @SuppressWarnings("unchecked") <ide> public Class<? extends Endpoint> getEndpointClass() { <del> return this.endpointProvider.getHandlerType(); <add> return (Class<? extends Endpoint>) this.handlerProvider.getHandlerType(); <ide> } <ide> <ide> public Endpoint getEndpoint() { <del> return this.endpointProvider.getHandler(); <add> return this.handlerProvider.getHandler(); <ide> } <ide> <ide> public void setSubprotocols(List<String> subprotocols) { <ide> public List<Extension> getNegotiatedExtensions(List<Extension> installed, List<E <ide> <ide> @Override <ide> public void setBeanFactory(BeanFactory beanFactory) throws BeansException { <del> this.endpointProvider.setBeanFactory(beanFactory); <add> if (this.handlerProvider instanceof BeanFactoryAware) { <add> ((BeanFactoryAware) this.handlerProvider).setBeanFactory(beanFactory); <add> } <ide> } <ide> <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/websocket/server/support/AbstractEndpointContainerFactoryBean.java <del>/* <del> * Copyright 2002-2013 the original author or authors. <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> */ <del>package org.springframework.websocket.server.support; <del> <del>import javax.websocket.WebSocketContainer; <del> <del>import org.springframework.beans.factory.FactoryBean; <del>import org.springframework.beans.factory.InitializingBean; <del> <del> <del>/** <del>* <del>* @author Rossen Stoyanchev <del>* @since 4.0 <del>*/ <del>public abstract class AbstractEndpointContainerFactoryBean implements FactoryBean<WebSocketContainer>, InitializingBean { <del> <del> private WebSocketContainer container; <del> <del> <del> public void setAsyncSendTimeout(long timeoutInMillis) { <del> this.container.setAsyncSendTimeout(timeoutInMillis); <del> } <del> <del> public long getAsyncSendTimeout() { <del> return this.container.getDefaultAsyncSendTimeout(); <del> } <del> <del> public void setMaxSessionIdleTimeout(long timeoutInMillis) { <del> this.container.setDefaultMaxSessionIdleTimeout(timeoutInMillis); <del> } <del> <del> public long getMaxSessionIdleTimeout() { <del> return this.container.getDefaultMaxSessionIdleTimeout(); <del> } <del> <del> public void setMaxTextMessageBufferSize(int bufferSize) { <del> this.container.setDefaultMaxTextMessageBufferSize(bufferSize); <del> } <del> <del> public int getMaxTextMessageBufferSize() { <del> return this.container.getDefaultMaxTextMessageBufferSize(); <del> } <del> <del> public void setMaxBinaryMessageBufferSize(int bufferSize) { <del> this.container.setDefaultMaxBinaryMessageBufferSize(bufferSize); <del> } <del> <del> public int getMaxBinaryMessageBufferSize() { <del> return this.container.getDefaultMaxBinaryMessageBufferSize(); <del> } <del> <del> @Override <del> public void afterPropertiesSet() throws Exception { <del> this.container = getContainer(); <del> } <del> <del> protected abstract WebSocketContainer getContainer(); <del> <del> @Override <del> public WebSocketContainer getObject() throws Exception { <del> return this.container; <del> } <del> <del> @Override <del> public Class<?> getObjectType() { <del> return WebSocketContainer.class; <del> } <del> <del> @Override <del> public boolean isSingleton() { <del> return true; <del> } <del> <del>} <ide><path>spring-websocket/src/main/java/org/springframework/websocket/server/support/AbstractEndpointUpgradeStrategy.java <ide> import org.apache.commons.logging.LogFactory; <ide> import org.springframework.http.server.ServerHttpRequest; <ide> import org.springframework.http.server.ServerHttpResponse; <add>import org.springframework.websocket.HandlerProvider; <ide> import org.springframework.websocket.WebSocketHandler; <ide> import org.springframework.websocket.endpoint.WebSocketHandlerEndpoint; <ide> import org.springframework.websocket.server.RequestUpgradeStrategy; <ide> public abstract class AbstractEndpointUpgradeStrategy implements RequestUpgradeS <ide> <ide> @Override <ide> public void upgrade(ServerHttpRequest request, ServerHttpResponse response, <del> String protocol, WebSocketHandler webSocketHandler) throws Exception { <add> String protocol, HandlerProvider<WebSocketHandler> handler) throws Exception { <ide> <del> upgradeInternal(request, response, protocol, adaptWebSocketHandler(webSocketHandler)); <add> upgradeInternal(request, response, protocol, adaptWebSocketHandler(handler)); <ide> } <ide> <del> protected Endpoint adaptWebSocketHandler(WebSocketHandler handler) { <add> protected Endpoint adaptWebSocketHandler(HandlerProvider<WebSocketHandler> handler) { <ide> return new WebSocketHandlerEndpoint(handler); <ide> } <ide> <ide><path>spring-websocket/src/main/java/org/springframework/websocket/server/support/WebSocketHttpRequestHandler.java <ide> import javax.servlet.http.HttpServletRequest; <ide> import javax.servlet.http.HttpServletResponse; <ide> <del>import org.springframework.beans.BeansException; <del>import org.springframework.beans.factory.BeanFactory; <del>import org.springframework.beans.factory.BeanFactoryAware; <ide> import org.springframework.http.server.ServerHttpRequest; <ide> import org.springframework.http.server.ServerHttpResponse; <ide> import org.springframework.http.server.ServletServerHttpRequest; <ide> import org.springframework.websocket.WebSocketHandler; <ide> import org.springframework.websocket.server.DefaultHandshakeHandler; <ide> import org.springframework.websocket.server.HandshakeHandler; <add>import org.springframework.websocket.support.SimpleHandlerProvider; <ide> <ide> <ide> /** <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> */ <del>public class WebSocketHttpRequestHandler implements HttpRequestHandler, BeanFactoryAware { <add>public class WebSocketHttpRequestHandler implements HttpRequestHandler { <ide> <ide> private HandshakeHandler handshakeHandler; <ide> <ide> public class WebSocketHttpRequestHandler implements HttpRequestHandler, BeanFact <ide> <ide> public WebSocketHttpRequestHandler(WebSocketHandler webSocketHandler) { <ide> Assert.notNull(webSocketHandler, "webSocketHandler is required"); <del> this.handlerProvider = new HandlerProvider<WebSocketHandler>(webSocketHandler); <add> this.handlerProvider = new SimpleHandlerProvider<WebSocketHandler>(webSocketHandler); <ide> this.handshakeHandler = new DefaultHandshakeHandler(); <ide> } <ide> <del> public WebSocketHttpRequestHandler( Class<? extends WebSocketHandler> webSocketHandlerClass) { <del> Assert.notNull(webSocketHandlerClass, "webSocketHandlerClass is required"); <del> this.handlerProvider = new HandlerProvider<WebSocketHandler>(webSocketHandlerClass); <add> public WebSocketHttpRequestHandler( HandlerProvider<WebSocketHandler> handlerProvider) { <add> Assert.notNull(handlerProvider, "handlerProvider is required"); <add> this.handlerProvider = handlerProvider; <ide> } <ide> <ide> public void setHandshakeHandler(HandshakeHandler handshakeHandler) { <ide> Assert.notNull(handshakeHandler, "handshakeHandler is required"); <ide> this.handshakeHandler = handshakeHandler; <ide> } <ide> <del> @Override <del> public void setBeanFactory(BeanFactory beanFactory) throws BeansException { <del> this.handlerProvider.setBeanFactory(beanFactory); <del> } <del> <ide> @Override <ide> public void handleRequest(HttpServletRequest request, HttpServletResponse response) <ide> throws ServletException, IOException { <ide> public void handleRequest(HttpServletRequest request, HttpServletResponse respon <ide> ServerHttpResponse httpResponse = new ServletServerHttpResponse(response); <ide> <ide> try { <del> WebSocketHandler webSocketHandler = this.handlerProvider.getHandler(); <del> this.handshakeHandler.doHandshake(httpRequest, httpResponse, webSocketHandler); <add> this.handshakeHandler.doHandshake(httpRequest, httpResponse, this.handlerProvider); <ide> } <ide> catch (Exception e) { <ide> // TODO <ide><path>spring-websocket/src/main/java/org/springframework/websocket/support/BeanCreatingHandlerProvider.java <add>/* <add> * Copyright 2002-2013 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * 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> <add>package org.springframework.websocket.support; <add> <add>import org.apache.commons.logging.Log; <add>import org.apache.commons.logging.LogFactory; <add>import org.springframework.beans.BeanUtils; <add>import org.springframework.beans.BeansException; <add>import org.springframework.beans.factory.BeanFactory; <add>import org.springframework.beans.factory.BeanFactoryAware; <add>import org.springframework.beans.factory.config.AutowireCapableBeanFactory; <add>import org.springframework.util.Assert; <add>import org.springframework.websocket.HandlerProvider; <add> <add> <add>/** <add> * A {@link HandlerProvider} that uses {@link AutowireCapableBeanFactory#createBean(Class) <add> * creating a fresh instance every time #getHandler() is called. <add> * <add> * @author Rossen Stoyanchev <add> * @since 4.0 <add> */ <add>public class BeanCreatingHandlerProvider<T> implements HandlerProvider<T>, BeanFactoryAware { <add> <add> private static final Log logger = LogFactory.getLog(BeanCreatingHandlerProvider.class); <add> <add> private final Class<? extends T> handlerClass; <add> <add> private AutowireCapableBeanFactory beanFactory; <add> <add> <add> public BeanCreatingHandlerProvider(Class<? extends T> handlerClass) { <add> Assert.notNull(handlerClass, "handlerClass is required"); <add> this.handlerClass = handlerClass; <add> } <add> <add> @Override <add> public void setBeanFactory(BeanFactory beanFactory) throws BeansException { <add> if (beanFactory instanceof AutowireCapableBeanFactory) { <add> this.beanFactory = (AutowireCapableBeanFactory) beanFactory; <add> } <add> } <add> <add> public boolean isSingleton() { <add> return false; <add> } <add> <add> public Class<? extends T> getHandlerType() { <add> return this.handlerClass; <add> } <add> <add> public T getHandler() { <add> if (logger.isTraceEnabled()) { <add> logger.trace("Creating instance for handler type " + this.handlerClass); <add> } <add> if (this.beanFactory == null) { <add> logger.warn("No BeanFactory available, attempting to use default constructor"); <add> return BeanUtils.instantiate(this.handlerClass); <add> } <add> else { <add> return this.beanFactory.createBean(this.handlerClass); <add> } <add> } <add> <add> @Override <add> public void destroy(T handler) { <add> if (this.beanFactory != null) { <add> if (logger.isTraceEnabled()) { <add> logger.trace("Destroying handler instance " + handler); <add> } <add> this.beanFactory.destroyBean(handler); <add> } <add> } <add> <add> @Override <add> public String toString() { <add> return "BeanCreatingHandlerProvider [handlerClass=" + handlerClass + "]"; <add> } <add> <add>} <ide><path>spring-websocket/src/main/java/org/springframework/websocket/support/SimpleHandlerProvider.java <add>/* <add> * Copyright 2002-2013 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * 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>package org.springframework.websocket.support; <add> <add>import org.springframework.util.ClassUtils; <add>import org.springframework.websocket.HandlerProvider; <add> <add> <add>/** <add> * A {@link HandlerProvider} that returns a singleton instance. <add> * <add> * @author Rossen Stoyanchev <add> * @since 4.0 <add> */ <add>public class SimpleHandlerProvider<T> implements HandlerProvider<T> { <add> <add> private final T handler; <add> <add> <add> public SimpleHandlerProvider(T handler) { <add> this.handler = handler; <add> } <add> <add> @Override <add> public boolean isSingleton() { <add> return true; <add> } <add> <add> @Override <add> public Class<?> getHandlerType() { <add> return ClassUtils.getUserClass(this.handler); <add> } <add> <add> @Override <add> public T getHandler() { <add> return this.handler; <add> } <add> <add> @Override <add> public void destroy(T handler) { <add> } <add> <add> @Override <add> public String toString() { <add> return "SimpleHandlerProvider [handler=" + handler + "]"; <add> } <add> <add>}
34
Ruby
Ruby
run a single eventmachine timer to send heartbeats
b099a7d2705428a4434813079f399dec54ec7611
<ide><path>lib/action_cable/connection.rb <ide> module ActionCable <ide> module Connection <ide> autoload :Authorization, 'action_cable/connection/authorization' <ide> autoload :Base, 'action_cable/connection/base' <del> autoload :Heartbeat, 'action_cable/connection/heartbeat' <ide> autoload :Identification, 'action_cable/connection/identification' <ide> autoload :InternalChannel, 'action_cable/connection/internal_channel' <ide> autoload :MessageBuffer, 'action_cable/connection/message_buffer' <ide><path>lib/action_cable/connection/base.rb <ide> def initialize(server, env) <ide> @logger = new_tagged_logger <ide> <ide> @websocket = ActionCable::Connection::WebSocket.new(env) <del> @heartbeat = ActionCable::Connection::Heartbeat.new(self) <ide> @subscriptions = ActionCable::Connection::Subscriptions.new(self) <ide> @message_buffer = ActionCable::Connection::MessageBuffer.new(self) <ide> <ide> def statistics <ide> { identifier: connection_identifier, started_at: @started_at, subscriptions: subscriptions.identifiers } <ide> end <ide> <add> def beat <add> transmit({ identifier: '_ping', message: Time.now.to_i }.to_json) <add> end <add> <ide> <ide> protected <ide> # The request that initiated the websocket connection is available here. This gives access to the environment, cookies, etc. <ide> def cookies <ide> <ide> private <ide> attr_reader :websocket <del> attr_reader :heartbeat, :subscriptions, :message_buffer <add> attr_reader :subscriptions, :message_buffer <ide> <ide> def on_open <ide> server.add_connection(self) <ide> <ide> connect if respond_to?(:connect) <ide> subscribe_to_internal_channel <del> heartbeat.start <add> beat <ide> <ide> message_buffer.process! <ide> rescue ActionCable::Connection::Authorization::UnauthorizedError <ide> def on_close <ide> <ide> subscriptions.unsubscribe_from_all <ide> unsubscribe_from_internal_channel <del> heartbeat.stop <ide> <ide> disconnect if respond_to?(:disconnect) <ide> end <ide><path>lib/action_cable/connection/heartbeat.rb <del>module ActionCable <del> module Connection <del> # Websocket connection implementations differ on when they'll mark a connection as stale. We basically never want a connection to go stale, as you <del> # then can't rely on being able to receive and send to it. So there's a 3 second heartbeat running on all connections. If the beat fails, we automatically <del> # disconnect. <del> class Heartbeat <del> BEAT_INTERVAL = 3 <del> <del> def initialize(connection) <del> @connection = connection <del> end <del> <del> def start <del> beat <del> @timer = EventMachine.add_periodic_timer(BEAT_INTERVAL) { beat } <del> end <del> <del> def stop <del> EventMachine.cancel_timer(@timer) if @timer <del> end <del> <del> private <del> attr_reader :connection <del> <del> def beat <del> connection.transmit({ identifier: '_ping', message: Time.now.to_i }.to_json) <del> end <del> end <del> end <del>end <ide><path>lib/action_cable/server/base.rb <ide> def initialize <ide> <ide> # Called by rack to setup the server. <ide> def call(env) <add> setup_heartbeat_timer <ide> config.connection_class.new(self, env).process <ide> end <ide> <ide><path>lib/action_cable/server/connections.rb <ide> module Server <ide> # you can't use this collection as an full list of all the connections established against your application. Use RemoteConnections for that. <ide> # As such, this is primarily for internal use. <ide> module Connections <add> BEAT_INTERVAL = 3 <add> <ide> def connections <ide> @connections ||= [] <ide> end <ide> def remove_connection(connection) <ide> connections.delete connection <ide> end <ide> <add> # Websocket connection implementations differ on when they'll mark a connection as stale. We basically never want a connection to go stale, as you <add> # then can't rely on being able to receive and send to it. So there's a 3 second heartbeat running on all connections. If the beat fails, we automatically <add> # disconnect. <add> def setup_heartbeat_timer <add> @heartbeat_timer ||= EventMachine.add_periodic_timer(BEAT_INTERVAL) do <add> EM.next_tick { connections.map &:beat } <add> end <add> end <add> <ide> def open_connections_statistics <ide> connections.map(&:statistics) <ide> end <ide><path>test/connection/base_test.rb <ide> <ide> class ActionCable::Connection::BaseTest < ActiveSupport::TestCase <ide> class Connection < ActionCable::Connection::Base <del> attr_reader :websocket, :heartbeat, :subscriptions, :message_buffer, :connected <add> attr_reader :websocket, :subscriptions, :message_buffer, :connected <ide> <ide> def connect <ide> @connected = true <ide> def disconnect <ide> test "on connection open" do <ide> assert ! @connection.connected <ide> <del> EventMachine.expects(:add_periodic_timer) <ide> @connection.websocket.expects(:transmit).with(regexp_matches(/\_ping/)) <ide> @connection.message_buffer.expects(:process!) <ide> <ide> def disconnect <ide> @connection.send :on_open <ide> assert @connection.connected <ide> <del> EventMachine.expects(:cancel_timer) <ide> @connection.subscriptions.expects(:unsubscribe_from_all) <ide> @connection.send :on_close <ide>
6
Javascript
Javascript
remove old jsc workarounds in hmrclient
02633fe522c753d1ee995430e29ea3e913a0576e
<ide><path>Libraries/Utilities/HMRClient.js <ide> 'use strict'; <ide> <ide> const DevSettings = require('./DevSettings'); <del>const Platform = require('./Platform'); <ide> const invariant = require('invariant'); <del> <ide> const MetroHMRClient = require('metro/src/lib/bundle-modules/HMRClient'); <add>const Platform = require('./Platform'); <add>const prettyFormat = require('pretty-format'); <ide> <ide> import NativeRedBox from '../NativeModules/specs/NativeRedBox'; <ide> import * as LogBoxData from '../LogBox/Data/LogBoxData'; <ide> const HMRClient: HMRClientNativeInterface = { <ide> return; <ide> } <ide> try { <del> let message; <del> if (global.Symbol) { <del> message = JSON.stringify({ <add> hmrClient.send( <add> JSON.stringify({ <ide> type: 'log', <ide> level, <ide> data: data.map(item => <ide> typeof item === 'string' <ide> ? item <del> : require('pretty-format')(item, { <add> : prettyFormat(item, { <ide> escapeString: true, <ide> highlight: true, <ide> maxDepth: 3, <ide> min: true, <del> plugins: [require('pretty-format').plugins.ReactElement], <add> plugins: [prettyFormat.plugins.ReactElement], <ide> }), <ide> ), <del> }); <del> } else { <del> try { <del> message = JSON.stringify({type: 'log', level, data}); <del> } catch (error) { <del> message = JSON.stringify({ <del> type: 'log', <del> level, <del> data: [error.message], <del> }); <del> } <del> } <del> <del> hmrClient.send(message); <add> }), <add> ); <ide> } catch (error) { <ide> // If sending logs causes any failures we want to silently ignore them <ide> // to ensure we do not cause infinite-logging loops.
1
Java
Java
use array.clone() instead of manual array creation
f2b3953d765782f5bc8bc0027634a32bd2aab5c8
<ide><path>spring-aop/src/main/java/org/springframework/aop/framework/ReflectiveMethodInvocation.java <ide> public MethodInvocation invocableClone() { <ide> Object[] cloneArguments = this.arguments; <ide> if (this.arguments.length > 0) { <ide> // Build an independent copy of the arguments array. <del> cloneArguments = new Object[this.arguments.length]; <del> System.arraycopy(this.arguments, 0, cloneArguments, 0, this.arguments.length); <add> cloneArguments = this.arguments.clone(); <ide> } <ide> return invocableClone(cloneArguments); <ide> } <ide><path>spring-context-support/src/main/java/org/springframework/mail/SimpleMailMessage.java <ide> private static String[] copyOrNull(@Nullable String[] state) { <ide> } <ide> <ide> private static String[] copy(String[] state) { <del> String[] copy = new String[state.length]; <del> System.arraycopy(state, 0, copy, 0, state.length); <del> return copy; <add> return state.clone(); <ide> } <ide> <ide> } <ide><path>spring-context/src/main/java/org/springframework/cache/interceptor/SimpleKey.java <ide> public class SimpleKey implements Serializable { <ide> */ <ide> public SimpleKey(Object... elements) { <ide> Assert.notNull(elements, "Elements must not be null"); <del> this.params = new Object[elements.length]; <del> System.arraycopy(elements, 0, this.params, 0, elements.length); <add> this.params = elements.clone(); <ide> this.hashCode = Arrays.deepHashCode(this.params); <ide> } <ide> <ide><path>spring-core/src/main/java/org/springframework/util/FastByteArrayOutputStream.java <ide> public byte[] toByteArrayUnsafe() { <ide> */ <ide> public byte[] toByteArray() { <ide> byte[] bytesUnsafe = toByteArrayUnsafe(); <del> byte[] ret = new byte[bytesUnsafe.length]; <del> System.arraycopy(bytesUnsafe, 0, ret, 0, bytesUnsafe.length); <del> return ret; <add> return bytesUnsafe.clone(); <ide> } <ide> <ide> /**
4
Go
Go
add test suite for logreaders
9aa9d6fafc3af407317ace630d2ab97f8b89d25b
<ide><path>daemon/logger/jsonfilelog/read_test.go <ide> import ( <ide> "time" <ide> <ide> "github.com/docker/docker/daemon/logger" <add> "github.com/docker/docker/daemon/logger/loggertest" <ide> "gotest.tools/v3/assert" <ide> ) <ide> <ide> func TestUnexpectedEOF(t *testing.T) { <ide> assert.Error(t, err, io.EOF.Error()) <ide> } <ide> <add>func TestReadLogs(t *testing.T) { <add> loggertest.Reader{ <add> Factory: func(t *testing.T, info logger.Info) func(*testing.T) logger.Logger { <add> dir := t.TempDir() <add> info.LogPath = filepath.Join(dir, info.ContainerID+".log") <add> return func(t *testing.T) logger.Logger { <add> l, err := New(info) <add> assert.NilError(t, err) <add> return l <add> } <add> }, <add> }.Do(t) <add>} <add> <ide> type readerWithErr struct { <ide> err error <ide> after int <ide><path>daemon/logger/local/local_test.go <ide> package local <ide> <ide> import ( <ide> "bytes" <del> "context" <ide> "encoding/binary" <ide> "fmt" <ide> "io" <ide> "os" <ide> "path/filepath" <del> "strings" <ide> "testing" <ide> "time" <ide> <ide> "github.com/docker/docker/api/types/backend" <ide> "github.com/docker/docker/api/types/plugins/logdriver" <ide> "github.com/docker/docker/daemon/logger" <add> "github.com/docker/docker/daemon/logger/loggertest" <ide> protoio "github.com/gogo/protobuf/io" <ide> "gotest.tools/v3/assert" <ide> is "gotest.tools/v3/assert/cmp" <ide> func TestWriteLog(t *testing.T) { <ide> } <ide> <ide> func TestReadLog(t *testing.T) { <del> t.Parallel() <del> <del> dir, err := os.MkdirTemp("", t.Name()) <del> assert.NilError(t, err) <del> defer os.RemoveAll(dir) <del> <del> logPath := filepath.Join(dir, "test.log") <del> l, err := New(logger.Info{LogPath: logPath}) <del> assert.NilError(t, err) <del> defer l.Close() <del> <del> m1 := logger.Message{Source: "stdout", Timestamp: time.Now().Add(-1 * 30 * time.Minute), Line: []byte("a message")} <del> m2 := logger.Message{Source: "stdout", Timestamp: time.Now().Add(-1 * 20 * time.Minute), Line: []byte("another message"), PLogMetaData: &backend.PartialLogMetaData{Ordinal: 1, Last: true}} <del> longMessage := []byte("a really long message " + strings.Repeat("a", initialBufSize*2)) <del> m3 := logger.Message{Source: "stderr", Timestamp: time.Now().Add(-1 * 10 * time.Minute), Line: longMessage} <del> m4 := logger.Message{Source: "stderr", Timestamp: time.Now().Add(-1 * 10 * time.Minute), Line: []byte("just one more message")} <del> <del> // copy the log message because the underlying log writer resets the log message and returns it to a buffer pool <del> err = l.Log(copyLogMessage(&m1)) <del> assert.NilError(t, err) <del> err = l.Log(copyLogMessage(&m2)) <del> assert.NilError(t, err) <del> err = l.Log(copyLogMessage(&m3)) <del> assert.NilError(t, err) <del> err = l.Log(copyLogMessage(&m4)) <del> assert.NilError(t, err) <del> <del> lr := l.(logger.LogReader) <del> <del> testMessage := func(t *testing.T, lw *logger.LogWatcher, m *logger.Message) { <del> t.Helper() <del> ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) <del> defer cancel() <del> select { <del> case <-ctx.Done(): <del> assert.Assert(t, ctx.Err()) <del> case err := <-lw.Err: <del> assert.NilError(t, err) <del> case msg, open := <-lw.Msg: <del> if !open { <del> select { <del> case err := <-lw.Err: <del> assert.NilError(t, err) <del> default: <del> assert.Assert(t, m == nil) <del> return <del> } <add> loggertest.Reader{ <add> Factory: func(t *testing.T, info logger.Info) func(*testing.T) logger.Logger { <add> dir := t.TempDir() <add> info.LogPath = filepath.Join(dir, info.ContainerID+".log") <add> return func(t *testing.T) logger.Logger { <add> l, err := New(info) <add> assert.NilError(t, err) <add> return l <ide> } <del> assert.Assert(t, m != nil) <del> if m.PLogMetaData == nil { <del> // a `\n` is appended on read to make this work with the existing API's when the message is not a partial. <del> // make sure it's the last entry in the line, and then truncate it for the deep equal below. <del> assert.Check(t, msg.Line[len(msg.Line)-1] == '\n') <del> msg.Line = msg.Line[:len(msg.Line)-1] <del> } <del> assert.Check(t, is.DeepEqual(m, msg), fmt.Sprintf("\n%+v\n%+v", m, msg)) <del> } <del> } <del> <del> t.Run("tail exact", func(t *testing.T) { <del> lw := lr.ReadLogs(logger.ReadConfig{Tail: 4}) <del> <del> testMessage(t, lw, &m1) <del> testMessage(t, lw, &m2) <del> testMessage(t, lw, &m3) <del> testMessage(t, lw, &m4) <del> testMessage(t, lw, nil) // no more messages <del> }) <del> <del> t.Run("tail less than available", func(t *testing.T) { <del> lw := lr.ReadLogs(logger.ReadConfig{Tail: 2}) <del> <del> testMessage(t, lw, &m3) <del> testMessage(t, lw, &m4) <del> testMessage(t, lw, nil) // no more messages <del> }) <del> <del> t.Run("tail more than available", func(t *testing.T) { <del> lw := lr.ReadLogs(logger.ReadConfig{Tail: 100}) <del> <del> testMessage(t, lw, &m1) <del> testMessage(t, lw, &m2) <del> testMessage(t, lw, &m3) <del> testMessage(t, lw, &m4) <del> testMessage(t, lw, nil) // no more messages <del> }) <add> }, <add> }.Do(t) <ide> } <ide> <ide> func BenchmarkLogWrite(b *testing.B) { <ide><path>daemon/logger/loggertest/logreader.go <add>package loggertest // import "github.com/docker/docker/daemon/logger/loggertest" <add> <add>import ( <add> "strings" <add> "testing" <add> "time" <add> <add> "github.com/google/go-cmp/cmp" <add> "github.com/google/go-cmp/cmp/cmpopts" <add> "gotest.tools/v3/assert" <add> <add> "github.com/docker/docker/api/types/backend" <add> "github.com/docker/docker/daemon/logger" <add>) <add> <add>// Reader tests that a logger.LogReader implementation behaves as it should. <add>type Reader struct { <add> // Factory returns a function which constructs loggers for the container <add> // specified in info. Each call to the returned function must yield a <add> // distinct logger instance which can read back logs written by earlier <add> // instances. <add> Factory func(*testing.T, logger.Info) func(*testing.T) logger.Logger <add>} <add> <add>var compareLog cmp.Options = []cmp.Option{ <add> // The json-log driver does not round-trip PLogMetaData and API users do <add> // not expect it. <add> cmpopts.IgnoreFields(logger.Message{}, "PLogMetaData"), <add> cmp.Transformer("string", func(b []byte) string { return string(b) }), <add>} <add> <add>// Do tests the behavior of the LogReader implementation. <add>func (tr Reader) Do(t *testing.T) { <add> t.Run("Live/Tail", func(t *testing.T) { tr.testTail(t, true) }) <add> t.Run("Live/TailEmpty", func(t *testing.T) { tr.testTailEmptyLogs(t, true) }) <add> t.Run("Live/Follow", tr.testFollow) <add> t.Run("Stopped/Tail", func(t *testing.T) { tr.testTail(t, false) }) <add> t.Run("Stopped/TailEmpty", func(t *testing.T) { tr.testTailEmptyLogs(t, false) }) <add>} <add> <add>func makeTestMessages() []*logger.Message { <add> return []*logger.Message{ <add> {Source: "stdout", Timestamp: time.Now().Add(-1 * 30 * time.Minute), Line: []byte("a message")}, <add> {Source: "stdout", Timestamp: time.Now().Add(-1 * 20 * time.Minute), Line: []byte("another message"), PLogMetaData: &backend.PartialLogMetaData{ID: "aaaaaaaa", Ordinal: 1, Last: true}}, <add> {Source: "stderr", Timestamp: time.Now().Add(-1 * 15 * time.Minute), Line: []byte("to be..."), PLogMetaData: &backend.PartialLogMetaData{ID: "bbbbbbbb", Ordinal: 1}}, <add> {Source: "stderr", Timestamp: time.Now().Add(-1 * 15 * time.Minute), Line: []byte("continued"), PLogMetaData: &backend.PartialLogMetaData{ID: "bbbbbbbb", Ordinal: 2, Last: true}}, <add> {Source: "stderr", Timestamp: time.Now().Add(-1 * 10 * time.Minute), Line: []byte("a really long message " + strings.Repeat("a", 4096))}, <add> {Source: "stderr", Timestamp: time.Now().Add(-1 * 10 * time.Minute), Line: []byte("just one more message")}, <add> } <add> <add>} <add> <add>func (tr Reader) testTail(t *testing.T, live bool) { <add> t.Parallel() <add> factory := tr.Factory(t, logger.Info{ <add> ContainerID: "tailtest0000", <add> ContainerName: "logtail", <add> }) <add> l := factory(t) <add> if live { <add> defer func() { assert.NilError(t, l.Close()) }() <add> } <add> <add> mm := makeTestMessages() <add> expected := logMessages(t, l, mm) <add> <add> if !live { <add> // Simulate reading from a stopped container. <add> assert.NilError(t, l.Close()) <add> l = factory(t) <add> defer func() { assert.NilError(t, l.Close()) }() <add> } <add> lr := l.(logger.LogReader) <add> <add> t.Run("Exact", func(t *testing.T) { <add> t.Parallel() <add> lw := lr.ReadLogs(logger.ReadConfig{Tail: len(mm)}) <add> defer lw.ConsumerGone() <add> assert.DeepEqual(t, readAll(t, lw), expected, compareLog) <add> }) <add> <add> t.Run("LessThanAvailable", func(t *testing.T) { <add> t.Parallel() <add> lw := lr.ReadLogs(logger.ReadConfig{Tail: 2}) <add> defer lw.ConsumerGone() <add> assert.DeepEqual(t, readAll(t, lw), expected[len(mm)-2:], compareLog) <add> }) <add> <add> t.Run("MoreThanAvailable", func(t *testing.T) { <add> t.Parallel() <add> lw := lr.ReadLogs(logger.ReadConfig{Tail: 100}) <add> defer lw.ConsumerGone() <add> assert.DeepEqual(t, readAll(t, lw), expected, compareLog) <add> }) <add> <add> t.Run("All", func(t *testing.T) { <add> t.Parallel() <add> lw := lr.ReadLogs(logger.ReadConfig{Tail: -1}) <add> defer lw.ConsumerGone() <add> assert.DeepEqual(t, readAll(t, lw), expected, compareLog) <add> }) <add> <add> t.Run("Since", func(t *testing.T) { <add> t.Parallel() <add> lw := lr.ReadLogs(logger.ReadConfig{Tail: -1, Since: mm[1].Timestamp.Truncate(time.Millisecond)}) <add> defer lw.ConsumerGone() <add> assert.DeepEqual(t, readAll(t, lw), expected[1:], compareLog) <add> }) <add> <add> t.Run("MoreThanSince", func(t *testing.T) { <add> t.Parallel() <add> lw := lr.ReadLogs(logger.ReadConfig{Tail: len(mm), Since: mm[1].Timestamp.Truncate(time.Millisecond)}) <add> defer lw.ConsumerGone() <add> assert.DeepEqual(t, readAll(t, lw), expected[1:], compareLog) <add> }) <add> <add> t.Run("LessThanSince", func(t *testing.T) { <add> t.Parallel() <add> lw := lr.ReadLogs(logger.ReadConfig{Tail: len(mm) - 2, Since: mm[1].Timestamp.Truncate(time.Millisecond)}) <add> defer lw.ConsumerGone() <add> assert.DeepEqual(t, readAll(t, lw), expected[2:], compareLog) <add> }) <add> <add> t.Run("Until", func(t *testing.T) { <add> t.Parallel() <add> lw := lr.ReadLogs(logger.ReadConfig{Tail: -1, Until: mm[2].Timestamp.Add(-time.Millisecond)}) <add> defer lw.ConsumerGone() <add> assert.DeepEqual(t, readAll(t, lw), expected[:2], compareLog) <add> }) <add> <add> t.Run("SinceAndUntil", func(t *testing.T) { <add> t.Parallel() <add> lw := lr.ReadLogs(logger.ReadConfig{Tail: -1, Since: mm[1].Timestamp.Truncate(time.Millisecond), Until: mm[1].Timestamp.Add(time.Millisecond)}) <add> defer lw.ConsumerGone() <add> assert.DeepEqual(t, readAll(t, lw), expected[1:2], compareLog) <add> }) <add>} <add> <add>func (tr Reader) testTailEmptyLogs(t *testing.T, live bool) { <add> t.Parallel() <add> factory := tr.Factory(t, logger.Info{ <add> ContainerID: "tailemptytest", <add> ContainerName: "logtail", <add> }) <add> l := factory(t) <add> if !live { <add> assert.NilError(t, l.Close()) <add> l = factory(t) <add> } <add> defer func() { assert.NilError(t, l.Close()) }() <add> <add> for _, tt := range []struct { <add> name string <add> cfg logger.ReadConfig <add> }{ <add> {name: "Zero", cfg: logger.ReadConfig{}}, <add> {name: "All", cfg: logger.ReadConfig{Tail: -1}}, <add> {name: "Tail", cfg: logger.ReadConfig{Tail: 42}}, <add> {name: "Since", cfg: logger.ReadConfig{Since: time.Unix(1, 0)}}, <add> {name: "Until", cfg: logger.ReadConfig{Until: time.Date(2100, time.January, 1, 1, 1, 1, 0, time.UTC)}}, <add> {name: "SinceAndUntil", cfg: logger.ReadConfig{Since: time.Unix(1, 0), Until: time.Date(2100, time.January, 1, 1, 1, 1, 0, time.UTC)}}, <add> } { <add> tt := tt <add> t.Run(tt.name, func(t *testing.T) { <add> t.Parallel() <add> lw := l.(logger.LogReader).ReadLogs(logger.ReadConfig{}) <add> defer lw.ConsumerGone() <add> assert.DeepEqual(t, readAll(t, lw), ([]*logger.Message)(nil), cmpopts.EquateEmpty()) <add> }) <add> } <add>} <add> <add>func (tr Reader) testFollow(t *testing.T) { <add> t.Parallel() <add> // Reader sends all logs and closes after logger is closed <add> // - Starting from empty log (like run) <add> t.Run("FromEmptyLog", func(t *testing.T) { <add> t.Parallel() <add> l := tr.Factory(t, logger.Info{ <add> ContainerID: "followstart0", <add> ContainerName: "logloglog", <add> })(t) <add> lw := l.(logger.LogReader).ReadLogs(logger.ReadConfig{Tail: -1, Follow: true}) <add> defer lw.ConsumerGone() <add> <add> doneReading := make(chan struct{}) <add> var logs []*logger.Message <add> go func() { <add> defer close(doneReading) <add> logs = readAll(t, lw) <add> }() <add> <add> mm := makeTestMessages() <add> expected := logMessages(t, l, mm) <add> assert.NilError(t, l.Close()) <add> <-doneReading <add> assert.DeepEqual(t, logs, expected, compareLog) <add> }) <add> <add> t.Run("AttachMidStream", func(t *testing.T) { <add> t.Parallel() <add> l := tr.Factory(t, logger.Info{ <add> ContainerID: "followmiddle", <add> ContainerName: "logloglog", <add> })(t) <add> <add> mm := makeTestMessages() <add> expected := logMessages(t, l, mm[0:1]) <add> <add> lw := l.(logger.LogReader).ReadLogs(logger.ReadConfig{Tail: -1, Follow: true}) <add> defer lw.ConsumerGone() <add> <add> doneReading := make(chan struct{}) <add> var logs []*logger.Message <add> go func() { <add> defer close(doneReading) <add> logs = readAll(t, lw) <add> }() <add> <add> expected = append(expected, logMessages(t, l, mm[1:])...) <add> assert.NilError(t, l.Close()) <add> <-doneReading <add> assert.DeepEqual(t, logs, expected, compareLog) <add> }) <add> <add> t.Run("Since", func(t *testing.T) { <add> t.Parallel() <add> l := tr.Factory(t, logger.Info{ <add> ContainerID: "followsince0", <add> ContainerName: "logloglog", <add> })(t) <add> <add> mm := makeTestMessages() <add> <add> lw := l.(logger.LogReader).ReadLogs(logger.ReadConfig{Tail: -1, Follow: true, Since: mm[2].Timestamp.Truncate(time.Millisecond)}) <add> defer lw.ConsumerGone() <add> <add> doneReading := make(chan struct{}) <add> var logs []*logger.Message <add> go func() { <add> defer close(doneReading) <add> logs = readAll(t, lw) <add> }() <add> <add> expected := logMessages(t, l, mm)[2:] <add> assert.NilError(t, l.Close()) <add> <-doneReading <add> assert.DeepEqual(t, logs, expected, compareLog) <add> }) <add> <add> t.Run("Until", func(t *testing.T) { <add> t.Parallel() <add> l := tr.Factory(t, logger.Info{ <add> ContainerID: "followuntil0", <add> ContainerName: "logloglog", <add> })(t) <add> <add> mm := makeTestMessages() <add> <add> lw := l.(logger.LogReader).ReadLogs(logger.ReadConfig{Tail: -1, Follow: true, Until: mm[2].Timestamp.Add(-time.Millisecond)}) <add> defer lw.ConsumerGone() <add> <add> doneReading := make(chan struct{}) <add> var logs []*logger.Message <add> go func() { <add> defer close(doneReading) <add> logs = readAll(t, lw) <add> }() <add> <add> expected := logMessages(t, l, mm)[:2] <add> defer assert.NilError(t, l.Close()) // Reading should end before the logger is closed. <add> <-doneReading <add> assert.DeepEqual(t, logs, expected, compareLog) <add> }) <add> <add> t.Run("SinceAndUntil", func(t *testing.T) { <add> t.Parallel() <add> l := tr.Factory(t, logger.Info{ <add> ContainerID: "followbounded", <add> ContainerName: "logloglog", <add> })(t) <add> <add> mm := makeTestMessages() <add> <add> lw := l.(logger.LogReader).ReadLogs(logger.ReadConfig{Tail: -1, Follow: true, Since: mm[1].Timestamp.Add(-time.Millisecond), Until: mm[2].Timestamp.Add(-time.Millisecond)}) <add> defer lw.ConsumerGone() <add> <add> doneReading := make(chan struct{}) <add> var logs []*logger.Message <add> go func() { <add> defer close(doneReading) <add> logs = readAll(t, lw) <add> }() <add> <add> expected := logMessages(t, l, mm)[1:2] <add> defer assert.NilError(t, l.Close()) // Reading should end before the logger is closed. <add> <-doneReading <add> assert.DeepEqual(t, logs, expected, compareLog) <add> }) <add> <add> t.Run("Tail=0", func(t *testing.T) { <add> t.Parallel() <add> l := tr.Factory(t, logger.Info{ <add> ContainerID: "followtail00", <add> ContainerName: "logloglog", <add> })(t) <add> <add> mm := makeTestMessages() <add> logMessages(t, l, mm[0:2]) <add> <add> lw := l.(logger.LogReader).ReadLogs(logger.ReadConfig{Tail: 0, Follow: true}) <add> defer lw.ConsumerGone() <add> <add> doneReading := make(chan struct{}) <add> var logs []*logger.Message <add> go func() { <add> defer close(doneReading) <add> logs = readAll(t, lw) <add> }() <add> <add> expected := logMessages(t, l, mm[2:]) <add> assert.NilError(t, l.Close()) <add> <-doneReading <add> assert.DeepEqual(t, logs, expected, compareLog) <add> }) <add> <add> t.Run("Tail>0", func(t *testing.T) { <add> t.Parallel() <add> l := tr.Factory(t, logger.Info{ <add> ContainerID: "followtail00", <add> ContainerName: "logloglog", <add> })(t) <add> <add> mm := makeTestMessages() <add> expected := logMessages(t, l, mm[0:2])[1:] <add> <add> lw := l.(logger.LogReader).ReadLogs(logger.ReadConfig{Tail: 1, Follow: true}) <add> defer lw.ConsumerGone() <add> <add> doneReading := make(chan struct{}) <add> var logs []*logger.Message <add> go func() { <add> defer close(doneReading) <add> logs = readAll(t, lw) <add> }() <add> <add> expected = append(expected, logMessages(t, l, mm[2:])...) <add> assert.NilError(t, l.Close()) <add> <-doneReading <add> assert.DeepEqual(t, logs, expected, compareLog) <add> }) <add> <add> t.Run("MultipleStarts", func(t *testing.T) { <add> t.Parallel() <add> factory := tr.Factory(t, logger.Info{ <add> ContainerID: "startrestart", <add> ContainerName: "startmeup", <add> }) <add> <add> mm := makeTestMessages() <add> l := factory(t) <add> expected := logMessages(t, l, mm[:3]) <add> assert.NilError(t, l.Close()) <add> <add> l = factory(t) <add> lw := l.(logger.LogReader).ReadLogs(logger.ReadConfig{Tail: -1, Follow: true}) <add> defer lw.ConsumerGone() <add> <add> doneReading := make(chan struct{}) <add> var logs []*logger.Message <add> go func() { <add> defer close(doneReading) <add> logs = readAll(t, lw) <add> }() <add> <add> expected = append(expected, logMessages(t, l, mm[3:])...) <add> assert.NilError(t, l.Close()) <add> <-doneReading <add> assert.DeepEqual(t, logs, expected, compareLog) <add> }) <add>} <add> <add>// logMessages logs messages to l and returns a slice of messages as would be <add>// expected to be read back. The message values are not modified and the <add>// returned slice of messages are deep-copied. <add>func logMessages(t *testing.T, l logger.Logger, messages []*logger.Message) []*logger.Message { <add> t.Helper() <add> var expected []*logger.Message <add> for _, m := range messages { <add> // Copy the log message because the underlying log writer resets <add> // the log message and returns it to a buffer pool. <add> assert.NilError(t, l.Log(copyLogMessage(m))) <add> <add> // Copy the log message again so as not to mutate the input. <add> expect := copyLogMessage(m) <add> // Existing API consumers expect a newline to be appended to <add> // messages other than nonterminal partials as that matches the <add> // existing behavior of the json-file log driver. <add> if m.PLogMetaData == nil || m.PLogMetaData.Last { <add> expect.Line = append(expect.Line, '\n') <add> } <add> expected = append(expected, expect) <add> } <add> return expected <add>} <add> <add>func copyLogMessage(src *logger.Message) *logger.Message { <add> dst := logger.NewMessage() <add> dst.Source = src.Source <add> dst.Timestamp = src.Timestamp <add> dst.Attrs = src.Attrs <add> dst.Err = src.Err <add> dst.Line = append(dst.Line, src.Line...) <add> if src.PLogMetaData != nil { <add> lmd := *src.PLogMetaData <add> dst.PLogMetaData = &lmd <add> } <add> return dst <add>} <add>func readMessage(t *testing.T, lw *logger.LogWatcher) *logger.Message { <add> t.Helper() <add> timeout := time.NewTimer(5 * time.Second) <add> defer timeout.Stop() <add> select { <add> case <-timeout.C: <add> t.Error("timed out waiting for message") <add> return nil <add> case err, open := <-lw.Err: <add> t.Errorf("unexpected receive on lw.Err: err=%v, open=%v", err, open) <add> return nil <add> case msg, open := <-lw.Msg: <add> if !open { <add> select { <add> case err, open := <-lw.Err: <add> t.Errorf("unexpected receive on lw.Err with closed lw.Msg: err=%v, open=%v", err, open) <add> return nil <add> default: <add> } <add> } <add> return msg <add> } <add>} <add> <add>func readAll(t *testing.T, lw *logger.LogWatcher) []*logger.Message { <add> t.Helper() <add> var msgs []*logger.Message <add> for { <add> m := readMessage(t, lw) <add> if m == nil { <add> return msgs <add> } <add> msgs = append(msgs, m) <add> } <add>}
3
PHP
PHP
remove unnecessary casting
d4efcb7e9bbc1f6edff9dbba5c4a10e29533359e
<ide><path>src/ORM/EagerLoader.php <ide> public function clearContain(): void <ide> */ <ide> public function enableAutoFields(bool $enable = true) <ide> { <del> $this->_autoFields = (bool)$enable; <add> $this->_autoFields = $enable; <ide> <ide> return $this; <ide> } <ide><path>src/ORM/Query.php <ide> public function counter(?callable $counter) <ide> public function enableHydration(bool $enable = true) <ide> { <ide> $this->_dirty(); <del> $this->_hydrate = (bool)$enable; <add> $this->_hydrate = $enable; <ide> <ide> return $this; <ide> } <ide> public function jsonSerialize(): ResultSetInterface <ide> */ <ide> public function enableAutoFields(bool $value = true) <ide> { <del> $this->_autoFields = (bool)$value; <add> $this->_autoFields = $value; <ide> <ide> return $this; <ide> }
2
Python
Python
move flask hook registration to end of file
e8b49d7ebedf7818ff1ba9c9b8595fc6dc13ba67
<ide><path>airflow/www/views.py <ide> def render_template(self, *args, **kwargs): <ide> ) <ide> <ide> <del>def add_user_permissions_to_dag(sender, template, context, **extra): <del> """ <del> Adds `.can_edit`, `.can_trigger`, and `.can_delete` properties <del> to DAG based on current user's permissions. <del> Located in `views.py` rather than the DAG model to keep <del> permissions logic out of the Airflow core. <del> """ <del> if 'dag' in context: <del> dag = context['dag'] <del> can_create_dag_run = get_airflow_app().appbuilder.sm.has_access( <del> permissions.ACTION_CAN_CREATE, permissions.RESOURCE_DAG_RUN <del> ) <del> <del> dag.can_edit = get_airflow_app().appbuilder.sm.can_edit_dag(dag.dag_id) <del> dag.can_trigger = dag.can_edit and can_create_dag_run <del> dag.can_delete = get_airflow_app().appbuilder.sm.can_delete_dag(dag.dag_id) <del> context['dag'] = dag <del> <del> <del>before_render_template.connect(add_user_permissions_to_dag) <del> <del> <ide> class Airflow(AirflowBaseView): <ide> """Main Airflow application.""" <ide> <ide> class CustomUserRemoteUserModelView(MultiResourceUserMixin, UserRemoteUserModelV <ide> permissions.ACTION_CAN_EDIT, <ide> permissions.ACTION_CAN_DELETE, <ide> ] <add> <add> <add>def add_user_permissions_to_dag(sender, template, context, **extra): <add> """ <add> Adds `.can_edit`, `.can_trigger`, and `.can_delete` properties <add> to DAG based on current user's permissions. <add> Located in `views.py` rather than the DAG model to keep <add> permissions logic out of the Airflow core. <add> """ <add> if 'dag' in context: <add> dag = context['dag'] <add> can_create_dag_run = get_airflow_app().appbuilder.sm.has_access( <add> permissions.ACTION_CAN_CREATE, permissions.RESOURCE_DAG_RUN <add> ) <add> <add> dag.can_edit = get_airflow_app().appbuilder.sm.can_edit_dag(dag.dag_id) <add> dag.can_trigger = dag.can_edit and can_create_dag_run <add> dag.can_delete = get_airflow_app().appbuilder.sm.can_delete_dag(dag.dag_id) <add> context['dag'] = dag <add> <add> <add># NOTE: Put this at the end of the file. Pylance is too clever and detects that <add># before_render_template.connect() is declared as NoReturn, and marks everything <add># after this line as unreachable code. It's technically correct based on the <add># lint-time information, but that's not what actually happens at runtime. <add>before_render_template.connect(add_user_permissions_to_dag)
1
PHP
PHP
add missing fallback to put method
a091aec8add9f7a603918e60873a242cc7e84cdc
<ide><path>src/Illuminate/Contracts/Cache/Repository.php <ide> public function pull($key, $default = null); <ide> * @param \DateTimeInterface|\DateInterval|float|int|null $minutes <ide> * @return bool <ide> */ <del> public function put($key, $value, $minutes); <add> public function put($key, $value, $minutes = null); <ide> <ide> /** <ide> * Store an item in the cache if the key does not exist.
1
Javascript
Javascript
fix position of @module doc for engine
574dccda8ba30dc3dac8701ccce0f831690aad0a
<ide><path>packages/@ember/engine/index.js <del>/** <del>@module @ember/engine <del>*/ <del> <ide> export { getEngineParent, setEngineParent } from './lib/engine-parent'; <ide> <ide> import { canInvoke } from '@ember/-internals/utils'; <ide> function props(obj) { <ide> return properties; <ide> } <ide> <add>/** <add>@module @ember/engine <add>*/ <add> <ide> /** <ide> The `Engine` class contains core functionality for both applications and <ide> engines.
1
Ruby
Ruby
remove missing check
1376b9e41c6483b36d5e12e7b8aa30c48091c996
<ide><path>Library/Homebrew/extend/os/mac/diagnostic.rb <ide> class Checks <ide> def development_tools_checks <ide> %w[ <ide> check_for_unsupported_macos <del> check_for_bad_install_name_tool <ide> check_for_installed_developer_tools <ide> check_xcode_license_approved <ide> check_xcode_up_to_date
1
PHP
PHP
remove invalid @param
9413c7d3178066acdcc0d859a500f79d28da5677
<ide><path>tests/TestCase/ORM/MarshallerTest.php <ide> public function testMergeInvalidAssociation(): void <ide> <ide> /** <ide> * Test merge when fields contains an association. <del> * <del> * @param $fields <ide> */ <ide> public function testMergeWithSingleAssociationAndFields(): void <ide> {
1
Ruby
Ruby
define hash on duration
6c57c78671ef49922643361cfb0a9287986be904
<ide><path>activesupport/lib/active_support/duration.rb <ide> def eql?(other) <ide> Duration === other && other.value.eql?(value) <ide> end <ide> <add> def hash <add> @value.hash <add> end <add> <ide> def self.===(other) #:nodoc: <ide> other.is_a?(Duration) <ide> rescue ::NoMethodError <ide><path>activesupport/test/core_ext/duration_test.rb <ide> def test_respond_to <ide> assert_respond_to 1.day, :since <ide> assert_respond_to 1.day, :zero? <ide> end <add> <add> def test_hash <add> assert_equal 1.minute.hash, 60.seconds.hash <add> end <ide> end
2
Text
Text
fix changelog entry [ci skip]
1f95e5b14d49390be7d0459e7479be985f499c86
<ide><path>railties/CHANGELOG.md <del>* Fix minitest rails plugin. The custom reporters are added only if needed. This will fix conflicts with others plugins. *Kevin Robatel* <add>* Fix minitest rails plugin. <add> <add> The custom reporters are added only if needed. <add> <add> This will fix conflicts with others plugins. <add> <add> *Kevin Robatel* <ide> <ide> Please check [5-2-stable](https://github.com/rails/rails/blob/5-2-stable/railties/CHANGELOG.md) for previous changes.
1
Text
Text
add jakobjingleheimer to collaborators list
b67300f561c7e5f8864bd8c7f1b2fe6ead9f1739
<ide><path>README.md <ide> For information about the governance of the Node.js project, see <ide> **Fedor Indutny** <<fedor@indutny.com>> <ide> * [JacksonTian](https://github.com/JacksonTian) - <ide> **Jackson Tian** <<shyvo1987@gmail.com>> <add>* [JakobJingleheimer](https://github.com/JakobJingleheimer) - <add> **Jacob Smith** <<jacob@frende.me>> (he/him) <ide> * [jasnell](https://github.com/jasnell) - <ide> **James M Snell** <<jasnell@gmail.com>> (he/him) <ide> * [jkrems](https://github.com/jkrems) -
1
PHP
PHP
apply fixes from styleci
5f82c995f8163cea04ccffa813da5cccf8916152
<ide><path>src/Illuminate/Foundation/Exceptions/Handler.php <ide> use Illuminate\Routing\Router; <ide> use Illuminate\Http\JsonResponse; <ide> use Illuminate\Support\Facades\Auth; <add>use Illuminate\Filesystem\Filesystem; <ide> use Illuminate\Http\RedirectResponse; <ide> use Whoops\Handler\PrettyPageHandler; <del>use Illuminate\Filesystem\Filesystem; <ide> use Illuminate\Auth\AuthenticationException; <ide> use Illuminate\Contracts\Container\Container; <ide> use Illuminate\Session\TokenMismatchException;
1
Go
Go
add unit test for cmdattach
ad1e8a9b0f0e57327d71827c1161c21f48910e42
<ide><path>commands_test.go <ide> func TestRunDisconnect(t *testing.T) { <ide> t.Fatalf("/bin/cat is still running after closing stdin") <ide> } <ide> } <add> <add>// Expected behaviour, the process stays alive when the client disconnects <add>func TestAttachDisconnect(t *testing.T) { <add> runtime, err := newTestRuntime() <add> if err != nil { <add> t.Fatal(err) <add> } <add> defer nuke(runtime) <add> <add> srv := &Server{runtime: runtime} <add> <add> container, err := runtime.Create( <add> &Config{ <add> Image: GetTestImage(runtime).Id, <add> Memory: 33554432, <add> Cmd: []string{"/bin/cat"}, <add> OpenStdin: true, <add> }, <add> ) <add> if err != nil { <add> t.Fatal(err) <add> } <add> defer runtime.Destroy(container) <add> <add> // Start the process <add> if err := container.Start(); err != nil { <add> t.Fatal(err) <add> } <add> <add> stdin, stdinPipe := io.Pipe() <add> stdout, stdoutPipe := io.Pipe() <add> <add> // Attach to it <add> c1 := make(chan struct{}) <add> go func() { <add> if err := srv.CmdAttach(stdin, stdoutPipe, container.Id); err != nil { <add> t.Fatal(err) <add> } <add> close(c1) <add> }() <add> <add> setTimeout(t, "First read/write assertion timed out", 2*time.Second, func() { <add> if err := assertPipe("hello\n", "hello", stdout, stdinPipe, 15); err != nil { <add> t.Fatal(err) <add> } <add> }) <add> // Close pipes (client disconnects) <add> if err := closeWrap(stdin, stdinPipe, stdout, stdoutPipe); err != nil { <add> t.Fatal(err) <add> } <add> <add> // Wait for attach to finish, the client disconnected, therefore, Attach finished his job <add> setTimeout(t, "Waiting for CmdAttach timed out", 2*time.Second, func() { <add> <-c1 <add> }) <add> // We closed stdin, expect /bin/cat to still be running <add> // Wait a little bit to make sure container.monitor() did his thing <add> err = container.WaitTimeout(500 * time.Millisecond) <add> if err == nil || !container.State.Running { <add> t.Fatalf("/bin/cat is not running after closing stdin") <add> } <add> <add> // Try to avoid the timeoout in destroy. Best effort, don't check error <add> cStdin, _ := container.StdinPipe() <add> cStdin.Close() <add>}
1
PHP
PHP
simplify array creation
bbd95a47e1e065c821037413e5a482eb2a5cd18a
<ide><path>src/Illuminate/Auth/Guard.php <ide> protected function fireAttemptEvent(array $credentials, $remember, $login) <ide> { <ide> if ($this->events) <ide> { <del> $payload = array_values(compact('credentials', 'remember', 'login')); <add> $payload = array($credentials, $remember, $login); <ide> <ide> $this->events->fire('auth.attempt', $payload); <ide> } <ide> public function getRecallerName() <ide> return 'remember_'.md5(get_class($this)); <ide> } <ide> <del>} <ide>\ No newline at end of file <add>}
1
Mixed
Ruby
raise argumenterror for bad strptime arguments
424e961be776d9918f39660d43439fc1973f680e
<ide><path>activesupport/CHANGELOG.md <add>* Fix `ActiveSupport::TimeZone#strptime`. Now raises `ArgumentError` when the <add> given time doesn't match the format. The error is the same as the one given <add> by Ruby's `Date.strptime`. Previously it raised <add> `NoMethodError: undefined method empty? for nil:NilClass.` due to a bug. <add> <add> Fixes #25701. <add> <add> *John Gesimondo* <add> <ide> * `travel/travel_to` travel time helpers, now raise on nested calls, <ide> as this can lead to confusing time stubbing. <ide> <ide><path>activesupport/lib/active_support/values/time_zone.rb <ide> def encode_with(coder) #:nodoc: <ide> <ide> private <ide> def parts_to_time(parts, now) <add> raise ArgumentError, "invalid date" if parts.nil? <ide> return if parts.empty? <ide> <ide> time = Time.new( <ide><path>activesupport/test/time_zone_test.rb <ide> def test_strptime_with_day_omitted <ide> end <ide> end <ide> <add> def test_strptime_with_malformed_string <add> with_env_tz 'US/Eastern' do <add> zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)'] <add> assert_raise(ArgumentError) { zone.strptime('1999-12-31', '%Y/%m/%d') } <add> end <add> end <add> <ide> def test_utc_offset_lazy_loaded_from_tzinfo_when_not_passed_in_to_initialize <ide> tzinfo = TZInfo::Timezone.get('America/New_York') <ide> zone = ActiveSupport::TimeZone.create(tzinfo.name, nil, tzinfo)
3
Text
Text
add docs for duplex.allowhalfopen property
d14878dc7c6d23038b59e837fcd61f8b35fced30
<ide><path>doc/api/stream.md <ide> Examples of `Duplex` streams include: <ide> * [zlib streams][zlib] <ide> * [crypto streams][crypto] <ide> <add>##### `duplex.allowHalfOpen` <add><!-- YAML <add>added: v0.9.4 <add>--> <add> <add>* {boolean} <add> <add>If `false` then the stream will automatically end the writable side when the <add>readable side ends. Set initially by the `allowHalfOpen` constructor option, <add>which defaults to `false`. <add> <add>This can be changed manually to change the half-open behavior of an existing <add>`Duplex` stream instance, but must be changed before the `'end'` event is <add>emitted. <add> <ide> #### Class: `stream.Transform` <ide> <!-- YAML <ide> added: v0.9.4
1
Text
Text
add pending-deprecation to collaborator_guide
c276851b2f0074a7402115d5336737f84726fa9c
<ide><path>COLLABORATOR_GUIDE.md <ide> Node.js uses three Deprecation levels: <ide> being staged for deprecation in a future Node.js major release. An explicit <ide> notice indicating the deprecated status is added to the API documentation <ide> but no functional changes are implemented in the code. There will be no <del> runtime deprecation warnings emitted for such deprecations. <add> runtime deprecation warnings emitted for such deprecations by default. <add> Documentation-only deprecations may trigger a runtime warning when launched <add> with [`--pending-deprecation`][] flag (or its alternative, <add> `NODE_PENDING_DEPRECATION=1` environment variable). <ide> <ide> * *Runtime Deprecation* refers to the use of process warnings emitted at <ide> runtime the first time that a deprecated API is used. A command-line <ide> LTS working group and the Release team. <ide> [backporting guide]: doc/guides/backporting-to-release-lines.md <ide> [Stability Index]: doc/api/documentation.md#stability-index <ide> [Enhancement Proposal]: https://github.com/nodejs/node-eps <add>[`--pending-deprecation`]: doc/api/cli.md#--pending-deprecation <ide> [git-username]: https://help.github.com/articles/setting-your-username-in-git/ <ide> [`node-core-utils`]: https://github.com/nodejs/node-core-utils <ide> [TSC]: https://github.com/nodejs/TSC
1
Ruby
Ruby
make use of new formula specs
b6d44dd38a69889c3e8f380d099fc9cae0decfb8
<ide><path>Library/Homebrew/cmd/fetch.rb <ide> def fetch <ide> puts "Fetching: #{bucket * ', '}" if bucket.size > 1 <ide> <ide> bucket.each do |f| <del> if ARGV.include? "--force" or ARGV.include? "-f" <del> where_to = f.cached_download <del> FileUtils.rm_rf where_to if File.exist? where_to <del> end <del> <ide> already_downloaded = f.cached_download.exist? <add> f.cached_download.rmtree if already_downloaded and ARGV.force? <add> <ide> the_tarball, _ = f.fetch <ide> next unless the_tarball.kind_of? Pathname <ide> <del> bottle = install_bottle? f <del> <del> previous_md5 = f.instance_variable_get(:@md5).to_s.downcase unless bottle <del> previous_sha1 = f.instance_variable_get(:@sha1).to_s.downcase <del> previous_sha2 = f.instance_variable_get(:@sha256).to_s.downcase unless bottle <add> previous_md5 = f.active_spec.md5.to_s.downcase <add> previous_sha1 = f.active_spec.sha1.to_s.downcase <add> previous_sha2 = f.active_spec.sha256.to_s.downcase <ide> <ide> puts "Downloaded to: #{the_tarball}" unless already_downloaded <del> puts "MD5: #{the_tarball.md5}" unless bottle <add> puts "MD5: #{the_tarball.md5}" <ide> puts "SHA1: #{the_tarball.sha1}" <del> puts "SHA256: #{the_tarball.sha2}" unless bottle <add> puts "SHA256: #{the_tarball.sha2}" <ide> <del> unless previous_md5.nil? or previous_md5.empty? or the_tarball.md5 == previous_md5 or bottle <add> unless previous_md5.nil? or previous_md5.empty? or the_tarball.md5 == previous_md5 <ide> opoo "Formula reports different MD5: #{previous_md5}" <ide> end <ide> unless previous_sha1.nil? or previous_sha1.empty? or the_tarball.sha1 == previous_sha1 <ide> opoo "Formula reports different SHA1: #{previous_sha1}" <ide> end <del> unless previous_sha2.nil? or previous_sha2.empty? or the_tarball.sha2 == previous_sha2 or bottle <add> unless previous_sha2.nil? or previous_sha2.empty? or the_tarball.sha2 == previous_sha2 <ide> opoo "Formula reports different SHA256: #{previous_sha2}" <ide> end <ide> end
1
Go
Go
fix pre-1.22 docker stats
d2c04f844b8258d712da4b8feac25df7590b037c
<ide><path>daemon/stats.go <ide> func (daemon *Daemon) ContainerStats(prefixOrName string, config *ContainerStats <ide> return nil <ide> } <ide> <del> statsJSON := getStatJSON(v) <add> var statsJSON interface{} <add> statsJSONPost120 := getStatJSON(v) <ide> if config.Version.LessThan("1.21") { <ide> var ( <ide> rxBytes uint64 <ide> func (daemon *Daemon) ContainerStats(prefixOrName string, config *ContainerStats <ide> txErrors uint64 <ide> txDropped uint64 <ide> ) <del> for _, v := range statsJSON.Networks { <add> for _, v := range statsJSONPost120.Networks { <ide> rxBytes += v.RxBytes <ide> rxPackets += v.RxPackets <ide> rxErrors += v.RxErrors <ide> func (daemon *Daemon) ContainerStats(prefixOrName string, config *ContainerStats <ide> txErrors += v.TxErrors <ide> txDropped += v.TxDropped <ide> } <del> statsJSONPre121 := &v1p20.StatsJSON{ <del> Stats: statsJSON.Stats, <add> statsJSON = &v1p20.StatsJSON{ <add> Stats: statsJSONPost120.Stats, <ide> Network: types.NetworkStats{ <ide> RxBytes: rxBytes, <ide> RxPackets: rxPackets, <ide> func (daemon *Daemon) ContainerStats(prefixOrName string, config *ContainerStats <ide> TxDropped: txDropped, <ide> }, <ide> } <del> <del> if !config.Stream && noStreamFirstFrame { <del> // prime the cpu stats so they aren't 0 in the final output <del> noStreamFirstFrame = false <del> continue <del> } <del> <del> if err := enc.Encode(statsJSONPre121); err != nil { <del> return err <del> } <del> <del> if !config.Stream { <del> return nil <del> } <add> } else { <add> statsJSON = statsJSONPost120 <ide> } <ide> <ide> if !config.Stream && noStreamFirstFrame {
1
Text
Text
add breakpoint section
03d76fb40a21bcef181335a5c0ebf75cf27bde43
<ide><path>guides/source/debugging_rails_applications.md <ide> instance variables: <ide> class variables: raise_on_open_redirects <ide> ``` <ide> <add>### Breakpoints <add> <add>There are many ways to insert and trigger a breakpoint in the debugger. In additional to adding debugging statements (e.g. `debugger`) directly in your code, you can also insert breakpoints with commands: <add> <add>- `break` (or `b`) <add> - `break` - list all breakpoints <add> - `break <num>` - set a breakpoint on the `num` line of the current file <add> - `break <file:num>` - set a breakpoint on the `num` line of `file` <add> - `break <Class#method>` or `break <Class.method>` - set a breakpoint on `Class#method` or `Class.method` <add> - `break <expr>.<method>` - sets a breakpoint on `<expr>` result's `<method>` method. <add>- `catch <Exception>` - set a breakpoint that'll stop when `Exception` is raised <add>- `watch <@ivar>` - set a breakpoint that'll stop when the result of current object's `@ivar` is changed (this is slow) <add> <add>And to remove them, you can use: <add> <add>- `delete` (or `del`) <add> - `delete` - delete all breakpoints <add> - `delete <num>` - delete the breakpoint with id `num` <add> <add>#### The break command <add> <add>**Set a breakpoint with specified line number - e.g. `b 28`** <add> <add>```rb <add>[20, 29] in ~/projects/rails-guide-example/app/controllers/posts_controller.rb <add> 20| end <add> 21| <add> 22| # POST /posts or /posts.json <add> 23| def create <add> 24| @post = Post.new(post_params) <add>=> 25| debugger <add> 26| <add> 27| respond_to do |format| <add> 28| if @post.save <add> 29| format.html { redirect_to @post, notice: "Post was successfully created." } <add>=>#0 PostsController#create at ~/projects/rails-guide-example/app/controllers/posts_controller.rb:25 <add> #1 ActionController::BasicImplicitRender#send_action(method="create", args=[]) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/actionpack-7.0.0.alpha2/lib/action_controller/metal/basic_implicit_render.rb:6 <add> # and 72 frames (use `bt' command for all frames) <add>(rdbg) b 28 # break command <add>#0 BP - Line /Users/st0012/projects/rails-guide-example/app/controllers/posts_controller.rb:28 (line) <add>``` <add> <add>```rb <add>(rdbg) c # continue command <add>[23, 32] in ~/projects/rails-guide-example/app/controllers/posts_controller.rb <add> 23| def create <add> 24| @post = Post.new(post_params) <add> 25| debugger <add> 26| <add> 27| respond_to do |format| <add>=> 28| if @post.save <add> 29| format.html { redirect_to @post, notice: "Post was successfully created." } <add> 30| format.json { render :show, status: :created, location: @post } <add> 31| else <add> 32| format.html { render :new, status: :unprocessable_entity } <add>=>#0 block {|format=#<ActionController::MimeResponds::Collec...|} in create at ~/projects/rails-guide-example/app/controllers/posts_controller.rb:28 <add> #1 ActionController::MimeResponds#respond_to(mimes=[]) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/actionpack-7.0.0.alpha2/lib/action_controller/metal/mime_responds.rb:205 <add> # and 74 frames (use `bt' command for all frames) <add> <add>Stop by #0 BP - Line /Users/st0012/projects/rails-guide-example/app/controllers/posts_controller.rb:28 (line) <add>``` <add> <add>**Set a breakpoint on a given method call - e.g. `b @post.save`** <add> <add>```rb <add>[20, 29] in ~/projects/rails-guide-example/app/controllers/posts_controller.rb <add> 20| end <add> 21| <add> 22| # POST /posts or /posts.json <add> 23| def create <add> 24| @post = Post.new(post_params) <add>=> 25| debugger <add> 26| <add> 27| respond_to do |format| <add> 28| if @post.save <add> 29| format.html { redirect_to @post, notice: "Post was successfully created." } <add>=>#0 PostsController#create at ~/projects/rails-guide-example/app/controllers/posts_controller.rb:25 <add> #1 ActionController::BasicImplicitRender#send_action(method="create", args=[]) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/actionpack-7.0.0.alpha2/lib/action_controller/metal/basic_implicit_render.rb:6 <add> # and 72 frames (use `bt' command for all frames) <add>(rdbg) b @post.save # break command <add>#0 BP - Method @post.save at /Users/st0012/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/activerecord-7.0.0.alpha2/lib/active_record/suppressor.rb:43 <add> <add>``` <add> <add>```rb <add>(rdbg) c # continue command <add>[39, 48] in ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/activerecord-7.0.0.alpha2/lib/active_record/suppressor.rb <add> 39| SuppressorRegistry.suppressed[name] = previous_state <add> 40| end <add> 41| end <add> 42| <add> 43| def save(**) # :nodoc: <add>=> 44| SuppressorRegistry.suppressed[self.class.name] ? true : super <add> 45| end <add> 46| <add> 47| def save!(**) # :nodoc: <add> 48| SuppressorRegistry.suppressed[self.class.name] ? true : super <add>=>#0 ActiveRecord::Suppressor#save(#arg_rest=nil) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/activerecord-7.0.0.alpha2/lib/active_record/suppressor.rb:44 <add> #1 block {|format=#<ActionController::MimeResponds::Collec...|} in create at ~/projects/rails-guide-example/app/controllers/posts_controller.rb:28 <add> # and 75 frames (use `bt' command for all frames) <add> <add>Stop by #0 BP - Method @post.save at /Users/st0012/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/activerecord-7.0.0.alpha2/lib/active_record/suppressor.rb:43 <add>``` <add> <add>#### The catch command <add> <add>**Stop when an exception is raised - e.g. `catch ActiveRecord::RecordInvalid`** <add> <add>```rb <add>[20, 29] in ~/projects/rails-guide-example/app/controllers/posts_controller.rb <add> 20| end <add> 21| <add> 22| # POST /posts or /posts.json <add> 23| def create <add> 24| @post = Post.new(post_params) <add>=> 25| debugger <add> 26| <add> 27| respond_to do |format| <add> 28| if @post.save! <add> 29| format.html { redirect_to @post, notice: "Post was successfully created." } <add>=>#0 PostsController#create at ~/projects/rails-guide-example/app/controllers/posts_controller.rb:25 <add> #1 ActionController::BasicImplicitRender#send_action(method="create", args=[]) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/actionpack-7.0.0.alpha2/lib/action_controller/metal/basic_implicit_render.rb:6 <add> # and 72 frames (use `bt' command for all frames) <add>(rdbg) catch ActiveRecord::RecordInvalid # command <add>#1 BP - Catch "ActiveRecord::RecordInvalid" <add>``` <add> <add>```rb <add>(rdbg) c # continue command <add>[75, 84] in ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/activerecord-7.0.0.alpha2/lib/active_record/validations.rb <add> 75| def default_validation_context <add> 76| new_record? ? :create : :update <add> 77| end <add> 78| <add> 79| def raise_validation_error <add>=> 80| raise(RecordInvalid.new(self)) <add> 81| end <add> 82| <add> 83| def perform_validations(options = {}) <add> 84| options[:validate] == false || valid?(options[:context]) <add>=>#0 ActiveRecord::Validations#raise_validation_error at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/activerecord-7.0.0.alpha2/lib/active_record/validations.rb:80 <add> #1 ActiveRecord::Validations#save!(options={}) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/activerecord-7.0.0.alpha2/lib/active_record/validations.rb:53 <add> # and 88 frames (use `bt' command for all frames) <add> <add>Stop by #1 BP - Catch "ActiveRecord::RecordInvalid" <add>``` <add> <add>#### The watch command <add> <add>**Stop when the instance variable is changed - e.g. `watch @_response_body`** <add> <add>```rb <add>[20, 29] in ~/projects/rails-guide-example/app/controllers/posts_controller.rb <add> 20| end <add> 21| <add> 22| # POST /posts or /posts.json <add> 23| def create <add> 24| @post = Post.new(post_params) <add>=> 25| debugger <add> 26| <add> 27| respond_to do |format| <add> 28| if @post.save! <add> 29| format.html { redirect_to @post, notice: "Post was successfully created." } <add>=>#0 PostsController#create at ~/projects/rails-guide-example/app/controllers/posts_controller.rb:25 <add> #1 ActionController::BasicImplicitRender#send_action(method="create", args=[]) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/actionpack-7.0.0.alpha2/lib/action_controller/metal/basic_implicit_render.rb:6 <add> # and 72 frames (use `bt' command for all frames) <add>(rdbg) watch @_response_body # command <add>#0 BP - Watch #<PostsController:0x00007fce69ca5320> @_response_body = <add>``` <add> <add>```rb <add>(rdbg) c # continue command <add>[173, 182] in ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/actionpack-7.0.0.alpha2/lib/action_controller/metal.rb <add> 173| body = [body] unless body.nil? || body.respond_to?(:each) <add> 174| response.reset_body! <add> 175| return unless body <add> 176| response.body = body <add> 177| super <add>=> 178| end <add> 179| <add> 180| # Tests if render or redirect has already happened. <add> 181| def performed? <add> 182| response_body || response.committed? <add>=>#0 ActionController::Metal#response_body=(body=["<html><body>You are being <a href=\"ht...) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/actionpack-7.0.0.alpha2/lib/action_controller/metal.rb:178 #=> ["<html><body>You are being <a href=\"ht... <add> #1 ActionController::Redirecting#redirect_to(options=#<Post id: 13, title: "qweqwe", content:..., response_options={:allow_other_host=>false}) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/actionpack-7.0.0.alpha2/lib/action_controller/metal/redirecting.rb:74 <add> # and 82 frames (use `bt' command for all frames) <add> <add>Stop by #0 BP - Watch #<PostsController:0x00007fce69ca5320> @_response_body = -> ["<html><body>You are being <a href=\"http://localhost:3000/posts/13\">redirected</a>.</body></html>"] <add>(rdbg) <add>``` <add> <add>#### Breakpoint options <add> <add>In addition to different types of breakpoints, you can also specify options to achieve more advanced debugging workflow. Currently, the debugger supports 4 options: <add> <add>- `do: <cmd or expr>` - when the breakpoint is triggered, execute the given command/expression and continue the program: <add> - `break Foo#bar do: bt` - when `Foo#bar` is called, print the stack frames <add>- `pre: <cmd or expr>` - when the breakpoint is triggered, execute the given command/expression before stopping: <add> - `break Foo#bar pre: info` - when `Foo#bar` is called, print its surrounding variables before stopping. <add>- `if: <expr>` - the breakpoint only stops if the result of `<expr`> is true: <add> - `break Post#save if: params[:debug]` - stops at `Post#save` if `params[:debug]` is also true <add>- `path: <path_regexp>` - the breakpoint only stops if the event that triggers it (e.g. a method call) happens from the given path: <add> - `break Post#save if: app/services/a_service` - stops at `Post#save` if the method call happens at a method matches Ruby regexp `/app\/services\/a_service/`. <add> <add>Please also note that the first 3 options: `do:`, `pre:` and `if:` are also available for the debug statements we mentioned earlier. For example: <add> <add>```rb <add>[2, 11] in ~/projects/rails-guide-example/app/controllers/posts_controller.rb <add> 2| before_action :set_post, only: %i[ show edit update destroy ] <add> 3| <add> 4| # GET /posts or /posts.json <add> 5| def index <add> 6| @posts = Post.all <add>=> 7| debugger(do: "info") <add> 8| end <add> 9| <add> 10| # GET /posts/1 or /posts/1.json <add> 11| def show <add>=>#0 PostsController#index at ~/projects/rails-guide-example/app/controllers/posts_controller.rb:7 <add> #1 ActionController::BasicImplicitRender#send_action(method="index", args=[]) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/actionpack-7.0.0.alpha2/lib/action_controller/metal/basic_implicit_render.rb:6 <add> # and 72 frames (use `bt' command for all frames) <add>(rdbg:binding.break) info <add>%self = #<PostsController:0x00000000017480> <add>@_action_has_layout = true <add>@_action_name = "index" <add>@_config = {} <add>@_lookup_context = #<ActionView::LookupContext:0x00007fce3ad336b8 @details_key=nil, @digest_cache=... <add>@_request = #<ActionDispatch::Request GET "http://localhost:3000/posts" for 127.0.0.1> <add>@_response = #<ActionDispatch::Response:0x00007fce3ad397e8 @mon_data=#<Monitor:0x00007fce3ad396a8>... <add>@_response_body = nil <add>@_routes = nil <add>@marked_for_same_origin_verification = true <add>@posts = #<ActiveRecord::Relation [#<Post id: 2, title: "qweqwe", content: "qweqwe", created_at: "... <add>@rendered_format = nil <add>``` <add> <add>#### Program your debugging workflow <add> <add>With those options, you can script your debugging workflow in one line like: <add> <add>```rb <add>def create <add> debugger(do: "catch ActiveRecord::RecordInvalid do: bt 10") <add> # ... <add>end <add>``` <add> <add>And then the debugger will run the scripted command and insert the catch breakpoint <add> <add>```rb <add>(rdbg:binding.break) catch ActiveRecord::RecordInvalid do: bt 10 <add>#0 BP - Catch "ActiveRecord::RecordInvalid" <add>[75, 84] in ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/activerecord-7.0.0.alpha2/lib/active_record/validations.rb <add> 75| def default_validation_context <add> 76| new_record? ? :create : :update <add> 77| end <add> 78| <add> 79| def raise_validation_error <add>=> 80| raise(RecordInvalid.new(self)) <add> 81| end <add> 82| <add> 83| def perform_validations(options = {}) <add> 84| options[:validate] == false || valid?(options[:context]) <add>=>#0 ActiveRecord::Validations#raise_validation_error at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/activerecord-7.0.0.alpha2/lib/active_record/validations.rb:80 <add> #1 ActiveRecord::Validations#save!(options={}) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/activerecord-7.0.0.alpha2/lib/active_record/validations.rb:53 <add> # and 88 frames (use `bt' command for all frames) <add>``` <add> <add>Once the catch breakpoint is triggered, it'll print the stack frames <add> <add>```rb <add>Stop by #0 BP - Catch "ActiveRecord::RecordInvalid" <add> <add>(rdbg:catch) bt 10 <add>=>#0 ActiveRecord::Validations#raise_validation_error at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/activerecord-7.0.0.alpha2/lib/active_record/validations.rb:80 <add> #1 ActiveRecord::Validations#save!(options={}) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/activerecord-7.0.0.alpha2/lib/active_record/validations.rb:53 <add> #2 block in save! at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/activerecord-7.0.0.alpha2/lib/active_record/transactions.rb:302 <add>``` <add> <add>This technique can save you from repeated manual input and make the debugging experience smoother. <add> <ide> You can find more commands and configuration options from its [documentation](https://github.com/ruby/debug). <ide> <ide> #### Autoloading Caveat
1
Text
Text
add inline code blocks to for i18n
167f93df767e3138fa169b8616c866a5f56831db
<ide><path>curriculum/challenges/english/01-responsive-web-design/applied-accessibility/jump-straight-to-the-content-using-the-main-element.md <ide> By default, a browser renders these elements similarly to the humble `div`. Howe <ide> <ide> The `main` element is used to wrap (you guessed it) the main content, and there should be only one per page. It's meant to surround the information that's related to the central topic of your page. It's not meant to include items that repeat across pages, like navigation links or banners. <ide> <del>The `main` tag also has an embedded landmark feature that assistive technology can use to quickly navigate to the main content. If you've ever seen a "Jump to Main Content" link at the top of a page, using a main tag automatically gives assistive devices that functionality. <add>The `main` tag also has an embedded landmark feature that assistive technology can use to quickly navigate to the main content. If you've ever seen a "Jump to Main Content" link at the top of a page, using a `main` tag automatically gives assistive devices that functionality. <ide> <ide> # --instructions-- <ide> <ide><path>curriculum/challenges/english/01-responsive-web-design/basic-css/override-class-declarations-by-styling-id-attributes.md <ide> Create a CSS declaration for your `orange-text` id in your `style` element. Here <ide> } <ide> ``` <ide> <del>**Note:** It doesn't matter whether you declare this CSS above or below pink-text class, since id attribute will always take precedence. <add>**Note:** It doesn't matter whether you declare this CSS above or below `pink-text` class, since the `id` attribute will always take precedence. <ide> <ide> # --hints-- <ide>
2
PHP
PHP
upgrade shell - option to specify extensions
c1d99017e97da98e94702b89740492e539bf7dd4
<ide><path>cake/console/shells/upgrade.php <ide> protected function _filesRegexpUpdate($patterns) { <ide> $this->_paths = array(App::pluginPath($this->params['plugin'])); <ide> } <ide> <del> $this->_findFiles(); <add> $extensions = 'php|ctp|thtml|inc|tpl'; <add> if (!empty($this->params['ext'])) { <add> $extensions = $this->params['ext']; <add> } <add> <add> $this->_findFiles($extensions); <ide> foreach ($this->_files as $file) { <ide> $this->out('Updating ' . $file . '...', 1, Shell::VERBOSE); <ide> $this->_updateFile($file, $patterns); <ide> } <ide> } <ide> <del> protected function _findFiles($pattern = '') { <add> protected function _findFiles($extensions = '', $pattern = '') { <ide> foreach ($this->_paths as $path) { <ide> $Folder = new Folder($path); <del> $files = $Folder->findRecursive('.*\.(php|ctp|thtml|inc|tpl)', true); <add> $files = $Folder->findRecursive(".*\.($extensions)", true); <ide> if (!empty($pattern)) { <ide> foreach ($files as $i => $file) { <ide> if (preg_match($pattern, $file)) { <ide> protected function _updateFile($file, $patterns) { <ide> * @return void <ide> */ <ide> function getOptionParser() { <add> $subcommandParser = array( <add> 'options' => array( <add> 'plugin' => array('short' => 'p', 'help' => __('The plugin to update.')), <add> 'ext' => array('short' => 'e', 'help' => __('The extension(s) to search.')), <add> ) <add> ); <add> <ide> return parent::getOptionParser() <ide> ->addSubcommand('i18n', array( <ide> 'help' => 'Update the i18n translation method calls.', <del> 'parser' => array( <del> 'options' => array( <del> 'plugin' => array('short' => 'p', 'help' => __('The plugin to update.')) <del> ) <del> ) <add> 'parser' => $subcommandParser <ide> )) <ide> ->addSubcommand('helpers', array( <ide> 'help' => 'Update calls to helpers.', <del> 'parser' => array( <del> 'options' => array( <del> 'plugin' => array('short' => 'p', 'help' => __('The plugin to update.')) <del> ) <del> ) <add> 'parser' => $subcommandParser <ide> )); <ide> } <ide> } <ide>\ No newline at end of file
1
Text
Text
add a link to some slides
7c9f730f6b93ee5ea8951576f835ee99c244e4c3
<ide><path>samples/languages/java/README.md <ide> # TensorFlow for Java: Examples <ide> <ide> Examples using the TensorFlow Java API. <add> <add>- [Slides](https://docs.google.com/presentation/d/e/2PACX-1vQ6DzxNTBrJo7K5P8t5_rBRGnyJoPUPBVOJR4ooHCwi4TlBFnIriFmI719rDNpcQzojqsV58aUqmBBx/pub?start=false&loop=false&delayms=3000) from January 2018. <add>- See README.md in each subdirectory for details.
1
Python
Python
add comment clarifying what languages does
bc87b815cc34d375e1a4b4c9b54c296691cee237
<ide><path>spacy/tests/conftest.py <ide> import os <ide> import pytest <ide> <del> <add># These languages get run through generic tokenizer tests <ide> LANGUAGES = [English, German, Spanish, Italian, French, Portuguese, Dutch, <ide> Swedish, Hungarian, Finnish, Bengali, Norwegian] <ide>
1
Ruby
Ruby
address ruby warnings
5a0dddda0980cefbaf80e9f8f10369f62a1d19d8
<ide><path>railties/test/application/integration_test_case_test.rb <ide> class MailerIntegrationTest < ActionDispatch::IntegrationTest <ide> <ide> output = Dir.chdir(app_path) { `bin/rails test 2>&1` } <ide> assert_equal 0, $?.to_i, output <del> assert_match /0 failures, 0 errors/, output <add> assert_match(/0 failures, 0 errors/, output) <ide> end <ide> end <ide> end <ide><path>railties/test/generators/channel_generator_test.rb <ide> class ChannelGeneratorTest < Rails::Generators::TestCase <ide> tests Rails::Generators::ChannelGenerator <ide> <ide> def test_application_cable_skeleton_is_created <del> run_generator ['books'] <add> run_generator ['books'] <ide> <del> assert_file "app/channels/application_cable/channel.rb" do |cable| <del> assert_match(/module ApplicationCable\n class Channel < ActionCable::Channel::Base\n/, cable) <del> end <add> assert_file "app/channels/application_cable/channel.rb" do |cable| <add> assert_match(/module ApplicationCable\n class Channel < ActionCable::Channel::Base\n/, cable) <add> end <ide> <del> assert_file "app/channels/application_cable/connection.rb" do |cable| <del> assert_match(/module ApplicationCable\n class Connection < ActionCable::Connection::Base\n/, cable) <del> end <del> end <add> assert_file "app/channels/application_cable/connection.rb" do |cable| <add> assert_match(/module ApplicationCable\n class Connection < ActionCable::Connection::Base\n/, cable) <add> end <add> end <ide> <ide> def test_channel_is_created <ide> run_generator ['chat']
2
Javascript
Javascript
remove switch-replace residue
444b33584df0de604cf62744d6daa8f01aca34d5
<ide><path>benchmark/http_simple.js <ide> Buffer = require("buffer").Buffer; <ide> <ide> port = parseInt(process.env.PORT || 8000); <ide> <del>var console.log = require("sys").console.log; <del> <ide> var old = (process.argv[2] == 'old'); <ide> <ide> console.log('pid ' + process.pid);
1
Ruby
Ruby
remove useless method
93d99c55bdeb837641fe10ee6fd961f62c89f772
<ide><path>railties/lib/rails/generators/rails/plugin/plugin_generator.rb <ide> def create_javascript_files <ide> build(:javascripts) unless api? <ide> end <ide> <del> def create_images_directory <del> build(:images) unless api? <del> end <del> <ide> def create_bin_files <ide> build(:bin) <ide> end
1
Text
Text
add whitespaces for consistent styling
82000111dc79e525aafa11debf2e241adba6add0
<ide><path>CONTRIBUTING.md <del>#Contributing to AngularJS <add># Contributing to AngularJS <ide> <ide> We'd love for you to contribute to our source code and to make AngularJS even better than it is <ide> today! Here are the guidelines we'd like you to follow: <ide> For large fixes, please build and test the documentation before submitting the P <ide> accidentally introduced any layout or formatting issues. You should also make sure that your commit message <ide> is labeled "docs:" and follows the **Git Commit Guidelines** outlined below. <ide> <del>If you're just making a small change, don't worry about filing an issue first. Use the friendly blue "Improve this doc" button at the top right of the doc page to fork the repository in-place and make a quick change on the fly. When naming the commit, it is advised to still label it according to the commit guidelines below, by starting the commit message with **docs** and referencing the filename. Since this is not obvious and some changes are made on the fly, this is not strictly necessary and we will understand if this isn't done the first few times. <add>If you're just making a small change, don't worry about filing an issue first. Use the friendly blue "Improve this doc" button at the top right of the doc page to fork the repository in-place and make a quick change on the fly. When naming the commit, it is advised to still label it according to the commit guidelines below, by starting the commit message with **docs** and referencing the filename. Since this is not obvious and some changes are made on the fly, this is not strictly necessary and we will understand if this isn't done the first few times. <ide> <ide> ## <a name="submit"></a> Submission Guidelines <ide> <ide> The subject contains succinct description of the change: <ide> * don't capitalize first letter <ide> * no dot (.) at the end <ide> <del>###Body <add>### Body <ide> Just as in the **subject**, use the imperative, present tense: "change" not "changed" nor "changes" <ide> The body should include the motivation for the change and contrast this with previous behavior. <ide> <del>###Footer <add>### Footer <ide> The footer should contain any information about **Breaking Changes** and is also the place to <ide> reference GitHub issues that this commit **Closes**. <ide>
1
Ruby
Ruby
suppress mysql_config errors
2c64b9d1270b0ef468f13152c9acd68e0bb49fd6
<ide><path>railties/lib/rails_generator/generators/applications/app/app_generator.rb <ide> def initialize(runtime_args, runtime_options = {}) <ide> super <ide> usage if args.empty? <ide> @destination_root = args.shift <del> @socket = `mysql_config --socket`.strip <add> @socket = `mysql_config --socket`.strip rescue nil <ide> @socket = '/path/to/your/mysql.sock' if @socket.blank? <ide> end <ide>
1
Javascript
Javascript
ignore ext_frag_depth for webgl 2.0
b1f0db4ea9a23fe12375d9058e7ff515df827a14
<ide><path>src/renderers/webgl/WebGLExtensions.js <ide> function WebGLExtensions( gl ) { <ide> 'OES_texture_half_float', <ide> 'OES_texture_half_float_linear', <ide> 'OES_element_index_uint', <del> 'OES_standard_derivatives' ].indexOf( name ) >= 0 ) { <add> 'OES_standard_derivatives', <add> 'EXT_frag_depth' ].indexOf( name ) >= 0 ) { <ide> <ide> extension = gl; <ide> <ide><path>src/renderers/webgl/WebGLProgram.js <ide> function generateExtensions( extensions, parameters, rendererExtensions, isWebGL <ide> <ide> var chunks = [ <ide> ( ! isWebGL2 && ( extensions.derivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.normalMap || parameters.flatShading ) ) ? '#extension GL_OES_standard_derivatives : enable' : '', <del> ( extensions.fragDepth || parameters.logarithmicDepthBuffer ) && rendererExtensions.get( 'EXT_frag_depth' ) ? '#extension GL_EXT_frag_depth : enable' : '', <add> ( ! isWebGL2 && ( extensions.fragDepth || parameters.logarithmicDepthBuffer ) && rendererExtensions.get( 'EXT_frag_depth' ) ) ? '#extension GL_EXT_frag_depth : enable' : '', <ide> ( extensions.drawBuffers ) && rendererExtensions.get( 'WEBGL_draw_buffers' ) ? '#extension GL_EXT_draw_buffers : require' : '', <ide> ( ! isWebGL2 && ( extensions.shaderTextureLOD || parameters.envMap ) && rendererExtensions.get( 'EXT_shader_texture_lod' ) ) ? '#extension GL_EXT_shader_texture_lod : enable' : '' <ide> ]; <ide> function WebGLProgram( renderer, extensions, code, material, shader, parameters <ide> '#define varying in', <ide> 'out highp vec4 pc_fragColor;', <ide> '#define gl_FragColor pc_fragColor', <add> '#define gl_FragDepthEXT gl_FragDepth', <ide> '#define texture2D texture', <ide> '#define textureCube texture', <ide> '#define texture2DProj textureProj',
2
Java
Java
update javadoc of filepart#filename
138f6bfd84d0a1d8aa13e8d1ea6832c5be1c8055
<ide><path>spring-web/src/main/java/org/springframework/http/codec/multipart/FilePart.java <ide> /* <del> * Copyright 2002-2018 the original author or authors. <add> * Copyright 2002-2021 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public interface FilePart extends Part { <ide> <ide> /** <ide> * Return the original filename in the client's filesystem. <add> * <p><strong>Note:</strong> Please keep in mind this filename is supplied <add> * by the client and should not be used blindly. In addition to not using <add> * the directory portion, the file name could also contain characters such <add> * as ".." and others that can be used maliciously. <add> * @return the original filename, or the empty String if no file has been chosen <add> * in the multipart form, or {@code null} if not defined or not available <add> * @see <a href="https://tools.ietf.org/html/rfc7578#section-4.2">RFC 7578, Section 4.2</a> <add> * @see <a href="https://owasp.org/www-community/vulnerabilities/Unrestricted_File_Upload">Unrestricted File Upload</a> <ide> */ <ide> String filename(); <ide> <ide><path>spring-web/src/main/java/org/springframework/web/multipart/MultipartFile.java <ide> public interface MultipartFile extends InputStreamSource { <ide> * but it typically will not with any other than Opera. <ide> * <p><strong>Note:</strong> Please keep in mind this filename is supplied <ide> * by the client and should not be used blindly. In addition to not using <del> * the directory portion, the file name could also contain characters * such <add> * the directory portion, the file name could also contain characters such <ide> * as ".." and others that can be used maliciously. <ide> * @return the original filename, or the empty String if no file has been chosen <ide> * in the multipart form, or {@code null} if not defined or not available <ide> * @see org.apache.commons.fileupload.FileItem#getName() <ide> * @see org.springframework.web.multipart.commons.CommonsMultipartFile#setPreserveFilename <del> * @see <a href="https://tools.ietf.org/html/rfc7578#section-4.2">RFC 7578, Section 3.4</a> <add> * @see <a href="https://tools.ietf.org/html/rfc7578#section-4.2">RFC 7578, Section 4.2</a> <ide> * @see <a href="https://owasp.org/www-community/vulnerabilities/Unrestricted_File_Upload">Unrestricted File Upload</a> <ide> */ <ide> @Nullable
2
Javascript
Javascript
add comments to infrastructure-log
ccf8bf53e25ba6a063a7f4387551f45bed389c9b
<ide><path>test/configCases/assets/delete-asset/infrastructure-log.js <ide> module.exports = [ <add> // each time sets different assetsInfo object instance in webpack.config.js:54 <add> // this prevents hit in inmemory cache <ide> /^Pack got invalid because of write to: TerserWebpackPlugin|bundle0\.js$/ <ide> ]; <ide><path>test/configCases/process-assets/html-plugin/infrastructure-log.js <ide> module.exports = [ <add> // each time returns different OriginalSource in webpack.config.js:78 <add> // this prevents hit in inmemory cache <ide> /^Pack got invalid because of write to: RealContentHashPlugin|analyse|index\.html$/ <ide> ];
2
Javascript
Javascript
ignore shell-quote on windows
ab5e606e1e0dfaac5c6dc5b22dabcc21bba2e802
<ide><path>lint-staged.config.js <ide> const escape = require('shell-quote').quote <add>const isWin = process.platform === 'win32' <ide> <ide> module.exports = { <ide> '**/*.{js,jsx}': filenames => { <ide> const escapedFileNames = filenames <del> .map(filename => `"${escape([filename])}"`) <add> .map(filename => `"${isWin ? filename : escape([filename])}"`) <ide> .join(' ') <ide> return [ <ide> `prettier --write ${escapedFileNames}`, <ide> module.exports = { <ide> }, <ide> '**/*.{json,ts,tsx,md,mdx,css,html,yml,yaml,scss,sass}': filenames => { <ide> const escapedFileNames = filenames <del> .map(filename => `"${escape([filename])}"`) <add> .map(filename => `"${isWin ? filename : escape([filename])}"`) <ide> .join(' ') <ide> return [ <ide> `prettier --write ${escapedFileNames}`,
1
Text
Text
update "net" section in node to io.js changes
bb766d2c47e8a416ce9f1e4f693f124afe857c1a
<ide><path>CHANGELOG.md <ide> https://iojs.org/api/http.html <ide> - Added `rawHeaders` and `rawTrailers` members on incoming message. <ide> - Removed default chunked encoding on `DELETE` and `OPTIONS`. <ide> <add>### net <add> <add>https://iojs.org/api/net.html <add> <add>- Changed `net.Server.listen` such that, when the bind address is omitted, IPv6 is tried first, and IPv4 is used as a fallback. <add> <ide> ### os <ide> <ide> https://iojs.org/api/os.html
1
Text
Text
add changelog entry for
88ba7056090717084b879002fb92f82ee34bcabf
<ide><path>actionpack/CHANGELOG.md <add>* Add alias method `to_hash` to `to_h` for `cookies`. <add> Add alias method `to_h` to `to_hash` for `session`. <add> <add> *Igor Kasyanchuk* <ide> <ide> <ide> Please check [5-2-stable](https://github.com/rails/rails/blob/5-2-stable/actionpack/CHANGELOG.md) for previous changes.
1
Ruby
Ruby
fix broken autocompleter test
12e0cb7971676fc990f8be87246e8d9f2693aa7a
<ide><path>actionpack/test/template/java_script_macros_helper_test.rb <ide> def test_auto_complete_result <ide> def test_text_field_with_auto_complete <ide> assert_match "<style>", <ide> text_field_with_auto_complete(:message, :recipient) <del> assert_dom_equal %(<input id=\"message_recipient\" name=\"message[recipient]\" size=\"30\" type=\"text\" /><div class=\"auto_complete\" id=\"message_recipient_auto_complete\"></div><script type=\"text/javascript\">\n//<![CDATA[\nnew Ajax.Autocompleter('message_recipient', 'message_recipient_auto_complete', 'http://www.example.com/auto_complete_for_message_recipient', {})\n//]]>\n</script>), <add> assert_dom_equal %(<input id=\"message_recipient\" name=\"message[recipient]\" size=\"30\" type=\"text\" /><div class=\"auto_complete\" id=\"message_recipient_auto_complete\"></div><script type=\"text/javascript\">\n//<![CDATA[\nvar message_recipient_auto_completer = new Ajax.Autocompleter('message_recipient', 'message_recipient_auto_complete', 'http://www.example.com/auto_complete_for_message_recipient', {})\n//]]>\n</script>), <ide> text_field_with_auto_complete(:message, :recipient, {}, :skip_style => true) <ide> end <ide> end
1
Text
Text
fix broken links in the documentation
70e97f96448a6af5ee314cf764b1cb609a9dedbf
<ide><path>docs/HandlingTouches.md <ide> next: animations <ide> <ide> Users interact with mobile apps mainly through touch. They can use a combination of gestures, such as tapping on a button, scrolling a list, or zooming on a map. <ide> <del>React Native provides components to handle common gestures, such as taps and swipes, as well as a comprehensive [gesture responder system](/docs/gesturerespondersystem.html) to allow for more advanced gesture recognition. <add>React Native provides components to handle common gestures, such as taps and swipes, as well as a comprehensive [gesture responder system](/react-native/docs/gesturerespondersystem.html) to allow for more advanced gesture recognition. <ide> <ide> ## Tappable Components <ide> <ide> Tappable components should provide feedback that show the user what is handling <ide> <ide> Which component you use will depend on what kind of feedback you want to provide: <ide> <del>- Generally, you can use [**TouchableHighlight**](/docs/touchablehighlight.html) anywhere you would use a button or link on web. The view's background will be darkened when the user presses down on the button. <add>- Generally, you can use [**TouchableHighlight**](/react-native/docs/touchablehighlight.html) anywhere you would use a button or link on web. The view's background will be darkened when the user presses down on the button. <ide> <del>- You may consider using [**TouchableNativeFeedback**](/docs/touchablenativefeedback.html) on Android to display ink surface reaction ripples that respond to the user's touch. <add>- You may consider using [**TouchableNativeFeedback**](/react-native/docs/touchablenativefeedback.html) on Android to display ink surface reaction ripples that respond to the user's touch. <ide> <del>- [**TouchableOpacity**](/docs/touchableopacity.html) can be used to provide feedback by reducing the opacity of the button, allowing the background to be seen through while the user is pressing down. <add>- [**TouchableOpacity**](/react-native/docs/touchableopacity.html) can be used to provide feedback by reducing the opacity of the button, allowing the background to be seen through while the user is pressing down. <ide> <del>- If you need to handle a tap gesture but you don't want any feedback to be displayed, use [**TouchableWithoutFeedback**](/docs/touchablewithoutfeedback.html). <add>- If you need to handle a tap gesture but you don't want any feedback to be displayed, use [**TouchableWithoutFeedback**](/react-native/docs/touchablewithoutfeedback.html). <ide> <ide> ### Long presses <ide> <ide> In some cases, you may want to detect when a user presses and holds a view for a set amount of time. These long presses can be handled by passing a function to the `onLongPress` props of any of the touchable components listed above. <ide> <ide> ## Scrolling lists and swiping views <ide> <del>A common pattern to many mobile apps is the scrollable list of items. Users interact with these using panning or swiping gestures. The [ScrollView](/docs/basics-component-scrollview.html) component displays a list of items that can be scrolled using these gestures. <add>A common pattern to many mobile apps is the scrollable list of items. Users interact with these using panning or swiping gestures. The [ScrollView](/react-native/docs/basics-component-scrollview.html) component displays a list of items that can be scrolled using these gestures. <ide> <del>ScrollViews can scroll vertically or horizontally, and can be configured to allow paging through views using swiping gestures by using the `pagingEnabled` props. Swiping horizontally between views can also be implemented on Android using the [ViewPagerAndroid](/docs/viewpagerandroid.html) component. <add>ScrollViews can scroll vertically or horizontally, and can be configured to allow paging through views using swiping gestures by using the `pagingEnabled` props. Swiping horizontally between views can also be implemented on Android using the [ViewPagerAndroid](/react-native/docs/viewpagerandroid.html) component. <ide> <del>A [ListView](/docs/basics-component-listview.html) is a special kind of ScrollView that is best suited for displaying long vertical lists of items. It can also display section headers and footers, similar to `UITableView`s on iOS. <add>A [ListView](/react-native/docs/basics-component-listview.html) is a special kind of ScrollView that is best suited for displaying long vertical lists of items. It can also display section headers and footers, similar to `UITableView`s on iOS. <ide> <ide> ### Pinch-to-zoom <ide> <ide> A ScrollView with a single item can be used to allow the user to zoom content. Set up the `maximumZoomScale` and `minimumZoomScale` props and your user will be able to use pinch and expand gestures to zoom in and out. <ide> <ide> ## Handling additional gestures <ide> <del>If you want to allow a user to drag a view around the screen, or you want to implement your own custom pan/drag gesture, take a look at the [PanResponder](/docs/panresponder.html) API or the [gesture responder system docs](/docs/gesturerespondersystem.html). <add>If you want to allow a user to drag a view around the screen, or you want to implement your own custom pan/drag gesture, take a look at the [PanResponder](/react-native/docs/panresponder.html) API or the [gesture responder system docs](/react-native/docs/gesturerespondersystem.html). <ide><path>docs/RunningOnDeviceIOS.md <ide> In Xcode, select your phone as build target and press "Build and run" <ide> <ide> > Hint <ide> > <del>> Shake the device to open the [developer menu](/docs/debugging.html#accessing-the-in-app-developer-menu). <add>> Shake the device to open the [developer menu](/react-native/docs/debugging.html#accessing-the-in-app-developer-menu). <ide> <ide> ## Building your app for production <ide>
2
Text
Text
fix weird word order in chaining-if-else
8e1a2bb4999882b9945a461e476069055e8e096a
<ide><path>curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/chaining-if-else-statements.spanish.md <ide> localeTitle: Encadenamiento en caso contrario <ide> --- <ide> <ide> ## Description <del><section id="description"> <code>if/else</code> declaraciones <code>if/else</code> se pueden encadenar para una lógica compleja. Aquí está el <dfn>pseudocódigo</dfn> de múltiples encadenadas <code>if</code> / <code>else if</code> sentencias: <blockquote> if ( <em>condición1</em> ) { <br> <em>declaración1</em> <br> } else if ( <em>condition2</em> ) { <br> <em>declaración2</em> <br> } else if ( <em>condition3</em> ) { <br> <em>declaración3</em> <br> . . . <br> } else { <br> <em>declaraciónN</em> <br> } </blockquote></section> <add><section id="description"> <code>if/else</code> declaraciones <code>if/else</code> se pueden encadenar para una lógica compleja. Aquí está el <dfn>pseudocódigo</dfn> de múltiples sentencias <code>if</code> / <code>else if</code> encadenadas: <blockquote> if ( <em>condición1</em> ) { <br> <em>declaración1</em> <br> } else if ( <em>condition2</em> ) { <br> <em>declaración2</em> <br> } else if ( <em>condition3</em> ) { <br> <em>declaración3</em> <br> . . . <br> } else { <br> <em>declaraciónN</em> <br> } </blockquote></section> <ide> <ide> ## Instructions <ide> <section id="instructions"> Escriba en cadena las sentencias <code>if</code> / <code>else if</code> para cumplir las siguientes condiciones: <code>num &lt; 5</code> - return &quot;Tiny&quot; <br> <code>num &lt; 10</code> - devuelve &quot;Small&quot; <br> <code>num &lt; 15</code> - devuelve &quot;Medio&quot; <br> <code>num &lt; 20</code> - devuelve &quot;Large&quot; <br> <code>num &gt;= 20</code> - devuelve &quot;Enorme&quot; </section>
1