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
Python
Python
resolve line-too-long in tests
e023c3e59ecbb4c84894623a3aa0a418d6f7b7a9
<ide><path>keras/tests/automatic_outside_compilation_test.py <ide> def validate_recorded_sumary_file(self, event_files, expected_event_counts): <ide> ) <ide> <ide> def testV2SummaryWithKerasSequentialModel(self): <del> # Histogram summaries require the MLIR bridge; see b/178826597#comment107. <del> # TODO(https://github.com/tensorflow/tensorboard/issues/2885): remove this <del> # if histogram summaries are supported fully on non-MLIR bridge or <del> # non-MLIR bridge is no longer run. <add> # Histogram summaries require the MLIR bridge; see <add> # b/178826597#comment107. <add> # TODO(https://github.com/tensorflow/tensorboard/issues/2885): remove <add> # this if histogram summaries are supported fully on non-MLIR bridge or <add> # non-MLIR bridge is no longer run. <ide> enable_histograms = tf_test_utils.is_mlir_bridge_enabled() <ide> strategy = get_tpu_strategy() <ide> <ide> def testV2SummaryWithKerasSequentialModel(self): <ide> os.path.join(self.summary_dir, "train", "event*") <ide> ) <ide> # Since total of 10 steps are ran and summary ops should be invoked <del> # every 2 batches, we should see total of 5 event logs for each summary. <add> # every 2 batches, we should see total of 5 event logs for each <add> # summary. <ide> expected_event_counts = { <ide> "sequential/layer_for_histogram_summary/custom_histogram_summary_v2": 5 <ide> if enable_histograms <ide> def testV2SummaryWithKerasSequentialModel(self): <ide> ) <ide> <ide> def testV2SummaryWithKerasSubclassedModel(self): <del> # Histogram summaries require the MLIR bridge; see b/178826597#comment107. <del> # TODO(https://github.com/tensorflow/tensorboard/issues/2885): remove this <del> # if histogram summaries are supported fully on non-MLIR bridge or <del> # non-MLIR bridge is no longer run. <add> # Histogram summaries require the MLIR bridge; see <add> # b/178826597#comment107. <add> # TODO(https://github.com/tensorflow/tensorboard/issues/2885): remove <add> # this if histogram summaries are supported fully on non-MLIR bridge or <add> # non-MLIR bridge is no longer run. <ide> enable_histograms = tf_test_utils.is_mlir_bridge_enabled() <ide> strategy = get_tpu_strategy() <ide> with strategy.scope(): <ide> def testV2SummaryWithKerasSubclassedModel(self): <ide> os.path.join(self.summary_dir, "train", "event*") <ide> ) <ide> # Since total of 10 steps are ran and summary ops should be invoked <del> # every 2 batches, we should see total of 5 event logs for each summary. <add> # every 2 batches, we should see total of 5 event logs for each <add> # summary. <ide> expected_event_counts = { <ide> ( <ide> "custom_model/layer_for_scalar_summary/" <ide><path>keras/tests/convert_to_constants_test.py <ide> def _testConvertedFunction( <ide> self.assertEqual(0, self._getNumVariables(constant_graph_def)) <ide> self.assertFalse(self._hasStatefulPartitionedCallOp(constant_graph_def)) <ide> <del> # Check that the converted ConcreteFunction produces the same result as the <del> # original Function. <add> # Check that the converted ConcreteFunction produces the same result as <add> # the original Function. <ide> expected_value = tf.nest.flatten(func(**input_data)) <ide> actual_value = tf.nest.flatten(converted_concrete_func(**input_data)) <ide> <ide><path>keras/tests/integration_test.py <ide> class TokenClassificationIntegrationTest(test_combinations.TestCase): <ide> """Tests a very simple token classification model. <ide> <ide> The main purpose of this test is to verify that everything works as expected <del> when input sequences have variable length, and batches are padded only to the <del> maximum length of each batch. This is very common in NLP, and results in the <del> sequence dimension varying with each batch step for both the features <add> when input sequences have variable length, and batches are padded only to <add> the maximum length of each batch. This is very common in NLP, and results in <add> the sequence dimension varying with each batch step for both the features <ide> and the labels. <ide> """ <ide> <ide><path>keras/tests/model_subclassing_compiled_test.py <ide> def test_single_io_workflow_with_datasets(self): <ide> _ = model.evaluate(dataset, steps=10, verbose=0) <ide> <ide> def test_attributes(self): <del> # layers, weights, trainable_weights, non_trainable_weights, inputs, outputs <add> # layers, weights, trainable_weights, non_trainable_weights, inputs, <add> # outputs <ide> <ide> num_classes = (2, 3) <ide> num_samples = 100 <ide><path>keras/tests/model_subclassing_test_util.py <ide> def call(self, inputs): <ide> <ide> def get_nested_model_3(input_dim, num_classes): <ide> # A functional-API model with a subclassed model inside. <del> # NOTE: this requires the inner subclass to implement `compute_output_shape`. <add> # NOTE: this requires the inner subclass to implement <add> # `compute_output_shape`. <ide> <ide> inputs = keras.Input(shape=(input_dim,)) <ide> x = keras.layers.Dense(32, activation="relu")(inputs) <ide><path>keras/tests/temporal_sample_weights_correctness_test.py <ide> def setUp(self): <ide> # mae (y1 - y_pred_1) = [[[.4], [.9]], [[.9], [1.4]], [[1.4], [.4]]] <ide> # mae = [[2.7/3, 2.7/3]] = [[0.9, 0.9]] = 1.8/2 = 0.9 <ide> # mae_2 (y2 - y_pred_2) = [[[.4], [1.4]], [[.9], [.4]], [[1.4], [.9]]] <del> # mae_2 = [[2.7/3, 2.7/3]] = [[0.9, 0.9]] = 1.8/2 = 0.9 <add> # mae_2 = [[2.7/3, 2.7/3]] = [[0.9, 0.9]] = 1.8/2 = <add> # 0.9 <ide> <ide> self.expected_fit_result = { <ide> "output_1_mae": [1, 0.9], <ide> def setUp(self): <ide> # mae_2 (sum over bs) = [[6/3, 1.5/3]] = [[2, .5]] = 2.5/2 = 1.25 <ide> <ide> # Epoch 2 - bias = 0.125 (2.5/2 * 0.1) <del> # y_pred_1 = [[[0.125], [0.125]], [[1.125], [1.125]], [[2.125], [2.125]]] <del> # y_pred_2 = [[[0.125], [0.125]], [[1.125], [1.125]], [[2.125], [2.125]]] <add> # y_pred_1 = [[[0.125], [0.125]], [[1.125], [1.125]], [[2.125], <add> # [2.125]]] <add> # y_pred_2 = [[[0.125], [0.125]], [[1.125], [1.125]], [[2.125], <add> # [2.125]]] <ide> <ide> # mae (y1 - y_pred_1) = [[[.375], [.875]], <ide> # [[.875], [1.375]], <ide> def setUp(self): <ide> # [[1.375 * .5], [.375 * 2.]]] <ide> # mae (w/o weights) = [[2.625/3, 2.625/3]] = (.875+.875)/2 = .875 <ide> # mae (weighted mean) = [[1.3125/1.5, 5.25/6]] = (.875+.875)/2 = .875 <del> # mae (sum over bs) = [[1.3125/3, 5.25/3]] = (0.4375+1.75)/2 = 1.09375 <add> # mae (sum over bs) = [[1.3125/3, 5.25/3]] = (0.4375+1.75)/2 = <add> # 1.09375 <ide> <ide> # mae_2 (y2 - y_pred_2) = [[[.375], [1.375]], <ide> # [[.875], [.375]], <ide> def setUp(self): <ide> # [[.875 * 2.], [.375 * .5]], <ide> # [[1.375 * 2.], [.875 * .5]]] <ide> # mae_2 (w/o weights) = [[2.625/3, 2.625/3]] = (.875+.875)/2 = .875 <del> # mae_2 (weighted mean) = [[5.25/6, 1.3125/1.5]] = (.875+.875)/2 = .875 <del> # mae_2 (sum over bs) = [[5.25/3, 1.3125/3]] = (1.75+0.4375)/2 = 1.09375 <add> # mae_2 (weighted mean) = [[5.25/6, 1.3125/1.5]] = (.875+.875)/2 = <add> # .875 <add> # mae_2 (sum over bs) = [[5.25/3, 1.3125/3]] = (1.75+0.4375)/2 = <add> # 1.09375 <ide> <ide> self.expected_fit_result_with_weights = { <ide> "output_1_mae": [1, 0.875], <ide><path>keras/tests/tracking_test.py <ide> def testIter(self): <ide> # This update() is super tricky. If the dict wrapper subclasses dict, <ide> # CPython will access its storage directly instead of calling any <ide> # methods/properties on the object. So the options are either not to <del> # subclass dict (in which case update will call normal iter methods, but the <del> # object won't pass isinstance checks) or to subclass dict and keep that <del> # storage updated (no shadowing all its methods like ListWrapper). <add> # subclass dict (in which case update will call normal iter methods, but <add> # the object won't pass isinstance checks) or to subclass dict and keep <add> # that storage updated (no shadowing all its methods like ListWrapper). <ide> new_dict.update(model.d) <ide> self.assertEqual({1: 3}, new_dict) <ide> <ide><path>keras/tests/tracking_util_test.py <ide> class CheckpointingTests(test_combinations.TestCase): <ide> def testNamingWithOptimizer(self): <ide> input_value = tf.constant([[3.0]]) <ide> model = MyModel() <del> # A nuisance Model using the same optimizer. Its slot variables should not <del> # go in the checkpoint, since it is never depended on. <add> # A nuisance Model using the same optimizer. Its slot variables should <add> # not go in the checkpoint, since it is never depended on. <ide> other_model = MyModel() <ide> optimizer = adam.Adam(0.001) <ide> step = tf.compat.v1.train.get_or_create_global_step() <ide> def testNamingWithOptimizer(self): <ide> self.assertEqual( <ide> len(expected_checkpoint_names), len(named_variables.keys()) <ide> ) <del> # Check that we've created the right full_names of objects (not exhaustive) <add> # Check that we've created the right full_names of objects (not <add> # exhaustive) <ide> expected_names = { <ide> "step" + suffix: "global_step", <ide> "model/_second/kernel" + suffix: "my_model/dense_1/kernel", <ide> def testSaveRestore(self): <ide> self.assertAllEqual(1, self.evaluate(root_trackable.save_counter)) <ide> self.assertAllEqual([1.5], self.evaluate(m_bias_slot)) <ide> if not tf.executing_eagerly(): <del> return # Restore-on-create is only supported when executing eagerly <add> # Restore-on-create is only supported when executing eagerly <add> return <ide> on_create_model = MyModel() <ide> on_create_optimizer = adam.Adam(0.001) <ide> on_create_root = tf.train.Checkpoint( <ide> def testSaveRestore(self): <ide> status.assert_consumed() <ide> self.assertAllEqual( <ide> optimizer_variables, <del> # Creation order is different, so .variables() needs to be re-sorted. <add> # Creation order is different, so .variables() needs to be <add> # re-sorted. <ide> self.evaluate( <ide> sorted(optimizer.variables(), key=lambda v: v.name) <ide> ), <ide> def testUsageGraph(self): <ide> ) <ide> def testAgnosticUsage(self): <ide> """Graph/eager agnostic usage.""" <del> # Does create garbage when executing eagerly due to ops.Graph() creation. <add> # Does create garbage when executing eagerly due to ops.Graph() <add> # creation. <ide> with self.test_session(): <ide> num_training_steps = 10 <ide> checkpoint_directory = self.get_temp_dir() <ide> def testDeferredSlotRestoration(self): <ide> gradients = [1.0] <ide> train_op = optimizer.apply_gradients(zip(gradients, variables)) <ide> # Note that `optimizer` has not been added as a dependency of <del> # `root`. Create a one-off grouping so that slot variables for `root.var` <del> # get initialized too. <add> # `root`. Create a one-off grouping so that slot variables for <add> # `root.var` get initialized too. <ide> self.evaluate( <ide> trackable_utils.gather_initializers( <ide> tf.train.Checkpoint(root=root, optimizer=optimizer) <ide> def testDeferredSlotRestoration(self): <ide> slot_status.assert_consumed() <ide> self.assertEqual(12.0, self.evaluate(new_root.var)) <ide> if tf.executing_eagerly(): <del> # Slot variables are only created with restoring initializers when <del> # executing eagerly. <add> # Slot variables are only created with restoring initializers <add> # when executing eagerly. <ide> self.assertEqual( <ide> 14.0, <ide> self.evaluate( <ide> def testDeferredSlotRestoration(self): <ide> train_op = new_root.optimizer.apply_gradients( <ide> zip(gradients, variables) <ide> ) <del> # The slot variable now exists; restore() didn't create it, but we should <del> # now have a restore op for it. <add> # The slot variable now exists; restore() didn't create it, but we <add> # should now have a restore op for it. <ide> slot_status.run_restore_ops() <ide> if not tf.executing_eagerly(): <del> # The train op hasn't run when graph building, so the slot variable has <del> # its restored value. It has run in eager, so the value will <del> # be different. <add> # The train op hasn't run when graph building, so the slot <add> # variable has its restored value. It has run in eager, so the <add> # value will be different. <ide> self.assertEqual( <ide> 14.0, <ide> self.evaluate( <ide> def train_fn(): <ide> if not tf.executing_eagerly(): <ide> train_fn = functools.partial(self.evaluate, train_fn()) <ide> status.initialize_or_restore() <del> # TODO(tanzheny): Add hyper variables to .variables(), and set them with <del> # set_weights etc. <add> # TODO(tanzheny): Add hyper variables to .variables(), and set <add> # them with set_weights etc. <ide> variables_not_in_the_variables_property = [ <ide> obj <ide> for obj in optimizer._hyper.values() <ide> def testLoadFromNameBasedSaver(self): <ide> status.assert_existing_objects_matched() <ide> status.assert_nontrivial_match() <ide> else: <del> # When graph building, we haven't read any keys, so we don't know <del> # whether the restore will be complete. <add> # When graph building, we haven't read any keys, so we don't <add> # know whether the restore will be complete. <ide> with self.assertRaisesRegex(AssertionError, "not restored"): <ide> status.assert_consumed() <ide> with self.assertRaisesRegex(AssertionError, "not restored"): <ide> def testLoadFromNameBasedSaver(self): <ide> status.initialize_or_restore() <ide> status.assert_nontrivial_match() <ide> self._check_sentinels(root) <del> # Check that there is no error when keys are missing from the name-based <del> # checkpoint. <add> # Check that there is no error when keys are missing from the <add> # name-based checkpoint. <ide> root.not_in_name_checkpoint = tf.Variable([1.0]) <ide> status = object_saver.read(save_path) <ide> with self.assertRaises(AssertionError): <ide> def testIgnoreSaveCounter(self): <ide> checkpoint_directory = self.get_temp_dir() <ide> checkpoint_prefix = os.path.join(checkpoint_directory, "ckpt") <ide> with self.cached_session() as session: <del> # Create and save a model using Saver() before using a Checkpoint. This <del> # generates a snapshot without the Checkpoint's `save_counter`. <add> # Create and save a model using Saver() before using a Checkpoint. <add> # This generates a snapshot without the Checkpoint's `save_counter`. <ide> model = sequential.Sequential() <ide> model.add(reshaping.Flatten(input_shape=(1,))) <ide> model.add(core.Dense(1)) <ide><path>keras/tests/tracking_util_with_v1_optimizers_test.py <ide> class CheckpointingTests(test_combinations.TestCase): <ide> def testNamingWithOptimizer(self): <ide> input_value = tf.constant([[3.0]]) <ide> model = MyModel() <del> # A nuisance Model using the same optimizer. Its slot variables should not <del> # go in the checkpoint, since it is never depended on. <add> # A nuisance Model using the same optimizer. Its slot variables should <add> # not go in the checkpoint, since it is never depended on. <ide> other_model = MyModel() <ide> optimizer = tf.compat.v1.train.AdamOptimizer(0.001) <ide> optimizer_step = tf.compat.v1.train.get_or_create_global_step() <ide> def testNamingWithOptimizer(self): <ide> self.assertEqual( <ide> len(expected_checkpoint_names), len(named_variables.keys()) <ide> ) <del> # Check that we've created the right full_names of objects (not exhaustive) <add> # Check that we've created the right full_names of objects (not <add> # exhaustive) <ide> expected_names = { <ide> "optimizer_step" + suffix: "global_step", <ide> "model/_second/kernel" + suffix: "my_model/dense_1/kernel", <ide> def testSaveRestore(self): <ide> optimizer.minimize(lambda: model(input_value)) <ide> else: <ide> train_op = optimizer.minimize(model(input_value)) <del> # TODO(allenl): Make initialization more pleasant when graph building. <del> root_trackable.save_counter # pylint: disable=pointless-statement <add> # TODO(allenl): Make initialization more pleasant when graph <add> # building. <add> root_trackable.save_counter <ide> self.evaluate( <ide> trackable_utils.gather_initializers(root_trackable) <ide> ) <ide> def testSaveRestore(self): <ide> self.assertAllEqual(1, self.evaluate(root_trackable.save_counter)) <ide> self.assertAllEqual([1.5], self.evaluate(m_bias_slot)) <ide> if not tf.executing_eagerly(): <del> return # Restore-on-create is only supported when executing eagerly <add> # Restore-on-create is only supported when executing eagerly <add> return <ide> on_create_model = MyModel() <ide> on_create_optimizer = tf.compat.v1.train.AdamOptimizer( <ide> 0.001, <ide> def testUsageGraph(self): <ide> ) <ide> def testAgnosticUsage(self): <ide> """Graph/eager agnostic usage.""" <del> # Does create garbage when executing eagerly due to ops.Graph() creation. <add> # Does create garbage when executing eagerly due to ops.Graph() <add> # creation. <ide> with self.test_session(): <ide> num_training_steps = 10 <ide> checkpoint_directory = self.get_temp_dir() <ide> def test_initialize_if_not_restoring(self): <ide> model = MyModel() <ide> optimizer = tf.compat.v1.train.AdamOptimizer(0.001) <ide> root = tf.train.Checkpoint( <del> model=model, # Do not save the optimizer with the checkpoint. <add> # Do not save the optimizer with the checkpoint. <add> model=model, <ide> global_step=tf.compat.v1.train.get_or_create_global_step(), <ide> ) <ide> optimizer_checkpoint = tf.train.Checkpoint(optimizer=optimizer) <ide> def testLoadFromNameBasedSaver(self): <ide> status.assert_existing_objects_matched() <ide> status.assert_nontrivial_match() <ide> else: <del> # When graph building, we haven't read any keys, so we don't know <del> # whether the restore will be complete. <add> # When graph building, we haven't read any keys, so we don't <add> # know whether the restore will be complete. <ide> with self.assertRaisesRegex(AssertionError, "not restored"): <ide> status.assert_consumed() <ide> with self.assertRaisesRegex(AssertionError, "not restored"): <ide> def testLoadFromNameBasedSaver(self): <ide> status = object_saver.read(save_path) <ide> status.initialize_or_restore() <ide> self._check_sentinels(root) <del> # Check that there is no error when keys are missing from the name-based <del> # checkpoint. <add> # Check that there is no error when keys are missing from the <add> # name-based checkpoint. <ide> root.not_in_name_checkpoint = tf.Variable([1.0]) <ide> status = object_saver.read(save_path) <ide> with self.assertRaises(AssertionError):
9
Text
Text
correct spelling error
72d989c68169426e5b27cd3c28b1418578231392
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-css-colors-by-building-a-set-of-colored-markers/step-037.md <ide> Notice that the red and cyan colors are very bright right next to each other. Th <ide> <ide> It's better practice to choose one color as the dominant color, and use its complementary color as an accent to bring attention to certain content on the page. <ide> <del>First, in the `h1` rule, use the `rbg` function to set its background color to cyan. <add>First, in the `h1` rule, use the `rgb` function to set its background color to cyan. <ide> <ide> # --hints-- <ide>
1
Text
Text
update chinese translation and fix indentation
37cf8fbffc61b6f49a0379001511e62d34f32ecc
<ide><path>guide/chinese/python/bool-function/index.md <ide> localeTitle: Python Bool函数 <ide> <ide> ## 参数 <ide> <del>它需要一个参数, `x` 。使用标准[真值测试程序](https://docs.python.org/3/library/stdtypes.html#truth)转换`x` 。 <add>它需要一个参数`x` 。使用标准[真值测试程序](https://docs.python.org/3/library/stdtypes.html#truth)转换`x` 。 <ide> <del>## 回报价值 <add>## 返回值 <ide> <ide> 如果`x`为false或省略,则返回`False` ;否则返回`True` 。 <ide> <ide> ## 代码示例 <ide> ``` <ide> print(bool(4 > 2)) # Returns True as 4 is greater than 2 <del> print(bool(4 < 2)) # Returns False as 4 is not less than 2 <del> print(bool(4 == 4)) # Returns True as 4 is equal to 4 <del> print(bool(4 != 4)) # Returns False as 4 is equal to 4 so inequality doesn't holds <del> print(bool(4)) # Returns True as 4 is a non-zero value <del> print(bool(-4)) # Returns True as -4 is a non-zero value <del> print(bool(0)) # Returns False as it is a zero value <del> print(bool('dskl')) # Returns True as the string is a non-zero value <del> print(bool([1, 2, 3])) # Returns True as the list is a non-zero value <del> print(bool((2,3,4))) # Returns True as tuple is a non-zero value <del> print(bool([])) # Returns False as list is empty and equal to 0 according to truth value testing <add>print(bool(4 < 2)) # Returns False as 4 is not less than 2 <add>print(bool(4 == 4)) # Returns True as 4 is equal to 4 <add>print(bool(4 != 4)) # Returns False as 4 is equal to 4 so inequality doesn't holds <add>print(bool(4)) # Returns True as 4 is a non-zero value <add>print(bool(-4)) # Returns True as -4 is a non-zero value <add>print(bool(0)) # Returns False as it is a zero value <add>print(bool('dskl')) # Returns True as the string is a non-zero value <add>print(bool([1, 2, 3])) # Returns True as the list is a non-zero value <add>print(bool((2,3,4))) # Returns True as tuple is a non-zero value <add>print(bool([])) # Returns False as list is empty and equal to 0 according to truth value testing <ide> ``` <ide> <del>![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":火箭:") [运行代码](https://repl.it/CVCS/2) <add>[运行代码](https://repl.it/CVCS/2) <ide> <del>[官方文件](https://docs.python.org/3/library/functions.html#bool) <ide>\ No newline at end of file <add>[官方文件](https://docs.python.org/3/library/functions.html#bool)
1
Mixed
Python
remove rmse objective (use mse instead)
65b5899d068daadb9101025dd8b8a7e4ceecec35
<ide><path>docs/templates/objectives.md <ide> For a few examples of such functions, check out the [objectives source](https:// <ide> ## Available objectives <ide> <ide> - __mean_squared_error__ / __mse__ <del>- __root_mean_squared_error__ / __rmse__ <ide> - __mean_absolute_error__ / __mae__ <ide> - __mean_absolute_percentage_error__ / __mape__ <ide> - __mean_squared_logarithmic_error__ / __msle__ <ide><path>keras/objectives.py <ide> def mean_squared_error(y_true, y_pred): <ide> return K.mean(K.square(y_pred - y_true), axis=-1) <ide> <ide> <del>def root_mean_squared_error(y_true, y_pred): <del> return K.sqrt(K.mean(K.square(y_pred - y_true), axis=-1)) <del> <del> <ide> def mean_absolute_error(y_true, y_pred): <ide> return K.mean(K.abs(y_pred - y_true), axis=-1) <ide> <ide> def cosine_proximity(y_true, y_pred): <ide> <ide> # aliases <ide> mse = MSE = mean_squared_error <del>rmse = RMSE = root_mean_squared_error <ide> mae = MAE = mean_absolute_error <ide> mape = MAPE = mean_absolute_percentage_error <ide> msle = MSLE = mean_squared_logarithmic_error
2
Javascript
Javascript
simplify binary search
1eb0932d04ce966cc034259f97334c53ec49af22
<ide><path>d3.layout.js <ide> d3.layout.histogram = function() { <ide> <ide> // Count the number of samples per bin. <ide> for (var i = 0; i < x.length; i++) { <del> var j = d3_layout_histogramSearchIndex(ticks, x[i]) - 1, <del> bin = bins[Math.max(0, Math.min(bins.length - 1, j))]; <add> var bin = bins[d3_layout_histogramSearch(ticks, x[i])]; <ide> bin.y++; <ide> bin.push(data[i]); <ide> } <ide> d3.layout.histogram = function() { <ide> }; <ide> <ide> // Performs a binary search on a sorted array. <del>// Returns the index of the value if found, otherwise -(insertion point) - 1. <del>// The insertion point is the index at which value should be inserted into the <del>// array for the array to remain sorted. <ide> function d3_layout_histogramSearch(array, value) { <del> var low = 0, high = array.length - 1; <add> var low = 1, high = array.length - 2; <ide> while (low <= high) { <ide> var mid = (low + high) >> 1, midValue = array[mid]; <ide> if (midValue < value) low = mid + 1; <ide> else if (midValue > value) high = mid - 1; <ide> else return mid; <ide> } <del> return -low - 1; <del>} <del> <del>function d3_layout_histogramSearchIndex(array, value) { <del> var i = d3_layout_histogramSearch(array, value); <del> return (i < 0) ? (-i - 1) : i; <add> return low - 1; <ide> } <ide> <ide> function d3_layout_histogramTicks(x) { <ide><path>d3.layout.min.js <del>(function(){function V(a,b,c){return a._tree.ancestor.parent==b.parent?a._tree.ancestor:c}function U(a,b,c){a=a._tree,b=b._tree;var d=c/(b.number-a.number);a.change+=d,b.change-=d,b.shift+=c,b.prelim+=c,b.mod+=c}function T(a){var b=0,c=0,d=a.children,e=d.length,f;while(--e>=0)f=d[e]._tree,f.prelim+=b,f.mod+=b,b+=f.shift+(c+=f.change)}function S(a,b){function c(a,d){var e=a.children;if(e){var f,g=null,h=-1,i=e.length;while(++h<i)f=e[h],c(f,g),g=f}b(a,d)}c(a,null)}function R(a,b){return a.depth-b.depth}function Q(a,b){return b.x-a.x}function P(a,b){return a.x-b.x}function O(a,b){var c=a.children;if(c){var d,e=c.length,f=-1;while(++f<e)b(d=O(c[f],b),a)>0&&(a=d)}return a}function N(a){return a.children?a.children[a.children.length-1]:a._tree.thread}function M(a){return a.children?a.children[0]:a._tree.thread}function L(a,b){return a.parent==b.parent?1:2}function K(a){return d3.merge(a.map(function(a){return(a.children||[]).map(function(b){return{source:a,target:b}})}))}function J(a){var b=a.children;return b?J(b[b.length-1]):a}function I(a){var b=a.children;return b?I(b[0]):a}function H(a){return a.reduce(function(a,b){return a+b.x},0)/a.length}function G(a){return 1+d3.max(a,function(a){return a.y})}function F(a,b,c){var d=b.r+c.r,e=a.r+c.r,f=b.x-a.x,g=b.y-a.y,h=Math.sqrt(f*f+g*g),i=(e*e+h*h-d*d)/(2*e*h),j=Math.acos(i),k=i*e,l=Math.sin(j)*e;f/=h,g/=h,c.x=a.x+k*f+l*g,c.y=a.y+k*g-l*f}function E(a,b,c,d){var e=a.children;a.x=b+=d*a.x,a.y=c+=d*a.y,a.r*=d;if(e){var f=-1,g=e.length;while(++f<g)E(e[f],b,c,d)}}function D(a){var b=a.children;b?(b.forEach(D),a.r=A(b)):a.r=Math.sqrt(a.value)}function C(a){delete a._pack_next,delete a._pack_prev}function B(a){a._pack_next=a._pack_prev=a}function A(a){function l(a){b=Math.min(a.x-a.r,b),c=Math.max(a.x+a.r,c),d=Math.min(a.y-a.r,d),e=Math.max(a.y+a.r,e)}var b=Infinity,c=-Infinity,d=Infinity,e=-Infinity,f=a.length,g,h,i,j,k;a.forEach(B),g=a[0],g.x=-g.r,g.y=0,l(g);if(f>1){h=a[1],h.x=h.r,h.y=0,l(h);if(f>2){i=a[2],F(g,h,i),l(i),x(g,i),g._pack_prev=i,x(i,h),h=g._pack_next;for(var m=3;m<f;m++){F(g,h,i=a[m]);var n=0,o=1,p=1;for(j=h._pack_next;j!=h;j=j._pack_next,o++)if(z(j,i)){n=1;break}if(n==1)for(k=g._pack_prev;k!=j._pack_prev;k=k._pack_prev,p++)if(z(k,i)){p<o&&(n=-1,j=k);break}n==0?(x(g,i),h=i,l(i)):n>0?(y(g,j),h=j,m--):(y(j,h),g=j,m--)}}}var q=(b+c)/2,r=(d+e)/2,s=0;for(var m=0;m<f;m++){var t=a[m];t.x-=q,t.y-=r,s=Math.max(s,t.r+Math.sqrt(t.x*t.x+t.y*t.y))}a.forEach(C);return s}function z(a,b){var c=b.x-a.x,d=b.y-a.y,e=a.r+b.r;return e*e-c*c-d*d>.001}function y(a,b){a._pack_next=b,b._pack_prev=a}function x(a,b){var c=a._pack_next;a._pack_next=b,b._pack_prev=a,b._pack_next=c,c._pack_prev=b}function w(a,b){return a.value-b.value}function v(a,b){return b.value-a.value}function u(a){return a.value}function t(a){return a.children}function s(a){return d3.scale.linear().domain(a).ticks(10)}function r(a,b){var c=q(a,b);return c<0?-c-1:c}function q(a,b){var c=0,d=a.length-1;while(c<=d){var e=c+d>>1,f=a[e];if(f<b)c=e+1;else if(f>b)d=e-1;else return e}return-c-1}function p(a,b){return a+b.y}function o(a){var b=1,c=0,d=a[0].y,e,f=a.length;for(;b<f;++b)(e=a[b].y)>d&&(c=b,d=e);return c}function n(a){return a.reduce(p,0)}function k(a){var b=0,c=0;a.count=0,a.leaf||a.nodes.forEach(function(d){k(d),a.count+=d.count,b+=d.count*d.cx,c+=d.count*d.cy}),a.point&&(a.leaf||(a.point.x+=Math.random()-.5,a.point.y+=Math.random()-.5),a.count++,b+=a.point.x,c+=a.point.y),a.cx=b/a.count,a.cy=c/a.count}function j(){d3.event.stopPropagation(),d3.event.preventDefault()}function i(){c&&(j(),c=!1)}function h(c,d){(a=c).fixed=!0,b=!1,e=this,j()}function g(b){b!==a&&(b.fixed=!1)}function f(a){a.fixed=!0}d3.layout={},d3.layout.chord=function(){function k(){b.sort(function(a,b){a=Math.min(a.source.value,a.target.value),b=Math.min(b.source.value,b.target.value);return i(a,b)})}function j(){var a={},j=[],l=d3.range(e),m=[],n,o,p,q,r;b=[],c=[],n=0,q=-1;while(++q<e){o=0,r=-1;while(++r<e)o+=d[q][r];j.push(o),m.push(d3.range(e)),n+=o}g&&l.sort(function(a,b){return g(j[a],j[b])}),h&&m.forEach(function(a,b){a.sort(function(a,c){return h(d[b][a],d[b][c])})}),n=(2*Math.PI-f*e)/n,o=0,q=-1;while(++q<e){p=o,r=-1;while(++r<e){var s=l[q],t=m[q][r],u=d[s][t];a[s+"-"+t]={index:s,subindex:t,startAngle:o,endAngle:o+=u*n,value:u}}c.push({index:s,startAngle:p,endAngle:o,value:(o-p)/n}),o+=f}q=-1;while(++q<e){r=q-1;while(++r<e){var v=a[q+"-"+r],w=a[r+"-"+q];(v.value||w.value)&&b.push({source:v,target:w})}}i&&k()}var a={},b,c,d,e,f=0,g,h,i;a.matrix=function(f){if(!arguments.length)return d;e=(d=f)&&d.length,b=c=null;return a},a.padding=function(d){if(!arguments.length)return f;f=d,b=c=null;return a},a.sortGroups=function(d){if(!arguments.length)return g;g=d,b=c=null;return a},a.sortSubgroups=function(c){if(!arguments.length)return h;h=c,b=null;return a},a.sortChords=function(c){if(!arguments.length)return i;i=c,b&&k();return a},a.chords=function(){b||j();return b},a.groups=function(){c||j();return c};return a},d3.layout.force=function(){function A(){!a||(b&&(c=!0,j()),z(),a.fixed=!1,a=e=null)}function z(){if(!!a){if(!e.parentNode){a.fixed=!1,a=e=null;return}var c=d3.svg.mouse(e);b=!0,a.px=c[0],a.py=c[1],d.resume()}}function y(){var a=u.length,b=v.length,c=d3.geom.quadtree(u),d,e,f,g,h,i,j;for(d=0;d<b;++d){e=v[d],f=e.source,g=e.target,i=g.x-f.x,j=g.y-f.y;if(h=i*i+j*j)h=n*((h=Math.sqrt(h))-p)/h,i*=h,j*=h,g.x-=i,g.y-=j,f.x+=i,f.y+=j}var s=n*r;i=m[0]/2,j=m[1]/2,d=-1;while(++d<a)e=u[d],e.x+=(i-e.x)*s,e.y+=(j-e.y)*s;k(c);var t=n*q;d=-1;while(++d<a)c.visit(x(u[d],t));d=-1;while(++d<a)e=u[d],e.fixed?(e.x=e.px,e.y=e.py):(e.x-=(e.px-(e.px=e.x))*o,e.y-=(e.py-(e.py=e.y))*o);l.tick.dispatch({type:"tick",alpha:n});return(n*=.99)<.005}function x(a,b){return function(c,d,e,f,g){if(c.point!==a){var h=c.cx-a.x,i=c.cy-a.y,j=1/Math.sqrt(h*h+i*i);if((f-d)*j<s){var k=b*c.count*j*j;a.x+=h*k,a.y+=i*k;return!0}if(c.point&&isFinite(j)){var k=b*j*j;a.x+=h*k,a.y+=i*k}}}}var d={},l=d3.dispatch("tick"),m=[1,1],n,o=.9,p=20,q=-30,r=.1,s=.8,t,u,v,w;d.on=function(a,b){l[a].add(b);return d},d.nodes=function(a){if(!arguments.length)return u;u=a;return d},d.links=function(a){if(!arguments.length)return v;v=a;return d},d.size=function(a){if(!arguments.length)return m;m=a;return d},d.distance=function(a){if(!arguments.length)return p;p=a;return d},d.drag=function(a){if(!arguments.length)return o;o=a;return d},d.charge=function(a){if(!arguments.length)return q;q=a;return d},d.gravity=function(a){if(!arguments.length)return r;r=a;return d},d.theta=function(a){if(!arguments.length)return s;s=a;return d},d.start=function(){function k(){if(!h){h=[];for(b=0;b<c;++b)h[b]=[];for(b=0;b<e;++b){var d=v[b];h[d.source.index].push(d.target),h[d.target.index].push(d.source)}}return h[a]}function j(b,c){var d=k(a),e=-1,f=d.length,g;while(++e<f)if(!isNaN(g=d[e][b]))return g;return Math.random()*c}var a,b,c=u.length,e=v.length,f=m[0],g=m[1],h,i;for(a=0;a<c;++a)(i=u[a]).index=a;for(a=0;a<e;++a)i=v[a],typeof i.source=="number"&&(i.source=u[i.source]),typeof i.target=="number"&&(i.target=u[i.target]);for(a=0;a<c;++a)i=u[a],isNaN(i.x)&&(i.x=j("x",f)),isNaN(i.y)&&(i.y=j("y",g)),isNaN(i.px)&&(i.px=i.x),isNaN(i.py)&&(i.py=i.y);return d.resume()},d.resume=function(){n=.1,d3.timer(y);return d},d.stop=function(){n=0;return d},d.drag=function(){this.on("mouseover.force",f).on("mouseout.force",g).on("mousedown.force",h),d3.select(window).on("mousemove.force",z).on("mouseup.force",A,!0).on("click.force",i,!0);return d};return d};var a,b,c,e;d3.layout.partition=function(){function e(e,f){var g=a.call(this,e,f);c(g[0],0,b[0],b[1]/d(g[0]));return g}function d(a){var b=a.children,c=0;if(b){var e=-1,f=b.length;while(++e<f)c=Math.max(c,d(b[e]))}return 1+c}function c(a,b,d,e){var f=a.children;a.x=b,a.y=a.depth*e,a.dx=d,a.dy=e;if(f){var g=-1,h=f.length,i,j;d/=a.value;while(++g<h)c(i=f[g],b,j=i.value*d,e),b+=j}}var a=d3.layout.hierarchy(),b=[1,1];e.sort=d3.rebind(e,a.sort),e.children=d3.rebind(e,a.children),e.value=d3.rebind(e,a.value),e.size=function(a){if(!arguments.length)return b;b=a;return e};return e},d3.layout.pie=function(){function f(f,g){var h=+(typeof c=="function"?c.apply(this,arguments):c),i=(typeof e=="function"?e.apply(this,arguments):e)-c,j=d3.range(f.length);b!=null&&j.sort(function(a,c){return b(f[a],f[c])});var k=f.map(a);i/=k.reduce(function(a,b){return a+b},0);var l=j.map(function(a){return{value:d=k[a],startAngle:h,endAngle:h+=d*i}});return f.map(function(a,b){return l[j[b]]})}var a=Number,b=null,c=0,e=2*Math.PI;f.value=function(b){if(!arguments.length)return a;a=b;return f},f.sort=function(a){if(!arguments.length)return b;b=a;return f},f.startAngle=function(a){if(!arguments.length)return c;c=a;return f},f.endAngle=function(a){if(!arguments.length)return e;e=a;return f};return f},d3.layout.stack=function(){function c(c){var d=c.length,e=c[0].length,f,g,h,i=l[a](c);m[b](c,i);for(g=0;g<e;++g)for(f=1,h=c[i[0]][g].y0;f<d;++f)c[i[f]][g].y0=h+=c[i[f-1]][g].y;return c}var a="default",b="zero";c.order=function(b){if(!arguments.length)return a;a=b;return c},c.offset=function(a){if(!arguments.length)return b;b=a;return c};return c};var l={"inside-out":function(a){var b=a.length,c,d,e=a.map(o),f=a.map(n),g=d3.range(b).sort(function(a,b){return e[a]-e[b]}),h=0,i=0,j=[],k=[];for(c=0;c<b;c++)d=g[c],h<i?(h+=f[d],j.push(d)):(i+=f[d],k.push(d));return k.reverse().concat(j)},reverse:function(a){return d3.range(a.length).reverse()},"default":function(a){return d3.range(a.length)}},m={silhouette:function(a,b){var c=a.length,d=a[0].length,e=[],f=0,g,h,i;for(h=0;h<d;++h){for(g=0,i=0;g<c;g++)i+=a[g][h].y;i>f&&(f=i),e.push(i)}for(h=0,g=b[0];h<d;++h)a[g][h].y0=(f-e[h])/2},wiggle:function(a,b){var c=a.length,d=a[0],e=d.length,f=0,g,h,i,j,k,l=b[0],m,n,o,p,q,r;a[l][0].y0=q=r=0;for(h=1;h<e;++h){for(g=0,m=0;g<c;++g)m+=a[g][h].y;for(g=0,n=0,p=d[h].x-d[h-1].x;g<c;++g){for(i=0,j=b[g],o=(a[j][h].y-a[j][h-1].y)/(2*p);i<g;++i)o+=(a[k=b[i]][h].y-a[k][h-1].y)/p;n+=o*a[j][h].y}a[l][h].y0=q-=m?n/m*p:0,q<r&&(r=q)}for(h=0;h<e;++h)a[l][h].y0-=r},zero:function(a,b){var c=0,d=a[0].length,e=b[0];for(;c<d;++c)a[e][c].y0=0}};d3.layout.histogram=function(){function d(d,e){var f=d.map(b),g=[],h=c.call(this,d,e);for(var e=0;e<h.length-1;e++){var i=g[e]=[];i.x=h[e],i.dx=h[e+1]-h[e],i.y=0}for(var e=0;e<f.length;e++){var j=r(h,f[e])-1,i=g[Math.max(0,Math.min(g.length-1,j))];i.y++,i.push(d[e])}if(!a)for(var e=0;e<g.length;e++)g[e].y/=f.length;return g}var a=!0,b=Number,c=s;d.frequency=function(b){if(!arguments.length)return a;a=Boolean(b);return d},d.ticks=function(a){if(!arguments.length)return c;c=d3.functor(a);return d},d.value=function(a){if(!arguments.length)return b;b=a;return d};return d},d3.layout.hierarchy=function(){function g(a){var b=[];e(a,0,b);return b}function f(a,b){var d=a.children,e=0;if(d){var h=-1,i=d.length,j=b+1;while(++h<i)e+=f(d[h],j)}else c&&(e=c.call(g,a.data,b));c&&(a.value=e);return e}function e(f,h,i){var j=b.call(g,f,h),k={depth:h,data:f};i.push(k);if(j){var l=-1,m=j.length,n=k.children=[],o=0,p=h+1;while(++l<m)d=e(j[l],p,i),d.parent=k,n.push(d),o+=d.value;a&&n.sort(a),c&&(k.value=o)}else c&&(k.value=c.call(g,f,h));return k}var a=v,b=t,c=u;g.sort=function(b){if(!arguments.length)return a;a=b;return g},g.children=function(a){if(!arguments.length)return b;b=a;return g},g.value=function(a){if(!arguments.length)return c;c=a;return g},g.revalue=function(a){f(a,0);return a};return g},d3.layout.pack=function(){function c(c,d){var e=a.call(this,c,d),f=e[0];f.x=0,f.y=0,D(f);var g=b[0],h=b[1],i=1/Math.max(2*f.r/g,2*f.r/h);E(f,g/2,h/2,i);return e}var a=d3.layout.hierarchy(),b=[1,1];c.sort=d3.rebind(c,a.sort),c.children=d3.rebind(c,a.children),c.value=d3.rebind(c,a.value),c.size=function(a){if(!arguments.length)return b;b=a;return c};return c.sort(w)},d3.layout.cluster=function(){function d(d,e){var f=a.call(this,d,e),g=f[0],h,i=0,j,k;S(g,function(a){a.children?(a.x=H(a.children),a.y=G(a.children)):(a.x=h?i+=b(a,h):0,a.y=0,h=a)});var l=I(g),m=J(g),n=l.x-b(l,m)/2,o=m.x+b(m,l)/2;S(g,function(a){a.x=(a.x-n)/(o-n)*c[0],a.y=(1-a.y/g.y)*c[1]});return f}var a=d3.layout.hierarchy().sort(null).value(null),b=L,c=[1,1];d.sort=d3.rebind(d,a.sort),d.children=d3.rebind(d,a.children),d.links=K,d.separation=function(a){if(!arguments.length)return b;b=a;return d},d.size=function(a){if(!arguments.length)return c;c=a;return d};return d},d3.layout.tree=function(){function d(d,e){function j(a,c,d){if(c){var e=a,f=a,g=c,h=a.parent.children[0],i=e._tree.mod,j=f._tree.mod,k=g._tree.mod,l=h._tree.mod,m;while(g=N(g),e=M(e),g&&e)h=M(h),f=N(f),f._tree.ancestor=a,m=g._tree.prelim+k-e._tree.prelim-i+b(g,e),m>0&&(U(V(g,a,d),a,m),i+=m,j+=m),k+=g._tree.mod,i+=e._tree.mod,l+=h._tree.mod,j+=f._tree.mod;g&&!N(f)&&(f._tree.thread=g,f._tree.mod+=k-j),e&&!M(h)&&(h._tree.thread=e,h._tree.mod+=i-l,d=a)}return d}function i(a,b){a.x=a._tree.prelim+b;var c=a.children;if(c){var d=-1,e=c.length;b+=a._tree.mod;while(++d<e)i(c[d],b)}}function h(a,c){var d=a.children,e=a._tree;if(d){var f=d.length,g=d[0],i,k=g,l,m=-1;while(++m<f)l=d[m],h(l,i),k=j(l,i,k),i=l;T(a);var n=.5*(g._tree.prelim+l._tree.prelim);c?(e.prelim=c._tree.prelim+b(a,c),e.mod=e.prelim-n):e.prelim=n}else c&&(e.prelim=c._tree.prelim+b(a,c))}var f=a.call(this,d,e),g=f[0];S(g,function(a,b){a._tree={ancestor:a,prelim:0,mod:0,change:0,shift:0,number:b?b._tree.number+1:0}}),h(g),i(g,-g._tree.prelim);var k=O(g,Q),l=O(g,P),m=O(g,R),n=k.x-b(k,l)/2,o=l.x+b(l,k)/2,p=m.depth;S(g,function(a){a.x=(a.x-n)/(o-n)*c[0],a.y=a.depth/p*c[1],delete a._tree});return f}var a=d3.layout.hierarchy().sort(null).value(null),b=L,c=[1,1];d.sort=d3.rebind(d,a.sort),d.children=d3.rebind(d,a.children),d.links=K,d.separation=function(a){if(!arguments.length)return b;b=a;return d},d.size=function(a){if(!arguments.length)return c;c=a;return d};return d},d3.layout.treemap=function(){function k(b){var i=e||a(b),j=i[0];j.x=0,j.y=0,j.dx=c[0],j.dy=c[1],e&&a.revalue(j),f(j,c[0]*c[1]/j.value),(e?h:g)(j),d&&(e=i);return i}function j(a,c,d,e){var f=-1,g=a.length,h=d.x,i=d.y,j=c?b(a.area/c):0,k;if(c==d.dx){if(e||j>d.dy)j=d.dy;while(++f<g)k=a[f],k.x=h,k.y=i,k.dy=j,h+=k.dx=b(k.area/j);k.z=!0,k.dx+=d.x+d.dx-h,d.y+=j,d.dy-=j}else{if(e||j>d.dx)j=d.dx;while(++f<g)k=a[f],k.x=h,k.y=i,k.dx=j,i+=k.dy=b(k.area/j);k.z=!1,k.dy+=d.y+d.dy-i,d.x+=j,d.dx-=j}}function i(a,b){var c=a.area,d,e=0,f=Infinity,g=-1,h=a.length;while(++g<h)d=a[g].area,d<f&&(f=d),d>e&&(e=d);c*=c,b*=b;return Math.max(b*e/c,c/(b*f))}function h(a){if(!!a.children){var b={x:a.x,y:a.y,dx:a.dx,dy:a.dy},c=a.children.slice(),d,e=[];e.area=0;while(d=c.pop())e.push(d),e.area+=d.area,d.z!=null&&(j(e,d.z?b.dx:b.dy,b,!c.length),e.length=e.area=0);a.children.forEach(h)}}function g(a){if(!!a.children){var b={x:a.x,y:a.y,dx:a.dx,dy:a.dy},c=[],d=a.children.slice(),e,f=Infinity,h,k=Math.min(b.dx,b.dy),l;c.area=0;while((l=d.length)>0)c.push(e=d[l-1]),c.area+=e.area,(h=i(c,k))<=f?(d.pop(),f=h):(c.area-=c.pop().area,j(c,k,b,!1),k=Math.min(b.dx,b.dy),c.length=c.area=0,f=Infinity);c.length&&(j(c,k,b,!0),c.length=c.area=0),a.children.forEach(g)}}function f(a,b){var c=a.children;a.area=a.value*b;if(c){var d=-1,e=c.length;while(++d<e)f(c[d],b)}}var a=d3.layout.hierarchy(),b=Math.round,c=[1,1],d=!1,e;k.sort=d3.rebind(k,a.sort),k.children=d3.rebind(k,a.children),k.value=d3.rebind(k,a.value),k.size=function(a){if(!arguments.length)return c;c=a;return k},k.round=function(a){if(!arguments.length)return b!=Number;b=a?Math.round:Number;return k},k.sticky=function(a){if(!arguments.length)return d;d=a,e=null;return k};return k}})() <ide>\ No newline at end of file <add>(function(){function U(a,b,c){return a._tree.ancestor.parent==b.parent?a._tree.ancestor:c}function T(a,b,c){a=a._tree,b=b._tree;var d=c/(b.number-a.number);a.change+=d,b.change-=d,b.shift+=c,b.prelim+=c,b.mod+=c}function S(a){var b=0,c=0,d=a.children,e=d.length,f;while(--e>=0)f=d[e]._tree,f.prelim+=b,f.mod+=b,b+=f.shift+(c+=f.change)}function R(a,b){function c(a,d){var e=a.children;if(e){var f,g=null,h=-1,i=e.length;while(++h<i)f=e[h],c(f,g),g=f}b(a,d)}c(a,null)}function Q(a,b){return a.depth-b.depth}function P(a,b){return b.x-a.x}function O(a,b){return a.x-b.x}function N(a,b){var c=a.children;if(c){var d,e=c.length,f=-1;while(++f<e)b(d=N(c[f],b),a)>0&&(a=d)}return a}function M(a){return a.children?a.children[a.children.length-1]:a._tree.thread}function L(a){return a.children?a.children[0]:a._tree.thread}function K(a,b){return a.parent==b.parent?1:2}function J(a){return d3.merge(a.map(function(a){return(a.children||[]).map(function(b){return{source:a,target:b}})}))}function I(a){var b=a.children;return b?I(b[b.length-1]):a}function H(a){var b=a.children;return b?H(b[0]):a}function G(a){return a.reduce(function(a,b){return a+b.x},0)/a.length}function F(a){return 1+d3.max(a,function(a){return a.y})}function E(a,b,c){var d=b.r+c.r,e=a.r+c.r,f=b.x-a.x,g=b.y-a.y,h=Math.sqrt(f*f+g*g),i=(e*e+h*h-d*d)/(2*e*h),j=Math.acos(i),k=i*e,l=Math.sin(j)*e;f/=h,g/=h,c.x=a.x+k*f+l*g,c.y=a.y+k*g-l*f}function D(a,b,c,d){var e=a.children;a.x=b+=d*a.x,a.y=c+=d*a.y,a.r*=d;if(e){var f=-1,g=e.length;while(++f<g)D(e[f],b,c,d)}}function C(a){var b=a.children;b?(b.forEach(C),a.r=z(b)):a.r=Math.sqrt(a.value)}function B(a){delete a._pack_next,delete a._pack_prev}function A(a){a._pack_next=a._pack_prev=a}function z(a){function l(a){b=Math.min(a.x-a.r,b),c=Math.max(a.x+a.r,c),d=Math.min(a.y-a.r,d),e=Math.max(a.y+a.r,e)}var b=Infinity,c=-Infinity,d=Infinity,e=-Infinity,f=a.length,g,h,i,j,k;a.forEach(A),g=a[0],g.x=-g.r,g.y=0,l(g);if(f>1){h=a[1],h.x=h.r,h.y=0,l(h);if(f>2){i=a[2],E(g,h,i),l(i),w(g,i),g._pack_prev=i,w(i,h),h=g._pack_next;for(var m=3;m<f;m++){E(g,h,i=a[m]);var n=0,o=1,p=1;for(j=h._pack_next;j!=h;j=j._pack_next,o++)if(y(j,i)){n=1;break}if(n==1)for(k=g._pack_prev;k!=j._pack_prev;k=k._pack_prev,p++)if(y(k,i)){p<o&&(n=-1,j=k);break}n==0?(w(g,i),h=i,l(i)):n>0?(x(g,j),h=j,m--):(x(j,h),g=j,m--)}}}var q=(b+c)/2,r=(d+e)/2,s=0;for(var m=0;m<f;m++){var t=a[m];t.x-=q,t.y-=r,s=Math.max(s,t.r+Math.sqrt(t.x*t.x+t.y*t.y))}a.forEach(B);return s}function y(a,b){var c=b.x-a.x,d=b.y-a.y,e=a.r+b.r;return e*e-c*c-d*d>.001}function x(a,b){a._pack_next=b,b._pack_prev=a}function w(a,b){var c=a._pack_next;a._pack_next=b,b._pack_prev=a,b._pack_next=c,c._pack_prev=b}function v(a,b){return a.value-b.value}function u(a,b){return b.value-a.value}function t(a){return a.value}function s(a){return a.children}function r(a){return d3.scale.linear().domain(a).ticks(10)}function q(a,b){var c=1,d=a.length-2;while(c<=d){var e=c+d>>1,f=a[e];if(f<b)c=e+1;else if(f>b)d=e-1;else return e}return c-1}function p(a,b){return a+b.y}function o(a){var b=1,c=0,d=a[0].y,e,f=a.length;for(;b<f;++b)(e=a[b].y)>d&&(c=b,d=e);return c}function n(a){return a.reduce(p,0)}function k(a){var b=0,c=0;a.count=0,a.leaf||a.nodes.forEach(function(d){k(d),a.count+=d.count,b+=d.count*d.cx,c+=d.count*d.cy}),a.point&&(a.leaf||(a.point.x+=Math.random()-.5,a.point.y+=Math.random()-.5),a.count++,b+=a.point.x,c+=a.point.y),a.cx=b/a.count,a.cy=c/a.count}function j(){d3.event.stopPropagation(),d3.event.preventDefault()}function i(){c&&(j(),c=!1)}function h(c,d){(a=c).fixed=!0,b=!1,e=this,j()}function g(b){b!==a&&(b.fixed=!1)}function f(a){a.fixed=!0}d3.layout={},d3.layout.chord=function(){function k(){b.sort(function(a,b){a=Math.min(a.source.value,a.target.value),b=Math.min(b.source.value,b.target.value);return i(a,b)})}function j(){var a={},j=[],l=d3.range(e),m=[],n,o,p,q,r;b=[],c=[],n=0,q=-1;while(++q<e){o=0,r=-1;while(++r<e)o+=d[q][r];j.push(o),m.push(d3.range(e)),n+=o}g&&l.sort(function(a,b){return g(j[a],j[b])}),h&&m.forEach(function(a,b){a.sort(function(a,c){return h(d[b][a],d[b][c])})}),n=(2*Math.PI-f*e)/n,o=0,q=-1;while(++q<e){p=o,r=-1;while(++r<e){var s=l[q],t=m[q][r],u=d[s][t];a[s+"-"+t]={index:s,subindex:t,startAngle:o,endAngle:o+=u*n,value:u}}c.push({index:s,startAngle:p,endAngle:o,value:(o-p)/n}),o+=f}q=-1;while(++q<e){r=q-1;while(++r<e){var v=a[q+"-"+r],w=a[r+"-"+q];(v.value||w.value)&&b.push({source:v,target:w})}}i&&k()}var a={},b,c,d,e,f=0,g,h,i;a.matrix=function(f){if(!arguments.length)return d;e=(d=f)&&d.length,b=c=null;return a},a.padding=function(d){if(!arguments.length)return f;f=d,b=c=null;return a},a.sortGroups=function(d){if(!arguments.length)return g;g=d,b=c=null;return a},a.sortSubgroups=function(c){if(!arguments.length)return h;h=c,b=null;return a},a.sortChords=function(c){if(!arguments.length)return i;i=c,b&&k();return a},a.chords=function(){b||j();return b},a.groups=function(){c||j();return c};return a},d3.layout.force=function(){function A(){!a||(b&&(c=!0,j()),z(),a.fixed=!1,a=e=null)}function z(){if(!!a){if(!e.parentNode){a.fixed=!1,a=e=null;return}var c=d3.svg.mouse(e);b=!0,a.px=c[0],a.py=c[1],d.resume()}}function y(){var a=u.length,b=v.length,c=d3.geom.quadtree(u),d,e,f,g,h,i,j;for(d=0;d<b;++d){e=v[d],f=e.source,g=e.target,i=g.x-f.x,j=g.y-f.y;if(h=i*i+j*j)h=n*((h=Math.sqrt(h))-p)/h,i*=h,j*=h,g.x-=i,g.y-=j,f.x+=i,f.y+=j}var s=n*r;i=m[0]/2,j=m[1]/2,d=-1;while(++d<a)e=u[d],e.x+=(i-e.x)*s,e.y+=(j-e.y)*s;k(c);var t=n*q;d=-1;while(++d<a)c.visit(x(u[d],t));d=-1;while(++d<a)e=u[d],e.fixed?(e.x=e.px,e.y=e.py):(e.x-=(e.px-(e.px=e.x))*o,e.y-=(e.py-(e.py=e.y))*o);l.tick.dispatch({type:"tick",alpha:n});return(n*=.99)<.005}function x(a,b){return function(c,d,e,f,g){if(c.point!==a){var h=c.cx-a.x,i=c.cy-a.y,j=1/Math.sqrt(h*h+i*i);if((f-d)*j<s){var k=b*c.count*j*j;a.x+=h*k,a.y+=i*k;return!0}if(c.point&&isFinite(j)){var k=b*j*j;a.x+=h*k,a.y+=i*k}}}}var d={},l=d3.dispatch("tick"),m=[1,1],n,o=.9,p=20,q=-30,r=.1,s=.8,t,u,v,w;d.on=function(a,b){l[a].add(b);return d},d.nodes=function(a){if(!arguments.length)return u;u=a;return d},d.links=function(a){if(!arguments.length)return v;v=a;return d},d.size=function(a){if(!arguments.length)return m;m=a;return d},d.distance=function(a){if(!arguments.length)return p;p=a;return d},d.drag=function(a){if(!arguments.length)return o;o=a;return d},d.charge=function(a){if(!arguments.length)return q;q=a;return d},d.gravity=function(a){if(!arguments.length)return r;r=a;return d},d.theta=function(a){if(!arguments.length)return s;s=a;return d},d.start=function(){function k(){if(!h){h=[];for(b=0;b<c;++b)h[b]=[];for(b=0;b<e;++b){var d=v[b];h[d.source.index].push(d.target),h[d.target.index].push(d.source)}}return h[a]}function j(b,c){var d=k(a),e=-1,f=d.length,g;while(++e<f)if(!isNaN(g=d[e][b]))return g;return Math.random()*c}var a,b,c=u.length,e=v.length,f=m[0],g=m[1],h,i;for(a=0;a<c;++a)(i=u[a]).index=a;for(a=0;a<e;++a)i=v[a],typeof i.source=="number"&&(i.source=u[i.source]),typeof i.target=="number"&&(i.target=u[i.target]);for(a=0;a<c;++a)i=u[a],isNaN(i.x)&&(i.x=j("x",f)),isNaN(i.y)&&(i.y=j("y",g)),isNaN(i.px)&&(i.px=i.x),isNaN(i.py)&&(i.py=i.y);return d.resume()},d.resume=function(){n=.1,d3.timer(y);return d},d.stop=function(){n=0;return d},d.drag=function(){this.on("mouseover.force",f).on("mouseout.force",g).on("mousedown.force",h),d3.select(window).on("mousemove.force",z).on("mouseup.force",A,!0).on("click.force",i,!0);return d};return d};var a,b,c,e;d3.layout.partition=function(){function e(e,f){var g=a.call(this,e,f);c(g[0],0,b[0],b[1]/d(g[0]));return g}function d(a){var b=a.children,c=0;if(b){var e=-1,f=b.length;while(++e<f)c=Math.max(c,d(b[e]))}return 1+c}function c(a,b,d,e){var f=a.children;a.x=b,a.y=a.depth*e,a.dx=d,a.dy=e;if(f){var g=-1,h=f.length,i,j;d/=a.value;while(++g<h)c(i=f[g],b,j=i.value*d,e),b+=j}}var a=d3.layout.hierarchy(),b=[1,1];e.sort=d3.rebind(e,a.sort),e.children=d3.rebind(e,a.children),e.value=d3.rebind(e,a.value),e.size=function(a){if(!arguments.length)return b;b=a;return e};return e},d3.layout.pie=function(){function f(f,g){var h=+(typeof c=="function"?c.apply(this,arguments):c),i=(typeof e=="function"?e.apply(this,arguments):e)-c,j=d3.range(f.length);b!=null&&j.sort(function(a,c){return b(f[a],f[c])});var k=f.map(a);i/=k.reduce(function(a,b){return a+b},0);var l=j.map(function(a){return{value:d=k[a],startAngle:h,endAngle:h+=d*i}});return f.map(function(a,b){return l[j[b]]})}var a=Number,b=null,c=0,e=2*Math.PI;f.value=function(b){if(!arguments.length)return a;a=b;return f},f.sort=function(a){if(!arguments.length)return b;b=a;return f},f.startAngle=function(a){if(!arguments.length)return c;c=a;return f},f.endAngle=function(a){if(!arguments.length)return e;e=a;return f};return f},d3.layout.stack=function(){function c(c){var d=c.length,e=c[0].length,f,g,h,i=l[a](c);m[b](c,i);for(g=0;g<e;++g)for(f=1,h=c[i[0]][g].y0;f<d;++f)c[i[f]][g].y0=h+=c[i[f-1]][g].y;return c}var a="default",b="zero";c.order=function(b){if(!arguments.length)return a;a=b;return c},c.offset=function(a){if(!arguments.length)return b;b=a;return c};return c};var l={"inside-out":function(a){var b=a.length,c,d,e=a.map(o),f=a.map(n),g=d3.range(b).sort(function(a,b){return e[a]-e[b]}),h=0,i=0,j=[],k=[];for(c=0;c<b;c++)d=g[c],h<i?(h+=f[d],j.push(d)):(i+=f[d],k.push(d));return k.reverse().concat(j)},reverse:function(a){return d3.range(a.length).reverse()},"default":function(a){return d3.range(a.length)}},m={silhouette:function(a,b){var c=a.length,d=a[0].length,e=[],f=0,g,h,i;for(h=0;h<d;++h){for(g=0,i=0;g<c;g++)i+=a[g][h].y;i>f&&(f=i),e.push(i)}for(h=0,g=b[0];h<d;++h)a[g][h].y0=(f-e[h])/2},wiggle:function(a,b){var c=a.length,d=a[0],e=d.length,f=0,g,h,i,j,k,l=b[0],m,n,o,p,q,r;a[l][0].y0=q=r=0;for(h=1;h<e;++h){for(g=0,m=0;g<c;++g)m+=a[g][h].y;for(g=0,n=0,p=d[h].x-d[h-1].x;g<c;++g){for(i=0,j=b[g],o=(a[j][h].y-a[j][h-1].y)/(2*p);i<g;++i)o+=(a[k=b[i]][h].y-a[k][h-1].y)/p;n+=o*a[j][h].y}a[l][h].y0=q-=m?n/m*p:0,q<r&&(r=q)}for(h=0;h<e;++h)a[l][h].y0-=r},zero:function(a,b){var c=0,d=a[0].length,e=b[0];for(;c<d;++c)a[e][c].y0=0}};d3.layout.histogram=function(){function d(d,e){var f=d.map(b),g=[],h=c.call(this,d,e);for(var e=0;e<h.length-1;e++){var i=g[e]=[];i.x=h[e],i.dx=h[e+1]-h[e],i.y=0}for(var e=0;e<f.length;e++){var i=g[q(h,f[e])];i.y++,i.push(d[e])}if(!a)for(var e=0;e<g.length;e++)g[e].y/=f.length;return g}var a=!0,b=Number,c=r;d.frequency=function(b){if(!arguments.length)return a;a=Boolean(b);return d},d.ticks=function(a){if(!arguments.length)return c;c=d3.functor(a);return d},d.value=function(a){if(!arguments.length)return b;b=a;return d};return d},d3.layout.hierarchy=function(){function g(a){var b=[];e(a,0,b);return b}function f(a,b){var d=a.children,e=0;if(d){var h=-1,i=d.length,j=b+1;while(++h<i)e+=f(d[h],j)}else c&&(e=c.call(g,a.data,b));c&&(a.value=e);return e}function e(f,h,i){var j=b.call(g,f,h),k={depth:h,data:f};i.push(k);if(j){var l=-1,m=j.length,n=k.children=[],o=0,p=h+1;while(++l<m)d=e(j[l],p,i),d.parent=k,n.push(d),o+=d.value;a&&n.sort(a),c&&(k.value=o)}else c&&(k.value=c.call(g,f,h));return k}var a=u,b=s,c=t;g.sort=function(b){if(!arguments.length)return a;a=b;return g},g.children=function(a){if(!arguments.length)return b;b=a;return g},g.value=function(a){if(!arguments.length)return c;c=a;return g},g.revalue=function(a){f(a,0);return a};return g},d3.layout.pack=function(){function c(c,d){var e=a.call(this,c,d),f=e[0];f.x=0,f.y=0,C(f);var g=b[0],h=b[1],i=1/Math.max(2*f.r/g,2*f.r/h);D(f,g/2,h/2,i);return e}var a=d3.layout.hierarchy(),b=[1,1];c.sort=d3.rebind(c,a.sort),c.children=d3.rebind(c,a.children),c.value=d3.rebind(c,a.value),c.size=function(a){if(!arguments.length)return b;b=a;return c};return c.sort(v)},d3.layout.cluster=function(){function d(d,e){var f=a.call(this,d,e),g=f[0],h,i=0,j,k;R(g,function(a){a.children?(a.x=G(a.children),a.y=F(a.children)):(a.x=h?i+=b(a,h):0,a.y=0,h=a)});var l=H(g),m=I(g),n=l.x-b(l,m)/2,o=m.x+b(m,l)/2;R(g,function(a){a.x=(a.x-n)/(o-n)*c[0],a.y=(1-a.y/g.y)*c[1]});return f}var a=d3.layout.hierarchy().sort(null).value(null),b=K,c=[1,1];d.sort=d3.rebind(d,a.sort),d.children=d3.rebind(d,a.children),d.links=J,d.separation=function(a){if(!arguments.length)return b;b=a;return d},d.size=function(a){if(!arguments.length)return c;c=a;return d};return d},d3.layout.tree=function(){function d(d,e){function j(a,c,d){if(c){var e=a,f=a,g=c,h=a.parent.children[0],i=e._tree.mod,j=f._tree.mod,k=g._tree.mod,l=h._tree.mod,m;while(g=M(g),e=L(e),g&&e)h=L(h),f=M(f),f._tree.ancestor=a,m=g._tree.prelim+k-e._tree.prelim-i+b(g,e),m>0&&(T(U(g,a,d),a,m),i+=m,j+=m),k+=g._tree.mod,i+=e._tree.mod,l+=h._tree.mod,j+=f._tree.mod;g&&!M(f)&&(f._tree.thread=g,f._tree.mod+=k-j),e&&!L(h)&&(h._tree.thread=e,h._tree.mod+=i-l,d=a)}return d}function i(a,b){a.x=a._tree.prelim+b;var c=a.children;if(c){var d=-1,e=c.length;b+=a._tree.mod;while(++d<e)i(c[d],b)}}function h(a,c){var d=a.children,e=a._tree;if(d){var f=d.length,g=d[0],i,k=g,l,m=-1;while(++m<f)l=d[m],h(l,i),k=j(l,i,k),i=l;S(a);var n=.5*(g._tree.prelim+l._tree.prelim);c?(e.prelim=c._tree.prelim+b(a,c),e.mod=e.prelim-n):e.prelim=n}else c&&(e.prelim=c._tree.prelim+b(a,c))}var f=a.call(this,d,e),g=f[0];R(g,function(a,b){a._tree={ancestor:a,prelim:0,mod:0,change:0,shift:0,number:b?b._tree.number+1:0}}),h(g),i(g,-g._tree.prelim);var k=N(g,P),l=N(g,O),m=N(g,Q),n=k.x-b(k,l)/2,o=l.x+b(l,k)/2,p=m.depth;R(g,function(a){a.x=(a.x-n)/(o-n)*c[0],a.y=a.depth/p*c[1],delete a._tree});return f}var a=d3.layout.hierarchy().sort(null).value(null),b=K,c=[1,1];d.sort=d3.rebind(d,a.sort),d.children=d3.rebind(d,a.children),d.links=J,d.separation=function(a){if(!arguments.length)return b;b=a;return d},d.size=function(a){if(!arguments.length)return c;c=a;return d};return d},d3.layout.treemap=function(){function k(b){var i=e||a(b),j=i[0];j.x=0,j.y=0,j.dx=c[0],j.dy=c[1],e&&a.revalue(j),f(j,c[0]*c[1]/j.value),(e?h:g)(j),d&&(e=i);return i}function j(a,c,d,e){var f=-1,g=a.length,h=d.x,i=d.y,j=c?b(a.area/c):0,k;if(c==d.dx){if(e||j>d.dy)j=d.dy;while(++f<g)k=a[f],k.x=h,k.y=i,k.dy=j,h+=k.dx=b(k.area/j);k.z=!0,k.dx+=d.x+d.dx-h,d.y+=j,d.dy-=j}else{if(e||j>d.dx)j=d.dx;while(++f<g)k=a[f],k.x=h,k.y=i,k.dx=j,i+=k.dy=b(k.area/j);k.z=!1,k.dy+=d.y+d.dy-i,d.x+=j,d.dx-=j}}function i(a,b){var c=a.area,d,e=0,f=Infinity,g=-1,h=a.length;while(++g<h)d=a[g].area,d<f&&(f=d),d>e&&(e=d);c*=c,b*=b;return Math.max(b*e/c,c/(b*f))}function h(a){if(!!a.children){var b={x:a.x,y:a.y,dx:a.dx,dy:a.dy},c=a.children.slice(),d,e=[];e.area=0;while(d=c.pop())e.push(d),e.area+=d.area,d.z!=null&&(j(e,d.z?b.dx:b.dy,b,!c.length),e.length=e.area=0);a.children.forEach(h)}}function g(a){if(!!a.children){var b={x:a.x,y:a.y,dx:a.dx,dy:a.dy},c=[],d=a.children.slice(),e,f=Infinity,h,k=Math.min(b.dx,b.dy),l;c.area=0;while((l=d.length)>0)c.push(e=d[l-1]),c.area+=e.area,(h=i(c,k))<=f?(d.pop(),f=h):(c.area-=c.pop().area,j(c,k,b,!1),k=Math.min(b.dx,b.dy),c.length=c.area=0,f=Infinity);c.length&&(j(c,k,b,!0),c.length=c.area=0),a.children.forEach(g)}}function f(a,b){var c=a.children;a.area=a.value*b;if(c){var d=-1,e=c.length;while(++d<e)f(c[d],b)}}var a=d3.layout.hierarchy(),b=Math.round,c=[1,1],d=!1,e;k.sort=d3.rebind(k,a.sort),k.children=d3.rebind(k,a.children),k.value=d3.rebind(k,a.value),k.size=function(a){if(!arguments.length)return c;c=a;return k},k.round=function(a){if(!arguments.length)return b!=Number;b=a?Math.round:Number;return k},k.sticky=function(a){if(!arguments.length)return d;d=a,e=null;return k};return k}})() <ide>\ No newline at end of file <ide><path>src/layout/histogram.js <ide> d3.layout.histogram = function() { <ide> <ide> // Count the number of samples per bin. <ide> for (var i = 0; i < x.length; i++) { <del> var j = d3_layout_histogramSearchIndex(ticks, x[i]) - 1, <del> bin = bins[Math.max(0, Math.min(bins.length - 1, j))]; <add> var bin = bins[d3_layout_histogramSearch(ticks, x[i])]; <ide> bin.y++; <ide> bin.push(data[i]); <ide> } <ide> d3.layout.histogram = function() { <ide> }; <ide> <ide> // Performs a binary search on a sorted array. <del>// Returns the index of the value if found, otherwise -(insertion point) - 1. <del>// The insertion point is the index at which value should be inserted into the <del>// array for the array to remain sorted. <ide> function d3_layout_histogramSearch(array, value) { <del> var low = 0, high = array.length - 1; <add> var low = 1, high = array.length - 2; <ide> while (low <= high) { <ide> var mid = (low + high) >> 1, midValue = array[mid]; <ide> if (midValue < value) low = mid + 1; <ide> else if (midValue > value) high = mid - 1; <ide> else return mid; <ide> } <del> return -low - 1; <del>} <del> <del>function d3_layout_histogramSearchIndex(array, value) { <del> var i = d3_layout_histogramSearch(array, value); <del> return (i < 0) ? (-i - 1) : i; <add> return low - 1; <ide> } <ide> <ide> function d3_layout_histogramTicks(x) {
3
Javascript
Javascript
move v8_bench into misc
844b33205c77fe32d2aae76209eb444044b9aeff
<add><path>benchmark/misc/v8_bench.js <del><path>benchmark/v8_bench.js <ide> var fs = require('fs'); <ide> var path = require('path'); <ide> var vm = require('vm'); <ide> <del>var dir = path.join(__dirname, '..', 'deps', 'v8', 'benchmarks'); <add>var dir = path.join(__dirname, '..', '..', 'deps', 'v8', 'benchmarks'); <ide> <del>global.print = console.log; <add>global.print = function(s) { <add> if (s === '----') return; <add> console.log('misc/v8_bench.js %s', s); <add>}; <ide> <ide> global.load = function (x) { <ide> var source = fs.readFileSync(path.join(dir, x), 'utf8');
1
Ruby
Ruby
show lazy middleware args in pretty print
e0660192806fc1ec8b75654e69211f85c9f1256b
<ide><path>actionpack/lib/action_dispatch/middleware/stack.rb <ide> def ==(middleware) <ide> <ide> def inspect <ide> str = klass.to_s <del> args.each { |arg| str += ", #{arg.inspect}" } <add> args.each { |arg| str += ", #{build_args.inspect}" } <ide> str <ide> end <ide> <ide> def build(app) <ide> end <ide> <ide> private <del> <ide> def build_args <ide> Array(args).map { |arg| arg.respond_to?(:call) ? arg.call : arg } <ide> end
1
Javascript
Javascript
add rfc references for each status code
9594b54f966c90c5c0270490a8b750e437a3cddb
<ide><path>lib/_http_server.js <ide> const kServerResponse = Symbol('ServerResponse'); <ide> const kServerResponseStatistics = Symbol('ServerResponseStatistics'); <ide> <ide> const STATUS_CODES = { <del> 100: 'Continue', <del> 101: 'Switching Protocols', <del> 102: 'Processing', // RFC 2518, obsoleted by RFC 4918 <del> 103: 'Early Hints', <del> 200: 'OK', <del> 201: 'Created', <del> 202: 'Accepted', <del> 203: 'Non-Authoritative Information', <del> 204: 'No Content', <del> 205: 'Reset Content', <del> 206: 'Partial Content', <del> 207: 'Multi-Status', // RFC 4918 <del> 208: 'Already Reported', <del> 226: 'IM Used', <del> 300: 'Multiple Choices', // RFC 7231 <del> 301: 'Moved Permanently', <del> 302: 'Found', <del> 303: 'See Other', <del> 304: 'Not Modified', <del> 305: 'Use Proxy', <del> 307: 'Temporary Redirect', <del> 308: 'Permanent Redirect', // RFC 7238 <del> 400: 'Bad Request', <del> 401: 'Unauthorized', <del> 402: 'Payment Required', <del> 403: 'Forbidden', <del> 404: 'Not Found', <del> 405: 'Method Not Allowed', <del> 406: 'Not Acceptable', <del> 407: 'Proxy Authentication Required', <del> 408: 'Request Timeout', <del> 409: 'Conflict', <del> 410: 'Gone', <del> 411: 'Length Required', <del> 412: 'Precondition Failed', <del> 413: 'Payload Too Large', <del> 414: 'URI Too Long', <del> 415: 'Unsupported Media Type', <del> 416: 'Range Not Satisfiable', <del> 417: 'Expectation Failed', <del> 418: 'I\'m a Teapot', // RFC 7168 <del> 421: 'Misdirected Request', <del> 422: 'Unprocessable Entity', // RFC 4918 <del> 423: 'Locked', // RFC 4918 <del> 424: 'Failed Dependency', // RFC 4918 <del> 425: 'Too Early', // RFC 8470 <del> 426: 'Upgrade Required', // RFC 2817 <del> 428: 'Precondition Required', // RFC 6585 <del> 429: 'Too Many Requests', // RFC 6585 <del> 431: 'Request Header Fields Too Large', // RFC 6585 <del> 451: 'Unavailable For Legal Reasons', <del> 500: 'Internal Server Error', <del> 501: 'Not Implemented', <del> 502: 'Bad Gateway', <del> 503: 'Service Unavailable', <del> 504: 'Gateway Timeout', <del> 505: 'HTTP Version Not Supported', <del> 506: 'Variant Also Negotiates', // RFC 2295 <del> 507: 'Insufficient Storage', // RFC 4918 <del> 508: 'Loop Detected', <add> 100: 'Continue', // RFC 7231 6.2.1 <add> 101: 'Switching Protocols', // RFC 7231 6.2.2 <add> 102: 'Processing', // RFC 2518 10.1 (obsoleted by RFC 4918) <add> 103: 'Early Hints', // RFC 8297 2 <add> 200: 'OK', // RFC 7231 6.3.1 <add> 201: 'Created', // RFC 7231 6.3.2 <add> 202: 'Accepted', // RFC 7231 6.3.3 <add> 203: 'Non-Authoritative Information', // RFC 7231 6.3.4 <add> 204: 'No Content', // RFC 7231 6.3.5 <add> 205: 'Reset Content', // RFC 7231 6.3.6 <add> 206: 'Partial Content', // RFC 7233 4.1 <add> 207: 'Multi-Status', // RFC 4918 11.1 <add> 208: 'Already Reported', // RFC 5842 7.1 <add> 226: 'IM Used', // RFC 3229 10.4.1 <add> 300: 'Multiple Choices', // RFC 7231 6.4.1 <add> 301: 'Moved Permanently', // RFC 7231 6.4.2 <add> 302: 'Found', // RFC 7231 6.4.3 <add> 303: 'See Other', // RFC 7231 6.4.4 <add> 304: 'Not Modified', // RFC 7232 4.1 <add> 305: 'Use Proxy', // RFC 7231 6.4.5 <add> 307: 'Temporary Redirect', // RFC 7231 6.4.7 <add> 308: 'Permanent Redirect', // RFC 7238 3 <add> 400: 'Bad Request', // RFC 7231 6.5.1 <add> 401: 'Unauthorized', // RFC 7235 3.1 <add> 402: 'Payment Required', // RFC 7231 6.5.2 <add> 403: 'Forbidden', // RFC 7231 6.5.3 <add> 404: 'Not Found', // RFC 7231 6.5.4 <add> 405: 'Method Not Allowed', // RFC 7231 6.5.5 <add> 406: 'Not Acceptable', // RFC 7231 6.5.6 <add> 407: 'Proxy Authentication Required', // RFC 7235 3.2 <add> 408: 'Request Timeout', // RFC 7231 6.5.7 <add> 409: 'Conflict', // RFC 7231 6.5.8 <add> 410: 'Gone', // RFC 7231 6.5.9 <add> 411: 'Length Required', // RFC 7231 6.5.10 <add> 412: 'Precondition Failed', // RFC 7232 4.2 <add> 413: 'Payload Too Large', // RFC 7231 6.5.11 <add> 414: 'URI Too Long', // RFC 7231 6.5.12 <add> 415: 'Unsupported Media Type', // RFC 7231 6.5.13 <add> 416: 'Range Not Satisfiable', // RFC 7233 4.4 <add> 417: 'Expectation Failed', // RFC 7231 6.5.14 <add> 418: 'I\'m a Teapot', // RFC 7168 2.3.3 <add> 421: 'Misdirected Request', // RFC 7540 9.1.2 <add> 422: 'Unprocessable Entity', // RFC 4918 11.2 <add> 423: 'Locked', // RFC 4918 11.3 <add> 424: 'Failed Dependency', // RFC 4918 11.4 <add> 425: 'Too Early', // RFC 8470 5.2 <add> 426: 'Upgrade Required', // RFC 2817 and RFC 7231 6.5.15 <add> 428: 'Precondition Required', // RFC 6585 3 <add> 429: 'Too Many Requests', // RFC 6585 4 <add> 431: 'Request Header Fields Too Large', // RFC 6585 5 <add> 451: 'Unavailable For Legal Reasons', // RFC 7725 3 <add> 500: 'Internal Server Error', // RFC 7231 6.6.1 <add> 501: 'Not Implemented', // RFC 7231 6.6.2 <add> 502: 'Bad Gateway', // RFC 7231 6.6.3 <add> 503: 'Service Unavailable', // RFC 7231 6.6.4 <add> 504: 'Gateway Timeout', // RFC 7231 6.6.5 <add> 505: 'HTTP Version Not Supported', // RFC 7231 6.6.6 <add> 506: 'Variant Also Negotiates', // RFC 2295 8.1 <add> 507: 'Insufficient Storage', // RFC 4918 11.5 <add> 508: 'Loop Detected', // RFC 5842 7.2 <ide> 509: 'Bandwidth Limit Exceeded', <del> 510: 'Not Extended', // RFC 2774 <del> 511: 'Network Authentication Required' // RFC 6585 <add> 510: 'Not Extended', // RFC 2774 7 <add> 511: 'Network Authentication Required' // RFC 6585 6 <ide> }; <ide> <ide> const kOnExecute = HTTPParser.kOnExecute | 0;
1
Go
Go
add coverage on pkg/fileutils
8454e1a3b24e2e076bb08a2a6b1fcb56efe2924e
<ide><path>pkg/fileutils/fileutils.go <ide> func OptimizedMatches(file string, patterns []string, patDirs [][]string) (bool, <ide> } <ide> <ide> func CopyFile(src, dst string) (int64, error) { <del> if src == dst { <add> cleanSrc := filepath.Clean(src) <add> cleanDst := filepath.Clean(dst) <add> if cleanSrc == cleanDst { <ide> return 0, nil <ide> } <del> sf, err := os.Open(src) <add> sf, err := os.Open(cleanSrc) <ide> if err != nil { <ide> return 0, err <ide> } <ide> defer sf.Close() <del> if err := os.Remove(dst); err != nil && !os.IsNotExist(err) { <add> if err := os.Remove(cleanDst); err != nil && !os.IsNotExist(err) { <ide> return 0, err <ide> } <del> df, err := os.Create(dst) <add> df, err := os.Create(cleanDst) <ide> if err != nil { <ide> return 0, err <ide> } <ide><path>pkg/fileutils/fileutils_test.go <ide> package fileutils <ide> <ide> import ( <add> "io/ioutil" <ide> "os" <add> "path" <ide> "testing" <ide> ) <ide> <add>// CopyFile with invalid src <add>func TestCopyFileWithInvalidSrc(t *testing.T) { <add> tempFolder, err := ioutil.TempDir("", "docker-fileutils-test") <add> defer os.RemoveAll(tempFolder) <add> if err != nil { <add> t.Fatal(err) <add> } <add> bytes, err := CopyFile("/invalid/file/path", path.Join(tempFolder, "dest")) <add> if err == nil { <add> t.Fatal("Should have fail to copy an invalid src file") <add> } <add> if bytes != 0 { <add> t.Fatal("Should have written 0 bytes") <add> } <add> <add>} <add> <add>// CopyFile with invalid dest <add>func TestCopyFileWithInvalidDest(t *testing.T) { <add> tempFolder, err := ioutil.TempDir("", "docker-fileutils-test") <add> defer os.RemoveAll(tempFolder) <add> if err != nil { <add> t.Fatal(err) <add> } <add> src := path.Join(tempFolder, "file") <add> err = ioutil.WriteFile(src, []byte("content"), 0740) <add> if err != nil { <add> t.Fatal(err) <add> } <add> bytes, err := CopyFile(src, path.Join(tempFolder, "/invalid/dest/path")) <add> if err == nil { <add> t.Fatal("Should have fail to copy an invalid src file") <add> } <add> if bytes != 0 { <add> t.Fatal("Should have written 0 bytes") <add> } <add> <add>} <add> <add>// CopyFile with same src and dest <add>func TestCopyFileWithSameSrcAndDest(t *testing.T) { <add> tempFolder, err := ioutil.TempDir("", "docker-fileutils-test") <add> defer os.RemoveAll(tempFolder) <add> if err != nil { <add> t.Fatal(err) <add> } <add> file := path.Join(tempFolder, "file") <add> err = ioutil.WriteFile(file, []byte("content"), 0740) <add> if err != nil { <add> t.Fatal(err) <add> } <add> bytes, err := CopyFile(file, file) <add> if err != nil { <add> t.Fatal(err) <add> } <add> if bytes != 0 { <add> t.Fatal("Should have written 0 bytes as it is the same file.") <add> } <add>} <add> <add>// CopyFile with same src and dest but path is different and not clean <add>func TestCopyFileWithSameSrcAndDestWithPathNameDifferent(t *testing.T) { <add> tempFolder, err := ioutil.TempDir("", "docker-fileutils-test") <add> defer os.RemoveAll(tempFolder) <add> if err != nil { <add> t.Fatal(err) <add> } <add> testFolder := path.Join(tempFolder, "test") <add> err = os.MkdirAll(testFolder, 0740) <add> if err != nil { <add> t.Fatal(err) <add> } <add> file := path.Join(testFolder, "file") <add> sameFile := testFolder + "/../test/file" <add> err = ioutil.WriteFile(file, []byte("content"), 0740) <add> if err != nil { <add> t.Fatal(err) <add> } <add> bytes, err := CopyFile(file, sameFile) <add> if err != nil { <add> t.Fatal(err) <add> } <add> if bytes != 0 { <add> t.Fatal("Should have written 0 bytes as it is the same file.") <add> } <add>} <add> <add>func TestCopyFile(t *testing.T) { <add> tempFolder, err := ioutil.TempDir("", "docker-fileutils-test") <add> defer os.RemoveAll(tempFolder) <add> if err != nil { <add> t.Fatal(err) <add> } <add> src := path.Join(tempFolder, "src") <add> dest := path.Join(tempFolder, "dest") <add> ioutil.WriteFile(src, []byte("content"), 0777) <add> ioutil.WriteFile(dest, []byte("destContent"), 0777) <add> bytes, err := CopyFile(src, dest) <add> if err != nil { <add> t.Fatal(err) <add> } <add> if bytes != 7 { <add> t.Fatalf("Should have written %d bytes but wrote %d", 7, bytes) <add> } <add> actual, err := ioutil.ReadFile(dest) <add> if err != nil { <add> t.Fatal(err) <add> } <add> if string(actual) != "content" { <add> t.Fatalf("Dest content was '%s', expected '%s'", string(actual), "content") <add> } <add>} <add> <ide> // Reading a symlink to a directory must return the directory <ide> func TestReadSymlinkedDirectoryExistingDirectory(t *testing.T) { <ide> var err error <ide> func TestExclusion(t *testing.T) { <ide> } <ide> } <ide> <add>// Matches with no patterns <add>func TestMatchesWithNoPatterns(t *testing.T) { <add> matches, err := Matches("/any/path/there", []string{}) <add> if err != nil { <add> t.Fatal(err) <add> } <add> if matches { <add> t.Fatalf("Should not have match anything") <add> } <add>} <add> <add>// Matches with malformed patterns <add>func TestMatchesWithMalformedPatterns(t *testing.T) { <add> matches, err := Matches("/any/path/there", []string{"["}) <add> if err == nil { <add> t.Fatal("Should have failed because of a malformed syntax in the pattern") <add> } <add> if matches { <add> t.Fatalf("Should not have match anything") <add> } <add>} <add> <ide> // An empty string should return true from Empty. <ide> func TestEmpty(t *testing.T) { <ide> empty := Empty("")
2
Python
Python
convert snake_case to camelcase or pascalcase
6118b05f0efd1c2839eb8bc4de36723af1fcc364
<ide><path>strings/snake_case_to_camel_pascal_case.py <add>def snake_to_camel_case(input: str, use_pascal: bool = False) -> str: <add> """ <add> Transforms a snake_case given string to camelCase (or PascalCase if indicated) <add> (defaults to not use Pascal) <add> <add> >>> snake_to_camel_case("some_random_string") <add> 'someRandomString' <add> <add> >>> snake_to_camel_case("some_random_string", use_pascal=True) <add> 'SomeRandomString' <add> <add> >>> snake_to_camel_case("some_random_string_with_numbers_123") <add> 'someRandomStringWithNumbers123' <add> <add> >>> snake_to_camel_case("some_random_string_with_numbers_123", use_pascal=True) <add> 'SomeRandomStringWithNumbers123' <add> <add> >>> snake_to_camel_case(123) <add> Traceback (most recent call last): <add> ... <add> ValueError: Expected string as input, found <class 'int'> <add> <add> >>> snake_to_camel_case("some_string", use_pascal="True") <add> Traceback (most recent call last): <add> ... <add> ValueError: Expected boolean as use_pascal parameter, found <class 'str'> <add> """ <add> <add> if not isinstance(input, str): <add> raise ValueError(f"Expected string as input, found {type(input)}") <add> if not isinstance(use_pascal, bool): <add> raise ValueError( <add> f"Expected boolean as use_pascal parameter, found {type(use_pascal)}" <add> ) <add> <add> words = input.split("_") <add> <add> start_index = 0 if use_pascal else 1 <add> <add> words_to_capitalize = words[start_index:] <add> <add> capitalized_words = [word[0].upper() + word[1:] for word in words_to_capitalize] <add> <add> initial_word = "" if use_pascal else words[0] <add> <add> return "".join([initial_word] + capitalized_words) <add> <add> <add>if __name__ == "__main__": <add> from doctest import testmod <add> <add> testmod()
1
PHP
PHP
add test checking that tests map to .. tests
27fa6a8cdda3c390863e7bcff53a1cd62be332a4
<ide><path>lib/Cake/Test/Case/Console/Command/TestShellTest.php <ide> public function testMapPluginFileToCase() { <ide> $this->assertSame('Controller/ExampleController', $return); <ide> } <ide> <add>/** <add> * testMapCoreTestToCategory <add> * <add> * @return void <add> */ <add> public function testMapCoreTestToCategory() { <add> $this->Shell->startup(); <add> <add> $return = $this->Shell->mapFileToCategory('lib/Cake/Test/Case/BasicsTest.php'); <add> $this->assertSame('core', $return); <add> <add> $return = $this->Shell->mapFileToCategory('lib/Cake/Test/Case/BasicsTest.php'); <add> $this->assertSame('core', $return); <add> <add> $return = $this->Shell->mapFileToCategory('lib/Cake/Test/Case/Some/Deeply/Nested/StructureTest.php'); <add> $this->assertSame('core', $return); <add> } <add> <add>/** <add> * testMapCoreTestToCase <add> * <add> * basics.php is a slightly special case - it's the only file in the core with a test that isn't Capitalized <add> * <add> * @return void <add> */ <add> public function testMapCoreTestToCase() { <add> $this->Shell->startup(); <add> <add> $return = $this->Shell->mapFileToCase('lib/Cake/Test/Case/BasicsTest.php', 'core'); <add> $this->assertSame('Basics', $return); <add> <add> $return = $this->Shell->mapFileToCase('lib/Cake/Test/Case/Core/AppTest.php', 'core'); <add> $this->assertSame('Core/App', $return); <add> <add> $return = $this->Shell->mapFileToCase('lib/Cake/Test/Case/Some/Deeply/Nested/StructureTest.php', 'core', false); <add> $this->assertSame('Some/Deeply/Nested/Structure', $return); <add> } <add> <add>/** <add> * testMapAppTestToCategory <add> * <add> * @return void <add> */ <add> public function testMapAppTestToCategory() { <add> $this->Shell->startup(); <add> <add> $return = $this->Shell->mapFileToCategory(APP . 'Test/Case/Controller/ExampleControllerTest.php'); <add> $this->assertSame('app', $return); <add> <add> $return = $this->Shell->mapFileToCategory(APP . 'Test/Case/My/File/Is/HereTest.php'); <add> $this->assertSame('app', $return); <add> <add> } <add> <add>/** <add> * testMapAppTestToCase <add> * <add> * @return void <add> */ <add> public function testMapAppTestToCase() { <add> $this->Shell->startup(); <add> <add> $return = $this->Shell->mapFileToCase(APP . 'Test/Case/Controller/ExampleControllerTest.php', 'app', false); <add> $this->assertSame('Controller/ExampleController', $return); <add> <add> $return = $this->Shell->mapFileToCase(APP . 'Test/Case/My/File/Is/HereTest.php', 'app', false); <add> $this->assertSame('My/File/Is/Here', $return); <add> } <add> <add>/** <add> * testMapPluginTestToCategory <add> * <add> * @return void <add> */ <add> public function testMapPluginTestToCategory() { <add> $this->Shell->startup(); <add> <add> $return = $this->Shell->mapFileToCategory(APP . 'Plugin/awesome/Test/Case/Controller/ExampleControllerTest.php'); <add> $this->assertSame('awesome', $return); <add> <add> $return = $this->Shell->mapFileToCategory(dirname(CAKE) . 'plugins/awesome/Test/Case/Controller/ExampleControllerTest.php'); <add> $this->assertSame('awesome', $return); <add> <add> } <add> <add>/** <add> * testMapPluginTestToCase <add> * <add> * @return void <add> */ <add> public function testMapPluginTestToCase() { <add> $this->Shell->startup(); <add> <add> $return = $this->Shell->mapFileToCase(APP . 'Plugin/awesome/Test/Case/Controller/ExampleControllerTest.php', 'awesome', false); <add> $this->assertSame('Controller/ExampleController', $return); <add> <add> $return = $this->Shell->mapFileToCase(dirname(CAKE) . 'plugins/awesome/Test/Case/Controller/ExampleControllerTest.php', 'awesome', false); <add> $this->assertSame('Controller/ExampleController', $return); <add> } <add> <ide> /** <ide> * test available list of test cases for an empty category <ide> *
1
Go
Go
use selinux labels for volumes
b2a43baf2e2cc68c83383a7524441f81bc4c4725
<ide><path>daemon/container.go <ide> func copyEscapable(dst io.Writer, src io.ReadCloser) (written int64, err error) <ide> func (container *Container) networkMounts() []execdriver.Mount { <ide> var mounts []execdriver.Mount <ide> if container.ResolvConfPath != "" { <add> label.SetFileLabel(container.ResolvConfPath, container.MountLabel) <ide> mounts = append(mounts, execdriver.Mount{ <ide> Source: container.ResolvConfPath, <ide> Destination: "/etc/resolv.conf", <ide> func (container *Container) networkMounts() []execdriver.Mount { <ide> }) <ide> } <ide> if container.HostnamePath != "" { <add> label.SetFileLabel(container.HostnamePath, container.MountLabel) <ide> mounts = append(mounts, execdriver.Mount{ <ide> Source: container.HostnamePath, <ide> Destination: "/etc/hostname", <ide> func (container *Container) networkMounts() []execdriver.Mount { <ide> }) <ide> } <ide> if container.HostsPath != "" { <add> label.SetFileLabel(container.HostsPath, container.MountLabel) <ide> mounts = append(mounts, execdriver.Mount{ <ide> Source: container.HostsPath, <ide> Destination: "/etc/hosts", <ide><path>daemon/create.go <ide> func (daemon *Daemon) Create(config *runconfig.Config, hostConfig *runconfig.Hos <ide> if err != nil { <ide> return nil, nil, err <ide> } <add> if err := label.Relabel(v.Path(), container.MountLabel, "z"); err != nil { <add> return nil, nil, err <add> } <ide> <ide> if err := container.copyImagePathContent(v, destination); err != nil { <ide> return nil, nil, err <ide><path>daemon/daemon.go <ide> func (daemon *Daemon) verifyHostConfig(hostConfig *runconfig.HostConfig) ([]stri <ide> } <ide> <ide> func (daemon *Daemon) setHostConfig(container *Container, hostConfig *runconfig.HostConfig) error { <del> if err := daemon.registerMountPoints(container, hostConfig); err != nil { <add> container.Lock() <add> if err := parseSecurityOpt(container, hostConfig); err != nil { <add> container.Unlock() <ide> return err <ide> } <add> container.Unlock() <ide> <del> container.Lock() <del> defer container.Unlock() <del> if err := parseSecurityOpt(container, hostConfig); err != nil { <add> // Do not lock while creating volumes since this could be calling out to external plugins <add> // Don't want to block other actions, like `docker ps` because we're waiting on an external plugin <add> if err := daemon.registerMountPoints(container, hostConfig); err != nil { <ide> return err <ide> } <ide> <add> container.Lock() <add> defer container.Unlock() <ide> // Register any links from the host config before starting the container <ide> if err := daemon.RegisterLinks(container, hostConfig); err != nil { <ide> return err <ide><path>daemon/volumes.go <ide> import ( <ide> "io/ioutil" <ide> "os" <ide> "path/filepath" <del> "runtime" <ide> "strings" <ide> <del> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/pkg/chrootarchive" <ide> "github.com/docker/docker/runconfig" <ide> "github.com/docker/docker/volume" <ide> type mountPoint struct { <ide> RW bool <ide> Volume volume.Volume `json:"-"` <ide> Source string <add> Relabel string <ide> } <ide> <ide> func (m *mountPoint) Setup() (string, error) { <ide> func parseBindMount(spec string, mountLabel string, config *runconfig.Config) (* <ide> return nil, fmt.Errorf("invalid mode for volumes-from: %s", mode) <ide> } <ide> bind.RW = rwModes[mode] <del> // check if we need to apply a SELinux label <del> if strings.ContainsAny(mode, "zZ") { <del> if err := label.Relabel(bind.Source, mountLabel, mode); err != nil { <del> return nil, err <del> } <del> } <add> // Relabel will apply a SELinux label, if necessary <add> bind.Relabel = mode <ide> default: <ide> return nil, fmt.Errorf("Invalid volume specification: %s", spec) <ide> } <ide> func (daemon *Daemon) registerMountPoints(container *Container, hostConfig *runc <ide> } <ide> } <ide> <del> // lock for labels <del> runtime.LockOSThread() <del> defer runtime.UnlockOSThread() <ide> // 3. Read bind mounts <ide> for _, b := range hostConfig.Binds { <ide> // #10618 <ide> func (daemon *Daemon) registerMountPoints(container *Container, hostConfig *runc <ide> } <ide> <ide> if len(bind.Name) > 0 && len(bind.Driver) > 0 { <del> // set the label <del> if err := label.SetFileCreateLabel(container.MountLabel); err != nil { <del> return fmt.Errorf("Unable to setup default labeling for volume creation %s: %v", bind.Source, err) <del> } <del> <ide> // create the volume <ide> v, err := createVolume(bind.Name, bind.Driver) <ide> if err != nil { <del> // reset the label <del> if e := label.SetFileCreateLabel(""); e != nil { <del> logrus.Errorf("Unable to reset labeling for volume creation %s: %v", bind.Source, e) <del> } <ide> return err <ide> } <ide> bind.Volume = v <del> <del> // reset the label <del> if err := label.SetFileCreateLabel(""); err != nil { <del> return fmt.Errorf("Unable to reset labeling for volume creation %s: %v", bind.Source, err) <add> bind.Source = v.Path() <add> // Since this is just a named volume and not a typical bind, set to shared mode `z` <add> if bind.Relabel == "" { <add> bind.Relabel = "z" <ide> } <ide> } <ide> <add> if err := label.Relabel(bind.Source, container.MountLabel, bind.Relabel); err != nil { <add> return err <add> } <ide> binds[bind.Destination] = true <ide> mountPoints[bind.Destination] = bind <ide> } <ide> <add> container.Lock() <ide> container.MountPoints = mountPoints <add> container.Unlock() <ide> <ide> return nil <ide> }
4
Javascript
Javascript
replace var with let in lib/path.js
896b75a4da58a7283d551c4595e0aa454baca3e0
<ide><path>lib/path.js <ide> function normalizeString(path, allowAboveRoot, separator, isPathSeparator) { <ide> let lastSlash = -1; <ide> let dots = 0; <ide> let code = 0; <del> for (var i = 0; i <= path.length; ++i) { <add> for (let i = 0; i <= path.length; ++i) { <ide> if (i < path.length) <ide> code = path.charCodeAt(i); <ide> else if (isPathSeparator(code)) <ide> const win32 = { <ide> let resolvedTail = ''; <ide> let resolvedAbsolute = false; <ide> <del> for (var i = args.length - 1; i >= -1; i--) { <add> for (let i = args.length - 1; i >= -1; i--) { <ide> let path; <ide> if (i >= 0) { <ide> path = args[i]; <ide> const win32 = { <ide> <ide> let joined; <ide> let firstPart; <del> for (var i = 0; i < args.length; ++i) { <add> for (let i = 0; i < args.length; ++i) { <ide> const arg = args[i]; <ide> validateString(arg, 'path'); <ide> if (arg.length > 0) { <ide> const win32 = { <ide> <ide> let end = -1; <ide> let matchedSlash = true; <del> for (var i = len - 1; i >= offset; --i) { <add> for (let i = len - 1; i >= offset; --i) { <ide> if (isPathSeparator(path.charCodeAt(i))) { <ide> if (!matchedSlash) { <ide> end = i; <ide> const win32 = { <ide> if (ext !== undefined) <ide> validateString(ext, 'ext'); <ide> validateString(path, 'path'); <del> var start = 0; <del> var end = -1; <del> var matchedSlash = true; <del> var i; <add> let start = 0; <add> let end = -1; <add> let matchedSlash = true; <ide> <ide> // Check for a drive letter prefix so as not to mistake the following <ide> // path separator as an extra separator at the end of the path that can be <ide> const win32 = { <ide> if (ext !== undefined && ext.length > 0 && ext.length <= path.length) { <ide> if (ext === path) <ide> return ''; <del> var extIdx = ext.length - 1; <del> var firstNonSlashEnd = -1; <del> for (i = path.length - 1; i >= start; --i) { <add> let extIdx = ext.length - 1; <add> let firstNonSlashEnd = -1; <add> for (let i = path.length - 1; i >= start; --i) { <ide> const code = path.charCodeAt(i); <ide> if (isPathSeparator(code)) { <ide> // If we reached a path separator that was not part of a set of path <ide> const win32 = { <ide> end = path.length; <ide> return path.slice(start, end); <ide> } <del> for (i = path.length - 1; i >= start; --i) { <add> for (let i = path.length - 1; i >= start; --i) { <ide> if (isPathSeparator(path.charCodeAt(i))) { <ide> // If we reached a path separator that was not part of a set of path <ide> // separators at the end of the string, stop now <ide> const win32 = { <ide> <ide> extname(path) { <ide> validateString(path, 'path'); <del> var start = 0; <del> var startDot = -1; <del> var startPart = 0; <del> var end = -1; <del> var matchedSlash = true; <add> let start = 0; <add> let startDot = -1; <add> let startPart = 0; <add> let end = -1; <add> let matchedSlash = true; <ide> // Track the state of characters (if any) we see before our first dot and <ide> // after any path separator we find <del> var preDotState = 0; <add> let preDotState = 0; <ide> <ide> // Check for a drive letter prefix so as not to mistake the following <ide> // path separator as an extra separator at the end of the path that can be <ide> const win32 = { <ide> start = startPart = 2; <ide> } <ide> <del> for (var i = path.length - 1; i >= start; --i) { <add> for (let i = path.length - 1; i >= start; --i) { <ide> const code = path.charCodeAt(i); <ide> if (isPathSeparator(code)) { <ide> // If we reached a path separator that was not part of a set of path <ide> const win32 = { <ide> return ret; <ide> <ide> const len = path.length; <del> var rootEnd = 0; <add> let rootEnd = 0; <ide> let code = path.charCodeAt(0); <ide> <ide> if (len === 1) { <ide> const win32 = { <ide> if (rootEnd > 0) <ide> ret.root = path.slice(0, rootEnd); <ide> <del> var startDot = -1; <del> var startPart = rootEnd; <del> var end = -1; <del> var matchedSlash = true; <del> var i = path.length - 1; <add> let startDot = -1; <add> let startPart = rootEnd; <add> let end = -1; <add> let matchedSlash = true; <add> let i = path.length - 1; <ide> <ide> // Track the state of characters (if any) we see before our first dot and <ide> // after any path separator we find <del> var preDotState = 0; <add> let preDotState = 0; <ide> <ide> // Get non-dir info <ide> for (; i >= rootEnd; --i) { <ide> const posix = { <ide> let resolvedPath = ''; <ide> let resolvedAbsolute = false; <ide> <del> for (var i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) { <add> for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) { <ide> const path = i >= 0 ? args[i] : process.cwd(); <ide> <ide> validateString(path, 'path'); <ide> const posix = { <ide> if (args.length === 0) <ide> return '.'; <ide> let joined; <del> for (var i = 0; i < args.length; ++i) { <add> for (let i = 0; i < args.length; ++i) { <ide> const arg = args[i]; <ide> validateString(arg, 'path'); <ide> if (arg.length > 0) { <ide> const posix = { <ide> if (path.length === 0) <ide> return '.'; <ide> const hasRoot = path.charCodeAt(0) === CHAR_FORWARD_SLASH; <del> var end = -1; <del> var matchedSlash = true; <del> for (var i = path.length - 1; i >= 1; --i) { <add> let end = -1; <add> let matchedSlash = true; <add> for (let i = path.length - 1; i >= 1; --i) { <ide> if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) { <ide> if (!matchedSlash) { <ide> end = i; <ide> const posix = { <ide> validateString(ext, 'ext'); <ide> validateString(path, 'path'); <ide> <del> var start = 0; <del> var end = -1; <del> var matchedSlash = true; <del> var i; <add> let start = 0; <add> let end = -1; <add> let matchedSlash = true; <ide> <ide> if (ext !== undefined && ext.length > 0 && ext.length <= path.length) { <ide> if (ext === path) <ide> return ''; <del> var extIdx = ext.length - 1; <del> var firstNonSlashEnd = -1; <del> for (i = path.length - 1; i >= 0; --i) { <add> let extIdx = ext.length - 1; <add> let firstNonSlashEnd = -1; <add> for (let i = path.length - 1; i >= 0; --i) { <ide> const code = path.charCodeAt(i); <ide> if (code === CHAR_FORWARD_SLASH) { <ide> // If we reached a path separator that was not part of a set of path <ide> const posix = { <ide> end = path.length; <ide> return path.slice(start, end); <ide> } <del> for (i = path.length - 1; i >= 0; --i) { <add> for (let i = path.length - 1; i >= 0; --i) { <ide> if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) { <ide> // If we reached a path separator that was not part of a set of path <ide> // separators at the end of the string, stop now <ide> const posix = { <ide> <ide> extname(path) { <ide> validateString(path, 'path'); <del> var startDot = -1; <del> var startPart = 0; <del> var end = -1; <del> var matchedSlash = true; <add> let startDot = -1; <add> let startPart = 0; <add> let end = -1; <add> let matchedSlash = true; <ide> // Track the state of characters (if any) we see before our first dot and <ide> // after any path separator we find <del> var preDotState = 0; <del> for (var i = path.length - 1; i >= 0; --i) { <add> let preDotState = 0; <add> for (let i = path.length - 1; i >= 0; --i) { <ide> const code = path.charCodeAt(i); <ide> if (code === CHAR_FORWARD_SLASH) { <ide> // If we reached a path separator that was not part of a set of path <ide> const posix = { <ide> if (path.length === 0) <ide> return ret; <ide> const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH; <del> var start; <add> let start; <ide> if (isAbsolute) { <ide> ret.root = '/'; <ide> start = 1; <ide> } else { <ide> start = 0; <ide> } <del> var startDot = -1; <del> var startPart = 0; <del> var end = -1; <del> var matchedSlash = true; <del> var i = path.length - 1; <add> let startDot = -1; <add> let startPart = 0; <add> let end = -1; <add> let matchedSlash = true; <add> let i = path.length - 1; <ide> <ide> // Track the state of characters (if any) we see before our first dot and <ide> // after any path separator we find <del> var preDotState = 0; <add> let preDotState = 0; <ide> <ide> // Get non-dir info <ide> for (; i >= start; --i) {
1
Python
Python
add key control on mac os x
dedf85164694a28284b89cd130c0d3739873ca52
<ide><path>glances/glances.py <ide> def displayProcess(self, processcount, processlist, sortedby='', log_count=0): <ide> len(processlist)) <ide> for processes in range(0, proc_num): <ide> # VMS <del> process_size = processlist[processes]['memory_info'][1] <del> self.term_window.addnstr( <del> self.process_y + 3 + processes, process_x, <del> format(self.__autoUnit(process_size), '>5'), 5) <add> if (processlist[processes]['memory_info'] != {}): <add> process_size = processlist[processes]['memory_info'][1] <add> self.term_window.addnstr( <add> self.process_y + 3 + processes, process_x, <add> format(self.__autoUnit(process_size), '>5'), 5) <add> else: <add> self.term_window.addnstr( <add> self.process_y + 3 + processes, process_x, <add> format('?', '>5'), 5) <ide> # RSS <del> process_resident = processlist[processes]['memory_info'][0] <del> self.term_window.addnstr( <del> self.process_y + 3 + processes, process_x + 6, <del> format(self.__autoUnit(process_resident), '>5'), 5) <add> if (processlist[processes]['memory_info'] != {}): <add> process_resident = processlist[processes]['memory_info'][0] <add> self.term_window.addnstr( <add> self.process_y + 3 + processes, process_x + 6, <add> format(self.__autoUnit(process_resident), '>5'), 5) <add> else: <add> self.term_window.addnstr( <add> self.process_y + 3 + processes, process_x + 6, <add> format('?', '>5'), 5) <ide> # CPU% <ide> cpu_percent = processlist[processes]['cpu_percent'] <ide> if psutil_get_cpu_percent_tag:
1
Javascript
Javascript
add brand checks for detached accessors
4ec64e320fb050d6d441c365f40668bfbeaa472a
<ide><path>lib/internal/event_target.js <ide> const { <ide> FunctionPrototypeCall, <ide> NumberIsInteger, <ide> ObjectAssign, <add> ObjectCreate, <ide> ObjectDefineProperties, <ide> ObjectDefineProperty, <ide> ObjectGetOwnPropertyDescriptor, <ide> const { customInspectSymbol } = require('internal/util'); <ide> const { inspect } = require('util'); <ide> <ide> const kIsEventTarget = SymbolFor('nodejs.event_target'); <add>const kIsNodeEventTarget = Symbol('kIsNodeEventTarget'); <ide> <ide> const EventEmitter = require('events'); <ide> const { <ide> const isTrusted = ObjectGetOwnPropertyDescriptor({ <ide> } <ide> }, 'isTrusted').get; <ide> <add>function isEvent(value) { <add> return typeof value?.[kType] === 'string'; <add>} <add> <ide> class Event { <ide> constructor(type, options = null) { <ide> if (arguments.length === 0) <ide> class Event { <ide> } <ide> <ide> [customInspectSymbol](depth, options) { <add> if (!isEvent(this)) <add> throw new ERR_INVALID_THIS('Event'); <ide> const name = this.constructor.name; <ide> if (depth < 0) <ide> return name; <ide> class Event { <ide> } <ide> <ide> stopImmediatePropagation() { <add> if (!isEvent(this)) <add> throw new ERR_INVALID_THIS('Event'); <ide> this[kStop] = true; <ide> } <ide> <ide> preventDefault() { <add> if (!isEvent(this)) <add> throw new ERR_INVALID_THIS('Event'); <ide> this[kDefaultPrevented] = true; <ide> } <ide> <del> get target() { return this[kTarget]; } <del> get currentTarget() { return this[kTarget]; } <del> get srcElement() { return this[kTarget]; } <add> get target() { <add> if (!isEvent(this)) <add> throw new ERR_INVALID_THIS('Event'); <add> return this[kTarget]; <add> } <ide> <del> get type() { return this[kType]; } <add> get currentTarget() { <add> if (!isEvent(this)) <add> throw new ERR_INVALID_THIS('Event'); <add> return this[kTarget]; <add> } <ide> <del> get cancelable() { return this[kCancelable]; } <add> get srcElement() { <add> if (!isEvent(this)) <add> throw new ERR_INVALID_THIS('Event'); <add> return this[kTarget]; <add> } <add> <add> get type() { <add> if (!isEvent(this)) <add> throw new ERR_INVALID_THIS('Event'); <add> return this[kType]; <add> } <add> <add> get cancelable() { <add> if (!isEvent(this)) <add> throw new ERR_INVALID_THIS('Event'); <add> return this[kCancelable]; <add> } <ide> <ide> get defaultPrevented() { <add> if (!isEvent(this)) <add> throw new ERR_INVALID_THIS('Event'); <ide> return this[kCancelable] && this[kDefaultPrevented]; <ide> } <ide> <del> get timeStamp() { return this[kTimestamp]; } <add> get timeStamp() { <add> if (!isEvent(this)) <add> throw new ERR_INVALID_THIS('Event'); <add> return this[kTimestamp]; <add> } <ide> <ide> <ide> // The following are non-op and unused properties/methods from Web API Event. <ide> // These are not supported in Node.js and are provided purely for <ide> // API completeness. <ide> <del> composedPath() { return this[kIsBeingDispatched] ? [this[kTarget]] : []; } <del> get returnValue() { return !this.defaultPrevented; } <del> get bubbles() { return this[kBubbles]; } <del> get composed() { return this[kComposed]; } <add> composedPath() { <add> if (!isEvent(this)) <add> throw new ERR_INVALID_THIS('Event'); <add> return this[kIsBeingDispatched] ? [this[kTarget]] : []; <add> } <add> <add> get returnValue() { <add> if (!isEvent(this)) <add> throw new ERR_INVALID_THIS('Event'); <add> return !this.defaultPrevented; <add> } <add> <add> get bubbles() { <add> if (!isEvent(this)) <add> throw new ERR_INVALID_THIS('Event'); <add> return this[kBubbles]; <add> } <add> <add> get composed() { <add> if (!isEvent(this)) <add> throw new ERR_INVALID_THIS('Event'); <add> return this[kComposed]; <add> } <add> <ide> get eventPhase() { <add> if (!isEvent(this)) <add> throw new ERR_INVALID_THIS('Event'); <ide> return this[kIsBeingDispatched] ? Event.AT_TARGET : Event.NONE; <ide> } <del> get cancelBubble() { return this[kPropagationStopped]; } <add> <add> get cancelBubble() { <add> if (!isEvent(this)) <add> throw new ERR_INVALID_THIS('Event'); <add> return this[kPropagationStopped]; <add> } <add> <ide> set cancelBubble(value) { <add> if (!isEvent(this)) <add> throw new ERR_INVALID_THIS('Event'); <ide> if (value) { <ide> this.stopPropagation(); <ide> } <ide> } <add> <ide> stopPropagation() { <add> if (!isEvent(this)) <add> throw new ERR_INVALID_THIS('Event'); <ide> this[kPropagationStopped] = true; <ide> } <ide> <ide> class Event { <ide> static BUBBLING_PHASE = 3; <ide> } <ide> <del>ObjectDefineProperty(Event.prototype, SymbolToStringTag, { <del> writable: false, <del> enumerable: false, <del> configurable: true, <del> value: 'Event', <del>}); <add>const kEnumerableProperty = ObjectCreate(null); <add>kEnumerableProperty.enumerable = true; <add> <add>ObjectDefineProperties( <add> Event.prototype, { <add> [SymbolToStringTag]: { <add> writable: false, <add> enumerable: false, <add> configurable: true, <add> value: 'Event', <add> }, <add> stopImmediatePropagation: kEnumerableProperty, <add> preventDefault: kEnumerableProperty, <add> target: kEnumerableProperty, <add> currentTarget: kEnumerableProperty, <add> srcElement: kEnumerableProperty, <add> type: kEnumerableProperty, <add> cancelable: kEnumerableProperty, <add> defaultPrevented: kEnumerableProperty, <add> timeStamp: kEnumerableProperty, <add> composedPath: kEnumerableProperty, <add> returnValue: kEnumerableProperty, <add> bubbles: kEnumerableProperty, <add> composed: kEnumerableProperty, <add> eventPhase: kEnumerableProperty, <add> cancelBubble: kEnumerableProperty, <add> stopPropagation: kEnumerableProperty, <add> }); <ide> <ide> class NodeCustomEvent extends Event { <ide> constructor(type, options) { <ide> class EventTarget { <ide> [kRemoveListener](size, type, listener, capture) {} <ide> <ide> addEventListener(type, listener, options = {}) { <add> if (!isEventTarget(this)) <add> throw new ERR_INVALID_THIS('EventTarget'); <ide> if (arguments.length < 2) <ide> throw new ERR_MISSING_ARGS('type', 'listener'); <ide> <ide> class EventTarget { <ide> } <ide> <ide> removeEventListener(type, listener, options = {}) { <add> if (!isEventTarget(this)) <add> throw new ERR_INVALID_THIS('EventTarget'); <ide> if (!shouldAddListener(listener)) <ide> return; <ide> <ide> class EventTarget { <ide> } <ide> <ide> dispatchEvent(event) { <del> if (!(event instanceof Event)) <del> throw new ERR_INVALID_ARG_TYPE('event', 'Event', event); <del> <ide> if (!isEventTarget(this)) <ide> throw new ERR_INVALID_THIS('EventTarget'); <ide> <add> if (!(event instanceof Event)) <add> throw new ERR_INVALID_ARG_TYPE('event', 'Event', event); <add> <ide> if (event[kIsBeingDispatched]) <ide> throw new ERR_EVENT_RECURSION(event.type); <ide> <ide> class EventTarget { <ide> return new NodeCustomEvent(type, { detail: nodeValue }); <ide> } <ide> [customInspectSymbol](depth, options) { <add> if (!isEventTarget(this)) <add> throw new ERR_INVALID_THIS('EventTarget'); <ide> const name = this.constructor.name; <ide> if (depth < 0) <ide> return name; <ide> class EventTarget { <ide> } <ide> <ide> ObjectDefineProperties(EventTarget.prototype, { <del> addEventListener: { enumerable: true }, <del> removeEventListener: { enumerable: true }, <del> dispatchEvent: { enumerable: true } <del>}); <del>ObjectDefineProperty(EventTarget.prototype, SymbolToStringTag, { <del> writable: false, <del> enumerable: false, <del> configurable: true, <del> value: 'EventTarget', <add> addEventListener: kEnumerableProperty, <add> removeEventListener: kEnumerableProperty, <add> dispatchEvent: kEnumerableProperty, <add> [SymbolToStringTag]: { <add> writable: false, <add> enumerable: false, <add> configurable: true, <add> value: 'EventTarget', <add> } <ide> }); <ide> <ide> function initNodeEventTarget(self) { <ide> initEventTarget(self); <ide> } <ide> <ide> class NodeEventTarget extends EventTarget { <add> static [kIsNodeEventTarget] = true; <ide> static defaultMaxListeners = 10; <ide> <ide> constructor() { <ide> class NodeEventTarget extends EventTarget { <ide> } <ide> <ide> setMaxListeners(n) { <add> if (!isNodeEventTarget(this)) <add> throw new ERR_INVALID_THIS('NodeEventTarget'); <ide> EventEmitter.setMaxListeners(n, this); <ide> } <ide> <ide> getMaxListeners() { <add> if (!isNodeEventTarget(this)) <add> throw new ERR_INVALID_THIS('NodeEventTarget'); <ide> return this[kMaxEventTargetListeners]; <ide> } <ide> <ide> eventNames() { <add> if (!isNodeEventTarget(this)) <add> throw new ERR_INVALID_THIS('NodeEventTarget'); <ide> return ArrayFrom(this[kEvents].keys()); <ide> } <ide> <ide> listenerCount(type) { <add> if (!isNodeEventTarget(this)) <add> throw new ERR_INVALID_THIS('NodeEventTarget'); <ide> const root = this[kEvents].get(String(type)); <ide> return root !== undefined ? root.size : 0; <ide> } <ide> <ide> off(type, listener, options) { <add> if (!isNodeEventTarget(this)) <add> throw new ERR_INVALID_THIS('NodeEventTarget'); <ide> this.removeEventListener(type, listener, options); <ide> return this; <ide> } <ide> <ide> removeListener(type, listener, options) { <add> if (!isNodeEventTarget(this)) <add> throw new ERR_INVALID_THIS('NodeEventTarget'); <ide> this.removeEventListener(type, listener, options); <ide> return this; <ide> } <ide> <ide> on(type, listener) { <add> if (!isNodeEventTarget(this)) <add> throw new ERR_INVALID_THIS('NodeEventTarget'); <ide> this.addEventListener(type, listener, { [kIsNodeStyleListener]: true }); <ide> return this; <ide> } <ide> <ide> addListener(type, listener) { <add> if (!isNodeEventTarget(this)) <add> throw new ERR_INVALID_THIS('NodeEventTarget'); <ide> this.addEventListener(type, listener, { [kIsNodeStyleListener]: true }); <ide> return this; <ide> } <ide> emit(type, arg) { <add> if (!isNodeEventTarget(this)) <add> throw new ERR_INVALID_THIS('NodeEventTarget'); <ide> validateString(type, 'type'); <ide> const hadListeners = this.listenerCount(type) > 0; <ide> this[kHybridDispatch](arg, type); <ide> return hadListeners; <ide> } <ide> <ide> once(type, listener) { <add> if (!isNodeEventTarget(this)) <add> throw new ERR_INVALID_THIS('NodeEventTarget'); <ide> this.addEventListener(type, listener, <ide> { once: true, [kIsNodeStyleListener]: true }); <ide> return this; <ide> } <ide> <ide> removeAllListeners(type) { <add> if (!isNodeEventTarget(this)) <add> throw new ERR_INVALID_THIS('NodeEventTarget'); <ide> if (type !== undefined) { <ide> this[kEvents].delete(String(type)); <ide> } else { <ide> class NodeEventTarget extends EventTarget { <ide> } <ide> <ide> ObjectDefineProperties(NodeEventTarget.prototype, { <del> setMaxListeners: { enumerable: true }, <del> getMaxListeners: { enumerable: true }, <del> eventNames: { enumerable: true }, <del> listenerCount: { enumerable: true }, <del> off: { enumerable: true }, <del> removeListener: { enumerable: true }, <del> on: { enumerable: true }, <del> addListener: { enumerable: true }, <del> once: { enumerable: true }, <del> emit: { enumerable: true }, <del> removeAllListeners: { enumerable: true }, <add> setMaxListeners: kEnumerableProperty, <add> getMaxListeners: kEnumerableProperty, <add> eventNames: kEnumerableProperty, <add> listenerCount: kEnumerableProperty, <add> off: kEnumerableProperty, <add> removeListener: kEnumerableProperty, <add> on: kEnumerableProperty, <add> addListener: kEnumerableProperty, <add> once: kEnumerableProperty, <add> emit: kEnumerableProperty, <add> removeAllListeners: kEnumerableProperty, <ide> }); <ide> <ide> // EventTarget API <ide> function isEventTarget(obj) { <ide> return obj?.constructor?.[kIsEventTarget]; <ide> } <ide> <add>function isNodeEventTarget(obj) { <add> return obj?.constructor?.[kIsNodeEventTarget]; <add>} <add> <ide> function addCatch(promise) { <ide> const then = promise.then; <ide> if (typeof then === 'function') { <ide><path>test/parallel/test-eventtarget-brandcheck.js <add>// Flags: --expose-internals <add>'use strict'; <add> <add>require('../common'); <add>const assert = require('assert'); <add> <add>const { <add> Event, <add> EventTarget, <add> NodeEventTarget, <add>} = require('internal/event_target'); <add> <add>[ <add> 'target', <add> 'currentTarget', <add> 'srcElement', <add> 'type', <add> 'cancelable', <add> 'defaultPrevented', <add> 'timeStamp', <add> 'returnValue', <add> 'bubbles', <add> 'composed', <add> 'eventPhase', <add>].forEach((i) => { <add> assert.throws(() => Reflect.get(Event.prototype, i, {}), { <add> code: 'ERR_INVALID_THIS', <add> }); <add>}); <add> <add>[ <add> 'stopImmediatePropagation', <add> 'preventDefault', <add> 'composedPath', <add> 'cancelBubble', <add> 'stopPropagation', <add>].forEach((i) => { <add> assert.throws(() => Reflect.apply(Event.prototype[i], [], {}), { <add> code: 'ERR_INVALID_THIS', <add> }); <add>}); <add> <add>[ <add> 'addEventListener', <add> 'removeEventListener', <add> 'dispatchEvent', <add>].forEach((i) => { <add> assert.throws(() => Reflect.apply(EventTarget.prototype[i], [], {}), { <add> code: 'ERR_INVALID_THIS', <add> }); <add>}); <add> <add>[ <add> 'setMaxListeners', <add> 'getMaxListeners', <add> 'eventNames', <add> 'listenerCount', <add> 'off', <add> 'removeListener', <add> 'on', <add> 'addListener', <add> 'once', <add> 'emit', <add> 'removeAllListeners', <add>].forEach((i) => { <add> assert.throws(() => Reflect.apply(NodeEventTarget.prototype[i], [], {}), { <add> code: 'ERR_INVALID_THIS', <add> }); <add>});
2
PHP
PHP
apply fixes from styleci
66bfbd5cbb2ea482312d098aa3b9b1c27ce521e7
<ide><path>src/Illuminate/Container/Container.php <ide> public function extend($abstract, Closure $closure) <ide> * Register an existing instance as shared in the container. <ide> * <ide> * @template T <add> * <ide> * @param string $abstract <ide> * @param T $instance <ide> * @return T <ide> public function makeWith($abstract, array $parameters = []) <ide> * Resolve the given type from the container. <ide> * <ide> * @template T <add> * <ide> * @param class-string<T> $abstract <ide> * @param array $parameters <ide> * @return T|mixed <ide><path>src/Illuminate/Contracts/Container/Container.php <ide> public function extend($abstract, Closure $closure); <ide> * Register an existing instance as shared in the container. <ide> * <ide> * @template T <add> * <ide> * @param string $abstract <ide> * @param T $instance <ide> * @return T <ide> public function flush(); <ide> * Resolve the given type from the container. <ide> * <ide> * @template T <add> * <ide> * @param class-string<T> $abstract <ide> * @param array $parameters <ide> * @return T|mixed <ide><path>src/Illuminate/Foundation/Application.php <ide> public function registerDeferredProvider($provider, $service = null) <ide> * Resolve the given type from the container. <ide> * <ide> * @template T <add> * <ide> * @param class-string<T> $abstract <ide> * @param array $parameters <ide> * @return T|mixed <ide><path>src/Illuminate/Foundation/helpers.php <ide> function action($name, $parameters = [], $absolute = true) <ide> * Get the available container instance. <ide> * <ide> * @template T <add> * <ide> * @param class-string<T>|mixed $abstract <ide> * @param array $parameters <ide> * @return mixed|T|\Illuminate\Contracts\Foundation\Application
4
PHP
PHP
fix cs errors
1e95b4200663d52c5886a53a6226a962d983df54
<ide><path>src/Http/Response.php <ide> class Response implements ResponseInterface <ide> 'image/psd', <ide> 'image/x-photoshop', <ide> 'image/photoshop', <del> 'zz-application/zz-winassoc-psd' <add> 'zz-application/zz-winassoc-psd', <ide> ], <ide> 'ice' => 'x-conference/x-cooltalk', <ide> 'iges' => 'model/iges', <ide><path>src/Validation/Validation.php <ide> public static function time($check): bool <ide> return false; <ide> } <ide> <del> // phpcs:ignore Generic.Files.LineLength <del> return static::_check($check, '%^((0?[1-9]|1[012])(:[0-5]\d){0,2} ?([AP]M|[ap]m))$|^([01]\d|2[0-3])(:[0-5]\d){0,2}$%'); <add> return static::_check( <add> $check, <add> '%^((0?[1-9]|1[012])(:[0-5]\d){0,2} ?([AP]M|[ap]m))$|^([01]\d|2[0-3])(:[0-5]\d){0,2}$%' <add> ); <ide> } <ide> <ide> /**
2
Javascript
Javascript
simplify check in previousvalueisvalid()
4ebb3f35e2c0a22744063f2a120516a8c26cbba1
<ide><path>lib/internal/process/per_thread.js <ide> function setupCpuUsage(_cpuUsage) { <ide> // Ensure that a previously passed in value is valid. Currently, the native <ide> // implementation always returns numbers <= Number.MAX_SAFE_INTEGER. <ide> function previousValueIsValid(num) { <del> return Number.isFinite(num) && <add> return typeof num === 'number' && <ide> num <= Number.MAX_SAFE_INTEGER && <ide> num >= 0; <ide> }
1
Python
Python
add pipe to attributeruler
06c3a5e048dc740bbe482d994505512845a6fd9f
<ide><path>spacy/pipeline/attributeruler.py <ide> def __call__(self, doc: Doc) -> Doc: <ide> set_token_attrs(token, attrs) <ide> return doc <ide> <add> def pipe(self, stream, *, batch_size=128): <add> """Apply the pipe to a stream of documents. This usually happens under <add> the hood when the nlp object is called on a text and all components are <add> applied to the Doc. <add> <add> stream (Iterable[Doc]): A stream of documents. <add> batch_size (int): The number of documents to buffer. <add> YIELDS (Doc): Processed documents in order. <add> <add> DOCS: https://spacy.io/attributeruler/pipe#pipe <add> """ <add> for doc in stream: <add> doc = self(doc) <add> yield doc <add> <ide> def load_from_tag_map( <ide> self, tag_map: Dict[str, Dict[Union[int, str], Union[int, str]]] <ide> ) -> None:
1
Java
Java
make testcontextmanager.gettestcontext() public
067994712df49b50b955e93944245a770b3962ad
<ide><path>spring-test/src/main/java/org/springframework/test/context/TestContextManager.java <ide> public TestContextManager(TestContextBootstrapper testContextBootstrapper) { <ide> /** <ide> * Get the {@link TestContext} managed by this {@code TestContextManager}. <ide> */ <del> protected final TestContext getTestContext() { <add> public final TestContext getTestContext() { <ide> return this.testContext; <ide> } <ide>
1
Text
Text
add list article
07d9862c0e50d8c67c56bcf78f002a766d932e50
<ide><path>guide/english/haskell/lists/index.md <add>--- <add>title: Lists <add>--- <add> <add>Lists are a widely used datatype in Haskell. In fact, if you have used strings you've used Haskell's lists! <add> <add># Definition <add>Haskell's lists are recursively defined as follows: <add> <add>```haskell <add>data [] a -- A List containing type `a` <add> = [] -- Empty list constructor. <add> | a : [a] -- "Construction" constructor, a.k.a. cons. <add>``` <add> <add>Notice that lists in Haskell are not arrays, but linked lists. <add> <add>The following are examples of lists: <add> <add>```haskell <add>empty :: [()] <add>empty = [] <add> <add>ints :: [Int] <add>ints = 1 : 2 : 3 : [] <add>``` <add> <add>There's syntactic sugar for making lists as well: <add> <add>```haskell <add>bools :: [Bool] <add>bools = [True, False, False, True] -- True : False : False : True : [] <add>``` <add> <add>`String` is just an alias for `[Char]`! <add> <add>```haskell <add>chars :: [Char] <add>chars = "This is a character list!" <add>``` <add> <add># Functions <add>Lists have many different built in functions. Here's a few: <add> <add>```haskell <add>-- Concatenation: <add>-- Stick two lists together. <add>greeting :: String <add>greeting = "Hello, " ++ "World!" -- "Hello, World!" <add> <add>-- Map: <add>-- Appy some function to overy element. <add>abc :: [Int] <add>abc = map succ [0, 1, 2] -- [1, 2, 3] <add>``` <add> <add># Pattern matching <add>You can easily pattern match lists to easily recurse over them. <add> <add>```haskell <add>map' :: (a -> b) -> [a] -> [b] <add>map' _ [] = [] -- Base case. <add>map' f (a:as) = f a : map' f as -- Recursive case. <add>```
1
Ruby
Ruby
move test_bot_user to a new module github
3ee3b78fbda48821e878feeafc313a9391c5729c
<ide><path>Library/Homebrew/dev-cmd/pull.rb <ide> require "version" <ide> require "pkg_version" <ide> <add>module GitHub <add> module_function <add> <add> # Return the corresponding test-bot user name for the given GitHub organization. <add> def test_bot_user(user) <add> test_bot = ARGV.value "test-bot-user" <add> return test_bot if test_bot <add> return "BrewTestBot" if user.casecmp("homebrew").zero? <add> "#{user.capitalize}TestBot" <add> end <add>end <add> <ide> module Homebrew <ide> module_function <ide> <ide> def pull <ide> url <ide> else <ide> bottle_branch = "pull-bottle-#{issue}" <del> "https://github.com/#{test_bot_user user}/homebrew-#{tap.repo}/compare/#{user}:master...pr-#{issue}" <add> "https://github.com/#{GitHub.test_bot_user user}/homebrew-#{tap.repo}/compare/#{user}:master...pr-#{issue}" <ide> end <ide> <ide> curl "--silent", "--fail", "--output", "/dev/null", "--head", bottle_commit_url <ide> def pull <ide> verify_bintray_published(bintray_published_formulae) <ide> end <ide> <del> def test_bot_user(user) <del> test_bot = ARGV.value "test-bot-user" <del> return test_bot if test_bot <del> return "BrewTestBot" if user.casecmp("homebrew").zero? <del> "#{user.capitalize}TestBot" <del> end <del> <ide> def force_utf8!(str) <ide> str.force_encoding("UTF-8") if str.respond_to?(:force_encoding) <ide> end
1
Text
Text
clarify dependency installation
2ff1b2e9e355b9932eb559075565741e14b0b6d6
<ide><path>docs/docs/getting-started.md <ide> ReactDOM.render( <ide> ); <ide> ``` <ide> <del>To install React DOM and build your bundle after installing browserify: <add>To install React DOM and build your bundle with browserify: <ide> <ide> ```sh <ide> $ npm install --save react react-dom babelify babel-preset-react <ide> $ browserify -t [ babelify --presets [ react ] ] main.js -o bundle.js <ide> ``` <ide> <add>To install React DOM and build your bundle with webpack: <add> <add>```sh <add>$ npm install --save react react-dom babel-preset-react <add>$ webpack <add>``` <add> <ide> > Note: <ide> > <ide> > If you are using ES2015, you will want to also use the `babel-preset-es2015` package.
1
Python
Python
remove metrics for predict
f1df4297c27f4a2dab675d253be67eb0372817af
<ide><path>keras/engine/training.py <ide> def _predict_loop(self, f, ins, batch_size=32, verbose=0, steps=None): <ide> or list of arrays of predictions <ide> (if the model has multiple outputs). <ide> """ <del> <del> if hasattr(self, 'metrics'): <del> for m in self.metrics: <del> if isinstance(m, Layer): <del> m.reset_states() <ide> num_samples = self._check_num_samples(ins, batch_size, <ide> steps, <ide> 'steps') <ide> if verbose == 1: <ide> if steps is not None: <del> progbar = Progbar(target=steps, <del> stateful_metrics=self.stateful_metric_names) <add> progbar = Progbar(target=steps) <ide> else: <del> progbar = Progbar(target=num_samples, <del> stateful_metrics=self.stateful_metric_names) <add> progbar = Progbar(target=num_samples) <ide> <ide> indices_for_conversion_to_dense = [] <ide> for i in range(len(self._feed_inputs)):
1
PHP
PHP
deprecate the arrayaccess interface methods
477e7562c0f6d896808ae176751725fec56aa7ad
<ide><path>src/Network/Request.php <ide> public function setInput($input) <ide> * <ide> * @param string $name Name of the key being accessed. <ide> * @return mixed <add> * @deprecated 3.4.0 The ArrayAccess methods will be removed in 4.0.0. Use param(), data() and query() instead. <ide> */ <ide> public function offsetGet($name) <ide> { <ide> public function offsetGet($name) <ide> * @param string $name Name of the key being written <ide> * @param mixed $value The value being written. <ide> * @return void <add> * @deprecated 3.4.0 The ArrayAccess methods will be removed in 4.0.0. Use param(), data() and query() instead. <ide> */ <ide> public function offsetSet($name, $value) <ide> { <ide> public function offsetSet($name, $value) <ide> * <ide> * @param string $name thing to check. <ide> * @return bool <add> * @deprecated 3.4.0 The ArrayAccess methods will be removed in 4.0.0. Use param(), data() and query() instead. <ide> */ <ide> public function offsetExists($name) <ide> { <ide> public function offsetExists($name) <ide> * <ide> * @param string $name Name to unset. <ide> * @return void <add> * @deprecated 3.4.0 The ArrayAccess methods will be removed in 4.0.0. Use param(), data() and query() instead. <ide> */ <ide> public function offsetUnset($name) <ide> {
1
Go
Go
fix wrong kill signal parsing
39eec4c25bce6291534f9524dc52de65787d5b6e
<ide><path>api/server/server.go <ide> func (s *Server) postContainersKill(version version.Version, w http.ResponseWrit <ide> name := vars["name"] <ide> <ide> // If we have a signal, look at it. Otherwise, do nothing <del> if sigStr := vars["signal"]; sigStr != "" { <add> if sigStr := r.Form.Get("signal"); sigStr != "" { <ide> // Check if we passed the signal as a number: <ide> // The largest legal signal is 31, so let's parse on 5 bits <del> sig, err := strconv.ParseUint(sigStr, 10, 5) <add> sigN, err := strconv.ParseUint(sigStr, 10, 5) <ide> if err != nil { <ide> // The signal is not a number, treat it as a string (either like <ide> // "KILL" or like "SIGKILL") <del> sig = uint64(signal.SignalMap[strings.TrimPrefix(sigStr, "SIG")]) <add> syscallSig, ok := signal.SignalMap[strings.TrimPrefix(sigStr, "SIG")] <add> if !ok { <add> return fmt.Errorf("Invalid signal: %s", sigStr) <add> } <add> sig = uint64(syscallSig) <add> } else { <add> sig = sigN <ide> } <ide> <ide> if sig == 0 { <ide><path>integration-cli/docker_cli_kill_test.go <ide> func (s *DockerSuite) TestKillDifferentUserContainer(c *check.C) { <ide> c.Fatal("killed container is still running") <ide> } <ide> } <add> <add>// regression test about correct signal parsing see #13665 <add>func (s *DockerSuite) TestKillWithSignal(c *check.C) { <add> runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "top") <add> out, _, err := runCommandWithOutput(runCmd) <add> c.Assert(err, check.IsNil) <add> <add> cid := strings.TrimSpace(out) <add> c.Assert(waitRun(cid), check.IsNil) <add> <add> killCmd := exec.Command(dockerBinary, "kill", "-s", "SIGWINCH", cid) <add> _, err = runCommand(killCmd) <add> c.Assert(err, check.IsNil) <add> <add> running, err := inspectField(cid, "State.Running") <add> if running != "true" { <add> c.Fatal("Container should be in running state after SIGWINCH") <add> } <add>} <add> <add>func (s *DockerSuite) TestKillWithInvalidSignal(c *check.C) { <add> runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "top") <add> out, _, err := runCommandWithOutput(runCmd) <add> c.Assert(err, check.IsNil) <add> <add> cid := strings.TrimSpace(out) <add> c.Assert(waitRun(cid), check.IsNil) <add> <add> killCmd := exec.Command(dockerBinary, "kill", "-s", "0", cid) <add> out, _, err = runCommandWithOutput(killCmd) <add> c.Assert(err, check.NotNil) <add> if !strings.ContainsAny(out, "Invalid signal: 0") { <add> c.Fatal("Kill with an invalid signal didn't error out correctly") <add> } <add> <add> running, err := inspectField(cid, "State.Running") <add> if running != "true" { <add> c.Fatal("Container should be in running state after an invalid signal") <add> } <add> <add> runCmd = exec.Command(dockerBinary, "run", "-d", "busybox", "top") <add> out, _, err = runCommandWithOutput(runCmd) <add> c.Assert(err, check.IsNil) <add> <add> cid = strings.TrimSpace(out) <add> c.Assert(waitRun(cid), check.IsNil) <add> <add> killCmd = exec.Command(dockerBinary, "kill", "-s", "SIG42", cid) <add> out, _, err = runCommandWithOutput(killCmd) <add> c.Assert(err, check.NotNil) <add> if !strings.ContainsAny(out, "Invalid signal: SIG42") { <add> c.Fatal("Kill with an invalid signal error out correctly") <add> } <add> <add> running, err = inspectField(cid, "State.Running") <add> if running != "true" { <add> c.Fatal("Container should be in running state after an invalid signal") <add> } <add>}
2
Javascript
Javascript
make slowbuffer inherit from buffer
38542f76a97e5c424aeada2e2dc8371797449335
<ide><path>lib/buffer.js <ide> function binaryWarn() { <ide> <ide> exports.INSPECT_MAX_BYTES = 50; <ide> <add>// Make SlowBuffer inherit from Buffer. <add>// This is an exception to the rule that __proto__ is not allowed in core. <add>SlowBuffer.prototype.__proto__ = Buffer.prototype; <add> <ide> <ide> function toHex(n) { <ide> if (n < 16) return '0' + n.toString(16); <ide> return n.toString(16); <ide> } <ide> <ide> <del>SlowBuffer.prototype.inspect = function() { <del> var out = [], <del> len = this.length; <del> for (var i = 0; i < len; i++) { <del> out[i] = toHex(this[i]); <del> if (i == exports.INSPECT_MAX_BYTES) { <del> out[i + 1] = '...'; <del> break; <del> } <del> } <del> return '<SlowBuffer ' + out.join(' ') + '>'; <del>}; <del> <del> <ide> SlowBuffer.prototype.hexSlice = function(start, end) { <ide> var len = this.length; <ide> <ide> function allocPool() { <ide> <ide> // Static methods <ide> Buffer.isBuffer = function isBuffer(b) { <del> return b instanceof Buffer || b instanceof SlowBuffer; <add> return b instanceof Buffer; <ide> }; <ide> <ide> <ide> // Inspect <ide> Buffer.prototype.inspect = function inspect() { <ide> var out = [], <del> len = this.length; <add> len = this.length, <add> name = this.constructor.name; <ide> <ide> for (var i = 0; i < len; i++) { <del> out[i] = toHex(this.parent[i + this.offset]); <add> out[i] = toHex(this[i]); <ide> if (i == exports.INSPECT_MAX_BYTES) { <ide> out[i + 1] = '...'; <ide> break; <ide> } <ide> } <ide> <del> return '<Buffer ' + out.join(' ') + '>'; <add> return '<' + name + ' ' + out.join(' ') + '>'; <ide> }; <ide> <ide> <ide> Buffer.prototype.writeDoubleLE = function(value, offset, noAssert) { <ide> Buffer.prototype.writeDoubleBE = function(value, offset, noAssert) { <ide> writeDouble(this, value, offset, true, noAssert); <ide> }; <del> <del>SlowBuffer.prototype.readUInt8 = Buffer.prototype.readUInt8; <del>SlowBuffer.prototype.readUInt16LE = Buffer.prototype.readUInt16LE; <del>SlowBuffer.prototype.readUInt16BE = Buffer.prototype.readUInt16BE; <del>SlowBuffer.prototype.readUInt32LE = Buffer.prototype.readUInt32LE; <del>SlowBuffer.prototype.readUInt32BE = Buffer.prototype.readUInt32BE; <del>SlowBuffer.prototype.readInt8 = Buffer.prototype.readInt8; <del>SlowBuffer.prototype.readInt16LE = Buffer.prototype.readInt16LE; <del>SlowBuffer.prototype.readInt16BE = Buffer.prototype.readInt16BE; <del>SlowBuffer.prototype.readInt32LE = Buffer.prototype.readInt32LE; <del>SlowBuffer.prototype.readInt32BE = Buffer.prototype.readInt32BE; <del>SlowBuffer.prototype.readFloatLE = Buffer.prototype.readFloatLE; <del>SlowBuffer.prototype.readFloatBE = Buffer.prototype.readFloatBE; <del>SlowBuffer.prototype.readDoubleLE = Buffer.prototype.readDoubleLE; <del>SlowBuffer.prototype.readDoubleBE = Buffer.prototype.readDoubleBE; <del>SlowBuffer.prototype.writeUInt8 = Buffer.prototype.writeUInt8; <del>SlowBuffer.prototype.writeUInt16LE = Buffer.prototype.writeUInt16LE; <del>SlowBuffer.prototype.writeUInt16BE = Buffer.prototype.writeUInt16BE; <del>SlowBuffer.prototype.writeUInt32LE = Buffer.prototype.writeUInt32LE; <del>SlowBuffer.prototype.writeUInt32BE = Buffer.prototype.writeUInt32BE; <del>SlowBuffer.prototype.writeInt8 = Buffer.prototype.writeInt8; <del>SlowBuffer.prototype.writeInt16LE = Buffer.prototype.writeInt16LE; <del>SlowBuffer.prototype.writeInt16BE = Buffer.prototype.writeInt16BE; <del>SlowBuffer.prototype.writeInt32LE = Buffer.prototype.writeInt32LE; <del>SlowBuffer.prototype.writeInt32BE = Buffer.prototype.writeInt32BE; <del>SlowBuffer.prototype.writeFloatLE = Buffer.prototype.writeFloatLE; <del>SlowBuffer.prototype.writeFloatBE = Buffer.prototype.writeFloatBE; <del>SlowBuffer.prototype.writeDoubleLE = Buffer.prototype.writeDoubleLE; <del>SlowBuffer.prototype.writeDoubleBE = Buffer.prototype.writeDoubleBE;
1
Javascript
Javascript
allow empty option to be removed and re-added
2fdfbe729660a0a55df96f3eb6f833d7a6e709a9
<ide><path>src/ng/directive/ngOptions.js <ide> var ngOptionsDirective = ['$compile', '$document', '$parse', function($compile, <ide> } <ide> } <ide> <add> // The empty option will be compiled and rendered before we first generate the options <add> selectElement.empty(); <add> <ide> var providedEmptyOption = !!selectCtrl.emptyOption; <ide> <ide> var unknownOption = jqLite(optionTemplate.cloneNode(false)); <ide> var ngOptionsDirective = ['$compile', '$document', '$parse', function($compile, <ide> <ide> if (providedEmptyOption) { <ide> <del> // we need to remove it before calling selectElement.empty() because otherwise IE will <del> // remove the label from the element. wtf? <del> selectCtrl.emptyOption.remove(); <del> <ide> // compile the element since there might be bindings in it <ide> $compile(selectCtrl.emptyOption)(scope); <ide> <add> selectElement.prepend(selectCtrl.emptyOption); <add> <ide> if (selectCtrl.emptyOption[0].nodeType === NODE_TYPE_COMMENT) { <ide> // This means the empty option has currently no actual DOM node, probably because <ide> // it has been modified by a transclusion directive. <ide> var ngOptionsDirective = ['$compile', '$document', '$parse', function($compile, <ide> <ide> } <ide> <del> selectElement.empty(); <del> <ide> // We need to do this here to ensure that the options object is defined <ide> // when we first hit it in writeNgOptionsValue <ide> updateOptions(); <ide> var ngOptionsDirective = ['$compile', '$document', '$parse', function($compile, <ide> <ide> var groupElementMap = {}; <ide> <del> // Ensure that the empty option is always there if it was explicitly provided <del> if (providedEmptyOption) { <del> <del> if (selectCtrl.unknownOption.parent().length) { <del> selectCtrl.unknownOption.after(selectCtrl.emptyOption); <del> } else { <del> selectElement.prepend(selectCtrl.emptyOption); <del> } <del> } <del> <ide> options.items.forEach(function addOption(option) { <ide> var groupElement; <ide> <ide><path>test/ng/directive/ngOptionsSpec.js <ide> describe('ngOptions', function() { <ide> expect(element.find('option').length).toBe(1); <ide> option = element.find('option').eq(0); <ide> expect(option.text()).toBe('A'); <add> <add> scope.$apply('isBlank = true'); <add> <add> expect(element).toEqualSelect([''], 'object:4'); <ide> }); <ide> <ide>
2
Text
Text
update copyright year in license to include 2014
0a6c892766abe47e5e535a654b45ab5db052bb76
<ide><path>LICENSE.md <del>Copyright (c) 2014 Nick Downie <add>Copyright (c) 2013-2014 Nick Downie <ide> <ide> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: <ide>
1
Javascript
Javascript
fix experimental macros test
889dfeccabe85d616df66695ffe013e55eb9c298
<ide><path>packages/@ember/-internals/glimmer/tests/integration/syntax/experimental-syntax-test.js <ide> import { moduleFor, RenderingTestCase, strip } from 'internal-test-helpers'; <ide> <ide> import { _registerMacros, _experimentalMacros } from '@ember/-internals/glimmer'; <add>import { invokeStaticBlockWithStack } from '@glimmer/opcode-compiler'; <ide> <ide> moduleFor( <ide> 'registerMacros', <ide> moduleFor( <ide> let originalMacros = _experimentalMacros.slice(); <ide> <ide> _registerMacros(blocks => { <del> blocks.add('-let', (params, hash, _default, inverse, builder) => { <del> builder.compileParams(params); <del> builder.invokeStaticBlock(_default, params.length); <add> blocks.add('-test-block', (params, _hash, blocks) => { <add> return invokeStaticBlockWithStack(blocks.get('default')); <ide> }); <ide> }); <ide> <ide> moduleFor( <ide> ['@test allows registering custom syntax via private API']() { <ide> this.render( <ide> strip` <del> {{#-let obj as |bar|}} <del> {{bar}} <del> {{/-let}} <del> `, <del> { obj: 'hello world!' } <add> {{#-test-block}} <add> hello world! <add> {{/-test-block}} <add> ` <ide> ); <ide> <ide> this.assertText('hello world!');
1
Javascript
Javascript
handle the removal of an interpolated attribute
a75546afdf41adab786eda30c258190cd4c5f1ae
<ide><path>src/ng/compile.js <ide> function $CompileProvider($provide, $$sanitizeUriProvider) { <ide> "ng- versions (such as ng-click instead of onclick) instead."); <ide> } <ide> <add> // If the attribute was removed, then we are done <add> if (!attr[name]) { <add> return; <add> } <add> <ide> // we need to interpolate again, in case the attribute value has been updated <ide> // (e.g. by another directive's compile function) <ide> interpolateFn = $interpolate(attr[name], true, getTrustedContext(node, name), <ide><path>test/ng/compileSpec.js <ide> describe('$compile', function() { <ide> }); <ide> }); <ide> <add> it('should allow the attribute to be removed before the attribute interpolation', function () { <add> module(function() { <add> directive('removeAttr', function () { <add> return { <add> restrict:'A', <add> compile: function (tElement, tAttr) { <add> tAttr.$set('removeAttr', null); <add> } <add> }; <add> }); <add> }); <add> inject(function ($rootScope, $compile) { <add> expect(function () { <add> element = $compile('<div remove-attr="{{ toBeRemoved }}"></div>')($rootScope); <add> }).not.toThrow(); <add> expect(element.attr('remove-attr')).toBeUndefined(); <add> }); <add> }); <ide> <ide> describe('SCE values', function() { <ide> it('should resolve compile and link both attribute and text bindings', inject(
2
Python
Python
use attention_mask everywhere
fe0f552e00e7556c9dd6eccc2486b962bb2a3460
<ide><path>transformers/pipelines.py <ide> def __call__(self, *texts, **kwargs): <ide> return_attention_masks=True, return_input_lengths=False <ide> ) <ide> <del> # TODO : Harmonize model arguments across all model <del> inputs['attention_mask'] = inputs.pop('encoder_attention_mask') <del> <ide> if is_tf_available(): <ide> # TODO trace model <ide> start, end = self.model(inputs)
1
Javascript
Javascript
optimize parse and stringify
85a92a37ef76059a4733c8e9462ff8da733dfb9e
<ide><path>lib/querystring.js <ide> <ide> const QueryString = exports; <ide> <del>// If obj.hasOwnProperty has been overridden, then calling <del>// obj.hasOwnProperty(prop) will break. <del>// See: https://github.com/joyent/node/issues/1707 <del>function hasOwnProperty(obj, prop) { <del> return Object.prototype.hasOwnProperty.call(obj, prop); <del>} <del> <ide> <ide> function charCode(c) { <ide> return c.charCodeAt(0); <ide> QueryString.unescape = function(s, decodeSpaces) { <ide> }; <ide> <ide> <add>var hexTable = new Array(256); <add>for (var i = 0; i < 256; ++i) <add> hexTable[i] = '%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase(); <ide> QueryString.escape = function(str) { <del> return encodeURIComponent(str); <add> var len = str.length; <add> var out = ''; <add> var i, c; <add> <add> if (len === 0) <add> return str; <add> <add> for (i = 0; i < len; ++i) { <add> c = str.charCodeAt(i); <add> <add> // These characters do not need escaping (in order): <add> // ! - . _ ~ <add> // ' ( ) * <add> // digits <add> // alpha (uppercase) <add> // alpha (lowercase) <add> if (c === 0x21 || c === 0x2D || c === 0x2E || c === 0x5F || c === 0x7E || <add> (c >= 0x27 && c <= 0x2A) || <add> (c >= 0x30 && c <= 0x39) || <add> (c >= 0x41 && c <= 0x5A) || <add> (c >= 0x61 && c <= 0x7A)) { <add> out += str[i]; <add> continue; <add> } <add> <add> // Other ASCII characters <add> if (c < 0x80) { <add> out += hexTable[c]; <add> continue; <add> } <add> <add> // Multi-byte characters ... <add> if (c < 0x800) { <add> out += hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]; <add> continue; <add> } <add> if (c < 0xD800 || c >= 0xE000) { <add> out += hexTable[0xE0 | (c >> 12)] + <add> hexTable[0x80 | ((c >> 6) & 0x3F)] + <add> hexTable[0x80 | (c & 0x3F)]; <add> continue; <add> } <add> // Surrogate pair <add> ++i; <add> c = 0x10000 + (((c & 0x3FF) << 10) | (str.charCodeAt(i) & 0x3FF)); <add> out += hexTable[0xF0 | (c >> 18)] + <add> hexTable[0x80 | ((c >> 12) & 0x3F)] + <add> hexTable[0x80 | ((c >> 6) & 0x3F)] + <add> hexTable[0x80 | (c & 0x3F)]; <add> } <add> return out; <ide> }; <ide> <ide> var stringifyPrimitive = function(v) { <del> let type = typeof v; <del> <del> if (type === 'string') <add> if (typeof v === 'string' || (typeof v === 'number' && isFinite(v))) <ide> return v; <del> if (type === 'boolean') <add> if (typeof v === 'boolean') <ide> return v ? 'true' : 'false'; <del> if (type === 'number') <del> return isFinite(v) ? v : ''; <ide> return ''; <ide> }; <ide> <ide> QueryString.stringify = QueryString.encode = function(obj, sep, eq, options) { <ide> <ide> if (obj !== null && typeof obj === 'object') { <ide> var keys = Object.keys(obj); <del> var fields = []; <del> <del> for (var i = 0; i < keys.length; i++) { <add> var len = keys.length; <add> var flast = len - 1; <add> var fields = ''; <add> for (var i = 0; i < len; ++i) { <ide> var k = keys[i]; <ide> var v = obj[k]; <ide> var ks = encode(stringifyPrimitive(k)) + eq; <ide> <ide> if (Array.isArray(v)) { <del> for (var j = 0; j < v.length; j++) <del> fields.push(ks + encode(stringifyPrimitive(v[j]))); <add> var vlen = v.length; <add> var vlast = vlen - 1; <add> for (var j = 0; j < vlen; ++j) { <add> fields += ks + encode(stringifyPrimitive(v[j])); <add> if (j < vlast) <add> fields += sep; <add> } <add> if (vlen && i < flast) <add> fields += sep; <ide> } else { <del> fields.push(ks + encode(stringifyPrimitive(v))); <add> fields += ks + encode(stringifyPrimitive(v)); <add> if (i < flast) <add> fields += sep; <ide> } <ide> } <del> return fields.join(sep); <add> return fields; <ide> } <ide> return ''; <ide> }; <ide> QueryString.parse = QueryString.decode = function(qs, sep, eq, options) { <ide> decode = options.decodeURIComponent; <ide> } <ide> <add> var keys = []; <ide> for (var i = 0; i < len; ++i) { <ide> var x = qs[i].replace(regexp, '%20'), <ide> idx = x.indexOf(eq), <del> kstr, vstr, k, v; <add> k, v; <ide> <ide> if (idx >= 0) { <del> kstr = x.substr(0, idx); <del> vstr = x.substr(idx + 1); <add> k = decodeStr(x.substring(0, idx), decode); <add> v = decodeStr(x.substring(idx + 1), decode); <ide> } else { <del> kstr = x; <del> vstr = ''; <add> k = decodeStr(x, decode); <add> v = ''; <ide> } <ide> <del> try { <del> k = decode(kstr); <del> v = decode(vstr); <del> } catch (e) { <del> k = QueryString.unescape(kstr, true); <del> v = QueryString.unescape(vstr, true); <del> } <del> <del> if (!hasOwnProperty(obj, k)) { <add> if (keys.indexOf(k) === -1) { <ide> obj[k] = v; <add> keys.push(k); <ide> } else if (Array.isArray(obj[k])) { <ide> obj[k].push(v); <ide> } else { <ide> QueryString.parse = QueryString.decode = function(qs, sep, eq, options) { <ide> <ide> return obj; <ide> }; <add> <add> <add>function decodeStr(s, decoder) { <add> try { <add> return decoder(s); <add> } catch (e) { <add> return QueryString.unescape(s, true); <add> } <add>}
1
Ruby
Ruby
add a forgotten word
cff0aebbc4e4a3c586066eb289e667de0962aedb
<ide><path>activesupport/lib/active_support/core_ext/object/with_options.rb <ide> class Object <ide> # end <ide> # end <ide> # <del> # It also be used with an explicit receiver: <add> # It can also be used with an explicit receiver: <ide> # <ide> # map.with_options :controller => "people" do |people| <ide> # people.connect "/people", :action => "index"
1
PHP
PHP
add timezone option
97d783449c5330b1e5fb9104f6073869ad3079c1
<ide><path>src/Illuminate/Console/Scheduling/ScheduleListCommand.php <ide> class ScheduleListCommand extends Command <ide> * <ide> * @var string <ide> */ <del> protected $name = 'schedule:list'; <add> protected $signature = 'schedule:list {--timezone= : The timezone that times should be displayed in}'; <ide> <ide> /** <ide> * The console command description. <ide> public function handle(Schedule $schedule) <ide> $event->command, <ide> $event->expression, <ide> $event->description, <del> (new CronExpression($event->expression))->getPreviousRunDate(Carbon::now()), <del> (new CronExpression($event->expression))->getNextRunDate(Carbon::now()), <add> (new CronExpression($event->expression)) <add> ->getNextRunDate(Carbon::now()) <add> ->setTimezone($this->option('timezone', config('app.timezone'))), <ide> ]; <ide> } <ide> <ide> $this->table([ <ide> 'Command', <ide> 'Interval', <ide> 'Description', <del> 'Last Run', <ide> 'Next Due', <ide> ], $rows ?? []); <ide> }
1
Text
Text
update terminology for challenges
b96ebf76634f327177967da6be4a3e887c9d7a5d
<ide><path>docs/how-to-work-on-coding-challenges.md <ide> Before you work on the curriculum, you would need to set up some tooling to help <ide> <ide> ### How to work on practice projects <ide> <del>The practice projects have some additional tooling to help create new projects and steps. To read more, see [these docs](how-to-work-on-practice-projects.md) <add>The practice projects have some additional tooling to help create new projects and steps. To read more, see [these docs](how-to-work-on-practice-projects.md) <add> <ide> ## Challenge Template <ide> <ide> ````md <del> <ide> --- <ide> id: Unique identifier (alphanumerical, MongoDB_id) <ide> title: 'Challenge Title' <ide> forumTopicId: 12345 <ide> Challenge description text, in markdown <ide> <ide> ```html <del><div> <del> example code <del></div> <add><div>example code</div> <ide> ``` <ide> <ide> # --instructions-- <ide> Boilerplate code to render to the editor. This section should only contain code <ide> <ide> ```html <ide> <body> <del> <p class="main-text"> <del> Hello world! <del> </p> <add> <p class="main-text">Hello world!</p> <ide> </body> <ide> ``` <ide> <ide> More answers <ide> ## --video-solution-- <ide> <ide> The number for the correct answer goes here. <del> <del> <ide> ```` <ide> <ide> > [!NOTE] <ide> > <ide> > 1. In the above sections, examples of `lang` are: <ide> > <del>> - `html` - HTML/CSS <del>> - `js` - JavaScript <del>> - `jsx` - JSX <add>> - `html` - HTML/CSS <add>> - `js` - JavaScript <add>> - `jsx` - JSX <ide> <ide> ## Numbering Challenges <ide> <ide> Proper nouns should use correct capitalization when possible. Below is a list of <ide> <ide> - JavaScript (capital letters in "J" and "S" and no abbreviations) <ide> - Node.js <del>- Front-end development (adjective form with a dash) is when you're working on the front end (noun form with no dash). The same goes with "back end", "full stack", and many other compound terms. <add>- Although sometimes inaccurate, non-hyphenated forms of 'back end' and 'front end' should be used, as they are more widely used. <ide> <ide> ### The 2-minute rule <ide> <ide> Here are specific formatting guidelines for challenge text and examples: <ide> <ide> - Language keywords go in `\`` backticks. For example, HTML tag names or CSS property names. <ide> - References to code parts (i.e. function, method, or variable names) should be wrapped in `\`` backticks. See example below: <add> <ide> ```md <ide> Use `parseInt` to convert the variable `realNumber` into an integer. <ide> ``` <add> <ide> - References to file names and path directories (e.g. `package.json`, `src/components`) should be wrapped in `\`` backticks. <ide> - Multi-line code blocks **must be preceded by an empty line**. The next line must start with three backticks followed immediately by one of the [supported languages](https://prismjs.com/#supported-languages). To complete the code block, you must start a new line which only has three backticks and **another empty line**. See example below: <del>- Whitespace matters in Markdown, so we recommend that you make it visible in your editor. <add>- Whitespace matters in Markdown, so we recommend that you make it visible in your editor. <ide> <ide> **Note:** If you are going to use an example code in YAML, use `yaml` instead of `yml` for the language to the right of the backticks. <ide> <ide> The following is an example of code: <add> <ide> ````md <ide> ```{language} <ide> <ide> Here are specific formatting guidelines for the challenge seed code: <ide> <ide> We have a [comment dictionary](/curriculum/dictionaries/english/comments.js) that contains the only comments that can be used within the seed code. The exact case and spacing of the dictionary comment must be used. The comment dictionary should not be expanded without prior discussion with the dev-team. <ide> <del>Comments used should have a space between the comment characters and the comment themselves. In general, comments should be used sparingly. Always consider rewriting a challenge's description or instructions if it could avoid using a seed code comment. <add>Comments used should have a space between the comment characters and the comment themselves. In general, comments should be used sparingly. Always consider rewriting a challenge's description or instructions if it could avoid using a seed code comment. <ide> <ide> Example of valid single line JavaScript comment: <ide> <ide> class MyComponent extends React.Component { <ide> constructor(props) { <ide> super(props); <ide> this.state = { <del> text: "Hello" <add> text: 'Hello' <ide> }; <ide> // Change code below this line <ide> <ide> // Change code above this line <ide> } <ide> handleClick() { <ide> this.setState({ <del> text: "You clicked!" <add> text: 'You clicked!' <ide> }); <ide> } <ide> render() { <ide> return ( <ide> <div> <del> { /* Change code below this line */ } <add> {/* Change code below this line */} <ide> <button>Click Me</button> <del> { /* Change code above this line */ } <add> {/* Change code above this line */} <ide> <h1>{this.state.text}</h1> <ide> </div> <ide> ); <ide> } <del>}; <add>} <ide> ``` <ide> <ide> ### Translation of seed code comments <ide> <del>There are separate comment dictionaries for each language. The [English version of the comment dictionary](/curriculum/dictionaries/english/comments.js) is the basis for the translations found in the corresponding non-English versions of the files. The non-English version of the Chinese comment dictionary would be located at `/curriculum/dictionaries/chinese/comments.js`. Each dictionary consists of an array of objects with a unique `id` property and a `text` property. Only the `text` should be modified to encompass the translation of the corresponding English comment. <add>There are separate comment dictionaries for each language. The [English version of the comment dictionary](/curriculum/dictionaries/english/comments.js) is the basis for the translations found in the corresponding non-English versions of the files. The non-English version of the Chinese comment dictionary would be located at `/curriculum/dictionaries/chinese/comments.js`. Each dictionary consists of an array of objects with a unique `id` property and a `text` property. Only the `text` should be modified to encompass the translation of the corresponding English comment. <ide> <del>Some comments may contain a word/phrase that should not be translated. For example, variable names or proper library names like "React" should not be translated. See the comment below as an example. The word `myGlobal` should not be translated. <add>Some comments may contain a word/phrase that should not be translated. For example, variable names or proper library names like "React" should not be translated. See the comment below as an example. The word `myGlobal` should not be translated. <ide> <ide> ```text <ide> Declare the myGlobal variable below this line <ide> ``` <ide> <del>>[!NOTE] <add>> [!NOTE] <ide> > <ide> > We are working on an integration to make it possible to work on i18n for the comment dictionary. <ide> <ide> function myFunc() { <ide> <ide> ## Testing Challenges <ide> <del>Before you [create a pull request](how-to-open-a-pull-request.md) for your changes, you need to validate that the changes you have made do not inadvertently cause problems with the challenge. <add>Before you [create a pull request](how-to-open-a-pull-request.md) for your changes, you need to validate that the changes you have made do not inadvertently cause problems with the challenge. <ide> <ide> 1. To test all challenges run the below command from the root directory <ide> <ide> ``` <ide> npm run test:curriculum <del>``` <add>``` <ide> <ide> 2. You can also test a block or a superblock of challenges with these commands <ide> <ide> Once you have verified that each challenge you've worked on passes the tests, [p <ide> <ide> > [!TIP] <ide> > You can set the environment variable `LOCALE` in the `.env` to the language of the challenge(s) you need to test. <del>> <add>> <ide> > The currently accepted values are `english` and `chinese`, with `english` being set by default. <ide> <ide> ### Useful Links
1
PHP
PHP
add tests for string properties
d0ebb56c0f293f0f55680187a0fd0be7c55d85f7
<ide><path>src/View/ViewBuilder.php <ide> class ViewBuilder <ide> protected $viewPath; <ide> <ide> /** <del> * The view file to render. <add> * The template file to render. <ide> * <ide> * @var string <ide> */ <del> protected $view; <add> protected $template; <ide> <ide> /** <ide> * The plugin name to use. <ide> class ViewBuilder <ide> * <ide> * @var string <ide> */ <del> protected $viewClass; <add> protected $className; <ide> <ide> /** <ide> * The view variables to use <ide> public function layoutPath($path = null) <ide> * On by default. Setting to off means that layouts will not be <ide> * automatically applied to rendered views. <ide> * <del> * @param bool|ull $autoLayout Boolean to turn on/off. If null returns current value. <add> * @param bool|null $autoLayout Boolean to turn on/off. If null returns current value. <ide> * @return bool|$this <ide> */ <ide> public function autoLayout($autoLayout = null) <ide> public function autoLayout($autoLayout = null) <ide> return $this->autoLayout; <ide> } <ide> <del> $this->autoLayout = $autoLayout; <add> $this->autoLayout = (bool)$autoLayout; <ide> return $this; <ide> } <ide> <ide> public function theme($theme = null) <ide> * @param string|null $name View file name to set. If null returns current name. <ide> * @return string|$this <ide> */ <del> public function view($name = null) <add> public function template($name = null) <ide> { <ide> if ($name === null) { <del> return $this->view; <add> return $this->template; <ide> } <ide> <del> $this->view = $name; <add> $this->template = $name; <ide> return $this; <ide> } <ide> <ide><path>tests/TestCase/View/ViewBuilderTest.php <add><?php <add>/** <add> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <add> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <add> * <add> * Licensed under The MIT License <add> * For full copyright and license information, please see the LICENSE.txt <add> * Redistributions of files must retain the above copyright notice <add> * <add> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <add> * @link http://cakephp.org CakePHP(tm) Project <add> * @since 3.1.0 <add> * @license http://www.opensource.org/licenses/mit-license.php MIT License <add> */ <add>namespace Cake\Test\TestCase\View; <add> <add>use Cake\TestSuite\TestCase; <add>use Cake\View\ViewBuilder; <add> <add>/** <add> * View builder test case. <add> */ <add>class ViewBuilderTest extends TestCase <add>{ <add> /** <add> * data provider for string properties. <add> * <add> * @return array <add> */ <add> public function stringPropertyProvider() <add> { <add> return [ <add> ['layoutPath', 'Admin/'], <add> ['viewPath', 'Admin/'], <add> ['plugin', 'TestPlugin'], <add> ['layout', 'admin'], <add> ['theme', 'TestPlugin'], <add> ['template', 'edit'], <add> ['name', 'Articles'], <add> ['autoLayout', true], <add> ['className', 'Cake\View\JsonView'], <add> ]; <add> } <add> <add> /** <add> * Test string property accessor/mutator methods. <add> * <add> * @dataProvider stringPropertyProvider <add> * @return void <add> */ <add> public function testStringProperties($property, $value) <add> { <add> $builder = new ViewBuilder(); <add> $this->assertNull($builder->{$property}(), 'Default value should be null'); <add> $this->assertSame($builder, $builder->{$property}($value), 'Setter returns this'); <add> $this->assertSame($value, $builder->{$property}(), 'Getter gets value.'); <add> } <add>}
2
Java
Java
fix checkstyle violation
984f9de191b6efad763bf64168ddf40c6377b000
<ide><path>spring-context/src/test/java/example/gh24375/B.java <ide> public @interface B { <ide> <ide> String name() default ""; <del>} <ide>\ No newline at end of file <add>}
1
Python
Python
remove deprecated flask.error_handlers
9491bf8695be9b24036b3d966d9c43b46f0ddc23
<ide><path>flask/app.py <ide> def __init__(self, import_name, static_path=None, static_url_path=None, <ide> #: To register a view function, use the :meth:`route` decorator. <ide> self.view_functions = {} <ide> <del> # support for the now deprecated `error_handlers` attribute. The <del> # :attr:`error_handler_spec` shall be used now. <del> self._error_handlers = {} <del> <ide> #: A dictionary of all registered error handlers. The key is ``None`` <ide> #: for error handlers active on the application, otherwise the key is <ide> #: the name of the blueprint. Each key points to another dictionary <ide> def __init__(self, import_name, static_path=None, static_url_path=None, <ide> #: <ide> #: To register an error handler, use the :meth:`errorhandler` <ide> #: decorator. <del> self.error_handler_spec = {None: self._error_handlers} <add> self.error_handler_spec = {} <ide> <ide> #: A list of functions that are called when :meth:`url_for` raises a <ide> #: :exc:`~werkzeug.routing.BuildError`. Each function registered here <ide> def __init__(self, import_name, static_path=None, static_url_path=None, <ide> #: This is an instance of a :class:`click.Group` object. <ide> self.cli = cli.AppGroup(self.name) <ide> <del> def _get_error_handlers(self): <del> from warnings import warn <del> warn(DeprecationWarning('error_handlers is deprecated, use the ' <del> 'new error_handler_spec attribute instead.'), stacklevel=1) <del> return self._error_handlers <del> def _set_error_handlers(self, value): <del> self._error_handlers = value <del> self.error_handler_spec[None] = value <del> error_handlers = property(_get_error_handlers, _set_error_handlers) <del> del _get_error_handlers, _set_error_handlers <del> <ide> @locked_cached_property <ide> def name(self): <ide> """The name of the application. This is usually the import name
1
Javascript
Javascript
limit selection to #qunit-fixture in attributes.js
ddb2c06f51a20d1da2d444ecda88f9ed64ef2e91
<ide><path>test/unit/attributes.js <ide> QUnit.test( "attr(String, Function)", function( assert ) { <ide> QUnit.test( "attr(Hash)", function( assert ) { <ide> assert.expect( 3 ); <ide> var pass = true; <del> jQuery( "div" ).attr( { <add> <add> jQuery( "#qunit-fixture div" ).attr( { <ide> "foo": "baz", <ide> "zoo": "ping" <ide> } ).each( function() { <ide> QUnit.test( "attr(String, Object)", function( assert ) { <ide> attributeNode, commentNode, textNode, obj, <ide> table, td, j, type, <ide> check, thrown, button, $radio, $radios, $svg, <del> div = jQuery( "div" ).attr( "foo", "bar" ), <add> div = jQuery( "#qunit-fixture div" ).attr( "foo", "bar" ), <ide> i = 0, <ide> fail = false; <ide> <ide> QUnit.test( "attr - extending the boolean attrHandle", function( assert ) { <ide> called = true; <ide> _handle.apply( this, arguments ); <ide> }; <del> jQuery( "input" ).attr( "checked" ); <add> jQuery( "#qunit-fixture input" ).attr( "checked" ); <ide> called = false; <del> jQuery( "input" ).attr( "checked" ); <add> jQuery( "#qunit-fixture input" ).attr( "checked" ); <ide> assert.ok( called, "The boolean attrHandle does not drop custom attrHandles" ); <ide> } ); <ide> <ide> QUnit.test( "val(Function)", function( assert ) { <ide> QUnit.test( "val(Array of Numbers) (Bug #7123)", function( assert ) { <ide> assert.expect( 4 ); <ide> jQuery( "#form" ).append( "<input type='checkbox' name='arrayTest' value='1' /><input type='checkbox' name='arrayTest' value='2' /><input type='checkbox' name='arrayTest' value='3' checked='checked' /><input type='checkbox' name='arrayTest' value='4' />" ); <del> var elements = jQuery( "input[name=arrayTest]" ).val( [ 1, 2 ] ); <add> var elements = jQuery( "#form input[name=arrayTest]" ).val( [ 1, 2 ] ); <ide> assert.ok( elements[ 0 ].checked, "First element was checked" ); <ide> assert.ok( elements[ 1 ].checked, "Second element was checked" ); <ide> assert.ok( !elements[ 2 ].checked, "Third element was unchecked" );
1
Java
Java
fix javadoc formatting issues
9af11ad5ce137e8fe71f0ce9e980745e4c840818
<ide><path>spring-core/src/main/java/org/springframework/core/convert/TypeDescriptor.java <ide> <ide> /** <ide> * Contextual descriptor about a type to convert from or to. <del> * Capable of representing arrays and generic collection types. <add> * <p>Capable of representing arrays and generic collection types. <ide> * <ide> * @author Keith Donald <ide> * @author Andy Clement <ide> public TypeDescriptor getElementTypeDescriptor() { <ide> * from the provided collection or array element. <ide> * <p>Narrows the {@link #getElementTypeDescriptor() elementType} property to the class <ide> * of the provided collection or array element. For example, if this describes a <del> * {@code java.util.List&lt;java.lang.Number&lt;} and the element argument is an <add> * {@code java.util.List<java.lang.Number>} and the element argument is a <ide> * {@code java.lang.Integer}, the returned TypeDescriptor will be {@code java.lang.Integer}. <del> * If this describes a {@code java.util.List&lt;?&gt;} and the element argument is an <add> * If this describes a {@code java.util.List<?>} and the element argument is a <ide> * {@code java.lang.Integer}, the returned TypeDescriptor will be {@code java.lang.Integer} <ide> * as well. <ide> * <p>Annotation and nested type context will be preserved in the narrowed <ide> public TypeDescriptor getMapKeyTypeDescriptor() { <ide> * from the provided map key. <ide> * <p>Narrows the {@link #getMapKeyTypeDescriptor() mapKeyType} property <ide> * to the class of the provided map key. For example, if this describes a <del> * {@code java.util.Map&lt;java.lang.Number, java.lang.String&lt;} and the key <add> * {@code java.util.Map<java.lang.Number, java.lang.String>} and the key <ide> * argument is a {@code java.lang.Integer}, the returned TypeDescriptor will be <del> * {@code java.lang.Integer}. If this describes a {@code java.util.Map&lt;?, ?&gt;} <add> * {@code java.lang.Integer}. If this describes a {@code java.util.Map<?, ?>} <ide> * and the key argument is a {@code java.lang.Integer}, the returned <ide> * TypeDescriptor will be {@code java.lang.Integer} as well. <ide> * <p>Annotation and nested type context will be preserved in the narrowed <ide> public TypeDescriptor getMapValueTypeDescriptor() { <ide> * from the provided map value. <ide> * <p>Narrows the {@link #getMapValueTypeDescriptor() mapValueType} property <ide> * to the class of the provided map value. For example, if this describes a <del> * {@code java.util.Map&lt;java.lang.String, java.lang.Number&lt;} and the value <add> * {@code java.util.Map<java.lang.String, java.lang.Number>} and the value <ide> * argument is a {@code java.lang.Integer}, the returned TypeDescriptor will be <del> * {@code java.lang.Integer}. If this describes a {@code java.util.Map&lt;?, ?&gt;} <add> * {@code java.lang.Integer}. If this describes a {@code java.util.Map<?, ?>} <ide> * and the value argument is a {@code java.lang.Integer}, the returned <ide> * TypeDescriptor will be {@code java.lang.Integer} as well. <ide> * <p>Annotation and nested type context will be preserved in the narrowed <ide><path>spring-expression/src/main/java/org/springframework/expression/TypeConverter.java <ide> /* <del> * Copyright 2002-2017 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 TypeConverter { <ide> * Convert (or coerce) a value from one type to another, for example from a <ide> * {@code boolean} to a {@code String}. <ide> * <p>The {@link TypeDescriptor} parameters enable support for typed collections: <del> * A caller may prefer a {@code List&lt;Integer&gt;}, for example, rather than <add> * A caller may prefer a {@code List<Integer>}, for example, rather than <ide> * simply any {@code List}. <ide> * @param value the value to be converted <ide> * @param sourceType a type descriptor that supplies extra information about the
2
Javascript
Javascript
limit lint rule disabling in message test
7e0410499d8816d67737c7232a898e8d67925b3b
<ide><path>test/message/nexttick_throw.js <ide> process.nextTick(function() { <ide> process.nextTick(function() { <ide> process.nextTick(function() { <ide> process.nextTick(function() { <del> // eslint-disable-next-line <add> // eslint-disable-next-line no-undef <ide> undefined_reference_error_maker; <ide> }); <ide> });
1
Text
Text
add french translation
8b54e19b84b163a93c8f53c54de02eb18f2ff788
<ide><path>threejs/lessons/fr/threejs-materials.md <del>Title: Les Matériaux dans Three.js <del>Description: Les Matériaux dans Three.js <del>TOC: Matériaux <add>Title: Les Materials de Three.js <add>Description: Les Materials dans Three.js <add>TOC: Materials <ide> <ide> Cet article fait partie d'une série consacrée à Three.js. <ide> Le premier article s'intitule [Principes de base](threejs-fundamentals.html).
1
Java
Java
break dependency between testcompiler and aot
4625e92eb86899f83513a9202d090b137a04f0e8
<ide><path>spring-aop/src/test/java/org/springframework/aop/scope/ScopedProxyBeanRegistrationAotProcessorTests.java <ide> private void compile(BiConsumer<DefaultListableBeanFactory, Compiled> result) { <ide> .build()); <ide> }); <ide> this.generationContext.writeGeneratedContent(); <del> TestCompiler.forSystem().withFiles(this.generationContext.getGeneratedFiles()).compile(compiled -> { <add> TestCompiler.forSystem().with(this.generationContext).compile(compiled -> { <ide> DefaultListableBeanFactory freshBeanFactory = new DefaultListableBeanFactory(); <ide> freshBeanFactory.setBeanClassLoader(compiled.getClassLoader()); <ide> compiled.getInstance(Consumer.class).accept(freshBeanFactory); <ide><path>spring-beans/src/test/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanRegistrationAotContributionTests.java <ide> private void compile(RegisteredBean registeredBean, <ide> <ide> }); <ide> this.generationContext.writeGeneratedContent(); <del> TestCompiler.forSystem().withFiles(this.generationContext.getGeneratedFiles()).compile(compiled -> <add> TestCompiler.forSystem().with(this.generationContext).compile(compiled -> <ide> result.accept(compiled.getInstance(BiFunction.class), compiled)); <ide> } <ide> <ide><path>spring-beans/src/test/java/org/springframework/beans/factory/aot/BeanDefinitionMethodGeneratorTests.java <ide> private void compile(MethodReference method, <ide> .addCode("return $L;", methodInvocation).build()); <ide> }); <ide> this.generationContext.writeGeneratedContent(); <del> TestCompiler.forSystem().withFiles(this.generationContext.getGeneratedFiles()).compile(compiled -> <add> TestCompiler.forSystem().with(this.generationContext).compile(compiled -> <ide> result.accept((RootBeanDefinition) compiled.getInstance(Supplier.class).get(), compiled)); <ide> } <ide> <ide><path>spring-beans/src/test/java/org/springframework/beans/factory/aot/BeanDefinitionPropertiesCodeGeneratorTests.java <ide> private void compile( <ide> .addStatement("return beanDefinition").build()); <ide> }); <ide> this.generationContext.writeGeneratedContent(); <del> TestCompiler.forSystem().withFiles(this.generationContext.getGeneratedFiles()).compile(compiled -> { <add> TestCompiler.forSystem().with(this.generationContext).compile(compiled -> { <ide> RootBeanDefinition suppliedBeanDefinition = (RootBeanDefinition) compiled <ide> .getInstance(Supplier.class).get(); <ide> result.accept(suppliedBeanDefinition, compiled); <ide><path>spring-beans/src/test/java/org/springframework/beans/factory/aot/BeanDefinitionPropertyValueCodeGeneratorTests.java <ide> private void compile(Object value, BiConsumer<Object, Compiled> result) { <ide> .returns(Object.class).addStatement("return $L", generatedCode).build()); <ide> }); <ide> generationContext.writeGeneratedContent(); <del> TestCompiler.forSystem().withFiles(generationContext.getGeneratedFiles()).compile(compiled -> <add> TestCompiler.forSystem().with(generationContext).compile(compiled -> <ide> result.accept(compiled.getInstance(Supplier.class).get(), compiled)); <ide> } <ide> <ide><path>spring-beans/src/test/java/org/springframework/beans/factory/aot/BeanRegistrationsAotContributionTests.java <ide> private void compile( <ide> .build()); <ide> }); <ide> this.generationContext.writeGeneratedContent(); <del> TestCompiler.forSystem().withFiles(this.generationContext.getGeneratedFiles()).compile(compiled -> <add> TestCompiler.forSystem().with(this.generationContext).compile(compiled -> <ide> result.accept(compiled.getInstance(Consumer.class), compiled)); <ide> } <ide> <ide><path>spring-beans/src/test/java/org/springframework/beans/factory/aot/InstanceSupplierCodeGeneratorTests.java <ide> private void compile(DefaultListableBeanFactory beanFactory, <ide> .addStatement("return $L", generatedCode).build()); <ide> }); <ide> this.generationContext.writeGeneratedContent(); <del> TestCompiler.forSystem().withFiles(this.generationContext.getGeneratedFiles()).compile(compiled -> <add> TestCompiler.forSystem().with(this.generationContext).compile(compiled -> <ide> result.accept((InstanceSupplier<?>) compiled.getInstance(Supplier.class).get(), compiled)); <ide> } <ide> <ide><path>spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostProcessorAotContributionTests.java <ide> private void compile(BiConsumer<Consumer<DefaultListableBeanFactory>, Compiled> <ide> .build()); <ide> }); <ide> generationContext.writeGeneratedContent(); <del> TestCompiler.forSystem().withFiles(generationContext.getGeneratedFiles()).compile(compiled -> <add> TestCompiler.forSystem().with(generationContext).compile(compiled -> <ide> result.accept(compiled.getInstance(Consumer.class), compiled)); <ide> } <ide> <ide> private void compile(BiConsumer<Consumer<GenericApplicationContext>, Compiled> r <ide> .build()); <ide> }); <ide> generationContext.writeGeneratedContent(); <del> TestCompiler.forSystem().withFiles(generationContext.getGeneratedFiles()).compile(compiled -> <add> TestCompiler.forSystem().with(generationContext).compile(compiled -> <ide> result.accept(compiled.getInstance(Consumer.class), compiled)); <ide> } <ide> <ide><path>spring-context/src/test/java/org/springframework/context/aot/ApplicationContextAotGeneratorTests.java <ide> private void testCompiledResult(GenericApplicationContext applicationContext, <ide> @SuppressWarnings({ "rawtypes", "unchecked" }) <ide> private void testCompiledResult(TestGenerationContext generationContext, <ide> BiConsumer<ApplicationContextInitializer<GenericApplicationContext>, Compiled> result) { <del> TestCompiler.forSystem().withFiles(generationContext.getGeneratedFiles()).compile(compiled -> <add> TestCompiler.forSystem().with(generationContext).compile(compiled -> <ide> result.accept(compiled.getInstance(ApplicationContextInitializer.class), compiled)); <ide> } <ide> <ide><path>spring-context/src/test/java/org/springframework/context/generator/ApplicationContextAotGeneratorRuntimeHintsTests.java <ide> private void compile(GenericApplicationContext applicationContext, BiConsumer<Ru <ide> TestGenerationContext generationContext = new TestGenerationContext(); <ide> generator.processAheadOfTime(applicationContext, generationContext); <ide> generationContext.writeGeneratedContent(); <del> TestCompiler.forSystem().withFiles(generationContext.getGeneratedFiles()).compile(compiled -> { <add> TestCompiler.forSystem().with(generationContext).compile(compiled -> { <ide> ApplicationContextInitializer instance = compiled.getInstance(ApplicationContextInitializer.class); <ide> GenericApplicationContext freshContext = new GenericApplicationContext(); <ide> RuntimeHintsInvocations recordedInvocations = RuntimeHintsRecorder.record(() -> { <ide><path>spring-core-test/src/main/java/org/springframework/aot/test/generate/GeneratedFilesTestCompilerUtils.java <add>/* <add> * Copyright 2002-2022 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * https://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.aot.test.generate; <add> <add>import java.util.ArrayList; <add>import java.util.List; <add> <add>import org.springframework.aot.generate.GeneratedFiles.Kind; <add>import org.springframework.aot.generate.InMemoryGeneratedFiles; <add>import org.springframework.core.test.tools.ClassFile; <add>import org.springframework.core.test.tools.ResourceFile; <add>import org.springframework.core.test.tools.SourceFile; <add>import org.springframework.core.test.tools.TestCompiler; <add> <add>/** <add> * {@link TestCompiler} utilities for generated files. <add> * <add> * @author Stephane Nicoll <add> * @since 6.0 <add> */ <add>public abstract class GeneratedFilesTestCompilerUtils { <add> <add> /** <add> * Apply the specified {@link InMemoryGeneratedFiles} to the specified {@link TestCompiler}. <add> * @param testCompiler the compiler to configure <add> * @param generatedFiles the generated files to apply <add> * @return a new {@link TestCompiler} instance configured with the generated files <add> */ <add> public static TestCompiler configure(TestCompiler testCompiler, InMemoryGeneratedFiles generatedFiles) { <add> List<SourceFile> sourceFiles = new ArrayList<>(); <add> generatedFiles.getGeneratedFiles(Kind.SOURCE).forEach( <add> (path, inputStreamSource) -> sourceFiles.add(SourceFile.of(inputStreamSource))); <add> List<ResourceFile> resourceFiles = new ArrayList<>(); <add> generatedFiles.getGeneratedFiles(Kind.RESOURCE).forEach( <add> (path, inputStreamSource) -> resourceFiles.add(ResourceFile.of(path, inputStreamSource))); <add> List<ClassFile> classFiles = new ArrayList<>(); <add> generatedFiles.getGeneratedFiles(Kind.CLASS).forEach( <add> (path, inputStreamSource) -> classFiles.add(ClassFile.of( <add> ClassFile.toClassName(path), inputStreamSource))); <add> return testCompiler.withSources(sourceFiles).withResources(resourceFiles).withClasses(classFiles); <add> } <add>} <ide><path>spring-core-test/src/main/java/org/springframework/aot/test/generate/TestGenerationContext.java <ide> <ide> package org.springframework.aot.test.generate; <ide> <add>import java.util.function.Function; <add> <ide> import org.springframework.aot.generate.ClassNameGenerator; <ide> import org.springframework.aot.generate.DefaultGenerationContext; <ide> import org.springframework.aot.generate.GenerationContext; <ide> import org.springframework.aot.generate.InMemoryGeneratedFiles; <add>import org.springframework.core.test.tools.TestCompiler; <ide> <ide> /** <ide> * {@link GenerationContext} test implementation that uses <del> * {@link InMemoryGeneratedFiles}. <add> * {@link InMemoryGeneratedFiles} and can configure a {@link TestCompiler} <add> * instance. <ide> * <ide> * @author Stephane Nicoll <ide> * @author Sam Brannen <ide> * @since 6.0 <ide> */ <del>public class TestGenerationContext extends DefaultGenerationContext { <add>public class TestGenerationContext extends DefaultGenerationContext implements Function<TestCompiler, TestCompiler> { <ide> <ide> /** <ide> * Create an instance using the specified {@link ClassNameGenerator}. <ide> public InMemoryGeneratedFiles getGeneratedFiles() { <ide> return (InMemoryGeneratedFiles) super.getGeneratedFiles(); <ide> } <ide> <add> /** <add> * Configure the specified {@link TestCompiler} with the state of this context. <add> * @param testCompiler the compiler to configure <add> * @return a new {@link TestCompiler} instance configured with the generated files <add> * @see TestCompiler#with(Function) <add> */ <add> @Override <add> public TestCompiler apply(TestCompiler testCompiler) { <add> return GeneratedFilesTestCompilerUtils.configure(testCompiler, getGeneratedFiles()); <add> } <add> <ide> } <ide><path>spring-core-test/src/main/java/org/springframework/core/test/tools/TestCompiler.java <ide> import java.util.List; <ide> import java.util.Locale; <ide> import java.util.function.Consumer; <add>import java.util.function.Function; <ide> <ide> import javax.annotation.processing.Processor; <ide> import javax.tools.Diagnostic; <ide> import javax.tools.StandardJavaFileManager; <ide> import javax.tools.ToolProvider; <ide> <del>import org.springframework.aot.generate.GeneratedFiles.Kind; <del>import org.springframework.aot.generate.InMemoryGeneratedFiles; <ide> import org.springframework.lang.Nullable; <ide> <ide> /** <ide> public static TestCompiler forCompiler(JavaCompiler javaCompiler) { <ide> } <ide> <ide> /** <del> * Create a new {@code TestCompiler} instance with additional generated <del> * source, resource, and class files. <del> * @param generatedFiles the generated files to add <del> * @return a new {@code TestCompiler} instance <add> * Apply customization to this compiler. <add> * @param customizer the customizer to call <add> * @return a new {@code TestCompiler} instance with the customizations applied <ide> */ <del> public TestCompiler withFiles(InMemoryGeneratedFiles generatedFiles) { <del> List<SourceFile> sourceFiles = new ArrayList<>(); <del> generatedFiles.getGeneratedFiles(Kind.SOURCE).forEach( <del> (path, inputStreamSource) -> sourceFiles.add(SourceFile.of(inputStreamSource))); <del> List<ResourceFile> resourceFiles = new ArrayList<>(); <del> generatedFiles.getGeneratedFiles(Kind.RESOURCE).forEach( <del> (path, inputStreamSource) -> resourceFiles.add(ResourceFile.of(path, inputStreamSource))); <del> List<ClassFile> classFiles = new ArrayList<>(); <del> generatedFiles.getGeneratedFiles(Kind.CLASS).forEach( <del> (path, inputStreamSource) -> classFiles.add(ClassFile.of( <del> ClassFile.toClassName(path), inputStreamSource))); <del> return withSources(sourceFiles).withResources(resourceFiles).withClasses(classFiles); <add> public TestCompiler with(Function<TestCompiler, TestCompiler> customizer) { <add> return customizer.apply(this); <ide> } <ide> <ide> /** <ide><path>spring-orm/src/test/java/org/springframework/orm/jpa/persistenceunit/PersistenceManagedTypesBeanRegistrationAotProcessorTests.java <ide> private void compile(GenericApplicationContext applicationContext, <ide> TestGenerationContext generationContext = new TestGenerationContext(); <ide> generator.processAheadOfTime(applicationContext, generationContext); <ide> generationContext.writeGeneratedContent(); <del> TestCompiler.forSystem().withFiles(generationContext.getGeneratedFiles()).compile(compiled -> <add> TestCompiler.forSystem().with(generationContext).compile(compiled -> <ide> result.accept(compiled.getInstance(ApplicationContextInitializer.class), compiled)); <ide> } <ide> <ide><path>spring-orm/src/test/java/org/springframework/orm/jpa/support/PersistenceAnnotationBeanPostProcessorAotContributionTests.java <ide> private void testCompile(RegisteredBean registeredBean, <ide> BeanRegistrationCode beanRegistrationCode = mock(BeanRegistrationCode.class); <ide> contribution.applyTo(generationContext, beanRegistrationCode); <ide> generationContext.writeGeneratedContent(); <del> TestCompiler.forSystem().withFiles(generationContext.getGeneratedFiles()) <add> TestCompiler.forSystem().with(generationContext) <ide> .compile(compiled -> result.accept(new Invoker(compiled), compiled)); <ide> } <ide> <ide><path>spring-test/src/test/java/org/springframework/test/context/aot/AotIntegrationTests.java <ide> import java.nio.file.Paths; <ide> import java.util.List; <ide> import java.util.Set; <add>import java.util.function.Function; <ide> import java.util.stream.Stream; <ide> <ide> import org.junit.jupiter.api.Disabled; <ide> import org.springframework.aot.AotDetector; <ide> import org.springframework.aot.generate.GeneratedFiles.Kind; <ide> import org.springframework.aot.generate.InMemoryGeneratedFiles; <add>import org.springframework.aot.test.generate.GeneratedFilesTestCompilerUtils; <ide> import org.springframework.core.test.tools.CompileWithForkedClassLoader; <ide> import org.springframework.core.test.tools.TestCompiler; <ide> import org.springframework.test.context.aot.samples.basic.BasicSpringJupiterSharedConfigTests; <ide> void endToEndTests() { <ide> assertThat(sourceFiles).containsExactlyInAnyOrder(expectedSourceFilesForBasicSpringTests); <ide> <ide> // AOT BUILD-TIME: COMPILATION <del> TestCompiler.forSystem().withFiles(generatedFiles) <add> TestCompiler.forSystem().with(setupGeneratedFiles(generatedFiles)) <ide> // .printFiles(System.out) <ide> .compile(compiled -> <ide> // AOT RUN-TIME: EXECUTION <ide> void endToEndTestsForEntireSpringTestModule() { <ide> generator.processAheadOfTime(testClasses.stream()); <ide> <ide> // AOT BUILD-TIME: COMPILATION <del> TestCompiler.forSystem().withFiles(generatedFiles) <add> TestCompiler.forSystem().with(setupGeneratedFiles(generatedFiles)) <ide> // .printFiles(System.out) <ide> .compile(compiled -> <ide> // AOT RUN-TIME: EXECUTION <ide> runTestsInAotMode(testClasses)); <ide> } <ide> <add> private static Function<TestCompiler, TestCompiler> setupGeneratedFiles(InMemoryGeneratedFiles generatedFiles) { <add> return testCompiler -> GeneratedFilesTestCompilerUtils.configure(testCompiler, generatedFiles); <add> } <add> <ide> private static void runTestsInAotMode(List<Class<?>> testClasses) { <ide> runTestsInAotMode(-1, testClasses); <ide> } <ide><path>spring-test/src/test/java/org/springframework/test/context/aot/TestContextAotGeneratorTests.java <ide> import java.util.ArrayList; <ide> import java.util.List; <ide> import java.util.Set; <add>import java.util.function.Function; <ide> import java.util.stream.Stream; <ide> <ide> import javax.sql.DataSource; <ide> import org.springframework.aot.hint.MemberCategory; <ide> import org.springframework.aot.hint.RuntimeHints; <ide> import org.springframework.aot.hint.TypeReference; <add>import org.springframework.aot.test.generate.GeneratedFilesTestCompilerUtils; <ide> import org.springframework.context.ApplicationContext; <ide> import org.springframework.context.ApplicationContextInitializer; <ide> import org.springframework.context.ConfigurableApplicationContext; <ide> @CompileWithForkedClassLoader <ide> class TestContextAotGeneratorTests extends AbstractAotTests { <ide> <add> private static Function<TestCompiler, TestCompiler> setupGeneratedFiles(InMemoryGeneratedFiles generatedFiles) { <add> return testCompiler -> GeneratedFilesTestCompilerUtils.configure(testCompiler, generatedFiles); <add> } <add> <ide> /** <ide> * End-to-end tests within the scope of the {@link TestContextAotGenerator}. <ide> * <ide> void endToEndTests() { <ide> List<String> sourceFiles = generatedFiles.getGeneratedFiles(Kind.SOURCE).keySet().stream().toList(); <ide> assertThat(sourceFiles).containsExactlyInAnyOrder(expectedSourceFiles); <ide> <del> TestCompiler.forSystem().withFiles(generatedFiles).compile(ThrowingConsumer.of(compiled -> { <add> TestCompiler.forSystem().with(setupGeneratedFiles(generatedFiles)).compile(ThrowingConsumer.of(compiled -> { <ide> try { <ide> System.setProperty(AotDetector.AOT_ENABLED, "true"); <ide> AotTestAttributesFactory.reset(); <ide> private void processAheadOfTime(Set<Class<?>> testClasses, ThrowingConsumer<Appl <ide> InMemoryGeneratedFiles generatedFiles = new InMemoryGeneratedFiles(); <ide> TestContextAotGenerator generator = new TestContextAotGenerator(generatedFiles); <ide> List<Mapping> mappings = processAheadOfTime(generator, testClasses); <del> TestCompiler.forSystem().withFiles(generatedFiles).compile(ThrowingConsumer.of(compiled -> { <add> TestCompiler.forSystem().with(setupGeneratedFiles(generatedFiles)).compile(ThrowingConsumer.of(compiled -> { <ide> for (Mapping mapping : mappings) { <ide> MergedContextConfiguration mergedConfig = mapping.mergedConfig(); <ide> ApplicationContextInitializer<ConfigurableApplicationContext> contextInitializer =
17
Python
Python
remove invalid part of r_ docstring
7af974d6b24945f2e4f31c42781a89cc168d6dfa
<ide><path>numpy/lib/index_tricks.py <ide> def __init__(self): <ide> <ide> class c_class(concatenator): <ide> """Translates slice objects to concatenation along the second axis. <del> <del> This is equivalent to r_['-1,2,0',...] <ide> """ <ide> def __init__(self): <ide> concatenator.__init__(self, -1, ndmin=2, trans1d=0)
1
Ruby
Ruby
note the ways #match may be called
007c41100b06db53630ce60048eaa625a9e955ee
<ide><path>actionpack/lib/action_dispatch/routing/mapper.rb <ide> def shallow? <ide> parent_resource.instance_of?(Resource) && @scope[:shallow] <ide> end <ide> <add> # match 'path' => 'controller#action' <add> # match 'path', as: 'controller#action' <add> # match 'path', 'otherpath', on: :member, via: :get <ide> def match(path, *rest) <ide> if rest.empty? && Hash === path <ide> options = path
1
Ruby
Ruby
stringify the parameters on follow_redirect
65f834ad45b2221fd442acc3c38fb2f750521a18
<ide><path>actionpack/lib/action_controller/test_process.rb <ide> def follow_redirect <ide> raise "Can't follow redirects outside of current controller (#{@response.redirected_to[:controller]})" <ide> end <ide> <del> get(@response.redirected_to.delete(:action), @response.redirected_to) <add> get(@response.redirected_to.delete(:action), @response.redirected_to.stringify_keys) <ide> end <ide> end <ide> end <ide><path>actionpack/test/controller/action_pack_assertions_test.rb <ide> def hello_xml_world() render "test/hello_xml_world"; end <ide> # a redirect to an internal location <ide> def redirect_internal() redirect_to "nothing"; end <ide> <del> def redirect_to_action() redirect_to :action => "flash_me"; end <add> def redirect_to_action() redirect_to :action => "flash_me", :id => 1, :params => { "panda" => "fun" }; end <ide> <ide> def redirect_to_controller() redirect_to :controller => "elsewhere", :action => "flash_me"; end <ide> <ide> def test_follow_redirect <ide> assert_redirected_to :action => "flash_me" <ide> <ide> follow_redirect <add> assert_equal 1, @request.parameters["id"] <add> <ide> assert "Inconceivable!", @response.body <ide> end <ide>
2
Javascript
Javascript
fix purerender test to use providesmodule
bb0fc28facaf4bb282a0ba98d7f366bd4840bbb0
<ide><path>src/addons/__tests__/ReactComponentWithPureRenderMixin-test.js <ide> describe('ReactComponentWithPureRenderMixin', function() { <ide> React = require('React'); <ide> ReactComponentWithPureRenderMixin = <ide> require('ReactComponentWithPureRenderMixin'); <del> ReactTestUtils = require("../../ReactTestUtils"); <add> ReactTestUtils = require('ReactTestUtils'); <ide> }); <ide> <ide> it('provides a default shouldComponentUpdate implementation', function() {
1
PHP
PHP
move time concatenation up one line
2fa9423eba89d63e5b0a18c48fcf90807009f42c
<ide><path>Cake/Utility/Time.php <ide> public static function niceShort($dateString = null, $timezone = null) { <ide> public static function daysAsSql($begin, $end, $fieldName, $timezone = null) { <ide> $dateTime = new \DateTime; <ide> $begin = $dateTime->setTimestamp(static::fromString($begin, $timezone)) <del> ->format('Y-m-d') <del> . ' 00:00:00'; <add> ->format('Y-m-d') . ' 00:00:00'; <ide> $end = $dateTime->setTimestamp(static::fromString($end, $timezone)) <ide> ->format('Y-m-d') . ' 23:59:59'; <ide>
1
Java
Java
ignore null locale in mockhttpservletresponse
c19b2851f190d192b97ce1131e2db49636811578
<ide><path>spring-test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.java <ide> public void reset() { <ide> <ide> @Override <ide> public void setLocale(Locale locale) { <add> if (locale == null) { <add> return; <add> } <ide> this.locale = locale; <ide> doAddHeaderValue(HttpHeaders.CONTENT_LANGUAGE, locale.toLanguageTag(), true); <ide> } <ide><path>spring-test/src/test/java/org/springframework/mock/web/MockHttpServletResponseTests.java <ide> void setHeaderWithNullValue(String headerName) { <ide> assertThat(response.containsHeader(headerName)).isFalse(); <ide> } <ide> <add> @Test // gh-26493 <add> void setLocaleWithNullValue() { <add> assertThat(response.getLocale()).isEqualTo(Locale.getDefault()); <add> response.setLocale(null); <add> assertThat(response.getLocale()).isEqualTo(Locale.getDefault()); <add> } <add> <ide> @Test <ide> void setContentType() { <ide> String contentType = "test/plain"; <ide><path>spring-web/src/testFixtures/java/org/springframework/web/testfixture/servlet/MockHttpServletResponse.java <ide> public void reset() { <ide> <ide> @Override <ide> public void setLocale(Locale locale) { <add> if (locale == null) { <add> return; <add> } <ide> this.locale = locale; <ide> doAddHeaderValue(HttpHeaders.CONTENT_LANGUAGE, locale.toLanguageTag(), true); <ide> }
3
PHP
PHP
allow passing of data to the view
c3c789b35fb0c3673a48dc400dd5cc4688776cb4
<ide><path>src/Illuminate/Routing/Router.php <ide> public function redirect($uri, $destination, $status = 301) <ide> * <ide> * @param string $uri <ide> * @param string $view <add> * @param array $data <ide> * @return \Illuminate\Routing\Route <ide> */ <del> public function view($uri, $view) <add> public function view($uri, $view, $data = []) <ide> { <ide> return $this->get($uri, '\Illuminate\Routing\ViewController') <del> ->defaults('view', $view); <add> ->defaults('view', $view) <add> ->defaults('data', $data); <ide> } <ide> <ide> /** <ide><path>src/Illuminate/Routing/ViewController.php <ide> public function __construct(ViewFactory $view) <ide> * Invoke the controller method. <ide> * <ide> * @param string $view <add> * @param array $data <ide> * @return \Illuminate\Contracts\View\View <ide> */ <del> public function __invoke($view) <add> public function __invoke($view, $data) <ide> { <del> return $this->view->make($view); <add> return $this->view->make($view, $data); <ide> } <ide> } <ide><path>tests/Routing/RoutingRouteTest.php <ide> public function testRouteView() <ide> { <ide> $container = new Container; <ide> $factory = m::mock('Illuminate\View\Factory'); <del> $factory->shouldReceive('make')->once()->with('pages.contact')->andReturn('Contact us'); <add> $factory->shouldReceive('make')->once()->with('pages.contact', ['foo' => 'bar'])->andReturn('Contact us'); <ide> $router = new Router(new Dispatcher, $container); <ide> $container->bind(ViewFactory::class, function () use ($factory) { <ide> return $factory; <ide> public function testRouteView() <ide> return $router; <ide> }); <ide> <del> $router->view('contact', 'pages.contact'); <add> $router->view('contact', 'pages.contact', ['foo' => 'bar']); <ide> <ide> $this->assertEquals('Contact us', $router->dispatch(Request::create('contact', 'GET'))->getContent()); <ide> }
3
PHP
PHP
remove usage of requestactiontrait
87480bce91f8f32abda51e340c0ae39507bda9c1
<ide><path>src/Controller/Controller.php <ide> use Cake\Http\ServerRequest; <ide> use Cake\Log\LogTrait; <ide> use Cake\ORM\Locator\LocatorAwareTrait; <del>use Cake\Routing\RequestActionTrait; <ide> use Cake\Routing\Router; <ide> use Cake\View\ViewVarsTrait; <ide> use LogicException; <ide> class Controller implements EventListenerInterface, EventDispatcherInterface <ide> use LocatorAwareTrait; <ide> use LogTrait; <ide> use ModelAwareTrait; <del> use RequestActionTrait; <ide> use ViewVarsTrait; <ide> <ide> /** <ide><path>src/View/View.php <ide> use Cake\Http\Response; <ide> use Cake\Http\ServerRequest; <ide> use Cake\Log\LogTrait; <del>use Cake\Routing\RequestActionTrait; <ide> use Cake\Routing\Router; <ide> use Cake\Utility\Inflector; <ide> use Cake\View\Exception\MissingElementException; <ide> class View implements EventDispatcherInterface <ide> } <ide> use EventDispatcherTrait; <ide> use LogTrait; <del> use RequestActionTrait; <ide> use ViewVarsTrait; <ide> <ide> /**
2
Mixed
Python
add equated_monthly_installments.py in financials
db5aa1d18890439e4108fa416679dbab5859f30c
<ide><path>DIRECTORY.md <ide> <ide> ## Financial <ide> * [Interest](https://github.com/TheAlgorithms/Python/blob/master/financial/interest.py) <add> * [EMI Calculation](https://github.com/TheAlgorithms/Python/blob/master/financial/equated_monthly_installments.py) <ide> <ide> ## Fractals <ide> * [Julia Sets](https://github.com/TheAlgorithms/Python/blob/master/fractals/julia_sets.py) <ide><path>financial/equated_monthly_installments.py <add>""" <add>Program to calculate the amortization amount per month, given <add>- Principal borrowed <add>- Rate of interest per annum <add>- Years to repay the loan <add> <add>Wikipedia Reference: https://en.wikipedia.org/wiki/Equated_monthly_installment <add>""" <add> <add> <add>def equated_monthly_installments( <add> principal: float, rate_per_annum: float, years_to_repay: int <add>) -> float: <add> """ <add> Formula for amortization amount per month: <add> A = p * r * (1 + r)^n / ((1 + r)^n - 1) <add> where p is the principal, r is the rate of interest per month <add> and n is the number of payments <add> <add> >>> equated_monthly_installments(25000, 0.12, 3) <add> 830.3577453212793 <add> >>> equated_monthly_installments(25000, 0.12, 10) <add> 358.67737100646826 <add> >>> equated_monthly_installments(0, 0.12, 3) <add> Traceback (most recent call last): <add> ... <add> Exception: Principal borrowed must be > 0 <add> >>> equated_monthly_installments(25000, -1, 3) <add> Traceback (most recent call last): <add> ... <add> Exception: Rate of interest must be >= 0 <add> >>> equated_monthly_installments(25000, 0.12, 0) <add> Traceback (most recent call last): <add> ... <add> Exception: Years to repay must be an integer > 0 <add> """ <add> if principal <= 0: <add> raise Exception("Principal borrowed must be > 0") <add> if rate_per_annum < 0: <add> raise Exception("Rate of interest must be >= 0") <add> if years_to_repay <= 0 or not isinstance(years_to_repay, int): <add> raise Exception("Years to repay must be an integer > 0") <add> <add> # Yearly rate is divided by 12 to get monthly rate <add> rate_per_month = rate_per_annum / 12 <add> <add> # Years to repay is multiplied by 12 to get number of payments as payment is monthly <add> number_of_payments = years_to_repay * 12 <add> <add> return ( <add> principal <add> * rate_per_month <add> * (1 + rate_per_month) ** number_of_payments <add> / ((1 + rate_per_month) ** number_of_payments - 1) <add> ) <add> <add> <add>if __name__ == "__main__": <add> import doctest <add> <add> doctest.testmod()
2
Go
Go
add [] and move errors to stderr
4107701062bc729d06e1729e2b4c8c92b3b8b4f2
<ide><path>commands.go <ide> func (cli *DockerCli) CmdStop(args ...string) error { <ide> for _, name := range cmd.Args() { <ide> _, _, err := cli.call("POST", "/containers/"+name+"/stop?"+v.Encode(), nil) <ide> if err != nil { <del> fmt.Printf("%s", err) <add> fmt.Fprintf(os.Stderr, "%s", err) <ide> } else { <ide> fmt.Println(name) <ide> } <ide> func (cli *DockerCli) CmdRestart(args ...string) error { <ide> for _, name := range cmd.Args() { <ide> _, _, err := cli.call("POST", "/containers/"+name+"/restart?"+v.Encode(), nil) <ide> if err != nil { <del> fmt.Printf("%s", err) <add> fmt.Fprintf(os.Stderr, "%s", err) <ide> } else { <ide> fmt.Println(name) <ide> } <ide> func (cli *DockerCli) CmdStart(args ...string) error { <ide> for _, name := range args { <ide> _, _, err := cli.call("POST", "/containers/"+name+"/start", nil) <ide> if err != nil { <del> fmt.Printf("%s", err) <add> fmt.Fprintf(os.Stderr, "%s", err) <ide> } else { <ide> fmt.Println(name) <ide> } <ide> func (cli *DockerCli) CmdInspect(args ...string) error { <ide> cmd.Usage() <ide> return nil <ide> } <del> <del> for _, name := range args { <add> fmt.Printf("[") <add> for i, name := range args { <add> if i > 0 { <add> fmt.Printf(",") <add> } <ide> obj, _, err := cli.call("GET", "/containers/"+name+"/json", nil) <ide> if err != nil { <ide> obj, _, err = cli.call("GET", "/images/"+name+"/json", nil) <ide> if err != nil { <del> fmt.Printf("%s", err) <add> fmt.Fprintf(os.Stderr, "%s", err) <ide> continue <ide> } <ide> } <ide> <ide> indented := new(bytes.Buffer) <ide> if err = json.Indent(indented, obj, "", " "); err != nil { <del> fmt.Printf("%s", err) <add> fmt.Fprintf(os.Stderr, "%s", err) <ide> continue <ide> } <ide> if _, err := io.Copy(os.Stdout, indented); err != nil { <del> fmt.Printf("%s", err) <add> fmt.Fprintf(os.Stderr, "%s", err) <ide> } <ide> } <add> fmt.Printf("]") <ide> return nil <ide> } <ide>
1
Javascript
Javascript
improve removeparentmodulesplugin performance
4daaf6cd3308cfd0331f43ccbf686602b3603f3d
<ide><path>lib/optimize/RemoveParentModulesPlugin.js <ide> class RemoveParentModulesPlugin { <ide> compiler.hooks.compilation.tap("RemoveParentModulesPlugin", compilation => { <ide> const handler = (chunks, chunkGroups) => { <ide> const queue = new Queue(); <del> const availableModulesMap = new Map(); <add> const availableModulesMap = new WeakMap(); <ide> <ide> for (const chunkGroup of compilation.entrypoints.values()) { <ide> // initialize available modules for chunks without parents <ide> class RemoveParentModulesPlugin { <ide> chunkGroup => availableModulesMap.get(chunkGroup) <ide> ); <ide> if (availableModulesSets.some(s => s === undefined)) continue; // No info about this chunk group <del> const availableModules = intersect(availableModulesSets); <add> const availableModules = <add> availableModulesSets.length === 1 <add> ? availableModulesSets[0] <add> : intersect(availableModulesSets); <ide> const numberOfModules = chunk.getNumberOfModules(); <ide> const toRemove = new Set(); <ide> if (numberOfModules < availableModules.size) {
1
PHP
PHP
remove unused code and remove strict type checks
2f799961404ed7fda48fbdbca15df08d15a86f0b
<ide><path>lib/Cake/View/Helper/FormHelper.php <ide> public function dateTime($fieldName, $dateFormat = 'DMY', $timeFormat = '12', $a <ide> $current->setDate($year, $month, $day); <ide> } <ide> if ($hour !== null) { <del> if ($timeFormat === '12') { <del> $hour = date('H', strtotime("$hour:$min $meridian")); <del> } <ide> $current->setTime($hour, $min); <ide> } <ide> $change = (round($min * (1 / $interval)) * $interval) - $min; <ide> protected function _getDateTimeValue($value, $timeFormat) { <ide> if (!empty($timeFormat)) { <ide> $time = explode(':', $days[1]); <ide> <del> if ($time[0] >= '12' && $timeFormat === '12') { <add> if ($time[0] >= 12 && $timeFormat == 12) { <ide> $meridian = 'pm'; <del> } elseif ($time[0] === '00' && $timeFormat === '12') { <add> } elseif ($time[0] === '00' && $timeFormat == 12) { <ide> $time[0] = 12; <ide> } elseif ($time[0] >= 12) { <ide> $meridian = 'pm'; <ide> } <del> if ($time[0] == 0 && $timeFormat === '12') { <add> if ($time[0] == 0 && $timeFormat == 12) { <ide> $time[0] = 12; <ide> } <ide> $hour = $min = null;
1
Text
Text
fix some recent nits in assert.md
603afe25c870efb030aed84c2e634652def1a3ec
<ide><path>doc/api/assert.md <ide> rejected. See [`assert.rejects()`][] for more details. <ide> When `assert.doesNotReject()` is called, it will immediately call the `block` <ide> function, and awaits for completion. <ide> <del>Besides the async nature to await the completion behaves identical to <add>Besides the async nature to await the completion behaves identically to <ide> [`assert.doesNotThrow()`][]. <ide> <ide> ```js <ide> assert(0); <ide> // assert(0) <ide> ``` <ide> <del>## assert.strictEqual(actual, expected[, message]) <del><!-- YAML <del>added: v0.1.21 <del>changes: <del> - version: REPLACEME <del> pr-url: https://github.com/nodejs/node/pull/17003 <del> description: Used comparison changed from Strict Equality to `Object.is()` <del>--> <del>* `actual` {any} <del>* `expected` {any} <del>* `message` {any} <del> <del>Tests strict equality between the `actual` and `expected` parameters as <del>determined by the [SameValue Comparison][]. <del> <del>```js <del>const assert = require('assert').strict; <del> <del>assert.strictEqual(1, 2); <del>// AssertionError: 1 strictEqual 2 <del> <del>assert.strictEqual(1, 1); <del>// OK <del> <del>assert.strictEqual(1, '1'); <del>// AssertionError: 1 strictEqual '1' <del>``` <del> <del>If the values are not strictly equal, an `AssertionError` is thrown with a <del>`message` property set equal to the value of the `message` parameter. If the <del>`message` parameter is undefined, a default error message is assigned. If the <del>`message` parameter is an instance of an [`Error`][] then it will be thrown <del>instead of the `AssertionError`. <del> <ide> ## assert.rejects(block[, error][, message]) <ide> <!-- YAML <ide> added: REPLACEME <ide> Awaits for promise returned by function `block` to be rejected. <ide> When `assert.rejects()` is called, it will immediately call the `block` <ide> function, and awaits for completion. <ide> <del>Besides the async nature to await the completion behaves identical to <add>Besides the async nature to await the completion behaves identically to <ide> [`assert.throws()`][]. <ide> <ide> If specified, `error` can be a constructor, [`RegExp`][], a validation <ide> assert.rejects( <ide> }); <ide> ``` <ide> <add>## assert.strictEqual(actual, expected[, message]) <add><!-- YAML <add>added: v0.1.21 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/17003 <add> description: Used comparison changed from Strict Equality to `Object.is()` <add>--> <add>* `actual` {any} <add>* `expected` {any} <add>* `message` {any} <add> <add>Tests strict equality between the `actual` and `expected` parameters as <add>determined by the [SameValue Comparison][]. <add> <add>```js <add>const assert = require('assert').strict; <add> <add>assert.strictEqual(1, 2); <add>// AssertionError: 1 strictEqual 2 <add> <add>assert.strictEqual(1, 1); <add>// OK <add> <add>assert.strictEqual(1, '1'); <add>// AssertionError: 1 strictEqual '1' <add>``` <add> <add>If the values are not strictly equal, an `AssertionError` is thrown with a <add>`message` property set equal to the value of the `message` parameter. If the <add>`message` parameter is undefined, a default error message is assigned. If the <add>`message` parameter is an instance of an [`Error`][] then it will be thrown <add>instead of the `AssertionError`. <add> <ide> ## assert.throws(block[, error][, message]) <ide> <!-- YAML <ide> added: v0.1.21 <ide> second argument. This might lead to difficult-to-spot errors. <ide> [`WeakSet`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet <ide> [`assert.deepEqual()`]: #assert_assert_deepequal_actual_expected_message <ide> [`assert.deepStrictEqual()`]: #assert_assert_deepstrictequal_actual_expected_message <add>[`assert.doesNotThrow()`]: #assert_assert_doesnotthrow_block_error_message <ide> [`assert.notDeepStrictEqual()`]: #assert_assert_notdeepstrictequal_actual_expected_message <ide> [`assert.notStrictEqual()`]: #assert_assert_notstrictequal_actual_expected_message <ide> [`assert.ok()`]: #assert_assert_ok_value_message <add>[`assert.rejects()`]: #assert_assert_rejects_block_error_message <ide> [`assert.strictEqual()`]: #assert_assert_strictequal_actual_expected_message <ide> [`assert.throws()`]: #assert_assert_throws_block_error_message <del>[`assert.rejects()`]: #assert_assert_rejects_block_error_message <ide> [`strict mode`]: #assert_strict_mode <ide> [Abstract Equality Comparison]: https://tc39.github.io/ecma262/#sec-abstract-equality-comparison <ide> [Object.prototype.toString()]: https://tc39.github.io/ecma262/#sec-object.prototype.tostring
1
Javascript
Javascript
remove unused xr.submitframe()
4c3419040361c3ef57453c222d5c29a6aaa764be
<ide><path>src/renderers/WebGLRenderer.js <ide> function WebGLRenderer( parameters ) { <ide> <ide> } <ide> <del> xr.submitFrame(); <del> <ide> } <ide> <ide> // _gl.finish();
1
Python
Python
update refresh jwt when needed
d425af380434422e083e9daca27fb6412e53beaf
<ide><path>libcloud/common/gig_g8.py <ide> # limitations under the License. <ide> <ide> from libcloud.common.base import ConnectionKey, JsonResponse <add>import json <add>import base64 <add>import requests <add>import os <add>import time <add> <add># normally we only use itsyou.online but you might want to work <add># against staging.itsyou.online for some testing <add>IYO_URL = os.environ.get("IYO_URL", "https://itsyou.online") <ide> <ide> <ide> class G8Connection(ConnectionKey): <ide> def add_default_headers(self, headers): <ide> """ <ide> Add headers that are necessary for every request <ide> """ <add> self.driver.key = maybe_update_jwt(self.driver.key) <ide> headers['Authorization'] = "bearer {}".format(self.driver.key) <ide> headers['Content-Type'] = 'application/json' <ide> return headers <add> <add> <add>def base64url_decode(input): <add> """ <add> Helper method to base64url_decode a string. <add> <add> :param input: Input to decode <add> :type input: str <add> <add> :rtype: str <add> """ <add> rem = len(input) % 4 <add> <add> if rem > 0: <add> input += b'=' * (4 - rem) <add> return base64.urlsafe_b64decode(input) <add> <add> <add>def is_jwt_expired(jwt): <add> """ <add> Check if jwt is expired <add> <add> :param jwt: jwt token to validate expiration <add> :type jwt: str <add> <add> :rtype: bool <add> """ <add> jwt = jwt.encode('utf-8') <add> signing_input, _ = jwt.rsplit(b'.', 1) <add> _, claims_segment = signing_input.split(b'.', 1) <add> claimsdata = base64url_decode(claims_segment) <add> if isinstance(claimsdata, bytes): <add> claimsdata = claimsdata.decode('utf-8') <add> data = json.loads(claimsdata) <add> # check if it's about to expire in the next minute <add> return data['exp'] < time.time() - 60 <add> <add> <add>def maybe_update_jwt(jwt): <add> """ <add> Update jwt if it is expired <add> <add> :param jwt: jwt token to validate expiration <add> :type jwt: str <add> <add> :rtype: str <add> """ <add> <add> if is_jwt_expired(jwt): <add> return refresh_jwt(jwt) <add> return jwt <add> <add> <add>def refresh_jwt(jwt): <add> """ <add> Refresh jwt <add> <add> :param jwt: jwt token to refresh <add> :type jwt: str <add> <add> :rtype: str <add> """ <add> url = IYO_URL + "/v1/oauth/jwt/refresh" <add> headers = {"Authorization": "bearer {}".format(jwt)} <add> response = requests.get(url, headers=headers) <add> response.raise_for_status() <add> return response.text
1
Javascript
Javascript
add sqrt and fix gettype
46dfb3990aa247d9406704d13f2d6734d7d31a72
<ide><path>examples/js/nodes/math/Math1Node.js <ide> THREE.Math1Node.EXP = 'exp'; <ide> THREE.Math1Node.EXP2 = 'exp2'; <ide> THREE.Math1Node.LOG = 'log'; <ide> THREE.Math1Node.LOG2 = 'log2'; <del>THREE.Math1Node.INVERSE_SQRT = 'inversesqrt'; <add>THREE.Math1Node.SQRT = 'sqrt'; <add>THREE.Math1Node.INV_SQRT = 'inversesqrt'; <ide> THREE.Math1Node.FLOOR = 'floor'; <ide> THREE.Math1Node.CEIL = 'ceil'; <ide> THREE.Math1Node.NORMALIZE = 'normalize'; <ide> THREE.Math1Node.prototype.constructor = THREE.Math1Node; <ide> THREE.Math1Node.prototype.getType = function( builder ) { <ide> <ide> switch ( this.method ) { <del> case THREE.Math1Node.DISTANCE: <add> case THREE.Math1Node.LENGTH: <ide> return 'fv1'; <ide> } <ide>
1
Ruby
Ruby
use runtime_dependencies from tab
42a39b16bff43ab6aae516dfd578501f1478e8eb
<ide><path>Library/Homebrew/formula.rb <ide> def recursive_requirements(&block) <ide> <ide> # Returns a list of Dependency objects that are required at runtime. <ide> # @private <del> def runtime_dependencies <add> def runtime_dependencies(read_from_tab: true) <add> if read_from_tab && <add> installed_prefix.directory? && <add> (keg = Keg.new(installed_prefix)) && <add> (tab_deps = keg.runtime_dependencies) <add> return tab_deps.map { |d| Dependency.new d["full_name"] }.compact <add> end <add> <ide> recursive_dependencies do |_, dependency| <ide> Dependency.prune if dependency.build? <ide> Dependency.prune if !dependency.required? && build.without?(dependency) <ide><path>Library/Homebrew/linkage_checker.rb <ide> def check_undeclared_deps <ide> formula.build.without?(dep) <ide> end <ide> declared_deps = formula.deps.reject { |dep| filter_out.call(dep) }.map(&:name) <del> recursive_deps = keg.to_formula.runtime_dependencies.map { |dep| dep.to_formula.name } <add> runtime_deps = keg.to_formula.runtime_dependencies(read_from_tab: false) <add> recursive_deps = runtime_deps.map { |dep| dep.to_formula.name } <ide> declared_dep_names = declared_deps.map { |dep| dep.split("/").last } <ide> indirect_deps = [] <ide> undeclared_deps = [] <ide><path>Library/Homebrew/tab.rb <ide> class Tab < OpenStruct <ide> # Instantiates a Tab for a new installation of a formula. <ide> def self.create(formula, compiler, stdlib) <ide> build = formula.build <add> runtime_deps = formula.runtime_dependencies(read_from_tab: false) <ide> attributes = { <ide> "homebrew_version" => HOMEBREW_VERSION, <ide> "used_options" => build.used_options.as_flags, <ide> def self.create(formula, compiler, stdlib) <ide> "compiler" => compiler, <ide> "stdlib" => stdlib, <ide> "aliases" => formula.aliases, <del> "runtime_dependencies" => formula.runtime_dependencies.map do |dep| <add> "runtime_dependencies" => runtime_deps.map do |dep| <ide> f = dep.to_formula <ide> { "full_name" => f.full_name, "version" => f.version.to_s } <ide> end,
3
Javascript
Javascript
remove redundant html5#play()
405b29b8f194c4d5d29534eaf7ebd872486451cb
<ide><path>src/js/tech/html5.js <ide> class Html5 extends Tech { <ide> }); <ide> } <ide> <del> /** <del> * Called by {@link Player#play} to play using the `Html5` `Tech`. <del> */ <del> play() { <del> const playPromise = this.el_.play(); <del> <del> // Catch/silence error when a pause interrupts a play request <del> // on browsers which return a promise <del> if (playPromise !== undefined && typeof playPromise.then === 'function') { <del> playPromise.then(null, (e) => {}); <del> } <del> } <del> <ide> /** <ide> * Set current time for the `HTML5` tech. <ide> * <ide><path>test/unit/tech/html5.test.js <ide> QUnit.test('Html5#reset calls Html5.resetMediaElement when called', function(ass <ide> Html5.resetMediaElement = oldResetMedia; <ide> }); <ide> <del>QUnit.test('Exception in play promise should be caught', function() { <del> const oldEl = tech.el_; <del> <del> tech.el_ = { <del> play: () => { <del> return new Promise(function(resolve, reject) { <del> reject(new DOMException()); <del> }); <del> } <del> }; <del> <del> tech.play(); <del> QUnit.ok(true, 'error was caught'); <del> <del> tech.el_ = oldEl; <del>}); <del> <ide> test('When Android Chrome reports Infinity duration with currentTime 0, return NaN', function() { <ide> const oldIsAndroid = browser.IS_ANDROID; <ide> const oldIsChrome = browser.IS_CHROME;
2
Javascript
Javascript
add missing tests for tokeyvalue() function
732bcd8a368d50995c796373e37be5a4d3b2bc8c
<ide><path>test/AngularSpec.js <ide> describe('parseKeyValue', function() { <ide> toEqual({flag1: true, key: 'value', flag2: true}); <ide> }); <ide> }); <add> <add>describe('toKeyValue', function() { <add> it('should parse key-value pairs into string', function() { <add> expect(toKeyValue({})).toEqual(''); <add> expect(toKeyValue({simple: 'pair'})).toEqual('simple=pair'); <add> expect(toKeyValue({first: '1', second: '2'})).toEqual('first=1&second=2'); <add> expect(toKeyValue({'escaped key': 'escaped value'})). <add> toEqual('escaped%20key=escaped%20value'); <add> expect(toKeyValue({emptyKey: ''})).toEqual('emptyKey='); <add> }); <add>});
1
Javascript
Javascript
fix code style
d0ca03dc5c3060182693ca2c53b0c1a1005a4ff3
<ide><path>examples/jsm/renderers/nodes/accessors/CameraNode.js <ide> class CameraNode extends Node { <ide> <ide> if ( scope === CameraNode.PROJECTION || scope === CameraNode.VIEW ) { <ide> <del> if ( !inputNode || !inputNode.isMatrix4Node ) { <add> if ( !inputNode || !inputNode.isMatrix4Node !== true ) { <ide> <ide> inputNode = new Matrix4Node( null ); <ide> <ide> } <ide> <del> } else if ( !inputNode || !inputNode.isVector3Node ) { <add> } else if ( !inputNode || !inputNode.isVector3Node !== true ) { <ide> <ide> inputNode = new Vector3Node(); <ide>
1
Python
Python
add test for 0d conditions in np.piecewise
303941c929ee2938dc55ad633c9fc063610941b9
<ide><path>numpy/lib/tests/test_function_base.py <ide> def test_0d_comparison(self): <ide> y = piecewise(x, [x <= 3, (x > 3) * (x <= 5), x > 5], [1, 2, 3]) <ide> assert_array_equal(y, 2) <ide> <add> def test_0d_0d_condition(self): <add> x = np.array(3) <add> c = np.array(x > 3) <add> y = piecewise(x, [c], [1, 2]) <add> assert_equal(y, 2) <add> <ide> def test_multidimensional_extrafunc(self): <ide> x = np.array([[-2.5, -1.5, -0.5], <ide> [0.5, 1.5, 2.5]])
1
Javascript
Javascript
fix inconsistent aspect ratio
fa6be2f772793525a9b2d68a58e5a6c9d31f426c
<ide><path>src/controllers/controller.doughnut.js <ide> module.exports = function(Chart) { <ide> // Boolean - Whether we animate scaling the Doughnut from the centre <ide> animateScale: false <ide> }, <del> aspectRatio: 1, <ide> hover: { <ide> mode: 'single' <ide> }, <ide><path>src/controllers/controller.polarArea.js <ide> module.exports = function(Chart) { <ide> }, <ide> <ide> startAngle: -0.5 * Math.PI, <del> aspectRatio: 1, <ide> legendCallback: function(chart) { <ide> var text = []; <ide> text.push('<ul class="' + chart.id + '-legend">'); <ide><path>src/controllers/controller.radar.js <ide> module.exports = function(Chart) { <ide> var helpers = Chart.helpers; <ide> <ide> Chart.defaults.radar = { <del> aspectRatio: 1, <ide> scale: { <ide> type: 'radialLinear' <ide> }, <ide><path>test/specs/platform.dom.tests.js <ide> describe('Platform.dom', function() { <ide> }); <ide> <ide> it('should use default "chart" aspect ratio for render and display sizes', function() { <add> var ratio = Chart.defaults.doughnut.aspectRatio; <add> Chart.defaults.doughnut.aspectRatio = 1; <add> <ide> var chart = acquireChart({ <ide> type: 'doughnut', <ide> options: { <ide> describe('Platform.dom', function() { <ide> } <ide> }); <ide> <add> Chart.defaults.doughnut.aspectRatio = ratio; <add> <ide> expect(chart).toBeChartOfSize({ <ide> dw: 425, dh: 425, <ide> rw: 425, rh: 425,
4
Javascript
Javascript
use dasherizedmodulename for test description
461988481aa50eda4ede938308e42a061584afff
<ide><path>blueprints/component-test/index.js <ide> 'use strict'; <ide> <ide> const path = require('path'); <del>const testInfo = require('ember-cli-test-info'); <ide> const stringUtil = require('ember-cli-string-utils'); <ide> const isPackageMissing = require('ember-cli-is-package-missing'); <ide> const getPathOption = require('ember-cli-get-component-path-option'); <ide> module.exports = useTestFrameworkDetector({ <ide> let dasherizedModuleName = stringUtil.dasherize(options.entity.name); <ide> let componentPathName = dasherizedModuleName; <ide> let testType = options.testType || 'integration'; <del> let friendlyTestDescription = testInfo.description(options.entity.name, 'Integration', 'Component'); <add> <add> let friendlyTestDescription = [ <add> testType === 'unit' ? 'Unit' : 'Integration', <add> 'Component', <add> dasherizedModuleName, <add> ].join(' | '); <ide> <ide> if (options.pod && options.path !== 'components' && options.path !== '') { <ide> componentPathName = [options.path, dasherizedModuleName].filter(Boolean).join('/'); <ide> } <ide> <del> if (options.testType === 'unit') { <del> friendlyTestDescription = testInfo.description(options.entity.name, 'Unit', 'Component'); <del> } <del> <ide> return { <ide> path: getPathOption(options), <ide> testType: testType, <ide><path>node-tests/fixtures/component-test/default.js <ide> import { moduleForComponent, test } from 'ember-qunit'; <ide> import hbs from 'htmlbars-inline-precompile'; <ide> <del>moduleForComponent('x-foo', 'Integration | Component | x foo', { <add>moduleForComponent('x-foo', 'Integration | Component | x-foo', { <ide> integration: true <ide> }); <ide> <ide><path>node-tests/fixtures/component-test/mocha-0.12-unit.js <ide> import { expect } from 'chai'; <ide> import { describe, it } from 'mocha'; <ide> import { setupComponentTest } from 'ember-mocha'; <ide> <del>describe('Unit | Component | x foo', function() { <add>describe('Unit | Component | x-foo', function() { <ide> setupComponentTest('x-foo', { <ide> // Specify the other units that are required for this test <ide> // needs: ['component:foo', 'helper:bar'], <ide><path>node-tests/fixtures/component-test/mocha-0.12.js <ide> import { describe, it } from 'mocha'; <ide> import { setupComponentTest } from 'ember-mocha'; <ide> import hbs from 'htmlbars-inline-precompile'; <ide> <del>describe('Integration | Component | x foo', function() { <add>describe('Integration | Component | x-foo', function() { <ide> setupComponentTest('x-foo', { <ide> integration: true <ide> }); <ide><path>node-tests/fixtures/component-test/mocha-unit.js <ide> import { expect } from 'chai'; <ide> import { describeComponent, it } from 'ember-mocha'; <ide> <del>describeComponent('x-foo', 'Unit | Component | x foo', <add>describeComponent('x-foo', 'Unit | Component | x-foo', <ide> { <ide> // Specify the other units that are required for this test <ide> // needs: ['component:foo', 'helper:bar'], <ide><path>node-tests/fixtures/component-test/mocha.js <ide> import { expect } from 'chai'; <ide> import { describeComponent, it } from 'ember-mocha'; <ide> import hbs from 'htmlbars-inline-precompile'; <ide> <del>describeComponent('x-foo', 'Integration | Component | x foo', <add>describeComponent('x-foo', 'Integration | Component | x-foo', <ide> { <ide> integration: true <ide> }, <ide><path>node-tests/fixtures/component-test/rfc232-unit.js <ide> import { module, test } from 'qunit'; <ide> import { setupTest } from 'ember-qunit'; <ide> <del>module('Unit | Component | x foo', function(hooks) { <add>module('Unit | Component | x-foo', function(hooks) { <ide> setupTest(hooks); <ide> <ide> test('it exists', function(assert) { <ide><path>node-tests/fixtures/component-test/rfc232.js <ide> import { setupRenderingTest } from 'ember-qunit'; <ide> import { render } from '@ember/test-helpers'; <ide> import hbs from 'htmlbars-inline-precompile'; <ide> <del>module('Integration | Component | x foo', function(hooks) { <add>module('Integration | Component | x-foo', function(hooks) { <ide> setupRenderingTest(hooks); <ide> <ide> test('it renders', async function(assert) { <ide><path>node-tests/fixtures/component-test/unit.js <ide> import { moduleForComponent, test } from 'ember-qunit'; <ide> <del>moduleForComponent('x-foo', 'Unit | Component | x foo', { <add>moduleForComponent('x-foo', 'Unit | Component | x-foo', { <ide> // Specify the other units that are required for this test <ide> // needs: ['component:foo', 'helper:bar'], <ide> unit: true
9
Javascript
Javascript
check jquery before extending it
68676afbbe8ab0f9169b06c5edf033c553c0e501
<ide><path>packages/ember-views/lib/system/jquery_ext.js <ide> @module ember <ide> @submodule ember-views <ide> */ <add>if (Ember.$) { <add> // http://www.whatwg.org/specs/web-apps/current-work/multipage/dnd.html#dndevents <add> var dragEvents = Ember.String.w('dragstart drag dragenter dragleave dragover drop dragend'); <ide> <del>// http://www.whatwg.org/specs/web-apps/current-work/multipage/dnd.html#dndevents <del>var dragEvents = Ember.String.w('dragstart drag dragenter dragleave dragover drop dragend'); <del> <del>// Copies the `dataTransfer` property from a browser event object onto the <del>// jQuery event object for the specified events <del>Ember.EnumerableUtils.forEach(dragEvents, function(eventName) { <del> Ember.$.event.fixHooks[eventName] = { props: ['dataTransfer'] }; <del>}); <add> // Copies the `dataTransfer` property from a browser event object onto the <add> // jQuery event object for the specified events <add> Ember.EnumerableUtils.forEach(dragEvents, function(eventName) { <add> Ember.$.event.fixHooks[eventName] = { props: ['dataTransfer'] }; <add> }); <add>}
1
PHP
PHP
fix response downloads
03c16cc6adba7065d50caa2308bc03512ad9a889
<ide><path>src/Illuminate/Support/Facades/Response.php <ide> <?php namespace Illuminate\Support\Facades; <ide> <ide> use Illuminate\Support\Contracts\ArrayableInterface; <add>use Symfony\Component\HttpFoundation\BinaryFileResponse; <ide> <ide> class Response { <ide> <ide> public static function stream($callback, $status = 200, array $headers = array() <ide> * @param array $headers <ide> * @return Symfony\Component\HttpFoundation\BinaryFileResponse <ide> */ <del> public static function download($file, $status = 200, $headers = array()) <add> public static function download($file, $name = null, $headers = array()) <ide> { <del> return new \Symfony\Component\HttpFoundation\BinaryFileResponse($file, $status, $headers); <add> $response = new BinaryFileResponse($file, 200, $headers, true, 'attachment'); <add> <add> if ( ! is_null($name)) <add> { <add> return $response->setContentDisposition('attachment', $name); <add> } <add> <add> return $response; <ide> } <ide> <ide> } <ide>\ No newline at end of file
1
Ruby
Ruby
remove redundant `utils`
e0acaeef816ae73566b2067608a6530b61a8037a
<ide><path>Library/Homebrew/cask/lib/hbc/cli/cleanup.rb <ide> def cache_completes <ide> end <ide> <ide> def disk_cleanup_size <del> Utils.size_in_bytes(cache_files) <add> cache_files.map(&:disk_usage).inject(:+) <ide> end <ide> <ide> def remove_cache_files(*tokens) <ide><path>Library/Homebrew/cask/lib/hbc/cli/style.rb <ide> def run <ide> end <ide> <ide> def install_rubocop <del> Utils.capture_stderr do <add> capture_stderr do <ide> begin <ide> Homebrew.install_gem_setup_path! "rubocop-cask", HOMEBREW_RUBOCOP_CASK_VERSION, "rubocop" <ide> rescue SystemExit <ide><path>Library/Homebrew/cask/lib/hbc/utils.rb <ide> def self.current_user <ide> Etc.getpwuid(Process.euid).name <ide> end <ide> <del> # paths that "look" descendant (textually) will still <del> # return false unless both the given paths exist <del> def self.file_is_descendant(file, dir) <del> file = Pathname.new(file) <del> dir = Pathname.new(dir) <del> return false unless file.exist? && dir.exist? <del> unless dir.directory? <del> onoe "Argument must be a directory: '#{dir}'" <del> return false <del> end <del> unless file.absolute? && dir.absolute? <del> onoe "Both arguments must be absolute: '#{file}', '#{dir}'" <del> return false <del> end <del> while file.parent != file <del> return true if File.identical?(file, dir) <del> file = file.parent <del> end <del> false <del> end <del> <ide> def self.path_occupied?(path) <ide> File.exist?(path) || File.symlink?(path) <ide> end <ide> def self.nowstamp_metadata_path(container_path) <ide> timestamp.concat(fraction) <ide> container_path.join(timestamp) <ide> end <del> <del> def self.size_in_bytes(files) <del> Array(files).reduce(0) { |acc, elem| acc + (File.size?(elem) || 0) } <del> end <del> <del> def self.capture_stderr <del> previous_stderr = $stderr <del> $stderr = StringIO.new <del> yield <del> $stderr.string <del> ensure <del> $stderr = previous_stderr <del> end <ide> end <ide> end <ide><path>Library/Homebrew/test/cask/cli/cleanup_spec.rb <ide> <ide> cached_downloads.each(&FileUtils.method(:touch)) <ide> <del> cleanup_size = Hbc::Utils.size_in_bytes(cached_downloads[0]) <add> cleanup_size = cached_downloads[0].disk_usage <ide> <ide> expect { <ide> subject.cleanup(cleaned_up_cached_download)
4
Javascript
Javascript
omit unneeded process.nexttick
3369e34645f9591d05e111c641b510bc2ac0873a
<ide><path>lib/Compilation.js <ide> class Compilation { <ide> return; <ide> } <ide> <del> process.nextTick(() => { <del> // This is nested so we need to allow one additional task <del> this.processDependenciesQueue.increaseParallelism(); <del> <del> asyncLib.forEach( <del> sortedDependencies, <del> (item, callback) => { <del> this.handleModuleCreation(item, err => { <del> // In V8, the Error objects keep a reference to the functions on the stack. These warnings & <del> // errors are created inside closures that keep a reference to the Compilation, so errors are <del> // leaking the Compilation object. <del> if (err && this.bail) { <del> // eslint-disable-next-line no-self-assign <del> err.stack = err.stack; <del> return callback(err); <del> } <del> callback(); <del> }); <del> }, <del> err => { <del> this.processDependenciesQueue.decreaseParallelism(); <add> // This is nested so we need to allow one additional task <add> this.processDependenciesQueue.increaseParallelism(); <ide> <del> return callback(err); <del> } <del> ); <del> }); <add> asyncLib.forEach( <add> sortedDependencies, <add> (item, callback) => { <add> this.handleModuleCreation(item, err => { <add> // In V8, the Error objects keep a reference to the functions on the stack. These warnings & <add> // errors are created inside closures that keep a reference to the Compilation, so errors are <add> // leaking the Compilation object. <add> if (err && this.bail) { <add> // eslint-disable-next-line no-self-assign <add> err.stack = err.stack; <add> return callback(err); <add> } <add> callback(); <add> }); <add> }, <add> err => { <add> this.processDependenciesQueue.decreaseParallelism(); <add> <add> return callback(err); <add> } <add> ); <ide> } <ide> <ide> /**
1
Text
Text
add new example
4f223e68d0a4d3956253850e3b17bc4d6bca89ff
<ide><path>guide/english/java/streams/index.md <ide> List<String> result2 = Arrays.asList("de", "abc", "f", "abc") <ide> // result: abc de <ide> ``` <ide> <add>```java <add>// Examples of extracting properties from a list of objects <add>// Let's say we have a List<Person> personList <add>// Each Person object has a property, age of type Integer with a getter, getAge <add>// To get a list of age from the List<Person> personList <add>// In a typical foor loop: <add> <add>List<Integer> ageList = new ArrayList<>(); <add>for(Person person: personList){ <add> ageList.add(person.getAge()); <add>} <add> <add>//Using streams to achieve the same result as above <add>List<Integer> ageList = personList.stream().map(Person::getAge).collect(Collectors.toList()); <add> <add>``` <add> <ide> ### Sources <ide> 1. [Processing Data with Java SE 8 Streams, Part 1](http://www.oracle.com/technetwork/articles/java/ma14-java-se-8-streams-2177646.html)
1
Go
Go
make the checksum async within commit
8ff1765674c93a169fe29483503709a008f30618
<ide><path>graph.go <ide> import ( <ide> "path" <ide> "path/filepath" <ide> "strings" <add> "sync" <ide> "time" <ide> ) <ide> <ide> // A Graph is a store for versioned filesystem images and the relationship between them. <ide> type Graph struct { <del> Root string <del> idIndex *TruncIndex <del> httpClient *http.Client <add> Root string <add> idIndex *TruncIndex <add> httpClient *http.Client <add> checksumLock map[string]*sync.Mutex <add> lockSumFile *sync.Mutex <add> lockSumMap *sync.Mutex <ide> } <ide> <ide> // NewGraph instantiates a new graph at the given root path in the filesystem. <ide> func NewGraph(root string) (*Graph, error) { <ide> return nil, err <ide> } <ide> graph := &Graph{ <del> Root: abspath, <del> idIndex: NewTruncIndex(), <add> Root: abspath, <add> idIndex: NewTruncIndex(), <add> checksumLock: make(map[string]*sync.Mutex), <add> lockSumFile: &sync.Mutex{}, <add> lockSumMap: &sync.Mutex{}, <ide> } <ide> if err := graph.restore(); err != nil { <ide> return nil, err <ide> func (graph *Graph) Get(name string) (*Image, error) { <ide> return nil, fmt.Errorf("Image stored at '%s' has wrong id '%s'", id, img.Id) <ide> } <ide> img.graph = graph <add> graph.lockSumMap.Lock() <add> defer graph.lockSumMap.Unlock() <add> if _, exists := graph.checksumLock[img.Id]; !exists { <add> graph.checksumLock[img.Id] = &sync.Mutex{} <add> } <ide> return img, nil <ide> } <ide> <ide> func (graph *Graph) Create(layerData Archive, container *Container, comment, aut <ide> if err := graph.Register(layerData, img); err != nil { <ide> return nil, err <ide> } <del> img.Checksum() <add> go img.Checksum() <ide> return img, nil <ide> } <ide> <ide> func (graph *Graph) Register(layerData Archive, img *Image) error { <ide> } <ide> img.graph = graph <ide> graph.idIndex.Add(img.Id) <add> graph.checksumLock[img.Id] = &sync.Mutex{} <ide> return nil <ide> } <ide> <ide><path>image.go <ide> func LoadImage(root string) (*Image, error) { <ide> if err != nil { <ide> return nil, err <ide> } <del> var img Image <del> if err := json.Unmarshal(jsonData, &img); err != nil { <add> img := &Image{} <add> <add> if err := json.Unmarshal(jsonData, img); err != nil { <ide> return nil, err <ide> } <ide> if err := ValidateId(img.Id); err != nil { <ide> func LoadImage(root string) (*Image, error) { <ide> } else if !stat.IsDir() { <ide> return nil, fmt.Errorf("Couldn't load image %s: %s is not a directory", img.Id, layerPath(root)) <ide> } <del> <del> return &img, nil <add> return img, nil <ide> } <ide> <ide> func StoreImage(img *Image, layerData Archive, root string) error { <ide> func (img *Image) layer() (string, error) { <ide> } <ide> <ide> func (img *Image) Checksum() (string, error) { <add> img.graph.checksumLock[img.Id].Lock() <add> defer img.graph.checksumLock[img.Id].Unlock() <add> <ide> root, err := img.root() <ide> if err != nil { <ide> return "", err <ide> func (img *Image) Checksum() (string, error) { <ide> checksums := make(map[string]string) <ide> <ide> if checksumDict, err := ioutil.ReadFile(checksumDictPth); err == nil { <del> if err := json.Unmarshal(checksumDict, checksums); err != nil { <add> if err := json.Unmarshal(checksumDict, &checksums); err != nil { <ide> return "", err <ide> } <ide> if checksum, ok := checksums[img.Id]; ok { <ide> func (img *Image) Checksum() (string, error) { <ide> if _, err := h.Write([]byte("\n")); err != nil { <ide> return "", err <ide> } <add> <add> fmt.Printf("precopy %s: %s\n", img.ShortId(), time.Now().String()) <add> <ide> if _, err := io.Copy(h, layerData); err != nil { <ide> return "", err <ide> } <add> fmt.Printf("postcopy presum %s: %s\n", img.ShortId(), time.Now().String()) <ide> <ide> hash := "sha256:" + hex.EncodeToString(h.Sum(nil)) <ide> checksums[img.Id] = hash <add> fmt.Printf("postsum %s: %s\n", img.ShortId(), time.Now().String()) <ide> <add> // Reload the json file to make sure not to overwrite faster sums <add> img.graph.lockSumFile.Lock() <add> defer img.graph.lockSumFile.Unlock() <add> if checksumDict, err := ioutil.ReadFile(checksumDictPth); err == nil { <add> if err := json.Unmarshal(checksumDict, &checksums); err != nil { <add> return "", err <add> } <add> } <ide> checksumJson, err := json.Marshal(checksums) <ide> if err != nil { <ide> return hash, err <ide> } <del> <ide> if err := ioutil.WriteFile(checksumDictPth, checksumJson, 0600); err != nil { <ide> return hash, err <ide> }
2
Javascript
Javascript
add some typings to `internal/modules/esm/resolve`
45f98fc60d12ca97ebeb35974ad966547990eda4
<ide><path>lib/internal/modules/esm/resolve.js <ide> const userConditions = getOptionValue('--conditions'); <ide> const DEFAULT_CONDITIONS = ObjectFreeze(['node', 'import', ...userConditions]); <ide> const DEFAULT_CONDITIONS_SET = new SafeSet(DEFAULT_CONDITIONS); <ide> <add>/** <add> * @typedef {string | string[] | Record<string, unknown>} Exports <add> * @typedef {'module' | 'commonjs'} PackageType <add> * @typedef {{ <add> * exports?: ExportConfig; <add> * name?: string; <add> * main?: string; <add> * type?: PackageType; <add> * }} PackageConfig <add> */ <add> <ide> const emittedPackageWarnings = new SafeSet(); <add> <add>/** <add> * @param {string} match <add> * @param {URL} pjsonUrl <add> * @param {boolean} isExports <add> * @param {string | URL | undefined} base <add> * @returns {void} <add> */ <ide> function emitFolderMapDeprecation(match, pjsonUrl, isExports, base) { <ide> const pjsonPath = fileURLToPath(pjsonUrl); <ide> <ide> function emitFolderMapDeprecation(match, pjsonUrl, isExports, base) { <ide> ); <ide> } <ide> <add>/** <add> * @param {URL} url <add> * @param {URL} packageJSONUrl <add> * @param {string | URL | undefined} base <add> * @param {string} main <add> * @returns <add> */ <ide> function emitLegacyIndexDeprecation(url, packageJSONUrl, base, main) { <ide> const { format } = defaultGetFormat(url); <ide> if (format !== 'module') <ide> function emitLegacyIndexDeprecation(url, packageJSONUrl, base, main) { <ide> ); <ide> } <ide> <add>/** <add> * @param {string[]} [conditions] <add> * @returns {Set<string>} <add> */ <ide> function getConditionsSet(conditions) { <ide> if (conditions !== undefined && conditions !== DEFAULT_CONDITIONS) { <ide> if (!ArrayIsArray(conditions)) { <ide> function getConditionsSet(conditions) { <ide> const realpathCache = new SafeMap(); <ide> const packageJSONCache = new SafeMap(); /* string -> PackageConfig */ <ide> <add>/** <add> * @param {string | URL} path <add> * @returns {import('fs').Stats} <add> */ <ide> const tryStatSync = <ide> (path) => statSync(path, { throwIfNoEntry: false }) ?? new Stats(); <ide> <add>/** <add> * @param {string} path <add> * @param {string} specifier <add> * @param {string | URL | undefined} base <add> * @returns {PackageConfig} <add> */ <ide> function getPackageConfig(path, specifier, base) { <ide> const existing = packageJSONCache.get(path); <ide> if (existing !== undefined) { <ide> function getPackageConfig(path, specifier, base) { <ide> return packageConfig; <ide> } <ide> <add>/** <add> * @param {URL | string} resolved <add> * @returns {PackageConfig} <add> */ <ide> function getPackageScopeConfig(resolved) { <ide> let packageJSONUrl = new URL('./package.json', resolved); <ide> while (true) { <ide> function getPackageScopeConfig(resolved) { <ide> } <ide> <ide> /** <del> * Legacy CommonJS main resolution: <del> * 1. let M = pkg_url + (json main field) <del> * 2. TRY(M, M.js, M.json, M.node) <del> * 3. TRY(M/index.js, M/index.json, M/index.node) <del> * 4. TRY(pkg_url/index.js, pkg_url/index.json, pkg_url/index.node) <del> * 5. NOT_FOUND <ide> * @param {string | URL} url <ide> * @returns {boolean} <ide> */ <ide> function fileExists(url) { <ide> return statSync(url, { throwIfNoEntry: false })?.isFile() ?? false; <ide> } <ide> <add>/** <add> * Legacy CommonJS main resolution: <add> * 1. let M = pkg_url + (json main field) <add> * 2. TRY(M, M.js, M.json, M.node) <add> * 3. TRY(M/index.js, M/index.json, M/index.node) <add> * 4. TRY(pkg_url/index.js, pkg_url/index.json, pkg_url/index.node) <add> * 5. NOT_FOUND <add> * @param {URL} packageJSONUrl <add> * @param {PackageConfig} packageConfig <add> * @param {string | URL | undefined} base <add> * @returns {URL} <add> */ <ide> function legacyMainResolve(packageJSONUrl, packageConfig, base) { <ide> let guess; <ide> if (packageConfig.main !== undefined) { <ide> function legacyMainResolve(packageJSONUrl, packageConfig, base) { <ide> fileURLToPath(new URL('.', packageJSONUrl)), fileURLToPath(base)); <ide> } <ide> <add>/** <add> * @param {URL} search <add> * @returns {URL | undefined} <add> */ <ide> function resolveExtensionsWithTryExactName(search) { <ide> if (fileExists(search)) return search; <ide> return resolveExtensions(search); <ide> } <ide> <ide> const extensions = ['.js', '.json', '.node', '.mjs']; <add> <add>/** <add> * @param {URL} search <add> * @returns {URL | undefined} <add> */ <ide> function resolveExtensions(search) { <ide> for (let i = 0; i < extensions.length; i++) { <ide> const extension = extensions[i]; <ide> function resolveExtensions(search) { <ide> return undefined; <ide> } <ide> <add>/** <add> * @param {URL} search <add> * @returns {URL | undefined} <add> */ <ide> function resolveDirectoryEntry(search) { <ide> const dirPath = fileURLToPath(search); <ide> const pkgJsonPath = resolve(dirPath, 'package.json'); <ide> function resolveDirectoryEntry(search) { <ide> } <ide> <ide> const encodedSepRegEx = /%2F|%2C/i; <add>/** <add> * @param {URL} resolved <add> * @param {string | URL | undefined} base <add> * @returns {URL | undefined} <add> */ <ide> function finalizeResolution(resolved, base) { <ide> if (RegExpPrototypeTest(encodedSepRegEx, resolved.pathname)) <ide> throw new ERR_INVALID_MODULE_SPECIFIER( <ide> function finalizeResolution(resolved, base) { <ide> return resolved; <ide> } <ide> <add>/** <add> * @param {string} specifier <add> * @param {URL} packageJSONUrl <add> * @param {string | URL | undefined} base <add> */ <ide> function throwImportNotDefined(specifier, packageJSONUrl, base) { <ide> throw new ERR_PACKAGE_IMPORT_NOT_DEFINED( <ide> specifier, packageJSONUrl && fileURLToPath(new URL('.', packageJSONUrl)), <ide> fileURLToPath(base)); <ide> } <ide> <add>/** <add> * @param {string} specifier <add> * @param {URL} packageJSONUrl <add> * @param {string | URL | undefined} base <add> */ <ide> function throwExportsNotFound(subpath, packageJSONUrl, base) { <ide> throw new ERR_PACKAGE_PATH_NOT_EXPORTED( <ide> fileURLToPath(new URL('.', packageJSONUrl)), subpath, <ide> base && fileURLToPath(base)); <ide> } <ide> <add>/** <add> * <add> * @param {string | URL} subpath <add> * @param {URL} packageJSONUrl <add> * @param {boolean} internal <add> * @param {string | URL | undefined} base <add> */ <ide> function throwInvalidSubpath(subpath, packageJSONUrl, internal, base) { <ide> const reason = `request is not a valid subpath for the "${internal ? <ide> 'imports' : 'exports'}" resolution of ${fileURLToPath(packageJSONUrl)}`; <ide> function resolvePackageTarget(packageJSONUrl, target, subpath, packageSubpath, <ide> base); <ide> } <ide> <add>/** <add> * <add> * @param {Exports} exports <add> * @param {URL} packageJSONUrl <add> * @param {string | URL | undefined} base <add> * @returns <add> */ <ide> function isConditionalExportsMainSugar(exports, packageJSONUrl, base) { <ide> if (typeof exports === 'string' || ArrayIsArray(exports)) return true; <ide> if (typeof exports !== 'object' || exports === null) return false; <ide> function isConditionalExportsMainSugar(exports, packageJSONUrl, base) { <ide> /** <ide> * @param {URL} packageJSONUrl <ide> * @param {string} packageSubpath <del> * @param {object} packageConfig <del> * @param {string} base <add> * @param {PackageConfig} packageConfig <add> * @param {string | URL | undefined} base <ide> * @param {Set<string>} conditions <ide> * @returns {URL} <ide> */ <ide> function packageExportsResolve( <ide> throwExportsNotFound(packageSubpath, packageJSONUrl, base); <ide> } <ide> <add>/** <add> * @param {string} name <add> * @param {string | URL | undefined} base <add> * @param {Set<string>} conditions <add> * @returns <add> */ <ide> function packageImportsResolve(name, base, conditions) { <ide> if (name === '#' || StringPrototypeStartsWith(name, '#/')) { <ide> const reason = 'is not a valid internal imports specifier name'; <ide> function packageImportsResolve(name, base, conditions) { <ide> throwImportNotDefined(name, packageJSONUrl, base); <ide> } <ide> <add>/** <add> * @param {URL} url <add> * @returns {PackageType} <add> */ <ide> function getPackageType(url) { <ide> const packageConfig = getPackageScopeConfig(url); <ide> return packageConfig.type; <ide> } <ide> <add>/** <add> * @param {string} specifier <add> * @param {string | URL | undefined} base <add> * @returns {{ packageName: string, packageSubpath: string, isScoped: boolean }} <add> */ <ide> function parsePackageName(specifier, base) { <ide> let separatorIndex = StringPrototypeIndexOf(specifier, '/'); <ide> let validPackageName = true; <ide> function parsePackageName(specifier, base) { <ide> <ide> /** <ide> * @param {string} specifier <del> * @param {URL} base <add> * @param {string | URL | undefined} base <ide> * @param {Set<string>} conditions <ide> * @returns {URL} <ide> */ <ide> function packageResolve(specifier, base, conditions) { <ide> throw new ERR_MODULE_NOT_FOUND(packageName, fileURLToPath(base)); <ide> } <ide> <add>/** <add> * @param {string} specifier <add> * @returns {boolean} <add> */ <ide> function isBareSpecifier(specifier) { <ide> return specifier[0] && specifier[0] !== '/' && specifier[0] !== '.'; <ide> } <ide> function shouldBeTreatedAsRelativeOrAbsolutePath(specifier) { <ide> <ide> /** <ide> * @param {string} specifier <del> * @param {URL} base <add> * @param {string | URL | undefined} base <ide> * @param {Set<string>} conditions <ide> * @returns {URL} <ide> */
1
Ruby
Ruby
make the 3rd arg optional for #failsafe_response
e320f28945290b527a5634ea473b5a8543d5ab0a
<ide><path>railties/lib/dispatcher.rb <ide> def prepare_breakpoint <ide> end <ide> <ide> # If the block raises, send status code as a last-ditch response. <del> def failsafe_response(output, status, exception) <add> def failsafe_response(output, status, exception = nil) <ide> yield <ide> rescue Object <ide> begin <ide> output.write "Status: #{status}\r\n" <ide> output.write "Content-Type: text/plain\r\n\r\n" <del> output.write exception.to_s + "\r\n" + exception.backtrace.join("\r\n") <add> output.write exception.to_s + "\r\n" + exception.backtrace.join("\r\n") if exception <ide> rescue Object <ide> end <ide> end
1
Javascript
Javascript
fix controller name in example
840e889e5353156e6187f808bcf92ffe876235a0
<ide><path>src/ng/filter/orderBy.js <ide> * @example <ide> <example module="orderByExample"> <ide> <file name="index.html"> <del> <div ng-controller="Ctrl"> <add> <div ng-controller="ExampleController"> <ide> <table class="friend"> <ide> <tr> <ide> <th><a href="" ng-click="reverse=false;order('name', false)">Name</a>
1
Javascript
Javascript
set ambientlight.castshadow to `false`
e9297a470c147b463e4e80a87e1471c1bd2ecad8
<ide><path>src/lights/AmbientLight.js <ide> function AmbientLight( color, intensity ) { <ide> <ide> this.type = 'AmbientLight'; <ide> <del> this.castShadow = undefined; <add> this.castShadow = false; <ide> <ide> } <ide>
1
Java
Java
refine antpathmatcher optimizations
c4117885bd61835159da14fb7fc9e3e28e1ddd31
<ide><path>spring-core/src/main/java/org/springframework/util/AntPathMatcher.java <ide> public class AntPathMatcher implements PathMatcher { <ide> <ide> private static final Pattern VARIABLE_PATTERN = Pattern.compile("\\{[^/]+?\\}"); <ide> <add> private static final char[] WILDCARD_CHARS = { '*', '?', '{' }; <add> <ide> <ide> private String pathSeparator; <ide> <ide> public class AntPathMatcher implements PathMatcher { <ide> <ide> private volatile Boolean cachePatterns; <ide> <del> private final Map<String, PreprocessedPattern> tokenizedPatternCache = new ConcurrentHashMap<String, PreprocessedPattern>(256); <add> private final Map<String, String[]> tokenizedPatternCache = new ConcurrentHashMap<String, String[]>(256); <ide> <ide> final Map<String, AntPathStringMatcher> stringMatcherCache = new ConcurrentHashMap<String, AntPathStringMatcher>(256); <ide> <ide> protected boolean doMatch(String pattern, String path, boolean fullMatch, Map<St <ide> return false; <ide> } <ide> <del> PreprocessedPattern preprocessedPattern = tokenizePattern(pattern); <del> if (fullMatch && this.caseSensitive && preprocessedPattern.certainlyNotMatch(path)) { <add> String[] pattDirs = tokenizePattern(pattern); <add> if (fullMatch && this.caseSensitive && !isPotentialMatch(path, pattDirs)) { <ide> return false; <ide> } <del> String[] pattDirs = preprocessedPattern.tokenized; <add> <ide> String[] pathDirs = tokenizePath(path); <ide> <ide> int pattIdxStart = 0; <ide> else if (!fullMatch && "**".equals(pattDirs[pattIdxStart])) { <ide> return true; <ide> } <ide> <add> private boolean isPotentialMatch(String path, String[] pattDirs) { <add> char[] pathChars = path.toCharArray(); <add> int pos = 0; <add> for (String pattDir : pattDirs) { <add> int count = countStartsWith(pathChars, pos, this.pathSeparator, false); <add> pos += (count == this.pathSeparator.length() ? count : 0); <add> count = countStartsWith(pathChars, pos, pattDir, true); <add> if (count < pattDir.length()) { <add> if (count > 0) { <add> return true; <add> } <add> return (pattDir.length() > 0) && isWildcardChar(pattDir.charAt(0)); <add> } <add> pos += count; <add> } <add> return true; <add> } <add> <add> private int countStartsWith(char[] chars, int pos, String prefix, boolean stopOnWildcard) { <add> int count = 0; <add> for (char c : prefix.toCharArray()) { <add> if (stopOnWildcard && isWildcardChar(c)) { <add> return count; <add> } <add> if (pos + count >= chars.length) { <add> return 0; <add> } <add> if (chars[pos + count] == c) { <add> count++; <add> } <add> } <add> return count; <add> } <add> <add> private boolean isWildcardChar(char c) { <add> for (char candidate : WILDCARD_CHARS) { <add> if (c == candidate) { <add> return true; <add> } <add> } <add> return false; <add> } <add> <ide> /** <ide> * Tokenize the given path pattern into parts, based on this matcher's settings. <ide> * <p>Performs caching based on {@link #setCachePatterns}, delegating to <ide> * {@link #tokenizePath(String)} for the actual tokenization algorithm. <ide> * @param pattern the pattern to tokenize <ide> * @return the tokenized pattern parts <ide> */ <del> protected PreprocessedPattern tokenizePattern(String pattern) { <del> PreprocessedPattern tokenized = null; <add> protected String[] tokenizePattern(String pattern) { <add> String[] tokenized = null; <ide> Boolean cachePatterns = this.cachePatterns; <ide> if (cachePatterns == null || cachePatterns.booleanValue()) { <ide> tokenized = this.tokenizedPatternCache.get(pattern); <ide> } <ide> if (tokenized == null) { <del> tokenized = compiledPattern(pattern); <add> tokenized = tokenizePath(pattern); <ide> if (cachePatterns == null && this.tokenizedPatternCache.size() >= CACHE_TURNOFF_THRESHOLD) { <ide> // Try to adapt to the runtime situation that we're encountering: <ide> // There are obviously too many different patterns coming in here... <ide> protected String[] tokenizePath(String path) { <ide> return StringUtils.tokenizeToStringArray(path, this.pathSeparator, this.trimTokens, true); <ide> } <ide> <del> private int firstSpecialCharIdx(int specialCharIdx, int prevFoundIdx) { <del> if (specialCharIdx != -1) { <del> return prevFoundIdx == -1 ? specialCharIdx : Math.min(prevFoundIdx, specialCharIdx); <del> } <del> else { <del> return prevFoundIdx; <del> } <del> } <del> <del> private PreprocessedPattern compiledPattern(String pattern) { <del> String[] tokenized = tokenizePath(pattern); <del> int specialCharIdx = -1; <del> specialCharIdx = firstSpecialCharIdx(pattern.indexOf('*'), specialCharIdx); <del> specialCharIdx = firstSpecialCharIdx(pattern.indexOf('?'), specialCharIdx); <del> specialCharIdx = firstSpecialCharIdx(pattern.indexOf('{'), specialCharIdx); <del> final String prefix; <del> if (specialCharIdx != -1) { <del> prefix = pattern.substring(0, specialCharIdx); <del> } <del> else { <del> prefix = pattern; <del> } <del> return new PreprocessedPattern(tokenized, prefix.isEmpty() ? null : prefix); <del> } <del> <ide> /** <ide> * Test whether or not a string matches against a pattern. <ide> * @param pattern the pattern to match against (never {@code null}) <ide> public String getEndsOnDoubleWildCard() { <ide> } <ide> } <ide> <del> private static class PreprocessedPattern { <del> private final String[] tokenized; <del> <del> private final String prefix; <del> <del> public PreprocessedPattern(String[] tokenized, String prefix) { <del> this.tokenized = tokenized; <del> this.prefix = prefix; <del> } <del> <del> private boolean certainlyNotMatch(String path) { <del> return prefix != null && !path.startsWith(prefix); <del> } <del> } <del> <ide> } <ide><path>spring-core/src/test/java/org/springframework/util/AntPathMatcherTests.java <ide> public void match() { <ide> <ide> assertFalse(pathMatcher.match("/x/x/**/bla", "/x/x/x/")); <ide> <add> assertTrue(pathMatcher.match("/foo/bar/**", "/foo/bar")) ; <add> <ide> assertTrue(pathMatcher.match("", "")); <ide> <ide> assertTrue(pathMatcher.match("/{bla}.*", "/testing.html"));
2
Python
Python
fix e722 flake8 warnings (x26)
631be27078fe394fdd8f98b9475ca87026f8044d
<ide><path>examples/contrib/run_swag.py <ide> <ide> try: <ide> from torch.utils.tensorboard import SummaryWriter <del>except: <add>except ImportError: <ide> from tensorboardX import SummaryWriter <ide> <ide> <ide><path>examples/distillation/distiller.py <ide> <ide> try: <ide> from torch.utils.tensorboard import SummaryWriter <del>except: <add>except ImportError: <ide> from tensorboardX import SummaryWriter <ide> <ide> <ide><path>examples/distillation/run_squad_w_distillation.py <ide> <ide> try: <ide> from torch.utils.tensorboard import SummaryWriter <del>except: <add>except ImportError: <ide> from tensorboardX import SummaryWriter <ide> <ide> <ide><path>examples/mm-imdb/run_mmimdb.py <ide> <ide> try: <ide> from torch.utils.tensorboard import SummaryWriter <del>except: <add>except ImportError: <ide> from tensorboardX import SummaryWriter <ide> <ide> <ide><path>examples/pplm/run_pplm.py <ide> def run_pplm_example( <ide> print("= Perturbed generated text {} =".format(i + 1)) <ide> print(pert_gen_text) <ide> print() <del> except: <del> pass <add> except Exception as exc: <add> print("Ignoring error while generating perturbed text:", exc) <ide> <ide> # keep the prefix, perturbed seq, original seq for each index <ide> generated_texts.append((tokenized_cond_text, pert_gen_tok_text, unpert_gen_tok_text)) <ide><path>examples/pplm/run_pplm_discrim_train.py <ide> def train_discriminator( <ide> for i, line in enumerate(f): <ide> try: <ide> data.append(eval(line)) <del> except: <add> except Exception: <ide> print("Error evaluating line {}: {}".format(i, line)) <ide> continue <ide> x = [] <ide> def train_discriminator( <ide> continue <ide> x.append(seq) <ide> y.append(d["label"]) <del> except: <add> except Exception: <ide> print("Error evaluating / tokenizing" " line {}, skipping it".format(i)) <ide> pass <ide> <ide> def train_discriminator( <ide> continue <ide> x.append(seq) <ide> y.append(int(np.sum(d["label"]) > 0)) <del> except: <add> except Exception: <ide> print("Error evaluating / tokenizing" " line {}, skipping it".format(i)) <ide> pass <ide> <ide> def train_discriminator( <ide> x.append(seq) <ide> y.append(class2idx[label]) <ide> <del> except: <add> except Exception: <ide> print("Error tokenizing line {}, skipping it".format(i)) <ide> pass <ide> <ide><path>examples/run_glue.py <ide> <ide> try: <ide> from torch.utils.tensorboard import SummaryWriter <del>except: <add>except ImportError: <ide> from tensorboardX import SummaryWriter <ide> <ide> <ide><path>examples/run_lm_finetuning.py <ide> <ide> try: <ide> from torch.utils.tensorboard import SummaryWriter <del>except: <add>except ImportError: <ide> from tensorboardX import SummaryWriter <ide> <ide> <ide><path>examples/run_multiple_choice.py <ide> <ide> try: <ide> from torch.utils.tensorboard import SummaryWriter <del>except: <add>except ImportError: <ide> from tensorboardX import SummaryWriter <ide> <ide> <ide><path>examples/run_squad.py <ide> <ide> try: <ide> from torch.utils.tensorboard import SummaryWriter <del>except: <add>except ImportError: <ide> from tensorboardX import SummaryWriter <ide> <ide> <ide><path>examples/run_xnli.py <ide> <ide> try: <ide> from torch.utils.tensorboard import SummaryWriter <del>except: <add>except ImportError: <ide> from tensorboardX import SummaryWriter <ide> <ide> <ide><path>templates/adding_a_new_example_script/run_xxx.py <ide> <ide> try: <ide> from torch.utils.tensorboard import SummaryWriter <del>except: <add>except ImportError: <ide> from tensorboardX import SummaryWriter <ide> <ide> <ide><path>transformers/__init__.py <ide> # and: https://github.com/tensorflow/tensorflow/issues/26691#issuecomment-500369493 <ide> try: <ide> import absl.logging <del> <add>except ImportError: <add> pass <add>else: <ide> absl.logging.set_verbosity("info") <ide> absl.logging.set_stderrthreshold("info") <ide> absl.logging._warn_preinit_stderr = False <del>except: <del> pass <ide> <ide> import logging <ide> <ide><path>transformers/hf_api.py <ide> def get_token(cls): <ide> try: <ide> with open(cls.path_token, "r") as f: <ide> return f.read() <del> except: <del> # this is too wide. When Py2 is dead use: <del> # `except FileNotFoundError:` instead <del> return None <add> except FileNotFoundError: <add> pass <ide> <ide> @classmethod <ide> def delete_token(cls): <ide> def delete_token(cls): <ide> """ <ide> try: <ide> os.remove(cls.path_token) <del> except: <del> return <add> except FileNotFoundError: <add> pass <ide><path>transformers/modeling_utils.py <ide> def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): <ide> if state_dict is None and not from_tf: <ide> try: <ide> state_dict = torch.load(resolved_archive_file, map_location="cpu") <del> except: <add> except Exception: <ide> raise OSError( <ide> "Unable to load weights from pytorch checkpoint file. " <ide> "If you tried to load a PyTorch model from a TF 2.0 checkpoint, please set from_tf=True. " <ide><path>transformers/tests/modeling_tf_common_test.py <ide> def _get_embeds(self, wte, input_ids): <ide> # We used to fall back to just synthetically creating a dummy tensor of ones: <ide> try: <ide> x = wte(input_ids, mode="embedding") <del> except: <add> except Exception: <ide> try: <ide> x = wte([input_ids], mode="embedding") <del> except: <add> except Exception: <ide> try: <ide> x = wte([input_ids, None, None, None], mode="embedding") <del> except: <add> except Exception: <ide> if hasattr(self.model_tester, "embedding_size"): <ide> x = tf.ones(input_ids.shape + [self.model_tester.embedding_size], dtype=tf.dtypes.float32) <ide> else: <ide><path>transformers/tokenization_ctrl.py <ide> def bpe(self, token): <ide> while i < len(word): <ide> try: <ide> j = word.index(first, i) <del> new_word.extend(word[i:j]) <del> i = j <del> except: <add> except ValueError: <ide> new_word.extend(word[i:]) <ide> break <add> else: <add> new_word.extend(word[i:j]) <add> i = j <ide> <ide> if word[i] == first and i < len(word) - 1 and word[i + 1] == second: <ide> new_word.append(first + second) <ide><path>transformers/tokenization_gpt2.py <ide> def bpe(self, token): <ide> while i < len(word): <ide> try: <ide> j = word.index(first, i) <del> new_word.extend(word[i:j]) <del> i = j <del> except: <add> except ValueError: <ide> new_word.extend(word[i:]) <ide> break <add> else: <add> new_word.extend(word[i:j]) <add> i = j <ide> <ide> if word[i] == first and i < len(word) - 1 and word[i + 1] == second: <ide> new_word.append(first + second) <ide><path>transformers/tokenization_openai.py <ide> def bpe(self, token): <ide> while i < len(word): <ide> try: <ide> j = word.index(first, i) <del> new_word.extend(word[i:j]) <del> i = j <del> except: <add> except ValueError: <ide> new_word.extend(word[i:]) <ide> break <add> else: <add> new_word.extend(word[i:j]) <add> i = j <ide> <ide> if word[i] == first and i < len(word) - 1 and word[i + 1] == second: <ide> new_word.append(first + second) <ide><path>transformers/tokenization_xlm.py <ide> def bpe(self, token): <ide> while i < len(word): <ide> try: <ide> j = word.index(first, i) <del> new_word.extend(word[i:j]) <del> i = j <del> except: <add> except ValueError: <ide> new_word.extend(word[i:]) <ide> break <add> else: <add> new_word.extend(word[i:j]) <add> i = j <ide> <ide> if word[i] == first and i < len(word) - 1 and word[i + 1] == second: <ide> new_word.append(first + second)
20
Python
Python
fix init for pymorphy2_lookup lemmatizer mode
fe06e037bcd733708401bce082863994b1fc48bd
<ide><path>spacy/lang/ru/lemmatizer.py <ide> def __init__( <ide> overwrite: bool = False, <ide> scorer: Optional[Callable] = lemmatizer_score, <ide> ) -> None: <del> if mode == "pymorphy2": <add> if mode in {"pymorphy2", "pymorphy2_lookup"}: <ide> try: <ide> from pymorphy2 import MorphAnalyzer <ide> except ImportError: <ide><path>spacy/lang/uk/lemmatizer.py <ide> def __init__( <ide> overwrite: bool = False, <ide> scorer: Optional[Callable] = lemmatizer_score, <ide> ) -> None: <del> if mode == "pymorphy2": <add> if mode in {"pymorphy2", "pymorphy2_lookup"}: <ide> try: <ide> from pymorphy2 import MorphAnalyzer <ide> except ImportError: <ide><path>spacy/tests/conftest.py <ide> def ru_lemmatizer(): <ide> return get_lang_class("ru")().add_pipe("lemmatizer") <ide> <ide> <add>@pytest.fixture <add>def ru_lookup_lemmatizer(): <add> pytest.importorskip("pymorphy2") <add> return get_lang_class("ru")().add_pipe( <add> "lemmatizer", config={"mode": "pymorphy2_lookup"} <add> ) <add> <add> <ide> @pytest.fixture(scope="session") <ide> def sa_tokenizer(): <ide> return get_lang_class("sa")().tokenizer <ide> def uk_lemmatizer(): <ide> return get_lang_class("uk")().add_pipe("lemmatizer") <ide> <ide> <add>@pytest.fixture <add>def uk_lookup_lemmatizer(): <add> pytest.importorskip("pymorphy2") <add> pytest.importorskip("pymorphy2_dicts_uk") <add> return get_lang_class("uk")().add_pipe( <add> "lemmatizer", config={"mode": "pymorphy2_lookup"} <add> ) <add> <add> <ide> @pytest.fixture(scope="session") <ide> def ur_tokenizer(): <ide> return get_lang_class("ur")().tokenizer <ide><path>spacy/tests/lang/ru/test_lemmatizer.py <ide> def test_ru_lemmatizer_punct(ru_lemmatizer): <ide> assert ru_lemmatizer.pymorphy2_lemmatize(doc[0]) == ['"'] <ide> doc = Doc(ru_lemmatizer.vocab, words=["»"], pos=["PUNCT"]) <ide> assert ru_lemmatizer.pymorphy2_lemmatize(doc[0]) == ['"'] <add> <add> <add>def test_ru_doc_lookup_lemmatization(ru_lookup_lemmatizer): <add> words = ["мама", "мыла", "раму"] <add> pos = ["NOUN", "VERB", "NOUN"] <add> morphs = [ <add> "Animacy=Anim|Case=Nom|Gender=Fem|Number=Sing", <add> "Aspect=Imp|Gender=Fem|Mood=Ind|Number=Sing|Tense=Past|VerbForm=Fin|Voice=Act", <add> "Animacy=Anim|Case=Acc|Gender=Fem|Number=Sing", <add> ] <add> doc = Doc(ru_lookup_lemmatizer.vocab, words=words, pos=pos, morphs=morphs) <add> doc = ru_lookup_lemmatizer(doc) <add> lemmas = [token.lemma_ for token in doc] <add> assert lemmas == ["мама", "мыла", "раму"] <ide><path>spacy/tests/lang/uk/test_lemmatizer.py <ide> def test_uk_lemmatizer(uk_lemmatizer): <ide> """Check that the default uk lemmatizer runs.""" <ide> doc = Doc(uk_lemmatizer.vocab, words=["a", "b", "c"]) <ide> uk_lemmatizer(doc) <add> assert [token.lemma for token in doc] <add> <add> <add>def test_uk_lookup_lemmatizer(uk_lookup_lemmatizer): <add> """Check that the lookup uk lemmatizer runs.""" <add> doc = Doc(uk_lookup_lemmatizer.vocab, words=["a", "b", "c"]) <add> uk_lookup_lemmatizer(doc) <add> assert [token.lemma for token in doc]
5
Java
Java
fix javadoc for mediatype
91ae711a541808ff28791da2e0f9bc8b06fd7ae7
<ide><path>spring-web/src/main/java/org/springframework/http/MediaType.java <ide> public MediaType(MediaType other, Charset charset) { <ide> <ide> /** <ide> * Copy-constructor that copies the type and subtype of the given {@code MediaType}, <del> * and allows for different parameter. <add> * and allows for different parameters. <ide> * @param other the other media type <ide> * @param parameters the parameters, may be {@code null} <ide> * @throws IllegalArgumentException if any of the parameters contain illegal characters <ide> public double getQualityValue() { <ide> * <p>For instance, {@code text/*} includes {@code text/plain} and {@code text/html}, <ide> * and {@code application/*+xml} includes {@code application/soap+xml}, etc. <ide> * This method is <b>not</b> symmetric. <del> * <p>Simply calls {@link #includes(MimeType)} but declared with a <add> * <p>Simply calls {@link MimeType#includes(MimeType)} but declared with a <ide> * {@code MediaType} parameter for binary backwards compatibility. <ide> * @param other the reference media type with which to compare <ide> * @return {@code true} if this media type includes the given media type; <ide> public boolean includes(@Nullable MediaType other) { <ide> * <p>For instance, {@code text/*} is compatible with {@code text/plain}, <ide> * {@code text/html}, and vice versa. In effect, this method is similar to <ide> * {@link #includes}, except that it <b>is</b> symmetric. <del> * <p>Simply calls {@link #isCompatibleWith(MimeType)} but declared with a <add> * <p>Simply calls {@link MimeType#isCompatibleWith(MimeType)} but declared with a <ide> * {@code MediaType} parameter for binary backwards compatibility. <ide> * @param other the reference media type with which to compare <ide> * @return {@code true} if this media type is compatible with the given media type;
1
PHP
PHP
fix docblock to be consistent with implementation
76c64672bf5de65cf1514cbe051d0207f9469c87
<ide><path>src/Illuminate/Contracts/Foundation/Application.php <ide> public function boot(); <ide> /** <ide> * Register a new boot listener. <ide> * <del> * @param mixed $callback <add> * @param callable $callback <ide> * @return void <ide> */ <ide> public function booting($callback); <ide> <ide> /** <ide> * Register a new "booted" listener. <ide> * <del> * @param mixed $callback <add> * @param callable $callback <ide> * @return void <ide> */ <ide> public function booted($callback);
1
Text
Text
add npm clean command
c77924664540b1cd89dd075d76b477af9190f31b
<ide><path>docs/how-to-setup-freecodecamp-locally.md <ide> There might be an error in the console of your browser or in Bash / Terminal / C <ide> If the app launches but you are encountering errors with the UI itself, for example if fonts are not being loaded or if the code editor is not displaying properly, you may try the following troubleshooting steps at least once: <ide> <ide> ```shell <del># Remove all installed node modules <del>rm -rf node_modules ./**/node_modules <add># We use a mono repo and have multiple components (server, client, tools, plugins, etc.) <add># Use this command to clean up all dependencies in all of the components <add>npm run clean <ide> <ide> # Reinstall npm packages <ide> npm install <ide> npm run bootstrap <ide> # Seed the database <ide> npm run seed <ide> <del># Re-start the application <add># Restart the application <ide> npm run develop <ide> ```
1
Javascript
Javascript
reorganize the top level around a fiberroot
7d028fd8cc047f4ae3739f9d380bf59640ea8129
<ide><path>src/renderers/shared/fiber/ReactFiber.js <ide> exports.cloneFiber = function(fiber : Fiber, priorityLevel : PriorityLevel) : Fi <ide> // Stop using the alternates of parents once we have a parent stack. <ide> // $FlowFixMe: This downcast is not safe. It is intentionally an error. <ide> alt.parent = fiber.parent.alternate; <add> if (!alt.parent) { <add> // TODO: There needs to be a "work in progress" tree all the way up to <add> // the final root. <add> throw new Error('The parent must have an alternate already.'); <add> } <ide> } <ide> <ide> alt.type = fiber.type; <ide> exports.cloneFiber = function(fiber : Fiber, priorityLevel : PriorityLevel) : Fi <ide> return alt; <ide> }; <ide> <del>exports.createHostContainerFiber = function(containerInfo : ?Object, priorityLevel : PriorityLevel) { <add>exports.createHostContainerFiber = function() { <ide> const fiber = createFiber(HostContainer, null); <del> fiber.stateNode = containerInfo; <del> fiber.pendingWorkPriority = priorityLevel; <ide> return fiber; <ide> }; <ide> <ide><path>src/renderers/shared/fiber/ReactFiberReconciler.js <ide> <ide> import type { Fiber } from 'ReactFiber'; <ide> import type { PriorityLevel } from 'ReactPriorityLevel'; <add>import type { FiberRoot } from 'ReactFiberRoot'; <ide> <ide> var ReactFiber = require('ReactFiber'); <ide> var { beginWork } = require('ReactFiberBeginWork'); <ide> var { completeWork } = require('ReactFiberCompleteWork'); <add>var { createFiberRoot } = require('ReactFiberRoot'); <ide> <ide> var { <ide> NoWork, <ide> module.exports = function<T, P, I>(config : HostConfig<T, P, I>) : Reconciler { <ide> // const scheduleHighPriCallback = config.scheduleHighPriCallback; <ide> const scheduleLowPriCallback = config.scheduleLowPriCallback; <ide> <add> // The next work in progress fiber that we're currently working on. <ide> let nextUnitOfWork : ?Fiber = null; <ide> <del> let currentRootsWithPendingWork : ?Fiber = null; <add> // Linked list of roots with scheduled work on them. <add> let nextScheduledRoot : ?FiberRoot = null; <add> let lastScheduledRoot : ?FiberRoot = null; <ide> <del> function findNextUnitOfWorkAtPriority(priorityLevel : PriorityLevel) : ?Fiber { <del> let current = currentRootsWithPendingWork; <add> function findNextUnitOfWorkAtPriority(root : FiberRoot, priorityLevel : PriorityLevel) : ?Fiber { <add> let current = root.current; <ide> while (current) { <ide> if (current.pendingWorkPriority !== 0 && <ide> current.pendingWorkPriority <= priorityLevel) { <ide> module.exports = function<T, P, I>(config : HostConfig<T, P, I>) : Reconciler { <ide> // TODO: Coroutines can have work in their stateNode which is another <ide> // type of child that needs to be searched for work. <ide> if (current.child) { <add> // Ensure we have a work in progress copy to backtrack through. <add> ReactFiber.cloneFiber(current, NoWork); <ide> current = current.child; <ide> continue; <ide> } <ide> module.exports = function<T, P, I>(config : HostConfig<T, P, I>) : Reconciler { <ide> } <ide> <ide> function findNextUnitOfWork() { <del> // Find the highest possible priority work to do. <del> // This loop is unrolled just to satisfy Flow's enum constraint. <del> // We could make arbitrary many idle priority levels but having <del> // too many just means flushing changes too often. <del> let work = findNextUnitOfWorkAtPriority(HighPriority); <del> if (!work) { <del> work = findNextUnitOfWorkAtPriority(LowPriority); <del> if (!work) { <del> work = findNextUnitOfWorkAtPriority(OffscreenPriority); <add> // Clear out roots with no more work on them. <add> while (nextScheduledRoot && nextScheduledRoot.current.pendingWorkPriority === NoWork) { <add> nextScheduledRoot.isScheduled = false; <add> if (nextScheduledRoot === lastScheduledRoot) { <add> nextScheduledRoot = null; <add> lastScheduledRoot = null; <add> return null; <ide> } <add> nextScheduledRoot = nextScheduledRoot.nextScheduledRoot; <ide> } <del> return work; <add> let root = nextScheduledRoot; <add> while (root) { <add> // Find the highest possible priority work to do. <add> // This loop is unrolled just to satisfy Flow's enum constraint. <add> // We could make arbitrary many idle priority levels but having <add> // too many just means flushing changes too often. <add> let work = findNextUnitOfWorkAtPriority(root, HighPriority); <add> if (work) { <add> return work; <add> } <add> work = findNextUnitOfWorkAtPriority(root, LowPriority); <add> if (work) { <add> return work; <add> } <add> work = findNextUnitOfWorkAtPriority(root, OffscreenPriority); <add> if (work) { <add> return work; <add> } <add> // We didn't find anything to do in this root, so let's try the next one. <add> root = root.nextScheduledRoot; <add> } <add> return null; <ide> } <ide> <ide> function completeUnitOfWork(workInProgress : Fiber) : ?Fiber { <ide> module.exports = function<T, P, I>(config : HostConfig<T, P, I>) : Reconciler { <ide> // If there's no more work in this parent. Complete the parent. <ide> workInProgress = parent; <ide> } else { <del> // If we're at the root, there's no more work to do. <del> console.log('completed flush with remaining work at priority', workInProgress.pendingWorkPriority); <del> if (workInProgress.pendingWorkPriority !== NoWork) { <del> // TODO: This removes all but one node. Broken. <del> currentRootsWithPendingWork = workInProgress; <del> const nextWork = findNextUnitOfWork(); <del> if (!nextWork) { <del> // Something went wrong and there wasn't actually any more work. <del> // TODO: This currently fails because of the parent/root hacks. <del> // throw new Error('Should never finish with a priority level unless there is work.'); <del> currentRootsWithPendingWork = null; <del> return null; <del> } <del> return nextWork; <del> } else { <del> currentRootsWithPendingWork = null; <del> return null; <add> // If we're at the root, there's no more work to do. We can flush it. <add> const root : FiberRoot = (workInProgress.stateNode : any); <add> root.current = workInProgress; <add> console.log('completed one root flush with remaining work at priority', workInProgress.pendingWorkPriority); <add> const hasMoreWork = workInProgress.pendingWorkPriority !== NoWork; <add> // TODO: We can be smarter here and only look for more work in the <add> // "next" scheduled work since we've already scanned passed. That <add> // also ensures that work scheduled during reconciliation gets deferred. <add> const nextWork = findNextUnitOfWork(); <add> if (!nextWork && hasMoreWork) { <add> throw new Error('FiberRoots should not have flagged more work if there is none.'); <ide> } <add> return nextWork; <ide> } <ide> } <ide> } <ide> module.exports = function<T, P, I>(config : HostConfig<T, P, I>) : Reconciler { <ide> while (nextUnitOfWork) { <ide> if (deadline.timeRemaining() > timeHeuristicForUnitOfWork) { <ide> nextUnitOfWork = performUnitOfWork(nextUnitOfWork); <add> if (!nextUnitOfWork) { <add> // Find more work. We might have time to complete some more. <add> nextUnitOfWork = findNextUnitOfWork(); <add> } <ide> } else { <ide> scheduleLowPriCallback(performLowPriWork); <del> break; <add> return; <ide> } <ide> } <ide> } <ide> <del> function scheduleLowPriWork(root : Fiber) { <add> function scheduleLowPriWork(root : FiberRoot) { <ide> // We must reset the current unit of work pointer so that we restart the <del> // search from the root during the next tick. <add> // search from the root during the next tick, in case there is now higher <add> // priority work somewhere earlier than before. <ide> nextUnitOfWork = null; <ide> <del> if (currentRootsWithPendingWork) { <del> if (root === currentRootsWithPendingWork) { <del> // We're already scheduled. <del> return; <del> } <del> // We already have some work pending in another root. Add this to the <del> // linked list. <del> let previousSibling = currentRootsWithPendingWork; <del> while (previousSibling.sibling) { <del> previousSibling = previousSibling.sibling; <del> if (root === previousSibling) { <del> // We're already scheduled. <del> return; <del> } <del> } <del> previousSibling.sibling = root; <add> if (root.isScheduled) { <add> // If we're already scheduled, we can bail out. <add> return; <add> } <add> root.isScheduled = true; <add> if (lastScheduledRoot) { <add> // Schedule ourselves to the end. <add> lastScheduledRoot.nextScheduledRoot = root; <add> lastScheduledRoot = root; <ide> } else { <del> // We're the first and only root with new changes. <del> currentRootsWithPendingWork = root; <del> root.sibling = null; <del> // Ensure we will get another callback to process the work. <add> // We're the only work scheduled. <add> nextScheduledRoot = root; <add> lastScheduledRoot = root; <ide> scheduleLowPriCallback(performLowPriWork); <ide> } <ide> } <ide> module.exports = function<T, P, I>(config : HostConfig<T, P, I>) : Reconciler { <ide> return { <ide> <ide> mountContainer(element : ReactElement<any>, containerInfo : ?Object) : OpaqueNode { <del> const container = ReactFiber.createHostContainerFiber(containerInfo, LowPriority); <del> container.alternate = container; <add> const root = createFiberRoot(containerInfo); <add> const container = root.current; <add> // TODO: Use pending work/state instead of props. <ide> container.pendingProps = element; <add> container.pendingWorkPriority = LowPriority; <ide> <del> scheduleLowPriWork(container); <add> scheduleLowPriWork(root); <ide> <add> // It may seem strange that we don't return the root here, but that will <add> // allow us to have containers that are in the middle of the tree instead <add> // of being roots. <ide> return container; <ide> }, <ide> <ide> updateContainer(element : ReactElement<any>, container : OpaqueNode) : void { <del> container.pendingProps = element; <del> container.pendingWorkPriority = LowPriority; <add> // TODO: If this is a nested container, this won't be the root. <add> const root : FiberRoot = (container.stateNode : any); <add> // TODO: Use pending work/state instead of props. <add> root.current.pendingProps = element; <add> root.current.pendingWorkPriority = LowPriority; <ide> <del> scheduleLowPriWork(container); <add> scheduleLowPriWork(root); <ide> }, <ide> <ide> unmountContainer(container : OpaqueNode) : void { <del> container.pendingProps = []; <del> container.pendingWorkPriority = LowPriority; <add> // TODO: If this is a nested container, this won't be the root. <add> const root : FiberRoot = (container.stateNode : any); <add> // TODO: Use pending work/state instead of props. <add> root.current.pendingProps = []; <add> root.current.pendingWorkPriority = LowPriority; <ide> <del> scheduleLowPriWork(container); <add> scheduleLowPriWork(root); <ide> }, <ide> <ide> getPublicRootInstance(container : OpaqueNode) : ?Object { <ide><path>src/renderers/shared/fiber/ReactFiberRoot.js <add>/** <add> * Copyright 2013-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> * <add> * @providesModule ReactFiberRoot <add> * @flow <add> */ <add> <add>'use strict'; <add> <add>import type { Fiber } from 'ReactFiber'; <add> <add>const { createHostContainerFiber } = require('ReactFiber'); <add> <add>export type FiberRoot = { <add> // Any additional information from the host associated with this root. <add> containerInfo: ?Object, <add> // The currently active root fiber. This is the mutable root of the tree. <add> current: Fiber, <add> // Determines if this root has already been added to the schedule for work. <add> isScheduled: bool, <add> // The work schedule is a linked list. <add> nextScheduledRoot: ?FiberRoot, <add>}; <add> <add>exports.createFiberRoot = function(containerInfo : ?Object) : FiberRoot { <add> // Cyclic construction. This cheats the type system right now because <add> // stateNode is any. <add> const uninitializedFiber = createHostContainerFiber(); <add> const root = { <add> current: uninitializedFiber, <add> containerInfo: containerInfo, <add> isScheduled: false, <add> nextScheduledRoot: null, <add> }; <add> uninitializedFiber.stateNode = root; <add> return root; <add>}; <ide><path>src/renderers/shared/fiber/__tests__/ReactIncremental-test.js <ide> describe('ReactIncremental', function() { <ide> ReactNoop.render(<Foo text="foo" />); <ide> ReactNoop.flush(); <ide> <add> expect(ops).toEqual(['Foo', 'Bar', 'Bar', 'Middle']); <add> <ide> ops = []; <ide> <ide> // Render part of the work. This should be enough to flush everything except
4
Java
Java
provide configurationclass#tostring implementation
faba5941f74ab6967cc712b7c4ce25c026c7fb88
<ide><path>org.springframework.context/src/main/java/org/springframework/context/annotation/ConfigurationClass.java <ide> public int hashCode() { <ide> return getMetadata().getClassName().hashCode(); <ide> } <ide> <add> @Override <add> public String toString() { <add> return String.format("[ConfigurationClass:beanName=%s,resource=%s]", this.beanName, this.resource); <add> } <add> <ide> <ide> /** <ide> * Configuration classes must be non-final to accommodate CGLIB subclassing.
1
Text
Text
restore h1 headings for pages with front matter
2427e063402d3196c7ffd3515013ab5419458cd8
<ide><path>docs/Brew-Test-Bot.md <ide> --- <del>title: Brew Test Bot <ide> logo: https://brew.sh/assets/img/brewtestbot.png <ide> image: https://brew.sh/assets/img/brewtestbot.png <ide> --- <add> <add># Brew Test Bot <add> <ide> `brew test-bot` is the name for the automated review and testing system funded <ide> by [our Kickstarter in 2013](https://www.kickstarter.com/projects/homebrew/brew-test-bot). <ide> <ide><path>docs/Homebrew-on-Linux.md <ide> --- <del>title: Homebrew on Linux <ide> logo: https://brew.sh/assets/img/linuxbrew.png <ide> image: https://brew.sh/assets/img/linuxbrew.png <ide> redirect_from: <ide> - /linux <ide> - /Linux <ide> - /Linuxbrew <ide> --- <add> <add># Homebrew on Linux <add> <ide> The Homebrew package manager may be used on Linux and [Windows Subsystem for Linux (WSL)](https://docs.microsoft.com/en-us/windows/wsl/about). Homebrew was formerly referred to as Linuxbrew when running on Linux or WSL. It can be installed in your home directory, in which case it does not use *sudo*. Homebrew does not use any libraries provided by your host system, except *glibc* and *gcc* if they are new enough. Homebrew can install its own current versions of *glibc* and *gcc* for older distributions of Linux. <ide> <del>[Features](#features), [dependencies](#dependencies) and [installation instructions](#install) are described below. Terminology (e.g. the difference between a Cellar, Tap, Cask and so forth) is [explained in the documentation](Formula-Cookbook.md#homebrew-terminology). <add>[Features](#features), [installation instructions](#install) and [requirements](#requirements) are described below. Terminology (e.g. the difference between a Cellar, Tap, Cask and so forth) is [explained in the documentation](Formula-Cookbook.md#homebrew-terminology). <ide> <ide> ## Features <ide> <ide> You're done! Try installing a package: <ide> brew install hello <ide> ``` <ide> <del>If you're using an older distribution of Linux, installing your first package will also install a recent version of `glibc` and `gcc`. Use `brew doctor` to troubleshoot common issues. <add>If you're using an older distribution of Linux, installing your first package will also install a recent version of *glibc* and *gcc*. Use `brew doctor` to troubleshoot common issues. <ide> <ide> ## Requirements <ide> <ide> sudo yum install libxcrypt-compat # needed by Fedora 30 and up <ide> <ide> Homebrew can run on 32-bit ARM (Raspberry Pi and others) and 64-bit ARM (AArch64), but no binary packages (bottles) are available. Support for ARM is on a best-effort basis. Pull requests are welcome to improve the experience on ARM platforms. <ide> <del>You may need to install your own Ruby using your system package manager, a PPA, or `rbenv/ruby-build` as in the future we will no longer distribute a Homebrew Portable Ruby for ARM. <add>You may need to install your own Ruby using your system package manager, a PPA, or `rbenv/ruby-build` as we no longer distribute a Homebrew Portable Ruby for ARM. <ide> <ide> ### 32-bit x86 <ide>
2
Javascript
Javascript
avoid boolean coercion when checking for object
55031ce070aa38edbc4ba6eda166d316a9fd4860
<ide><path>packages/ember-metal/lib/merge.js <ide> @public <ide> */ <ide> export default function merge(original, updates) { <del> if (!updates || typeof updates !== 'object') { <add> if (updates === null || typeof updates !== 'object') { <ide> return original; <ide> } <ide> <ide><path>packages/ember-metal/lib/set_properties.js <ide> import { set } from './property_set'; <ide> @public <ide> */ <ide> export default function setProperties(obj, properties) { <del> if (!properties || typeof properties !== 'object') { return properties; } <add> if (properties === null || typeof properties !== 'object') { return properties; } <ide> changeProperties(() => { <ide> let props = Object.keys(properties); <ide> let propertyName;
2
Ruby
Ruby
prevent repeated lookups of nil-valued keys
c2fd7856d207dca4ec498ea611eec2cdeb40a617
<ide><path>Library/Homebrew/macos.rb <ide> def locate tool <ide> # Don't call tools (cc, make, strip, etc.) directly! <ide> # Give the name of the binary you look for as a string to this method <ide> # in order to get the full path back as a Pathname. <del> @locate ||= {} <del> @locate[tool.to_s] ||= if File.executable? "/usr/bin/#{tool}" <del> Pathname.new "/usr/bin/#{tool}" <del> else <del> # If the tool isn't in /usr/bin, then we first try to use xcrun to find <del> # it. If it's not there, or xcode-select is misconfigured, we have to <del> # look in dev_tools_path, and finally in xctoolchain_path, because the <del> # tools were split over two locations beginning with Xcode 4.3+. <del> xcrun_path = unless Xcode.bad_xcode_select_path? <del> `/usr/bin/xcrun -find #{tool} 2>/dev/null`.chomp <del> end <add> (@locate ||= {}).fetch(tool.to_s) do <add> @locate[tool.to_s] = if File.executable? "/usr/bin/#{tool}" <add> Pathname.new "/usr/bin/#{tool}" <add> else <add> # If the tool isn't in /usr/bin, then we first try to use xcrun to find <add> # it. If it's not there, or xcode-select is misconfigured, we have to <add> # look in dev_tools_path, and finally in xctoolchain_path, because the <add> # tools were split over two locations beginning with Xcode 4.3+. <add> xcrun_path = unless Xcode.bad_xcode_select_path? <add> `/usr/bin/xcrun -find #{tool} 2>/dev/null`.chomp <add> end <ide> <del> paths = %W[#{xcrun_path} <del> #{dev_tools_path}/#{tool} <del> #{xctoolchain_path}/usr/bin/#{tool}] <del> paths.map { |p| Pathname.new(p) }.find { |p| p.executable? } <add> paths = %W[#{xcrun_path} <add> #{dev_tools_path}/#{tool} <add> #{xctoolchain_path}/usr/bin/#{tool}] <add> paths.map { |p| Pathname.new(p) }.find { |p| p.executable? } <add> end <ide> end <ide> end <ide> <ide> def xctoolchain_path <ide> end <ide> <ide> def sdk_path(v = version) <del> @sdk_path ||= {} <del> @sdk_path[v.to_s] ||= begin <del> opts = [] <del> # First query Xcode itself <del> opts << `#{locate('xcodebuild')} -version -sdk macosx#{v} Path 2>/dev/null`.chomp unless Xcode.bad_xcode_select_path? <del> # Xcode.prefix is pretty smart, so lets look inside to find the sdk <del> opts << "#{Xcode.prefix}/Platforms/MacOSX.platform/Developer/SDKs/MacOSX#{v}.sdk" <del> # Xcode < 4.3 style <del> opts << "/Developer/SDKs/MacOSX#{v}.sdk" <del> opts.map{|a| Pathname.new(a) }.detect { |p| p.directory? } <add> (@sdk_path ||= {}).fetch(v.to_s) do <add> @sdk_path[v.to_s] = begin <add> opts = [] <add> # First query Xcode itself <add> opts << `#{locate('xcodebuild')} -version -sdk macosx#{v} Path 2>/dev/null`.chomp unless Xcode.bad_xcode_select_path? <add> # Xcode.prefix is pretty smart, so lets look inside to find the sdk <add> opts << "#{Xcode.prefix}/Platforms/MacOSX.platform/Developer/SDKs/MacOSX#{v}.sdk" <add> # Xcode < 4.3 style <add> opts << "/Developer/SDKs/MacOSX#{v}.sdk" <add> opts.map{|a| Pathname.new(a) }.detect { |p| p.directory? } <add> end <ide> end <ide> end <ide>
1
Python
Python
add extra utility function into ec2 driver
ffab16d53312bc9eb7eacbf713b49af6230e94e7
<ide><path>libcloud/compute/drivers/ec2.py <ide> def _to_reserved_node(self, element): <ide> extra_attributes_map = { <ide> 'instance_type': { <ide> 'xpath': 'instanceType', <del> 'type': str <add> 'cast_func': str <ide> }, <ide> 'availability': { <ide> 'xpath': 'availabilityZone', <del> 'type': str <add> 'cast_func': str <ide> }, <ide> 'start': { <ide> 'xpath': 'start', <del> 'type': str <add> 'cast_func': str <ide> }, <ide> 'duration': { <ide> 'xpath': 'duration', <del> 'type': int <add> 'cast_func': int <ide> }, <ide> 'usage_price': { <ide> 'xpath': 'usagePrice', <del> 'type': float <add> 'cast_func': float <ide> }, <ide> 'fixed_price': { <ide> 'xpath': 'fixedPrice', <del> 'type': float <add> 'cast_func': float <ide> }, <ide> 'instance_count': { <ide> 'xpath': 'instanceCount', <del> 'type': int <add> 'cast_func': int <ide> }, <ide> 'description': { <ide> 'xpath': 'productDescription', <del> 'type': str <add> 'cast_func': str <ide> }, <ide> 'instance_tenancy': { <ide> 'xpath': 'instanceTenancy', <del> 'type': str <add> 'cast_func': str <ide> }, <ide> 'currency_code': { <ide> 'xpath': 'currencyCode', <del> 'type': str <add> 'cast_func': str <ide> }, <ide> 'offering_type': { <ide> 'xpath': 'offeringType', <del> 'type': str <add> 'cast_func': str <ide> } <ide> } <ide> <del> # Define and build our extra dictionary <del> extra = {} <del> for attribute, values in extra_attributes_map.items(): <del> type_func = values['type'] <del> value = findattr(element=element, xpath=values['xpath'], <del> namespace=NAMESPACE) <del> extra[attribute] = type_func(value) <add> # Get our extra dictionary <add> extra = self._get_extra_dict(element, extra_attributes_map) <ide> <ide> try: <ide> size = [size for size in self.list_sizes() if <ide> def _to_volume(self, element, name=None): <ide> } <ide> } <ide> <del> # Define and build our extra dictionary <del> extra = {} <del> for attribute, values in extra_attributes_map.items(): <del> cast_func = values['cast_func'] <del> value = findattr(element=element, xpath=values['xpath'], <del> namespace=NAMESPACE) <del> if value is not None: <del> extra[attribute] = cast_func(value) <del> else: <del> extra[attribute] = None <add> # Get our extra dictionary <add> extra = self._get_extra_dict(element, extra_attributes_map) <ide> <ide> return StorageVolume(id=volId, <ide> name=name, <ide> def _to_network(self, element): <ide> extra_attributes_map = { <ide> 'state': { <ide> 'xpath': 'state', <del> 'type': str <add> 'cast_func': str <ide> }, <ide> 'dhcp_options_id': { <ide> 'xpath': 'dhcpOptionsId', <del> 'type': str <add> 'cast_func': str <ide> }, <ide> 'instance_tenancy': { <ide> 'xpath': 'instanceTenancy', <del> 'type': str <add> 'cast_func': str <ide> }, <ide> 'is_default': { <ide> 'xpath': 'isDefault', <del> 'type': str <add> 'cast_func': str <ide> } <ide> } <ide> <del> # Define and build our extra dictionary <del> extra = {} <del> for attribute, values in extra_attributes_map.items(): <del> type_func = values['type'] <del> value = findattr(element=element, xpath=values['xpath'], <del> namespace=NAMESPACE) <del> extra[attribute] = type_func(value) <add> # Get our extra dictionary <add> extra = self._get_extra_dict(element, extra_attributes_map) <ide> <ide> # Add tags to the extra dict <ide> extra['tags'] = tags <ide> def _to_subnet(self, element): <ide> extra_attributes_map = { <ide> 'cidr_block': { <ide> 'xpath': 'cidrBlock', <del> 'type': str <add> 'cast_func': str <ide> }, <ide> 'available_ips': { <ide> 'xpath': 'availableIpAddressCount', <del> 'type': int <add> 'cast_func': int <ide> }, <ide> 'zone': { <ide> 'xpath': 'availabilityZone', <del> 'type': str <add> 'cast_func': str <ide> }, <ide> 'vpc_id': { <ide> 'xpath': 'vpcId', <del> 'type': str <add> 'cast_func': str <ide> } <ide> } <ide> <del> # Define and build our extra dictionary <del> extra = {} <del> for attribute, values in extra_attributes_map.items(): <del> type_func = values['type'] <del> value = findattr(element=element, xpath=values['xpath'], <del> namespace=NAMESPACE) <del> extra[attribute] = type_func(value) <add> # Get our extra dictionary <add> extra = self._get_extra_dict(element, extra_attributes_map) <ide> <ide> # Also include our tags <ide> extra['tags'] = tags <ide> def ex_get_console_output(self, node): <ide> 'timestamp': timestamp, <ide> 'output': output} <ide> <add> def _get_extra_dict(self, element, mapping): <add> """ <add> Build the extra dictionary based on an attribute mapping <add> <add> :param mapping: Dictionary with the extra layout <add> :type node: :class:`Node` <add> <add> :rtype: ``dict`` <add> """ <add> extra = {} <add> for attribute, values in mapping.items(): <add> cast_func = values['cast_func'] <add> value = findattr(element=element, <add> xpath=values['xpath'], <add> namespace=NAMESPACE) <add> <add> if value is not None: <add> extra[attribute] = cast_func(value) <add> else: <add> extra[attribute] = None <add> <add> return extra <add> <ide> def _get_resource_tags(self, element): <ide> """ <ide> Parse tags from the provided element and return a dictionary with
1
Text
Text
remove trailing whitespaces
f906ca52eacf93bc98b97b0d9b7af1a606029661
<ide><path>project/ISSUE-TRIAGE.md <ide> Triaging of issues <ide> ------------------ <ide> <del>Triage provides an important way to contribute to an open source project. Triage helps ensure issues resolve quickly by: <add>Triage provides an important way to contribute to an open source project. Triage helps ensure issues resolve quickly by: <ide> <del>- Describing the issue's intent and purpose is conveyed precisely. This is necessary because it can be difficult for an issue to explain how an end user experiences an problem and what actions they took. <del>- Giving a contributor the information they need before they commit to resolving an issue. <add>- Describing the issue's intent and purpose is conveyed precisely. This is necessary because it can be difficult for an issue to explain how an end user experiences an problem and what actions they took. <add>- Giving a contributor the information they need before they commit to resolving an issue. <ide> - Lowering the issue count by preventing duplicate issues. <ide> - Streamlining the development process by preventing duplicate discussions. <ide> <ide> Before triaging an issue very far, make sure that the issue's author provided th <ide> - the output of `uname -a` <ide> - a reproducible case if this is a bug, Dockerfiles FTW <ide> - host distribution and version ( ubuntu 14.04, RHEL, fedora 23 ) <del>- page URL if this is a docs issue or the name of a man page <add>- page URL if this is a docs issue or the name of a man page <ide> <del>Depending on the issue, you might not feel all this information is needed. Use your best judgement. If you cannot triage an issue using what its author provided, explain kindly to the author that they must provide the above information to clarify the problem. <add>Depending on the issue, you might not feel all this information is needed. Use your best judgement. If you cannot triage an issue using what its author provided, explain kindly to the author that they must provide the above information to clarify the problem. <ide> <ide> If the author provides the standard information but you are still unable to triage the issue, request additional information. Do this kindly and politely because you are asking for more of the author's time. <ide> <ide> urgent). <ide> | priority/P3 | Best effort: those are nice to have / minor issues. | <ide> <ide> And that's it. That should be all the information required for a new or existing contributor to come in an resolve an issue. <del>
1
Ruby
Ruby
reduce texttemplate cost for simple cases
c5e73b897616049c613b0331dd53e88dbc9c1532
<ide><path>actionpack/lib/action_dispatch/http/mime_type.rb <ide> def #{method}(*args) <ide> LOOKUP = Hash.new { |h, k| h[k] = Type.new(k) unless k.blank? } <ide> <ide> def self.[](type) <add> return type if type.is_a?(Type) <ide> Type.lookup_by_extension(type.to_s) <ide> end <ide> <ide><path>actionpack/lib/action_view/template/text.rb <ide> module ActionView #:nodoc: <ide> class TextTemplate < String #:nodoc: <del> def initialize(string, content_type = Mime[:html]) <add> HTML = Mime[:html] <add> <add> def initialize(string, content_type = HTML) <ide> super(string.to_s) <ide> @content_type = Mime[content_type] || content_type <ide> end
2
Java
Java
fix handling of line height with inline images
c4ffc7d71c1c34599d3dd303e0b5bb674fa691f5
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextShadowNode.java <ide> protected static Spannable fromTextCSSNode(ReactTextShadowNode textCSSNode) { <ide> } <ide> <ide> textCSSNode.mContainsImages = false; <add> textCSSNode.mHeightOfTallestInlineImage = Float.NaN; <ide> <ide> // While setting the Spans on the final text, we also check whether any of them are images <ide> for (int i = ops.size() - 1; i >= 0; i--) { <ide> SetSpanOperation op = ops.get(i); <ide> if (op.what instanceof TextInlineImageSpan) { <add> int height = ((TextInlineImageSpan)op.what).getHeight(); <ide> textCSSNode.mContainsImages = true; <add> if (Float.isNaN(textCSSNode.mHeightOfTallestInlineImage) || height > textCSSNode.mHeightOfTallestInlineImage) { <add> textCSSNode.mHeightOfTallestInlineImage = height; <add> } <ide> } <ide> op.execute(sb); <ide> } <ide> public void measure( <ide> // technically, width should never be negative, but there is currently a bug in <ide> boolean unconstrainedWidth = widthMode == CSSMeasureMode.UNDEFINED || width < 0; <ide> <add> float effectiveLineHeight = reactCSSNode.getEffectiveLineHeight(); <add> float lineSpacingExtra = 0; <add> float lineSpacingMultiplier = 1; <add> if (!Float.isNaN(effectiveLineHeight)) { <add> lineSpacingExtra = effectiveLineHeight; <add> lineSpacingMultiplier = 0; <add> } <add> <ide> if (boring == null && <ide> (unconstrainedWidth || <ide> (!CSSConstants.isUndefined(desiredWidth) && desiredWidth <= width))) { <ide> public void measure( <ide> textPaint, <ide> (int) Math.ceil(desiredWidth), <ide> Layout.Alignment.ALIGN_NORMAL, <del> 1, <del> 0, <add> lineSpacingMultiplier, <add> lineSpacingExtra, <ide> true); <ide> } else if (boring != null && (unconstrainedWidth || boring.width <= width)) { <ide> // Is used for single-line, boring text when the width is either unknown or bigger <ide> public void measure( <ide> textPaint, <ide> boring.width, <ide> Layout.Alignment.ALIGN_NORMAL, <del> 1, <del> 0, <add> lineSpacingMultiplier, <add> lineSpacingExtra, <ide> boring, <ide> true); <ide> } else { <ide> public void measure( <ide> textPaint, <ide> (int) width, <ide> Layout.Alignment.ALIGN_NORMAL, <del> 1, <del> 0, <add> lineSpacingMultiplier, <add> lineSpacingExtra, <ide> true); <ide> } <ide> <ide> public void measure( <ide> reactCSSNode.mNumberOfLines < layout.getLineCount()) { <ide> measureOutput.height = layout.getLineBottom(reactCSSNode.mNumberOfLines - 1); <ide> } <del> if (reactCSSNode.mLineHeight != UNSET) { <del> int lines = reactCSSNode.mNumberOfLines != UNSET <del> ? Math.min(reactCSSNode.mNumberOfLines, layout.getLineCount()) <del> : layout.getLineCount(); <del> float lineHeight = PixelUtil.toPixelFromSP(reactCSSNode.mLineHeight); <del> measureOutput.height = lineHeight * lines; <del> } <ide> } <ide> }; <ide> <ide> private static int parseNumericFontWeight(String fontWeightString) { <ide> 100 * (fontWeightString.charAt(0) - '0') : -1; <ide> } <ide> <del> private int mLineHeight = UNSET; <add> private float mLineHeight = Float.NaN; <ide> private boolean mIsColorSet = false; <ide> private int mColor; <ide> private boolean mIsBackgroundColorSet = false; <ide> private static int parseNumericFontWeight(String fontWeightString) { <ide> private final boolean mIsVirtual; <ide> <ide> protected boolean mContainsImages = false; <add> private float mHeightOfTallestInlineImage = Float.NaN; <ide> <ide> public ReactTextShadowNode(boolean isVirtual) { <ide> mIsVirtual = isVirtual; <ide> public ReactTextShadowNode(boolean isVirtual) { <ide> } <ide> } <ide> <add> // Returns a line height which takes into account the requested line height <add> // and the height of the inline images. <add> public float getEffectiveLineHeight() { <add> boolean useInlineViewHeight = !Float.isNaN(mLineHeight) && <add> !Float.isNaN(mHeightOfTallestInlineImage) && <add> mHeightOfTallestInlineImage > mLineHeight; <add> return useInlineViewHeight ? mHeightOfTallestInlineImage : mLineHeight; <add> } <add> <ide> @Override <ide> public void onBeforeLayout() { <ide> if (mIsVirtual) { <ide> public void setNumberOfLines(int numberOfLines) { <ide> <ide> @ReactProp(name = ViewProps.LINE_HEIGHT, defaultInt = UNSET) <ide> public void setLineHeight(int lineHeight) { <del> mLineHeight = lineHeight; <add> mLineHeight = lineHeight == UNSET ? Float.NaN : PixelUtil.toPixelFromSP(lineHeight); <ide> markUpdated(); <ide> } <ide> <ide> public void onCollectExtraUpdates(UIViewOperationQueue uiViewOperationQueue) { <ide> super.onCollectExtraUpdates(uiViewOperationQueue); <ide> if (mPreparedSpannableText != null) { <ide> ReactTextUpdate reactTextUpdate = <del> new ReactTextUpdate(mPreparedSpannableText, UNSET, mContainsImages, getPadding()); <add> new ReactTextUpdate(mPreparedSpannableText, UNSET, mContainsImages, getPadding(), getEffectiveLineHeight()); <ide> uiViewOperationQueue.enqueueUpdateExtraData(getReactTag(), reactTextUpdate); <ide> } <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextUpdate.java <ide> public class ReactTextUpdate { <ide> private final float mPaddingTop; <ide> private final float mPaddingRight; <ide> private final float mPaddingBottom; <add> private final float mLineHeight; <ide> <ide> public ReactTextUpdate( <ide> Spannable text, <ide> int jsEventCounter, <ide> boolean containsImages, <del> Spacing padding) { <add> Spacing padding, <add> float lineHeight) { <ide> mText = text; <ide> mJsEventCounter = jsEventCounter; <ide> mContainsImages = containsImages; <ide> mPaddingLeft = padding.get(Spacing.LEFT); <ide> mPaddingTop = padding.get(Spacing.TOP); <ide> mPaddingRight = padding.get(Spacing.RIGHT); <ide> mPaddingBottom = padding.get(Spacing.BOTTOM); <add> mLineHeight = lineHeight; <ide> } <ide> <ide> public Spannable getText() { <ide> public float getPaddingRight() { <ide> public float getPaddingBottom() { <ide> return mPaddingBottom; <ide> } <add> <add> public float getLineHeight() { <add> return mLineHeight; <add> } <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextView.java <ide> import android.view.ViewGroup; <ide> import android.widget.TextView; <ide> <add>import com.facebook.csslayout.FloatUtil; <ide> import com.facebook.react.uimanager.ReactCompoundView; <ide> <ide> public class ReactTextView extends TextView implements ReactCompoundView { <ide> public class ReactTextView extends TextView implements ReactCompoundView { <ide> private int mDefaultGravityHorizontal; <ide> private int mDefaultGravityVertical; <ide> private boolean mTextIsSelectable; <add> private float mLineHeight = Float.NaN; <ide> <ide> public ReactTextView(Context context) { <ide> super(context); <ide> public void setText(ReactTextUpdate update) { <ide> (int) Math.ceil(update.getPaddingTop()), <ide> (int) Math.ceil(update.getPaddingRight()), <ide> (int) Math.ceil(update.getPaddingBottom())); <add> <add> float nextLineHeight = update.getLineHeight(); <add> if (!FloatUtil.floatsEqual(mLineHeight, nextLineHeight)) { <add> mLineHeight = nextLineHeight; <add> if (Float.isNaN(mLineHeight)) { // NaN will be used if property gets reset <add> setLineSpacing(0, 1); <add> } else { <add> setLineSpacing(mLineHeight, 0); <add> } <add> } <ide> } <ide> <ide> @Override <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextViewManager.java <ide> public void setTextAlignVertical(ReactTextView view, @Nullable String textAlignV <ide> } <ide> } <ide> <del> @ReactProp(name = ViewProps.LINE_HEIGHT, defaultFloat = Float.NaN) <del> public void setLineHeight(ReactTextView view, float lineHeight) { <del> if (Float.isNaN(lineHeight)) { // NaN will be used if property gets reset <del> view.setLineSpacing(0, 1); <del> } else { <del> view.setLineSpacing(PixelUtil.toPixelFromSP(lineHeight), 0); <del> } <del> } <del> <ide> @ReactProp(name = "selectable") <ide> public void setSelectable(ReactTextView view, boolean isSelectable) { <ide> view.setTextIsSelectable(isSelectable); <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/text/TextInlineImageSpan.java <ide> public static void possiblyUpdateInlineImageSpans(Spannable spannable, TextView <ide> * Set the textview that will contain this span. <ide> */ <ide> public abstract void setTextView(TextView textView); <add> <add> /** <add> * Get the width of the span. <add> */ <add> public abstract int getWidth(); <add> <add> /** <add> * Get the height of the span. <add> */ <add> public abstract int getHeight(); <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/text/frescosupport/FrescoBasedReactTextInlineImageSpan.java <ide> public void draw( <ide> <ide> canvas.save(); <ide> <del> int transY = bottom - mDrawable.getBounds().bottom; <del> <ide> // Align to baseline by default <del> transY -= paint.getFontMetricsInt().descent; <add> int transY = y - mDrawable.getBounds().bottom; <ide> <ide> canvas.translate(x, transY); <ide> mDrawable.draw(canvas); <ide> canvas.restore(); <ide> } <add> <add> @Override <add> public int getWidth() { <add> return mWidth; <add> } <add> <add> @Override <add> public int getHeight() { <add> return mHeight; <add> } <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputShadowNode.java <ide> public void onCollectExtraUpdates(UIViewOperationQueue uiViewOperationQueue) { <ide> if (mJsEventCount != UNSET) { <ide> Spannable preparedSpannableText = fromTextCSSNode(this); <ide> ReactTextUpdate reactTextUpdate = <del> new ReactTextUpdate(preparedSpannableText, mJsEventCount, mContainsImages, getPadding()); <add> new ReactTextUpdate(preparedSpannableText, mJsEventCount, mContainsImages, getPadding(), getEffectiveLineHeight()); <ide> uiViewOperationQueue.enqueueUpdateExtraData(getReactTag(), reactTextUpdate); <ide> } <ide> }
7
Ruby
Ruby
remove double test for header inheritance leaks
a93cbbd40c22821336953647e43ae5a8771b7886
<ide><path>activeresource/test/cases/base_test.rb <ide> def test_header_inheritance_should_not_leak_upstream <ide> assert_equal nil, fruit.headers['key2'] <ide> end <ide> <del> def test_header_inheritance_should_not_leak_upstream <del> fruit = Class.new(ActiveResource::Base) <del> apple = Class.new(fruit) <del> fruit.site = 'http://market' <del> <del> fruit.headers['key'] = 'value' <del> <del> apple.headers['key2'] = 'value2' <del> assert_equal nil, fruit.headers['key2'] <del> end <del> <ide> ######################################################################## <ide> # Tests for setting up remote URLs for a given model (including adding <ide> # parameters appropriately)
1
Go
Go
skip flaky testlogblocking
6c75c862403c98138ab0f7811f6ba9113f9e5d61
<ide><path>daemon/logger/awslogs/cloudwatchlogs_test.go <ide> import ( <ide> "github.com/docker/docker/dockerversion" <ide> "gotest.tools/assert" <ide> is "gotest.tools/assert/cmp" <add> "gotest.tools/skip" <ide> ) <ide> <ide> const ( <ide> func TestLogClosed(t *testing.T) { <ide> } <ide> <ide> func TestLogBlocking(t *testing.T) { <add> skip.If(t, runtime.GOOS == "windows", "FIXME: test is flaky on Windows. See #39857") <ide> mockClient := newMockClient() <ide> stream := &logStream{ <ide> client: mockClient,
1
Python
Python
apply reviewers comments. thanks to @eric-wieser!
0930786a79ba01492c7db266cd8a501ffad4451a
<ide><path>numpy/f2py/cfuncs.py <ide> cppmacros['STRINGFREE'] = """\ <ide> #define STRINGFREE(str) do {if (!(str == NULL)) free(str);} while (0) <ide> """ <del>needs['STRINGPADN'] = ['string.h'] <del>cppmacros['STRINGPADN'] = """\ <del>/* <del>STRINGPADN replaces nulls with padding from the right. <del> <del>`to` must have size of at least N bytes. <del> <del>If the `to[N-1]` is null (`\\0`), then replace it and all the <del>preceeding nulls with the given padding. <del>*/ <del>#define STRINGPADN(to, N, PADDING) \\ <del> do { \\ <del> int _m = (N); \\ <del> char *_to = (to); \\ <del> FAILNULL(_to); \\ <del> for (_m -= 1; _m >= 0 && _to[_m] == '\\0'; _m--) { \\ <del> _to[_m] = PADDING; \\ <del> } \\ <del> } while (0) <del>""" <ide> needs['STRINGCOPYN'] = ['string.h', 'FAILNULL'] <ide> cppmacros['STRINGCOPYN'] = """\ <ide> /* <ide> STRINGCOPYN copies N bytes. <ide> <ide> `to` and `from` buffers must have sizes of at least N bytes. <del> <del>If the last byte in `to` is null (`\\0`), then replace all the <del>preceeding nulls with spaces. <ide> */ <ide> #define STRINGCOPYN(to,from,N) \\ <ide> do { \\ <ide> /* <ide> try_pyarr_from_string copies str[:len(obj)] to the data of an `ndarray`. <ide> <del> if the specified len==-1, str must be null-terminated. <add> If obj is an `ndarray`, it is assumed to be contiguous. <add> <add> If the specified len==-1, str must be null-terminated. <ide> */ <ide> static int try_pyarr_from_string(PyObject *obj, <ide> const string str, const int len) { <ide> #ifdef DEBUGCFUNCS <ide> fprintf(stderr, "try_pyarr_from_string(str='%s', len=%d, obj=%p)\\n", <ide> (char*)str,len, obj); <ide> #endif <del> PyArrayObject *arr = NULL; <del> if (PyArray_Check(obj) && (!((arr = (PyArrayObject *)obj) == NULL))) { <add> if (PyArray_Check(obj)) { <add> PyArrayObject *arr = (PyArrayObject *)obj; <ide> string buf = PyArray_DATA(arr); <ide> npy_intp n = len; <ide> if (n == -1) { <ide> needs['string_from_pyobj'] = ['string', 'STRINGMALLOC', 'STRINGCOPYN'] <ide> cfuncs['string_from_pyobj'] = """\ <ide> /* <del> Create a new string buffer from a Python string-like object. <add> Create a new string buffer `str` of at most length `len` from a Python string-like object `obj`. <ide> <ide> The string buffer has given size (len) or the size of inistr when len==-1. <ide> <ide> buf = inistr; <ide> } <ide> else if (PyArray_Check(obj)) { <del> if ((arr = (PyArrayObject *)obj) == NULL) <del> goto capi_fail; <add> arr = (PyArrayObject *)obj; <ide> if (!ISCONTIGUOUS(arr)) { <ide> PyErr_SetString(PyExc_ValueError, <ide> \"array object is non-contiguous.\"); <ide> } <ide> STRINGMALLOC(*str, *len); // *str is allocated with size (*len + 1) <ide> if (n < *len) { <del> /* Pad fixed-width string with nulls */ <del> memset(*str + n, '\\0', *len - n); <add> /* Pad fixed-width string with nulls */ <add> memset(*str + n, '\\0', *len - n); <ide> } <ide> STRINGCOPYN(*str, buf, n); <ide> Py_XDECREF(tmp);
1
Javascript
Javascript
allow alpha tags
bc7d5ac99dcb36679c90b60731458063fb8c82f3
<ide><path>scripts/release/publish-commands/parse-params.js <ide> module.exports = () => { <ide> case 'latest': <ide> case 'next': <ide> case 'experimental': <add> case 'alpha': <ide> case 'untagged': <ide> break; <ide> default:
1
Ruby
Ruby
add document in mailer
40b1f648b949f4ad944024619e546765e3729776
<ide><path>actionmailer/lib/action_mailer/base.rb <ide> module ActionMailer <ide> # end <ide> # end <ide> # <add> # You can also send attachments with html template, in this case you need to add body, attachments, <add> # and custom content type like this: <add> # <add> # class NotifierMailer < ApplicationMailer <add> # def welcome(recipient) <add> # attachments['free_book.pdf'] = File.read('path/to/file.pdf') <add> # mail(to: recipient, <add> # subject: "New account information", <add> # content_type: "text/html", <add> # body: "<html><body>Hello there</body></html>") <add> # end <add> # end <add> # <ide> # = Inline Attachments <ide> # <ide> # You can also specify that a file should be displayed inline with other HTML. This is useful
1
Ruby
Ruby
fix false positive in `audit_gcc_dependency`
2af5a974c215712eb96ed6d46b2c4c8ced315371
<ide><path>Library/Homebrew/formula_auditor.rb <ide> def linux_only_gcc_dep?(formula) <ide> bottle_tag = Utils::Bottles::Tag.new(system: macos_version, arch: arch) <ide> next unless bottle_tag.valid_combination? <ide> <del> variation = variations[bottle_tag.to_sym] <del> # This variation does not exist, so it must match Linux. <del> return false if variation.blank? <add> variation_dependencies = variations.dig(bottle_tag.to_sym, "dependencies") <add> # This variation either: <add> # 1. does not exist <add> # 2. has no variation-specific dependencies <add> # In either case, it matches Linux. <add> return false if variation_dependencies.blank? <ide> # We found a non-Linux variation that depends on GCC. <del> return false if variation["dependencies"]&.include?("gcc") <add> return false if variation_dependencies.include?("gcc") <ide> end <ide> end <ide>
1
Javascript
Javascript
use unicode escape sequences instead of octal
c7bc4cacde163f916b62f196194ff5c1cabb61a2
<ide><path>lib/util.js <ide> function stylizeWithColor(str, styleType) { <ide> var style = styles[styleType]; <ide> <ide> if (style) { <del> return '\033[' + colors[style][0] + 'm' + str + <del> '\033[' + colors[style][1] + 'm'; <add> return '\u001b[' + colors[style][0] + 'm' + str + <add> '\u001b[' + colors[style][1] + 'm'; <ide> } else { <ide> return str; <ide> }
1
Javascript
Javascript
fix fs benchmark test
7991b57cfdba96ddcd6553c8233cd6392e16a42a
<ide><path>test/benchmark/test-benchmark-fs.js <ide> const tmpdir = require('../common/tmpdir'); <ide> tmpdir.refresh(); <ide> <ide> runBenchmark('fs', [ <del> 'n=1', <del> 'size=1', <add> 'concurrent=1', <add> 'dir=.github', <ide> 'dur=0.1', <add> 'encodingType=buf', <add> 'filesize=1024', <ide> 'len=1024', <del> 'concurrent=1', <add> 'mode=callback', <add> 'n=1', <ide> 'pathType=relative', <del> 'statType=fstat', <add> 'size=1', <ide> 'statSyncType=fstatSync', <del> 'encodingType=buf', <del> 'filesize=1024', <del> 'dir=.github', <del> 'withFileTypes=false' <add> 'statType=fstat', <add> 'withFileTypes=false', <ide> ], { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 });
1