content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
PHP
PHP
add octane cache store
3131f789ae05bb727e8f8b65981f6957391a5e3d
<ide><path>config/cache.php <ide> 'driver' => 'apc', <ide> ], <ide> <add> 'octane' => [ <add> 'driver' => 'octane', <add> ], <add> <ide> 'array' => [ <ide> 'driver' => 'array', <ide> 'serialize' => false,
1
Javascript
Javascript
add tests for native set
6d64f3b48811efe4ed961c63e1afb673621edf22
<ide><path>packages/ember-glimmer/tests/integration/syntax/each-test.js <ide> class ArrayDelegate { <ide> } <ide> } <ide> <add>const makeSet = (() => { <add> // IE11 does not support `new Set(items);` <add> let set = new Set([1,2,3]); <add> <add> if (set.size === 3) { <add> return items => new Set(items); <add> } else { <add> return items => { <add> let s = new Set(); <add> items.forEach(value => s.add(value)); <add> return s; <add> }; <add> } <add>})(); <add> <add>class SetDelegate extends ArrayDelegate { <add> constructor(set) { <add> let array = []; <add> set.forEach(value => array.push(value)); <add> super(array, set); <add> this._set = set; <add> } <add> <add> arrayContentDidChange() { <add> this._set.clear(); <add> this._array.forEach(value => this._set.add(value)); <add> super.arrayContentDidChange(); <add> } <add>} <add> <ide> class ForEachable extends ArrayDelegate { <ide> get length() { <ide> return this._array.length; <ide> class BasicEachTest extends TogglingEachTest {} <ide> const TRUTHY_CASES = [ <ide> ['hello'], <ide> emberA(['hello']), <add> makeSet(['hello']), <ide> new ForEachable(['hello']), <ide> ArrayProxy.create({ content: ['hello'] }), <ide> ArrayProxy.create({ content: emberA(['hello']) }) <ide> const FALSY_CASES = [ <ide> 0, <ide> [], <ide> emberA([]), <add> makeSet([]), <ide> new ForEachable([]), <ide> ArrayProxy.create({ content: [] }), <ide> ArrayProxy.create({ content: emberA([]) }) <ide> moduleFor('Syntax test: {{#each}} with emberA-wrapped arrays', class extends Eac <ide> <ide> }); <ide> <add>moduleFor('Syntax test: {{#each}} with native Set', class extends EachTest { <add> <add> createList(items) { <add> let set = makeSet(items); <add> return { list: set, delegate: new SetDelegate(set) }; <add> } <add> <add> ['@test it can render duplicate primitive items'](assert) { <add> assert.ok(true, 'not supported by Set'); <add> } <add> <add> ['@test it can render duplicate objects'](assert) { <add> assert.ok(true, 'not supported by Set'); <add> } <add> <add>}); <add> <ide> moduleFor('Syntax test: {{#each}} with array-like objects implementing forEach', class extends EachTest { <ide> <ide> createList(items) {
1
Javascript
Javascript
use limit for array split
fa5bc5bc1f19dd3038540b74fda80bafb5217814
<ide><path>lib/WebpackOptionsValidationError.js <ide> const WebpackError = require("./WebpackError"); <ide> <ide> const getSchemaPart = (path, parents, additionalPath) => { <ide> parents = parents || 0; <del> path = path.split("/"); <del> path = path.slice(0, path.length - parents); <add> path = path.split("/", path.length - parents); <ide> if (additionalPath) { <ide> additionalPath = additionalPath.split("/"); <ide> path = path.concat(additionalPath); <ide><path>lib/util/createHash.js <ide> class DebugHash { <ide> if (data.startsWith("debug-digest-")) { <ide> data = Buffer.from(data.slice("debug-digest-".length), "hex").toString(); <ide> } <del> this.string += `[${data}](${new Error().stack.split("\n")[2]})\n`; <add> this.string += `[${data}](${new Error().stack.split("\n", 3)[2]})\n`; <ide> return this; <ide> } <ide>
2
PHP
PHP
add missing docblock
ee71973398875afffad81c2c601d6aacf4723cf0
<ide><path>src/Illuminate/Support/Traits/EnumeratesValues.php <ide> * @property-read HigherOrderCollectionProxy $min <ide> * @property-read HigherOrderCollectionProxy $partition <ide> * @property-read HigherOrderCollectionProxy $reject <add> * @property-read HigherOrderCollectionProxy $some <ide> * @property-read HigherOrderCollectionProxy $sortBy <ide> * @property-read HigherOrderCollectionProxy $sortByDesc <ide> * @property-read HigherOrderCollectionProxy $sum
1
Javascript
Javascript
undo the "forrige" to "sist" change, as advised in
67635b4f1b433bfee20cd6cefb8b47a2cd87f96d
<ide><path>locale/nb.js <ide> nextDay: '[i morgen kl.] LT', <ide> nextWeek: 'dddd [kl.] LT', <ide> lastDay: '[i går kl.] LT', <del> lastWeek: '[sist] dddd [kl.] LT', <add> lastWeek: '[forrige] dddd [kl.] LT', <ide> sameElse: 'L' <ide> }, <ide> relativeTime : {
1
Python
Python
move trainers to core/
45da63a93fea59d886cd55cfa02d097d95998497
<ide><path>official/core/base_task_test.py <add># Lint as: python3 <add># Copyright 2020 The TensorFlow Authors. All Rights Reserved. <add># <add># Licensed under the Apache License, Version 2.0 (the "License"); <add># you may not use this file except in compliance with the License. <add># You may obtain a copy of the License at <add># <add># http://www.apache.org/licenses/LICENSE-2.0 <add># <add># Unless required by applicable law or agreed to in writing, software <add># distributed under the License is distributed on an "AS IS" BASIS, <add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add># See the License for the specific language governing permissions and <add># limitations under the License. <add># ============================================================================== <add>"""Tests for tensorflow_models.core.base_task.""" <add> <add>import functools <add> <add>from absl.testing import parameterized <add>import tensorflow as tf <add> <add>from tensorflow.python.distribute import combinations <add>from tensorflow.python.distribute import strategy_combinations <add>from official.utils.testing import mock_task <add> <add> <add>def all_strategy_combinations(): <add> return combinations.combine( <add> distribution=[ <add> strategy_combinations.default_strategy, <add> strategy_combinations.tpu_strategy, <add> strategy_combinations.one_device_strategy_gpu, <add> ], <add> mode='eager', <add> ) <add> <add> <add>class TaskKerasTest(tf.test.TestCase, parameterized.TestCase): <add> <add> @combinations.generate(all_strategy_combinations()) <add> def test_task_with_step_override(self, distribution): <add> with distribution.scope(): <add> task = mock_task.MockTask() <add> model = task.build_model() <add> model = task.compile_model( <add> model, <add> optimizer=tf.keras.optimizers.SGD(learning_rate=1e-3), <add> metrics=task.build_metrics(), <add> train_step=task.train_step, <add> validation_step=task.validation_step) <add> <add> dataset = task.build_inputs(params=None) <add> logs = model.fit(dataset, epochs=1, steps_per_epoch=2) <add> self.assertIn('loss', logs.history) <add> self.assertIn('acc', logs.history) <add> <add> # Without specifying metrics through compile. <add> with distribution.scope(): <add> train_metrics = task.build_metrics(training=True) <add> val_metrics = task.build_metrics(training=False) <add> model = task.build_model() <add> model = task.compile_model( <add> model, <add> optimizer=tf.keras.optimizers.SGD(learning_rate=1e-3), <add> train_step=functools.partial(task.train_step, metrics=train_metrics), <add> validation_step=functools.partial( <add> task.validation_step, metrics=val_metrics)) <add> logs = model.fit(dataset, epochs=1, steps_per_epoch=2) <add> self.assertIn('loss', logs.history) <add> self.assertIn('acc', logs.history) <add> <add> def test_task_with_fit(self): <add> task = mock_task.MockTask() <add> model = task.build_model() <add> model = task.compile_model( <add> model, <add> optimizer=tf.keras.optimizers.SGD(learning_rate=1e-3), <add> loss=tf.keras.losses.CategoricalCrossentropy(), <add> metrics=task.build_metrics()) <add> dataset = task.build_inputs(params=None) <add> logs = model.fit(dataset, epochs=1, steps_per_epoch=2) <add> self.assertIn('loss', logs.history) <add> self.assertIn('acc', logs.history) <add> self.assertLen(model.evaluate(dataset, steps=1), 2) <add> <add> def test_task_invalid_compile(self): <add> task = mock_task.MockTask() <add> model = task.build_model() <add> with self.assertRaises(ValueError): <add> _ = task.compile_model( <add> model, <add> optimizer=tf.keras.optimizers.SGD(learning_rate=1e-3), <add> loss=tf.keras.losses.CategoricalCrossentropy(), <add> metrics=task.build_metrics(), <add> train_step=task.train_step) <add> <add> <add>if __name__ == '__main__': <add> tf.test.main() <ide><path>official/core/base_trainer.py <add># Lint as: python3 <add># Copyright 2020 The TensorFlow Authors. All Rights Reserved. <add># <add># Licensed under the Apache License, Version 2.0 (the "License"); <add># you may not use this file except in compliance with the License. <add># You may obtain a copy of the License at <add># <add># http://www.apache.org/licenses/LICENSE-2.0 <add># <add># Unless required by applicable law or agreed to in writing, software <add># distributed under the License is distributed on an "AS IS" BASIS, <add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add># See the License for the specific language governing permissions and <add># limitations under the License. <add># ============================================================================== <add>"""Standard Trainer implementation. <add> <add>The base trainer implements the Orbit `StandardTrainable` and <add>`StandardEvaluable` interfaces. Trainers inside this project should be <add>interchangable and independent on model architectures and tasks. <add>""" <add>import gin <add>import orbit <add>import tensorflow as tf <add> <add>from official.core import base_task <add>from official.modeling import optimization <add>from official.modeling import performance <add>from official.modeling.hyperparams import config_definitions <add> <add> <add>ExperimentConfig = config_definitions.ExperimentConfig <add> <add> <add>@gin.configurable <add>class Trainer(orbit.StandardTrainer, orbit.StandardEvaluator): <add> """Implements the common trainer shared for TensorFlow models.""" <add> <add> def __init__(self, <add> config: ExperimentConfig, <add> task: base_task.Task, <add> train: bool = True, <add> evaluate: bool = True, <add> model=None, <add> optimizer=None): <add> """Initialize common trainer for TensorFlow models. <add> <add> Args: <add> config: An `ExperimentConfig` instance specifying experiment config. <add> task: A base_task.Task instance. <add> train: bool, whether or not this trainer will be used for training. <add> default to True. <add> evaluate: bool, whether or not this trainer will be used for evaluation. <add> default to True. <add> model: tf.keras.Model instance. If provided, it will be used instead <add> of building model using task.build_model(). Default to None. <add> optimizer: tf.keras.optimizers.Optimizer instance. If provided, it will <add> used instead of the optimizer from config. Default to None. <add> """ <add> # Gets the current distribution strategy. If not inside any strategy scope, <add> # it gets a single-replica no-op strategy. <add> self._strategy = tf.distribute.get_strategy() <add> self._config = config <add> self._task = task <add> <add> self._model = model or task.build_model() <add> <add> if optimizer is None: <add> opt_factory = optimization.OptimizerFactory( <add> config.trainer.optimizer_config) <add> self._optimizer = opt_factory.build_optimizer( <add> opt_factory.build_learning_rate()) <add> else: <add> self._optimizer = optimizer <add> <add> # Configuring optimizer when loss_scale is set in runtime config. This helps <add> # avoiding overflow/underflow for float16 computations. <add> if config.runtime.loss_scale: <add> self._optimizer = performance.configure_optimizer( <add> self._optimizer, <add> use_float16=config.runtime.mixed_precision_dtype == 'float16', <add> loss_scale=config.runtime.loss_scale) <add> <add> # global_step increases by 1 after each training iteration. <add> # We should have global_step.numpy() == self.optimizer.iterations.numpy() <add> # when there is only 1 optimizer. <add> self._global_step = orbit.utils.create_global_step() <add> if hasattr(self.model, 'checkpoint_items'): <add> checkpoint_items = self.model.checkpoint_items <add> else: <add> checkpoint_items = {} <add> self._checkpoint = tf.train.Checkpoint( <add> global_step=self.global_step, model=self.model, <add> optimizer=self.optimizer, **checkpoint_items) <add> <add> self._train_loss = tf.keras.metrics.Mean('training_loss', dtype=tf.float32) <add> self._validation_loss = tf.keras.metrics.Mean( <add> 'validation_loss', dtype=tf.float32) <add> self._train_metrics = self.task.build_metrics( <add> training=True) + self.model.metrics <add> self._validation_metrics = self.task.build_metrics( <add> training=False) + self.model.metrics <add> <add> if train: <add> train_dataset = orbit.utils.make_distributed_dataset( <add> self.strategy, self.task.build_inputs, self.config.task.train_data) <add> orbit.StandardTrainer.__init__( <add> self, <add> train_dataset, <add> options=orbit.StandardTrainerOptions( <add> use_tf_while_loop=config.trainer.train_tf_while_loop, <add> use_tf_function=config.trainer.train_tf_function, <add> use_tpu_summary_optimization=config.trainer.allow_tpu_summary)) <add> <add> if evaluate: <add> eval_dataset = orbit.utils.make_distributed_dataset( <add> self.strategy, self.task.build_inputs, <add> self.config.task.validation_data) <add> orbit.StandardEvaluator.__init__( <add> self, <add> eval_dataset, <add> options=orbit.StandardEvaluatorOptions( <add> use_tf_function=config.trainer.eval_tf_function)) <add> <add> @property <add> def strategy(self): <add> return self._strategy <add> <add> @property <add> def config(self): <add> return self._config <add> <add> @property <add> def task(self): <add> return self._task <add> <add> @property <add> def model(self): <add> return self._model <add> <add> @property <add> def optimizer(self): <add> return self._optimizer <add> <add> @property <add> def global_step(self): <add> return self._global_step <add> <add> @property <add> def train_loss(self): <add> """Accesses the training loss metric object.""" <add> return self._train_loss <add> <add> @property <add> def validation_loss(self): <add> """Accesses the validation loss metric object.""" <add> return self._validation_loss <add> <add> @property <add> def train_metrics(self): <add> """Accesses all training metric objects.""" <add> return self._train_metrics <add> <add> @property <add> def validation_metrics(self): <add> """Accesses all validation metric metric objects.""" <add> return self._validation_metrics <add> <add> def initialize(self): <add> """A callback function. <add> <add> This function will be called when no checkpoint found for the model. <add> If there is a checkpoint, the checkpoint will be loaded and this function <add> will not be called. Tasks may use this callback function to load a <add> pretrained checkpoint, saved under a directory other than the model_dir. <add> """ <add> self.task.initialize(self.model) <add> <add> @property <add> def checkpoint(self): <add> """Accesses the training checkpoint.""" <add> return self._checkpoint <add> <add> def train_loop_end(self): <add> """See base class.""" <add> logs = {} <add> for metric in self.train_metrics + [self.train_loss]: <add> logs[metric.name] = metric.result() <add> metric.reset_states() <add> if callable(self.optimizer.learning_rate): <add> logs['learning_rate'] = self.optimizer.learning_rate(self.global_step) <add> else: <add> logs['learning_rate'] = self.optimizer.learning_rate <add> return logs <add> <add> def train_step(self, iterator): <add> """See base class.""" <add> <add> def step_fn(inputs): <add> logs = self.task.train_step( <add> inputs, <add> model=self.model, <add> optimizer=self.optimizer, <add> metrics=self.train_metrics) <add> self._train_loss.update_state(logs[self.task.loss]) <add> self.global_step.assign_add(1) <add> <add> self.strategy.run(step_fn, args=(next(iterator),)) <add> <add> def eval_begin(self): <add> """Sets up metrics.""" <add> for metric in self.validation_metrics + [self.validation_loss]: <add> metric.reset_states() <add> <add> def eval_step(self, iterator): <add> """See base class.""" <add> <add> def step_fn(inputs): <add> logs = self.task.validation_step( <add> inputs, model=self.model, metrics=self.validation_metrics) <add> self._validation_loss.update_state(logs[self.task.loss]) <add> return logs <add> <add> distributed_outputs = self.strategy.run(step_fn, args=(next(iterator),)) <add> return tf.nest.map_structure(self.strategy.experimental_local_results, <add> distributed_outputs) <add> <add> def eval_end(self, aggregated_logs=None): <add> """Processes evaluation results.""" <add> logs = {} <add> for metric in self.validation_metrics + [self.validation_loss]: <add> logs[metric.name] = metric.result() <add> if aggregated_logs: <add> metrics = self.task.reduce_aggregated_logs(aggregated_logs) <add> logs.update(metrics) <add> return logs <add> <add> def eval_reduce(self, state=None, step_outputs=None): <add> return self.task.aggregate_logs(state, step_outputs) <ide><path>official/core/base_trainer_test.py <add># Lint as: python3 <add># Copyright 2020 The TensorFlow Authors. All Rights Reserved. <add># <add># Licensed under the Apache License, Version 2.0 (the "License"); <add># you may not use this file except in compliance with the License. <add># You may obtain a copy of the License at <add># <add># http://www.apache.org/licenses/LICENSE-2.0 <add># <add># Unless required by applicable law or agreed to in writing, software <add># distributed under the License is distributed on an "AS IS" BASIS, <add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add># See the License for the specific language governing permissions and <add># limitations under the License. <add># ============================================================================== <add>"""Tests for tensorflow_models.core.trainers.trainer.""" <add># pylint: disable=g-direct-tensorflow-import <add>from absl.testing import parameterized <add>import tensorflow as tf <add> <add>from tensorflow.python.distribute import combinations <add>from tensorflow.python.distribute import strategy_combinations <add>from official.core import base_trainer as trainer_lib <add>from official.modeling.hyperparams import config_definitions as cfg <add>from official.utils.testing import mock_task <add> <add> <add>def all_strategy_combinations(): <add> return combinations.combine( <add> distribution=[ <add> strategy_combinations.default_strategy, <add> strategy_combinations.tpu_strategy, <add> strategy_combinations.one_device_strategy_gpu, <add> ], <add> mode='eager', <add> ) <add> <add> <add>class TrainerTest(tf.test.TestCase, parameterized.TestCase): <add> <add> def setUp(self): <add> super().setUp() <add> self._config = cfg.ExperimentConfig( <add> trainer=cfg.TrainerConfig( <add> optimizer_config=cfg.OptimizationConfig( <add> {'optimizer': { <add> 'type': 'sgd' <add> }, <add> 'learning_rate': { <add> 'type': 'constant' <add> }}))) <add> <add> def create_test_trainer(self): <add> task = mock_task.MockTask() <add> trainer = trainer_lib.Trainer(self._config, task) <add> return trainer <add> <add> @combinations.generate(all_strategy_combinations()) <add> def test_trainer_train(self, distribution): <add> with distribution.scope(): <add> trainer = self.create_test_trainer() <add> logs = trainer.train(tf.convert_to_tensor(5, dtype=tf.int32)) <add> self.assertIn('training_loss', logs) <add> self.assertIn('learning_rate', logs) <add> <add> @combinations.generate(all_strategy_combinations()) <add> def test_trainer_validate(self, distribution): <add> with distribution.scope(): <add> trainer = self.create_test_trainer() <add> logs = trainer.evaluate(tf.convert_to_tensor(5, dtype=tf.int32)) <add> self.assertIn('validation_loss', logs) <add> self.assertEqual(logs['acc'], 5. * distribution.num_replicas_in_sync) <add> <add> @combinations.generate( <add> combinations.combine( <add> mixed_precision_dtype=['float32', 'bfloat16', 'float16'], <add> loss_scale=[None, 'dynamic', 128, 256], <add> )) <add> def test_configure_optimizer(self, mixed_precision_dtype, loss_scale): <add> config = cfg.ExperimentConfig( <add> runtime=cfg.RuntimeConfig( <add> mixed_precision_dtype=mixed_precision_dtype, loss_scale=loss_scale), <add> trainer=cfg.TrainerConfig( <add> optimizer_config=cfg.OptimizationConfig( <add> {'optimizer': { <add> 'type': 'sgd' <add> }, <add> 'learning_rate': { <add> 'type': 'constant' <add> }}))) <add> task = mock_task.MockTask() <add> trainer = trainer_lib.Trainer(config, task) <add> if mixed_precision_dtype != 'float16': <add> self.assertIsInstance(trainer.optimizer, tf.keras.optimizers.SGD) <add> elif mixed_precision_dtype == 'float16' and loss_scale is None: <add> self.assertIsInstance(trainer.optimizer, tf.keras.optimizers.SGD) <add> else: <add> self.assertIsInstance( <add> trainer.optimizer, <add> tf.keras.mixed_precision.experimental.LossScaleOptimizer) <add> <add> metrics = trainer.train(tf.convert_to_tensor(5, dtype=tf.int32)) <add> self.assertIn('training_loss', metrics) <add> <add> <add>if __name__ == '__main__': <add> tf.test.main() <ide><path>official/utils/testing/mock_task.py <add># Lint as: python3 <add># Copyright 2020 The TensorFlow Authors. All Rights Reserved. <add># <add># Licensed under the Apache License, Version 2.0 (the "License"); <add># you may not use this file except in compliance with the License. <add># You may obtain a copy of the License at <add># <add># http://www.apache.org/licenses/LICENSE-2.0 <add># <add># Unless required by applicable law or agreed to in writing, software <add># distributed under the License is distributed on an "AS IS" BASIS, <add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add># See the License for the specific language governing permissions and <add># limitations under the License. <add># ============================================================================== <add>"""Mock task for testing.""" <add> <add>import dataclasses <add>import numpy as np <add>import tensorflow as tf <add> <add>from official.core import base_task <add>from official.core import exp_factory <add>from official.core import task_factory <add>from official.modeling.hyperparams import config_definitions as cfg <add> <add> <add>class MockModel(tf.keras.Model): <add> <add> def __init__(self, network): <add> super().__init__() <add> self.network = network <add> <add> def call(self, inputs): <add> outputs = self.network(inputs) <add> self.add_loss(tf.reduce_mean(outputs)) <add> return outputs <add> <add> <add>@dataclasses.dataclass <add>class MockTaskConfig(cfg.TaskConfig): <add> pass <add> <add> <add>@task_factory.register_task_cls(MockTaskConfig) <add>class MockTask(base_task.Task): <add> """Mock task object for testing.""" <add> <add> def __init__(self, params=None, logging_dir=None): <add> super().__init__(params=params, logging_dir=logging_dir) <add> <add> def build_model(self, *arg, **kwargs): <add> inputs = tf.keras.layers.Input(shape=(2,), name="random", dtype=tf.float32) <add> outputs = tf.keras.layers.Dense(1)(inputs) <add> network = tf.keras.Model(inputs=inputs, outputs=outputs) <add> return MockModel(network) <add> <add> def build_metrics(self, training: bool = True): <add> del training <add> return [tf.keras.metrics.Accuracy(name="acc")] <add> <add> def build_inputs(self, params): <add> <add> def generate_data(_): <add> x = tf.zeros(shape=(2,), dtype=tf.float32) <add> label = tf.zeros([1], dtype=tf.int32) <add> return x, label <add> <add> dataset = tf.data.Dataset.range(1) <add> dataset = dataset.repeat() <add> dataset = dataset.map( <add> generate_data, num_parallel_calls=tf.data.experimental.AUTOTUNE) <add> return dataset.prefetch(buffer_size=1).batch(2, drop_remainder=True) <add> <add> def aggregate_logs(self, state, step_outputs): <add> if state is None: <add> state = {} <add> for key, value in step_outputs.items(): <add> if key not in state: <add> state[key] = [] <add> state[key].append( <add> np.concatenate([np.expand_dims(v.numpy(), axis=0) for v in value])) <add> return state <add> <add> def reduce_aggregated_logs(self, aggregated_logs): <add> for k, v in aggregated_logs.items(): <add> aggregated_logs[k] = np.sum(np.stack(v, axis=0)) <add> return aggregated_logs <add> <add> <add>@exp_factory.register_config_factory("mock") <add>def mock_experiment() -> cfg.ExperimentConfig: <add> config = cfg.ExperimentConfig( <add> task=MockTaskConfig(), trainer=cfg.TrainerConfig()) <add> return config
4
Javascript
Javascript
fix toweb typo
79f4d5a34537def5c5555332eafabfd6577ccc5b
<ide><path>lib/internal/streams/readable.js <ide> Readable.fromWeb = function(readableStream, options) { <ide> }; <ide> <ide> Readable.toWeb = function(streamReadable) { <del> return lazyWebStreams().newStreamReadableFromReadableStream(streamReadable); <add> return lazyWebStreams().newReadableStreamFromStreamReadable(streamReadable); <ide> };
1
Javascript
Javascript
fix typo in skeleton
8583c8e13aba7afc8eae9dd838da74e2a8cd98e7
<ide><path>src/objects/Skeleton.js <ide> function Skeleton( bones, boneInverses, useVertexTexture ) { <ide> <ide> } else { <ide> <del> console.warn( 'THREE.Skeleton bonInverses is the wrong length.' ); <add> console.warn( 'THREE.Skeleton boneInverses is the wrong length.' ); <ide> <ide> this.boneInverses = []; <ide>
1
Javascript
Javascript
fix inaccurate spec description
76fe572a97890237da6d2552ed6921d4dce85da4
<ide><path>src/browser/ui/dom/components/__tests__/LocalEventTrapMixin-test.js <ide> describe('LocalEventTrapMixin', function() { <ide> ReactTestUtils = require('ReactTestUtils'); <ide> }); <ide> <del> it('does not fatal when trapping bubbled state on null', function() { <add> it('throws when trapping bubbled state on null', function() { <ide> var BadImage = React.createClass({ <ide> mixins: [LocalEventTrapMixin], <ide> render: function() {
1
Python
Python
add additional test back in (it works now)
689600e17d0e3734b29bf758e09068b7b4413437
<ide><path>spacy/tests/test_lemmatizer.py <ide> def test_tagger_warns_no_lookups(): <ide> nlp.vocab.lookups = Lookups() <ide> assert not len(nlp.vocab.lookups) <ide> tagger = nlp.create_pipe("tagger") <add> with pytest.warns(UserWarning): <add> tagger.begin_training() <ide> nlp.add_pipe(tagger) <ide> with pytest.warns(UserWarning): <ide> nlp.begin_training()
1
Text
Text
add missing change to resolver ctor
75a96b4ad8a29da975b425b576c2efd73573af8b
<ide><path>doc/api/dns.md <ide> The following methods from the `dns` module are available: <ide> <!-- YAML <ide> added: v8.3.0 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/39610 <add> description: The `options` object now accepts a `tries` option. <ide> - version: v12.18.3 <ide> pr-url: https://github.com/nodejs/node/pull/33472 <ide> description: The constructor now accepts an `options` object. <ide> Create a new resolver. <ide> * `timeout` {integer} Query timeout in milliseconds, or `-1` to use the <ide> default timeout. <ide> * `tries` {integer} The number of tries the resolver will try contacting <del> each name server before giving up, `4` by default. <add> each name server before giving up. **Default:** `4` <ide> <ide> ### `resolver.cancel()` <ide> <!-- YAML
1
Python
Python
set version to 2.0.4.dev0
04650e38c7d1bf886d235bb3ace61a91c28cb60b
<ide><path>spacy/about.py <ide> # https://github.com/pypa/warehouse/blob/master/warehouse/__about__.py <ide> <ide> __title__ = 'spacy' <del>__version__ = '2.0.3' <add>__version__ = '2.0.4.dev0' <ide> __summary__ = 'Industrial-strength Natural Language Processing (NLP) with Python and Cython' <ide> __uri__ = 'https://spacy.io' <ide> __author__ = 'Explosion AI' <ide> __email__ = 'contact@explosion.ai' <ide> __license__ = 'MIT' <del>__release__ = True <add>__release__ = False <ide> <ide> __docs_models__ = 'https://spacy.io/usage/models' <ide> __download_url__ = 'https://github.com/explosion/spacy-models/releases/download'
1
Ruby
Ruby
add a test case for
bd4f28a46dc3cafd00aabd7c7e6540b3d48593b2
<ide><path>activerecord/test/cases/json_shared_test_cases.rb <ide> def test_changes_in_place <ide> assert_not json.changed? <ide> end <ide> <add> def test_changes_in_place_ignores_key_order <add> json = klass.new <add> assert_not json.changed? <add> <add> json.payload = { "three" => "four", "one" => "two" } <add> json.save! <add> json.reload <add> <add> json.payload = { "three" => "four", "one" => "two" } <add> assert_not json.changed? <add> <add> json.payload = [{ "three" => "four", "one" => "two" }, { "seven" => "eight", "five" => "six" }] <add> json.save! <add> json.reload <add> <add> json.payload = [{ "three" => "four", "one" => "two" }, { "seven" => "eight", "five" => "six" }] <add> assert_not json.changed? <add> end <add> <ide> def test_changes_in_place_with_ruby_object <ide> time = Time.now.utc <ide> json = klass.create!(payload: time)
1
PHP
PHP
change the method to support array only
f9d2db1876504bf82a5d3fd13f95488a1f71c56f
<ide><path>src/TestSuite/TestCase.php <ide> public function loadFixtures() <ide> * Useful to test how plugins being loaded/not loaded interact with other <ide> * elements in CakePHP or applications. <ide> * <del> * @param string|array $plugins list of Plugins to load <add> * @param array $plugins list of Plugins to load <ide> * @return \Cake\Http\BaseApplication <ide> */ <del> public function loadPlugins($plugins = []) <add> public function loadPlugins(array $plugins = []) <ide> { <ide> $app = $this->getMockForAbstractClass( <ide> BaseApplication::class, <ide> [''] <ide> ); <ide> <del> if (is_string($plugins)) { <del> $plugins = (array)$plugins; <del> } <ide> foreach ($plugins as $k => $opts) { <ide> if (is_array($opts)) { <ide> $app->addPlugin($k, $opts); <ide><path>tests/TestCase/Auth/FormAuthenticateTest.php <ide> public function testAuthenticateIncludesVirtualFields() <ide> */ <ide> public function testPluginModel() <ide> { <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> <ide> $PluginModel = $this->getTableLocator()->get('TestPlugin.AuthUsers'); <ide> $user['id'] = 1; <ide><path>tests/TestCase/Auth/PasswordHasherFactoryTest.php <ide> public function testBuild() <ide> $this->assertInstanceof('Cake\Auth\DefaultPasswordHasher', $hasher); <ide> $this->assertEquals(['foo' => 'bar'], $hasher->getConfig('hashOptions')); <ide> <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> $hasher = PasswordHasherFactory::build('TestPlugin.Legacy'); <ide> $this->assertInstanceof('TestPlugin\Auth\LegacyPasswordHasher', $hasher); <ide> Plugin::unload(); <ide><path>tests/TestCase/Cache/CacheTest.php <ide> public function testConfigFailedInit() <ide> public function testConfigWithLibAndPluginEngines() <ide> { <ide> static::setAppNamespace(); <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> <ide> $config = ['engine' => 'TestAppCache', 'path' => TMP, 'prefix' => 'cake_test_']; <ide> Cache::setConfig('libEngine', $config); <ide><path>tests/TestCase/Console/HelperRegistryTest.php <ide> public function testLoadMissingHelper() <ide> */ <ide> public function testLoadWithAlias() <ide> { <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> <ide> $result = $this->helpers->load('SimpleAliased', ['className' => 'Simple']); <ide> $this->assertInstanceOf(SimpleHelper::class, $result); <ide><path>tests/TestCase/Console/ShellTest.php <ide> public function testInitialize() <ide> { <ide> static::setAppNamespace(); <ide> <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> $this->Shell->tasks = ['Extract' => ['one', 'two']]; <ide> $this->Shell->plugin = 'TestPlugin'; <ide> $this->Shell->modelClass = 'TestPlugin.TestPluginComments'; <ide> public function testLoadModel() <ide> ); <ide> $this->assertEquals('Articles', $Shell->modelClass); <ide> <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> $result = $this->Shell->loadModel('TestPlugin.TestPluginComments'); <ide> $this->assertInstanceOf( <ide> 'TestPlugin\Model\Table\TestPluginCommentsTable', <ide><path>tests/TestCase/Console/TaskRegistryTest.php <ide> public function testLoadPluginTask() <ide> $shell = $this->getMockBuilder('Cake\Console\Shell') <ide> ->disableOriginalConstructor() <ide> ->getMock(); <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> $this->Tasks = new TaskRegistry($shell, $dispatcher); <ide> <ide> $result = $this->Tasks->load('TestPlugin.OtherTask'); <ide> public function testLoadPluginTask() <ide> */ <ide> public function testLoadWithAlias() <ide> { <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> <ide> $result = $this->Tasks->load('CommandAliased', ['className' => 'Command']); <ide> $this->assertInstanceOf('Cake\Shell\Task\CommandTask', $result); <ide><path>tests/TestCase/Controller/ComponentRegistryTest.php <ide> public function testLoadWithAlias() <ide> $result = $this->Components->load('Cookie'); <ide> $this->assertInstanceOf(__NAMESPACE__ . '\CookieAliasComponent', $result); <ide> <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> $result = $this->Components->load('SomeOther', ['className' => 'TestPlugin.Other']); <ide> $this->assertInstanceOf('TestPlugin\Controller\Component\OtherComponent', $result); <ide> $this->assertInstanceOf('TestPlugin\Controller\Component\OtherComponent', $this->Components->SomeOther); <ide> public function testLoadMissingComponent() <ide> */ <ide> public function testLoadPluginComponent() <ide> { <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> $result = $this->Components->load('TestPlugin.Other'); <ide> $this->assertInstanceOf('TestPlugin\Controller\Component\OtherComponent', $result, 'Component class is wrong.'); <ide> $this->assertInstanceOf('TestPlugin\Controller\Component\OtherComponent', $this->Components->Other, 'Class is wrong'); <ide> public function testLoadPluginComponent() <ide> */ <ide> public function testLoadWithAliasAndPlugin() <ide> { <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> $result = $this->Components->load('AliasedOther', ['className' => 'TestPlugin.Other']); <ide> $this->assertInstanceOf('TestPlugin\Controller\Component\OtherComponent', $result); <ide> $this->assertInstanceOf('TestPlugin\Controller\Component\OtherComponent', $this->Components->AliasedOther); <ide><path>tests/TestCase/Controller/ControllerTest.php <ide> public function testLoadModel() <ide> */ <ide> public function testLoadModelInPlugins() <ide> { <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> <ide> $Controller = new TestPluginController(); <ide> $Controller->setPlugin('TestPlugin'); <ide> public function testLoadModelInPlugins() <ide> */ <ide> public function testConstructSetModelClass() <ide> { <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> <ide> $request = new ServerRequest(); <ide> $response = new Response(); <ide> public function testConstructSetModelClass() <ide> */ <ide> public function testConstructClassesWithComponents() <ide> { <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> <ide> $Controller = new TestPluginController(new ServerRequest(), new Response()); <ide> $Controller->loadComponent('TestPlugin.Other'); <ide> public function testConstructClassesWithComponents() <ide> */ <ide> public function testRender() <ide> { <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> <ide> $request = new ServerRequest([ <ide> 'url' => 'controller_posts/index', <ide><path>tests/TestCase/Core/Configure/Engine/IniConfigTest.php <ide> public function testReadWithDots() <ide> */ <ide> public function testReadPluginValue() <ide> { <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> $engine = new IniConfig($this->path); <ide> $result = $engine->read('TestPlugin.nested'); <ide> <ide><path>tests/TestCase/Core/Configure/Engine/JsonConfigTest.php <ide> public function testReadWithDots() <ide> */ <ide> public function testReadPluginValue() <ide> { <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> $engine = new JsonConfig($this->path); <ide> $result = $engine->read('TestPlugin.load'); <ide> $this->assertArrayHasKey('plugin_load', $result); <ide><path>tests/TestCase/Core/Configure/Engine/PhpConfigTest.php <ide> public function testReadWithDots() <ide> */ <ide> public function testReadPluginValue() <ide> { <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> $engine = new PhpConfig($this->path); <ide> $result = $engine->read('TestPlugin.load'); <ide> $this->assertArrayHasKey('plugin_load', $result); <ide><path>tests/TestCase/Core/ConfigureTest.php <ide> public function testLoadMergeWithExistingData() <ide> public function testLoadPlugin() <ide> { <ide> Configure::config('test', new PhpConfig()); <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> $result = Configure::load('TestPlugin.load', 'test'); <ide> $this->assertTrue($result); <ide> $expected = '/test_app/Plugin/TestPlugin/Config/load.php'; <ide><path>tests/TestCase/Datasource/ConnectionManagerTest.php <ide> public function testConfigured() <ide> */ <ide> public function testGetPluginDataSource() <ide> { <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> $name = 'test_variant'; <ide> $config = ['className' => 'TestPlugin.TestSource', 'foo' => 'bar']; <ide> ConnectionManager::setConfig($name, $config); <ide><path>tests/TestCase/Error/ErrorHandlerTest.php <ide> public function testHandleExceptionLogSkipping() <ide> */ <ide> public function testLoadPluginHandler() <ide> { <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> $errorHandler = new TestErrorHandler([ <ide> 'exceptionRenderer' => 'TestPlugin.TestPluginExceptionRenderer', <ide> ]); <ide><path>tests/TestCase/Error/ExceptionRendererTest.php <ide> public function testMissingPluginRenderSafe() <ide> */ <ide> public function testMissingPluginRenderSafeWithPlugin() <ide> { <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> $exception = new NotFoundException(); <ide> $ExceptionRenderer = new ExceptionRenderer($exception); <ide> <ide><path>tests/TestCase/Http/SessionTest.php <ide> public function testUsingAppLibsHandler() <ide> public function testUsingPluginHandler() <ide> { <ide> static::setAppNamespace(); <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> <ide> $config = [ <ide> 'defaults' => 'cake', <ide><path>tests/TestCase/I18n/I18nTest.php <ide> public function testPluginMesagesLoad() <ide> */ <ide> public function testPluginOverride() <ide> { <del> $this->loadPlugins('TestTheme'); <add> $this->loadPlugins(['TestTheme']); <ide> $translator = I18n::getTranslator('test_theme'); <ide> $this->assertEquals( <ide> 'translated', <ide><path>tests/TestCase/Log/LogTest.php <ide> public function tearDown() <ide> public function testImportingLoggers() <ide> { <ide> static::setAppNamespace(); <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> <ide> Log::setConfig('libtest', [ <ide> 'engine' => 'TestApp' <ide><path>tests/TestCase/Mailer/EmailTest.php <ide> public function testSendRenderJapanese() <ide> */ <ide> public function testSendRenderThemed() <ide> { <del> $this->loadPlugins('TestTheme'); <add> $this->loadPlugins(['TestTheme']); <ide> $this->Email->reset(); <ide> $this->Email->setTransport('debug'); <ide> <ide><path>tests/TestCase/ORM/AssociationTest.php <ide> public function testSetTarget() <ide> */ <ide> public function testTargetPlugin() <ide> { <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> $config = [ <ide> 'className' => 'TestPlugin.Comments', <ide> 'foreignKey' => 'a_key', <ide><path>tests/TestCase/ORM/BehaviorRegistryTest.php <ide> public function tearDown() <ide> */ <ide> public function testClassName() <ide> { <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> <ide> $expected = 'Cake\ORM\Behavior\TranslateBehavior'; <ide> $result = BehaviorRegistry::className('Translate'); <ide> public function testClassName() <ide> */ <ide> public function testLoad() <ide> { <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> $config = ['alias' => 'Sluggable', 'replacement' => '-']; <ide> $result = $this->Behaviors->load('Sluggable', $config); <ide> $this->assertInstanceOf('TestApp\Model\Behavior\SluggableBehavior', $result); <ide> public function testLoadEnabledFalse() <ide> */ <ide> public function testLoadPlugin() <ide> { <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> $result = $this->Behaviors->load('TestPlugin.PersisterOne'); <ide> <ide> $expected = 'TestPlugin\Model\Behavior\PersisterOneBehavior'; <ide> public function testLoadDuplicateFinderAliasing() <ide> */ <ide> public function testHasMethod() <ide> { <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> $this->Behaviors->load('TestPlugin.PersisterOne'); <ide> $this->Behaviors->load('Sluggable'); <ide> <ide><path>tests/TestCase/ORM/Locator/TableLocatorTest.php <ide> public function testGetConfig() <ide> */ <ide> public function testConfigPlugin() <ide> { <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> <ide> $data = [ <ide> 'connection' => 'testing', <ide> public function testGetWithConventions() <ide> */ <ide> public function testGetPlugin() <ide> { <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> $table = $this->_locator->get('TestPlugin.TestPluginComments'); <ide> <ide> $this->assertInstanceOf('TestPlugin\Model\Table\TestPluginCommentsTable', $table); <ide> public function testGetMultiplePlugins() <ide> */ <ide> public function testGetPluginWithClassNameOption() <ide> { <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> $table = $this->_locator->get('Comments', [ <ide> 'className' => 'TestPlugin.TestPluginComments', <ide> ]); <ide> public function testGetPluginWithClassNameOption() <ide> */ <ide> public function testGetPluginWithFullNamespaceName() <ide> { <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> $class = 'TestPlugin\Model\Table\TestPluginCommentsTable'; <ide> $table = $this->_locator->get('Comments', [ <ide> 'className' => $class, <ide> public function testSet() <ide> */ <ide> public function testSetPlugin() <ide> { <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> <ide> $mock = $this->getMockBuilder('TestPlugin\Model\Table\CommentsTable')->getMock(); <ide> <ide><path>tests/TestCase/ORM/QueryRegressionTest.php <ide> public function testBelongsToManyDeepSave2() <ide> public function testPluginAssociationQueryGeneration() <ide> { <ide> $this->loadFixtures('Articles', 'Comments', 'Authors'); <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> $articles = $this->getTableLocator()->get('Articles'); <ide> $articles->hasMany('TestPlugin.Comments'); <ide> $articles->belongsTo('TestPlugin.Authors'); <ide><path>tests/TestCase/ORM/ResultSetTest.php <ide> public function testFetchMissingDefaultAlias() <ide> */ <ide> public function testSourceOnContainAssociations() <ide> { <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> $comments = $this->getTableLocator()->get('TestPlugin.Comments'); <ide> $comments->belongsTo('Authors', [ <ide> 'className' => 'TestPlugin.Authors', <ide><path>tests/TestCase/ORM/TableTest.php <ide> public function testHasManyWithClassName() <ide> public function testHasManyPluginOverlap() <ide> { <ide> $this->getTableLocator()->get('Comments'); <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> <ide> $table = new Table(['table' => 'authors']); <ide> <ide> public function testHasManyPluginOverlap() <ide> public function testHasManyPluginOverlapConfig() <ide> { <ide> $this->getTableLocator()->get('Comments'); <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> <ide> $table = new Table(['table' => 'authors']); <ide> <ide> public function testHasValidator() <ide> */ <ide> public function testEntitySourceExistingAndNew() <ide> { <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> $table = $this->getTableLocator()->get('TestPlugin.Authors'); <ide> <ide> $existingAuthor = $table->find()->first(); <ide> public function testEntitySource() <ide> $table = $this->getTableLocator()->get('Articles'); <ide> $this->assertEquals('Articles', $table->newEntity()->source()); <ide> <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> $table = $this->getTableLocator()->get('TestPlugin.Comments'); <ide> $this->assertEquals('TestPlugin.Comments', $table->newEntity()->source()); <ide> }); <ide> public function testSetEntitySource() <ide> $table = $this->getTableLocator()->get('Articles'); <ide> $this->assertEquals('Articles', $table->newEntity()->getSource()); <ide> <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> $table = $this->getTableLocator()->get('TestPlugin.Comments'); <ide> $this->assertEquals('TestPlugin.Comments', $table->newEntity()->getSource()); <ide> } <ide><path>tests/TestCase/Routing/DispatcherTest.php <ide> public function testDispatchBadPluginName() <ide> { <ide> $this->expectException(\Cake\Routing\Exception\MissingControllerException::class); <ide> $this->expectExceptionMessage('Controller class TestPlugin.Tests could not be found.'); <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> <ide> $request = new ServerRequest([ <ide> 'url' => 'TestPlugin.Tests/index', <ide><path>tests/TestCase/Routing/RequestActionTraitTest.php <ide> public function testRequestAction() <ide> */ <ide> public function testRequestActionPlugins() <ide> { <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> Router::reload(); <ide> Router::connect('/test_plugin/tests/:action/*', ['controller' => 'Tests', 'plugin' => 'TestPlugin']); <ide> <ide><path>tests/TestCase/Routing/RouteBuilderTest.php <ide> public function testLoadPluginBadFile() <ide> $this->deprecated(function () { <ide> $this->expectException(\InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Cannot load routes for the plugin named TestPlugin.'); <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> $routes = new RouteBuilder($this->collection, '/'); <ide> $routes->loadPlugin('TestPlugin', 'nope.php'); <ide> }); <ide> public function testLoadPluginBadFile() <ide> */ <ide> public function testLoadPlugin() <ide> { <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> $routes = new RouteBuilder($this->collection, '/'); <ide> $routes->loadPlugin('TestPlugin'); <ide> $this->assertCount(1, $this->collection->routes()); <ide><path>tests/TestCase/Routing/RouterTest.php <ide> public function testRegexRouteMatchUrl() <ide> */ <ide> public function testUsingCustomRouteClass() <ide> { <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> Router::connect( <ide> '/:slug', <ide> ['plugin' => 'TestPlugin', 'action' => 'index'], <ide> public function testUsingCustomRouteClass() <ide> */ <ide> public function testUsingCustomRouteClassPluginDotSyntax() <ide> { <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> Router::connect( <ide> '/:slug', <ide> ['controller' => 'posts', 'action' => 'view'], <ide><path>tests/TestCase/Shell/Task/AssetsTaskTest.php <ide> public function testSymlink() <ide> */ <ide> public function testSymlinkWhenVendorDirectoryExits() <ide> { <del> $this->loadPlugins('Company/TestPluginThree'); <add> $this->loadPlugins(['Company/TestPluginThree']); <ide> <ide> mkdir(WWW_ROOT . 'company'); <ide> <ide> public function testSymlinkWhenVendorDirectoryExits() <ide> */ <ide> public function testSymlinkWhenTargetAlreadyExits() <ide> { <del> $this->loadPlugins('TestTheme'); <add> $this->loadPlugins(['TestTheme']); <ide> <ide> $shell = $this->getMockBuilder('Cake\Shell\Task\AssetsTask') <ide> ->setMethods(['in', 'out', 'err', '_stop', '_createSymlink', '_copyDirectory']) <ide> public function testSymlinkWhenTargetAlreadyExits() <ide> */ <ide> public function testForPluginWithoutWebroot() <ide> { <del> $this->loadPlugins('TestPluginTwo'); <add> $this->loadPlugins(['TestPluginTwo']); <ide> <ide> $this->Task->symlink(); <ide> $this->assertFileNotExists(WWW_ROOT . 'test_plugin_two'); <ide> public function testCopy() <ide> */ <ide> public function testCopyOverwrite() <ide> { <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> <ide> $this->Task->copy(); <ide> <ide><path>tests/TestCase/TestSuite/FixtureManagerTest.php <ide> public function testFixturizeCoreConstraint() <ide> */ <ide> public function testFixturizePlugin() <ide> { <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> <ide> $test = $this->getMockBuilder('Cake\TestSuite\TestCase')->getMock(); <ide> $test->fixtures = ['plugin.test_plugin.articles']; <ide> public function testFixturizePlugin() <ide> */ <ide> public function testFixturizePluginSubdirectory() <ide> { <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> <ide> $test = $this->getMockBuilder('Cake\TestSuite\TestCase')->getMock(); <ide> $test->fixtures = ['plugin.test_plugin.blog/comments']; <ide><path>tests/TestCase/TestSuite/TestCaseTest.php <ide> public function testGetMockForModelSecondaryDatasource() <ide> public function testGetMockForModelWithPlugin() <ide> { <ide> static::setAppNamespace(); <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> $TestPluginComment = $this->getMockForModel('TestPlugin.TestPluginComments'); <ide> <ide> $result = $this->getTableLocator()->get('TestPlugin.TestPluginComments'); <ide><path>tests/TestCase/View/Helper/FlashHelperTest.php <ide> public function testFlashElementInAttrs() <ide> */ <ide> public function testFlashWithPluginElement() <ide> { <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> <ide> $result = $this->Flash->render('flash', ['element' => 'TestPlugin.Flash/plugin_element']); <ide> $expected = 'this is the plugin element'; <ide> public function testFlashWithPluginElement() <ide> */ <ide> public function testFlashWithTheme() <ide> { <del> $this->loadPlugins('TestTheme'); <add> $this->loadPlugins(['TestTheme']); <ide> <ide> $this->View->setTheme('TestTheme'); <ide> $result = $this->Flash->render('flash'); <ide><path>tests/TestCase/View/Helper/HtmlHelperTest.php <ide> public function testCssLink() <ide> $result = $this->Html->css('screen.css', ['once' => false]); <ide> $this->assertHtml($expected, $result); <ide> <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> $result = $this->Html->css('TestPlugin.style', ['plugin' => false]); <ide> $expected['link']['href'] = 'preg:/.*css\/TestPlugin\.style\.css/'; <ide> $this->assertHtml($expected, $result); <ide> public function testCssWithFullBase() <ide> */ <ide> public function testPluginCssLink() <ide> { <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> <ide> $result = $this->Html->css('TestPlugin.test_plugin_asset'); <ide> $expected = [ <ide> public function testCssTimestamping() <ide> */ <ide> public function testPluginCssTimestamping() <ide> { <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> <ide> Configure::write('debug', true); <ide> Configure::write('Asset.timestamp', true); <ide> public function testScriptTimestamping() <ide> */ <ide> public function testPluginScriptTimestamping() <ide> { <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> <ide> $pluginPath = Plugin::path('TestPlugin'); <ide> $pluginJsPath = $pluginPath . 'webroot/js'; <ide> public function testScript() <ide> */ <ide> public function testPluginScript() <ide> { <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> <ide> $result = $this->Html->script('TestPlugin.foo'); <ide> $expected = [ <ide><path>tests/TestCase/View/Helper/NumberHelperTest.php <ide> public function testEngineOverride() <ide> $Number = new NumberHelperTestObject($this->View, ['engine' => 'TestAppEngine']); <ide> $this->assertInstanceOf('TestApp\Utility\TestAppEngine', $Number->engine()); <ide> <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> $Number = new NumberHelperTestObject($this->View, ['engine' => 'TestPlugin.TestPluginEngine']); <ide> $this->assertInstanceOf('TestPlugin\Utility\TestPluginEngine', $Number->engine()); <ide> Plugin::unload('TestPlugin'); <ide><path>tests/TestCase/View/Helper/TextHelperTest.php <ide> public function testEngineOverride() <ide> $Text = new TextHelperTestObject($this->View, ['engine' => 'TestAppEngine']); <ide> $this->assertInstanceOf('TestApp\Utility\TestAppEngine', $Text->engine()); <ide> <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> $Text = new TextHelperTestObject($this->View, ['engine' => 'TestPlugin.TestPluginEngine']); <ide> $this->assertInstanceOf('TestPlugin\Utility\TestPluginEngine', $Text->engine()); <ide> Plugin::unload(); <ide><path>tests/TestCase/View/Helper/UrlHelperTest.php <ide> public function testAssetUrlNoRewrite() <ide> public function testAssetUrlPlugin() <ide> { <ide> $this->Helper->webroot = ''; <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> <ide> $result = $this->Helper->assetUrl('TestPlugin.style', ['ext' => '.css']); <ide> $this->assertEquals('test_plugin/style.css', $result); <ide><path>tests/TestCase/View/HelperRegistryTest.php <ide> public function testLoadWithAlias() <ide> */ <ide> public function testLoadWithAliasAndPlugin() <ide> { <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> $result = $this->Helpers->load('SomeOther', ['className' => 'TestPlugin.OtherHelper']); <ide> $this->assertInstanceOf('TestPlugin\View\Helper\OtherHelperHelper', $result); <ide> $this->assertInstanceOf('TestPlugin\View\Helper\OtherHelperHelper', $this->Helpers->SomeOther); <ide><path>tests/TestCase/View/StringTemplateTest.php <ide> public function testLoad() <ide> */ <ide> public function testLoadPlugin() <ide> { <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> $this->assertNull($this->template->load('TestPlugin.test_templates')); <ide> $this->assertEquals('<em>{{text}}</em>', $this->template->get('italic')); <ide> Plugin::unload(); <ide><path>tests/TestCase/View/Widget/WidgetLocatorTest.php <ide> public function testAddWidgetsFromConfigInConstructor() <ide> */ <ide> public function testAddPluginWidgetsFromConfigInConstructor() <ide> { <del> $this->loadPlugins('TestPlugin'); <add> $this->loadPlugins(['TestPlugin']); <ide> $widgets = [ <ide> 'text' => ['Cake\View\Widget\BasicWidget'], <ide> 'TestPlugin.test_widgets',
41
Python
Python
adjust setup so that all extras run on windows
c5f3149f95855ac52d44b8a9bb0754e8e94792bd
<ide><path>setup.py <ide> ] <ide> extras["torch"] = ["torch>=1.0"] <ide> <del>extras["flax"] = ["jaxlib==0.1.55", "jax>=0.2.0", "flax==0.2.2"] <ide> if os.name == "nt": # windows <add> extras["retrieval"] = ["datasets"] # faiss is not supported on windows <ide> extras["flax"] = [] # jax is not supported on windows <add>else: <add> extras["retrieval"] = ["faiss-cpu", "datasets"] <add> extras["flax"] = ["jaxlib==0.1.55", "jax>=0.2.0", "flax==0.2.2"] <ide> <ide> extras["tokenizers"] = ["tokenizers==0.9.2"] <ide> extras["onnxruntime"] = ["onnxruntime>=1.4.0", "onnxruntime-tools>=1.4.2"]
1
Javascript
Javascript
add github api query to bug report template
b522638b994abfea16b981efdf88e11d1078c982
<ide><path>packages/react-devtools-shared/src/devtools/views/ErrorBoundary/ReportNewIssue.js <ide> <ide> import * as React from 'react'; <ide> import Icon from '../Icon'; <add>import {searchGitHubIssuesURL} from './githubAPI'; <ide> import styles from './shared.css'; <ide> <ide> function encodeURIWrapper(string: string): string { <ide> export default function ReportNewIssue({ <ide> return null; <ide> } <ide> <add> const gitHubAPISearch = <add> errorMessage !== null ? searchGitHubIssuesURL(errorMessage) : '(none)'; <add> <ide> const title = `Error: "${errorMessage || ''}"`; <ide> const labels = ['Component: Developer Tools', 'Status: Unconfirmed']; <ide> <ide> If possible, please describe how to reproduce this bug on the website or app men <ide> DevTools version: ${process.env.DEVTOOLS_VERSION || ''} <ide> <ide> Call stack: <del>${callStack || '(not available)'} <add>${callStack || '(none)'} <ide> <ide> Component stack: <del>${componentStack || '(not available)'} <add>${componentStack || '(none)'} <add> <add>GitHub URL search query: <add>${gitHubAPISearch} <ide> `; <ide> <ide> bugURL += `/issues/new?labels=${encodeURIWrapper( <ide><path>packages/react-devtools-shared/src/devtools/views/ErrorBoundary/githubAPI.js <ide> export type GitHubIssue = {| <ide> <ide> const GITHUB_ISSUES_API = 'https://api.github.com/search/issues'; <ide> <del>export async function searchGitHubIssues( <del> message: string, <del>): Promise<GitHubIssue | null> { <add>export function searchGitHubIssuesURL(message: string): string { <ide> // Remove Fiber IDs from error message (as those will be unique). <ide> message = message.replace(/"[0-9]+"/g, ''); <ide> <ide> export async function searchGitHubIssues( <ide> 'repo:facebook/react', <ide> ]; <ide> <del> const response = await fetch( <add> return ( <ide> GITHUB_ISSUES_API + <del> '?q=' + <del> encodeURIComponent(message) + <del> '%20' + <del> filters.map(encodeURIComponent).join('%20'), <add> '?q=' + <add> encodeURIComponent(message) + <add> '%20' + <add> filters.map(encodeURIComponent).join('%20') <ide> ); <add>} <add> <add>export async function searchGitHubIssues( <add> message: string, <add>): Promise<GitHubIssue | null> { <add> const response = await fetch(searchGitHubIssuesURL(message)); <ide> const data = await response.json(); <ide> if (data.items.length > 0) { <ide> const item = data.items[0];
2
Javascript
Javascript
simplify promise nesting
9487db8be7f5453bde952bf9a6b5c4c0e1748c7f
<ide><path>examples/real-world/src/middleware/api.js <ide> const callApi = (endpoint, schema) => { <ide> <ide> return fetch(fullUrl) <ide> .then(response => <del> response.json().then(json => ({ json, response })) <del> ).then(({ json, response }) => { <del> if (!response.ok) { <del> return Promise.reject(json) <del> } <del> <del> const camelizedJson = camelizeKeys(json) <del> const nextPageUrl = getNextPageUrl(response) <del> <del> return Object.assign({}, <del> normalize(camelizedJson, schema), <del> { nextPageUrl } <del> ) <del> }) <add> response.json().then(json => { <add> if (!response.ok) { <add> return Promise.reject(json) <add> } <add> <add> const camelizedJson = camelizeKeys(json) <add> const nextPageUrl = getNextPageUrl(response) <add> <add> return Object.assign({}, <add> normalize(camelizedJson, schema), <add> { nextPageUrl } <add> ) <add> }) <add> ) <ide> } <ide> <ide> // We use this Normalizr schemas to transform API responses from a nested form
1
Text
Text
fix minor typo and improve wording
1bcc37caec07c01ab385f562ffa56d2b2bb0a7d8
<ide><path>docs/sources/reference/builder.md <ide> To [*build*](../commandline/cli/#cli-build) an image from a source repository, <ide> create a description file called Dockerfile at the root of your repository. <ide> This file will describe the steps to assemble the image. <ide> <del>Then call `docker build` with the path of you source repository as argument <add>Then call `docker build` with the path of your source repository as the argument <ide> (for example, `.`): <ide> <ide> $ sudo docker build .
1
Text
Text
fix a typo in the flaky test template
b1704e43475d0af2019c1cb1da1cd610473168d6
<ide><path>.github/ISSUE_TEMPLATE/4-report-a-flaky-test.md <ide> labels: "CI / flaky test" <ide> <!-- <ide> Thank you for reporting a flaky test. <ide> <del>Flaky tests are tests that fail occaisonally in Node.js CI, but not consistently <del>enough to block PRs from landing, or that are failing in CI jobs or test modes <del>that are not run for every PR. <add>Flaky tests are tests that fail occasionally in the Node.js CI, but not <add>consistently enough to block PRs from landing, or that are failing in CI jobs or <add>test modes that are not run for every PR. <ide> <ide> Please fill in as much of the template below as you're able. <ide>
1
Java
Java
fix lint warning in reactchoreographer
0df2530c9e2440e0e14337c37f6fa35b807ff917
<ide><path>ReactAndroid/src/main/java/com/facebook/react/modules/core/ReactChoreographer.java <ide> public enum CallbackType { <ide> <ide> private final int mOrder; <ide> <del> private CallbackType(int order) { <add> CallbackType(int order) { <ide> mOrder = order; <ide> } <ide>
1
Java
Java
fix tests in dispatcherservlettests
06679a5583e6e5bbd8ec10a12f665cdfc561cc19
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/DispatcherServletTests.java <ide> import javax.servlet.http.HttpServletRequestWrapper; <ide> import javax.servlet.http.HttpServletResponse; <ide> <add>import org.assertj.core.api.InstanceOfAssertFactories; <ide> import org.junit.jupiter.api.BeforeEach; <ide> import org.junit.jupiter.api.Test; <ide> <ide> public void detectAllHandlerAdapters() throws ServletException, IOException { <ide> <ide> request = new MockHttpServletRequest(getServletContext(), "GET", "/form.do"); <ide> response = new MockHttpServletResponse(); <add> request.addParameter("fail", "yes"); <ide> complexDispatcherServlet.service(request, response); <add> assertThat(response.getForwardedUrl()).as("forwarded URL").isEqualTo("failed1.jsp"); <add> assertThat(request.getAttribute("exception")).isNull(); <ide> } <ide> <ide> @Test <ide> public void notDetectAllHandlerAdapters() throws ServletException, IOException { <ide> complexDispatcherServlet.service(request, response); <ide> assertThat(response.getContentAsString()).isEqualTo("body"); <ide> <del> // SimpleControllerHandlerAdapter not detected <add> // MyHandlerAdapter not detected <ide> request = new MockHttpServletRequest(getServletContext(), "GET", "/form.do"); <ide> response = new MockHttpServletResponse(); <add> request.addParameter("fail", "yes"); <ide> complexDispatcherServlet.service(request, response); <del> assertThat(response.getForwardedUrl()).as("forwarded to failed").isEqualTo("failed0.jsp"); <del> assertThat(request.getAttribute("exception").getClass().equals(ServletException.class)).as("Exception exposed").isTrue(); <add> assertThat(response.getForwardedUrl()).as("forwarded URL").isEqualTo("failed0.jsp"); <add> assertThat(request.getAttribute("exception")) <add> .asInstanceOf(InstanceOfAssertFactories.type(ServletException.class)) <add> .extracting(Throwable::getMessage).asString().startsWith("No adapter for handler"); <ide> } <ide> <ide> @Test
1
Text
Text
fix position for some entries in 1.4.1
c61149213ba2c4999ae7f3e71a5f290a072357aa
<ide><path>CHANGELOG.md <ide> - prevent exception when using `watch` as isolated scope binding property in Firefox <ide> ([a6339d30](https://github.com/angular/angular.js/commit/a6339d30d1379689da5eec9647a953f64821f8b0), <ide> [#11627](https://github.com/angular/angular.js/issues/11627)) <add> - assign controller return values correctly for multiple directives <add> ([8caf1802](https://github.com/angular/angular.js/commit/8caf1802e0e93389dec626ef35e04a302aa6c39d), <add> [#12029](https://github.com/angular/angular.js/issues/12029), [#12036](https://github.com/angular/angular.js/issues/12036)) <ide> - **$location:** do not get caught in infinite digest in IE9 when redirecting in `$locationChangeSuccess` <ide> ([91b60226](https://github.com/angular/angular.js/commit/91b602263b96b6fce1331208462e18eb647f4d60), <ide> [#11439](https://github.com/angular/angular.js/issues/11439), [#11675](https://github.com/angular/angular.js/issues/11675), [#11935](https://github.com/angular/angular.js/issues/11935), [#12083](https://github.com/angular/angular.js/issues/12083)) <del>- **$parse:** <del> - set null reference properties to `undefined` <add>- **$parse:** set null reference properties to `undefined` <ide> ([71fc3f4f](https://github.com/angular/angular.js/commit/71fc3f4fa0cd12eff335d57efed7c033554749f4), <ide> [#12099](https://github.com/angular/angular.js/issues/12099)) <ide> ([d19504a1](https://github.com/angular/angular.js/commit/d19504a179355d7801d59a8db0285a1322e04601), <ide> [#11959](https://github.com/angular/angular.js/issues/11959)) <ide> - **$sanitize:** do not remove `tabindex` attribute <ide> ([799353c7](https://github.com/angular/angular.js/commit/799353c75de28e6fbf52dac6e0721e85b578575a), <ide> [#8371](https://github.com/angular/angular.js/issues/8371), [#5853](https://github.com/angular/angular.js/issues/5853)) <del>- **compile:** assign controller return values correctly for multiple directives <del> ([8caf1802](https://github.com/angular/angular.js/commit/8caf1802e0e93389dec626ef35e04a302aa6c39d), <del> [#12029](https://github.com/angular/angular.js/issues/12029), [#12036](https://github.com/angular/angular.js/issues/12036)) <ide> - **copy:** do not copy the same object twice <ide> ([0e622f7b](https://github.com/angular/angular.js/commit/0e622f7b5bc3d5d0ab0fbc1a1bc69404bd7216d5)) <ide> - **forms:** parse exponential notation in `numberInputType` directive
1
Javascript
Javascript
improve checks in test-path-parse-format
0700927832e167ac83183aefa0f63af02b6c3a75
<ide><path>test/parallel/test-path-parse-format.js <ide> 'use strict'; <del>const common = require('../common'); <add>require('../common'); <ide> const assert = require('assert'); <ide> const path = require('path'); <ide> <ide> const unixSpecialCaseFormatTests = [ <ide> <ide> const errors = [ <ide> {method: 'parse', input: [null], <del> message: /Path must be a string. Received null/}, <add> message: /^TypeError: Path must be a string. Received null$/}, <ide> {method: 'parse', input: [{}], <del> message: /Path must be a string. Received {}/}, <add> message: /^TypeError: Path must be a string. Received {}$/}, <ide> {method: 'parse', input: [true], <del> message: /Path must be a string. Received true/}, <add> message: /^TypeError: Path must be a string. Received true$/}, <ide> {method: 'parse', input: [1], <del> message: /Path must be a string. Received 1/}, <add> message: /^TypeError: Path must be a string. Received 1$/}, <ide> {method: 'parse', input: [], <del> message: /Path must be a string. Received undefined/}, <add> message: /^TypeError: Path must be a string. Received undefined$/}, <ide> {method: 'format', input: [null], <del> message: /Parameter "pathObject" must be an object, not/}, <add> message: <add> /^TypeError: Parameter "pathObject" must be an object, not object$/}, <ide> {method: 'format', input: [''], <del> message: /Parameter "pathObject" must be an object, not string/}, <add> message: <add> /^TypeError: Parameter "pathObject" must be an object, not string$/}, <ide> {method: 'format', input: [true], <del> message: /Parameter "pathObject" must be an object, not boolean/}, <add> message: <add> /^TypeError: Parameter "pathObject" must be an object, not boolean$/}, <ide> {method: 'format', input: [1], <del> message: /Parameter "pathObject" must be an object, not number/}, <add> message: <add> /^TypeError: Parameter "pathObject" must be an object, not number$/}, <ide> ]; <ide> <ide> checkParseFormat(path.win32, winPaths); <ide> assert.strictEqual(failures.length, 0, failures.join('')); <ide> <ide> function checkErrors(path) { <ide> errors.forEach(function(errorCase) { <del> try { <add> assert.throws(() => { <ide> path[errorCase.method].apply(path, errorCase.input); <del> } catch (err) { <del> assert.ok(err instanceof TypeError); <del> assert.ok( <del> errorCase.message.test(err.message), <del> 'expected ' + errorCase.message + ' to match ' + err.message <del> ); <del> return; <del> } <del> <del> common.fail('should have thrown'); <add> }, errorCase.message); <ide> }); <ide> } <ide>
1
Java
Java
remove duplicate assertion in matchwithnullpath()
bccc7a62f461d62f4fa98ea4f68f1e24da548b16
<ide><path>spring-core/src/test/java/org/springframework/util/AntPathMatcherTests.java <ide> public void match() { <ide> public void matchWithNullPath() { <ide> assertThat(pathMatcher.match("/test", null)).isFalse(); <ide> assertThat(pathMatcher.match("/", null)).isFalse(); <del> assertThat(pathMatcher.match("/", null)).isFalse(); <ide> assertThat(pathMatcher.match(null, null)).isFalse(); <ide> } <ide>
1
Text
Text
add link to dns definition
cba9f2e7a2ff04619ceba1350418469049d79b1c
<ide><path>doc/api/dns.md <ide> The `dns` module enables name resolution. For example, use it to look up IP <ide> addresses of host names. <ide> <del>Although named for the Domain Name System (DNS), it does not always use the DNS <del>protocol for lookups. [`dns.lookup()`][] uses the operating system facilities to <del>perform name resolution. It may not need to perform any network communication. <del>Developers looking to perform name resolution in the same way that other <del>applications on the same operating system behave should use [`dns.lookup()`][]. <add>Although named for the [Domain Name System (DNS)][], it does not always use the <add>DNS protocol for lookups. [`dns.lookup()`][] uses the operating system <add>facilities to perform name resolution. It may not need to perform any network <add>communication. Developers looking to perform name resolution in the same way <add>that other applications on the same operating system behave should use <add>[`dns.lookup()`][]. <ide> <ide> ```js <ide> const dns = require('dns'); <ide> uses. For instance, _they do not use the configuration from `/etc/hosts`_. <ide> [`socket.connect()`]: net.html#net_socket_connect_options_connectlistener <ide> [`util.promisify()`]: util.html#util_util_promisify_original <ide> [DNS error codes]: #dns_error_codes <add>[Domain Name System (DNS)]: https://en.wikipedia.org/wiki/Domain_Name_System <ide> [Implementation considerations section]: #dns_implementation_considerations <ide> [RFC 8482]: https://tools.ietf.org/html/rfc8482 <ide> [RFC 5952]: https://tools.ietf.org/html/rfc5952#section-6
1
Text
Text
change example title to dr
f0fd77648fb488c26852cd1494b69073e5766b65
<ide><path>website/docs/usage/rule-based-matching.md <ide> what you need for your application. <ide> > available corpus. <ide> <ide> For example, the corpus spaCy's [English models](/models/en) were trained on <del>defines a `PERSON` entity as just the **person name**, without titles like "Mr" <del>or "Dr". This makes sense, because it makes it easier to resolve the entity type <del>back to a knowledge base. But what if your application needs the full names, <del>_including_ the titles? <add>defines a `PERSON` entity as just the **person name**, without titles like "Mr." <add>or "Dr.". This makes sense, because it makes it easier to resolve the entity <add>type back to a knowledge base. But what if your application needs the full <add>names, _including_ the titles? <ide> <ide> ```python <ide> ### {executable="true"} <ide> import spacy <ide> <ide> nlp = spacy.load("en_core_web_sm") <del>doc = nlp("Dr Alex Smith chaired first board meeting of Acme Corp Inc.") <add>doc = nlp("Dr. Alex Smith chaired first board meeting of Acme Corp Inc.") <ide> print([(ent.text, ent.label_) for ent in doc.ents]) <ide> ``` <ide> <ide> def expand_person_entities(doc): <ide> # Add the component after the named entity recognizer <ide> nlp.add_pipe(expand_person_entities, after='ner') <ide> <del>doc = nlp("Dr Alex Smith chaired first board meeting of Acme Corp Inc.") <add>doc = nlp("Dr. Alex Smith chaired first board meeting of Acme Corp Inc.") <ide> print([(ent.text, ent.label_) for ent in doc.ents]) <ide> ``` <ide>
1
PHP
PHP
add use statements for all fully qualified classes
5a77162a44a197f0e3751a5d00e1ed4d5847eeaa
<ide><path>src/Mailer/Transport/SmtpTransport.php <ide> use Cake\Network\Exception\SocketException; <ide> use Cake\Network\Socket; <ide> use Exception; <add>use RuntimeException; <ide> <ide> /** <ide> * Send mail using SMTP protocol <ide> protected function _smtpSend(?string $data, $checkCode = '250'): ?string <ide> protected function _socket(): Socket <ide> { <ide> if ($this->_socket === null) { <del> throw new \RuntimeException('Socket is null, but must be set.'); <add> throw new RuntimeException('Socket is null, but must be set.'); <ide> } <ide> <ide> return $this->_socket; <ide><path>src/ORM/Locator/LocatorInterface.php <ide> */ <ide> namespace Cake\ORM\Locator; <ide> <add>use Cake\Datasource\Locator\LocatorInterface as BaseLocatorInterface; <ide> use Cake\Datasource\RepositoryInterface; <ide> use Cake\ORM\Table; <ide> <ide> /** <ide> * Registries for Table objects should implement this interface. <ide> */ <del>interface LocatorInterface extends \Cake\Datasource\Locator\LocatorInterface <add>interface LocatorInterface extends BaseLocatorInterface <ide> { <ide> /** <ide> * Returns configuration for an alias or the full configuration array for <ide><path>tests/TestCase/BasicsTest.php <ide> use Cake\Event\EventManager; <ide> use Cake\Http\Response; <ide> use Cake\TestSuite\TestCase; <add>use stdClass; <ide> <ide> require_once CAKE . 'basics.php'; <ide> <ide> public function testH(): void <ide> $this->assertFalse($result['foo']); <ide> $this->assertTrue($result['bar']); <ide> <del> $obj = new \stdClass(); <add> $obj = new stdClass(); <ide> $result = h($obj); <ide> $this->assertSame('(object)stdClass', $result); <ide> <ide><path>tests/TestCase/Cache/CacheTest.php <ide> */ <ide> namespace Cake\Test\TestCase\Cache; <ide> <add>use BadMethodCallException; <ide> use Cake\Cache\Cache; <ide> use Cake\Cache\CacheRegistry; <ide> use Cake\Cache\Engine\FileEngine; <ide> use Cake\Cache\Engine\NullEngine; <ide> use Cake\Cache\InvalidArgumentException; <ide> use Cake\TestSuite\TestCase; <ide> use Psr\SimpleCache\CacheInterface as SimpleCacheInterface; <add>use stdClass; <ide> <ide> /** <ide> * CacheTest class <ide> public function testConfigInvalidEngine(): void <ide> $config = ['engine' => 'Imaginary']; <ide> Cache::setConfig('test', $config); <ide> <del> $this->expectException(\BadMethodCallException::class); <add> $this->expectException(BadMethodCallException::class); <ide> <ide> Cache::pool('test'); <ide> } <ide> public function testConfigInvalidEngine(): void <ide> */ <ide> public function testConfigInvalidObject(): void <ide> { <del> $this->getMockBuilder(\stdClass::class) <add> $this->getMockBuilder(stdClass::class) <ide> ->setMockClassName('RubbishEngine') <ide> ->getMock(); <ide> <del> $this->expectException(\BadMethodCallException::class); <add> $this->expectException(BadMethodCallException::class); <ide> <ide> Cache::setConfig('test', [ <ide> 'engine' => '\RubbishEngine', <ide> public function testConfigErrorOnReconfigure(): void <ide> { <ide> Cache::setConfig('tests', ['engine' => 'File', 'path' => CACHE]); <ide> <del> $this->expectException(\BadMethodCallException::class); <add> $this->expectException(BadMethodCallException::class); <ide> <ide> Cache::setConfig('tests', ['engine' => 'Apc']); <ide> } <ide><path>tests/TestCase/Cache/Engine/ArrayEngineTest.php <ide> */ <ide> namespace Cake\Test\TestCase\Cache\Engine; <ide> <add>use ArrayObject; <ide> use Cake\Cache\Cache; <ide> use Cake\Cache\Engine\ArrayEngine; <ide> use Cake\Cache\InvalidArgumentException; <ide> public function testAdd(): void <ide> */ <ide> public function testWriteManyTraversable(): void <ide> { <del> $data = new \ArrayObject([ <add> $data = new ArrayObject([ <ide> 'a' => 1, <ide> 'b' => 'foo', <ide> ]); <ide><path>tests/TestCase/Cache/Engine/MemcachedEngineTest.php <ide> public function testCompressionSetting(): void <ide> 'compress' => false, <ide> ]); <ide> <del> $this->assertFalse($Memcached->getOption(\Memcached::OPT_COMPRESSION)); <add> $this->assertFalse($Memcached->getOption(Memcached::OPT_COMPRESSION)); <ide> <ide> $MemcachedCompressed = new MemcachedEngine(); <ide> $MemcachedCompressed->init([ <ide> public function testCompressionSetting(): void <ide> 'compress' => true, <ide> ]); <ide> <del> $this->assertTrue($MemcachedCompressed->getOption(\Memcached::OPT_COMPRESSION)); <add> $this->assertTrue($MemcachedCompressed->getOption(Memcached::OPT_COMPRESSION)); <ide> } <ide> <ide> /** <ide> public function testOptionsSetting(): void <ide> */ <ide> public function testInvalidSerializerSetting(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('invalid_serializer is not a valid serializer engine for Memcached'); <ide> $Memcached = new MemcachedEngine(); <ide> $config = [ <ide> public function testJsonSerializerThrowException(): void <ide> 'serialize' => 'json', <ide> ]; <ide> <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Memcached extension is not compiled with json support'); <ide> $Memcached->init($config); <ide> } <ide> public function testMsgpackSerializerThrowException(): void <ide> 'serialize' => 'msgpack', <ide> ]; <ide> <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Memcached extension is not compiled with msgpack support'); <ide> $Memcached->init($config); <ide> } <ide> public function testIgbinarySerializerThrowException(): void <ide> 'serialize' => 'igbinary', <ide> ]; <ide> <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Memcached extension is not compiled with igbinary support'); <ide> $Memcached->init($config); <ide> } <ide> public function testIgbinarySerializerThrowException(): void <ide> */ <ide> public function testSaslAuthException(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Memcached extension is not build with SASL support'); <ide> $this->skipIf( <ide> method_exists(Memcached::class, 'setSaslAuthData'), <ide> public function testSaslAuthException(): void <ide> 'username' => 'test', <ide> 'password' => 'password', <ide> ]; <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Memcached extension is not built with SASL support'); <ide> $MemcachedEngine->init($config); <ide> } <ide><path>tests/TestCase/Collection/CollectionTest.php <ide> use ArrayIterator; <ide> use ArrayObject; <ide> use Cake\Collection\Collection; <add>use Cake\Collection\Iterator\BufferedIterator; <ide> use Cake\ORM\Entity; <ide> use Cake\TestSuite\TestCase; <add>use DateInterval; <ide> use DatePeriod; <add>use DateTime; <ide> use Generator; <ide> use InvalidArgumentException; <add>use LogicException; <ide> use NoRewindIterator; <ide> use stdClass; <ide> use TestApp\Collection\CountableIterator; <ide> public function testMedianWithMatcher(iterable $items): void <ide> */ <ide> public function testIteratorIsWrapped(): void <ide> { <del> $items = new \ArrayObject([1, 2, 3]); <add> $items = new ArrayObject([1, 2, 3]); <ide> $collection = new Collection($items); <ide> $this->assertEquals(iterator_to_array($items), iterator_to_array($collection)); <ide> } <ide> public function testTakeWithTraversableNonIterator(): void <ide> $collection = new Collection($this->datePeriod('2017-01-01', '2017-01-07')); <ide> $result = $collection->take(3, 1)->toList(); <ide> $expected = [ <del> new \DateTime('2017-01-02'), <del> new \DateTime('2017-01-03'), <del> new \DateTime('2017-01-04'), <add> new DateTime('2017-01-02'), <add> new DateTime('2017-01-03'), <add> new DateTime('2017-01-04'), <ide> ]; <ide> $this->assertEquals($expected, $result); <ide> } <ide> public function testBufferedIterator(): void <ide> ['myField' => '2'], <ide> ['myField' => '3'], <ide> ]; <del> $buffered = (new \Cake\Collection\Collection($data))->buffered(); <add> $buffered = (new Collection($data))->buffered(); <ide> // Check going forwards <ide> $this->assertNotEmpty($buffered->firstMatch(['myField' => '1'])); <ide> $this->assertNotEmpty($buffered->firstMatch(['myField' => '2'])); <ide> public function testIsEmpty(): void <ide> */ <ide> public function testIsEmptyDoesNotConsume(): void <ide> { <del> $array = new \ArrayIterator([1, 2, 3]); <del> $inner = new \Cake\Collection\Iterator\BufferedIterator($array); <add> $array = new ArrayIterator([1, 2, 3]); <add> $inner = new BufferedIterator($array); <ide> $collection = new Collection($inner); <ide> $this->assertFalse($collection->isEmpty()); <ide> $this->assertCount(3, $collection->toArray()); <ide> public function testSkipWithTraversableNonIterator(): void <ide> $collection = new Collection($this->datePeriod('2017-01-01', '2017-01-07')); <ide> $result = $collection->skip(3)->toList(); <ide> $expected = [ <del> new \DateTime('2017-01-04'), <del> new \DateTime('2017-01-05'), <del> new \DateTime('2017-01-06'), <add> new DateTime('2017-01-04'), <add> new DateTime('2017-01-05'), <add> new DateTime('2017-01-06'), <ide> ]; <ide> $this->assertEquals($expected, $result); <ide> } <ide> public function testLastNtWithCountable(): void <ide> public function testLastNtWithNegative($data): void <ide> { <ide> $collection = new Collection($data); <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('The takeLast method requires a number greater than 0.'); <ide> $collection->takeLast(-1)->toArray(); <ide> } <ide> public function testCartesianProduct(): void <ide> */ <ide> public function testCartesianProductMultidimensionalArray(): void <ide> { <del> $this->expectException(\LogicException::class); <add> $this->expectException(LogicException::class); <ide> $collection = new Collection([ <ide> [ <ide> 'names' => [ <ide> public function testTranspose(): void <ide> */ <ide> public function testTransposeUnEvenLengthShouldThrowException(): void <ide> { <del> $this->expectException(\LogicException::class); <add> $this->expectException(LogicException::class); <ide> $collection = new Collection([ <ide> ['Products', '2012', '2013', '2014'], <ide> ['Product A', '200', '100', '50'], <ide> protected function yieldItems(iterable $items): Generator <ide> */ <ide> protected function datePeriod($start, $end): DatePeriod <ide> { <del> return new \DatePeriod(new \DateTime($start), new \DateInterval('P1D'), new \DateTime($end)); <add> return new DatePeriod(new DateTime($start), new DateInterval('P1D'), new DateTime($end)); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Collection/Iterator/FilterIteratorTest.php <ide> */ <ide> namespace Cake\Test\TestCase\Collection\Iterator; <ide> <add>use ArrayIterator; <ide> use Cake\Collection\Iterator\FilterIterator; <ide> use Cake\TestSuite\TestCase; <ide> <ide> class FilterIteratorTest extends TestCase <ide> */ <ide> public function testFilter(): void <ide> { <del> $items = new \ArrayIterator([1, 2, 3]); <add> $items = new ArrayIterator([1, 2, 3]); <ide> $callable = function ($value, $key, $itemArg) use ($items) { <ide> $this->assertSame($items, $itemArg); <ide> $this->assertContains($value, $items); <ide><path>tests/TestCase/Collection/Iterator/MapReduceTest.php <ide> use ArrayIterator; <ide> use Cake\Collection\Iterator\MapReduce; <ide> use Cake\TestSuite\TestCase; <add>use LogicException; <ide> <ide> /** <ide> * Tests MapReduce class <ide> public function testEmitFinalInMapper(): void <ide> */ <ide> public function testReducerRequired(): void <ide> { <del> $this->expectException(\LogicException::class); <add> $this->expectException(LogicException::class); <ide> $data = ['a' => ['one', 'two'], 'b' => ['three', 'four']]; <ide> $mapper = function ($row, $key, $mr): void { <ide> foreach ($row as $number) { <ide><path>tests/TestCase/Collection/Iterator/ReplaceIteratorTest.php <ide> */ <ide> namespace Cake\Test\TestCase\Collection\Iterator; <ide> <add>use ArrayIterator; <ide> use Cake\Collection\Iterator\ReplaceIterator; <ide> use Cake\TestSuite\TestCase; <ide> <ide> class ReplaceIteratorTest extends TestCase <ide> */ <ide> public function testReplace(): void <ide> { <del> $items = new \ArrayIterator([1, 2, 3]); <add> $items = new ArrayIterator([1, 2, 3]); <ide> $callable = function ($value, $key, $itemsArg) use ($items) { <ide> $this->assertSame($items, $itemsArg); <ide> $this->assertContains($value, $items); <ide><path>tests/TestCase/Collection/Iterator/SortIteratorTest.php <ide> use ArrayObject; <ide> use Cake\Collection\Iterator\SortIterator; <ide> use Cake\TestSuite\TestCase; <add>use DateInterval; <add>use DateTime; <add>use DateTimeImmutable; <add>use const SORT_ASC; <add>use const SORT_DESC; <add>use const SORT_NUMERIC; <ide> <ide> /** <ide> * SortIterator Test <ide> public function testSortComplexNumeric(): void <ide> $callback = function ($a) { <ide> return $a['foo']; <ide> }; <del> $sorted = new SortIterator($items, $callback, \SORT_DESC, \SORT_NUMERIC); <add> $sorted = new SortIterator($items, $callback, SORT_DESC, SORT_NUMERIC); <ide> $expected = [ <ide> ['foo' => 13, 'bar' => 'a'], <ide> ['foo' => 10, 'bar' => 'a'], <ide> public function testSortComplexNumeric(): void <ide> ]; <ide> $this->assertEquals($expected, $sorted->toList()); <ide> <del> $sorted = new SortIterator($items, $callback, \SORT_ASC, \SORT_NUMERIC); <add> $sorted = new SortIterator($items, $callback, SORT_ASC, SORT_NUMERIC); <ide> $expected = [ <ide> ['foo' => 1, 'bar' => 'a'], <ide> ['foo' => 2, 'bar' => 'a'], <ide> public function testSortComplexDeepPath(): void <ide> public function testSortDateTime(): void <ide> { <ide> $items = new ArrayObject([ <del> new \DateTime('2014-07-21'), <del> new \DateTime('2015-06-30'), <del> new \DateTimeImmutable('2013-08-12'), <add> new DateTime('2014-07-21'), <add> new DateTime('2015-06-30'), <add> new DateTimeImmutable('2013-08-12'), <ide> ]); <ide> <ide> $callback = function ($a) { <del> return $a->add(new \DateInterval('P1Y')); <add> return $a->add(new DateInterval('P1Y')); <ide> }; <ide> $sorted = new SortIterator($items, $callback); <ide> $expected = [ <del> new \DateTime('2016-06-30'), <del> new \DateTime('2015-07-21'), <del> new \DateTimeImmutable('2013-08-12'), <add> new DateTime('2016-06-30'), <add> new DateTime('2015-07-21'), <add> new DateTimeImmutable('2013-08-12'), <ide> <ide> ]; <ide> $this->assertEquals($expected, $sorted->toList()); <ide> <ide> $items = new ArrayObject([ <del> new \DateTime('2014-07-21'), <del> new \DateTime('2015-06-30'), <del> new \DateTimeImmutable('2013-08-12'), <add> new DateTime('2014-07-21'), <add> new DateTime('2015-06-30'), <add> new DateTimeImmutable('2013-08-12'), <ide> ]); <ide> <ide> $sorted = new SortIterator($items, $callback, SORT_ASC); <ide> $expected = [ <del> new \DateTimeImmutable('2013-08-12'), <del> new \DateTime('2015-07-21'), <del> new \DateTime('2016-06-30'), <add> new DateTimeImmutable('2013-08-12'), <add> new DateTime('2015-07-21'), <add> new DateTime('2016-06-30'), <ide> ]; <ide> $this->assertEquals($expected, $sorted->toList()); <ide> } <ide><path>tests/TestCase/Command/PluginAssetsCommandsTest.php <ide> use Cake\TestSuite\ConsoleIntegrationTestTrait; <ide> use Cake\TestSuite\Stub\ConsoleOutput; <ide> use Cake\TestSuite\TestCase; <add>use SplFileInfo; <ide> <ide> /** <ide> * PluginAssetsCommandsTest class <ide> public function testSymlinkingSpecifiedPlugin(): void <ide> $this->exec('plugin assets symlink TestPlugin'); <ide> <ide> $path = $this->wwwRoot . 'test_plugin'; <del> $link = new \SplFileInfo($path); <add> $link = new SplFileInfo($path); <ide> $this->assertFileExists($path . DS . 'root.js'); <ide> <ide> $path = $this->wwwRoot . 'company' . DS . 'test_plugin_three'; <ide> public function testCopyOverwrite(): void <ide> $pluginPath = TEST_APP . 'Plugin' . DS . 'TestPlugin' . DS . 'webroot'; <ide> <ide> $path = $this->wwwRoot . 'test_plugin'; <del> $dir = new \SplFileInfo($path); <add> $dir = new SplFileInfo($path); <ide> $this->assertTrue($dir->isDir()); <ide> $this->assertFileExists($path . DS . 'root.js'); <ide> <ide><path>tests/TestCase/Console/CommandCollectionTest.php <ide> public function testConstructor(): void <ide> */ <ide> public function testConstructorInvalidClass(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Cannot use \'stdClass\' for command \'nope\'. It is not a subclass of Cake\Console\Shell'); <ide> new CommandCollection([ <ide> 'sample' => SampleShell::class, <ide> public function testAddCommandInvalidName(string $name): void <ide> */ <ide> public function testInvalidShellClassName(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Cannot use \'stdClass\' for command \'routes\'. It is not a subclass of Cake\Console\Shell'); <ide> $collection = new CommandCollection(); <ide> $collection->add('routes', stdClass::class); <ide><path>tests/TestCase/Console/CommandRunnerTest.php <ide> use Cake\TestSuite\Stub\ConsoleOutput; <ide> use Cake\TestSuite\TestCase; <ide> use InvalidArgumentException; <add>use RuntimeException; <ide> use TestApp\Command\AbortCommand; <ide> use TestApp\Command\DemoCommand; <ide> use TestApp\Command\DependencyCommand; <ide> public function testSetEventManagerNonEventedApplication(): void <ide> */ <ide> public function testRunMissingRootCommand(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> $this->expectExceptionMessage('Cannot run any commands. No arguments received.'); <ide> $app = $this->getMockBuilder(BaseApplication::class) <ide> ->onlyMethods(['middleware', 'bootstrap', 'routes']) <ide><path>tests/TestCase/Console/HelperRegistryTest.php <ide> */ <ide> namespace Cake\Test\TestCase\Console; <ide> <add>use Cake\Console\Exception\MissingHelperException; <ide> use Cake\Console\HelperRegistry; <ide> use Cake\TestSuite\TestCase; <ide> use TestApp\Command\Helper\CommandHelper; <ide> public function testLoadWithConfig(): void <ide> */ <ide> public function testLoadMissingHelper(): void <ide> { <del> $this->expectException(\Cake\Console\Exception\MissingHelperException::class); <add> $this->expectException(MissingHelperException::class); <ide> $this->helpers->load('ThisTaskShouldAlwaysBeMissing'); <ide> } <ide> <ide><path>tests/TestCase/Controller/Component/PaginatorComponentTest.php <ide> use Cake\ORM\Entity; <ide> use Cake\ORM\Query; <ide> use Cake\TestSuite\TestCase; <add>use InvalidArgumentException; <ide> use stdClass; <ide> use TestApp\Datasource\CustomPaginator; <ide> <ide> public function testPaginatorSetting(): void <ide> */ <ide> public function testInvalidPaginatorOption(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Paginator must be an instance of Cake\Datasource\Paginator'); <ide> new PaginatorComponent($this->registry, [ <ide> 'paginator' => new stdClass(), <ide> public function testOutOfRangePageNumberStillProvidesPageCount(): void <ide> */ <ide> public function testOutOfVeryBigPageNumberGetsClamped(): void <ide> { <del> $this->expectException(\Cake\Http\Exception\NotFoundException::class); <add> $this->expectException(NotFoundException::class); <ide> $this->loadFixtures('Posts'); <ide> $this->controller->setRequest($this->controller->getRequest()->withQueryParams([ <ide> 'page' => '3000000000000000000000000', <ide><path>tests/TestCase/Controller/Component/RequestHandlerComponentTest.php <ide> use Cake\Controller\ComponentRegistry; <ide> use Cake\Controller\Controller; <ide> use Cake\Event\Event; <add>use Cake\Event\EventInterface; <ide> use Cake\Http\Exception\NotFoundException; <ide> use Cake\Http\Response; <ide> use Cake\Http\ServerRequest; <ide> public function testRespondAsWithAttachment(): void <ide> */ <ide> public function testRenderAsCalledTwice(): void <ide> { <del> $this->Controller->getEventManager()->on('Controller.beforeRender', function (\Cake\Event\EventInterface $e) { <add> $this->Controller->getEventManager()->on('Controller.beforeRender', function (EventInterface $e) { <ide> return $e->getSubject()->getResponse(); <ide> }); <ide> $this->Controller->render(); <ide><path>tests/TestCase/Controller/ComponentRegistryTest.php <ide> use Cake\Controller\Component\FlashComponent; <ide> use Cake\Controller\ComponentRegistry; <ide> use Cake\Controller\Controller; <add>use Cake\Controller\Exception\MissingComponentException; <ide> use Cake\Http\Response; <ide> use Cake\Http\ServerRequest; <ide> use Cake\TestSuite\TestCase; <ide> public function testLoadWithEnableFalse(): void <ide> */ <ide> public function testLoadMissingComponent(): void <ide> { <del> $this->expectException(\Cake\Controller\Exception\MissingComponentException::class); <add> $this->expectException(MissingComponentException::class); <ide> $this->Components->load('ThisComponentShouldAlwaysBeMissing'); <ide> } <ide> <ide> public function testUnset(): void <ide> */ <ide> public function testUnloadUnknown(): void <ide> { <del> $this->expectException(\Cake\Controller\Exception\MissingComponentException::class); <add> $this->expectException(MissingComponentException::class); <ide> $this->expectExceptionMessage('Component class FooComponent could not be found.'); <ide> $this->Components->unload('Foo'); <ide> } <ide><path>tests/TestCase/Controller/ComponentTest.php <ide> use Cake\Controller\Component\FlashComponent; <ide> use Cake\Controller\ComponentRegistry; <ide> use Cake\Controller\Controller; <add>use Cake\Controller\Exception\MissingComponentException; <ide> use Cake\Core\Exception\CakeException; <ide> use Cake\Event\EventManager; <ide> use Cake\TestSuite\TestCase; <add>use RuntimeException; <ide> use TestApp\Controller\Component\AppleComponent; <ide> use TestApp\Controller\Component\BananaComponent; <ide> use TestApp\Controller\Component\ConfiguredComponent; <ide> public function testMultipleComponentInitialize(): void <ide> */ <ide> public function testDuplicateComponentInitialize(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> $this->expectExceptionMessage('The "Banana" alias has already been loaded. The `property` key'); <ide> $Collection = new ComponentRegistry(); <ide> $Collection->load('Banana', ['property' => ['closure' => function (): void { <ide> public function testLazyLoading(): void <ide> */ <ide> public function testLazyLoadingDoesNotExists(): void <ide> { <del> $this->expectException(\Cake\Controller\Exception\MissingComponentException::class); <add> $this->expectException(MissingComponentException::class); <ide> $this->expectExceptionMessage('Component class YouHaveNoBananasComponent could not be found.'); <ide> $Component = new ConfiguredComponent(new ComponentRegistry(), [], ['YouHaveNoBananas']); <ide> $bananas = $Component->YouHaveNoBananas; <ide><path>tests/TestCase/Controller/ControllerTest.php <ide> namespace Cake\Test\TestCase\Controller; <ide> <ide> use Cake\Controller\Controller; <add>use Cake\Controller\Exception\MissingActionException; <ide> use Cake\Core\Configure; <ide> use Cake\Event\Event; <ide> use Cake\Event\EventInterface; <ide> use Cake\TestSuite\TestCase; <ide> use Laminas\Diactoros\Uri; <ide> use ReflectionFunction; <del>use TestApp\Controller\Admin\PostsController; <add>use RuntimeException; <add>use TestApp\Controller\Admin\PostsController as AdminPostsController; <ide> use TestApp\Controller\ArticlesController; <add>use TestApp\Controller\PagesController; <add>use TestApp\Controller\PostsController; <ide> use TestApp\Controller\TestController; <ide> use TestApp\Model\Table\ArticlesTable; <add>use TestPlugin\Controller\Admin\CommentsController; <ide> use TestPlugin\Controller\TestPluginController; <add>use UnexpectedValueException; <ide> <ide> /** <ide> * ControllerTest class <ide> public function testConstructSetModelClass(): void <ide> <ide> $request = new ServerRequest(); <ide> $response = new Response(); <del> $controller = new \TestApp\Controller\PostsController($request, $response); <add> $controller = new PostsController($request, $response); <ide> $this->assertInstanceOf('Cake\ORM\Table', $controller->loadModel()); <ide> $this->assertInstanceOf('Cake\ORM\Table', $controller->Posts); <ide> <del> $controller = new \TestApp\Controller\Admin\PostsController($request, $response); <add> $controller = new AdminPostsController($request, $response); <ide> $this->assertInstanceOf('Cake\ORM\Table', $controller->loadModel()); <ide> $this->assertInstanceOf('Cake\ORM\Table', $controller->Posts); <ide> <ide> $request = $request->withParam('plugin', 'TestPlugin'); <del> $controller = new \TestPlugin\Controller\Admin\CommentsController($request, $response); <add> $controller = new CommentsController($request, $response); <ide> $this->assertInstanceOf('TestPlugin\Model\Table\CommentsTable', $controller->loadModel()); <ide> $this->assertInstanceOf('TestPlugin\Model\Table\CommentsTable', $controller->Comments); <ide> } <ide> public function testPaginateUsesModelClass(): void <ide> */ <ide> public function testGetActionMissingAction(): void <ide> { <del> $this->expectException(\Cake\Controller\Exception\MissingActionException::class); <add> $this->expectException(MissingActionException::class); <ide> $this->expectExceptionMessage('Action TestController::missing() could not be found, or is not accessible.'); <ide> $url = new ServerRequest([ <ide> 'url' => 'test/missing', <ide> public function testGetActionMissingAction(): void <ide> */ <ide> public function testGetActionPrivate(): void <ide> { <del> $this->expectException(\Cake\Controller\Exception\MissingActionException::class); <add> $this->expectException(MissingActionException::class); <ide> $this->expectExceptionMessage('Action TestController::private_m() could not be found, or is not accessible.'); <ide> $url = new ServerRequest([ <ide> 'url' => 'test/private_m/', <ide> public function testGetActionPrivate(): void <ide> */ <ide> public function testGetActionProtected(): void <ide> { <del> $this->expectException(\Cake\Controller\Exception\MissingActionException::class); <add> $this->expectException(MissingActionException::class); <ide> $this->expectExceptionMessage('Action TestController::protected_m() could not be found, or is not accessible.'); <ide> $url = new ServerRequest([ <ide> 'url' => 'test/protected_m/', <ide> public function testGetActionProtected(): void <ide> */ <ide> public function testGetActionBaseMethods(): void <ide> { <del> $this->expectException(\Cake\Controller\Exception\MissingActionException::class); <add> $this->expectException(MissingActionException::class); <ide> $this->expectExceptionMessage('Action TestController::redirect() could not be found, or is not accessible.'); <ide> $url = new ServerRequest([ <ide> 'url' => 'test/redirect/', <ide> public function testGetActionBaseMethods(): void <ide> */ <ide> public function testGetActionMethodCasing(): void <ide> { <del> $this->expectException(\Cake\Controller\Exception\MissingActionException::class); <add> $this->expectException(MissingActionException::class); <ide> $this->expectExceptionMessage('Action TestController::RETURNER() could not be found, or is not accessible.'); <ide> $url = new ServerRequest([ <ide> 'url' => 'test/RETURNER/', <ide> public function testInvokeActionWithPassedParams(): void <ide> */ <ide> public function testInvokeActionException(): void <ide> { <del> $this->expectException(\UnexpectedValueException::class); <add> $this->expectException(UnexpectedValueException::class); <ide> $this->expectExceptionMessage( <ide> 'Controller actions can only return ResponseInterface instance or null. ' <ide> . 'Got string instead.' <ide> public function testViewPathConventions(): void <ide> 'params' => ['prefix' => 'Admin'], <ide> ]); <ide> $response = new Response(); <del> $Controller = new \TestApp\Controller\Admin\PostsController($request, $response); <add> $Controller = new AdminPostsController($request, $response); <ide> $Controller->getEventManager()->on('Controller.beforeRender', function (EventInterface $e) { <ide> return $e->getSubject()->getResponse(); <ide> }); <ide> public function testViewPathConventions(): void <ide> <ide> $request = $request->withParam('prefix', 'admin/super'); <ide> $response = new Response(); <del> $Controller = new \TestApp\Controller\Admin\PostsController($request, $response); <add> $Controller = new AdminPostsController($request, $response); <ide> $Controller->getEventManager()->on('Controller.beforeRender', function (EventInterface $e) { <ide> return $e->getSubject()->getResponse(); <ide> }); <ide> public function testViewPathConventions(): void <ide> 'prefix' => false, <ide> ], <ide> ]); <del> $Controller = new \TestApp\Controller\PagesController($request, $response); <add> $Controller = new PagesController($request, $response); <ide> $Controller->getEventManager()->on('Controller.beforeRender', function (EventInterface $e) { <ide> return $e->getSubject()->getResponse(); <ide> }); <ide> public function testLoadComponentDuplicate(): void <ide> try { <ide> $controller->loadComponent('Paginator', ['bad' => 'settings']); <ide> $this->fail('No exception'); <del> } catch (\RuntimeException $e) { <add> } catch (RuntimeException $e) { <ide> $this->assertStringContainsString('The "Paginator" alias has already been loaded', $e->getMessage()); <ide> } <ide> } <ide> public function testIsAction(): void <ide> */ <ide> public function testBeforeRenderViewVariables(): void <ide> { <del> $controller = new PostsController(); <add> $controller = new AdminPostsController(); <ide> <ide> $controller->getEventManager()->on('Controller.beforeRender', function (EventInterface $event): void { <ide> /** @var \Cake\Controller\Controller $controller */ <ide> public function testBeforeRenderTemplateAndLayout(): void <ide> */ <ide> public function testName(): void <ide> { <del> $controller = new PostsController(); <add> $controller = new AdminPostsController(); <ide> $this->assertSame('Posts', $controller->getName()); <ide> <ide> $this->assertSame($controller, $controller->setName('Articles')); <ide> public function testName(): void <ide> */ <ide> public function testPlugin(): void <ide> { <del> $controller = new PostsController(); <add> $controller = new AdminPostsController(); <ide> $this->assertNull($controller->getPlugin()); <ide> <ide> $this->assertSame($controller, $controller->setPlugin('Articles')); <ide> public function testPlugin(): void <ide> */ <ide> public function testRequest(): void <ide> { <del> $controller = new PostsController(); <add> $controller = new AdminPostsController(); <ide> $this->assertInstanceOf(ServerRequest::class, $controller->getRequest()); <ide> <ide> $request = new ServerRequest([ <ide> public function testRequest(): void <ide> */ <ide> public function testResponse(): void <ide> { <del> $controller = new PostsController(); <add> $controller = new AdminPostsController(); <ide> $this->assertInstanceOf(Response::class, $controller->getResponse()); <ide> <ide> $response = new Response(); <ide> public function testResponse(): void <ide> */ <ide> public function testAutoRender(): void <ide> { <del> $controller = new PostsController(); <add> $controller = new AdminPostsController(); <ide> $this->assertTrue($controller->isAutoRenderEnabled()); <ide> <ide> $this->assertSame($controller, $controller->disableAutoRender()); <ide><path>tests/TestCase/Core/Configure/Engine/IniConfigTest.php <ide> namespace Cake\Test\TestCase\Core\Configure\Engine; <ide> <ide> use Cake\Core\Configure\Engine\IniConfig; <add>use Cake\Core\Exception\CakeException; <ide> use Cake\TestSuite\TestCase; <ide> <ide> /** <ide> public function testBooleanReading(): void <ide> */ <ide> public function testReadWithExistentFileWithoutExtension(): void <ide> { <del> $this->expectException(\Cake\Core\Exception\CakeException::class); <add> $this->expectException(CakeException::class); <ide> $engine = new IniConfig($this->path); <ide> $engine->read('no_ini_extension'); <ide> } <ide> public function testReadWithExistentFileWithoutExtension(): void <ide> */ <ide> public function testReadWithNonExistentFile(): void <ide> { <del> $this->expectException(\Cake\Core\Exception\CakeException::class); <add> $this->expectException(CakeException::class); <ide> $engine = new IniConfig($this->path); <ide> $engine->read('fake_values'); <ide> } <ide> public function testReadEmptyFile(): void <ide> */ <ide> public function testReadWithDots(): void <ide> { <del> $this->expectException(\Cake\Core\Exception\CakeException::class); <add> $this->expectException(CakeException::class); <ide> $engine = new IniConfig($this->path); <ide> $engine->read('../empty'); <ide> } <ide><path>tests/TestCase/Core/Configure/Engine/JsonConfigTest.php <ide> namespace Cake\Test\TestCase\Core\Configure\Engine; <ide> <ide> use Cake\Core\Configure\Engine\JsonConfig; <add>use Cake\Core\Exception\CakeException; <ide> use Cake\TestSuite\TestCase; <ide> <ide> /** <ide> public function testRead(): void <ide> */ <ide> public function testReadWithExistentFileWithoutExtension(): void <ide> { <del> $this->expectException(\Cake\Core\Exception\CakeException::class); <add> $this->expectException(CakeException::class); <ide> $engine = new JsonConfig($this->path); <ide> $engine->read('no_json_extension'); <ide> } <ide> public function testReadWithExistentFileWithoutExtension(): void <ide> */ <ide> public function testReadWithNonExistentFile(): void <ide> { <del> $this->expectException(\Cake\Core\Exception\CakeException::class); <add> $this->expectException(CakeException::class); <ide> $engine = new JsonConfig($this->path); <ide> $engine->read('fake_values'); <ide> } <ide> public function testReadWithNonExistentFile(): void <ide> */ <ide> public function testReadEmptyFile(): void <ide> { <del> $this->expectException(\Cake\Core\Exception\CakeException::class); <add> $this->expectException(CakeException::class); <ide> $this->expectExceptionMessage('config file "empty.json"'); <ide> $engine = new JsonConfig($this->path); <ide> $config = $engine->read('empty'); <ide> public function testReadEmptyFile(): void <ide> */ <ide> public function testReadWithInvalidJson(): void <ide> { <del> $this->expectException(\Cake\Core\Exception\CakeException::class); <add> $this->expectException(CakeException::class); <ide> $this->expectExceptionMessage('Error parsing JSON string fetched from config file "invalid.json"'); <ide> $engine = new JsonConfig($this->path); <ide> $engine->read('invalid'); <ide> public function testReadWithInvalidJson(): void <ide> */ <ide> public function testReadWithDots(): void <ide> { <del> $this->expectException(\Cake\Core\Exception\CakeException::class); <add> $this->expectException(CakeException::class); <ide> $engine = new JsonConfig($this->path); <ide> $engine->read('../empty'); <ide> } <ide><path>tests/TestCase/Core/Configure/Engine/PhpConfigTest.php <ide> namespace Cake\Test\TestCase\Core\Configure\Engine; <ide> <ide> use Cake\Core\Configure\Engine\PhpConfig; <add>use Cake\Core\Exception\CakeException; <ide> use Cake\TestSuite\TestCase; <ide> <ide> /** <ide> public function testRead(): void <ide> */ <ide> public function testReadWithExistentFileWithoutExtension(): void <ide> { <del> $this->expectException(\Cake\Core\Exception\CakeException::class); <add> $this->expectException(CakeException::class); <ide> $engine = new PhpConfig($this->path); <ide> $engine->read('no_php_extension'); <ide> } <ide> public function testReadWithExistentFileWithoutExtension(): void <ide> */ <ide> public function testReadWithNonExistentFile(): void <ide> { <del> $this->expectException(\Cake\Core\Exception\CakeException::class); <add> $this->expectException(CakeException::class); <ide> $engine = new PhpConfig($this->path); <ide> $engine->read('fake_values'); <ide> } <ide> public function testReadWithNonExistentFile(): void <ide> */ <ide> public function testReadEmptyFile(): void <ide> { <del> $this->expectException(\Cake\Core\Exception\CakeException::class); <add> $this->expectException(CakeException::class); <ide> $engine = new PhpConfig($this->path); <ide> $engine->read('empty'); <ide> } <ide> public function testReadEmptyFile(): void <ide> */ <ide> public function testReadWithDots(): void <ide> { <del> $this->expectException(\Cake\Core\Exception\CakeException::class); <add> $this->expectException(CakeException::class); <ide> $engine = new PhpConfig($this->path); <ide> $engine->read('../empty'); <ide> } <ide><path>tests/TestCase/Core/ConfigureTest.php <ide> use Cake\Cache\Cache; <ide> use Cake\Core\Configure; <ide> use Cake\Core\Configure\Engine\PhpConfig; <add>use Cake\Core\Exception\CakeException; <ide> use Cake\TestSuite\TestCase; <add>use Exception; <add>use RuntimeException; <ide> <ide> /** <ide> * ConfigureTest <ide> public function testReadOrFail(): void <ide> */ <ide> public function testReadOrFailThrowingException(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> $this->expectExceptionMessage('Expected configuration key "This.Key.Does.Not.exist" not found'); <ide> Configure::readOrFail('This.Key.Does.Not.exist'); <ide> } <ide> public function testCheckEmpty(): void <ide> */ <ide> public function testLoadExceptionOnNonExistentFile(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> Configure::config('test', new PhpConfig()); <ide> Configure::load('nonexistent_configuration_file', 'test'); <ide> } <ide> public function testLoadExceptionOnNonExistentFile(): void <ide> */ <ide> public function testLoadExceptionOnNonExistentEngine(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> Configure::load('nonexistent_configuration_file', 'nonexistent_configuration_engine'); <ide> } <ide> <ide> public function testLoadDefaultConfig(): void <ide> { <ide> try { <ide> Configure::load('nonexistent_configuration_file'); <del> } catch (\Exception $e) { <add> } catch (Exception $e) { <ide> $this->assertTrue(Configure::isConfigured('default')); <ide> $this->assertFalse(Configure::isConfigured('nonexistent_configuration_file')); <ide> } <ide> public function testClear(): void <ide> <ide> public function testDumpNoAdapter(): void <ide> { <del> $this->expectException(\Cake\Core\Exception\CakeException::class); <add> $this->expectException(CakeException::class); <ide> Configure::dump(TMP . 'test.php', 'does_not_exist'); <ide> } <ide> <ide> public function testConsumeOrFail(): void <ide> */ <ide> public function testConsumeOrFailThrowingException(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> $this->expectExceptionMessage('Expected configuration key "This.Key.Does.Not.exist" not found'); <ide> Configure::consumeOrFail('This.Key.Does.Not.exist'); <ide> } <ide><path>tests/TestCase/Core/FunctionsTest.php <ide> use Cake\Core\Configure; <ide> use Cake\Http\Response; <ide> use Cake\TestSuite\TestCase; <add>use stdClass; <ide> <ide> /** <ide> * Test cases for functions in Core\functions.php <ide> public function hInputProvider(): array <ide> [null, null], <ide> [1, 1], <ide> [1.1, 1.1], <del> [new \stdClass(), '(object)stdClass'], <add> [new stdClass(), '(object)stdClass'], <ide> [new Response(), ''], <ide> [['clean', '"clean-me'], ['clean', '&quot;clean-me']], <ide> ]; <ide><path>tests/TestCase/Core/InstanceConfigTraitTest.php <ide> namespace Cake\Test\TestCase\Core; <ide> <ide> use Cake\TestSuite\TestCase; <add>use Exception; <ide> use InvalidArgumentException; <ide> use RuntimeException; <ide> use TestApp\Config\ReadOnlyTestInstanceConfig; <ide> public function testSetMergeNoClobber(): void <ide> */ <ide> public function testReadOnlyConfig(): void <ide> { <del> $this->expectException(\Exception::class); <add> $this->expectException(Exception::class); <ide> $this->expectExceptionMessage('This Instance is readonly'); <ide> $object = new ReadOnlyTestInstanceConfig(); <ide> <ide> public function testDeleteArray(): void <ide> */ <ide> public function testDeleteClobber(): void <ide> { <del> $this->expectException(\Exception::class); <add> $this->expectException(Exception::class); <ide> $this->expectExceptionMessage('Cannot unset a.nested.value.whoops'); <ide> $this->object->setConfig('a.nested.value.whoops', null); <ide> } <ide><path>tests/TestCase/Core/PluginCollectionTest.php <ide> use Cake\TestSuite\TestCase; <ide> use Company\TestPluginThree\Plugin as TestPluginThree; <ide> use InvalidArgumentException; <add>use ParentPlugin\Plugin; <ide> use TestPlugin\Plugin as TestPlugin; <ide> <ide> /** <ide> public function testGetAutoload(): void <ide> { <ide> $plugins = new PluginCollection(); <ide> $plugin = $plugins->get('ParentPlugin'); <del> $this->assertInstanceOf(\ParentPlugin\Plugin::class, $plugin); <add> $this->assertInstanceOf(Plugin::class, $plugin); <ide> } <ide> <ide> public function testGetInvalid(): void <ide> public function testCreate(): void <ide> $plugins = new PluginCollection(); <ide> <ide> $plugin = $plugins->create('ParentPlugin'); <del> $this->assertInstanceOf(\ParentPlugin\Plugin::class, $plugin); <add> $this->assertInstanceOf(Plugin::class, $plugin); <ide> <ide> $plugin = $plugins->create('ParentPlugin', ['name' => 'Granpa']); <del> $this->assertInstanceOf(\ParentPlugin\Plugin::class, $plugin); <add> $this->assertInstanceOf(Plugin::class, $plugin); <ide> $this->assertSame('Granpa', $plugin->getName()); <ide> <del> $plugin = $plugins->create(\ParentPlugin\Plugin::class); <del> $this->assertInstanceOf(\ParentPlugin\Plugin::class, $plugin); <add> $plugin = $plugins->create(Plugin::class); <add> $this->assertInstanceOf(Plugin::class, $plugin); <ide> <ide> $plugin = $plugins->create('TestTheme'); <ide> $this->assertInstanceOf(BasePlugin::class, $plugin); <ide><path>tests/TestCase/Core/Retry/CommandRetryTest.php <ide> use Cake\Core\Retry\CommandRetry; <ide> use Cake\TestSuite\TestCase; <ide> use Exception; <add>use TestApp\Database\Retry\TestRetryStrategy; <ide> <ide> /** <ide> * Tests for the CommandRetry class <ide> public function testRetry(): void <ide> return $count; <ide> }; <ide> <del> $strategy = new \TestApp\Database\Retry\TestRetryStrategy(true); <add> $strategy = new TestRetryStrategy(true); <ide> $retry = new CommandRetry($strategy, 2); <ide> $this->assertSame(2, $retry->run($action)); <ide> } <ide> public function testExceedAttempts(): void <ide> return $count; <ide> }; <ide> <del> $strategy = new \TestApp\Database\Retry\TestRetryStrategy(true); <add> $strategy = new TestRetryStrategy(true); <ide> $retry = new CommandRetry($strategy, 1); <ide> $this->expectException(Exception::class); <ide> $this->expectExceptionMessage('this is failing'); <ide> public function testRespectStrategy(): void <ide> throw new Exception('this is failing'); <ide> }; <ide> <del> $strategy = new \TestApp\Database\Retry\TestRetryStrategy(false); <add> $strategy = new TestRetryStrategy(false); <ide> $retry = new CommandRetry($strategy, 2); <ide> $this->expectException(Exception::class); <ide> $this->expectExceptionMessage('this is failing'); <ide><path>tests/TestCase/Database/ConnectionTest.php <ide> use Cake\Database\Connection; <ide> use Cake\Database\Driver; <ide> use Cake\Database\Driver\Mysql; <add>use Cake\Database\Driver\Sqlite; <add>use Cake\Database\Driver\Sqlserver; <ide> use Cake\Database\Exception\MissingConnectionException; <add>use Cake\Database\Exception\MissingDriverException; <add>use Cake\Database\Exception\MissingExtensionException; <ide> use Cake\Database\Exception\NestedTransactionRollbackException; <ide> use Cake\Database\Log\LoggingStatement; <ide> use Cake\Database\Log\QueryLogger; <ide> use Cake\Datasource\ConnectionManager; <ide> use Cake\Log\Log; <ide> use Cake\TestSuite\TestCase; <add>use DateTime; <ide> use Exception; <add>use InvalidArgumentException; <add>use PDO; <ide> use ReflectionMethod; <ide> use ReflectionProperty; <ide> <ide> public function testConnect(): void <ide> */ <ide> public function testNoDriver(): void <ide> { <del> $this->expectException(\Cake\Database\Exception\MissingDriverException::class); <add> $this->expectException(MissingDriverException::class); <ide> $this->expectExceptionMessage('Database driver could not be found.'); <ide> $connection = new Connection([]); <ide> } <ide> public function testNoDriver(): void <ide> */ <ide> public function testEmptyDriver(): void <ide> { <del> $this->expectException(\Cake\Database\Exception\MissingDriverException::class); <add> $this->expectException(MissingDriverException::class); <ide> $this->expectExceptionMessage('Database driver could not be found.'); <ide> $connection = new Connection(['driver' => false]); <ide> } <ide> public function testEmptyDriver(): void <ide> */ <ide> public function testMissingDriver(): void <ide> { <del> $this->expectException(\Cake\Database\Exception\MissingDriverException::class); <add> $this->expectException(MissingDriverException::class); <ide> $this->expectExceptionMessage('Database driver \Foo\InvalidDriver could not be found.'); <ide> $connection = new Connection(['driver' => '\Foo\InvalidDriver']); <ide> } <ide> public function testMissingDriver(): void <ide> */ <ide> public function testDisabledDriver(): void <ide> { <del> $this->expectException(\Cake\Database\Exception\MissingExtensionException::class); <add> $this->expectException(MissingExtensionException::class); <ide> $this->expectExceptionMessage('Database driver DriverMock cannot be used due to a missing PHP extension or unmet dependency'); <ide> $mock = $this->getMockBuilder(Mysql::class) <ide> ->onlyMethods(['enabled']) <ide> public function testWrongCredentials(): void <ide> <ide> public function testConnectRetry(): void <ide> { <del> $this->skipIf(!ConnectionManager::get('test')->getDriver() instanceof \Cake\Database\Driver\Sqlserver); <add> $this->skipIf(!ConnectionManager::get('test')->getDriver() instanceof Sqlserver); <ide> <ide> $connection = new Connection(['driver' => 'RetryDriver']); <ide> $this->assertInstanceOf('TestApp\Database\Driver\RetryDriver', $connection->getDriver()); <ide> public function testExecuteWithArguments(): void <ide> public function testExecuteWithArgumentsAndTypes(): void <ide> { <ide> $sql = "SELECT '2012-01-01' = ?"; <del> $statement = $this->connection->execute($sql, [new \DateTime('2012-01-01')], ['date']); <add> $statement = $this->connection->execute($sql, [new DateTime('2012-01-01')], ['date']); <ide> $result = $statement->fetch(); <ide> $statement->closeCursor(); <ide> $this->assertTrue((bool)$result[0]); <ide> public function testExecuteWithArgumentsAndTypes(): void <ide> public function testBufferedStatementCollectionWrappingStatement(): void <ide> { <ide> $this->skipIf( <del> !($this->connection->getDriver() instanceof \Cake\Database\Driver\Sqlite), <add> !($this->connection->getDriver() instanceof Sqlite), <ide> 'Only required for SQLite driver which does not support buffered results natively' <ide> ); <ide> <ide> public function testBufferedStatementCollectionWrappingStatement(): void <ide> */ <ide> public function testExecuteWithMissingType(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $sql = 'SELECT ?'; <del> $statement = $this->connection->execute($sql, [new \DateTime('2012-01-01')], ['bar']); <add> $statement = $this->connection->execute($sql, [new DateTime('2012-01-01')], ['bar']); <ide> } <ide> <ide> /** <ide> public function testStatementReusing(): void <ide> public function testStatementFetchObject(): void <ide> { <ide> $statement = $this->connection->execute('SELECT title, body FROM things'); <del> $row = $statement->fetch(\PDO::FETCH_OBJ); <add> $row = $statement->fetch(PDO::FETCH_OBJ); <ide> $this->assertSame('a title', $row->title); <ide> $this->assertSame('a body', $row->body); <ide> $statement->closeCursor(); <ide> public function testUpdateWithConditionsCombinedNoTypes(): void <ide> public function testUpdateWithTypes(): void <ide> { <ide> $title = 'changed the title!'; <del> $body = new \DateTime('2012-01-01'); <add> $body = new DateTime('2012-01-01'); <ide> $values = compact('title', 'body'); <ide> $this->connection->update('things', $values, [], ['body' => 'date']); <ide> $result = $this->connection->execute('SELECT * FROM things WHERE title = :title AND body = :body', $values, ['body' => 'date']); <ide> public function testUpdateWithTypes(): void <ide> public function testUpdateWithConditionsAndTypes(): void <ide> { <ide> $title = 'changed the title!'; <del> $body = new \DateTime('2012-01-01'); <add> $body = new DateTime('2012-01-01'); <ide> $values = compact('title', 'body'); <ide> $this->connection->update('things', $values, ['id' => '1'], ['body' => 'date', 'id' => 'integer']); <ide> $result = $this->connection->execute('SELECT * FROM things WHERE title = :title AND body = :body', $values, ['body' => 'date']); <ide> public function testInTransaction(): void <ide> public function testInTransactionWithSavePoints(): void <ide> { <ide> $this->skipIf( <del> $this->connection->getDriver() instanceof \Cake\Database\Driver\Sqlserver, <add> $this->connection->getDriver() instanceof Sqlserver, <ide> 'SQLServer fails when this test is included.' <ide> ); <ide> $this->skipIf(!$this->connection->enableSavePoints(true)); <ide> public function testQuote(): void <ide> { <ide> $this->skipIf(!$this->connection->supportsQuoting()); <ide> $expected = "'2012-01-01'"; <del> $result = $this->connection->quote(new \DateTime('2012-01-01'), 'date'); <add> $result = $this->connection->quote(new DateTime('2012-01-01'), 'date'); <ide> $this->assertEquals($expected, $result); <ide> <ide> $expected = "'1'"; <ide> public function testTransactionalFail(): void <ide> */ <ide> public function testTransactionalWithException(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $driver = $this->getMockFormDriver(); <ide> $connection = $this->getMockBuilder(Connection::class) <ide> ->onlyMethods(['connect', 'commit', 'begin', 'rollback']) <ide> public function testTransactionalWithException(): void <ide> $connection->expects($this->never())->method('commit'); <ide> $connection->transactional(function ($conn) use ($connection): void { <ide> $this->assertSame($connection, $conn); <del> throw new \InvalidArgumentException(); <add> throw new InvalidArgumentException(); <ide> }); <ide> } <ide> <ide><path>tests/TestCase/Database/Driver/SqlserverTest.php <ide> public function testConnectionPersistentFalse(): void <ide> */ <ide> public function testConnectionPersistentTrueException(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Config setting "persistent" cannot be set to true, as the Sqlserver PDO driver does not support PDO::ATTR_PERSISTENT'); <ide> $this->skipIf($this->missingExtension, 'pdo_sqlsrv is not installed.'); <ide> $config = [ <ide><path>tests/TestCase/Database/DriverTest.php <ide> use Cake\Database\Schema\TableSchema; <ide> use Cake\Database\ValueBinder; <ide> use Cake\TestSuite\TestCase; <add>use Exception; <ide> use PDO; <ide> use PDOStatement; <ide> <ide> public function testConstructorException(): void <ide> $arg = ['login' => 'Bear']; <ide> try { <ide> $this->getMockForAbstractClass(Driver::class, [$arg]); <del> } catch (\Exception $e) { <add> } catch (Exception $e) { <ide> $this->assertStringContainsString( <ide> 'Please pass "username" instead of "login" for connecting to the database', <ide> $e->getMessage() <ide><path>tests/TestCase/Database/Log/LoggedQueryTest.php <ide> use Cake\Datasource\ConnectionManager; <ide> use Cake\TestSuite\TestCase; <ide> use Cake\Utility\Text; <add>use Exception; <ide> <ide> /** <ide> * Tests LoggedQuery class <ide> public function testJsonSerialize(): void <ide> $query->query = 'SELECT a FROM b where a = :p1'; <ide> $query->params = ['p1' => '$2y$10$dUAIj']; <ide> $query->numRows = 4; <del> $query->error = new \Exception('You fail!'); <add> $query->error = new Exception('You fail!'); <ide> <ide> $expected = json_encode([ <ide> 'query' => $query->query, <ide><path>tests/TestCase/Database/Log/LoggingStatementTest.php <ide> use Cake\Database\StatementInterface; <ide> use Cake\Log\Log; <ide> use Cake\TestSuite\TestCase; <add>use DateTime; <ide> use LogicException; <ide> <ide> /** <ide> public function testExecuteWithBinding(): void <ide> $inner->method('rowCount')->will($this->returnValue(4)); <ide> $inner->method('execute')->will($this->returnValue(true)); <ide> <del> $date = new \DateTime('2013-01-01'); <add> $date = new DateTime('2013-01-01'); <ide> $inner->expects($this->atLeast(2)) <ide> ->method('bindValue') <ide> ->withConsecutive(['a', 1], ['b', $date]); <ide> public function testExecuteWithBinding(): void <ide> $st->execute(); <ide> $st->fetchAll(); <ide> <del> $st->bindValue('b', new \DateTime('2014-01-01'), 'date'); <add> $st->bindValue('b', new DateTime('2014-01-01'), 'date'); <ide> $st->execute(); <ide> $st->fetchAll(); <ide> <ide><path>tests/TestCase/Database/QueryTest.php <ide> use Cake\Database\ValueBinder; <ide> use Cake\Datasource\ConnectionManager; <ide> use Cake\TestSuite\TestCase; <add>use DateTime; <ide> use DateTimeImmutable; <ide> use InvalidArgumentException; <ide> use ReflectionProperty; <ide> public function testSelectWithJoinsConditions(): void <ide> $result->closeCursor(); <ide> <ide> $query = new Query($this->connection); <del> $time = new \DateTime('2007-03-18 10:45:23'); <add> $time = new DateTime('2007-03-18 10:45:23'); <ide> $types = ['created' => 'datetime']; <ide> $result = $query <ide> ->select(['title', 'comment' => 'c.comment']) <ide> public function testSelectAliasedJoins(): void <ide> $result->closeCursor(); <ide> <ide> $query = new Query($this->connection); <del> $time = new \DateTime('2007-03-18 10:45:23'); <add> $time = new DateTime('2007-03-18 10:45:23'); <ide> $types = ['created' => 'datetime']; <ide> $result = $query <ide> ->select(['title', 'name' => 'c.comment']) <ide> public function testSelectLeftJoin(): void <ide> { <ide> $this->loadFixtures('Articles', 'Comments'); <ide> $query = new Query($this->connection); <del> $time = new \DateTime('2007-03-18 10:45:23'); <add> $time = new DateTime('2007-03-18 10:45:23'); <ide> $types = ['created' => 'datetime']; <ide> $result = $query <ide> ->select(['title', 'name' => 'c.comment']) <ide> public function testSelectInnerJoin(): void <ide> { <ide> $this->loadFixtures('Articles', 'Comments'); <ide> $query = new Query($this->connection); <del> $time = new \DateTime('2007-03-18 10:45:23'); <add> $time = new DateTime('2007-03-18 10:45:23'); <ide> $types = ['created' => 'datetime']; <ide> $statement = $query <ide> ->select(['title', 'name' => 'c.comment']) <ide> public function testSelectRightJoin(): void <ide> { <ide> $this->loadFixtures('Articles', 'Comments'); <ide> $this->skipIf( <del> $this->connection->getDriver() instanceof \Cake\Database\Driver\Sqlite, <add> $this->connection->getDriver() instanceof Sqlite, <ide> 'SQLite does not support RIGHT joins' <ide> ); <ide> $query = new Query($this->connection); <del> $time = new \DateTime('2007-03-18 10:45:23'); <add> $time = new DateTime('2007-03-18 10:45:23'); <ide> $types = ['created' => 'datetime']; <ide> $result = $query <ide> ->select(['title', 'name' => 'c.comment']) <ide> public function testSelectJoinWithCallback(): void <ide> ->from('articles') <ide> ->innerJoin(['c' => 'comments'], function ($exp, $q) use ($query, $types) { <ide> $this->assertSame($q, $query); <del> $exp->add(['created <' => new \DateTime('2007-03-18 10:45:23')], $types); <add> $exp->add(['created <' => new DateTime('2007-03-18 10:45:23')], $types); <ide> <ide> return $exp; <ide> }) <ide> public function testSelectJoinWithCallback2(): void <ide> ->from('authors') <ide> ->innerJoin('comments', function ($exp, $q) use ($query, $types) { <ide> $this->assertSame($q, $query); <del> $exp->add(['created' => new \DateTime('2007-03-18 10:47:23')], $types); <add> $exp->add(['created' => new DateTime('2007-03-18 10:47:23')], $types); <ide> <ide> return $exp; <ide> }) <ide> public function testSelectWhereTypes(): void <ide> $result = $query <ide> ->select(['id']) <ide> ->from('comments') <del> ->where(['created' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime']) <add> ->where(['created' => new DateTime('2007-03-18 10:45:23')], ['created' => 'datetime']) <ide> ->execute(); <ide> $this->assertCount(1, $result); <ide> $this->assertEquals(['id' => 1], $result->fetch('assoc')); <ide> public function testSelectWhereTypes(): void <ide> $result = $query <ide> ->select(['id']) <ide> ->from('comments') <del> ->where(['created >' => new \DateTime('2007-03-18 10:46:00')], ['created' => 'datetime']) <add> ->where(['created >' => new DateTime('2007-03-18 10:46:00')], ['created' => 'datetime']) <ide> ->execute(); <ide> $this->assertCount(5, $result); <ide> $this->assertEquals(['id' => 2], $result->fetch('assoc')); <ide> public function testSelectWhereTypes(): void <ide> ->from('comments') <ide> ->where( <ide> [ <del> 'created >' => new \DateTime('2007-03-18 10:40:00'), <del> 'created <' => new \DateTime('2007-03-18 10:46:00'), <add> 'created >' => new DateTime('2007-03-18 10:40:00'), <add> 'created <' => new DateTime('2007-03-18 10:46:00'), <ide> ], <ide> ['created' => 'datetime'] <ide> ) <ide> public function testSelectWhereTypes(): void <ide> ->where( <ide> [ <ide> 'id' => '3', <del> 'created <' => new \DateTime('2013-01-01 12:00'), <add> 'created <' => new DateTime('2013-01-01 12:00'), <ide> ], <ide> ['created' => 'datetime', 'id' => 'integer'] <ide> ) <ide> public function testSelectWhereTypes(): void <ide> ->where( <ide> [ <ide> 'id' => '1', <del> 'created <' => new \DateTime('2013-01-01 12:00'), <add> 'created <' => new DateTime('2013-01-01 12:00'), <ide> ], <ide> ['created' => 'datetime', 'id' => 'integer'] <ide> ) <ide> public function testSelectAndWhere(): void <ide> $result = $query <ide> ->select(['id']) <ide> ->from('comments') <del> ->where(['created' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime']) <add> ->where(['created' => new DateTime('2007-03-18 10:45:23')], ['created' => 'datetime']) <ide> ->andWhere(['id' => 1]) <ide> ->execute(); <ide> $this->assertCount(1, $result); <ide> public function testSelectAndWhere(): void <ide> $result = $query <ide> ->select(['id']) <ide> ->from('comments') <del> ->where(['created' => new \DateTime('2007-03-18 10:50:55')], ['created' => 'datetime']) <add> ->where(['created' => new DateTime('2007-03-18 10:50:55')], ['created' => 'datetime']) <ide> ->andWhere(['id' => 2]) <ide> ->execute(); <ide> $this->assertCount(0, $result); <ide> public function testSelectAndWhereNoPreviousCondition(): void <ide> $result = $query <ide> ->select(['id']) <ide> ->from('comments') <del> ->andWhere(['created' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime']) <add> ->andWhere(['created' => new DateTime('2007-03-18 10:45:23')], ['created' => 'datetime']) <ide> ->andWhere(['id' => 1]) <ide> ->execute(); <ide> $this->assertCount(1, $result); <ide> public function testSelectWhereUsingClosure(): void <ide> ->where(function ($exp) { <ide> return $exp <ide> ->eq('id', 1) <del> ->eq('created', new \DateTime('2007-03-18 10:45:23'), 'datetime'); <add> ->eq('created', new DateTime('2007-03-18 10:45:23'), 'datetime'); <ide> }) <ide> ->execute(); <ide> $this->assertCount(1, $result); <ide> public function testSelectWhereUsingClosure(): void <ide> ->where(function ($exp) { <ide> return $exp <ide> ->eq('id', 1) <del> ->eq('created', new \DateTime('2021-12-30 15:00'), 'datetime'); <add> ->eq('created', new DateTime('2021-12-30 15:00'), 'datetime'); <ide> }) <ide> ->execute(); <ide> $this->assertCount(0, $result); <ide> public function testSelectAndWhereUsingClosure(): void <ide> ->from('comments') <ide> ->where(['id' => '1']) <ide> ->andWhere(function ($exp) { <del> return $exp->eq('created', new \DateTime('2007-03-18 10:45:23'), 'datetime'); <add> return $exp->eq('created', new DateTime('2007-03-18 10:45:23'), 'datetime'); <ide> }) <ide> ->execute(); <ide> $this->assertCount(1, $result); <ide> public function testSelectAndWhereUsingClosure(): void <ide> ->from('comments') <ide> ->where(['id' => '1']) <ide> ->andWhere(function ($exp) { <del> return $exp->eq('created', new \DateTime('2022-12-21 12:00'), 'datetime'); <add> return $exp->eq('created', new DateTime('2022-12-21 12:00'), 'datetime'); <ide> }) <ide> ->execute(); <ide> $this->assertCount(0, $result); <ide> public function testSelectWhereOperatorMethods(): void <ide> ->where(function ($exp) { <ide> return $exp->in( <ide> 'created', <del> [new \DateTime('2007-03-18 10:45:23'), new \DateTime('2007-03-18 10:47:23')], <add> [new DateTime('2007-03-18 10:45:23'), new DateTime('2007-03-18 10:47:23')], <ide> 'datetime' <ide> ); <ide> }) <ide> public function testSelectWhereOperatorMethods(): void <ide> ->where(function ($exp) { <ide> return $exp->notIn( <ide> 'created', <del> [new \DateTime('2007-03-18 10:45:23'), new \DateTime('2007-03-18 10:47:23')], <add> [new DateTime('2007-03-18 10:45:23'), new DateTime('2007-03-18 10:47:23')], <ide> 'datetime' <ide> ); <ide> }) <ide> public function testWhereWithBetweenComplex(): void <ide> ->select(['id']) <ide> ->from('comments') <ide> ->where(function ($exp) { <del> $from = new \DateTime('2007-03-18 10:51:00'); <del> $to = new \DateTime('2007-03-18 10:54:00'); <add> $from = new DateTime('2007-03-18 10:51:00'); <add> $to = new DateTime('2007-03-18 10:54:00'); <ide> <ide> return $exp->between('created', $from, $to, 'datetime'); <ide> }) <ide> public function testSelectWhereNot(): void <ide> ->from('comments') <ide> ->where(function ($exp) { <ide> return $exp->not( <del> $exp->and(['id' => 2, 'created' => new \DateTime('2007-03-18 10:47:23')], ['created' => 'datetime']) <add> $exp->and(['id' => 2, 'created' => new DateTime('2007-03-18 10:47:23')], ['created' => 'datetime']) <ide> ); <ide> }) <ide> ->execute(); <ide> public function testSelectWhereNot(): void <ide> ->from('comments') <ide> ->where(function ($exp) { <ide> return $exp->not( <del> $exp->and(['id' => 2, 'created' => new \DateTime('2012-12-21 12:00')], ['created' => 'datetime']) <add> $exp->and(['id' => 2, 'created' => new DateTime('2012-12-21 12:00')], ['created' => 'datetime']) <ide> ); <ide> }) <ide> ->execute(); <ide> public function testSuqueryInFrom(): void <ide> $subquery = (new Query($this->connection)) <ide> ->select(['id', 'comment']) <ide> ->from('comments') <del> ->where(['created >' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime']); <add> ->where(['created >' => new DateTime('2007-03-18 10:45:23')], ['created' => 'datetime']); <ide> $result = $query <ide> ->select(['say' => 'comment']) <ide> ->from(['b' => $subquery]) <ide> public function testSubqueryInWhere(): void <ide> $subquery = (new Query($this->connection)) <ide> ->select(['id']) <ide> ->from('comments') <del> ->where(['created >' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime']); <add> ->where(['created >' => new DateTime('2007-03-18 10:45:23')], ['created' => 'datetime']); <ide> $result = $query <ide> ->select(['name']) <ide> ->from(['authors']) <ide> public function testUnionOrderBy(): void <ide> { <ide> $this->loadFixtures('Articles', 'Comments'); <ide> $this->skipIf( <del> ($this->connection->getDriver() instanceof \Cake\Database\Driver\Sqlite || <del> $this->connection->getDriver() instanceof \Cake\Database\Driver\Sqlserver), <add> ($this->connection->getDriver() instanceof Sqlite || <add> $this->connection->getDriver() instanceof Sqlserver), <ide> 'Driver does not support ORDER BY in UNIONed queries.' <ide> ); <ide> $union = (new Query($this->connection)) <ide> public function testDeleteNoFrom(): void <ide> */ <ide> public function testDeleteRemovingAliasesCanBreakJoins(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> $this->expectExceptionMessage('Aliases are being removed from conditions for UPDATE/DELETE queries, this can break references to joined tables.'); <ide> $query = new Query($this->connection); <ide> <ide> public function testUpdateArrayFields(): void <ide> { <ide> $this->loadFixtures('Comments'); <ide> $query = new Query($this->connection); <del> $date = new \DateTime(); <add> $date = new DateTime(); <ide> $query->update('comments') <ide> ->set(['comment' => 'mark', 'created' => $date], ['created' => 'date']) <ide> ->where(['id' => 1]); <ide> public function testUpdateSetCallable(): void <ide> { <ide> $this->loadFixtures('Comments'); <ide> $query = new Query($this->connection); <del> $date = new \DateTime(); <add> $date = new DateTime(); <ide> $query->update('comments') <ide> ->set(function ($exp) use ($date) { <ide> return $exp <ide> public function testUpdateStripAliasesFromConditions(): void <ide> */ <ide> public function testUpdateRemovingAliasesCanBreakJoins(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> $this->expectExceptionMessage('Aliases are being removed from conditions for UPDATE/DELETE queries, this can break references to joined tables.'); <ide> $query = new Query($this->connection); <ide> <ide> public function testInsertSimple(): void <ide> $result->closeCursor(); <ide> <ide> //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT <del> if (!$this->connection->getDriver() instanceof \Cake\Database\Driver\Sqlserver) { <add> if (!$this->connection->getDriver() instanceof Sqlserver) { <ide> $this->assertCount(1, $result, '1 row should be inserted'); <ide> } <ide> <ide> public function testInsertSparseRow(): void <ide> $result->closeCursor(); <ide> <ide> //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT <del> if (!$this->connection->getDriver() instanceof \Cake\Database\Driver\Sqlserver) { <add> if (!$this->connection->getDriver() instanceof Sqlserver) { <ide> $this->assertCount(1, $result, '1 row should be inserted'); <ide> } <ide> <ide> public function testInsertMultipleRowsSparse(): void <ide> $result->closeCursor(); <ide> <ide> //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT <del> if (!$this->connection->getDriver() instanceof \Cake\Database\Driver\Sqlserver) { <add> if (!$this->connection->getDriver() instanceof Sqlserver) { <ide> $this->assertCount(2, $result, '2 rows should be inserted'); <ide> } <ide> <ide> public function testInsertFromSelect(): void <ide> $result->closeCursor(); <ide> <ide> //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT <del> if (!$this->connection->getDriver() instanceof \Cake\Database\Driver\Sqlserver) { <add> if (!$this->connection->getDriver() instanceof Sqlserver) { <ide> $this->assertCount(1, $result); <ide> } <ide> <ide> public function testInsertExpressionValues(): void <ide> $result->closeCursor(); <ide> <ide> //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT <del> if (!$this->connection->getDriver() instanceof \Cake\Database\Driver\Sqlserver) { <add> if (!$this->connection->getDriver() instanceof Sqlserver) { <ide> $this->assertCount(1, $result); <ide> } <ide> <ide> public function testInsertExpressionValues(): void <ide> $result = $query->execute(); <ide> $result->closeCursor(); <ide> //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT <del> if (!$this->connection->getDriver() instanceof \Cake\Database\Driver\Sqlserver) { <add> if (!$this->connection->getDriver() instanceof Sqlserver) { <ide> $this->assertCount(1, $result); <ide> } <ide> <ide> function ($q) { <ide> <ide> $this->assertWithinRange( <ide> date('U'), <del> (new \DateTime($result->fetchAll('assoc')[0]['d']))->format('U'), <add> (new DateTime($result->fetchAll('assoc')[0]['d']))->format('U'), <ide> 5 <ide> ); <ide> <ide> function ($q) { <ide> ->execute(); <ide> $this->assertWithinRange( <ide> date('U'), <del> (new \DateTime($result->fetchAll('assoc')[0]['d']))->format('U'), <add> (new DateTime($result->fetchAll('assoc')[0]['d']))->format('U'), <ide> 5 <ide> ); <ide> <ide> public function testDefaultTypes(): void <ide> <ide> $results = $query->select(['id', 'comment']) <ide> ->from('comments') <del> ->where(['created >=' => new \DateTime('2007-03-18 10:55:00')]) <add> ->where(['created >=' => new DateTime('2007-03-18 10:55:00')]) <ide> ->execute(); <ide> $expected = [['id' => '6', 'comment' => 'Second Comment for Second Article']]; <ide> $this->assertEquals($expected, $results->fetchAll('assoc')); <ide> <ide> // Now test default can be overridden <ide> $types = ['created' => 'date']; <ide> $results = $query <del> ->where(['created >=' => new \DateTime('2007-03-18 10:50:00')], $types, true) <add> ->where(['created >=' => new DateTime('2007-03-18 10:50:00')], $types, true) <ide> ->execute(); <ide> $this->assertCount(6, $results, 'All 6 rows should match.'); <ide> } <ide> public function testBind(): void <ide> $results = $query->select(['id', 'comment']) <ide> ->from('comments') <ide> ->where(['created BETWEEN :foo AND :bar']) <del> ->bind(':foo', new \DateTime('2007-03-18 10:50:00'), 'datetime') <del> ->bind(':bar', new \DateTime('2007-03-18 10:52:00'), 'datetime') <add> ->bind(':foo', new DateTime('2007-03-18 10:50:00'), 'datetime') <add> ->bind(':bar', new DateTime('2007-03-18 10:52:00'), 'datetime') <ide> ->execute(); <ide> $expected = [['id' => '4', 'comment' => 'Fourth Comment for First Article']]; <ide> $this->assertEquals($expected, $results->fetchAll('assoc')); <ide> public function testDirectIsNull(): void <ide> */ <ide> public function testIsNullInvalid(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Expression `name` is missing operator (IS, IS NOT) with `null` value.'); <ide> <ide> $this->loadFixtures('Authors'); <ide> public function testIsNullInvalid(): void <ide> */ <ide> public function testIsNotNullInvalid(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> <ide> $this->loadFixtures('Authors'); <ide> (new Query($this->connection)) <ide> public function testSqlCaseStatement(): void <ide> ); <ide> <ide> // Postgres requires the case statement to be cast to a integer <del> if ($this->connection->getDriver() instanceof \Cake\Database\Driver\Postgres) { <add> if ($this->connection->getDriver() instanceof Postgres) { <ide> $publishedCase = $query->func()->cast($publishedCase, 'integer'); <ide> $notPublishedCase = $query->func()->cast($notPublishedCase, 'integer'); <ide> } <ide> public function testBetweenExpressionAndTypeMap(): void <ide> ->from('comments') <ide> ->setDefaultTypes(['created' => 'datetime']) <ide> ->where(function ($expr) { <del> $from = new \DateTime('2007-03-18 10:45:00'); <del> $to = new \DateTime('2007-03-18 10:48:00'); <add> $from = new DateTime('2007-03-18 10:45:00'); <add> $to = new DateTime('2007-03-18 10:48:00'); <ide> <ide> return $expr->between('created', $from, $to); <ide> }); <ide> public function testAllNoDuplicateTypeCasting(): void <ide> */ <ide> public function testClauseUndefined(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('The \'nope\' clause is not defined. Valid clauses are: delete, update'); <ide> $query = new Query($this->connection); <ide> $this->assertEmpty($query->clause('where')); <ide><path>tests/TestCase/Database/QueryTests/AggregatesQueryTests.php <ide> */ <ide> namespace Cake\Test\TestCase\Database\QueryTests; <ide> <add>use Cake\Database\Driver\Postgres; <add>use Cake\Database\Driver\Sqlite; <ide> use Cake\Database\Query; <ide> use Cake\Datasource\ConnectionManager; <ide> use Cake\TestSuite\TestCase; <ide> public function tearDown(): void <ide> */ <ide> public function testFilters(): void <ide> { <del> $skip = !($this->connection->getDriver() instanceof \Cake\Database\Driver\Postgres); <del> if ($this->connection->getDriver() instanceof \Cake\Database\Driver\Sqlite) { <add> $skip = !($this->connection->getDriver() instanceof Postgres); <add> if ($this->connection->getDriver() instanceof Sqlite) { <ide> $skip = version_compare($this->connection->getDriver()->version(), '3.30.0', '<'); <ide> } <ide> $this->skipif($skip); <ide><path>tests/TestCase/Database/QueryTests/WindowQueryTests.php <ide> */ <ide> namespace Cake\Test\TestCase\Database\QueryTests; <ide> <add>use Cake\Database\Driver\Mysql; <add>use Cake\Database\Driver\Sqlite; <add>use Cake\Database\Driver\Sqlserver; <ide> use Cake\Database\Expression\QueryExpression; <ide> use Cake\Database\Expression\WindowExpression; <ide> use Cake\Database\Query; <ide> public function setUp(): void <ide> <ide> $driver = $this->connection->getDriver(); <ide> if ( <del> $driver instanceof \Cake\Database\Driver\Mysql || <del> $driver instanceof \Cake\Database\Driver\Sqlite <add> $driver instanceof Mysql || <add> $driver instanceof Sqlite <ide> ) { <ide> $this->skipTests = !$this->connection->getDriver()->supportsWindowFunctions(); <ide> } else { <ide> public function testNamedWindow(): void <ide> { <ide> $skip = $this->skipTests; <ide> if (!$skip) { <del> $skip = $this->connection->getDriver() instanceof \Cake\Database\Driver\Sqlserver; <add> $skip = $this->connection->getDriver() instanceof Sqlserver; <ide> } <ide> $this->skipIf($skip); <ide> <ide> public function testWindowChaining(): void <ide> $skip = $this->skipTests; <ide> if (!$skip) { <ide> $driver = $this->connection->getDriver(); <del> $skip = $driver instanceof \Cake\Database\Driver\Sqlserver; <del> if ($driver instanceof \Cake\Database\Driver\Sqlite) { <add> $skip = $driver instanceof Sqlserver; <add> if ($driver instanceof Sqlite) { <ide> $skip = version_compare($driver->version(), '3.28.0', '<'); <ide> } <ide> } <ide><path>tests/TestCase/Database/Schema/CollectionTest.php <ide> namespace Cake\Test\TestCase\Database\Schema; <ide> <ide> use Cake\Cache\Cache; <add>use Cake\Database\Exception\DatabaseException; <ide> use Cake\Database\Schema\Collection; <ide> use Cake\Datasource\ConnectionManager; <ide> use Cake\TestSuite\TestCase; <ide> public function tearDown(): void <ide> */ <ide> public function testDescribeIncorrectTable(): void <ide> { <del> $this->expectException(\Cake\Database\Exception::class); <add> $this->expectException(DatabaseException::class); <ide> $schema = new Collection($this->connection); <ide> $this->assertNull($schema->describe('derp')); <ide> } <ide><path>tests/TestCase/Database/Schema/TableSchemaTest.php <ide> namespace Cake\Test\TestCase\Database\Schema; <ide> <ide> use Cake\Database\Driver\Postgres; <add>use Cake\Database\Exception\DatabaseException; <ide> use Cake\Database\Schema\TableSchema; <ide> use Cake\Database\TypeFactory; <ide> use Cake\Datasource\ConnectionManager; <ide> public static function addConstraintErrorProvider(): array <ide> */ <ide> public function testAddConstraintError(array $props): void <ide> { <del> $this->expectException(\Cake\Database\Exception::class); <add> $this->expectException(DatabaseException::class); <ide> $table = new TableSchema('articles'); <ide> $table->addColumn('author_id', 'integer'); <ide> $table->addConstraint('author_idx', $props); <ide> public static function addIndexErrorProvider(): array <ide> */ <ide> public function testAddIndexError(array $props): void <ide> { <del> $this->expectException(\Cake\Database\Exception::class); <add> $this->expectException(DatabaseException::class); <ide> $table = new TableSchema('articles'); <ide> $table->addColumn('author_id', 'integer'); <ide> $table->addIndex('author_idx', $props); <ide> public static function badForeignKeyProvider(): array <ide> */ <ide> public function testAddConstraintForeignKeyBadData(array $data): void <ide> { <del> $this->expectException(\Cake\Database\Exception::class); <add> $this->expectException(DatabaseException::class); <ide> $table = new TableSchema('articles'); <ide> $table->addColumn('author_id', 'integer') <ide> ->addConstraint('author_id_idx', $data); <ide><path>tests/TestCase/Database/Type/BinaryTypeTest.php <ide> */ <ide> namespace Cake\Test\TestCase\Database\Type; <ide> <add>use Cake\Core\Exception\CakeException; <ide> use Cake\Database\TypeFactory; <ide> use Cake\TestSuite\TestCase; <ide> use PDO; <ide> public function testToPHP(): void <ide> */ <ide> public function testToPHPFailure(): void <ide> { <del> $this->expectException(\Cake\Core\Exception\CakeException::class); <add> $this->expectException(CakeException::class); <ide> $this->expectExceptionMessage('Unable to convert array into binary.'); <ide> $this->type->toPHP([], $this->driver); <ide> } <ide><path>tests/TestCase/Database/Type/BoolTypeTest.php <ide> <ide> use Cake\Database\TypeFactory; <ide> use Cake\TestSuite\TestCase; <add>use InvalidArgumentException; <ide> use PDO; <ide> <ide> /** <ide> public function testToDatabase(): void <ide> */ <ide> public function testToDatabaseInvalid(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->type->toDatabase([1, 2], $this->driver); <ide> } <ide> <ide> public function testToDatabaseInvalid(): void <ide> */ <ide> public function testToDatabaseInvalidArray(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->type->toDatabase([1, 2, 3], $this->driver); <ide> } <ide> <ide><path>tests/TestCase/Database/Type/DecimalTypeTest.php <ide> use Cake\Database\Type\DecimalType; <ide> use Cake\I18n\I18n; <ide> use Cake\TestSuite\TestCase; <add>use InvalidArgumentException; <ide> use PDO; <add>use RuntimeException; <ide> <ide> /** <ide> * Test for the Decimal type. <ide> public function testToDatabase(): void <ide> */ <ide> public function testToDatabaseInvalid(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->type->toDatabase(['3', '4'], $this->driver); <ide> } <ide> <ide> public function testToDatabaseInvalid(): void <ide> */ <ide> public function testToDatabaseInvalid2(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->type->toDatabase('some data', $this->driver); <ide> } <ide> <ide> public function testMarshalWithLocaleParsingDanish(): void <ide> */ <ide> public function testUseLocaleParsingInvalid(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> DecimalType::$numberClass = 'stdClass'; <ide> $this->type->useLocaleParser(); <ide> } <ide><path>tests/TestCase/Database/Type/FloatTypeTest.php <ide> use Cake\I18n\I18n; <ide> use Cake\TestSuite\TestCase; <ide> use PDO; <add>use RuntimeException; <ide> <ide> /** <ide> * Test for the Float type. <ide> public function testMarshalWithLocaleParsing(): void <ide> */ <ide> public function testUseLocaleParsingInvalid(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> FloatType::$numberClass = 'stdClass'; <ide> $this->type->useLocaleParser(); <ide> } <ide><path>tests/TestCase/Database/Type/IntegerTypeTest.php <ide> <ide> use Cake\Database\TypeFactory; <ide> use Cake\TestSuite\TestCase; <add>use InvalidArgumentException; <ide> use PDO; <ide> <ide> /** <ide> public function testManyToPHP(): void <ide> */ <ide> public function testInvalidManyToPHP(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $values = [ <ide> 'a' => null, <ide> 'b' => '2.3', <ide> public function invalidIntegerProvider(): array <ide> */ <ide> public function testToDatabaseInvalid($value): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->type->toDatabase($value, $this->driver); <ide> } <ide> <ide><path>tests/TestCase/Database/Type/JsonTypeTest.php <ide> use Cake\Database\Type\JsonType; <ide> use Cake\Database\TypeFactory; <ide> use Cake\TestSuite\TestCase; <add>use InvalidArgumentException; <ide> use PDO; <ide> <ide> /** <ide> public function testToDatabase(): void <ide> */ <ide> public function testToDatabaseInvalid(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $value = fopen(__FILE__, 'r'); <ide> $this->type->toDatabase($value, $this->driver); <ide> } <ide><path>tests/TestCase/Database/Type/StringTypeTest.php <ide> use Cake\Database\Driver; <ide> use Cake\Database\TypeFactory; <ide> use Cake\TestSuite\TestCase; <add>use InvalidArgumentException; <ide> use PDO; <ide> <ide> /** <ide> public function testToDatabase(): void <ide> */ <ide> public function testToDatabaseInvalidArray(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->type->toDatabase([1, 2, 3], $this->driver); <ide> } <ide> <ide><path>tests/TestCase/Database/TypeFactoryTest.php <ide> use Cake\Database\TypeFactory; <ide> use Cake\Database\TypeInterface; <ide> use Cake\TestSuite\TestCase; <add>use InvalidArgumentException; <ide> use PDO; <ide> use TestApp\Database\Type\BarType; <ide> use TestApp\Database\Type\FooType; <ide> public function basicTypesProvider(): array <ide> */ <ide> public function testBuildUnknownType(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> TypeFactory::build('foo'); <ide> } <ide> <ide><path>tests/TestCase/Datasource/ConnectionManagerTest.php <ide> */ <ide> namespace Cake\Test\TestCase\Datasource; <ide> <add>use BadMethodCallException; <add>use Cake\Core\Exception\CakeException; <ide> use Cake\Datasource\ConnectionManager; <add>use Cake\Datasource\Exception\MissingDatasourceConfigException; <add>use Cake\Datasource\Exception\MissingDatasourceException; <ide> use Cake\TestSuite\TestCase; <add>use InvalidArgumentException; <ide> use TestApp\Datasource\FakeConnection; <ide> <ide> /** <ide> public function testConfigVariants($settings): void <ide> */ <ide> public function testConfigInvalidOptions(): void <ide> { <del> $this->expectException(\Cake\Datasource\Exception\MissingDatasourceException::class); <add> $this->expectException(MissingDatasourceException::class); <ide> ConnectionManager::setConfig('test_variant', [ <ide> 'className' => 'Herp\Derp', <ide> ]); <ide> public function testConfigInvalidOptions(): void <ide> */ <ide> public function testConfigDuplicateConfig(): void <ide> { <del> $this->expectException(\BadMethodCallException::class); <add> $this->expectException(BadMethodCallException::class); <ide> $this->expectExceptionMessage('Cannot reconfigure existing key "test_variant"'); <ide> $settings = [ <ide> 'className' => FakeConnection::class, <ide> public function testConfigDuplicateConfig(): void <ide> */ <ide> public function testGetFailOnMissingConfig(): void <ide> { <del> $this->expectException(\Cake\Core\Exception\CakeException::class); <add> $this->expectException(CakeException::class); <ide> $this->expectExceptionMessage('The datasource configuration "test_variant" was not found.'); <ide> ConnectionManager::get('test_variant'); <ide> } <ide> public function testGet(): void <ide> */ <ide> public function testGetNoAlias(): void <ide> { <del> $this->expectException(\Cake\Core\Exception\CakeException::class); <add> $this->expectException(CakeException::class); <ide> $this->expectExceptionMessage('The datasource configuration "other_name" was not found.'); <ide> $config = ConnectionManager::getConfig('test'); <ide> $this->skipIf(empty($config), 'No test config, skipping'); <ide> public function testAlias(): void <ide> */ <ide> public function testAliasError(): void <ide> { <del> $this->expectException(\Cake\Datasource\Exception\MissingDatasourceConfigException::class); <add> $this->expectException(MissingDatasourceConfigException::class); <ide> $this->assertNotContains('test_kaboom', ConnectionManager::configured()); <ide> ConnectionManager::alias('test_kaboom', 'other_name'); <ide> } <ide> public function testParseDsn(string $dsn, array $expected): void <ide> */ <ide> public function testParseDsnInvalid(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('The DSN string \'bagof:nope\' could not be parsed.'); <ide> $result = ConnectionManager::parseDsn('bagof:nope'); <ide> } <ide><path>tests/TestCase/Datasource/FactoryLocatorTest.php <ide> use Cake\Datasource\Locator\LocatorInterface; <ide> use Cake\TestSuite\TestCase; <ide> use InvalidArgumentException; <add>use stdClass; <ide> <ide> /** <ide> * FactoryLocatorTest test case <ide> public function testGet(): void <ide> */ <ide> public function testGetNonExistent(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Unknown repository type "Test". Make sure you register a type before trying to use it.'); <ide> FactoryLocator::get('Test'); <ide> } <ide> public function testGetNonExistent(): void <ide> public function testAdd(): void <ide> { <ide> FactoryLocator::add('Test', function ($name) { <del> $mock = new \stdClass(); <add> $mock = new stdClass(); <ide> $mock->name = $name; <ide> <ide> return $mock; <ide> public function testFactoryAddException(): void <ide> */ <ide> public function testDrop(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Unknown repository type "Test". Make sure you register a type before trying to use it.'); <ide> FactoryLocator::drop('Test'); <ide> <ide><path>tests/TestCase/Datasource/ModelAwareTraitTest.php <ide> */ <ide> namespace Cake\Test\TestCase\Datasource; <ide> <add>use Cake\Datasource\Exception\MissingModelException; <ide> use Cake\Datasource\FactoryLocator; <ide> use Cake\Datasource\Locator\LocatorInterface; <ide> use Cake\Datasource\RepositoryInterface; <ide> use Cake\TestSuite\TestCase; <ide> use InvalidArgumentException; <add>use stdClass; <ide> use TestApp\Model\Table\PaginatorPostsTable; <ide> use TestApp\Stub\Stub; <add>use UnexpectedValueException; <ide> <ide> /** <ide> * ModelAwareTrait test case <ide> public function testLoadModel(): void <ide> */ <ide> public function testLoadModelException(): void <ide> { <del> $this->expectException(\UnexpectedValueException::class); <add> $this->expectException(UnexpectedValueException::class); <ide> $this->expectExceptionMessage('Default modelClass is empty'); <ide> <ide> $stub = new Stub(); <ide> public function testGetSetModelType(): void <ide> $stub->setProps('Articles'); <ide> <ide> FactoryLocator::add('Test', function ($name) { <del> $mock = new \stdClass(); <add> $mock = new stdClass(); <ide> $mock->name = $name; <ide> <ide> return $mock; <ide> public function testGetSetModelType(): void <ide> */ <ide> public function testMissingModelException(): void <ide> { <del> $this->expectException(\Cake\Datasource\Exception\MissingModelException::class); <add> $this->expectException(MissingModelException::class); <ide> $this->expectExceptionMessage('Model class "Magic" of type "Test" could not be found.'); <ide> $stub = new Stub(); <ide> <ide><path>tests/TestCase/Datasource/PaginatorTestTrait.php <ide> public function testOutOfRangePageNumberGetsClamped(): void <ide> */ <ide> public function testOutOfVeryBigPageNumberGetsClamped(): void <ide> { <del> $this->expectException(\Cake\Datasource\Exception\PageOutOfBoundsException::class); <add> $this->expectException(PageOutOfBoundsException::class); <ide> $this->loadFixtures('Posts'); <ide> $params = [ <ide> 'page' => '3000000000000000000000000', <ide><path>tests/TestCase/Datasource/QueryCacherTest.php <ide> use Cake\Cache\Cache; <ide> use Cake\Datasource\QueryCacher; <ide> use Cake\TestSuite\TestCase; <add>use RuntimeException; <ide> use stdClass; <ide> <ide> /** <ide> public function testFetchFunctionKey(): void <ide> */ <ide> public function testFetchFunctionKeyNoString(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> $this->expectExceptionMessage('Cache key functions must return a string. Got false.'); <ide> $this->engine->set('my_key', 'A winner'); <ide> $query = new stdClass(); <ide><path>tests/TestCase/Datasource/ResultSetDecoratorTest.php <ide> */ <ide> namespace Cake\Test\TestCase\Datasource; <ide> <add>use ArrayIterator; <ide> use Cake\Datasource\ResultSetDecorator; <ide> use Cake\TestSuite\TestCase; <ide> <ide> class ResultSetDecoratorTest extends TestCase <ide> */ <ide> public function testDecorateSimpleIterator(): void <ide> { <del> $data = new \ArrayIterator([1, 2, 3]); <add> $data = new ArrayIterator([1, 2, 3]); <ide> $decorator = new ResultSetDecorator($data); <ide> $this->assertEquals([1, 2, 3], iterator_to_array($decorator)); <ide> } <ide> public function testDecorateSimpleIterator(): void <ide> */ <ide> public function testToArray(): void <ide> { <del> $data = new \ArrayIterator([1, 2, 3]); <add> $data = new ArrayIterator([1, 2, 3]); <ide> $decorator = new ResultSetDecorator($data); <ide> $this->assertEquals([1, 2, 3], $decorator->toArray()); <ide> } <ide> public function testToArray(): void <ide> */ <ide> public function testToJson(): void <ide> { <del> $data = new \ArrayIterator([1, 2, 3]); <add> $data = new ArrayIterator([1, 2, 3]); <ide> $decorator = new ResultSetDecorator($data); <ide> $this->assertEquals(json_encode([1, 2, 3]), json_encode($decorator)); <ide> } <ide> public function testToJson(): void <ide> */ <ide> public function testSerialization(): void <ide> { <del> $data = new \ArrayIterator([1, 2, 3]); <add> $data = new ArrayIterator([1, 2, 3]); <ide> $decorator = new ResultSetDecorator($data); <ide> $serialized = serialize($decorator); <ide> $this->assertEquals([1, 2, 3], unserialize($serialized)->toArray()); <ide> public function testSerialization(): void <ide> */ <ide> public function testFirst(): void <ide> { <del> $data = new \ArrayIterator([1, 2, 3]); <add> $data = new ArrayIterator([1, 2, 3]); <ide> $decorator = new ResultSetDecorator($data); <ide> <ide> $this->assertSame(1, $decorator->first()); <ide> public function testFirst(): void <ide> */ <ide> public function testCount(): void <ide> { <del> $data = new \ArrayIterator([1, 2, 3]); <add> $data = new ArrayIterator([1, 2, 3]); <ide> $decorator = new ResultSetDecorator($data); <ide> <ide> $this->assertSame(3, $decorator->count()); <ide><path>tests/TestCase/Error/ConsoleErrorHandlerTest.php <ide> use Cake\Log\Log; <ide> use Cake\TestSuite\Stub\ConsoleOutput; <ide> use Cake\TestSuite\TestCase; <add>use InvalidArgumentException; <ide> <ide> /** <ide> * ConsoleErrorHandler Test case. <ide> public function testCakeErrors(): void <ide> */ <ide> public function testNonCakeExceptions(): void <ide> { <del> $exception = new \InvalidArgumentException('Too many parameters.'); <add> $exception = new InvalidArgumentException('Too many parameters.'); <ide> <ide> $this->Error->expects($this->once()) <ide> ->method('_stop') <ide><path>tests/TestCase/Error/DebuggerTest.php <ide> use Cake\Form\Form; <ide> use Cake\Log\Log; <ide> use Cake\TestSuite\TestCase; <add>use InvalidArgumentException; <add>use MyClass; <ide> use RuntimeException; <ide> use SplFixedArray; <ide> use stdClass; <ide> public function testGetSetOutputFormat(): void <ide> */ <ide> public function testSetOutputAsException(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> Debugger::setOutputFormat('Invalid junk'); <ide> } <ide> <ide> public function testExportVarTypedProperty(): void <ide> // This is gross but was simpler than adding a fixture file. <ide> // phpcs:ignore <ide> eval('class MyClass { private string $field; }'); <del> $obj = new \MyClass(); <add> $obj = new MyClass(); <ide> $out = Debugger::exportVar($obj); <ide> $this->assertTextContains('field => [uninitialized]', $out); <ide> } <ide><path>tests/TestCase/Error/ErrorHandlerTest.php <ide> use Cake\Log\Log; <ide> use Cake\Routing\Router; <ide> use Cake\TestSuite\TestCase; <add>use Exception; <ide> use RuntimeException; <add>use stdClass; <ide> use TestApp\Error\TestErrorHandler; <ide> <ide> /** <ide> public function testInvalidRenderer(): void <ide> $this->expectExceptionMessage('The \'TotallyInvalid\' renderer class could not be found'); <ide> <ide> $errorHandler = new ErrorHandler(['exceptionRenderer' => 'TotallyInvalid']); <del> $errorHandler->getRenderer(new \Exception('Something bad')); <add> $errorHandler->getRenderer(new Exception('Something bad')); <ide> } <ide> <ide> /** <ide> public function testGetLogger(): void <ide> */ <ide> public function testGetLoggerInvalid(): void <ide> { <del> $errorHandler = new TestErrorHandler(['errorLogger' => \stdClass::class]); <add> $errorHandler = new TestErrorHandler(['errorLogger' => stdClass::class]); <ide> $this->expectException(RuntimeException::class); <ide> $this->expectExceptionMessage('Cannot create logger'); <ide> $errorHandler->getLogger(); <ide><path>tests/TestCase/Error/ExceptionRendererTest.php <ide> use Cake\View\Exception\MissingLayoutException; <ide> use Cake\View\Exception\MissingTemplateException; <ide> use Exception; <add>use OutOfBoundsException; <add>use PDOException; <ide> use RuntimeException; <ide> use TestApp\Controller\Admin\ErrorController; <ide> use TestApp\Error\Exception\MissingWidgetThing; <ide> use TestApp\Error\Exception\MissingWidgetThingException; <ide> use TestApp\Error\MyCustomExceptionRenderer; <add>use TestApp\Error\TestAppsExceptionRenderer; <ide> <ide> class ExceptionRendererTest extends TestCase <ide> { <ide> public function testCakeErrorHelpersNotLost(): void <ide> { <ide> static::setAppNamespace(); <ide> $exception = new NotFoundException(); <del> $renderer = new \TestApp\Error\TestAppsExceptionRenderer($exception); <add> $renderer = new TestAppsExceptionRenderer($exception); <ide> <ide> $result = $renderer->render(); <ide> $this->assertStringContainsString('<b>peeled</b>', (string)$result->getBody()); <ide> public function testUnknownExceptionTypeWithExceptionThatHasA400Code(): void <ide> */ <ide> public function testUnknownExceptionTypeWithNoCodeIsA500(): void <ide> { <del> $exception = new \OutOfBoundsException('foul ball.'); <add> $exception = new OutOfBoundsException('foul ball.'); <ide> $ExceptionRenderer = new ExceptionRenderer($exception); <ide> $result = $ExceptionRenderer->render(); <ide> <ide> public function testUnknownExceptionInProduction(): void <ide> { <ide> Configure::write('debug', false); <ide> <del> $exception = new \OutOfBoundsException('foul ball.'); <add> $exception = new OutOfBoundsException('foul ball.'); <ide> $ExceptionRenderer = new ExceptionRenderer($exception); <ide> <ide> $response = $ExceptionRenderer->render(); <ide> public function testSubclassTriggerShutdownEvents(): void <ide> */ <ide> public function testPDOException(): void <ide> { <del> $exception = new \PDOException('There was an error in the SQL query'); <add> $exception = new PDOException('There was an error in the SQL query'); <ide> $exception->queryString = 'SELECT * from poo_query < 5 and :seven'; <ide> $exception->params = ['seven' => 7]; <ide> $ExceptionRenderer = new ExceptionRenderer($exception); <ide><path>tests/TestCase/Error/Middleware/ErrorHandlerMiddlewareTest.php <ide> namespace Cake\Test\TestCase\Error\Middleware; <ide> <ide> use Cake\Core\Configure; <add>use Cake\Datasource\Exception\RecordNotFoundException; <ide> use Cake\Error\ErrorHandler; <ide> use Cake\Error\ExceptionRendererInterface; <ide> use Cake\Error\Middleware\ErrorHandlerMiddleware; <ide> use Cake\Http\Exception\MissingControllerException; <add>use Cake\Http\Exception\NotFoundException; <ide> use Cake\Http\Exception\RedirectException; <add>use Cake\Http\Exception\ServiceUnavailableException; <ide> use Cake\Http\Response; <ide> use Cake\Http\ServerRequestFactory; <ide> use Cake\Log\Log; <ide> public function testHandleException(): void <ide> $request = ServerRequestFactory::fromGlobals(); <ide> $middleware = new ErrorHandlerMiddleware(); <ide> $handler = new TestRequestHandler(function (): void { <del> throw new \Cake\Http\Exception\NotFoundException('whoops'); <add> throw new NotFoundException('whoops'); <ide> }); <ide> $result = $middleware->process($request, $handler); <ide> $this->assertInstanceOf('Cake\Http\Response', $result); <ide> public function testHandleExceptionPreserveRequest(): void <ide> <ide> $middleware = new ErrorHandlerMiddleware(); <ide> $handler = new TestRequestHandler(function (): void { <del> throw new \Cake\Http\Exception\NotFoundException('whoops'); <add> throw new NotFoundException('whoops'); <ide> }); <ide> $result = $middleware->process($request, $handler); <ide> $this->assertInstanceOf('Cake\Http\Response', $result); <ide> public function testHandleExceptionLogAndTrace(): void <ide> ]); <ide> $middleware = new ErrorHandlerMiddleware(['log' => true, 'trace' => true]); <ide> $handler = new TestRequestHandler(function (): void { <del> throw new \Cake\Http\Exception\NotFoundException('Kaboom!'); <add> throw new NotFoundException('Kaboom!'); <ide> }); <ide> $result = $middleware->process($request, $handler); <ide> $this->assertSame(404, $result->getStatusCode()); <ide> public function testHandleExceptionLogAndTraceWithPrevious(): void <ide> ]); <ide> $middleware = new ErrorHandlerMiddleware(['log' => true, 'trace' => true]); <ide> $handler = new TestRequestHandler(function ($req): void { <del> $previous = new \Cake\Datasource\Exception\RecordNotFoundException('Previous logged'); <del> throw new \Cake\Http\Exception\NotFoundException('Kaboom!', null, $previous); <add> $previous = new RecordNotFoundException('Previous logged'); <add> throw new NotFoundException('Kaboom!', null, $previous); <ide> }); <ide> $result = $middleware->process($request, $handler); <ide> $this->assertSame(404, $result->getStatusCode()); <ide> public function testHandleExceptionSkipLog(): void <ide> 'skipLog' => ['Cake\Http\Exception\NotFoundException'], <ide> ]); <ide> $handler = new TestRequestHandler(function (): void { <del> throw new \Cake\Http\Exception\NotFoundException('Kaboom!'); <add> throw new NotFoundException('Kaboom!'); <ide> }); <ide> $result = $middleware->process($request, $handler); <ide> $this->assertSame(404, $result->getStatusCode()); <ide> public function testHandleExceptionRenderingFails(): void <ide> 'exceptionRenderer' => $factory, <ide> ])); <ide> $handler = new TestRequestHandler(function (): void { <del> throw new \Cake\Http\Exception\ServiceUnavailableException('whoops'); <add> throw new ServiceUnavailableException('whoops'); <ide> }); <ide> $response = $middleware->process($request, $handler); <ide> $this->assertSame(500, $response->getStatusCode()); <ide><path>tests/TestCase/Event/Decorator/ConditionDecoratorTest.php <ide> use Cake\Event\EventInterface; <ide> use Cake\Event\EventManager; <ide> use Cake\TestSuite\TestCase; <add>use RuntimeException; <ide> <ide> /** <ide> * Tests the Cake\Event\Event class functionality <ide> public function testCascadingEvents(): void <ide> */ <ide> public function testCallableRuntimeException(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> $this->expectExceptionMessage('Cake\Event\Decorator\ConditionDecorator the `if` condition is not a callable!'); <ide> $callable = function (EventInterface $event) { <ide> return 'success'; <ide><path>tests/TestCase/Http/Client/Adapter/StreamTest.php <ide> */ <ide> namespace Cake\Test\TestCase\Http\Client\Adapter; <ide> <add>use Cake\Core\Exception\CakeException; <ide> use Cake\Http\Client\Adapter\Stream; <add>use Cake\Http\Client\Exception\NetworkException; <ide> use Cake\Http\Client\Request; <ide> use Cake\Http\Client\Response; <ide> use Cake\TestSuite\TestCase; <add>use Exception; <ide> use TestApp\Http\Client\Adapter\CakeStreamWrapper; <ide> <ide> /** <ide> public function testSend(): void <ide> <ide> try { <ide> $responses = $stream->send($request, []); <del> } catch (\Cake\Core\Exception\CakeException $e) { <add> } catch (CakeException $e) { <ide> $this->markTestSkipped('Could not connect to localhost, skipping'); <ide> } <ide> $this->assertInstanceOf(Response::class, $responses[0]); <ide> public function testSendWrapperException(): void <ide> <ide> try { <ide> $stream->send($request, []); <del> } catch (\Exception $e) { <add> } catch (Exception $e) { <ide> } <ide> <ide> $newHandler = set_error_handler(function (): void { <ide> public function testMissDeadline(): void <ide> <ide> $stream = new Stream(); <ide> <del> $this->expectException(\Cake\Http\Client\Exception\NetworkException::class); <add> $this->expectException(NetworkException::class); <ide> $this->expectExceptionMessage('Connection timed out http://dummy/?sleep'); <ide> <ide> $stream->send($request, $options); <ide><path>tests/TestCase/Http/Client/Auth/OauthTest.php <ide> */ <ide> namespace Cake\Test\TestCase\Http\Client\Auth; <ide> <add>use Cake\Core\Exception\CakeException; <ide> use Cake\Http\Client\Auth\Oauth; <ide> use Cake\Http\Client\Request; <ide> use Cake\TestSuite\TestCase; <ide> class OauthTest extends TestCase <ide> <ide> public function testExceptionUnknownSigningMethod(): void <ide> { <del> $this->expectException(\Cake\Core\Exception\CakeException::class); <add> $this->expectException(CakeException::class); <ide> $auth = new Oauth(); <ide> $creds = [ <ide> 'consumerSecret' => 'it is secret', <ide><path>tests/TestCase/Http/ClientTest.php <ide> */ <ide> namespace Cake\Test\TestCase\Http; <ide> <add>use Cake\Core\Exception\CakeException; <ide> use Cake\Http\Client; <ide> use Cake\Http\Client\Adapter\Stream; <ide> use Cake\Http\Client\Exception\MissingResponseException; <ide> use Cake\Http\Cookie\CookieCollection; <ide> use Cake\TestSuite\TestCase; <ide> use InvalidArgumentException; <add>use Laminas\Diactoros\Request as LaminasRequest; <ide> <ide> /** <ide> * HTTP client test. <ide> public function testGetWithContent(): void <ide> */ <ide> public function testInvalidAuthenticationType(): void <ide> { <del> $this->expectException(\Cake\Core\Exception\CakeException::class); <add> $this->expectException(CakeException::class); <ide> $mock = $this->getMockBuilder(Stream::class) <ide> ->onlyMethods(['send']) <ide> ->getMock(); <ide> public function testPostWithStringDataDefaultsToFormEncoding(): void <ide> */ <ide> public function testExceptionOnUnknownType(): void <ide> { <del> $this->expectException(\Cake\Core\Exception\CakeException::class); <add> $this->expectException(CakeException::class); <ide> $mock = $this->getMockBuilder(Stream::class) <ide> ->onlyMethods(['send']) <ide> ->getMock(); <ide> public function testAddCookie(): void <ide> */ <ide> public function testAddCookieWithoutDomain(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Cookie must have a domain and a path set.'); <ide> $client = new Client(); <ide> $cookie = new Cookie('foo', '', null, '/', ''); <ide> public function testAddCookieWithoutDomain(): void <ide> */ <ide> public function testAddCookieWithoutPath(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Cookie must have a domain and a path set.'); <ide> $client = new Client(); <ide> $cookie = new Cookie('foo', '', null, '', 'example.com'); <ide> public function testSendRequest(): void <ide> ->will($this->returnValue([$response])); <ide> <ide> $http = new Client(['adapter' => $mock]); <del> $request = new \Laminas\Diactoros\Request( <add> $request = new LaminasRequest( <ide> 'http://cakephp.org/test.html', <ide> Request::METHOD_GET, <ide> 'php://temp', <ide><path>tests/TestCase/Http/Cookie/CookieCollectionTest.php <ide> public function testGetByName(): void <ide> */ <ide> public function testConstructorWithInvalidCookieObjects(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Expected `Cake\Http\Cookie\CookieCollection[]` as $cookies but instead got `array` at index 1'); <ide> $array = [ <ide> new Cookie('one', 'one'), <ide><path>tests/TestCase/Http/Cookie/CookieTest.php <ide> use Cake\Http\Cookie\CookieInterface; <ide> use Cake\TestSuite\TestCase; <ide> use DateTimeInterface; <add>use InvalidArgumentException; <ide> <ide> /** <ide> * HTTP cookies test. <ide> public function invalidNameProvider(): array <ide> */ <ide> public function testValidateNameInvalidChars(string $name): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('contains invalid characters.'); <ide> new Cookie($name, 'value'); <ide> } <ide> public function testValidateNameInvalidChars(string $name): void <ide> */ <ide> public function testValidateNameEmptyName(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('The cookie name cannot be empty.'); <ide> new Cookie('', ''); <ide> } <ide> public function testWithSameSite(): void <ide> */ <ide> public function testWithSameSiteException(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Samesite value must be either of: ' . implode(', ', CookieInterface::SAMESITE_VALUES)); <ide> <ide> $cookie = new Cookie('cakephp', 'cakephp-rocks'); <ide> public function testDefaults(): void <ide> <ide> public function testInvalidExpiresForDefaults(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Invalid type `array` for expire'); <ide> <ide> Cookie::setDefaults(['expires' => ['ompalompa']]); <ide> public function testInvalidExpiresForDefaults(): void <ide> <ide> public function testInvalidSameSiteForDefaults(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Samesite value must be either of: ' . implode(', ', CookieInterface::SAMESITE_VALUES)); <ide> <ide> Cookie::setDefaults(['samesite' => 'ompalompa']); <ide><path>tests/TestCase/Http/Middleware/CsrfProtectionMiddlewareTest.php <ide> public function testValidTokenRequestDataSalted(string $method): void <ide> */ <ide> public function testInvalidTokenNonStringCookies(): void <ide> { <del> $this->expectException(\Cake\Http\Exception\InvalidCsrfTokenException::class); <add> $this->expectException(InvalidCsrfTokenException::class); <ide> $request = new ServerRequest([ <ide> 'environment' => [ <ide> 'REQUEST_METHOD' => 'POST', <ide><path>tests/TestCase/Http/Middleware/SecurityHeadersMiddlewareTest.php <ide> use Cake\Http\Middleware\SecurityHeadersMiddleware; <ide> use Cake\Http\ServerRequestFactory; <ide> use Cake\TestSuite\TestCase; <add>use InvalidArgumentException; <ide> use Laminas\Diactoros\Response; <ide> use TestApp\Http\TestRequestHandler; <ide> <ide> public function testAddingSecurityHeaders(): void <ide> */ <ide> public function testInvalidArgumentExceptionForsetXFrameOptionsUrl(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('The 2nd arg $url can not be empty when `allow-from` is used'); <ide> $middleware = new SecurityHeadersMiddleware(); <ide> $middleware->setXFrameOptions('allow-from'); <ide> public function testInvalidArgumentExceptionForsetXFrameOptionsUrl(): void <ide> */ <ide> public function testCheckValues(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Invalid arg `INVALID-VALUE!`, use one of these: all, none, master-only, by-content-type, by-ftp-filename'); <ide> $middleware = new SecurityHeadersMiddleware(); <ide> $middleware->setCrossDomainPolicy('INVALID-VALUE!'); <ide><path>tests/TestCase/Http/MiddlewareQueueTest.php <ide> <ide> use Cake\Http\MiddlewareQueue; <ide> use Cake\TestSuite\TestCase; <add>use LogicException; <add>use OutOfBoundsException; <ide> use TestApp\Middleware\DumbMiddleware; <ide> use TestApp\Middleware\SampleMiddleware; <ide> <ide> public function testGet(): void <ide> */ <ide> public function testGetException(): void <ide> { <del> $this->expectException(\OutOfBoundsException::class); <add> $this->expectException(OutOfBoundsException::class); <ide> $this->expectExceptionMessage('Invalid current position (0)'); <ide> <ide> $queue = new MiddlewareQueue(); <ide> public function testInsertBefore(): void <ide> */ <ide> public function testInsertBeforeInvalid(): void <ide> { <del> $this->expectException(\LogicException::class); <add> $this->expectException(LogicException::class); <ide> $this->expectExceptionMessage('No middleware matching \'InvalidClassName\' could be found.'); <ide> $one = function (): void { <ide> }; <ide><path>tests/TestCase/Http/ResponseTest.php <ide> use Cake\Http\ServerRequest; <ide> use Cake\I18n\FrozenTime; <ide> use Cake\TestSuite\TestCase; <add>use DateTime as NativeDateTime; <add>use DateTimeImmutable; <add>use DateTimeZone; <add>use InvalidArgumentException; <ide> use Laminas\Diactoros\Stream; <ide> <ide> /** <ide> public function withTypeFull(): void <ide> */ <ide> public function testWithTypeInvalidType(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('"beans" is an invalid content type'); <ide> $response = new Response(); <ide> $response->withType('beans'); <ide> public function testWithAddedLink(): void <ide> public function testWithExpires(): void <ide> { <ide> $response = new Response(); <del> $now = new \DateTime('now', new \DateTimeZone('America/Los_Angeles')); <add> $now = new NativeDateTime('now', new DateTimeZone('America/Los_Angeles')); <ide> <ide> $new = $response->withExpires($now); <ide> $this->assertFalse($response->hasHeader('Expires')); <ide> <del> $now->setTimeZone(new \DateTimeZone('UTC')); <add> $now->setTimeZone(new DateTimeZone('UTC')); <ide> $this->assertSame($now->format(DATE_RFC7231), $new->getHeaderLine('Expires')); <ide> <ide> $now = time(); <ide> $new = $response->withExpires($now); <ide> $this->assertSame(gmdate(DATE_RFC7231), $new->getHeaderLine('Expires')); <ide> <del> $time = new \DateTime('+1 day', new \DateTimeZone('UTC')); <add> $time = new NativeDateTime('+1 day', new DateTimeZone('UTC')); <ide> $new = $response->withExpires('+1 day'); <ide> $this->assertSame($time->format(DATE_RFC7231), $new->getHeaderLine('Expires')); <ide> } <ide> public function testWithExpires(): void <ide> public function testWithModified(): void <ide> { <ide> $response = new Response(); <del> $now = new \DateTime('now', new \DateTimeZone('America/Los_Angeles')); <add> $now = new NativeDateTime('now', new DateTimeZone('America/Los_Angeles')); <ide> $new = $response->withModified($now); <ide> $this->assertFalse($response->hasHeader('Last-Modified')); <ide> <del> $now->setTimeZone(new \DateTimeZone('UTC')); <add> $now->setTimeZone(new DateTimeZone('UTC')); <ide> $this->assertSame($now->format(DATE_RFC7231), $new->getHeaderLine('Last-Modified')); <ide> <ide> $now = time(); <ide> $new = $response->withModified($now); <ide> $this->assertSame(gmdate(DATE_RFC7231, $now), $new->getHeaderLine('Last-Modified')); <ide> <del> $now = new \DateTimeImmutable(); <add> $now = new DateTimeImmutable(); <ide> $new = $response->withModified($now); <ide> $this->assertSame(gmdate(DATE_RFC7231, $now->getTimestamp()), $new->getHeaderLine('Last-Modified')); <ide> <del> $time = new \DateTime('+1 day', new \DateTimeZone('UTC')); <add> $time = new NativeDateTime('+1 day', new DateTimeZone('UTC')); <ide> $new = $response->withModified('+1 day'); <ide> $this->assertSame($time->format(DATE_RFC7231), $new->getHeaderLine('Last-Modified')); <ide> } <ide> public function testWithCookieScalar(): void <ide> */ <ide> public function testWithDuplicateCookie(): void <ide> { <del> $expiry = new \DateTimeImmutable('+24 hours'); <add> $expiry = new DateTimeImmutable('+24 hours'); <ide> <ide> $response = new Response(); <ide> $cookie = new Cookie( <ide> public function testWithExpiredCookieOptions(): void <ide> 'path' => '/custompath/', <ide> 'secure' => true, <ide> 'httponly' => true, <del> 'expires' => new \DateTimeImmutable('+14 days'), <add> 'expires' => new DateTimeImmutable('+14 days'), <ide> ], <ide> ]; <ide> <ide> public function testCors(): void <ide> */ <ide> public function testWithFileNotFound(): void <ide> { <del> $this->expectException(\Cake\Http\Exception\NotFoundException::class); <add> $this->expectException(NotFoundException::class); <ide> $this->expectExceptionMessage('The requested file /some/missing/folder/file.jpg was not found'); <ide> <ide> $response = new Response(); <ide> public function testWithFileNotFoundNoDebug(): void <ide> { <ide> Configure::write('debug', 0); <ide> <del> $this->expectException(\Cake\Http\Exception\NotFoundException::class); <add> $this->expectException(NotFoundException::class); <ide> $this->expectExceptionMessage('The requested file was not found'); <ide> $response = new Response(); <ide> $response->withFile('/some/missing/folder/file.jpg'); <ide> public function testWithStatusCode(): void <ide> */ <ide> public function testWithStatusInvalid(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Invalid status code: 1001. Use a valid HTTP status code in range 1xx - 5xx.'); <ide> $response = new Response(); <ide> $response->withStatus(1001); <ide><path>tests/TestCase/Http/RunnerTest.php <ide> public function testRunSequencing(): void <ide> */ <ide> public function testRunExceptionInMiddleware(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> $this->expectExceptionMessage('A bad thing'); <ide> $this->queue->add($this->ok)->add($this->fail); <ide> $req = $this->getMockBuilder('Psr\Http\Message\ServerRequestInterface')->getMock(); <ide><path>tests/TestCase/Http/ServerRequestTest.php <ide> */ <ide> namespace Cake\Test\TestCase\Http; <ide> <add>use BadMethodCallException; <ide> use Cake\Core\Configure; <ide> use Cake\Http\Cookie\Cookie; <ide> use Cake\Http\Cookie\CookieCollection; <ide> use Cake\Http\ServerRequest; <ide> use Cake\Http\Session; <ide> use Cake\TestSuite\TestCase; <add>use InvalidArgumentException; <ide> use Laminas\Diactoros\UploadedFile; <ide> use Laminas\Diactoros\Uri; <ide> <ide> public function testGetUploadedFile(): void <ide> */ <ide> public function testWithUploadedFilesInvalidFile(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Invalid file at \'avatar\''); <ide> $request = new ServerRequest(); <ide> $request->withUploadedFiles(['avatar' => 'not a file']); <ide> public function testWithUploadedFilesInvalidFile(): void <ide> */ <ide> public function testWithUploadedFilesInvalidFileNested(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Invalid file at \'user.avatar\''); <ide> $request = new ServerRequest(); <ide> $request->withUploadedFiles(['user' => ['avatar' => 'not a file']]); <ide> public function testWithMethod(): void <ide> */ <ide> public function testWithMethodInvalid(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Unsupported HTTP method "no good" provided'); <ide> $request = new ServerRequest([ <ide> 'environment' => ['REQUEST_METHOD' => 'delete'], <ide> public function testWithProtocolVersion(): void <ide> */ <ide> public function testWithProtocolVersionInvalid(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Unsupported protocol version \'no good\' provided'); <ide> $request = new ServerRequest(); <ide> $request->withProtocolVersion('no good'); <ide> public function testisAjax(): void <ide> */ <ide> public function testMagicCallExceptionOnUnknownMethod(): void <ide> { <del> $this->expectException(\BadMethodCallException::class); <add> $this->expectException(BadMethodCallException::class); <ide> $request = new ServerRequest(); <ide> $request->IamABanana(); <ide> } <ide> public function testWithoutAttribute(): void <ide> */ <ide> public function testWithoutAttributesDenyEmulatedProperties(string $prop): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $request = new ServerRequest([]); <ide> $request->withoutAttribute($prop); <ide> } <ide><path>tests/TestCase/Http/ServerTest.php <ide> use Cake\Http\Session; <ide> use Cake\TestSuite\TestCase; <ide> use InvalidArgumentException; <del>use Laminas\Diactoros\Response; <add>use Laminas\Diactoros\Response as LaminasResponse; <add>use Laminas\Diactoros\ServerRequest as LaminasServerRequest; <ide> use TestApp\Http\MiddlewareApplication; <ide> <ide> require_once __DIR__ . '/server_mocks.php'; <ide> public function testRunClosesSessionIfServerRequestUsed(): void <ide> */ <ide> public function testRunDoesNotCloseSessionIfServerRequestNotUsed(): void <ide> { <del> $request = new \Laminas\Diactoros\ServerRequest(); <add> $request = new LaminasServerRequest(); <ide> <ide> $app = new MiddlewareApplication($this->config); <ide> $server = new Server($app); <ide> public function testEmit(): void <ide> public function testEmitCallbackStream(): void <ide> { <ide> $GLOBALS['mockedHeadersSent'] = false; <del> $response = new Response('php://memory', 200, ['x-testing' => 'source header']); <add> $response = new LaminasResponse('php://memory', 200, ['x-testing' => 'source header']); <ide> $response = $response->withBody(new CallbackStream(function (): void { <ide> echo 'body content'; <ide> })); <ide><path>tests/TestCase/Http/Session/CacheSessionTest.php <ide> use Cake\Cache\Cache; <ide> use Cake\Http\Session\CacheSession; <ide> use Cake\TestSuite\TestCase; <add>use InvalidArgumentException; <ide> <ide> /** <ide> * CacheSessionTest <ide> public function testDestroy(): void <ide> */ <ide> public function testMissingConfig(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('The cache configuration name to use is required'); <ide> new CacheSession(['foo' => 'bar']); <ide> } <ide><path>tests/TestCase/I18n/DateTest.php <ide> use Cake\I18n\FrozenDate; <ide> use Cake\TestSuite\TestCase; <ide> use DateTimeZone; <add>use IntlDateFormatter; <ide> <ide> /** <ide> * DateTest class <ide> public function testI18nFormat(string $class): void <ide> $expected = '1/14/10'; <ide> $this->assertSame($expected, $result); <ide> <del> $format = [\IntlDateFormatter::NONE, \IntlDateFormatter::SHORT]; <add> $format = [IntlDateFormatter::NONE, IntlDateFormatter::SHORT]; <ide> $result = $time->i18nFormat($format); <ide> $expected = '12:00 AM'; <ide> $this->assertSame($expected, $result); <ide> public function testI18nFormat(string $class): void <ide> $this->assertSame($expected, $result); <ide> <ide> $class::setDefaultLocale('fr-FR'); <del> $result = $time->i18nFormat(\IntlDateFormatter::FULL); <add> $result = $time->i18nFormat(IntlDateFormatter::FULL); <ide> $result = str_replace(' à', '', $result); <ide> $expected = 'jeudi 14 janvier 2010 00:00:00'; <ide> $this->assertStringStartsWith($expected, $result); <ide> <del> $result = $time->i18nFormat(\IntlDateFormatter::FULL, null, 'es-ES'); <add> $result = $time->i18nFormat(IntlDateFormatter::FULL, null, 'es-ES'); <ide> $this->assertStringContainsString('14 de enero de 2010', $result, 'Default locale should not be used'); <ide> <ide> $time = new $class('2014-01-01T00:00:00Z'); <del> $result = $time->i18nFormat(\IntlDateFormatter::FULL, null, 'en-US'); <add> $result = $time->i18nFormat(IntlDateFormatter::FULL, null, 'en-US'); <ide> $expected = 'Wednesday, January 1, 2014 at 12:00:00 AM'; <ide> $this->assertStringStartsWith($expected, $result); <ide> } <ide><path>tests/TestCase/I18n/Formatter/IcuFormatterTest.php <ide> <ide> use Cake\I18n\Formatter\IcuFormatter; <ide> use Cake\TestSuite\TestCase; <add>use Exception; <ide> <ide> /** <ide> * IcuFormatter tests <ide> public function testNativePluralSelection(): void <ide> */ <ide> public function testBadMessageFormat(): void <ide> { <del> $this->expectException(\Exception::class); <add> $this->expectException(Exception::class); <ide> <ide> $formatter = new IcuFormatter(); <ide> $formatter->format('en_US', '{crazy format', ['some', 'vars']); <ide><path>tests/TestCase/I18n/NumberTest.php <ide> use Cake\I18n\I18n; <ide> use Cake\I18n\Number; <ide> use Cake\TestSuite\TestCase; <add>use NumberFormatter; <ide> <ide> /** <ide> * NumberTest class <ide> public function testConfig(): void <ide> $result = $this->Number->currency(150000, 'USD', ['locale' => 'en_US']); <ide> $this->assertSame('$150,000.00', $result); <ide> <del> Number::config('en_US', \NumberFormatter::CURRENCY, [ <add> Number::config('en_US', NumberFormatter::CURRENCY, [ <ide> 'pattern' => '¤ #,##,##0', <ide> ]); <ide> <ide><path>tests/TestCase/I18n/TimeTest.php <ide> use Cake\I18n\I18n; <ide> use Cake\I18n\Time; <ide> use Cake\TestSuite\TestCase; <add>use DateTime as NativeDateTime; <add>use DateTimeZone; <ide> use IntlDateFormatter; <ide> <ide> /** <ide> public function testConstructFromAnotherInstance(string $class): void <ide> $subject = new $class($mut); <ide> $this->assertSame($time, $subject->format('Y-m-d H:i:s.u'), 'mutable time construction'); <ide> <del> $mut = new \DateTime($time, new \DateTimeZone('America/Chicago')); <add> $mut = new NativeDateTime($time, new DateTimeZone('America/Chicago')); <ide> $subject = new $class($mut); <del> $this->assertSame($time, $subject->format('Y-m-d H:i:s.u'), 'mutable time construction'); <add> $this->assertSame($time, $subject->format('Y-m-d H:i:s.u'), 'time construction'); <ide> } <ide> <ide> /** <ide> public function testI18nFormat(string $class): void <ide> $this->assertTimeFormat($expected, $result); <ide> <ide> // Test using a time-specific format <del> $format = [\IntlDateFormatter::NONE, \IntlDateFormatter::SHORT]; <add> $format = [IntlDateFormatter::NONE, IntlDateFormatter::SHORT]; <ide> $result = $time->i18nFormat($format); <ide> $expected = '1:59 PM'; <ide> $this->assertTimeFormat($expected, $result); <ide> <ide> // Test using a specific format, timezone and locale <del> $result = $time->i18nFormat(\IntlDateFormatter::FULL, null, 'es-ES'); <add> $result = $time->i18nFormat(IntlDateFormatter::FULL, null, 'es-ES'); <ide> $expected = 'jueves, 14 de enero de 2010, 13:59:28 (GMT)'; <ide> $this->assertTimeFormat($expected, $result); <ide> <ide> // Test with custom default locale <ide> $class::setDefaultLocale('fr-FR'); <del> $result = $time->i18nFormat(\IntlDateFormatter::FULL); <add> $result = $time->i18nFormat(IntlDateFormatter::FULL); <ide> $expected = 'jeudi 14 janvier 2010 13:59:28 UTC'; <ide> $this->assertTimeFormat($expected, $result); <ide> <ide> // Test with a non-gregorian calendar in locale <del> $result = $time->i18nFormat(\IntlDateFormatter::FULL, 'Asia/Tokyo', 'ja-JP@calendar=japanese'); <add> $result = $time->i18nFormat(IntlDateFormatter::FULL, 'Asia/Tokyo', 'ja-JP@calendar=japanese'); <ide> $expected = '平成22年1月14日木曜日 22時59分28秒 日本標準時'; <ide> $this->assertTimeFormat($expected, $result); <ide> } <ide> public function testI18nFormatUsingSystemLocale(): void <ide> public function testI18nFormatWithOffsetTimezone(string $class): void <ide> { <ide> $time = new $class('2014-01-01T00:00:00+00'); <del> $result = $time->i18nFormat(\IntlDateFormatter::FULL); <add> $result = $time->i18nFormat(IntlDateFormatter::FULL); <ide> $expected = 'Wednesday January 1 2014 12:00:00 AM GMT'; <ide> $this->assertTimeFormat($expected, $result); <ide> <ide> $time = new $class('2014-01-01T00:00:00+09'); <del> $result = $time->i18nFormat(\IntlDateFormatter::FULL); <add> $result = $time->i18nFormat(IntlDateFormatter::FULL); <ide> $expected = 'Wednesday January 1 2014 12:00:00 AM GMT+09:00'; <ide> $this->assertTimeFormat($expected, $result); <ide> <ide> $time = new $class('2014-01-01T00:00:00-01:30'); <del> $result = $time->i18nFormat(\IntlDateFormatter::FULL); <add> $result = $time->i18nFormat(IntlDateFormatter::FULL); <ide> $expected = 'Wednesday January 1 2014 12:00:00 AM GMT-01:30'; <ide> $this->assertTimeFormat($expected, $result); <ide> <ide> $time = new $class('2014-01-01T00:00Z'); <del> $result = $time->i18nFormat(\IntlDateFormatter::FULL); <add> $result = $time->i18nFormat(IntlDateFormatter::FULL); <ide> $expected = 'Wednesday January 1 2014 12:00:00 AM GMT'; <ide> $this->assertTimeFormat($expected, $result); <ide> } <ide> public function testListTimezones(string $class): void <ide> $this->assertArrayHasKey('America/Argentina/Buenos_Aires', $return); <ide> $this->assertArrayHasKey('Pacific/Tahiti', $return); <ide> <del> $return = $class::listTimezones(\DateTimeZone::ASIA); <add> $return = $class::listTimezones(DateTimeZone::ASIA); <ide> $this->assertTrue(isset($return['Asia']['Asia/Bangkok'])); <ide> $this->assertArrayNotHasKey('Pacific', $return); <ide> <del> $return = $class::listTimezones(\DateTimeZone::PER_COUNTRY, 'US', false); <add> $return = $class::listTimezones(DateTimeZone::PER_COUNTRY, 'US', false); <ide> $this->assertArrayHasKey('Pacific/Honolulu', $return); <ide> $this->assertArrayNotHasKey('Asia/Bangkok', $return); <ide> } <ide> public function testToString(string $class): void <ide> { <ide> $time = new $class('2014-04-20 22:10'); <ide> $class::setDefaultLocale('fr-FR'); <del> $class::setToStringFormat(\IntlDateFormatter::FULL); <add> $class::setToStringFormat(IntlDateFormatter::FULL); <ide> $this->assertTimeFormat('dimanche 20 avril 2014 22:10:00 UTC', (string)$time); <ide> } <ide> <ide> public function testParseDateDifferentTimezone(string $class): void <ide> $class::setDefaultLocale('fr-FR'); <ide> $result = $class::parseDate('12/03/2015'); <ide> $this->assertSame('2015-03-12', $result->format('Y-m-d')); <del> $this->assertEquals(new \DateTimeZone('Europe/Paris'), $result->tz); <add> $this->assertEquals(new DateTimeZone('Europe/Paris'), $result->tz); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Log/LogTest.php <ide> */ <ide> namespace Cake\Test\TestCase\Log; <ide> <add>use BadMethodCallException; <ide> use Cake\Log\Engine\FileLog; <ide> use Cake\Log\Log; <ide> use Cake\TestSuite\TestCase; <add>use InvalidArgumentException; <add>use RuntimeException; <ide> <ide> /** <ide> * LogTest class <ide> public function testImportingLoggers(): void <ide> */ <ide> public function testImportingLoggerFailure(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> Log::setConfig('fail', []); <ide> Log::engine('fail'); <ide> } <ide> public function testNotImplementingInterface(): void <ide> { <ide> Log::setConfig('fail', ['engine' => '\stdClass']); <ide> <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> <ide> Log::engine('fail'); <ide> } <ide> public function testDrop(): void <ide> */ <ide> public function testInvalidLevel(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> Log::setConfig('myengine', ['engine' => 'File']); <ide> Log::write('invalid', 'This will not be logged'); <ide> } <ide> public function testConfigRead(): void <ide> */ <ide> public function testConfigErrorOnReconfigure(): void <ide> { <del> $this->expectException(\BadMethodCallException::class); <add> $this->expectException(BadMethodCallException::class); <ide> Log::setConfig('tests', ['engine' => 'File', 'path' => TMP]); <ide> Log::setConfig('tests', ['engine' => 'Apc']); <ide> } <ide><path>tests/TestCase/Mailer/MailerTest.php <ide> */ <ide> namespace Cake\Test\TestCase\Mailer; <ide> <add>use BadMethodCallException; <ide> use Cake\Core\Configure; <ide> use Cake\Core\Exception\CakeException; <ide> use Cake\Log\Log; <ide> use Cake\Mailer\TransportFactory; <ide> use Cake\TestSuite\TestCase; <ide> use Cake\View\Exception\MissingTemplateException; <add>use DateTime; <add>use InvalidArgumentException; <ide> use RuntimeException; <add>use stdClass; <ide> use TestApp\Mailer\TestMailer; <ide> <ide> class MailerTest extends TestCase <ide> public function testTransport(): void <ide> */ <ide> public function testTransportInvalid(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('The "Invalid" transport configuration does not exist'); <ide> $this->mailer->setTransport('Invalid'); <ide> } <ide> public function testTransportInvalid(): void <ide> public function testTransportInstanceInvalid(): void <ide> { <ide> $this->expectException(CakeException::class); <del> $this->mailer->setTransport(new \stdClass()); <add> $this->mailer->setTransport(new stdClass()); <ide> } <ide> <ide> /** <ide> * Test that using unknown transports fails. <ide> */ <ide> public function testTransportTypeInvalid(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('The value passed for the "$name" argument must be either a string, or an object, integer given.'); <ide> $this->mailer->setTransport(123); <ide> } <ide> public function testConfig(): void <ide> */ <ide> public function testConfigErrorOnDuplicate(): void <ide> { <del> $this->expectException(\BadMethodCallException::class); <add> $this->expectException(BadMethodCallException::class); <ide> $settings = [ <ide> 'to' => 'mark@example.com', <ide> 'from' => 'noreply@example.com', <ide> public function testDefaultProfile(): void <ide> */ <ide> public function testProfileInvalid(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Unknown email configuration "derp".'); <ide> $mailer = new Mailer(); <ide> $mailer->setProfile('derp'); <ide> public function testSendWithContent(): void <ide> */ <ide> public function testSendWithoutTransport(): void <ide> { <del> $this->expectException(\BadMethodCallException::class); <add> $this->expectException(BadMethodCallException::class); <ide> $this->expectExceptionMessage( <ide> 'Transport was not defined. You must set on using setTransport() or set `transport` option in your mailer profile.' <ide> ); <ide> public function testSendRenderWithHelpers(): void <ide> $this->mailer->setViewVars(['time' => $timestamp]); <ide> <ide> $result = $this->mailer->send(); <del> $dateTime = new \DateTime(); <add> $dateTime = new DateTime(); <ide> $dateTime->setTimestamp($timestamp); <ide> $this->assertStringContainsString('Right now: ' . $dateTime->format($dateTime::ATOM), $result['message']); <ide> <ide><path>tests/TestCase/Mailer/MessageTest.php <ide> use Cake\Mailer\Message; <ide> use Cake\Mailer\Transport\DebugTransport; <ide> use Cake\TestSuite\TestCase; <add>use InvalidArgumentException; <ide> use Laminas\Diactoros\UploadedFile; <ide> use TestApp\Mailer\TestMessage; <ide> <ide> public function testFrom(): void <ide> $this->assertSame($expected, $this->message->getFrom()); <ide> $this->assertSame($this->message, $result); <ide> <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $result = $this->message->setFrom(['cake@cakephp.org' => 'CakePHP', 'fail@cakephp.org' => 'From can only be one address']); <ide> } <ide> <ide> public static function invalidEmails(): array <ide> */ <ide> public function testInvalidEmail($value): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->message->setTo($value); <ide> } <ide> <ide> public function testInvalidEmail($value): void <ide> */ <ide> public function testInvalidEmailAdd($value): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->message->addTo($value); <ide> } <ide> <ide> public function testCustomEmailValidation(): void <ide> */ <ide> public function testUnsetEmailPattern(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Invalid email set for "to". You passed "fail.@example.com".'); <ide> $email = new Message(); <ide> $this->assertSame(Message::EMAIL_PATTERN, $email->getEmailPattern()); <ide> public function testUnsetEmailPattern(): void <ide> */ <ide> public function testEmptyTo(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('The email set for "to" is empty.'); <ide> $email = new Message(); <ide> $email->setTo(''); <ide> public function testPriority(): void <ide> */ <ide> public function testMessageIdInvalid(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->message->setMessageId('my-email@localhost'); <ide> } <ide> <ide> public function testSetAttachments(): void <ide> 'license' => ['file' => CORE_PATH . 'LICENSE', 'mimetype' => 'text/plain'], <ide> ]; <ide> $this->assertSame($expected, $this->message->getAttachments()); <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->message->setAttachments([['nofile' => CAKE . 'basics.php', 'mimetype' => 'text/plain']]); <ide> } <ide> <ide> public function testSetAttachmentDataNoMimetype(): void <ide> <ide> public function testSetAttachmentInvalidFile(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage( <ide> 'File must be a filepath or UploadedFileInterface instance. Found `boolean` instead.' <ide> ); <ide> public function testEmailFormat(): void <ide> $result = $this->message->getEmailFormat(); <ide> $this->assertSame('html', $result); <ide> <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->message->setEmailFormat('invalid'); <ide> } <ide> <ide> public function testTransferEncoding(): void <ide> $this->assertSame($expected, $this->message->getContentTransferEncoding()); <ide> <ide> //Test wrong encoding <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->message->setTransferEncoding('invalid'); <ide> } <ide> <ide><path>tests/TestCase/Mailer/Transport/SmtpTransportTest.php <ide> public function testConnectEhloTlsOnNonTlsServer(): void <ide> */ <ide> public function testConnectEhloNoTlsOnRequiredTlsServer(): void <ide> { <del> $this->expectException(\Cake\Network\Exception\SocketException::class); <add> $this->expectException(SocketException::class); <ide> $this->expectExceptionMessage('SMTP authentication method not allowed, check if SMTP server requires TLS.'); <ide> $this->SmtpTransport->setConfig(['tls' => false] + $this->credentials); <ide> <ide> public function testAuthLogin(): void <ide> */ <ide> public function testAuthNotRecognized(): void <ide> { <del> $this->expectException(\Cake\Network\Exception\SocketException::class); <add> $this->expectException(SocketException::class); <ide> $this->expectExceptionMessage('AUTH command not recognized or not implemented, SMTP server may not require authentication.'); <ide> <ide> $this->socket->expects($this->exactly(2)) <ide> public function testAuthNotRecognized(): void <ide> */ <ide> public function testAuthNotImplemented(): void <ide> { <del> $this->expectException(\Cake\Network\Exception\SocketException::class); <add> $this->expectException(SocketException::class); <ide> $this->expectExceptionMessage('AUTH command not recognized or not implemented, SMTP server may not require authentication.'); <ide> <ide> $this->socket->expects($this->exactly(2)) <ide> public function testAuthNotImplemented(): void <ide> */ <ide> public function testAuthBadSequence(): void <ide> { <del> $this->expectException(\Cake\Network\Exception\SocketException::class); <add> $this->expectException(SocketException::class); <ide> $this->expectExceptionMessage('SMTP Error: 503 5.5.1 Already authenticated'); <ide> <ide> $this->socket->expects($this->exactly(2)) <ide><path>tests/TestCase/Mailer/TransportFactoryTest.php <ide> */ <ide> namespace Cake\Test\TestCase\Mailer; <ide> <add>use BadMethodCallException; <ide> use Cake\Mailer\Transport\DebugTransport; <ide> use Cake\Mailer\TransportFactory; <ide> use Cake\TestSuite\TestCase; <add>use InvalidArgumentException; <ide> <ide> /** <ide> * TransportFactory Test class <ide> public function tearDown(): void <ide> */ <ide> public function testGetMissingClassName(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Transport config "debug" is invalid, the required `className` option is missing'); <ide> <ide> TransportFactory::drop('debug'); <ide> public function testSetConfigMultiple(): void <ide> */ <ide> public function testSetConfigErrorOnDuplicate(): void <ide> { <del> $this->expectException(\BadMethodCallException::class); <add> $this->expectException(BadMethodCallException::class); <ide> $settings = [ <ide> 'className' => 'Debug', <ide> 'log' => true, <ide><path>tests/TestCase/Network/SocketTest.php <ide> use Cake\Network\Exception\SocketException; <ide> use Cake\Network\Socket; <ide> use Cake\TestSuite\TestCase; <add>use InvalidArgumentException; <ide> <ide> /** <ide> * SocketTest class <ide> public static function invalidConnections(): array <ide> */ <ide> public function testInvalidConnection(array $data): void <ide> { <del> $this->expectException(\Cake\Network\Exception\SocketException::class); <add> $this->expectException(SocketException::class); <ide> $this->Socket->setConfig($data); <ide> $this->Socket->connect(); <ide> } <ide> protected function _connectSocketToSslTls(): void <ide> */ <ide> public function testEnableCryptoBadMode(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> // testing wrong encryption mode <ide> $this->_connectSocketToSslTls(); <ide> $this->Socket->enableCrypto('doesntExistMode', 'server'); <ide> public function testEnableCrypto(): void <ide> */ <ide> public function testEnableCryptoExceptionEnableTwice(): void <ide> { <del> $this->expectException(\Cake\Network\Exception\SocketException::class); <add> $this->expectException(SocketException::class); <ide> // testing on tls server <ide> $this->_connectSocketToSslTls(); <ide> $this->Socket->enableCrypto('tls', 'client'); <ide> public function testEnableCryptoExceptionEnableTwice(): void <ide> */ <ide> public function testEnableCryptoExceptionDisableTwice(): void <ide> { <del> $this->expectException(\Cake\Network\Exception\SocketException::class); <add> $this->expectException(SocketException::class); <ide> $this->_connectSocketToSslTls(); <ide> $this->Socket->enableCrypto('tls', 'client', false); <ide> } <ide><path>tests/TestCase/ORM/Association/BelongsToManyTest.php <ide> use Cake\ORM\Table; <ide> use Cake\TestSuite\TestCase; <ide> use InvalidArgumentException; <add>use RuntimeException; <ide> <ide> /** <ide> * Tests BelongsToMany class <ide> public function testRequiresKeys(): void <ide> */ <ide> public function testStrategyFailure(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Invalid strategy "join" was provided'); <ide> $assoc = new BelongsToMany('Test'); <ide> $assoc->setStrategy(BelongsToMany::STRATEGY_JOIN); <ide> public function testSaveStrategyInOptions(): void <ide> */ <ide> public function testSaveStrategyInvalid(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Invalid save strategy "depsert"'); <ide> new BelongsToMany('Test', ['saveStrategy' => 'depsert']); <ide> } <ide> public function testCascadeDeleteCallbacksRuleFailure(): void <ide> */ <ide> public function testLinkWithNotPersistedSource(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Source entity needs to be persisted before links can be created or removed'); <ide> $config = [ <ide> 'sourceTable' => $this->article, <ide> public function testLinkWithNotPersistedSource(): void <ide> */ <ide> public function testLinkWithNotPersistedTarget(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Cannot link entities that have not been persisted yet'); <ide> $config = [ <ide> 'sourceTable' => $this->article, <ide> public function testLinkSetSourceToJunctionEntities(): void <ide> */ <ide> public function testUnlinkWithNotPersistedSource(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Source entity needs to be persisted before links can be created or removed'); <ide> $config = [ <ide> 'sourceTable' => $this->article, <ide> public function testUnlinkWithNotPersistedSource(): void <ide> */ <ide> public function testUnlinkWithNotPersistedTarget(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Cannot link entities that have not been persisted'); <ide> $config = [ <ide> 'sourceTable' => $this->article, <ide> public function testUnlinkWithoutPropertyClean(): void <ide> */ <ide> public function testReplaceWithMissingPrimaryKey(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Could not find primary key value for source entity'); <ide> $config = [ <ide> 'sourceTable' => $this->article, <ide> public function testGeneratedAssociations(): void <ide> */ <ide> public function testEagerLoadingRequiresPrimaryKey(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> $this->expectExceptionMessage('The "tags" table does not define a primary key'); <ide> $table = $this->getTableLocator()->get('Articles'); <ide> $tags = $this->getTableLocator()->get('Tags'); <ide><path>tests/TestCase/ORM/Association/BelongsToTest.php <ide> use Cake\ORM\Query; <ide> use Cake\TestSuite\TestCase; <ide> use InvalidArgumentException; <add>use RuntimeException; <ide> <ide> /** <ide> * Tests BelongsTo class <ide> public function testAttachToMultiPrimaryKey(): void <ide> */ <ide> public function testAttachToMultiPrimaryKeyMismatch(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> $this->expectExceptionMessage('Cannot match provided foreignKey for "Companies", got "(company_id)" but expected foreign key for "(id, tenant_id)"'); <ide> $this->company->setPrimaryKey(['id', 'tenant_id']); <ide> $query = $this->client->query(); <ide><path>tests/TestCase/ORM/Association/HasManyTest.php <ide> public function testRequiresKeys(): void <ide> */ <ide> public function testStrategyFailure(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Invalid strategy "join" was provided'); <ide> $assoc = new HasMany('Test'); <ide> $assoc->setStrategy(HasMany::STRATEGY_JOIN); <ide> public function testEagerLoaderWithOverrides(): void <ide> */ <ide> public function testEagerLoaderFieldsException(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('You are required to select the "Articles.author_id"'); <ide> $config = [ <ide> 'sourceTable' => $this->author, <ide> public function testLinkUsesSingleTransaction(): void <ide> */ <ide> public function testSaveAssociatedNotEmptyNotIterable(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Could not save comments, it cannot be traversed'); <ide> $articles = $this->getTableLocator()->get('Articles'); <ide> $association = $articles->hasMany('Comments', [ <ide> public function testSaveAssociatedWithFailedRuleOnAssociated(): void <ide> */ <ide> public function testInvalidSaveStrategy(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $articles = $this->getTableLocator()->get('Articles'); <ide> <ide> $association = $articles->hasMany('Comments'); <ide><path>tests/TestCase/ORM/Association/HasOneTest.php <ide> */ <ide> namespace Cake\Test\TestCase\ORM\Association; <ide> <add>use ArrayObject; <ide> use Cake\Database\Expression\IdentifierExpression; <ide> use Cake\Database\Expression\QueryExpression; <ide> use Cake\Database\TypeMap; <ide> use Cake\ORM\Association\HasOne; <ide> use Cake\ORM\Entity; <ide> use Cake\TestSuite\TestCase; <add>use RuntimeException; <ide> <ide> /** <ide> * Tests HasOne class <ide> public function testAttachToMultiPrimaryKey(): void <ide> */ <ide> public function testAttachToMultiPrimaryKeyMismatch(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> $this->expectExceptionMessage('Cannot match provided foreignKey for "Profiles", got "(user_id)" but expected foreign key for "(id, site_id)"'); <ide> $query = $this->getMockBuilder('Cake\ORM\Query') <ide> ->onlyMethods(['join', 'select']) <ide> public function testAttachToBeforeFindExtraOptions(): void <ide> 'targetTable' => $this->profile, <ide> ]; <ide> $this->listenerCalled = false; <del> $opts = new \ArrayObject(['something' => 'more']); <add> $opts = new ArrayObject(['something' => 'more']); <ide> $this->profile->getEventManager()->on( <ide> 'Model.beforeFind', <ide> function ($event, $query, $options, $primary) use ($opts): void { <ide><path>tests/TestCase/ORM/AssociationCollectionTest.php <ide> public function testSaveChildrenFiltered(): void <ide> */ <ide> public function testErrorOnUnknownAlias(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Cannot save Profiles, it is not associated to Users'); <ide> $table = $this->getMockBuilder('Cake\ORM\Table') <ide> ->onlyMethods(['save']) <ide><path>tests/TestCase/ORM/AssociationProxyTest.php <ide> namespace Cake\Test\TestCase\ORM; <ide> <ide> use Cake\TestSuite\TestCase; <add>use RuntimeException; <ide> <ide> /** <ide> * Tests the features related to proxying methods from the Association <ide> public function testAssociationAsProperty(): void <ide> */ <ide> public function testGetBadAssociation(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> $this->expectExceptionMessage('You have not defined'); <ide> $articles = $this->getTableLocator()->get('articles'); <ide> $articles->posts; <ide><path>tests/TestCase/ORM/AssociationTest.php <ide> use Cake\ORM\Association; <ide> use Cake\ORM\Table; <ide> use Cake\TestSuite\TestCase; <add>use InvalidArgumentException; <add>use RuntimeException; <ide> use TestApp\Model\Table\AuthorsTable; <ide> use TestApp\Model\Table\TestTable; <ide> <ide> public function testSetNameBeforeTarget(): void <ide> */ <ide> public function testSetNameAfterTarget(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Association name "Bar" does not match target table alias'); <ide> $this->association->getTarget(); <ide> $this->association->setName('Bar'); <ide> public function testSetClassNameBeforeTarget(): void <ide> */ <ide> public function testSetClassNameAfterTarget(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('The class name "' . AuthorsTable::class . '" doesn\'t match the target table class name of'); <ide> $this->association->getTarget(); <ide> $this->association->setClassName(AuthorsTable::class); <ide> public function testSetClassNameAfterTarget(): void <ide> */ <ide> public function testSetClassNameWithShortSyntaxAfterTarget(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('The class name "Authors" doesn\'t match the target table class name of'); <ide> $this->association->getTarget(); <ide> $this->association->setClassName('Authors'); <ide> public function testClassNameUnnormalized(): void <ide> */ <ide> public function testInvalidTableFetchedFromRegistry(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> $this->getTableLocator()->get('Test'); <ide> <ide> $config = [ <ide> public function testSetStrategy(): void <ide> */ <ide> public function testInvalidStrategy(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->association->setStrategy('anotherThing'); <ide> } <ide> <ide><path>tests/TestCase/ORM/Behavior/TimestampBehaviorTest.php <ide> use Cake\ORM\Entity; <ide> use Cake\ORM\Table; <ide> use Cake\TestSuite\TestCase; <add>use DateTime as NativeDateTime; <ide> use RuntimeException; <add>use UnexpectedValueException; <ide> <ide> /** <ide> * Behavior test case <ide> public function testCreatedAbsent(): void <ide> { <ide> $table = $this->getTable(); <ide> $this->Behavior = new TimestampBehavior($table); <del> $ts = new \DateTime('2000-01-01'); <add> $ts = new NativeDateTime('2000-01-01'); <ide> $this->Behavior->timestamp($ts); <ide> <ide> $event = new Event('Model.beforeSave'); <ide> public function testCreatedPresent(): void <ide> { <ide> $table = $this->getTable(); <ide> $this->Behavior = new TimestampBehavior($table); <del> $ts = new \DateTime('2000-01-01'); <add> $ts = new NativeDateTime('2000-01-01'); <ide> $this->Behavior->timestamp($ts); <ide> <ide> $event = new Event('Model.beforeSave'); <del> $existingValue = new \DateTime('2011-11-11'); <add> $existingValue = new NativeDateTime('2011-11-11'); <ide> $entity = new Entity(['name' => 'Foo', 'created' => $existingValue]); <ide> <ide> $return = $this->Behavior->handleEvent($event, $entity); <ide> public function testCreatedNotNew(): void <ide> { <ide> $table = $this->getTable(); <ide> $this->Behavior = new TimestampBehavior($table); <del> $ts = new \DateTime('2000-01-01'); <add> $ts = new NativeDateTime('2000-01-01'); <ide> $this->Behavior->timestamp($ts); <ide> <ide> $event = new Event('Model.beforeSave'); <ide> public function testModifiedAbsent(): void <ide> { <ide> $table = $this->getTable(); <ide> $this->Behavior = new TimestampBehavior($table); <del> $ts = new \DateTime('2000-01-01'); <add> $ts = new NativeDateTime('2000-01-01'); <ide> $this->Behavior->timestamp($ts); <ide> <ide> $event = new Event('Model.beforeSave'); <ide> public function testModifiedPresent(): void <ide> { <ide> $table = $this->getTable(); <ide> $this->Behavior = new TimestampBehavior($table); <del> $ts = new \DateTime('2000-01-01'); <add> $ts = new NativeDateTime('2000-01-01'); <ide> $this->Behavior->timestamp($ts); <ide> <ide> $event = new Event('Model.beforeSave'); <del> $existingValue = new \DateTime('2011-11-11'); <add> $existingValue = new NativeDateTime('2011-11-11'); <ide> $entity = new Entity(['name' => 'Foo', 'modified' => $existingValue]); <ide> $entity->clean(); <ide> $entity->setNew(false); <ide> public function testModifiedMissingColumn(): void <ide> $table = $this->getTable(); <ide> $table->getSchema()->removeColumn('created')->removeColumn('modified'); <ide> $this->Behavior = new TimestampBehavior($table); <del> $ts = new \DateTime('2000-01-01'); <add> $ts = new NativeDateTime('2000-01-01'); <ide> $this->Behavior->timestamp($ts); <ide> <ide> $event = new Event('Model.beforeSave'); <ide> public function testNonDateTimeTypeException(): void <ide> */ <ide> public function testInvalidEventConfig(): void <ide> { <del> $this->expectException(\UnexpectedValueException::class); <add> $this->expectException(UnexpectedValueException::class); <ide> $this->expectExceptionMessage('When should be one of "always", "new" or "existing". The passed value "fat fingers" is invalid'); <ide> $table = $this->getTable(); <ide> $settings = ['events' => ['Model.beforeSave' => ['created' => 'fat fingers']]]; <ide> public function testSetTimestampExplicit(): void <ide> $table = $this->getTable(); <ide> $this->Behavior = new TimestampBehavior($table); <ide> <del> $ts = new \DateTime(); <add> $ts = new NativeDateTime(); <ide> $this->Behavior->timestamp($ts); <ide> $return = $this->Behavior->timestamp(); <ide> <ide> public function testTouch(): void <ide> { <ide> $table = $this->getTable(); <ide> $this->Behavior = new TimestampBehavior($table); <del> $ts = new \DateTime('2000-01-01'); <add> $ts = new NativeDateTime('2000-01-01'); <ide> $this->Behavior->timestamp($ts); <ide> <ide> $entity = new Entity(['username' => 'timestamp test']); <ide> public function testTouchNoop(): void <ide> ]; <ide> <ide> $this->Behavior = new TimestampBehavior($table, $config); <del> $ts = new \DateTime('2000-01-01'); <add> $ts = new NativeDateTime('2000-01-01'); <ide> $this->Behavior->timestamp($ts); <ide> <ide> $entity = new Entity(['username' => 'timestamp test']); <ide> public function testTouchCustomEvent(): void <ide> $table = $this->getTable(); <ide> $settings = ['events' => ['Something.special' => ['date_specialed' => 'always']]]; <ide> $this->Behavior = new TimestampBehavior($table, $settings); <del> $ts = new \DateTime('2000-01-01'); <add> $ts = new NativeDateTime('2000-01-01'); <ide> $this->Behavior->timestamp($ts); <ide> <ide> $entity = new Entity(['username' => 'timestamp test']); <ide><path>tests/TestCase/ORM/Behavior/TranslateBehaviorShadowTableTest.php <ide> use Cake\ORM\Behavior\Translate\ShadowTableStrategy; <ide> use Cake\ORM\Behavior\TranslateBehavior; <ide> use Cake\Utility\Hash; <add>use Cake\Validation\Validator; <ide> use TestApp\Model\Entity\TranslateArticle; <ide> use TestApp\Model\Entity\TranslateBakedArticle; <ide> <ide> public function testSaveNewRecordWithTranslatesField(): void <ide> $table = $this->getTableLocator()->get('Articles'); <ide> $table->addBehavior('Translate', [ <ide> 'fields' => ['title'], <del> 'validator' => (new \Cake\Validation\Validator())->add('title', 'notBlank', ['rule' => 'notBlank']), <add> 'validator' => (new Validator())->add('title', 'notBlank', ['rule' => 'notBlank']), <ide> ]); <ide> $table->setEntityClass(TranslateArticle::class); <ide> <ide><path>tests/TestCase/ORM/Behavior/TranslateBehaviorTest.php <ide> public function testSaveNewRecordWithTranslatesField(): void <ide> $table = $this->getTableLocator()->get('Articles'); <ide> $table->addBehavior('Translate', [ <ide> 'fields' => ['title'], <del> 'validator' => (new \Cake\Validation\Validator())->add('title', 'notBlank', ['rule' => 'notBlank']), <add> 'validator' => (new Validator())->add('title', 'notBlank', ['rule' => 'notBlank']), <ide> ]); <ide> $table->setEntityClass(TranslateArticle::class); <ide> <ide> public function testSaveNewRecordWithOnlyTranslationsNotDefaultLocale(): void <ide> $table = $this->getTableLocator()->get('Sections'); <ide> $table->addBehavior('Translate', [ <ide> 'fields' => ['title'], <del> 'validator' => (new \Cake\Validation\Validator())->add('title', 'notBlank', ['rule' => 'notBlank']), <add> 'validator' => (new Validator())->add('title', 'notBlank', ['rule' => 'notBlank']), <ide> ]); <ide> <ide> $data = [ <ide><path>tests/TestCase/ORM/Behavior/TreeBehaviorTest.php <ide> */ <ide> namespace Cake\Test\TestCase\ORM\Behavior; <ide> <add>use Cake\Datasource\Exception\RecordNotFoundException; <ide> use Cake\ORM\Entity; <ide> use Cake\TestSuite\TestCase; <add>use RuntimeException; <ide> <ide> /** <ide> * Translate behavior test case <ide> public function testScopeNull(): void <ide> */ <ide> public function testFindChildrenException(): void <ide> { <del> $this->expectException(\Cake\Datasource\Exception\RecordNotFoundException::class); <add> $this->expectException(RecordNotFoundException::class); <ide> $table = $this->getTableLocator()->get('MenuLinkTrees'); <ide> $table->addBehavior('Tree', ['scope' => ['menu' => 'main-menu']]); <ide> $query = $table->find('children', ['for' => 500]); <ide> public function testAddRoot(): void <ide> */ <ide> public function testReParentSelf(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> $this->expectExceptionMessage('Cannot set a node\'s parent as itself'); <ide> $entity = $this->table->get(1); <ide> $entity->parent_id = $entity->id; <ide> public function testReParentSelf(): void <ide> */ <ide> public function testReParentSelfNewEntity(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> $this->expectExceptionMessage('Cannot set a node\'s parent as itself'); <ide> $entity = $this->table->newEntity(['name' => 'root']); <ide> $entity->id = 1; <ide> public function testRootingNoTreeColumns(): void <ide> */ <ide> public function testReparentCycle(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> $this->expectExceptionMessage('Cannot use node "5" as parent for entity "2"'); <ide> $table = $this->table; <ide> $entity = $table->get(2); <ide><path>tests/TestCase/ORM/BehaviorRegistryTest.php <ide> */ <ide> namespace Cake\Test\TestCase\ORM; <ide> <add>use BadMethodCallException; <ide> use Cake\ORM\BehaviorRegistry; <add>use Cake\ORM\Exception\MissingBehaviorException; <ide> use Cake\ORM\Query; <ide> use Cake\ORM\Table; <ide> use Cake\TestSuite\TestCase; <add>use LogicException; <ide> <ide> /** <ide> * Test case for BehaviorRegistry. <ide> public function testLoadPlugin(): void <ide> */ <ide> public function testLoadMissingClass(): void <ide> { <del> $this->expectException(\Cake\ORM\Exception\MissingBehaviorException::class); <add> $this->expectException(MissingBehaviorException::class); <ide> $this->Behaviors->load('DoesNotExist'); <ide> } <ide> <ide> public function testLoadMissingClass(): void <ide> */ <ide> public function testLoadDuplicateMethodError(): void <ide> { <del> $this->expectException(\LogicException::class); <add> $this->expectException(LogicException::class); <ide> $this->expectExceptionMessage('TestApp\Model\Behavior\DuplicateBehavior contains duplicate method "slugify"'); <ide> $this->Behaviors->load('Sluggable'); <ide> $this->Behaviors->load('Duplicate'); <ide> public function testLoadDuplicateMethodAliasing(): void <ide> */ <ide> public function testLoadDuplicateFinderError(): void <ide> { <del> $this->expectException(\LogicException::class); <add> $this->expectException(LogicException::class); <ide> $this->expectExceptionMessage('TestApp\Model\Behavior\DuplicateBehavior contains duplicate finder "children"'); <ide> $this->Behaviors->load('Tree'); <ide> $this->Behaviors->load('Duplicate'); <ide> public function testCall(): void <ide> */ <ide> public function testCallError(): void <ide> { <del> $this->expectException(\BadMethodCallException::class); <add> $this->expectException(BadMethodCallException::class); <ide> $this->expectExceptionMessage('Cannot call "nope"'); <ide> $this->Behaviors->load('Sluggable'); <ide> $this->Behaviors->call('nope'); <ide> public function testCallFinder(): void <ide> */ <ide> public function testCallFinderError(): void <ide> { <del> $this->expectException(\BadMethodCallException::class); <add> $this->expectException(BadMethodCallException::class); <ide> $this->expectExceptionMessage('Cannot call finder "nope"'); <ide> $this->Behaviors->load('Sluggable'); <ide> $this->Behaviors->callFinder('nope'); <ide> public function testCallFinderError(): void <ide> */ <ide> public function testUnloadBehaviorThenCall(): void <ide> { <del> $this->expectException(\BadMethodCallException::class); <add> $this->expectException(BadMethodCallException::class); <ide> $this->expectExceptionMessage('Cannot call "slugify" it does not belong to any attached behavior.'); <ide> $this->Behaviors->load('Sluggable'); <ide> $this->Behaviors->unload('Sluggable'); <ide> public function testUnloadBehaviorThenCall(): void <ide> */ <ide> public function testUnloadBehaviorThenCallFinder(): void <ide> { <del> $this->expectException(\BadMethodCallException::class); <add> $this->expectException(BadMethodCallException::class); <ide> $this->expectExceptionMessage('Cannot call finder "noslug" it does not belong to any attached behavior.'); <ide> $this->Behaviors->load('Sluggable'); <ide> $this->Behaviors->unload('Sluggable'); <ide> public function testUnload(): void <ide> */ <ide> public function testUnloadUnknown(): void <ide> { <del> $this->expectException(\Cake\ORM\Exception\MissingBehaviorException::class); <add> $this->expectException(MissingBehaviorException::class); <ide> $this->expectExceptionMessage('Behavior class FooBehavior could not be found.'); <ide> $this->Behaviors->unload('Foo'); <ide> } <ide><path>tests/TestCase/ORM/CompositeKeysTest.php <ide> use Cake\Database\Driver\Sqlite; <ide> use Cake\Database\Driver\Sqlserver; <ide> use Cake\Datasource\ConnectionManager; <add>use Cake\Datasource\ResultSetDecorator; <ide> use Cake\ORM\Entity; <ide> use Cake\ORM\Marshaller; <ide> use Cake\ORM\Query; <ide> use Cake\ORM\Table; <ide> use Cake\TestSuite\TestCase; <ide> use PDO; <add>use RuntimeException; <ide> use TestApp\Model\Entity\OpenArticleEntity; <ide> <ide> /** <ide> public function strategiesProviderBelongsToMany(): array <ide> */ <ide> public function testSaveNewErrorCompositeKeyNoIncrement(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> $this->expectExceptionMessage('Cannot insert row, some of the primary key values are missing'); <ide> $articles = $this->getTableLocator()->get('SiteArticles'); <ide> $article = $articles->newEntity(['site_id' => 1, 'author_id' => 1, 'title' => 'testing']); <ide> public function testSaveNewEntity(): void <ide> */ <ide> public function testSaveNewEntityMissingKey(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> $this->expectExceptionMessage('Cannot insert row, some of the primary key values are missing. Got (5, ), expecting (id, site_id)'); <ide> $entity = new Entity([ <ide> 'id' => 5, <ide> public function testFindThreadedCompositeKeys(): void <ide> ->setConstructorArgs([$table->getConnection(), $table]) <ide> ->getMock(); <ide> <del> $items = new \Cake\Datasource\ResultSetDecorator([ <add> $items = new ResultSetDecorator([ <ide> ['id' => 1, 'name' => 'a', 'site_id' => 1, 'parent_id' => null], <ide> ['id' => 2, 'name' => 'a', 'site_id' => 2, 'parent_id' => null], <ide> ['id' => 3, 'name' => 'a', 'site_id' => 1, 'parent_id' => 1], <ide><path>tests/TestCase/ORM/EntityTest.php <ide> <ide> use Cake\ORM\Entity; <ide> use Cake\TestSuite\TestCase; <add>use InvalidArgumentException; <add>use stdClass; <ide> use TestApp\Model\Entity\Extending; <ide> use TestApp\Model\Entity\NonExtending; <ide> <ide> public function emptyNamesProvider(): array <ide> */ <ide> public function testEmptyProperties(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $entity = new Entity(); <ide> $entity->get(''); <ide> } <ide> public function testIsEmpty(): void <ide> $entity = new Entity([ <ide> 'array' => ['foo' => 'bar'], <ide> 'emptyArray' => [], <del> 'object' => new \stdClass(), <add> 'object' => new stdClass(), <ide> 'string' => 'string', <ide> 'stringZero' => '0', <ide> 'emptyString' => '', <ide> public function testHasValue(): void <ide> $entity = new Entity([ <ide> 'array' => ['foo' => 'bar'], <ide> 'emptyArray' => [], <del> 'object' => new \stdClass(), <add> 'object' => new stdClass(), <ide> 'string' => 'string', <ide> 'stringZero' => '0', <ide> 'emptyString' => '', <ide><path>tests/TestCase/ORM/Locator/TableLocatorTest.php <ide> use Cake\ORM\Table; <ide> use Cake\TestSuite\TestCase; <ide> use Cake\Validation\Validator; <add>use RuntimeException; <ide> use TestApp\Infrastructure\Table\AddressesTable; <ide> use TestApp\Model\Table\ArticlesTable; <ide> use TestApp\Model\Table\MyUsersTable; <ide> public function testConfigOnDefinedInstance(): void <ide> $users = $this->_locator->get('Users'); <ide> $this->assertNotEmpty($users); <ide> <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> $this->expectExceptionMessage('You cannot configure "Users", it has already been constructed.'); <ide> <ide> $this->_locator->setConfig('Users', ['table' => 'my_users']); <ide> public function testGetExistingWithConfigData(): void <ide> $users = $this->_locator->get('Users'); <ide> $this->assertNotEmpty($users); <ide> <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> $this->expectExceptionMessage('You cannot configure "Users", it already exists in the registry.'); <ide> <ide> $this->_locator->get('Users', ['table' => 'my_users']); <ide><path>tests/TestCase/ORM/MarshallerTest.php <ide> use Cake\ORM\Marshaller; <ide> use Cake\TestSuite\TestCase; <ide> use Cake\Validation\Validator; <add>use InvalidArgumentException; <add>use RuntimeException; <ide> use TestApp\Model\Entity\OpenArticleEntity; <ide> use TestApp\Model\Entity\OpenTag; <ide> use TestApp\Model\Entity\ProtectedArticle; <ide> public function testOneAccessibleFieldsOption(): void <ide> */ <ide> public function testOneInvalidAssociation(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Cannot marshal data for "Derp" association. It is not associated with "Articles".'); <ide> $data = [ <ide> 'title' => 'My title', <ide> public function testManyAssociations(): void <ide> */ <ide> public function testManyInvalidAssociation(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $data = [ <ide> [ <ide> 'comment' => 'First post', <ide> public function testMergeWhitelist(): void <ide> */ <ide> public function testMergeInvalidAssociation(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Cannot marshal data for "Derp" association. It is not associated with "Articles".'); <ide> $data = [ <ide> 'title' => 'My title', <ide> public function testValidationFail(): void <ide> */ <ide> public function testValidateInvalidType(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> $data = ['title' => 'foo']; <ide> $marshaller = new Marshaller($this->articles); <ide> $marshaller->one($data, [ <ide> public function testEnsurePrimaryKeyBeingReadFromTableWhenLoadingBelongsToManyRe <ide> */ <ide> public function testInvalidTypesWhenLoadingAssociatedByIds(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Cannot convert value of type `string` to integer'); <ide> <ide> $data = [ <ide> public function testInvalidTypesWhenLoadingAssociatedByIds(): void <ide> */ <ide> public function testInvalidTypesWhenLoadingAssociatedByCompositeIds(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Cannot convert value of type `string` to integer'); <ide> <ide> $data = [ <ide><path>tests/TestCase/ORM/QueryRegressionTest.php <ide> */ <ide> namespace Cake\Test\TestCase\ORM; <ide> <add>use Cake\Database\Driver\Sqlserver; <ide> use Cake\Database\Expression\ComparisonExpression; <ide> use Cake\Database\Expression\QueryExpression; <ide> use Cake\Datasource\EntityInterface; <ide> use Cake\Event\EventInterface; <ide> use Cake\I18n\FrozenTime; <add>use Cake\ORM\Entity; <ide> use Cake\ORM\Query; <ide> use Cake\TestSuite\TestCase; <add>use DateTime as NativeDateTime; <add>use InvalidArgumentException; <add>use RuntimeException; <ide> <ide> /** <ide> * Contains regression test for the Query builder <ide> public function testEagerLoadingBelongsToManyList(): void <ide> 'finder' => 'list', <ide> ]); <ide> <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> $this->expectExceptionMessage('"_joinData" is missing from the belongsToMany results'); <ide> $table->find()->contain('Tags')->toArray(); <ide> } <ide> public function testDeepHasManyEitherStrategy(): void <ide> $tags = $this->getTableLocator()->get('Tags'); <ide> <ide> $this->skipIf( <del> $tags->getConnection()->getDriver() instanceof \Cake\Database\Driver\Sqlserver, <add> $tags->getConnection()->getDriver() instanceof Sqlserver, <ide> 'SQL server is temporarily weird in this test, will investigate later' <ide> ); <ide> $tags = $this->getTableLocator()->get('Tags'); <ide> public function testFindMatchingOverwrite2(): void <ide> */ <ide> public function testQueryNotFatalError(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->loadFixtures('Comments'); <ide> $comments = $this->getTableLocator()->get('Comments'); <ide> $comments->find()->contain('Deprs')->all(); <ide> public function testComplexTypesInJoinedWhere(): void <ide> $query = $table->find() <ide> ->contain('Comments') <ide> ->where([ <del> 'Comments.updated >' => new \DateTime('2007-03-18 10:55:00'), <add> 'Comments.updated >' => new NativeDateTime('2007-03-18 10:55:00'), <ide> ]); <ide> <ide> $result = $query->first(); <ide> public function testComplexNestedTypesInJoinedWhere(): void <ide> $query = $table->find() <ide> ->contain('Comments.Articles.Authors') <ide> ->where([ <del> 'Authors.created >' => new \DateTime('2007-03-17 01:16:00'), <add> 'Authors.created >' => new NativeDateTime('2007-03-17 01:16:00'), <ide> ]); <ide> <ide> $result = $query->first(); <ide> public function testComplexTypesInJoinedWhereWithMatching(): void <ide> $query = $table->find() <ide> ->matching('Comments') <ide> ->where([ <del> 'Comments.updated >' => new \DateTime('2007-03-18 10:55:00'), <add> 'Comments.updated >' => new NativeDateTime('2007-03-18 10:55:00'), <ide> ]); <ide> <ide> $result = $query->first(); <ide> public function testComplexTypesInJoinedWhereWithMatching(): void <ide> $query = $table->find() <ide> ->matching('Comments.Articles.Authors') <ide> ->where([ <del> 'Authors.created >' => new \DateTime('2007-03-17 01:16:00'), <add> 'Authors.created >' => new NativeDateTime('2007-03-17 01:16:00'), <ide> ]); <ide> <ide> $result = $query->first(); <ide> public function testComplexTypesInJoinedWhereWithNotMatching(): void <ide> return $q ->where(['ArticlesTags.tag_id !=' => 3 ]); <ide> }) <ide> ->where([ <del> 'Tags.created <' => new \DateTime('2016-01-02 00:00:00'), <add> 'Tags.created <' => new NativeDateTime('2016-01-02 00:00:00'), <ide> ]); <ide> <ide> $result = $query->first(); <ide> public function testComplexTypesInJoinedWhereWithInnerJoinWith(): void <ide> $query = $table->find() <ide> ->innerJoinWith('Comments') <ide> ->where([ <del> 'Comments.updated >' => new \DateTime('2007-03-18 10:55:00'), <add> 'Comments.updated >' => new NativeDateTime('2007-03-18 10:55:00'), <ide> ]); <ide> <ide> $result = $query->first(); <ide> public function testComplexTypesInJoinedWhereWithInnerJoinWith(): void <ide> $query = $table->find() <ide> ->innerJoinWith('Comments.Articles.Authors') <ide> ->where([ <del> 'Authors.created >' => new \DateTime('2007-03-17 01:16:00'), <add> 'Authors.created >' => new NativeDateTime('2007-03-17 01:16:00'), <ide> ]); <ide> <ide> $result = $query->first(); <ide> public function testComplexTypesInJoinedWhereWithLeftJoinWith(): void <ide> $query = $table->find() <ide> ->leftJoinWith('Comments') <ide> ->where([ <del> 'Comments.updated >' => new \DateTime('2007-03-18 10:55:00'), <add> 'Comments.updated >' => new NativeDateTime('2007-03-18 10:55:00'), <ide> ]); <ide> <ide> $result = $query->first(); <ide> public function testComplexTypesInJoinedWhereWithLeftJoinWith(): void <ide> $query = $table->find() <ide> ->leftJoinWith('Comments.Articles.Authors') <ide> ->where([ <del> 'Authors.created >' => new \DateTime('2007-03-17 01:16:00'), <add> 'Authors.created >' => new NativeDateTime('2007-03-17 01:16:00'), <ide> ]); <ide> <ide> $result = $query->first(); <ide> public function testFormatDeepDistantAssociationRecords2(): void <ide> <ide> $tags->getTarget()->getEventManager()->on('Model.beforeFind', function ($e, $query) { <ide> return $query->formatResults(function ($results) { <del> return $results->map(function (\Cake\ORM\Entity $tag) { <add> return $results->map(function (Entity $tag) { <ide> $tag->name .= ' - visited'; <ide> <ide> return $tag; <ide><path>tests/TestCase/ORM/QueryTest.php <ide> */ <ide> namespace Cake\Test\TestCase\ORM; <ide> <add>use Cake\Cache\Engine\FileEngine; <ide> use Cake\Collection\Collection; <ide> use Cake\Collection\Iterator\BufferedIterator; <ide> use Cake\Database\Driver\Mysql; <ide> use Cake\ORM\Query; <ide> use Cake\ORM\ResultSet; <ide> use Cake\TestSuite\TestCase; <add>use InvalidArgumentException; <ide> use ReflectionProperty; <ide> use RuntimeException; <ide> <ide> public function testCollectionProxyBadMethod(): void <ide> */ <ide> public function testCacheErrorOnNonSelect(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> $table = $this->getTableLocator()->get('articles', ['table' => 'articles']); <ide> $query = new Query($this->connection, $table); <ide> $query->insert(['test']); <ide> public function testCacheIntegrationWithFormatResults(): void <ide> { <ide> $table = $this->getTableLocator()->get('Articles'); <ide> $query = new Query($this->connection, $table); <del> $cacher = new \Cake\Cache\Engine\FileEngine(); <add> $cacher = new FileEngine(); <ide> $cacher->init(); <ide> <ide> $query <ide> public function testContainSecondSignature(): void <ide> */ <ide> public function testContainWithQueryBuilderHasManyError(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> $table = $this->getTableLocator()->get('Authors'); <ide> $table->hasMany('Articles'); <ide> $query = new Query($this->connection, $table); <ide> public function testLeftJoinWithAndContainOnOptionalAssociation(): void <ide> ], <ide> ]; <ide> $this->assertEquals($expected, $results->toList()); <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('The `Tags` association is not defined on `Articles`.'); <ide> $table <ide> ->find() <ide><path>tests/TestCase/ORM/Rule/LinkConstraintTest.php <ide> use Cake\ORM\Rule\LinkConstraint; <ide> use Cake\ORM\RulesChecker; <ide> use Cake\TestSuite\TestCase; <add>use InvalidArgumentException; <add>use RuntimeException; <add>use stdClass; <ide> <ide> /** <ide> * Tests the LinkConstraint rule. <ide> public function testInvalidConstructorArgumentOne($value, $actualType): void <ide> */ <ide> public function testInvalidConstructorArgumentTwo(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Argument 2 is expected to match one of the `\Cake\ORM\Rule\LinkConstraint::STATUS_*` constants.'); <ide> <ide> new LinkConstraint('Association', 'invalid'); <ide> public function testInvalidConstructorArgumentTwo(): void <ide> */ <ide> public function testNonExistentAssociation(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('The `NonExistent` association is not defined on `Articles`.'); <ide> <ide> $Articles = $this->getTableLocator()->get('Articles'); <ide> public function testNonExistentAssociation(): void <ide> */ <ide> public function testMissingPrimaryKeyValues(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> $this->expectExceptionMessage( <ide> 'LinkConstraint rule on `Articles` requires all primary key values for building the counting ' . <ide> 'conditions, expected values for `(id, nonexistent)`, got `(1, )`.' <ide> public function testMissingPrimaryKeyValues(): void <ide> */ <ide> public function testNonMatchingKeyFields(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage( <ide> 'The number of fields is expected to match the number of values, got 0 field(s) and 1 value(s).' <ide> ); <ide> public function invalidRepositoryOptionsDataProvider(): array <ide> { <ide> return [ <ide> [['repository' => null]], <del> [['repository' => new \stdClass()]], <add> [['repository' => new stdClass()]], <ide> [[]], <ide> ]; <ide> } <ide> public function invalidRepositoryOptionsDataProvider(): array <ide> */ <ide> public function testInvalidRepository($options): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Argument 2 is expected to have a `repository` key that holds an instance of `\Cake\ORM\Table`'); <ide> <ide> $Articles = $this->getMockForModel('Articles', ['buildRules'], ['table' => 'articles']); <ide><path>tests/TestCase/ORM/RulesCheckerIntegrationTest.php <ide> */ <ide> namespace Cake\Test\TestCase\ORM; <ide> <add>use ArrayObject; <ide> use Cake\Database\Driver\Sqlserver; <ide> use Cake\Datasource\ConnectionManager; <ide> use Cake\Datasource\EntityInterface; <ide> use Cake\ORM\RulesChecker; <ide> use Cake\ORM\Table; <ide> use Cake\TestSuite\TestCase; <add>use Closure; <add>use RuntimeException; <add>use stdClass; <ide> <ide> /** <ide> * Tests the integration between the ORM and the domain checker <ide> public function testExistsInWithBindingKey(): void <ide> */ <ide> public function testExistsInInvalidAssociation(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> $this->expectExceptionMessage('ExistsIn rule for \'author_id\' is invalid. \'NotValid\' is not associated with \'Cake\ORM\Table\'.'); <ide> $entity = new Entity([ <ide> 'title' => 'An Article', <ide> public function testUseBeforeRules(): void <ide> <ide> $table->getEventManager()->on( <ide> 'Model.beforeRules', <del> function (EventInterface $event, EntityInterface $entity, \ArrayObject $options, $operation) { <add> function (EventInterface $event, EntityInterface $entity, ArrayObject $options, $operation) { <ide> $this->assertEquals( <ide> [ <ide> 'atomic' => true, <ide> public function testUseAfterRules(): void <ide> <ide> $table->getEventManager()->on( <ide> 'Model.afterRules', <del> function (EventInterface $event, EntityInterface $entity, \ArrayObject $options, $result, $operation) { <add> function (EventInterface $event, EntityInterface $entity, ArrayObject $options, $result, $operation) { <ide> $this->assertEquals( <ide> [ <ide> 'atomic' => true, <ide> public function testCountOfAssociatedItems(): void <ide> $entity->tags = null; <ide> $this->assertFalse($table->save($entity)); <ide> <del> $entity->tags = new \stdClass(); <add> $entity->tags = new stdClass(); <ide> $this->assertFalse($table->save($entity)); <ide> <ide> $entity->tags = 'string'; <ide> public function testIsLinkedToMessageWithoutI18n(): void <ide> /** @var \Cake\ORM\RulesChecker $rulesChecker */ <ide> $rulesChecker = $Comments->rulesChecker(); <ide> <del> \Closure::bind( <add> Closure::bind( <ide> function () use ($rulesChecker): void { <ide> $rulesChecker->{'_useI18n'} = false; <ide> }, <ide> public function testIsNotLinkedToMessageWithoutI18n(): void <ide> /** @var \Cake\ORM\RulesChecker $rulesChecker */ <ide> $rulesChecker = $Comments->rulesChecker(); <ide> <del> \Closure::bind( <add> Closure::bind( <ide> function () use ($rulesChecker): void { <ide> $rulesChecker->{'_useI18n'} = false; <ide> }, <ide><path>tests/TestCase/ORM/SaveOptionsBuilderTest.php <ide> use Cake\ORM\SaveOptionsBuilder; <ide> use Cake\ORM\Table; <ide> use Cake\TestSuite\TestCase; <add>use RuntimeException; <ide> <ide> /** <ide> * SaveOptionsBuilder test case. <ide> public function testAssociatedChecks(): void <ide> 'Comments.DoesNotExist' <ide> ); <ide> $this->fail('No \RuntimeException throw for invalid association!'); <del> } catch (\RuntimeException $e) { <add> } catch (RuntimeException $e) { <ide> } <ide> <ide> $expected = [ <ide><path>tests/TestCase/ORM/TableRegressionTest.php <ide> */ <ide> namespace Cake\Test\TestCase\ORM; <ide> <add>use Cake\ORM\Exception\RolledbackTransactionException; <ide> use Cake\TestSuite\TestCase; <ide> use InvalidArgumentException; <ide> <ide> class TableRegressionTest extends TestCase <ide> */ <ide> public function testAfterSaveRollbackTransaction(): void <ide> { <del> $this->expectException(\Cake\ORM\Exception\RolledbackTransactionException::class); <add> $this->expectException(RolledbackTransactionException::class); <ide> $table = $this->getTableLocator()->get('Authors'); <ide> $table->getEventManager()->on( <ide> 'Model.afterSave', <ide><path>tests/TestCase/ORM/TableTest.php <ide> namespace Cake\Test\TestCase\ORM; <ide> <ide> use ArrayObject; <add>use BadMethodCallException; <ide> use Cake\Collection\Collection; <add>use Cake\Database\Driver\Sqlserver; <ide> use Cake\Database\Exception\DatabaseException; <ide> use Cake\Database\Expression\QueryExpression; <ide> use Cake\Database\Schema\TableSchema; <ide> use Cake\Database\StatementInterface; <ide> use Cake\Database\TypeMap; <ide> use Cake\Datasource\ConnectionManager; <ide> use Cake\Datasource\EntityInterface; <add>use Cake\Datasource\Exception\InvalidPrimaryKeyException; <add>use Cake\Datasource\Exception\RecordNotFoundException; <ide> use Cake\Event\EventInterface; <ide> use Cake\Event\EventManager; <ide> use Cake\I18n\FrozenTime; <ide> use Cake\ORM\Association\HasOne; <ide> use Cake\ORM\AssociationCollection; <ide> use Cake\ORM\Entity; <add>use Cake\ORM\Exception\MissingBehaviorException; <add>use Cake\ORM\Exception\MissingEntityException; <ide> use Cake\ORM\Exception\PersistenceFailedException; <ide> use Cake\ORM\Query; <ide> use Cake\ORM\RulesChecker; <ide> use Cake\TestSuite\TestCase; <ide> use Cake\Utility\Hash; <ide> use Cake\Validation\Validator; <add>use Exception; <ide> use InvalidArgumentException; <add>use PDOException; <ide> use RuntimeException; <ide> use TestApp\Model\Entity\ProtectedEntity; <add>use TestApp\Model\Entity\Tag; <ide> use TestApp\Model\Entity\VirtualUser; <ide> use TestApp\Model\Table\ArticlesTable; <ide> use TestApp\Model\Table\UsersTable; <ide> class_alias($class, 'MyPlugin\Model\Entity\SuperUser'); <ide> */ <ide> public function testTableClassNonExistent(): void <ide> { <del> $this->expectException(\Cake\ORM\Exception\MissingEntityException::class); <add> $this->expectException(MissingEntityException::class); <ide> $this->expectExceptionMessage('Entity class FooUser could not be found.'); <ide> $table = new Table(); <ide> $table->setEntityClass('FooUser'); <ide> public function testTableClassNonExistent(): void <ide> */ <ide> public function testTableClassConventionForAPP(): void <ide> { <del> $table = new \TestApp\Model\Table\ArticlesTable(); <add> $table = new ArticlesTable(); <ide> $this->assertSame('TestApp\Model\Entity\Article', $table->getEntityClass()); <ide> } <ide> <ide> public function testSetEntityClass(): void <ide> */ <ide> public function testReciprocalBelongsToLoading(): void <ide> { <del> $table = new \TestApp\Model\Table\ArticlesTable([ <add> $table = new ArticlesTable([ <ide> 'connection' => $this->connection, <ide> ]); <ide> $result = $table->find('all')->contain(['Authors'])->first(); <ide> public function testReciprocalBelongsToLoading(): void <ide> */ <ide> public function testReciprocalHasManyLoading(): void <ide> { <del> $table = new \TestApp\Model\Table\ArticlesTable([ <add> $table = new ArticlesTable([ <ide> 'connection' => $this->connection, <ide> ]); <ide> $result = $table->find('all')->contain(['Authors' => ['articles']])->first(); <ide> public function testReciprocalHasManyLoading(): void <ide> */ <ide> public function testReciprocalBelongsToMany(): void <ide> { <del> $table = new \TestApp\Model\Table\ArticlesTable([ <add> $table = new ArticlesTable([ <ide> 'connection' => $this->connection, <ide> ]); <ide> $result = $table->find('all')->contain(['Tags'])->first(); <ide> public function testReciprocalBelongsToMany(): void <ide> */ <ide> public function testFindCleanEntities(): void <ide> { <del> $table = new \TestApp\Model\Table\ArticlesTable([ <add> $table = new ArticlesTable([ <ide> 'connection' => $this->connection, <ide> ]); <ide> $results = $table->find('all')->contain(['Tags', 'Authors'])->toArray(); <ide> public function testFindCleanEntities(): void <ide> */ <ide> public function testFindPersistedEntities(): void <ide> { <del> $table = new \TestApp\Model\Table\ArticlesTable([ <add> $table = new ArticlesTable([ <ide> 'connection' => $this->connection, <ide> ]); <ide> $results = $table->find('all')->contain(['Tags', 'Authors'])->toArray(); <ide> public function testAddBehaviorDuplicate(): void <ide> try { <ide> $table->addBehavior('Sluggable', ['thing' => 'thing']); <ide> $this->fail('No exception raised'); <del> } catch (\RuntimeException $e) { <add> } catch (RuntimeException $e) { <ide> $this->assertStringContainsString('The "Sluggable" alias has already been loaded', $e->getMessage()); <ide> } <ide> } <ide> public function testGetBehaviorThrowsExceptionForMissingBehavior(): void <ide> */ <ide> public function testAddBehaviorMissing(): void <ide> { <del> $this->expectException(\Cake\ORM\Exception\MissingBehaviorException::class); <add> $this->expectException(MissingBehaviorException::class); <ide> $table = $this->getTableLocator()->get('article'); <ide> $this->assertNull($table->addBehavior('NopeNotThere')); <ide> } <ide> public function testAfterSaveCommitTriggeredOnlyForPrimaryTable(): void <ide> */ <ide> public function testSaveNewErrorOnNoPrimaryKey(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> $this->expectExceptionMessage('Cannot insert row in "users" table, it has no primary key'); <ide> $entity = new Entity(['username' => 'superuser']); <ide> $table = $this->getTableLocator()->get('users', [ <ide> public function testAtomicSave(): void <ide> */ <ide> public function testAtomicSaveRollback(): void <ide> { <del> $this->expectException(\PDOException::class); <add> $this->expectException(PDOException::class); <ide> $connection = $this->getMockBuilder('Cake\Database\Connection') <ide> ->onlyMethods(['begin', 'rollback']) <ide> ->setConstructorArgs([ConnectionManager::getConfig('test')]) <ide> public function testAtomicSaveRollback(): void <ide> $connection->expects($this->once())->method('begin'); <ide> $connection->expects($this->once())->method('rollback'); <ide> $query->expects($this->once())->method('execute') <del> ->will($this->throwException(new \PDOException())); <add> ->will($this->throwException(new PDOException())); <ide> <ide> $data = new Entity([ <ide> 'username' => 'superuser', <ide> public function testUpdateDirtyNoActualChanges(): void <ide> */ <ide> public function testUpdateNoPrimaryButOtherKeys(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> /** @var \Cake\ORM\Table|\PHPUnit\Framework\MockObject\MockObject $table */ <ide> $table = $this->getMockBuilder(Table::class) <ide> ->onlyMethods(['query']) <ide> public function testSaveManyFailedWithException(): void <ide> <ide> $table->getEventManager()->on('Model.beforeSave', function (EventInterface $event, EntityInterface $entity): void { <ide> if ($entity->name === 'jose') { <del> throw new \Exception('Oh noes'); <add> throw new Exception('Oh noes'); <ide> } <ide> }); <ide> <del> $this->expectException(\Exception::class); <add> $this->expectException(Exception::class); <ide> <ide> try { <ide> $table->saveMany($entities); <ide> public function testDeleteBelongsToManyDependentFailure(): void <ide> public function testDeleteCallbacks(): void <ide> { <ide> $entity = new Entity(['id' => 1, 'name' => 'mark']); <del> $options = new \ArrayObject(['atomic' => true, 'checkRules' => false, '_primary' => true]); <add> $options = new ArrayObject(['atomic' => true, 'checkRules' => false, '_primary' => true]); <ide> <ide> $mock = $this->getMockBuilder('Cake\Event\EventManager')->getMock(); <ide> <ide> public function testDeleteCallbacksNonAtomic(): void <ide> $table = $this->getTableLocator()->get('users'); <ide> <ide> $data = $table->get(1); <del> $options = new \ArrayObject(['atomic' => false, 'checkRules' => false]); <add> $options = new ArrayObject(['atomic' => false, 'checkRules' => false]); <ide> <ide> $called = false; <ide> $listener = function ($e, $entity, $options) use ($data, &$called): void { <ide> public function testAfterDeleteCommitTriggeredOnlyForPrimaryTable(): void <ide> public function testDeleteBeforeDeleteAbort(): void <ide> { <ide> $entity = new Entity(['id' => 1, 'name' => 'mark']); <del> $options = new \ArrayObject(['atomic' => true, 'cascade' => true]); <add> $options = new ArrayObject(['atomic' => true, 'cascade' => true]); <ide> <ide> $mock = $this->getMockBuilder('Cake\Event\EventManager')->getMock(); <ide> $mock->expects($this->any()) <ide> public function testDeleteBeforeDeleteAbort(): void <ide> public function testDeleteBeforeDeleteReturnResult(): void <ide> { <ide> $entity = new Entity(['id' => 1, 'name' => 'mark']); <del> $options = new \ArrayObject(['atomic' => true, 'cascade' => true]); <add> $options = new ArrayObject(['atomic' => true, 'cascade' => true]); <ide> <ide> $mock = $this->getMockBuilder('Cake\Event\EventManager')->getMock(); <ide> $mock->expects($this->any()) <ide> public function testValidationWithBadDefiner(): void <ide> $table->expects($this->once()) <ide> ->method('validationBad'); <ide> <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> $this->expectExceptionMessage(sprintf( <ide> 'The %s::validationBad() validation method must return an instance of Cake\Validation\Validator.', <ide> get_class($table) <ide> public function testValidationWithBadDefiner(): void <ide> */ <ide> public function testValidatorWithMissingMethod(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> $this->expectExceptionMessage('The Cake\ORM\Table::validationMissing() validation method does not exists.'); <ide> $table = new Table(); <ide> $table->getValidator('missing'); <ide> public function testValidatorWithMissingMethod(): void <ide> public function testValidatorSetter(): void <ide> { <ide> $table = new Table(); <del> $validator = new \Cake\Validation\Validator(); <add> $validator = new Validator(); <ide> $table->setValidator('other', $validator); <ide> $this->assertSame($validator, $table->getValidator('other')); <ide> $this->assertSame($table, $validator->getProvider('table')); <ide> public function testHasValidator(): void <ide> $this->assertTrue($table->hasValidator('default')); <ide> $this->assertFalse($table->hasValidator('other')); <ide> <del> $validator = new \Cake\Validation\Validator(); <add> $validator = new Validator(); <ide> $table->setValidator('other', $validator); <ide> $this->assertTrue($table->hasValidator('other')); <ide> } <ide> public function testMagicFindDefaultToAll(): void <ide> */ <ide> public function testMagicFindError(): void <ide> { <del> $this->expectException(\BadMethodCallException::class); <add> $this->expectException(BadMethodCallException::class); <ide> $this->expectExceptionMessage('Not enough arguments for magic finder. Got 0 required 1'); <ide> $table = $this->getTableLocator()->get('Users'); <ide> <ide> public function testMagicFindError(): void <ide> */ <ide> public function testMagicFindErrorMissingField(): void <ide> { <del> $this->expectException(\BadMethodCallException::class); <add> $this->expectException(BadMethodCallException::class); <ide> $this->expectExceptionMessage('Not enough arguments for magic finder. Got 1 required 2'); <ide> $table = $this->getTableLocator()->get('Users'); <ide> <ide> public function testMagicFindErrorMissingField(): void <ide> */ <ide> public function testMagicFindErrorMixOfOperators(): void <ide> { <del> $this->expectException(\BadMethodCallException::class); <add> $this->expectException(BadMethodCallException::class); <ide> $this->expectExceptionMessage('Cannot mix "and" & "or" in a magic finder. Use find() instead.'); <ide> $table = $this->getTableLocator()->get('Users'); <ide> <ide> public function testBelongsToManyIntegration(): void <ide> $article = $table->find('all')->where(['id' => 1])->contain(['Tags'])->first(); <ide> $tags = $article->tags; <ide> $this->assertNotEmpty($tags); <del> $tags[] = new \TestApp\Model\Entity\Tag(['name' => 'Something New']); <add> $tags[] = new Tag(['name' => 'Something New']); <ide> $article->tags = $tags; <ide> $this->assertSame($article, $table->save($article)); <ide> $tags = $article->tags; <ide> public function testBelongsToFluentInterface(): void <ide> ->setFinder('list') <ide> ->setProperty('authors') <ide> ->setJoinType('inner'); <del> } catch (\BadMethodCallException $e) { <add> } catch (BadMethodCallException $e) { <ide> $this->fail('Method chaining should be ok'); <ide> } <ide> $this->assertSame('articles', $articles->getTable()); <ide> public function testHasOneFluentInterface(): void <ide> ->setStrategy('select') <ide> ->setProperty('authors') <ide> ->setJoinType('inner'); <del> } catch (\BadMethodCallException $e) { <add> } catch (BadMethodCallException $e) { <ide> $this->fail('Method chaining should be ok'); <ide> } <ide> $this->assertSame('authors', $authors->getTable()); <ide> public function testHasManyFluentInterface(): void <ide> ->setSaveStrategy('replace') <ide> ->setProperty('authors') <ide> ->setJoinType('inner'); <del> } catch (\BadMethodCallException $e) { <add> } catch (BadMethodCallException $e) { <ide> $this->fail('Method chaining should be ok'); <ide> } <ide> $this->assertSame('authors', $authors->getTable()); <ide> public function testBelongsToManyFluentInterface(): void <ide> ->setSaveStrategy('append') <ide> ->setThrough('author_articles') <ide> ->setJoinType('inner'); <del> } catch (\BadMethodCallException $e) { <add> } catch (BadMethodCallException $e) { <ide> $this->fail('Method chaining should be ok'); <ide> } <ide> $this->assertSame('authors', $authors->getTable()); <ide> public function testLinkBelongsToMany(): void <ide> 'id' => 1, <ide> ], $options); <ide> <del> $newTag = new \TestApp\Model\Entity\Tag([ <add> $newTag = new Tag([ <ide> 'name' => 'Foo', <ide> 'description' => 'Foo desc', <ide> 'created' => null, <ide> ], $source); <del> $tags[] = new \TestApp\Model\Entity\Tag([ <add> $tags[] = new Tag([ <ide> 'id' => 3, <ide> ], $options + $source); <ide> $tags[] = $newTag; <ide> public function testUnlinkBelongsToManyMultiple(): void <ide> $options = ['markNew' => false]; <ide> <ide> $article = new Entity(['id' => 1], $options); <del> $tags[] = new \TestApp\Model\Entity\Tag(['id' => 1], $options); <del> $tags[] = new \TestApp\Model\Entity\Tag(['id' => 2], $options); <add> $tags[] = new Tag(['id' => 1], $options); <add> $tags[] = new Tag(['id' => 2], $options); <ide> <ide> $table->getAssociation('Tags')->unlink($article, $tags); <ide> $left = $table->find('all')->where(['id' => 1])->contain(['Tags'])->first(); <ide> public function testUnlinkBelongsToManyPassingJoint(): void <ide> $options = ['markNew' => false]; <ide> <ide> $article = new Entity(['id' => 1], $options); <del> $tags[] = new \TestApp\Model\Entity\Tag(['id' => 1], $options); <del> $tags[] = new \TestApp\Model\Entity\Tag(['id' => 2], $options); <add> $tags[] = new Tag(['id' => 1], $options); <add> $tags[] = new Tag(['id' => 2], $options); <ide> <ide> $tags[1]->_joinData = new Entity([ <ide> 'article_id' => 1, <ide> public function testReplacelinksBelongsToMany(): void <ide> $options = ['markNew' => false]; <ide> <ide> $article = new Entity(['id' => 1], $options); <del> $tags[] = new \TestApp\Model\Entity\Tag(['id' => 2], $options); <del> $tags[] = new \TestApp\Model\Entity\Tag(['id' => 3], $options); <del> $tags[] = new \TestApp\Model\Entity\Tag(['name' => 'foo']); <add> $tags[] = new Tag(['id' => 2], $options); <add> $tags[] = new Tag(['id' => 3], $options); <add> $tags[] = new Tag(['name' => 'foo']); <ide> <ide> $table->getAssociation('Tags')->replaceLinks($article, $tags); <ide> $this->assertSame(2, $article->tags[0]->id); <ide> public function testReplacelinksBelongsToManyWithJoint(): void <ide> $options = ['markNew' => false]; <ide> <ide> $article = new Entity(['id' => 1], $options); <del> $tags[] = new \TestApp\Model\Entity\Tag([ <add> $tags[] = new Tag([ <ide> 'id' => 2, <ide> '_joinData' => new Entity([ <ide> 'article_id' => 1, <ide> 'tag_id' => 2, <ide> ]), <ide> ], $options); <del> $tags[] = new \TestApp\Model\Entity\Tag(['id' => 3], $options); <add> $tags[] = new Tag(['id' => 3], $options); <ide> <ide> $table->getAssociation('Tags')->replaceLinks($article, $tags); <ide> $this->assertSame($tags, $article->tags); <ide> public function testGetWithCache($options, $cacheKey, $cacheConfig): void <ide> */ <ide> public function testGetNotFoundException(): void <ide> { <del> $this->expectException(\Cake\Datasource\Exception\RecordNotFoundException::class); <add> $this->expectException(RecordNotFoundException::class); <ide> $this->expectExceptionMessage('Record not found in table "articles"'); <ide> $table = new Table([ <ide> 'name' => 'Articles', <ide> public function testGetNotFoundException(): void <ide> */ <ide> public function testGetExceptionOnNoData(): void <ide> { <del> $this->expectException(\Cake\Datasource\Exception\InvalidPrimaryKeyException::class); <add> $this->expectException(InvalidPrimaryKeyException::class); <ide> $this->expectExceptionMessage('Record not found in table "articles" with primary key [NULL]'); <ide> $table = new Table([ <ide> 'name' => 'Articles', <ide> public function testGetExceptionOnNoData(): void <ide> */ <ide> public function testGetExceptionOnTooMuchData(): void <ide> { <del> $this->expectException(\Cake\Datasource\Exception\InvalidPrimaryKeyException::class); <add> $this->expectException(InvalidPrimaryKeyException::class); <ide> $this->expectExceptionMessage('Record not found in table "articles" with primary key [1, \'two\']'); <ide> $table = new Table([ <ide> 'name' => 'Articles', <ide> public function testLoadIntoMany(): void <ide> */ <ide> public function testSaveOrFail(): void <ide> { <del> $this->expectException(\Cake\ORM\Exception\PersistenceFailedException::class); <add> $this->expectException(PersistenceFailedException::class); <ide> $this->expectExceptionMessage('Entity save failure.'); <ide> <ide> $entity = new Entity([ <ide> public function testSaveOrFail(): void <ide> */ <ide> public function testSaveOrFailErrorDisplay(): void <ide> { <del> $this->expectException(\Cake\ORM\Exception\PersistenceFailedException::class); <add> $this->expectException(PersistenceFailedException::class); <ide> $this->expectExceptionMessage('Entity save failure. Found the following errors (field.0: "Some message", multiple.one: "One", multiple.two: "Two")'); <ide> <ide> $entity = new Entity([ <ide> public function testSaveOrFailErrorDisplay(): void <ide> */ <ide> public function testSaveOrFailNestedError(): void <ide> { <del> $this->expectException(\Cake\ORM\Exception\PersistenceFailedException::class); <add> $this->expectException(PersistenceFailedException::class); <ide> $this->expectExceptionMessage('Entity save failure. Found the following errors (articles.0.title.0: "Bad value")'); <ide> <ide> $entity = new Entity([ <ide> public function testSaveOrFailGetEntity(): void <ide> <ide> try { <ide> $table->saveOrFail($entity); <del> } catch (\Cake\ORM\Exception\PersistenceFailedException $e) { <add> } catch (PersistenceFailedException $e) { <ide> $this->assertSame($entity, $e->getEntity()); <ide> } <ide> } <ide> public function testSaveOrFailGetEntity(): void <ide> */ <ide> public function testDeleteOrFail(): void <ide> { <del> $this->expectException(\Cake\ORM\Exception\PersistenceFailedException::class); <add> $this->expectException(PersistenceFailedException::class); <ide> $this->expectExceptionMessage('Entity delete failure.'); <ide> $entity = new Entity([ <ide> 'id' => 999, <ide> public function testDeleteOrFailGetEntity(): void <ide> <ide> try { <ide> $table->deleteOrFail($entity); <del> } catch (\Cake\ORM\Exception\PersistenceFailedException $e) { <add> } catch (PersistenceFailedException $e) { <ide> $this->assertSame($entity, $e->getEntity()); <ide> } <ide> } <ide> public function getSaveOptionsBuilder(): void <ide> public function skipIfSqlServer(): void <ide> { <ide> $this->skipIf( <del> $this->connection->getDriver() instanceof \Cake\Database\Driver\Sqlserver, <add> $this->connection->getDriver() instanceof Sqlserver, <ide> 'SQLServer does not support the requirements of this test.' <ide> ); <ide> } <ide><path>tests/TestCase/Routing/Middleware/RoutingMiddlewareTest.php <ide> use Cake\Core\Configure; <ide> use Cake\Core\HttpApplicationInterface; <ide> use Cake\Http\ServerRequestFactory; <add>use Cake\Routing\Exception\MissingRouteException; <ide> use Cake\Routing\Middleware\RoutingMiddleware; <ide> use Cake\Routing\RouteBuilder; <ide> use Cake\Routing\RouteCollection; <ide> public function testRouterNoopOnController(): void <ide> */ <ide> public function testMissingRouteNotCaught(): void <ide> { <del> $this->expectException(\Cake\Routing\Exception\MissingRouteException::class); <add> $this->expectException(MissingRouteException::class); <ide> $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/missing']); <ide> $middleware = new RoutingMiddleware($this->app()); <ide> $middleware->process($request, new TestRequestHandler()); <ide><path>tests/TestCase/Routing/Route/RouteTest.php <ide> use Cake\Routing\Route\Route; <ide> use Cake\Routing\Router; <ide> use Cake\TestSuite\TestCase; <add>use InvalidArgumentException; <ide> use TestApp\Routing\Route\ProtectedRoute; <ide> <ide> /** <ide> public function testConstruction(): void <ide> <ide> public function testConstructionWithInvalidMethod(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Invalid HTTP method received. `NOPE` is invalid'); <ide> $route = new Route('/books/reviews', ['controller' => 'Reviews', 'action' => 'index', '_method' => 'nope']); <ide> } <ide> public function testSetMethods(): void <ide> */ <ide> public function testSetMethodsInvalid(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Invalid HTTP method received. `NOPE` is invalid'); <ide> $route = new Route('/books/reviews', ['controller' => 'Reviews', 'action' => 'index']); <ide> $route->setMethods(['nope']); <ide><path>tests/TestCase/Routing/RouteBuilderTest.php <ide> */ <ide> namespace Cake\Test\TestCase\Routing; <ide> <add>use BadMethodCallException; <add>use Cake\Core\Exception\MissingPluginException; <ide> use Cake\Core\Plugin; <ide> use Cake\Routing\Route\InflectedRoute; <ide> use Cake\Routing\Route\RedirectRoute; <ide> use Cake\Routing\Router; <ide> use Cake\TestSuite\TestCase; <ide> use InvalidArgumentException; <add>use RuntimeException; <ide> <ide> /** <ide> * RouteBuilder test case <ide> public function testConnectErrorInvalidRouteClass(): void <ide> */ <ide> public function testConnectConflictingParameters(): void <ide> { <del> $this->expectException(\BadMethodCallException::class); <add> $this->expectException(BadMethodCallException::class); <ide> $this->expectExceptionMessage('You cannot define routes that conflict with the scope.'); <ide> $routes = new RouteBuilder($this->collection, '/admin', ['plugin' => 'TestPlugin']); <ide> $routes->connect('/', ['plugin' => 'TestPlugin2', 'controller' => 'Dashboard', 'action' => 'view']); <ide> public function testMiddlewareGroup(): void <ide> */ <ide> public function testMiddlewareGroupOverlap(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> $this->expectExceptionMessage('Cannot add middleware group \'test\'. A middleware by this name has already been registered.'); <ide> $func = function (): void { <ide> }; <ide> public function testMiddlewareGroupOverlap(): void <ide> */ <ide> public function testApplyMiddlewareInvalidName(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> $this->expectExceptionMessage('Cannot apply \'bad\' middleware or middleware group. Use registerMiddleware() to register middleware'); <ide> $routes = new RouteBuilder($this->collection, '/api'); <ide> $routes->applyMiddleware('bad'); <ide> public function testHttpMethodIntegration(): void <ide> */ <ide> public function testLoadPluginBadPlugin(): void <ide> { <del> $this->expectException(\Cake\Core\Exception\MissingPluginException::class); <add> $this->expectException(MissingPluginException::class); <ide> $routes = new RouteBuilder($this->collection, '/'); <ide> $routes->loadPlugin('Nope'); <ide> } <ide><path>tests/TestCase/Routing/RouteCollectionTest.php <ide> namespace Cake\Test\TestCase\Routing; <ide> <ide> use Cake\Http\ServerRequest; <add>use Cake\Routing\Exception\DuplicateNamedRouteException; <ide> use Cake\Routing\Exception\MissingRouteException; <ide> use Cake\Routing\Route\Route; <ide> use Cake\Routing\RouteBuilder; <ide> use Cake\Routing\RouteCollection; <ide> use Cake\TestSuite\TestCase; <add>use RuntimeException; <ide> <ide> class RouteCollectionTest extends TestCase <ide> { <ide> public function setUp(): void <ide> */ <ide> public function testParseMissingRoute(): void <ide> { <del> $this->expectException(\Cake\Routing\Exception\MissingRouteException::class); <add> $this->expectException(MissingRouteException::class); <ide> $this->expectExceptionMessage('A route matching "/" could not be found'); <ide> $routes = new RouteBuilder($this->collection, '/b', ['key' => 'value']); <ide> $routes->connect('/', ['controller' => 'Articles']); <ide> public function testParseMissingRoute(): void <ide> */ <ide> public function testParseMissingRouteMethod(): void <ide> { <del> $this->expectException(\Cake\Routing\Exception\MissingRouteException::class); <add> $this->expectException(MissingRouteException::class); <ide> $this->expectExceptionMessage('A "POST" route matching "/b" could not be found'); <ide> $routes = new RouteBuilder($this->collection, '/b', ['key' => 'value']); <ide> $routes->connect('/', ['controller' => 'Articles', '_method' => ['GET']]); <ide> public function testParseFallback(): void <ide> */ <ide> public function testParseRequestMissingRoute(): void <ide> { <del> $this->expectException(\Cake\Routing\Exception\MissingRouteException::class); <add> $this->expectException(MissingRouteException::class); <ide> $this->expectExceptionMessage('A route matching "/" could not be found'); <ide> $routes = new RouteBuilder($this->collection, '/b', ['key' => 'value']); <ide> $routes->connect('/', ['controller' => 'Articles']); <ide> public static function hostProvider(): array <ide> */ <ide> public function testParseRequestCheckHostConditionFail(string $host): void <ide> { <del> $this->expectException(\Cake\Routing\Exception\MissingRouteException::class); <add> $this->expectException(MissingRouteException::class); <ide> $this->expectExceptionMessage('A route matching "/fallback" could not be found'); <ide> $routes = new RouteBuilder($this->collection, '/'); <ide> $routes->connect( <ide> public function testParseRequestUnicode(): void <ide> */ <ide> public function testMatchError(): void <ide> { <del> $this->expectException(\Cake\Routing\Exception\MissingRouteException::class); <add> $this->expectException(MissingRouteException::class); <ide> $this->expectExceptionMessage('A route matching "array ('); <ide> $context = [ <ide> '_base' => '/', <ide> public function testMatchNamed(): void <ide> */ <ide> public function testMatchNamedError(): void <ide> { <del> $this->expectException(\Cake\Routing\Exception\MissingRouteException::class); <add> $this->expectException(MissingRouteException::class); <ide> $this->expectExceptionMessage('A named route was found for `fail`, but matching failed'); <ide> $context = [ <ide> '_base' => '/', <ide> public function testMatchNamedError(): void <ide> */ <ide> public function testMatchNamedMissingError(): void <ide> { <del> $this->expectException(\Cake\Routing\Exception\MissingRouteException::class); <add> $this->expectException(MissingRouteException::class); <ide> $context = [ <ide> '_base' => '/', <ide> '_scheme' => 'http', <ide> public function testAddingRoutes(): void <ide> */ <ide> public function testAddingDuplicateNamedRoutes(): void <ide> { <del> $this->expectException(\Cake\Routing\Exception\DuplicateNamedRouteException::class); <add> $this->expectException(DuplicateNamedRouteException::class); <ide> $one = new Route('/pages/*', ['controller' => 'Pages', 'action' => 'display']); <ide> $two = new Route('/', ['controller' => 'Dashboards', 'action' => 'display']); <ide> $this->collection->add($one, ['_name' => 'test']); <ide> public function testMiddlewareGroupOverwrite(): void <ide> */ <ide> public function testMiddlewareGroupUnregisteredMiddleware(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> $this->expectExceptionMessage('Cannot add \'bad\' middleware to group \'group\'. It has not been registered.'); <ide> $this->collection->middlewareGroup('group', ['bad']); <ide> } <ide><path>tests/TestCase/Routing/RouterTest.php <ide> use Cake\Core\Configure; <ide> use Cake\Http\ServerRequest; <ide> use Cake\Http\ServerRequestFactory; <add>use Cake\Routing\Exception\DuplicateNamedRouteException; <add>use Cake\Routing\Exception\MissingRouteException; <ide> use Cake\Routing\Route\Route; <ide> use Cake\Routing\RouteBuilder; <ide> use Cake\Routing\RouteCollection; <ide> use Cake\Routing\Router; <ide> use Cake\TestSuite\TestCase; <add>use Exception; <ide> use InvalidArgumentException; <ide> use RuntimeException; <ide> <ide> public function testUrlGenerationNamedRoute(): void <ide> */ <ide> public function testNamedRouteException(): void <ide> { <del> $this->expectException(\Cake\Routing\Exception\MissingRouteException::class); <add> $this->expectException(MissingRouteException::class); <ide> Router::connect( <ide> '/users/{name}', <ide> ['controller' => 'Users', 'action' => 'view'], <ide> public function testNamedRouteException(): void <ide> */ <ide> public function testDuplicateNamedRouteException(): void <ide> { <del> $this->expectException(\Cake\Routing\Exception\DuplicateNamedRouteException::class); <add> $this->expectException(DuplicateNamedRouteException::class); <ide> Router::connect( <ide> '/users/{name}', <ide> ['controller' => 'Users', 'action' => 'view'], <ide> public function testRouteSymmetry(): void <ide> */ <ide> public function testParseError(): void <ide> { <del> $this->expectException(\Cake\Routing\Exception\MissingRouteException::class); <add> $this->expectException(MissingRouteException::class); <ide> Router::connect('/', ['controller' => 'Pages', 'action' => 'display', 'home']); <ide> Router::parseRequest($this->makeRequest('/nope', 'GET')); <ide> } <ide> public function testRouteParamDefaults(): void <ide> try { <ide> Router::url(['controller' => '0', 'action' => '1', 'test']); <ide> $this->fail('No exception raised'); <del> } catch (\Exception $e) { <add> } catch (Exception $e) { <ide> $this->assertTrue(true, 'Exception was raised'); <ide> } <ide> <ide> try { <ide> Router::url(['prefix' => '1', 'controller' => '0', 'action' => '1', 'test']); <ide> $this->fail('No exception raised'); <del> } catch (\Exception $e) { <add> } catch (Exception $e) { <ide> $this->assertTrue(true, 'Exception was raised'); <ide> } <ide> } <ide> public function testParsingWithTrailingPeriodAndParseExtensions(): void <ide> */ <ide> public function testParsingWithPatternOnAction(): void <ide> { <del> $this->expectException(\Cake\Routing\Exception\MissingRouteException::class); <add> $this->expectException(MissingRouteException::class); <ide> Router::connect( <ide> '/blog/{action}/*', <ide> ['controller' => 'BlogPosts'], <ide> public function testUrlArray(): void <ide> */ <ide> public function testUrlPatternOnAction(): void <ide> { <del> $this->expectException(\Cake\Routing\Exception\MissingRouteException::class); <add> $this->expectException(MissingRouteException::class); <ide> Router::connect( <ide> '/blog/{action}/*', <ide> ['controller' => 'BlogPosts'], <ide> public function testRegexRouteMatching(): void <ide> */ <ide> public function testRegexRouteMatchUrl(): void <ide> { <del> $this->expectException(\Cake\Routing\Exception\MissingRouteException::class); <add> $this->expectException(MissingRouteException::class); <ide> Router::connect('/{locale}/{controller}/{action}/*', [], ['locale' => 'dan|eng']); <ide> <ide> $request = new ServerRequest([ <ide> public function testUsingCustomRouteClassPluginDotSyntax(): void <ide> */ <ide> public function testCustomRouteException(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> Router::connect('/{controller}', [], ['routeClass' => 'Object']); <ide> } <ide> <ide><path>tests/TestCase/TestSuite/Constraint/EventFiredWithTest.php <ide> use Cake\Event\EventManager; <ide> use Cake\TestSuite\Constraint\EventFiredWith; <ide> use Cake\TestSuite\TestCase; <add>use PHPUnit\Framework\AssertionFailedError; <ide> use stdClass; <ide> <ide> /** <ide> public function testMatches(): void <ide> */ <ide> public function testMatchesInvalid(): void <ide> { <del> $this->expectException(\PHPUnit\Framework\AssertionFailedError::class); <add> $this->expectException(AssertionFailedError::class); <ide> $manager = EventManager::instance(); <ide> $manager->setEventList(new EventList()); <ide> $manager->trackEvents(true); <ide><path>tests/TestCase/TestSuite/Fixture/SchemaCleanerTest.php <ide> use Cake\Datasource\ConnectionManager; <ide> use Cake\TestSuite\Fixture\SchemaCleaner; <ide> use Cake\TestSuite\TestCase; <add>use Throwable; <ide> <ide> class SchemaCleanerTest extends TestCase <ide> { <ide> public function testForeignKeyConstruction(): void <ide> $exceptionThrown = false; <ide> try { <ide> $connection->delete($table); <del> } catch (\Throwable $e) { <add> } catch (Throwable $e) { <ide> $exceptionThrown = true; <ide> } finally { <ide> $this->assertTrue($exceptionThrown); <ide><path>tests/TestCase/TestSuite/Fixture/SchemaManagerTest.php <ide> use Cake\TestSuite\Fixture\SchemaCleaner; <ide> use Cake\TestSuite\Fixture\SchemaManager; <ide> use Cake\TestSuite\TestCase; <add>use RuntimeException; <ide> <ide> class SchemaManagerTest extends TestCase <ide> { <ide> public function testCreateFromMultipleFiles(): void <ide> <ide> public function testCreateFromNonExistentFile(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> SchemaManager::create('test', 'foo'); <ide> } <ide> <ide> public function testCreateFromCorruptedFile(): void <ide> $tmpFile = tempnam(sys_get_temp_dir(), 'SchemaManagerTest'); <ide> file_put_contents($tmpFile, $query); <ide> <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> SchemaManager::create('test', $tmpFile, false, false); <ide> } <ide> <ide><path>tests/TestCase/TestSuite/IntegrationTestTraitTest.php <ide> use Cake\TestSuite\TestCase; <ide> use Cake\Utility\Security; <ide> use Laminas\Diactoros\UploadedFile; <add>use LogicException; <add>use OutOfBoundsException; <ide> use PHPUnit\Framework\AssertionFailedError; <ide> use stdClass; <ide> <ide> public function testGetSpecificRouteHttpServer(): void <ide> */ <ide> public function testConfigApplication(): void <ide> { <del> $this->expectException(\LogicException::class); <add> $this->expectException(LogicException::class); <ide> $this->expectExceptionMessage('Cannot load `TestApp\MissingApp` for use in integration'); <ide> $this->configApplication('TestApp\MissingApp', []); <ide> $this->get('/request_action/test_request_action'); <ide> public function testAssertFileNoFile(): void <ide> */ <ide> public function testDisableErrorHandlerMiddleware(): void <ide> { <del> $this->expectException(\OutOfBoundsException::class); <add> $this->expectException(OutOfBoundsException::class); <ide> $this->expectExceptionMessage('oh no!'); <ide> $this->disableErrorHandlerMiddleware(); <ide> $this->get('/posts/throw_exception'); <ide><path>tests/TestCase/TestSuite/TestCaseTest.php <ide> class TestCaseTest extends TestCase <ide> */ <ide> public function testEventFiredMisconfiguredEventList(): void <ide> { <del> $this->expectException(\PHPUnit\Framework\AssertionFailedError::class); <add> $this->expectException(AssertionFailedError::class); <ide> $manager = EventManager::instance(); <ide> $this->assertEventFired('my.event', $manager); <ide> } <ide> public function testEventFiredMisconfiguredEventList(): void <ide> */ <ide> public function testEventFiredWithMisconfiguredEventList(): void <ide> { <del> $this->expectException(\PHPUnit\Framework\AssertionFailedError::class); <add> $this->expectException(AssertionFailedError::class); <ide> $manager = EventManager::instance(); <ide> $this->assertEventFiredWith('my.event', 'some', 'data', $manager); <ide> } <ide><path>tests/TestCase/TestSuite/TestFixtureTest.php <ide> */ <ide> namespace Cake\Test\TestCase\TestSuite; <ide> <add>use Cake\Core\Exception\CakeException; <ide> use Cake\Database\Schema\TableSchema; <ide> use Cake\Database\StatementInterface; <ide> use Cake\Datasource\ConnectionManager; <ide> public function testInitImportModel(): void <ide> */ <ide> public function testInitNoImportNoFieldsException(): void <ide> { <del> $this->expectException(\Cake\Core\Exception\CakeException::class); <add> $this->expectException(CakeException::class); <ide> $this->expectExceptionMessage('Cannot describe schema for table `letters` for fixture `' . LettersFixture::class . '`: the table does not exist.'); <ide> $fixture = new LettersFixture(); <ide> $fixture->init(); <ide><path>tests/TestCase/Utility/HashTest.php <ide> use Cake\ORM\Entity; <ide> use Cake\TestSuite\TestCase; <ide> use Cake\Utility\Hash; <add>use InvalidArgumentException; <add>use RuntimeException; <ide> <ide> /** <ide> * HashTest <ide> public function testCombineWithNullKeyPath(): void <ide> */ <ide> public function testCombineErrorMissingValue(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> $data = [ <ide> ['User' => ['id' => 1, 'name' => 'mark']], <ide> ['User' => ['name' => 'jose']], <ide> public function testCombineErrorMissingValue(): void <ide> */ <ide> public function testCombineErrorMissingKey(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> $data = [ <ide> ['User' => ['id' => 1, 'name' => 'mark']], <ide> ['User' => ['id' => 2]], <ide> public function testMissingParent(): void <ide> */ <ide> public function testNestInvalid(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $input = [ <ide> [ <ide> 'ParentCategory' => [ <ide><path>tests/TestCase/Utility/SecurityTest.php <ide> use Cake\TestSuite\TestCase; <ide> use Cake\Utility\Crypto\OpenSsl; <ide> use Cake\Utility\Security; <add>use InvalidArgumentException; <ide> use RuntimeException; <ide> <ide> /** <ide> public function testDecryptHmacSaltFailure(): void <ide> */ <ide> public function testEncryptInvalidKey(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Invalid key for encrypt(), key must be at least 256 bits (32 bytes) long.'); <ide> $txt = 'The quick brown fox jumped over the lazy dog.'; <ide> $key = 'this is too short'; <ide> public function testEncryptDecryptFalseyData(): void <ide> */ <ide> public function testDecryptInvalidKey(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Invalid key for decrypt(), key must be at least 256 bits (32 bytes) long.'); <ide> $txt = 'The quick brown fox jumped over the lazy dog.'; <ide> $key = 'this is too short'; <ide> public function testDecryptInvalidKey(): void <ide> */ <ide> public function testDecryptInvalidData(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('The data to decrypt cannot be empty.'); <ide> $txt = ''; <ide> $key = 'This is a key that is long enough to be ok.'; <ide><path>tests/TestCase/Utility/TextTest.php <ide> use Cake\I18n\FrozenTime; <ide> use Cake\TestSuite\TestCase; <ide> use Cake\Utility\Text; <add>use InvalidArgumentException; <add>use ReflectionMethod; <add>use Transliterator; <ide> <ide> /** <ide> * TextTest class <ide> public function testParseFileSize(array $params, $expected): void <ide> */ <ide> public function testParseFileSizeException(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> Text::parseFileSize('bogus', false); <ide> } <ide> <ide> public function testGetSetTransliterator(): void <ide> { <ide> $this->assertNull(Text::getTransliterator()); <ide> <del> $transliterator = \Transliterator::createFromRules(' <add> $transliterator = Transliterator::createFromRules(' <ide> $nonletter = [:^Letter:]; <ide> $nonletter → \'*\'; <ide> ::Latin-ASCII; <ide> '); <del> $this->assertInstanceOf(\Transliterator::class, $transliterator); <add> $this->assertInstanceOf(Transliterator::class, $transliterator); <ide> Text::setTransliterator($transliterator); <ide> $this->assertSame($transliterator, Text::getTransliterator()); <ide> } <ide> public function testGetSetTransliteratorId(): void <ide> Text::setTransliteratorId($expected); <ide> $this->assertSame($expected, Text::getTransliteratorId()); <ide> <del> $this->assertInstanceOf(\Transliterator::class, Text::getTransliterator()); <add> $this->assertInstanceOf(Transliterator::class, Text::getTransliterator()); <ide> $this->assertSame($expected, Text::getTransliterator()->id); <ide> <ide> Text::setTransliteratorId($defaultTransliteratorId); <ide> public function testTruncateByWidth(): void <ide> */ <ide> public function testStrlen(): void <ide> { <del> $method = new \ReflectionMethod('Cake\Utility\Text', '_strlen'); <add> $method = new ReflectionMethod('Cake\Utility\Text', '_strlen'); <ide> $method->setAccessible(true); <ide> $strlen = function () use ($method) { <ide> return $method->invokeArgs(null, func_get_args()); <ide> public function testStrlen(): void <ide> */ <ide> public function testSubstr(): void <ide> { <del> $method = new \ReflectionMethod('Cake\Utility\Text', '_substr'); <add> $method = new ReflectionMethod('Cake\Utility\Text', '_substr'); <ide> $method->setAccessible(true); <ide> $substr = function () use ($method) { <ide> return $method->invokeArgs(null, func_get_args()); <ide><path>tests/TestCase/Utility/XmlTest.php <ide> use Cake\TestSuite\TestCase; <ide> use Cake\Utility\Exception\XmlException; <ide> use Cake\Utility\Xml; <add>use DateTime; <add>use DOMDocument; <add>use Exception; <add>use RuntimeException; <add>use SimpleXMLElement; <ide> use TypeError; <ide> <ide> /** <ide> public function testExceptionChainingForInvalidInput(): void <ide> } catch (XmlException $exception) { <ide> $cause = $exception->getPrevious(); <ide> $this->assertNotNull($cause); <del> $this->assertInstanceOf(\Exception::class, $cause); <add> $this->assertInstanceOf(Exception::class, $cause); <ide> } <ide> } <ide> <ide> public function testBuild(): void <ide> { <ide> $xml = '<tag>value</tag>'; <ide> $obj = Xml::build($xml); <del> $this->assertInstanceOf(\SimpleXMLElement::class, $obj); <add> $this->assertInstanceOf(SimpleXMLElement::class, $obj); <ide> $this->assertSame('tag', (string)$obj->getName()); <ide> $this->assertSame('value', (string)$obj); <ide> <ide> $xml = '<?xml version="1.0" encoding="UTF-8"?><tag>value</tag>'; <ide> $this->assertEquals($obj, Xml::build($xml)); <ide> <ide> $obj = Xml::build($xml, ['return' => 'domdocument']); <del> $this->assertInstanceOf(\DOMDocument::class, $obj); <add> $this->assertInstanceOf(DOMDocument::class, $obj); <ide> $this->assertSame('tag', $obj->firstChild->nodeName); <ide> $this->assertSame('value', $obj->firstChild->nodeValue); <ide> <ide> public function testBuildHuge(): void <ide> */ <ide> public function testBuildFromFileWhenDisabled(): void <ide> { <del> $this->expectException(\Cake\Utility\Exception\XmlException::class); <add> $this->expectException(XmlException::class); <ide> $xml = CORE_TESTS . 'Fixture/sample.xml'; <ide> $obj = Xml::build($xml, ['readFile' => false]); <ide> } <ide> public static function invalidDataProvider(): array <ide> */ <ide> public function testBuildInvalidData($value): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> Xml::build($value); <ide> } <ide> <ide> public function testBuildInvalidData($value): void <ide> */ <ide> public function testBuildInvalidDataSimpleXml(): void <ide> { <del> $this->expectException(\Cake\Utility\Exception\XmlException::class); <add> $this->expectException(XmlException::class); <ide> $input = '<derp'; <ide> Xml::build($input, ['return' => 'simplexml']); <ide> } <ide> public function testBuildEmptyTag(): void <ide> try { <ide> Xml::build('<tag>'); <ide> $this->fail('No exception'); <del> } catch (\Exception $e) { <add> } catch (Exception $e) { <ide> $this->assertTrue(true, 'An exception was raised'); <ide> } <ide> } <ide> public function testFromArray(): void <ide> ], <ide> ]; <ide> $obj = Xml::fromArray($xml, ['format' => 'attributes']); <del> $this->assertInstanceOf(\SimpleXMLElement::class, $obj); <add> $this->assertInstanceOf(SimpleXMLElement::class, $obj); <ide> $this->assertSame('tags', $obj->getName()); <ide> $this->assertSame(2, count($obj)); <ide> $xmlText = <<<XML <ide> public function testFromArray(): void <ide> $this->assertXmlStringEqualsXmlString($xmlText, $obj->asXML()); <ide> <ide> $obj = Xml::fromArray($xml); <del> $this->assertInstanceOf(\SimpleXMLElement::class, $obj); <add> $this->assertInstanceOf(SimpleXMLElement::class, $obj); <ide> $this->assertSame('tags', $obj->getName()); <ide> $this->assertSame(2, count($obj)); <ide> $xmlText = <<<XML <ide> public static function invalidArrayDataProvider(): array <ide> ], <ide> ], <ide> ]], <del> [new \DateTime()], <add> [new DateTime()], <ide> ]; <ide> } <ide> <ide> public static function invalidArrayDataProvider(): array <ide> */ <ide> public function testFromArrayFail($value): void <ide> { <del> $this->expectException(\Exception::class); <add> $this->expectException(Exception::class); <ide> Xml::fromArray($value); <ide> } <ide> <ide><path>tests/TestCase/Validation/ValidationRuleTest.php <ide> <ide> use Cake\TestSuite\TestCase; <ide> use Cake\Validation\ValidationRule; <add>use InvalidArgumentException; <ide> <ide> /** <ide> * ValidationRuleTest <ide> public function testCustomMethodNoProvider(): void <ide> */ <ide> public function testCustomMethodMissingError(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Unable to call method "totallyMissing" in "default" provider for field "test"'); <ide> $def = ['rule' => ['totallyMissing']]; <ide> $data = 'some data'; <ide><path>tests/TestCase/Validation/ValidationTest.php <ide> use Cake\I18n\I18n; <ide> use Cake\TestSuite\TestCase; <ide> use Cake\Validation\Validation; <add>use DateTime; <add>use DateTimeImmutable; <add>use InvalidArgumentException; <ide> use Laminas\Diactoros\UploadedFile; <ide> use Locale; <add>use RuntimeException; <ide> use stdClass; <ide> <ide> require_once __DIR__ . '/stubs.php'; <ide> public function testCustomAsArray(): void <ide> */ <ide> public function testDateTimeObject(): void <ide> { <del> $dateTime = new \DateTime(); <add> $dateTime = new DateTime(); <ide> $this->assertTrue(Validation::date($dateTime)); <ide> $this->assertTrue(Validation::time($dateTime)); <ide> $this->assertTrue(Validation::dateTime($dateTime)); <ide> $this->assertTrue(Validation::localizedTime($dateTime)); <ide> <del> $dateTime = new \DateTimeImmutable(); <add> $dateTime = new DateTimeImmutable(); <ide> $this->assertTrue(Validation::date($dateTime)); <ide> $this->assertTrue(Validation::time($dateTime)); <ide> $this->assertTrue(Validation::dateTime($dateTime)); <ide> public function testMimeTypePsr7(): void <ide> */ <ide> public function testMimeTypeFalse(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> $image = CORE_TESTS . 'invalid-file.png'; <ide> Validation::mimeType($image, ['image/gif']); <ide> } <ide> public function testIsInteger(): void <ide> $this->assertFalse(Validation::isInteger('2.5')); <ide> $this->assertFalse(Validation::isInteger(2.5)); <ide> $this->assertFalse(Validation::isInteger([])); <del> $this->assertFalse(Validation::isInteger(new \stdClass())); <add> $this->assertFalse(Validation::isInteger(new stdClass())); <ide> $this->assertFalse(Validation::isInteger('2 bears')); <ide> $this->assertFalse(Validation::isInteger(true)); <ide> $this->assertFalse(Validation::isInteger(false)); <ide> public function testAscii(): void <ide> $this->assertFalse(Validation::ascii([])); <ide> $this->assertFalse(Validation::ascii(1001)); <ide> $this->assertFalse(Validation::ascii(3.14)); <del> $this->assertFalse(Validation::ascii(new \stdClass())); <add> $this->assertFalse(Validation::ascii(new stdClass())); <ide> <ide> // Latin-1 supplement <ide> $this->assertFalse(Validation::ascii('some' . "\xc2\x82" . 'value')); <ide> public function testUtf8Basic(): void <ide> $this->assertFalse(Validation::utf8([])); <ide> $this->assertFalse(Validation::utf8(1001)); <ide> $this->assertFalse(Validation::utf8(3.14)); <del> $this->assertFalse(Validation::utf8(new \stdClass())); <add> $this->assertFalse(Validation::utf8(new stdClass())); <ide> $this->assertTrue(Validation::utf8('1 big blue bus.')); <ide> $this->assertTrue(Validation::utf8(',.<>[]{;/?\)()')); <ide> <ide> public function testUtf8Extended(): void <ide> $this->assertFalse(Validation::utf8([], ['extended' => true])); <ide> $this->assertFalse(Validation::utf8(1001, ['extended' => true])); <ide> $this->assertFalse(Validation::utf8(3.14, ['extended' => true])); <del> $this->assertFalse(Validation::utf8(new \stdClass(), ['extended' => true])); <add> $this->assertFalse(Validation::utf8(new stdClass(), ['extended' => true])); <ide> $this->assertTrue(Validation::utf8('1 big blue bus.', ['extended' => true])); <ide> $this->assertTrue(Validation::utf8(',.<>[]{;/?\)()', ['extended' => true])); <ide> <ide> public function testNumElements(): void <ide> */ <ide> public function testImageSizeInvalidArgumentException(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->assertTrue(Validation::imageSize([], [])); <ide> } <ide> <ide><path>tests/TestCase/Validation/ValidatorTest.php <ide> namespace Cake\Test\TestCase\Validation; <ide> <ide> use Cake\TestSuite\TestCase; <add>use Cake\Validation\RulesProvider; <ide> use Cake\Validation\Validation; <ide> use Cake\Validation\ValidationRule; <ide> use Cake\Validation\ValidationSet; <ide> use Cake\Validation\Validator; <ide> use InvalidArgumentException; <ide> use Laminas\Diactoros\UploadedFile; <add>use stdClass; <ide> <ide> /** <ide> * Tests Validator class <ide> public function testErrorsWithEmptyAllowed(): void <ide> public function testProvider(): void <ide> { <ide> $validator = new Validator(); <del> $object = new \stdClass(); <add> $object = new stdClass(); <ide> $this->assertSame($validator, $validator->setProvider('foo', $object)); <ide> $this->assertSame($object, $validator->getProvider('foo')); <ide> $this->assertNull($validator->getProvider('bar')); <ide> <del> $another = new \stdClass(); <add> $another = new stdClass(); <ide> $this->assertSame($validator, $validator->setProvider('bar', $another)); <ide> $this->assertSame($another, $validator->getProvider('bar')); <ide> <del> $this->assertEquals(new \Cake\Validation\RulesProvider(), $validator->getProvider('default')); <add> $this->assertEquals(new RulesProvider(), $validator->getProvider('default')); <ide> } <ide> <ide> public function testProviderWarning(): void <ide> public function testErrorsFromCustomProvider(): void <ide> ->will($this->returnCallback(function ($data, $context) use ($thing) { <ide> $this->assertSame('bar', $data); <ide> $expected = [ <del> 'default' => new \Cake\Validation\RulesProvider(), <add> 'default' => new RulesProvider(), <ide> 'thing' => $thing, <ide> ]; <ide> $expected = [ <ide> public function testMethodsWithExtraArguments(): void <ide> $this->assertSame('and', $a); <ide> $this->assertSame('awesome', $b); <ide> $expected = [ <del> 'default' => new \Cake\Validation\RulesProvider(), <add> 'default' => new RulesProvider(), <ide> 'thing' => $thing, <ide> ]; <ide> $expected = [ <ide> public function testLengthBetween(): void <ide> */ <ide> public function testLengthBetweenFailure(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $validator = new Validator(); <ide> $validator->lengthBetween('username', [7]); <ide> } <ide> public function testRange(): void <ide> */ <ide> public function testRangeFailure(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $validator = new Validator(); <ide> $validator->range('username', [1]); <ide> } <ide><path>tests/TestCase/View/CellTest.php <ide> */ <ide> namespace Cake\Test\TestCase\View; <ide> <add>use BadMethodCallException; <ide> use Cake\Cache\Cache; <ide> use Cake\Http\Response; <ide> use Cake\Http\ServerRequest; <ide> use Cake\TestSuite\TestCase; <ide> use Cake\View\Cell; <add>use Cake\View\Exception\MissingCellException; <ide> use Cake\View\Exception\MissingCellTemplateException; <ide> use Cake\View\Exception\MissingTemplateException; <ide> use Cake\View\View; <ide> public function testPluginCellAlternateTemplateRenderParam(): void <ide> */ <ide> public function testNonExistentCell(): void <ide> { <del> $this->expectException(\Cake\View\Exception\MissingCellException::class); <add> $this->expectException(MissingCellException::class); <ide> $cell = $this->View->cell('TestPlugin.Void::echoThis', ['arg1' => 'v1']); <ide> $cell = $this->View->cell('Void::echoThis', ['arg1' => 'v1', 'arg2' => 'v2']); <ide> } <ide> public function testNonExistentCell(): void <ide> */ <ide> public function testCellMissingMethod(): void <ide> { <del> $this->expectException(\BadMethodCallException::class); <add> $this->expectException(BadMethodCallException::class); <ide> $this->expectExceptionMessage('Class TestApp\View\Cell\ArticlesCell does not have a "nope" method.'); <ide> $cell = $this->View->cell('Articles::nope'); <ide> $cell->render(); <ide><path>tests/TestCase/View/Form/ContextFactoryTest.php <ide> use Cake\Http\ServerRequest; <ide> use Cake\TestSuite\TestCase; <ide> use Cake\View\Form\ContextFactory; <add>use RuntimeException; <ide> <ide> /** <ide> * ContextFactory test case. <ide> class ContextFactoryTest extends TestCase <ide> { <ide> public function testGetException(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> $this->expectExceptionMessage( <ide> 'No context provider found for value of type `boolean`.' <ide> . ' Use `null` as 1st argument of FormHelper::create() to create a context-less form.' <ide><path>tests/TestCase/View/Form/EntityContextTest.php <ide> use Cake\TestSuite\TestCase; <ide> use Cake\Validation\Validator; <ide> use Cake\View\Form\EntityContext; <add>use RuntimeException; <add>use stdClass; <ide> use TestApp\Model\Entity\Article; <ide> use TestApp\Model\Entity\ArticlesTag; <ide> use TestApp\Model\Entity\Tag; <ide> public function testIsCreateCollection($collection): void <ide> */ <ide> public function testInvalidTable(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> $this->expectExceptionMessage('Unable to find table class for current entity'); <del> $row = new \stdClass(); <add> $row = new stdClass(); <ide> $context = new EntityContext([ <ide> 'entity' => $row, <ide> ]); <ide> public function testInvalidTable(): void <ide> */ <ide> public function testDefaultEntityError(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> $this->expectExceptionMessage('Unable to find table class for current entity'); <ide> $context = new EntityContext([ <ide> 'entity' => new Entity(), <ide><path>tests/TestCase/View/Helper/BreadcrumbsHelperTest.php <ide> use Cake\TestSuite\TestCase; <ide> use Cake\View\Helper\BreadcrumbsHelper; <ide> use Cake\View\View; <add>use LogicException; <ide> <ide> class BreadcrumbsHelperTest extends TestCase <ide> { <ide> public function testInsertAt(): void <ide> */ <ide> public function testInsertAtIndexOutOfBounds(): void <ide> { <del> $this->expectException(\LogicException::class); <add> $this->expectException(LogicException::class); <ide> $this->breadcrumbs <ide> ->add('Home', '/', ['class' => 'first']) <ide> ->insertAt(2, 'Insert At Again', ['controller' => 'Insert', 'action' => 'at_again']); <ide><path>tests/TestCase/View/Helper/FormHelperTest.php <ide> */ <ide> namespace Cake\Test\TestCase\View\Helper; <ide> <add>use ArrayObject; <ide> use Cake\Collection\Collection; <ide> use Cake\Core\Configure; <add>use Cake\Core\Exception\CakeException; <ide> use Cake\Form\Form; <ide> use Cake\Http\ServerRequest; <ide> use Cake\I18n\FrozenDate; <ide> use Cake\View\Helper\FormHelper; <ide> use Cake\View\View; <ide> use Cake\View\Widget\WidgetLocator; <add>use InvalidArgumentException; <ide> use ReflectionProperty; <add>use RuntimeException; <ide> use TestApp\Model\Entity\Article; <ide> use TestApp\Model\Table\ContactsTable; <ide> use TestApp\Model\Table\ValidateUsersTable; <ide> public function contextSelectionProvider(): array <ide> $entity = new Article(); <ide> $collection = new Collection([$entity]); <ide> $emptyCollection = new Collection([]); <del> $arrayObject = new \ArrayObject([]); <add> $arrayObject = new ArrayObject([]); <ide> $data = [ <ide> 'schema' => [ <ide> 'title' => ['type' => 'string'], <ide> public function testControlSelectType(): void <ide> <ide> $result = $this->Form->control('email', [ <ide> 'type' => 'select', <del> 'options' => new \ArrayObject(['First', 'Second']), <add> 'options' => new ArrayObject(['First', 'Second']), <ide> 'empty' => true, <ide> ]); <ide> $this->assertHtml($expected, $result); <ide> public function testControlMagicSelectForTypeNumber(): void <ide> */ <ide> public function testInvalidControlTypeOption(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> $this->expectExceptionMessage('Invalid type \'input\' used for field \'text\''); <ide> $this->Form->control('text', ['type' => 'input']); <ide> } <ide> public function testHtml5ControlWithControl(): void <ide> */ <ide> public function testHtml5ControlException(): void <ide> { <del> $this->expectException(\Cake\Core\Exception\CakeException::class); <add> $this->expectException(CakeException::class); <ide> $this->Form->email(); <ide> } <ide> <ide> public function testHtml5ErrorMessage(): void <ide> { <ide> $this->Form->setConfig('autoSetCustomValidity', true); <ide> <del> $validator = (new \Cake\Validation\Validator()) <add> $validator = (new Validator()) <ide> ->notEmptyString('email', 'Custom error message') <ide> ->requirePresence('password') <ide> ->alphaNumeric('password') <ide> public function testHtml5ErrorMessage(): void <ide> */ <ide> public function testHtml5ErrorMessageInTemplateVars(): void <ide> { <del> $validator = (new \Cake\Validation\Validator()) <add> $validator = (new Validator()) <ide> ->notEmptyString('email', 'Custom error "message" & entities') <ide> ->requirePresence('password') <ide> ->alphaNumeric('password') <ide> public function testFormValueSourcesSettersGetters(): void <ide> <ide> public function testValueSourcesValidation(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $this->expectExceptionMessage('Invalid value source(s): invalid, foo. Valid values are: context, data, query'); <ide> <ide> $this->Form->setValueSources(['query', 'data', 'invalid', 'context', 'foo']); <ide><path>tests/TestCase/View/Helper/TimeHelperTest.php <ide> use Cake\TestSuite\TestCase; <ide> use Cake\View\Helper\TimeHelper; <ide> use Cake\View\View; <add>use DateTime as NativeDateTime; <add>use DateTimeZone; <add>use IntlDateFormatter; <ide> <ide> /** <ide> * TimeHelperTest class <ide> public function testToUnix(): void <ide> */ <ide> public function testToAtom(): void <ide> { <del> $dateTime = new \DateTime(); <add> $dateTime = new NativeDateTime(); <ide> $this->assertSame($dateTime->format($dateTime::ATOM), $this->Time->toAtom($dateTime->getTimestamp())); <ide> } <ide> <ide> public function testToRss(): void <ide> <ide> $timezones = ['Europe/London', 'Europe/Brussels', 'UTC', 'America/Denver', 'America/Caracas', 'Asia/Kathmandu']; <ide> foreach ($timezones as $timezone) { <del> $yourTimezone = new \DateTimeZone($timezone); <del> $yourTime = new \DateTime($date, $yourTimezone); <add> $yourTimezone = new DateTimeZone($timezone); <add> $yourTime = new NativeDateTime($date, $yourTimezone); <ide> $time = $yourTime->format('U'); <ide> $this->assertSame($yourTime->format('r'), $this->Time->toRss($time, $timezone), "Failed on $timezone"); <ide> } <ide> public function testFormat(): void <ide> $expected = '1/14/10, 1:59 PM'; <ide> $this->assertTimeFormat($expected, $result); <ide> <del> $result = $this->Time->format($time, \IntlDateFormatter::FULL); <add> $result = $this->Time->format($time, IntlDateFormatter::FULL); <ide> $expected = 'Thursday, January 14, 2010 at 1:59:28 PM'; <ide> $this->assertStringStartsWith($expected, $result); <ide> <ide> public function testI18nFormatOutputTimezone(): void <ide> $this->Time->setConfig('outputTimezone', 'America/Vancouver'); <ide> <ide> $time = strtotime('Thu Jan 14 8:59:28 2010 UTC'); <del> $result = $this->Time->i18nFormat($time, [\IntlDateFormatter::SHORT, \IntlDateFormatter::FULL]); <add> $result = $this->Time->i18nFormat($time, [IntlDateFormatter::SHORT, IntlDateFormatter::FULL]); <ide> $expected = '1/14/10, 12:59:28 AM'; <ide> $this->assertStringStartsWith($expected, $result); <ide> } <ide> public function testNullDateFormat(): void <ide> $this->assertFalse($result); <ide> <ide> $fallback = 'Date invalid or not set'; <del> $result = $this->Time->format(null, \IntlDateFormatter::FULL, $fallback); <add> $result = $this->Time->format(null, IntlDateFormatter::FULL, $fallback); <ide> $this->assertSame($fallback, $result); <ide> } <ide> } <ide><path>tests/TestCase/View/HelperRegistryTest.php <ide> namespace Cake\Test\TestCase\View; <ide> <ide> use Cake\TestSuite\TestCase; <add>use Cake\View\Exception\MissingHelperException; <ide> use Cake\View\Helper\FormHelper; <ide> use Cake\View\Helper\HtmlHelper; <ide> use Cake\View\HelperRegistry; <ide> use Cake\View\View; <add>use RuntimeException; <ide> use TestApp\View\Helper\HtmlAliasHelper; <ide> use TestPlugin\View\Helper\OtherHelperHelper; <ide> <ide> public function testLazyLoad(): void <ide> */ <ide> public function testLazyLoadException(): void <ide> { <del> $this->expectException(\Cake\View\Exception\MissingHelperException::class); <add> $this->expectException(MissingHelperException::class); <ide> $this->Helpers->NotAHelper; <ide> } <ide> <ide> public function testLoadWithEnabledFalse(): void <ide> */ <ide> public function testLoadMissingHelper(): void <ide> { <del> $this->expectException(\Cake\View\Exception\MissingHelperException::class); <add> $this->expectException(MissingHelperException::class); <ide> $this->Helpers->load('ThisHelperShouldAlwaysBeMissing'); <ide> } <ide> <ide> public function testUnload(): void <ide> */ <ide> public function testUnloadUnknown(): void <ide> { <del> $this->expectException(\Cake\View\Exception\MissingHelperException::class); <add> $this->expectException(MissingHelperException::class); <ide> $this->expectExceptionMessage('Helper class FooHelper could not be found.'); <ide> $this->Helpers->unload('Foo'); <ide> } <ide> public function testLoadMultipleTimesDefaultConfigValuesWorks(): void <ide> */ <ide> public function testLoadMultipleTimesDifferentConfigured(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> $this->expectExceptionMessage('The "Html" alias has already been loaded'); <ide> $this->Helpers->load('Html'); <ide> $this->Helpers->load('Html', ['same' => 'stuff']); <ide> public function testLoadMultipleTimesDifferentConfigured(): void <ide> */ <ide> public function testLoadMultipleTimesDifferentConfigValues(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> $this->expectExceptionMessage('The "Html" alias has already been loaded'); <ide> $this->Helpers->load('Html', ['key' => 'value']); <ide> $this->Helpers->load('Html', ['key' => 'new value']); <ide><path>tests/TestCase/View/StringTemplateTest.php <ide> */ <ide> namespace Cake\Test\TestCase\View; <ide> <add>use Cake\Core\Exception\CakeException; <ide> use Cake\TestSuite\TestCase; <ide> use Cake\View\StringTemplate; <add>use RuntimeException; <add>use stdClass; <ide> <ide> class StringTemplateTest extends TestCase <ide> { <ide> public function testFormatArrayData(): void <ide> */ <ide> public function testFormatMissingTemplate(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> $this->expectExceptionMessage('Cannot find template named \'missing\''); <ide> $templates = [ <ide> 'text' => '{{text}}', <ide> public function testLoadPlugin(): void <ide> */ <ide> public function testLoadErrorNoFile(): void <ide> { <del> $this->expectException(\Cake\Core\Exception\CakeException::class); <add> $this->expectException(CakeException::class); <ide> $this->expectExceptionMessage('Could not load configuration file'); <ide> $this->template->load('no_such_file'); <ide> } <ide> public function testAddClassMethodCurrentClass(): void <ide> $result = $this->template->addClass(false, 'new_class'); <ide> $this->assertEquals($result, ['class' => ['new_class']]); <ide> <del> $result = $this->template->addClass(new \stdClass(), 'new_class'); <add> $result = $this->template->addClass(new stdClass(), 'new_class'); <ide> $this->assertEquals($result, ['class' => ['new_class']]); <ide> } <ide> <ide><path>tests/TestCase/View/ViewBuilderTest.php <ide> use Cake\Http\Response; <ide> use Cake\Http\ServerRequest; <ide> use Cake\TestSuite\TestCase; <add>use Cake\View\Exception\MissingViewException; <ide> use Cake\View\ViewBuilder; <ide> <ide> /** <ide> public function testBuildAppViewPresent(): void <ide> */ <ide> public function testBuildMissingViewClass(): void <ide> { <del> $this->expectException(\Cake\View\Exception\MissingViewException::class); <add> $this->expectException(MissingViewException::class); <ide> $this->expectExceptionMessage('View class "Foo" is missing.'); <ide> $builder = new ViewBuilder(); <ide> $builder->setClassName('Foo'); <ide><path>tests/TestCase/View/ViewTest.php <ide> use Cake\Controller\Controller; <ide> use Cake\Core\App; <ide> use Cake\Core\Configure; <add>use Cake\Core\Exception\CakeException; <ide> use Cake\Core\Plugin; <ide> use Cake\Event\EventInterface; <ide> use Cake\Http\Response; <ide> use Cake\Http\ServerRequest; <ide> use Cake\TestSuite\TestCase; <add>use Cake\View\Exception\MissingElementException; <add>use Cake\View\Exception\MissingLayoutException; <add>use Cake\View\Exception\MissingTemplateException; <ide> use Cake\View\View; <add>use Exception; <add>use InvalidArgumentException; <add>use LogicException; <add>use PDOException; <ide> use RuntimeException; <ide> use TestApp\Controller\ThemePostsController; <ide> use TestApp\Controller\ViewPostsController; <ide> public function testPluginGetTemplate(): void <ide> */ <ide> public function testPluginGetTemplateAbsoluteFail(): void <ide> { <del> $this->expectException(\Cake\View\Exception\MissingTemplateException::class); <add> $this->expectException(MissingTemplateException::class); <ide> $viewOptions = [ <ide> 'plugin' => null, <ide> 'name' => 'Pages', <ide> public function testGetViewFileNames(): void <ide> */ <ide> public function testGetViewFileNameDirectoryTraversal(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $viewOptions = [ <ide> 'plugin' => null, <ide> 'name' => 'Pages', <ide> public function testGetLayoutFileNamePrefix(): void <ide> */ <ide> public function testGetLayoutFileNameDirectoryTraversal(): void <ide> { <del> $this->expectException(\InvalidArgumentException::class); <add> $this->expectException(InvalidArgumentException::class); <ide> $viewOptions = [ <ide> 'plugin' => null, <ide> 'name' => 'Pages', <ide> public function testGetLayoutFileNameDirectoryTraversal(): void <ide> */ <ide> public function testMissingTemplate(): void <ide> { <del> $this->expectException(\Cake\View\Exception\MissingTemplateException::class); <add> $this->expectException(MissingTemplateException::class); <ide> $this->expectExceptionMessage('Template file `does_not_exist.php` could not be found'); <ide> $this->expectExceptionMessage('The following paths were searched'); <ide> $this->expectExceptionMessage('- `' . ROOT . DS . 'templates' . DS . 'does_not_exist.php`'); <ide> public function testMissingTemplate(): void <ide> */ <ide> public function testMissingLayout(): void <ide> { <del> $this->expectException(\Cake\View\Exception\MissingLayoutException::class); <add> $this->expectException(MissingLayoutException::class); <ide> $this->expectExceptionMessage('Layout file `whatever.php` could not be found'); <ide> $this->expectExceptionMessage('The following paths were searched'); <ide> $this->expectExceptionMessage('- `' . ROOT . DS . 'templates' . DS . 'layout' . DS . 'whatever.php`'); <ide> public function testPrefixElement(): void <ide> */ <ide> public function testElementMissing(): void <ide> { <del> $this->expectException(\Cake\View\Exception\MissingElementException::class); <add> $this->expectException(MissingElementException::class); <ide> $this->expectExceptionMessage('Element file `nonexistent_element.php` could not be found'); <ide> <ide> $this->View->element('nonexistent_element'); <ide> public function testElementMissing(): void <ide> */ <ide> public function testElementMissingPluginElement(): void <ide> { <del> $this->expectException(\Cake\View\Exception\MissingElementException::class); <add> $this->expectException(MissingElementException::class); <ide> $this->expectExceptionMessage('Element file `TestPlugin.nope.php` could not be found'); <ide> $this->expectExceptionMessage(implode(DS, ['test_app', 'templates', 'plugin', 'TestPlugin', 'element', 'nope.php'])); <ide> $this->expectExceptionMessage(implode(DS, ['test_app', 'Plugin', 'TestPlugin', 'templates', 'element', 'nope.php'])); <ide> public function testLoadHelperDuplicate(): void <ide> try { <ide> $View->loadHelper('Html', ['test' => 'value']); <ide> $this->fail('No exception'); <del> } catch (\RuntimeException $e) { <add> } catch (RuntimeException $e) { <ide> $this->assertStringContainsString('The "Html" alias has already been loaded', $e->getMessage()); <ide> } <ide> } <ide> public function testRenderUsingViewProperty(): void <ide> */ <ide> public function testRenderUsingLayoutArgument(): void <ide> { <del> $error = new \PDOException(); <add> $error = new PDOException(); <ide> $error->queryString = 'this is sql string'; <ide> $message = 'it works'; <ide> $trace = $error->getTrace(); <ide> public function testStartBlocksTwice(): void <ide> $this->View->start('first'); <ide> $this->View->start('first'); <ide> $this->fail('No exception'); <del> } catch (\Cake\Core\Exception\CakeException $e) { <add> } catch (CakeException $e) { <ide> ob_end_clean(); <ide> $this->assertTrue(true); <ide> } <ide> public function testExceptionOnOpenBlock(): void <ide> try { <ide> $this->View->render('open_block'); <ide> $this->fail('No exception'); <del> } catch (\LogicException $e) { <add> } catch (LogicException $e) { <ide> ob_end_clean(); <ide> $this->assertStringContainsString('The "no_close" block was left open', $e->getMessage()); <ide> } <ide> public function testExtendSelf(): void <ide> try { <ide> $this->View->render('extend_self', false); <ide> $this->fail('No exception'); <del> } catch (\LogicException $e) { <add> } catch (LogicException $e) { <ide> $this->assertStringContainsString('cannot have templates extend themselves', $e->getMessage()); <ide> } <ide> } <ide> public function testExtendLoop(): void <ide> try { <ide> $this->View->render('extend_loop', false); <ide> $this->fail('No exception'); <del> } catch (\LogicException $e) { <add> } catch (LogicException $e) { <ide> $this->assertStringContainsString('cannot have templates extend in a loop', $e->getMessage()); <ide> } <ide> } <ide> public function testExtendMissingElement(): void <ide> try { <ide> $this->View->render('extend_missing_element', false); <ide> $this->fail('No exception'); <del> } catch (\LogicException $e) { <add> } catch (LogicException $e) { <ide> $this->assertStringContainsString('element', $e->getMessage()); <ide> } <ide> } <ide> public function testBuffersOpenedDuringTemplateEvaluationAreBeingClosed(): void <ide> $e = null; <ide> try { <ide> $this->View->element('exception_with_open_buffers'); <del> } catch (\Exception $e) { <add> } catch (Exception $e) { <ide> } <ide> <ide> $this->assertNotNull($e); <ide> public function testBuffersOpenedDuringBlockCachingAreBeingClosed(): void <ide> $this->View->cache(function (): void { <ide> ob_start(); <ide> <del> throw new \Exception('Exception with open buffers'); <add> throw new Exception('Exception with open buffers'); <ide> }, [ <ide> 'key' => __FUNCTION__, <ide> 'config' => 'test_view', <ide> ]); <del> } catch (\Exception $e) { <add> } catch (Exception $e) { <ide> } <ide> <ide> Cache::clear('test_view'); <ide><path>tests/TestCase/View/ViewVarsTraitTest.php <ide> <ide> use Cake\Controller\Controller; <ide> use Cake\TestSuite\TestCase; <add>use Cake\View\Exception\MissingViewException; <ide> <ide> /** <ide> * ViewVarsTrait test case <ide> public function testCreateViewParameter(): void <ide> */ <ide> public function testCreateViewException(): void <ide> { <del> $this->expectException(\Cake\View\Exception\MissingViewException::class); <add> $this->expectException(MissingViewException::class); <ide> $this->expectExceptionMessage('View class "Foo" is missing.'); <ide> $this->subject->createView('Foo'); <ide> } <ide><path>tests/TestCase/View/Widget/DateTimeWidgetTest.php <ide> use Cake\View\Form\NullContext; <ide> use Cake\View\StringTemplate; <ide> use Cake\View\Widget\DateTimeWidget; <add>use DateTime; <ide> <ide> /** <ide> * DateTimeWidget test case <ide> public function testRenderInvalid($selected): void <ide> */ <ide> public static function selectedValuesProvider(): array <ide> { <del> $date = new \DateTime('2014-01-20 12:30:45'); <add> $date = new DateTime('2014-01-20 12:30:45'); <ide> <ide> return [ <ide> 'DateTime' => [$date], <ide> public function testRenderInvalidTypeException(): void <ide> { <ide> $this->expectException('InvalidArgumentException'); <ide> $this->expectExceptionMessage('Invalid type `foo` for input tag, expected datetime-local, date, time, month or week'); <del> $result = $this->DateTime->render(['type' => 'foo', 'val' => new \DateTime()], $this->context); <add> $result = $this->DateTime->render(['type' => 'foo', 'val' => new DateTime()], $this->context); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/View/Widget/SelectBoxWidgetTest.php <ide> */ <ide> namespace Cake\Test\TestCase\View\Widget; <ide> <add>use ArrayObject; <ide> use Cake\Collection\Collection; <ide> use Cake\TestSuite\TestCase; <ide> use Cake\View\Form\NullContext; <ide> public function testRenderBoolean(): void <ide> public function testRenderSimpleIterator(): void <ide> { <ide> $select = new SelectBoxWidget($this->templates); <del> $options = new \ArrayObject(['a' => 'Albatross', 'b' => 'Budgie']); <add> $options = new ArrayObject(['a' => 'Albatross', 'b' => 'Budgie']); <ide> $data = [ <ide> 'name' => 'Birds[name]', <ide> 'options' => $options, <ide> public function testRenderOptionGroupsWithAttributes(): void <ide> public function testRenderOptionGroupsTraversable(): void <ide> { <ide> $select = new SelectBoxWidget($this->templates); <del> $mammals = new \ArrayObject(['beaver' => 'Beaver', 'elk' => 'Elk']); <add> $mammals = new ArrayObject(['beaver' => 'Beaver', 'elk' => 'Elk']); <ide> $data = [ <ide> 'name' => 'Birds[name]', <ide> 'options' => [ <ide><path>tests/TestCase/View/Widget/WidgetLocatorTest.php <ide> use Cake\View\StringTemplate; <ide> use Cake\View\View; <ide> use Cake\View\Widget\WidgetLocator; <add>use RuntimeException; <add>use stdClass; <ide> use TestApp\View\Widget\TestUsingViewWidget; <ide> <ide> /** <ide> public function testAdd(): void <ide> */ <ide> public function testAddInvalidType(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> $this->expectExceptionMessage( <ide> 'Widget objects must implement `Cake\View\Widget\WidgetInterface`. Got `stdClass` instance instead.' <ide> ); <ide> $inputs = new WidgetLocator($this->templates, $this->view); <ide> $inputs->add([ <del> 'text' => new \stdClass(), <add> 'text' => new stdClass(), <ide> ]); <ide> } <ide> <ide> public function testGetFallback(): void <ide> */ <ide> public function testGetNoFallbackError(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> $this->expectExceptionMessage('Unknown widget `foo`'); <ide> $inputs = new WidgetLocator($this->templates, $this->view); <ide> $inputs->clear(); <ide> public function testGetResolveDependency(): void <ide> */ <ide> public function testGetResolveDependencyMissingClass(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> $this->expectExceptionMessage('Unable to locate widget class "TestApp\View\DerpWidget"'); <ide> $inputs = new WidgetLocator($this->templates, $this->view); <ide> $inputs->add(['test' => ['TestApp\View\DerpWidget']]); <ide> public function testGetResolveDependencyMissingClass(): void <ide> */ <ide> public function testGetResolveDependencyMissingDependency(): void <ide> { <del> $this->expectException(\RuntimeException::class); <add> $this->expectException(RuntimeException::class); <ide> $this->expectExceptionMessage('Unknown widget `label`'); <ide> $inputs = new WidgetLocator($this->templates, $this->view); <ide> $inputs->clear(); <ide><path>tests/test_app/Plugin/TestPlugin/src/View/Cell/Admin/MenuCell.php <ide> */ <ide> namespace TestPlugin\View\Cell\Admin; <ide> <add>use Cake\View\Cell; <add> <ide> /** <ide> * TestPlugin Admin Menu Cell <ide> */ <del>class MenuCell extends \Cake\View\Cell <add>class MenuCell extends Cell <ide> { <ide> /** <ide> * Default cell action. <ide><path>tests/test_app/Plugin/TestPlugin/src/View/Cell/DummyCell.php <ide> */ <ide> namespace TestPlugin\View\Cell; <ide> <add>use Cake\View\Cell; <add> <ide> /** <ide> * DummyCell class <ide> */ <del>class DummyCell extends \Cake\View\Cell <add>class DummyCell extends Cell <ide> { <ide> /** <ide> * Default cell action. <ide><path>tests/test_app/TestApp/Collection/CountableIterator.php <ide> <ide> namespace TestApp\Collection; <ide> <del>class CountableIterator extends \IteratorIterator implements \Countable <add>use Countable; <add>use IteratorIterator; <add> <add>class CountableIterator extends IteratorIterator implements Countable <ide> { <ide> /** <ide> * @param mixed $items <ide><path>tests/test_app/TestApp/Collection/TestCollection.php <ide> <ide> namespace TestApp\Collection; <ide> <add>use ArrayIterator; <ide> use Cake\Collection\CollectionInterface; <ide> use Cake\Collection\CollectionTrait; <add>use InvalidArgumentException; <add>use IteratorIterator; <add>use Traversable; <ide> <del>class TestCollection extends \IteratorIterator implements CollectionInterface <add>class TestCollection extends IteratorIterator implements CollectionInterface <ide> { <ide> use CollectionTrait; <ide> <ide> class TestCollection extends \IteratorIterator implements CollectionInterface <ide> public function __construct(iterable $items) <ide> { <ide> if (is_array($items)) { <del> $items = new \ArrayIterator($items); <add> $items = new ArrayIterator($items); <ide> } <ide> <del> if (!($items instanceof \Traversable)) { <add> if (!($items instanceof Traversable)) { <ide> $msg = 'Only an array or \Traversable is allowed for Collection'; <del> throw new \InvalidArgumentException($msg); <add> throw new InvalidArgumentException($msg); <ide> } <ide> <ide> parent::__construct($items); <ide><path>tests/test_app/TestApp/Controller/PostsController.php <ide> <ide> use Cake\Event\EventInterface; <ide> use Cake\Http\Cookie\Cookie; <add>use OutOfBoundsException; <ide> <ide> /** <ide> * PostsController class <ide> public function stacked_flash() <ide> public function throw_exception() <ide> { <ide> $this->Flash->error('Error 1'); <del> throw new \OutOfBoundsException('oh no!'); <add> throw new OutOfBoundsException('oh no!'); <ide> } <ide> } <ide><path>tests/test_app/TestApp/Controller/TestsAppsController.php <ide> */ <ide> namespace TestApp\Controller; <ide> <add>use RuntimeException; <add> <ide> class TestsAppsController extends AppController <ide> { <ide> public function index() <ide> public function set_type() <ide> <ide> public function throw_exception() <ide> { <del> throw new \RuntimeException('Foo'); <add> throw new RuntimeException('Foo'); <ide> } <ide> } <ide><path>tests/test_app/TestApp/Database/Type/ColumnSchemaAwareType.php <ide> use Cake\Database\Type\BaseType; <ide> use Cake\Database\Type\ColumnSchemaAwareInterface; <ide> use Cake\Database\Type\ExpressionTypeInterface; <add>use InvalidArgumentException; <ide> use TestApp\Database\ColumnSchemaAwareTypeValueObject; <ide> <ide> class ColumnSchemaAwareType extends BaseType implements ExpressionTypeInterface, ColumnSchemaAwareInterface <ide> public function toExpression($value): ExpressionInterface <ide> ); <ide> } <ide> <del> throw new \InvalidArgumentException(sprintf( <add> throw new InvalidArgumentException(sprintf( <ide> 'The `$value` argument must be an instance of `\%s`, or a string, `%s` given.', <ide> ColumnSchemaAwareTypeValueObject::class, <ide> getTypeName($value) <ide><path>tests/test_app/TestApp/Error/TestAppsExceptionRenderer.php <ide> use Cake\Http\Response; <ide> use Cake\Http\ServerRequest; <ide> use Cake\Routing\Router; <add>use Exception; <ide> use TestApp\Controller\TestAppsErrorController; <ide> <ide> class TestAppsExceptionRenderer extends ExceptionRenderer <ide> protected function _getController(): Controller <ide> try { <ide> $controller = new TestAppsErrorController($request, $response); <ide> $controller->viewBuilder()->setLayout('banana'); <del> } catch (\Exception $e) { <add> } catch (Exception $e) { <ide> $controller = new Controller($request, $response); <ide> $controller->viewBuilder()->setTemplatePath('Error'); <ide> } <ide><path>tests/test_app/TestApp/Http/Client/Adapter/CakeStreamWrapper.php <ide> namespace TestApp\Http\Client\Adapter; <ide> <ide> use ArrayAccess; <add>use Exception; <ide> use ReturnTypeWillChange; <ide> <ide> class CakeStreamWrapper implements ArrayAccess <ide> class CakeStreamWrapper implements ArrayAccess <ide> public function stream_open(string $path, string $mode, int $options, ?string &$openedPath): bool <ide> { <ide> if ($path === 'http://throw_exception/') { <del> throw new \Exception(); <add> throw new Exception(); <ide> } <ide> <ide> $query = parse_url($path, PHP_URL_QUERY); <ide><path>tests/test_app/TestApp/View/Cell/Admin/MenuCell.php <ide> */ <ide> namespace TestApp\View\Cell\Admin; <ide> <add>use Cake\View\Cell; <add> <ide> /** <ide> * Admin Menu Cell <ide> */ <del>class MenuCell extends \Cake\View\Cell <add>class MenuCell extends Cell <ide> { <ide> /** <ide> * Default cell action. <ide><path>tests/test_app/TestApp/View/Cell/ArticlesCell.php <ide> */ <ide> namespace TestApp\View\Cell; <ide> <add>use Cake\View\Cell; <add> <ide> /** <ide> * TagCloudCell class <ide> */ <del>class ArticlesCell extends \Cake\View\Cell <add>class ArticlesCell extends Cell <ide> { <ide> /** <ide> * valid cell options.
147
Javascript
Javascript
simplify err_require_esm message generation
f54254afedd5a2b4800854e7766d845e3803bef6
<ide><path>lib/internal/errors.js <ide> E('ERR_REQUIRE_ESM', <ide> filename : path.basename(filename); <ide> msg += <ide> '\nrequire() of ES modules is not supported.\nrequire() of ' + <del> `${filename} ${parentPath ? `from ${parentPath} ` : ''}` + <add> `${filename} from ${parentPath} ` + <ide> 'is an ES module file as it is a .js file whose nearest parent ' + <ide> 'package.json contains "type": "module" which defines all .js ' + <ide> 'files in that package scope as ES modules.\nInstead rename ' +
1
Python
Python
use consistent quoting and docstring style
cff3adf20230d47e7f77329262f38a7bf90820b0
<ide><path>libcloud/compute/base.py <ide> <ide> <ide> __all__ = [ <del> "Node", <del> "NodeState", <del> "NodeSize", <del> "NodeImage", <del> "NodeLocation", <del> "NodeAuthSSHKey", <del> "NodeAuthPassword", <del> "NodeDriver" <add> 'Node', <add> 'NodeState', <add> 'NodeSize', <add> 'NodeImage', <add> 'NodeLocation', <add> 'NodeAuthSSHKey', <add> 'NodeAuthPassword', <add> 'NodeDriver' <ide> ] <ide> <ide> <ide> def __init__(self): <ide> self._uuid = None <ide> <ide> def get_uuid(self): <del> """Unique hash for a node, node image, or node size <del> <del> :return: ``string`` <add> """ <add> Unique hash for a node, node image, or node size <ide> <ide> The hash is a function of an SHA1 hash of the node, node image, <ide> or node size's ID and its driver which means that it should be <ide> def get_uuid(self): <ide> <ide> Note, for example, that this example will always produce the <ide> same UUID! <add> <add> :rtype: ``str`` <ide> """ <ide> if not self._uuid: <ide> self._uuid = hashlib.sha1(b('%s:%s' % <ide> def _get_private_ips(self): <ide> private_ip = property(fget=_get_private_ips, fset=_set_private_ips) <ide> <ide> def reboot(self): <del> """Reboot this node <add> """ <add> Reboot this node <ide> <ide> :return: ``bool`` <ide> <ide> def reboot(self): <ide> return self.driver.reboot_node(self) <ide> <ide> def destroy(self): <del> """Destroy this node <add> """ <add> Destroy this node <ide> <ide> :return: ``bool`` <ide> <ide> def create_node(self, **kwargs): <ide> 'create_node not implemented for this driver') <ide> <ide> def destroy_node(self, node): <del> """Destroy a node. <add> """ <add> Destroy a node. <ide> <ide> Depending upon the provider, this may destroy all data associated with <ide> the node, including backups. <ide> def reboot_node(self, node): <ide> <ide> def list_nodes(self): <ide> """ <del> List all nodes <add> List all nodes. <add> <ide> :return: list of node objects <ide> :rtype: ``list`` of :class:`.Node` <ide> """ <ide> def is_valid_ip_address(address, family=socket.AF_INET): <ide> return True <ide> <ide> <del>if __name__ == "__main__": <add>if __name__ == '__main__': <ide> import doctest <ide> doctest.testmod() <ide><path>libcloud/loadbalancer/base.py <ide> from libcloud.common.types import LibcloudError <ide> <ide> __all__ = [ <del> "Member", <del> "LoadBalancer", <del> "Driver", <del> "Algorithm" <add> 'Member', <add> 'LoadBalancer', <add> 'Driver', <add> 'Algorithm' <ide> ] <ide> <ide>
2
PHP
PHP
add test for removecolumn
5475631046088ff7fe5c5f8e5c83fe54f9c84893
<ide><path>tests/Database/DatabaseSchemaBlueprintTest.php <ide> public function testUnsignedDecimalTable() <ide> $blueprint = clone $base; <ide> $this->assertEquals(['alter table `users` add `money` decimal(10, 2) unsigned not null'], $blueprint->toSql($connection, new MySqlGrammar)); <ide> } <add> <add> public function testRemoveColumn() <add> { <add> $base = new Blueprint('users', function ($table) { <add> $table->string('foo'); <add> $table->string('remove_this'); <add> $table->removeColumn('remove_this'); <add> }); <add> <add> $connection = m::mock(Connection::class); <add> <add> $blueprint = clone $base; <add> <add> $this->assertEquals(['alter table `users` add `foo` varchar(255) not null'], $blueprint->toSql($connection, new MySqlGrammar)); <add> } <ide> }
1
PHP
PHP
add iscreate() method to context classes
53e500531e7fc9cd77291c60261a26b6dcdfc72c
<ide><path>src/View/Form/ArrayContext.php <ide> * like maxlength, step and other HTML attributes. <ide> * - `errors` An array of validation errors. Errors should be nested following <ide> * the dot separated paths you access your fields with. <add> * - `isCreate` A boolean that indicates whether or not this form should <add> * be treated as a create operation. If false this form will be an update. <ide> */ <ide> class ArrayContext { <ide> <ide> public function __construct(Request $request, array $context) { <ide> 'required' => [], <ide> 'defaults' => [], <ide> 'errors' => [], <add> 'create' => true, <ide> ]; <ide> $this->_context = $context; <ide> } <ide> <add>/** <add> * Returns whether or not this form is for a create operation. <add> * <add> * @return boolean <add> */ <add> public function isCreate() { <add> return (bool)$this->_context['create']; <add> } <add> <ide> /** <ide> * Get the current value for a given field. <ide> * <ide><path>src/View/Form/EntityContext.php <ide> protected function _prepare() { <ide> $this->_tables[$alias] = $table; <ide> } <ide> <add>/** <add> * Check whether or not this form is a create or update. <add> * <add> * If the context is for a single entity, the entity's isNew() method will <add> * be used. If isNew() returns null, a create operation will be assumed. <add> * <add> * If the context is for a collection or array the first object in the <add> * collection will be used. <add> * <add> * @return boolean <add> */ <add> public function isCreate() { <add> $entity = $this->_context['entity']; <add> if (is_array($entity) || $entity instanceof Traversable) { <add> $entity = (new Collection($entity))->first(); <add> } <add> if ($entity instanceof Entity) { <add> return $entity->isNew() !== false; <add> } <add> return true; <add> } <add> <ide> /** <ide> * Get the value for a given path. <ide> * <ide><path>src/View/Form/NullContext.php <ide> public function __construct(Request $request, array $context) { <ide> $this->_request = $request; <ide> } <ide> <add>/** <add> * Returns whether or not this form is for a create operation. <add> * <add> * @return boolean <add> */ <add> public function isCreate() { <add> return true; <add> } <add> <ide> /** <ide> * Get the current value for a given field. <ide> * <ide><path>tests/TestCase/View/Form/ArrayContextTest.php <ide> public function setUp() { <ide> $this->request = new Request(); <ide> } <ide> <add>/** <add> * Test the isCreate method. <add> * <add> * @return void <add> */ <add> public function testIsCreate() { <add> $context = new ArrayContext($this->request, []); <add> $this->assertTrue($context->isCreate()); <add> <add> $context = new ArrayContext($this->request, [ <add> 'create' => false, <add> ]); <add> $this->assertFalse($context->isCreate()); <add> <add> $context = new ArrayContext($this->request, [ <add> 'create' => true, <add> ]); <add> $this->assertTrue($context->isCreate()); <add> } <add> <ide> /** <ide> * Test reading values from the request & defaults. <ide> */ <ide><path>tests/TestCase/View/Form/EntityContextTest.php <ide> public function setUp() { <ide> $this->request = new Request(); <ide> } <ide> <add>/** <add> * Test isCreate on a single entity. <add> * <add> * @return void <add> */ <add> public function testIsCreateSingle() { <add> $row = new Entity(); <add> $context = new EntityContext($this->request, [ <add> 'entity' => $row, <add> ]); <add> $this->assertTrue($context->isCreate()); <add> <add> $row->isNew(false); <add> $this->assertFalse($context->isCreate()); <add> <add> $row->isNew(true); <add> $this->assertTrue($context->isCreate()); <add> } <add> <add>/** <add> * Test isCreate on a collection. <add> * <add> * @dataProvider collectionProvider <add> * @return void <add> */ <add> public function testIsCreateCollection($collection) { <add> $context = new EntityContext($this->request, [ <add> 'entity' => $collection, <add> ]); <add> $this->assertTrue($context->isCreate()); <add> } <add> <ide> /** <ide> * Test an invalid table scope throws an error. <ide> *
5
Text
Text
fix typo in image optimization documentation
8b485e161df72b9f33e62f441a32607997ee98e4
<ide><path>docs/basic-features/image-optimization.md <ide> import profilePic from '../public/me.png' <ide> <ide> Dynamic `await import()` or `require()` are _not_ supported. The `import` must be static. Also note that static image support requires Webpack 5, which is enabled by default in Next.js applications. <ide> <del>Next.js will automatically determine the `width` and `height` or your image based on the imported file. These values are used to prevent [Cumulative Layout Shift](https://nextjs.org/learn/seo/web-performance/cls) while your image is loading. <add>Next.js will automatically determine the `width` and `height` of your image based on the imported file. These values are used to prevent [Cumulative Layout Shift](https://nextjs.org/learn/seo/web-performance/cls) while your image is loading. <ide> <ide> ```js <ide> import Image from 'next/image'
1
Javascript
Javascript
add support for #each foo in bar
dd1851eea9fc6979570ba761cd1931c3a1ee7e57
<ide><path>packages/ember-handlebars/lib/helpers/collection.js <ide> Ember.Handlebars.registerHelper('collection', function(path, options) { <ide> } <ide> <ide> if (inverse && inverse !== Handlebars.VM.noop) { <del> var emptyViewClass = Ember.View; <del> <del> if (hash.emptyViewClass) { <del> emptyViewClass = Ember.View.detect(hash.emptyViewClass) ? <del> hash.emptyViewClass : getPath(this, hash.emptyViewClass, options); <del> } <add> var emptyViewClass = get(collectionPrototype, 'emptyViewClass'); <ide> <ide> hash.emptyView = emptyViewClass.extend({ <ide> template: inverse, <ide> tagName: itemHash.tagName <ide> }); <ide> } <ide> <del> if (hash.preserveContext) { <add> if (hash.eachHelper === 'each') { <ide> itemHash._templateContext = Ember.computed(function() { <ide> return get(this, 'content'); <ide> }).property('content'); <del> delete hash.preserveContext; <add> delete hash.eachHelper; <ide> } <ide> <ide> hash.itemViewClass = Ember.Handlebars.ViewHelper.viewClassFromHTMLOptions(itemViewClass, { data: data, hash: itemHash }, this); <ide><path>packages/ember-handlebars/lib/helpers/each.js <ide> require("ember-handlebars/ext"); <ide> require("ember-views/views/collection_view"); <ide> require("ember-handlebars/views/metamorph_view"); <ide> <add>var get = Ember.get, set = Ember.set; <add> <ide> Ember.Handlebars.EachView = Ember.CollectionView.extend(Ember._Metamorph, { <del> itemViewClass: Ember._MetamorphView <add> itemViewClass: Ember._MetamorphView, <add> emptyViewClass: Ember._MetamorphView, <add> <add> createChildView: function(view, attrs) { <add> view = this._super(view, attrs); <add> <add> // At the moment, if a container view subclass wants <add> // to insert keywords, it is responsible for cloning <add> // the keywords hash. This will be fixed momentarily. <add> var keyword = get(this, 'keyword'); <add> <add> if (keyword) { <add> var data = get(view, 'templateData'); <add> <add> data = Ember.copy(data); <add> data.keywords = view.cloneKeywords(); <add> set(view, 'templateData', data); <add> <add> var content = get(view, 'content'); <add> <add> // In this case, we do not bind, because the `content` of <add> // a #each item cannot change. <add> data.keywords[keyword] = content; <add> } <add> <add> return view; <add> } <ide> }); <ide> <ide> Ember.Handlebars.registerHelper('each', function(path, options) { <del> options.hash.contentBinding = path; <del> options.hash.preserveContext = true; <add> if (arguments.length === 4) { <add> Ember.assert("If you pass more than one argument to the each helper, it must be in the form #each foo in bar", arguments[1] === "in"); <add> <add> var keywordName = arguments[0]; <add> <add> options = arguments[3]; <add> path = arguments[2]; <ide> <add> options.hash.keyword = keywordName; <add> } else { <add> options.hash.eachHelper = 'each'; <add> } <add> <add> Ember.assert("You must pass a block to the each helper", options.fn && options.fn !== Handlebars.VM.noop); <add> <add> options.hash.contentBinding = path; <ide> // Set up emptyView as a metamorph with no tag <del> options.hash.itemTagName = ''; <del> options.hash.emptyViewClass = Ember._MetamorphView; <add> //options.hash.emptyViewClass = Ember._MetamorphView; <ide> <ide> return Ember.Handlebars.helpers.collection.call(this, 'Ember.Handlebars.EachView', options); <ide> }); <add><path>packages/ember-handlebars/tests/helpers/each_test.js <del><path>packages/ember-handlebars/tests/each_test.js <ide> test("it works with the controller keyword", function() { <ide> <ide> equal(view.$().text(), "foobarbaz"); <ide> }); <add> <add>module("{{#each foo in bar}}"); <add> <add>test("#each accepts a name binding and does not change the context", function() { <add> view = Ember.View.create({ <add> template: templateFor("{{#each item in items}}{{title}} {{debugger}}{{item}}{{/each}}"), <add> title: "My Cool Each Test", <add> items: Ember.A([1, 2]) <add> }); <add> <add> append(view); <add> <add> equal(view.$().text(), "My Cool Each Test 1My Cool Each Test 2"); <add>}); <add> <add>test("#each accepts a name binding and can display child properties", function() { <add> view = Ember.View.create({ <add> template: templateFor("{{#each item in items}}{{title}} {{item.name}}{{/each}}"), <add> title: "My Cool Each Test", <add> items: Ember.A([{ name: 1 }, { name: 2 }]) <add> }); <add> <add> append(view); <add> <add> equal(view.$().text(), "My Cool Each Test 1My Cool Each Test 2"); <add>}); <ide><path>packages/ember-handlebars/tests/views/collection_view_test.js <ide> test("empty views should be removed when content is added to the collection (reg <ide> Ember.run(function(){ window.App.destroy(); }); <ide> }); <ide> <del>test("collection helper should accept emptyViewClass attribute", function() { <del> window.App = Ember.Application.create(); <del> <del> App.EmptyView = Ember.View.extend({ <del> classNames: ['empty'] <del> }); <del> <del> App.ListController = Ember.ArrayProxy.create({ <del> content : Ember.A() <del> }); <del> <del> view = Ember.View.create({ <del> template: Ember.Handlebars.compile('{{#collection emptyViewClass="App.EmptyView" contentBinding="App.ListController" tagName="table"}} <td>{{content.title}}</td> {{/collection}}') <del> }); <del> <del> Ember.run(function() { <del> view.appendTo('#qunit-fixture'); <del> }); <del> <del> equal(view.$('tr').length, 0, 'emptyViewClass has no effect without inverse'); <del> view.remove(); <del> <del> view = Ember.View.create({ <del> template: Ember.Handlebars.compile('{{#collection emptyViewClass="App.EmptyView" contentBinding="App.ListController" tagName="table"}} <td>{{content.title}}</td> {{else}} <td>No Rows Yet</td> {{/collection}}') <del> }); <del> <del> Ember.run(function() { <del> view.appendTo('#qunit-fixture'); <del> }); <del> <del> equal(view.$('tr').hasClass('empty'), 1, 'if emptyViewClass is given it is used for inverse'); <del> <del> Ember.run(function(){ window.App.destroy(); }); <del>}); <del> <ide> test("if no content is passed, and no 'else' is specified, nothing is rendered", function() { <ide> TemplateTests.CollectionTestView = Ember.CollectionView.extend({ <ide> tagName: 'ul', <ide><path>packages/ember-views/lib/views/collection_view.js <ide> Ember.CollectionView = Ember.ContainerView.extend( <ide> */ <ide> content: null, <ide> <add> /** <add> @private <add> <add> This provides metadata about what kind of empty view class this <add> collection would like if it is being instantiated from another <add> system (like Handlebars) <add> */ <add> emptyViewClass: Ember.View, <add> <ide> /** <ide> An optional view to display if content is set to an empty array. <ide> <ide><path>packages/ember-views/lib/views/container_view.js <ide> Ember.ContainerView = Ember.View.extend({ <ide> initializeViews: function(views, parentView, templateData) { <ide> forEach(views, function(view) { <ide> set(view, '_parentView', parentView); <del> set(view, 'templateData', templateData); <add> <add> if (!get(view, 'templateData')) { <add> set(view, 'templateData', templateData); <add> } <ide> }); <ide> }, <ide> <ide><path>packages/ember-views/lib/views/view.js <ide> Ember.View = Ember.Object.extend(Ember.Evented, <ide> }); <ide> }, '_parentView'), <ide> <add> cloneKeywords: function() { <add> var templateData = get(this, 'templateData'), <add> controller = get(this, 'controller'); <add> <add> var keywords = templateData ? Ember.copy(templateData.keywords) : {}; <add> keywords.view = get(this, 'concreteView'); <add> <add> // If the view has a controller specified, make it available to the <add> // template. If not, pass along the parent template's controller, <add> // if it exists. <add> if (controller) { <add> keywords.controller = controller; <add> } <add> <add> return keywords; <add> }, <add> <ide> /** <ide> Called on your view when it should push strings of HTML into a <ide> Ember.RenderBuffer. Most users will want to override the `template` <ide> Ember.View = Ember.Object.extend(Ember.Evented, <ide> var template = get(this, 'layout') || get(this, 'template'); <ide> <ide> if (template) { <del> var context = get(this, '_templateContext'), <del> templateData = this.get('templateData'), <del> controller = this.get('controller'); <del> <del> var keywords = templateData ? Ember.copy(templateData.keywords) : {}; <del> keywords.view = get(this, 'concreteView'); <del> <del> // If the view has a controller specified, make it available to the <del> // template. If not, pass along the parent template's controller, <del> // if it exists. <del> if (controller) { <del> keywords.controller = controller; <del> } <add> var context = get(this, '_templateContext'); <add> var keywords = this.cloneKeywords(); <ide> <ide> var data = { <ide> view: this, <ide> Ember.View = Ember.Object.extend(Ember.Evented, <ide> @test in createChildViews <ide> */ <ide> createChildView: function(view, attrs) { <del> var coreAttrs; <add> var coreAttrs, templateData; <ide> <ide> if (Ember.View.detect(view)) { <del> coreAttrs = { _parentView: this }; <add> coreAttrs = { _parentView: this, templateData: get(this, 'templateData') }; <add> <ide> if (attrs) { <ide> view = view.create(coreAttrs, attrs); <ide> } else { <ide> Ember.View = Ember.Object.extend(Ember.Evented, <ide> // consumers of the view API <ide> if (viewName) { set(get(this, 'concreteView'), viewName, view); } <ide> } else { <add> if (attrs) { throw "EWOT"; } <add> <ide> Ember.assert('must pass instance of View', view instanceof Ember.View); <add> <add> if (!get(view, 'templateData')) { <add> set(view, 'templateData', get(this, 'templateData')); <add> } <add> <ide> set(view, '_parentView', this); <ide> } <ide>
7
Text
Text
replace wrong u+00a0 by common spaces
11a1bc11364ea88091b73cec5d5f69bdccb03ac1
<ide><path>doc/api/dgram.md <ide> If `msg` is a `String`, then it is automatically converted to a `Buffer` <ide> with `'utf8'` encoding. With messages that <ide> contain multi-byte characters, `offset` and `length` will be calculated with <ide> respect to [byte length][] and not the character position. <del>If `msg` is an array, `offset` and `length` must not be specified. <add>If `msg` is an array, `offset` and `length` must not be specified. <ide> <ide> The `address` argument is a string. If the value of `address` is a host name, <ide> DNS will be used to resolve the address of the host. If `address` is not <ide><path>doc/api/http2.md <ide> the status message for HTTP codes is ignored. <ide> ### ALPN negotiation <ide> <ide> ALPN negotiation allows to support both [HTTPS][] and HTTP/2 over <del>the same socket. The `req` and `res` objects can be either HTTP/1 or <add>the same socket. The `req` and `res` objects can be either HTTP/1 or <ide> HTTP/2, and an application **must** restrict itself to the public API of <ide> [HTTP/1][], and detect if it is possible to use the more advanced <ide> features of HTTP/2. <ide><path>doc/api/tls.md <ide> changes: <ide> * `servername`: {string} Server name for the SNI (Server Name Indication) TLS <ide> extension. <ide> * `checkServerIdentity(servername, cert)` {Function} A callback function <del>    to be used (instead of the builtin `tls.checkServerIdentity()` function) <add> to be used (instead of the builtin `tls.checkServerIdentity()` function) <ide> when checking the server's hostname (or the provided `servername` when <ide> explicitly set) against the certificate. This should return an {Error} if <ide> verification fails. The method should return `undefined` if the `servername`
3
Text
Text
use bash highlighting instead of bat
c91ddbefd04ef19701884a7cf0b76000f2e2a7b2
<ide><path>docs/build-instructions/windows.md <ide> <ide> ## Instructions <ide> <del> ```bat <del> # Use the `Git Shell` app which was installed by GitHub for Windows. Also Make <del> # sure you have logged into the GitHub for Windows GUI App. <del> cd C:\ <del> git clone https://github.com/atom/atom/ <del> cd atom <del> script/build # Creates application in the `Program Files` directory <del> ``` <add>```bash <add># Use the `Git Shell` program which was installed by GitHub for Windows. <add># Also make sure that you are logged into GitHub for Windows. <add>cd C:\ <add>git clone https://github.com/atom/atom/ <add>cd atom <add>script/build # Creates application in the `Program Files` directory <add>``` <ide> <ide> ## Why do I have to use GitHub for Windows? <ide>
1
Javascript
Javascript
fix typo in example
0921bd0816f1a146703ba3573e0c1ed2d76823e3
<ide><path>src/ngMock/angular-mocks.js <ide> angular.module('ngMockE2E', ['ng']).config(function($provide) { <ide> * <ide> * // adds a new phone to the phones array <ide> * $httpBackend.whenPOST('/phones').respond(function(method, url, data) { <del> * phones.push(angular.fromJSON(data)); <add> * phones.push(angular.fromJson(data)); <ide> * }); <ide> * $httpBackend.whenGET(/^\/templates\//).passThrough(); <ide> * //...
1
Ruby
Ruby
add block form for temporary change
f5d6d80d5bac2c83a89021481812b461c54cfba3
<ide><path>Library/Homebrew/extend/ENV/std.rb <ide> def determine_pkg_config_libdir <ide> paths.select { |d| File.directory? d }.join(File::PATH_SEPARATOR) <ide> end <ide> <add> # Removes the MAKEFLAGS environment variable, causing make to use a single job. <add> # This is useful for makefiles with race conditions. <add> # When passed a block, MAKEFLAGS is removed only for the duration of the block and is restored after its completion. <add> # Returns the value of MAKEFLAGS. <ide> def deparallelize <add> old = self['MAKEFLAGS'] <ide> remove 'MAKEFLAGS', /-j\d+/ <add> if block_given? <add> begin <add> yield <add> ensure <add> self['MAKEFLAGS'] = old <add> end <add> end <add> <add> old <ide> end <ide> alias_method :j1, :deparallelize <ide> <ide><path>Library/Homebrew/extend/ENV/super.rb <ide> def determine_cccfg <ide> <ide> public <ide> <add> # Removes the MAKEFLAGS environment variable, causing make to use a single job. <add> # This is useful for makefiles with race conditions. <add> # When passed a block, MAKEFLAGS is removed only for the duration of the block and is restored after its completion. <add> # Returns the value of MAKEFLAGS. <ide> def deparallelize <del> delete('MAKEFLAGS') <add> old = delete('MAKEFLAGS') <add> if block_given? <add> begin <add> yield <add> ensure <add> self['MAKEFLAGS'] = old <add> end <add> end <add> <add> old <ide> end <ide> alias_method :j1, :deparallelize <ide> <ide><path>Library/Homebrew/test/test_ENV.rb <ide> def test_switching_compilers_updates_compiler <ide> assert_equal compiler, @env.compiler <ide> end <ide> end <add> <add> def test_deparallelize_block_form_restores_makeflags <add> @env['MAKEFLAGS'] = '-j4' <add> @env.deparallelize do <add> assert_nil @env['MAKEFLAGS'] <add> end <add> assert_equal '-j4', @env['MAKEFLAGS'] <add> end <ide> end <ide> <ide> class StdenvTests < Homebrew::TestCase
3
Ruby
Ruby
remove samesite=none restrictions for rack 2.1.0
28f81c05589e4be98b6500b2b915842c68846c41
<ide><path>actionpack/lib/action_dispatch/middleware/cookies.rb <ide> def handle_options(options) <ide> <ide> options[:path] ||= "/" <ide> options[:same_site] ||= request.cookies_same_site_protection <del> options[:same_site] = false if options[:same_site] == :none # TODO: Remove when rack 2.1.0 is out. <ide> <ide> if options[:domain] == :all || options[:domain] == "all" <ide> # If there is a provided tld length then we use it otherwise default domain regexp. <ide><path>actionpack/test/dispatch/cookies_test.rb <ide> def test_setting_cookie_with_no_protection <ide> @request.env["action_dispatch.cookies_same_site_protection"] = :none <ide> <ide> get :authenticate <del> assert_cookie_header "user_name=david; path=/" # TODO: append "; SameSite=None" when rack 2.1.0 is out and bump rack dependency version. <add> assert_cookie_header "user_name=david; path=/; SameSite=None" <ide> assert_equal({ "user_name" => "david" }, @response.cookies) <ide> end <ide>
2
Python
Python
bakcbone config update
842cdd4d60599ea21c4169bed7f6ef5334d32bb3
<ide><path>official/vision/beta/projects/yolo/configs/backbones.py <ide> # See the License for the specific language governing permissions and <ide> # limitations under the License. <ide> <del># Lint as: python3 <del> <ide> """Backbones configurations.""" <del> <ide> import dataclasses <del> <ide> from official.modeling import hyperparams <del> <ide> from official.vision.beta.configs import backbones <ide> <ide> <ide> @dataclasses.dataclass <ide> class Darknet(hyperparams.Config): <del> """Darknet config.""" <del> model_id: str = 'darknet53' <del> width_scale: float = 1.0 <del> depth_scale: float = 1.0 <add> """DarkNet config.""" <add> model_id: str = 'cspdarknet53' <add> width_scale: int = 1.0 <add> depth_scale: int = 1.0 <ide> dilate: bool = False <ide> min_level: int = 3 <ide> max_level: int = 5 <add> use_separable_conv: bool = False <add> use_reorg_input: bool = False <ide> <ide> <ide> @dataclasses.dataclass <ide><path>official/vision/beta/projects/yolo/ops/anchor.py <del>import numpy as np <add># Copyright 2021 The TensorFlow Authors. All Rights Reserved. <add># <add># Licensed under the Apache License, Version 2.0 (the "License"); <add># you may not use this file except in compliance with the License. <add># You may obtain a copy of the License at <add># <add># http://www.apache.org/licenses/LICENSE-2.0 <add># <add># Unless required by applicable law or agreed to in writing, software <add># distributed under the License is distributed on an "AS IS" BASIS, <add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add># See the License for the specific language governing permissions and <add># limitations under the License. <add> <add>"""Yolo Anchor labler.""" <ide> import tensorflow as tf <ide> from tensorflow.python.ops.gen_math_ops import maximum, minimum <ide> from official.vision.beta.projects.yolo.ops import box_ops <ide><path>official/vision/beta/projects/yolo/ops/mosaic.py <add># Copyright 2021 The TensorFlow Authors. All Rights Reserved. <add># <add># Licensed under the Apache License, Version 2.0 (the "License"); <add># you may not use this file except in compliance with the License. <add># You may obtain a copy of the License at <add># <add># http://www.apache.org/licenses/LICENSE-2.0 <add># <add># Unless required by applicable law or agreed to in writing, software <add># distributed under the License is distributed on an "AS IS" BASIS, <add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add># See the License for the specific language governing permissions and <add># limitations under the License. <add> <add>"""Mosaic op.""" <ide> import random <ide> import tensorflow as tf <ide> import tensorflow_addons as tfa
3
Python
Python
move scores per type handling into util function
327f83573ac2ba8dc8e4d594c4f66019089610ea
<ide><path>spacy/cli/evaluate.py <del>from typing import Optional, List, Dict <add>from typing import Optional, List, Dict, Any, Union <ide> from wasabi import Printer <ide> from pathlib import Path <ide> import re <ide> def evaluate( <ide> displacy_path: Optional[Path] = None, <ide> displacy_limit: int = 25, <ide> silent: bool = True, <del> spans_key="sc", <del>) -> Scorer: <add> spans_key: str = "sc", <add>) -> Dict[str, Any]: <ide> msg = Printer(no_print=silent, pretty=not silent) <ide> fix_random_seed() <ide> setup_gpu(use_gpu) <ide> def evaluate( <ide> data[re.sub(r"[\s/]", "_", key.lower())] = scores[key] <ide> <ide> msg.table(results, title="Results") <add> data = handle_scores_per_type(scores, data, spans_key=spans_key, silent=silent) <ide> <add> if displacy_path: <add> factory_names = [nlp.get_pipe_meta(pipe).factory for pipe in nlp.pipe_names] <add> docs = list(nlp.pipe(ex.reference.text for ex in dev_dataset[:displacy_limit])) <add> render_deps = "parser" in factory_names <add> render_ents = "ner" in factory_names <add> render_parses( <add> docs, <add> displacy_path, <add> model_name=model, <add> limit=displacy_limit, <add> deps=render_deps, <add> ents=render_ents, <add> ) <add> msg.good(f"Generated {displacy_limit} parses as HTML", displacy_path) <add> <add> if output_path is not None: <add> srsly.write_json(output_path, data) <add> msg.good(f"Saved results to {output_path}") <add> return data <add> <add> <add>def handle_scores_per_type( <add> scores: Union[Scorer, Dict[str, Any]], <add> data: Dict[str, Any] = {}, <add> *, <add> spans_key: str = "sc", <add> silent: bool = False, <add>) -> Dict[str, Any]: <add> msg = Printer(no_print=silent, pretty=not silent) <ide> if "morph_per_feat" in scores: <ide> if scores["morph_per_feat"]: <ide> print_prf_per_type(msg, scores["morph_per_feat"], "MORPH", "feat") <ide> def evaluate( <ide> if scores["cats_auc_per_type"]: <ide> print_textcats_auc_per_cat(msg, scores["cats_auc_per_type"]) <ide> data["cats_auc_per_type"] = scores["cats_auc_per_type"] <del> <del> if displacy_path: <del> factory_names = [nlp.get_pipe_meta(pipe).factory for pipe in nlp.pipe_names] <del> docs = list(nlp.pipe(ex.reference.text for ex in dev_dataset[:displacy_limit])) <del> render_deps = "parser" in factory_names <del> render_ents = "ner" in factory_names <del> render_parses( <del> docs, <del> displacy_path, <del> model_name=model, <del> limit=displacy_limit, <del> deps=render_deps, <del> ents=render_ents, <del> ) <del> msg.good(f"Generated {displacy_limit} parses as HTML", displacy_path) <del> <del> if output_path is not None: <del> srsly.write_json(output_path, data) <del> msg.good(f"Saved results to {output_path}") <del> return data <add> return scores <ide> <ide> <ide> def render_parses(
1
Python
Python
add xglm conversion script
7865f4d01f533759647048fb12607da6b33050e6
<ide><path>src/transformers/models/xglm/convert_xglm_original_ckpt_to_trfms.py <add>import argparse <add>from argparse import Namespace <add> <add>import torch <add>from torch import nn <add> <add>from transformers import XGLMConfig, XGLMForCausalLM <add> <add> <add>def remove_ignore_keys_(state_dict): <add> ignore_keys = [ <add> "decoder.version", <add> "decoder.output_projection.weight", <add> "_float_tensor", <add> "decoder.embed_positions._float_tensor", <add> ] <add> for k in ignore_keys: <add> state_dict.pop(k, None) <add> <add> <add>def make_linear_from_emb(emb): <add> vocab_size, emb_size = emb.weight.shape <add> lin_layer = nn.Linear(vocab_size, emb_size, bias=False) <add> lin_layer.weight.data = emb.weight.data <add> return lin_layer <add> <add> <add>def convert_fairseq_xglm_checkpoint_from_disk(checkpoint_path): <add> checkpoint = torch.load(checkpoint_path, map_location="cpu") <add> args = Namespace(**checkpoint["cfg"]["model"]) <add> state_dict = checkpoint["model"] <add> remove_ignore_keys_(state_dict) <add> vocab_size = state_dict["decoder.embed_tokens.weight"].shape[0] <add> <add> state_dict = {key.replace("decoder", "model"): val for key, val in state_dict.items()} <add> <add> config = XGLMConfig( <add> vocab_size=vocab_size, <add> max_position_embeddings=args.max_target_positions, <add> num_layers=args.decoder_layers, <add> attention_heads=args.decoder_attention_heads, <add> ffn_dim=args.decoder_ffn_embed_dim, <add> d_model=args.decoder_embed_dim, <add> layerdrop=args.decoder_layerdrop, <add> dropout=args.dropout, <add> attention_dropout=args.attention_dropout, <add> activation_dropout=args.activation_dropout, <add> activation_function="gelu", <add> scale_embedding=not args.no_scale_embedding, <add> tie_word_embeddings=args.share_decoder_input_output_embed, <add> ) <add> <add> model = XGLMForCausalLM(config) <add> missing = model.load_state_dict(state_dict, strict=False) <add> print(missing) <add> model.lm_head = make_linear_from_emb(model.model.embed_tokens) <add> <add> return model <add> <add> <add>if __name__ == "__main__": <add> parser = argparse.ArgumentParser() <add> # Required parameters <add> parser.add_argument("fairseq_path", type=str, help="path to a model.pt on local filesystem.") <add> parser.add_argument("pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") <add> args = parser.parse_args() <add> model = convert_fairseq_xglm_checkpoint_from_disk(args.fairseq_path) <add> model.save_pretrained(args.pytorch_dump_folder_path)
1
Javascript
Javascript
fix $destroy describe block titles
efaf59f9880de042e81a91149776785e8dd5547e
<ide><path>test/jQueryPatchSpec.js <ide> if (window.jQuery) { <ide> expect(spy2).toHaveBeenCalledTimes(1); <ide> }); <ide> <del> describe('$detach event', function() { <add> describe('$destroy event', function() { <ide> <ide> it('should fire on remove()', function() { <ide> doc.find('span').remove(); <ide> if (window.jQuery) { <ide> expect(spy1).not.toHaveBeenCalled(); <ide> }); <ide> <del> describe('$detach event is not invoked in too many cases', function() { <add> describe('$destroy event is not invoked in too many cases', function() { <ide> <ide> it('should fire only on matched elements on remove(selector)', function() { <ide> doc.find('span').remove('.second');
1
Javascript
Javascript
fix missing stacks in www warnings
3c54df0914f02fed146faa519a5a899d0e3af32e
<ide><path>packages/shared/consoleWithStackDev.js <ide> export function error(format, ...args) { <ide> } <ide> <ide> function printWarning(level, format, args) { <add> // When changing this logic, you might want to also <add> // update consoleWithStackDev.www.js as well. <ide> if (__DEV__) { <ide> const hasExistingStack = <ide> args.length > 0 && <ide><path>packages/shared/forks/consoleWithStackDev.www.js <ide> // This refers to a WWW module. <ide> const warningWWW = require('warning'); <ide> <del>export function warn() { <del> // TODO: use different level for "warn". <del> const args = Array.prototype.slice.call(arguments); <del> args.unshift(false); <del> warningWWW.apply(null, args); <add>export function warn(format, ...args) { <add> if (__DEV__) { <add> printWarning('warn', format, args); <add> } <ide> } <ide> <del>export function error() { <del> const args = Array.prototype.slice.call(arguments); <del> args.unshift(false); <del> warningWWW.apply(null, args); <add>export function error(format, ...args) { <add> if (__DEV__) { <add> printWarning('error', format, args); <add> } <add>} <add> <add>function printWarning(level, format, args) { <add> if (__DEV__) { <add> const hasExistingStack = <add> args.length > 0 && <add> typeof args[args.length - 1] === 'string' && <add> args[args.length - 1].indexOf('\n in') === 0; <add> <add> if (!hasExistingStack) { <add> const React = require('react'); <add> const ReactSharedInternals = <add> React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; <add> // Defensive in case this is fired before React is initialized. <add> if (ReactSharedInternals != null) { <add> const ReactDebugCurrentFrame = <add> ReactSharedInternals.ReactDebugCurrentFrame; <add> const stack = ReactDebugCurrentFrame.getStackAddendum(); <add> if (stack !== '') { <add> format += '%s'; <add> args.push(stack); <add> } <add> } <add> } <add> // TODO: don't ignore level and pass it down somewhere too. <add> args.unshift(format); <add> args.unshift(false); <add> warningWWW.apply(null, args); <add> } <ide> }
2
Javascript
Javascript
improve performance of nexttick
804d57db676d54e237a19d42bf443db2b9796525
<ide><path>lib/internal/process/next_tick.js <ide> function setupNextTick() { <ide> } while (tickInfo[kLength] !== 0); <ide> } <ide> <del> function TickObject(c, args) { <del> this.callback = c; <del> this.domain = process.domain || null; <del> this.args = args; <del> } <del> <ide> function nextTick(callback) { <ide> if (typeof callback !== 'function') <ide> throw new TypeError('callback is not a function'); <ide> function setupNextTick() { <ide> args[i - 1] = arguments[i]; <ide> } <ide> <del> nextTickQueue.push(new TickObject(callback, args)); <add> nextTickQueue.push({ <add> callback, <add> domain: process.domain || null, <add> args <add> }); <ide> tickInfo[kLength]++; <ide> } <ide> }
1
PHP
PHP
remove brittle message check
54f002434adc0f800d500c204aa0f524fc7a96ea
<ide><path>src/Illuminate/Database/Query/Builder.php <ide> public function orHavingRaw($sql, array $bindings = []) <ide> public function orderBy($column, $direction = 'asc') <ide> { <ide> $direction = strtolower($direction); <add> <ide> if (! in_array($direction, ['asc', 'desc'], true)) { <del> throw new InvalidArgumentException('Invalid value of direction.'); <add> throw new InvalidArgumentException('Order direction must be "asc" or "desc".'); <ide> } <ide> <ide> $this->{$this->unions ? 'unionOrders' : 'orders'}[] = [ <ide><path>tests/Database/DatabaseQueryBuilderTest.php <ide> public function testOrderBys() <ide> public function testOrderByInvalidDirectionParam() <ide> { <ide> $this->expectException(InvalidArgumentException::class); <del> $this->expectExceptionMessage('Invalid value of direction.'); <ide> <ide> $builder = $this->getBuilder(); <ide> $builder->select('*')->from('users')->orderBy('age', 'asec');
2
Python
Python
use fixture around f2py shared memory tests
cb7dca7c3c963ff14c4f58507d3672536c441921
<ide><path>numpy/f2py/tests/test_array_from_pyobj.py <ide> from __future__ import division, absolute_import, print_function <ide> <del>import unittest <ide> import os <ide> import sys <ide> import copy <ide> <add>import pytest <add> <ide> from numpy import ( <ide> array, alltrue, ndarray, zeros, dtype, intp, clongdouble <ide> ) <ide> def test_in_out(self): <ide> assert_(not intent.in_.is_intent('c')) <ide> <ide> <del>class _test_shared_memory(object): <add>class TestSharedMemory(object): <ide> num2seq = [1, 2] <ide> num23seq = [[1, 2, 3], [4, 5, 6]] <ide> <add> @pytest.fixture(autouse=True, scope='class', params=_type_names) <add> def setup_type(self, request): <add> request.cls.type = Type(request.param) <add> request.cls.array = lambda self, dims, intent, obj: \ <add> Array(Type(request.param), dims, intent, obj) <add> <ide> def test_in_from_2seq(self): <ide> a = self.array([2], intent.in_, self.num2seq) <ide> assert_(not a.has_shared_memory()) <ide> def test_inplace_from_casttype(self): <ide> assert_(obj.flags['FORTRAN']) # obj attributes changed inplace! <ide> assert_(not obj.flags['CONTIGUOUS']) <ide> assert_(obj.dtype.type is self.type.dtype) # obj changed inplace! <del> <del> <del>for t in _type_names: <del> exec('''\ <del>class TestGen_%s(_test_shared_memory): <del> def setup(self): <del> self.type = Type(%r) <del> array = lambda self,dims,intent,obj: Array(Type(%r),dims,intent,obj) <del>''' % (t, t, t))
1
Javascript
Javascript
add perf markers in xmlhttprequest
71b8ececf9b298fbf99aa27d0e363b533411e93d
<ide><path>Libraries/Network/XMLHttpRequest.js <ide> <ide> const BlobManager = require('../Blob/BlobManager'); <ide> const EventTarget = require('event-target-shim'); <add>const GlobalPerformanceLogger = require('react-native/Libraries/Utilities/GlobalPerformanceLogger'); <ide> const RCTNetworking = require('./RCTNetworking'); <ide> <ide> const base64 = require('base64-js'); <ide> class XMLHttpRequest extends (EventTarget(...XHR_EVENTS): any) { <ide> _headers: Object; <ide> _lowerCaseResponseHeaders: Object; <ide> _method: ?string = null; <add> _perfKey: ?string = null; <ide> _response: string | ?Object; <ide> _responseType: ResponseType; <ide> _response: string = ''; <ide> class XMLHttpRequest extends (EventTarget(...XHR_EVENTS): any) { <ide> responseURL: ?string, <ide> ): void { <ide> if (requestId === this._requestId) { <add> this._perfKey != null && <add> GlobalPerformanceLogger.stopTimespan(this._perfKey); <ide> this.status = status; <ide> this.setResponseHeaders(responseHeaders); <ide> this.setReadyState(this.HEADERS_RECEIVED); <ide> class XMLHttpRequest extends (EventTarget(...XHR_EVENTS): any) { <ide> } <ide> <ide> const doSend = () => { <del> invariant(this._method, 'Request method needs to be defined.'); <del> invariant(this._url, 'Request URL needs to be defined.'); <add> const friendlyName = <add> this._trackingName !== 'unknown' ? this._trackingName : this._url; <add> this._perfKey = 'network_XMLHttpRequest_' + String(friendlyName); <add> GlobalPerformanceLogger.startTimespan(this._perfKey); <add> invariant( <add> this._method, <add> 'XMLHttpRequest method needs to be defined (%s).', <add> friendlyName, <add> ); <add> invariant( <add> this._url, <add> 'XMLHttpRequest URL needs to be defined (%s).', <add> friendlyName, <add> ); <ide> RCTNetworking.sendRequest( <ide> this._method, <ide> this._trackingName,
1
Text
Text
add contributor agreement
b91986b72670ce59ef3a2039b284a578b5e0dba3
<ide><path>.github/contributors/sorenlind.md <add># spaCy contributor agreement <add> <add>This spaCy Contributor Agreement (**"SCA"**) is based on the <add>[Oracle Contributor Agreement](http://www.oracle.com/technetwork/oca-405177.pdf). <add>The SCA applies to any contribution that you make to any product or project <add>managed by us (the **"project"**), and sets out the intellectual property rights <add>you grant to us in the contributed materials. The term **"us"** shall mean <add>[ExplosionAI UG (haftungsbeschränkt)](https://explosion.ai/legal). The term <add>**"you"** shall mean the person or entity identified below. <add> <add>If you agree to be bound by these terms, fill in the information requested <add>below and include the filled-in version with your first pull request, under the <add>folder [`.github/contributors/`](/.github/contributors/). The name of the file <add>should be your GitHub username, with the extension `.md`. For example, the user <add>example_user would create the file `.github/contributors/example_user.md`. <add> <add>Read this agreement carefully before signing. These terms and conditions <add>constitute a binding legal agreement. <add> <add>## Contributor Agreement <add> <add>1. The term "contribution" or "contributed materials" means any source code, <add>object code, patch, tool, sample, graphic, specification, manual, <add>documentation, or any other material posted or submitted by you to the project. <add> <add>2. With respect to any worldwide copyrights, or copyright applications and <add>registrations, in your contribution: <add> <add> * you hereby assign to us joint ownership, and to the extent that such <add> assignment is or becomes invalid, ineffective or unenforceable, you hereby <add> grant to us a perpetual, irrevocable, non-exclusive, worldwide, no-charge, <add> royalty-free, unrestricted license to exercise all rights under those <add> copyrights. This includes, at our option, the right to sublicense these same <add> rights to third parties through multiple levels of sublicensees or other <add> licensing arrangements; <add> <add> * you agree that each of us can do all things in relation to your <add> contribution as if each of us were the sole owners, and if one of us makes <add> a derivative work of your contribution, the one who makes the derivative <add> work (or has it made will be the sole owner of that derivative work; <add> <add> * you agree that you will not assert any moral rights in your contribution <add> against us, our licensees or transferees; <add> <add> * you agree that we may register a copyright in your contribution and <add> exercise all ownership rights associated with it; and <add> <add> * you agree that neither of us has any duty to consult with, obtain the <add> consent of, pay or render an accounting to the other for any use or <add> distribution of your contribution. <add> <add>3. With respect to any patents you own, or that you can license without payment <add>to any third party, you hereby grant to us a perpetual, irrevocable, <add>non-exclusive, worldwide, no-charge, royalty-free license to: <add> <add> * make, have made, use, sell, offer to sell, import, and otherwise transfer <add> your contribution in whole or in part, alone or in combination with or <add> included in any product, work or materials arising out of the project to <add> which your contribution was submitted, and <add> <add> * at our option, to sublicense these same rights to third parties through <add> multiple levels of sublicensees or other licensing arrangements. <add> <add>4. Except as set out above, you keep all right, title, and interest in your <add>contribution. The rights that you grant to us under these terms are effective <add>on the date you first submitted a contribution to us, even if your submission <add>took place before the date you sign these terms. <add> <add>5. You covenant, represent, warrant and agree that: <add> <add> * Each contribution that you submit is and shall be an original work of <add> authorship and you can legally grant the rights set out in this SCA; <add> <add> * to the best of your knowledge, each contribution will not violate any <add> third party's copyrights, trademarks, patents, or other intellectual <add> property rights; and <add> <add> * each contribution shall be in compliance with U.S. export control laws and <add> other applicable export and import laws. You agree to notify us if you <add> become aware of any circumstance which would make any of the foregoing <add> representations inaccurate in any respect. We may publicly disclose your <add> participation in the project, including the fact that you have signed the SCA. <add> <add>6. This SCA is governed by the laws of the State of California and applicable <add>U.S. Federal law. Any choice of law rules will not apply. <add> <add>7. Please place an “x” on one of the applicable statement below. Please do NOT <add>mark both statements: <add> <add> * [x] I am signing on behalf of myself as an individual and no other person <add> or entity, including my employer, has or will have rights with respect to my <add> contributions. <add> <add> * [ ] I am signing on behalf of my employer or a legal entity and I have the <add> actual authority to contractually bind that entity. <add> <add>## Contributor Details <add> <add>| Field | Entry | <add>|------------------------------- | -------------------- | <add>| Name | Søren Lind Kristiansen | <add>| Company name (if applicable) | | <add>| Title or role (if applicable) | | <add>| Date | 24 November 2017 | <add>| GitHub username | sorenlind | <add>| Website (optional) | |
1
PHP
PHP
allow dynamic access of route parameters
f8c1b19cd13f6700e110373a68c8a646776bb1a2
<ide><path>src/Illuminate/Routing/Route.php <ide> public function prepareForSerialization() <ide> unset($this->compiled); <ide> } <ide> <add> /** <add> * Dynamically access route parameters. <add> * <add> * @param string $key <add> * @return mixed <add> */ <add> public function __get($key) <add> { <add> return $this->parameter($key); <add> } <add> <ide> }
1
Javascript
Javascript
remove unnecessary check for color library
13851c0209a1478184743d290b2ec07fc838a866
<ide><path>src/helpers/index.js <ide> import * as options from './helpers.options'; <ide> import * as math from './helpers.math'; <ide> import * as rtl from './helpers.rtl'; <ide> <del>const colorHelper = !color ? <del> function(value) { <del> console.error('Color.js not found!'); <del> return value; <del> } : <add>const colorHelper = <ide> function(value) { <ide> if (value instanceof CanvasGradient || value instanceof CanvasPattern) { <ide> // TODO: figure out what this should be. Previously returned
1
Python
Python
correct pep issue on string
9441ebbf1d6d9af73efb9df7e98dac3a3a13b052
<ide><path>glances/outputs/glances_curses.py <ide> def display(self, stats, cs_status=None): <ide> 'Examples:\n' + <ide> '- python\n' + <ide> '- .*python.*\n' + <del> '- \/usr\/lib.*\n' + <add> '- /usr/lib.*\n' + <ide> '- name:.*nautilus.*\n' + <ide> '- cmdline:.*glances.*\n' + <ide> '- username:nicolargo\n' +
1
Mixed
Go
support src in --secret
f70470b71e519012e91137a2512f40d5bb8d18af
<ide><path>cli/command/service/opts.go <ide> func (o *SecretOpt) Set(value string) error { <ide> <ide> value := parts[1] <ide> switch key { <del> case "source": <add> case "source", "src": <ide> spec.source = value <ide> case "target": <ide> tDir, _ := filepath.Split(value) <ide><path>docs/reference/commandline/service_create.md <ide> Create a service specifying the secret, target, user/group ID and mode: <ide> ```bash <ide> $ docker service create --name redis \ <ide> --secret source=ssh-key,target=ssh \ <del> --secret source=app-key,target=app,uid=1000,gid=1001,mode=0400 \ <add> --secret src=app-key,target=app,uid=1000,gid=1001,mode=0400 \ <ide> redis:3.0.6 <ide> 4cdgfyky7ozwh3htjfw0d12qv <ide> ```
2
PHP
PHP
fix coding standards
7a39b9285deb80308685c08327425100ecd343dd
<ide><path>Cake/Test/TestCase/Utility/FolderTest.php <ide> public function testInCakePath() { <ide> $result = $Folder->inCakePath($path); <ide> $this->assertFalse($result); <ide> <del> $path = DS . 'Cake' . DS . 'Config'; <add> $path = DS . 'Cake' . DS . 'Config'; <ide> $Folder->cd(ROOT . DS . 'Cake' . DS . 'Config'); <ide> $result = $Folder->inCakePath($path); <ide> $this->assertTrue($result);
1
Javascript
Javascript
adjust jumplist projects to match file explorer
66d7503e6965dd8af8686ed1a66a9b798274e1e0
<ide><path>src/reopen-project-menu-manager.js <ide> export default class ReopenProjectMenuManager { <ide> { <ide> type: 'custom', <ide> name: 'Recent Projects', <del> items: this.projects.map(p => ({ <add> items: this.projects.map(project => ({ <ide> type: 'task', <del> title: ReopenProjectMenuManager.createLabel(p), <add> title: project.paths.map(ReopenProjectMenuManager.betterBaseName).join(', '), <add> description: project.paths.map(path => `${ReopenProjectMenuManager.betterBaseName(path)} (${path})`).join(' '), <ide> program: process.execPath, <del> args: p.paths.map(path => `"${path}"`).join(' ') })) <add> args: project.paths.map(path => `"${path}"`).join(' ') })) <ide> }, <ide> { type: 'recent' }, <ide> { items: [
1
Javascript
Javascript
remove forced optimization from crypto
17c85ffd80a00289479a7355802cd264935e72d4
<ide><path>benchmark/crypto/get-ciphers.js <ide> function main(conf) { <ide> const v = conf.v; <ide> const method = require(v).getCiphers; <ide> var i = 0; <del> <del> common.v8ForceOptimization(method); <add> // first call to getChipers will dominate the results <add> if (n > 1) { <add> for (; i < n; i++) <add> method(); <add> } <ide> bench.start(); <ide> for (; i < n; i++) method(); <ide> bench.end(n);
1
Text
Text
add note about animation breaking change
8b7b62c974e8c4264b8858c42b0ca612ec46c761
<ide><path>CHANGELOG.md <ide> _Note: This release also contains all bug fixes available in [1.0.7](#1.0.7)._ <ide> <ide> ## Breaking Changes <ide> <del>- **$animator/ngAnimate:** <add>- **$animator/ngAnimate:** due to [11f712bc](https://github.com/angular/angular.js/commit/11f712bc3e310302eb2e8691cf6d110bdcde1810), <add> css transition classes changed from `foo-setup`/`foo-start` to `foo`/`foo-active` <ide> <add> The CSS transition classes have changed suffixes. To migrate rename <add> <add> .foo-setup {...} to .foo {...} <add> .foo-start {...} to .foo-active {...} <add> <add> or for type: enter, leave, move, show, hide <add> <add> .foo-type-setup {...} to .foo-type {...} <add> .foo-type-start {...} to .foo-type-active {...} <ide> <ide> - **$resource:** due to [53061363](https://github.com/angular/angular.js/commit/53061363c7aa1ab9085273d269c6f04ac2162336), <del> A `/` followed by a `.`, in the last segment of the URL template is now collapsed into a single `.` delimiter. <add> a `/` followed by a `.`, in the last segment of the URL template is now collapsed into a single `.` delimiter. <ide> <ide> For example: `users/.json` will become `users.json`. If your server relied upon this sequence then it will no longer <ide> work. In this case you can now escape the `/.` sequence with `/\.`
1
Javascript
Javascript
support callbacks in newresource
141d339fe35053b9bd971f8a6f25da934547bbac
<ide><path>lib/NormalModuleReplacementPlugin.js <ide> NormalModuleReplacementPlugin.prototype.apply = function(compiler) { <ide> nmf.plugin("before-resolve", function(result, callback) { <ide> if(!result) return callback(); <ide> if(resourceRegExp.test(result.request)) { <del> result.request = newResource; <add> if (typeof newResource === 'function') { <add> newResource(result); <add> } else { <add> result.request = newResource; <add> } <ide> } <ide> return callback(null, result); <ide> }); <ide> nmf.plugin("after-resolve", function(result, callback) { <ide> if(!result) return callback(); <ide> if(resourceRegExp.test(result.resource)) { <del> result.resource = path.resolve(path.dirname(result.resource), newResource); <add> if (typeof newResource === 'function') { <add> newResource(result); <add> } else { <add> result.resource = path.resolve(path.dirname(result.resource), newResource); <add> } <ide> } <ide> return callback(null, result); <ide> });
1
Ruby
Ruby
remove unused assignments
d56f5c8db7e937cabd07ff192c386f2aefed33a4
<ide><path>actionpack/lib/action_dispatch/middleware/cookies.rb <ide> def initialize(app) <ide> end <ide> <ide> def call(env) <del> cookie_jar = nil <ide> status, headers, body = @app.call(env) <ide> <ide> if cookie_jar = env['action_dispatch.cookies'] <ide><path>activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb <ide> def reap <ide> private <ide> <ide> def release(conn) <del> thread_id = nil <del> <del> if @reserved_connections[current_connection_id] == conn <del> thread_id = current_connection_id <add> thread_id = if @reserved_connections[current_connection_id] == conn <add> current_connection_id <ide> else <del> thread_id = @reserved_connections.keys.find { |k| <add> @reserved_connections.keys.find { |k| <ide> @reserved_connections[k] == conn <ide> } <ide> end <ide><path>activesupport/lib/active_support/testing/performance/jruby.rb <ide> def record <ide> klasses.each do |klass| <ide> fname = output_filename(klass) <ide> FileUtils.mkdir_p(File.dirname(fname)) <del> file = File.open(fname, 'wb') do |file| <add> File.open(fname, 'wb') do |file| <ide> klass.new(@data).printProfile(file) <ide> end <ide> end <ide><path>railties/lib/rails/commands/runner.rb <ide> end <ide> <ide> ARGV.clone.options do |opts| <del> script_name = File.basename($0) <ide> opts.banner = "Usage: runner [options] ('Some.ruby(code)' or a filename)" <ide> <ide> opts.separator ""
4
Ruby
Ruby
remove ocaml support
aa1461b7d67e5c0f0f37420c8168b38f9784e28f
<ide><path>Library/Homebrew/dependency_collector.rb <ide> class DependencyCollector <ide> # Define the languages that we can handle as external dependencies. <ide> LANGUAGE_MODULES = Set[ <del> :jruby, :lua, :ocaml, :perl, :python, :python3, :ruby <add> :jruby, :lua, :perl, :python, :python3, :ruby <ide> ].freeze <ide> <ide> CACHE = {}
1
Ruby
Ruby
simplify code branch, remove #tap
dccdee7e2d021e700c51fc4612ff617e645ccb51
<ide><path>actionpack/lib/action_controller/metal/url_for.rb <ide> def url_options <ide> (script_name = env["ROUTES_#{_routes.object_id}_SCRIPT_NAME"]) || <ide> (original_script_name = env['ORIGINAL_SCRIPT_NAME'.freeze]) <ide> <del> @_url_options.dup.tap do |options| <del> if original_script_name <del> options[:original_script_name] = original_script_name <del> else <del> options[:script_name] = same_origin ? request.script_name.dup : script_name <del> end <del> options.freeze <add> options = @_url_options.dup <add> if original_script_name <add> options[:original_script_name] = original_script_name <add> else <add> options[:script_name] = same_origin ? request.script_name.dup : script_name <ide> end <add> options.freeze <ide> else <ide> @_url_options <ide> end
1
Javascript
Javascript
join multicast group *after* binding
aef62a03ee27ffb149950df5caccc2b4965169d8
<ide><path>test/simple/test-dgram-multicast-multi-process.js <ide> if (!cluster.isMaster) { <ide> var receivedMessages = []; <ide> var listenSocket = dgram.createSocket('udp4'); <ide> <del> listenSocket.addMembership(LOCAL_BROADCAST_HOST); <del> <ide> listenSocket.on('message', function(buf, rinfo) { <ide> console.error('%s received %s from %j', process.pid <ide> ,util.inspect(buf.toString()), rinfo); <ide> if (!cluster.isMaster) { <ide> }); <ide> <ide> listenSocket.bind(common.PORT); <add> <add> listenSocket.addMembership(LOCAL_BROADCAST_HOST); <ide> }
1
PHP
PHP
fix failing tests related to year rollover
656c24a5327426b326eb50ee00c51540227dce79
<ide><path>src/View/Widget/DateTimeWidget.php <ide> public function render(array $data, ContextInterface $context) <ide> */ <ide> protected function _deconstructDate($value, $options) <ide> { <del> if (empty($value)) { <add> if ($value === '' || $value === null) { <ide> return [ <ide> 'year' => '', 'month' => '', 'day' => '', <ide> 'hour' => '', 'minute' => '', 'second' => '', <ide> protected function _deconstructDate($value, $options) <ide> try { <ide> if (is_string($value)) { <ide> $date = new \DateTime($value); <del> } elseif (is_bool($value) || $value === null) { <add> } elseif (is_bool($value)) { <ide> $date = new \DateTime(); <ide> } elseif (is_int($value)) { <ide> $date = new \DateTime('@' . $value); <ide><path>tests/TestCase/View/Widget/DateTimeWidgetTest.php <ide> public function setUp() <ide> public static function invalidSelectedValuesProvider() <ide> { <ide> return [ <del> 'null' => null, <del> 'false' => false, <del> 'true' => true, <add> 'false' => [false], <add> 'true' => [true], <ide> 'string' => ['Bag of poop'], <del> 'int' => [-1], <ide> 'array' => [[ <ide> 'derp' => 'hurt' <ide> ]] <ide> public static function invalidSelectedValuesProvider() <ide> /** <ide> * test rendering selected values. <ide> * <del> * @dataProvider selectedValuesProvider <add> * @dataProvider invalidSelectedValuesProvider <ide> * @return void <ide> */ <ide> public function testRenderSelectedInvalid($selected)
2
Python
Python
add targets arg to fill-mask pipeline
bc820476a5c72060f810f825298befd5ec85da4d
<ide><path>src/transformers/pipelines.py <ide> def ensure_exactly_one_mask_token(self, masked_index: np.ndarray): <ide> f"No mask_token ({self.tokenizer.mask_token}) found on the input", <ide> ) <ide> <del> def __call__(self, *args, **kwargs): <add> def __call__(self, *args, targets=None, **kwargs): <ide> """ <ide> Fill the masked token in the text(s) given as inputs. <ide> <ide> Args: <del> args (:obj:`str` or :obj:`List[str]`): One or several texts (or one list of prompts) with masked tokens. <add> args (:obj:`str` or :obj:`List[str]`): <add> One or several texts (or one list of prompts) with masked tokens. <add> targets (:obj:`str` or :obj:`List[str]`, `optional`): <add> When passed, the model will return the scores for the passed token or tokens rather than the top k <add> predictions in the entire vocabulary. If the provided targets are not in the model vocab, they will <add> be tokenized and the first resulting token will be used (with a warning). <ide> <ide> Return: <ide> A list or a list of list of :obj:`dict`: Each result comes as list of dictionaries with the <ide> def __call__(self, *args, **kwargs): <ide> results = [] <ide> batch_size = outputs.shape[0] if self.framework == "tf" else outputs.size(0) <ide> <add> if targets is not None: <add> if len(targets) == 0 or len(targets[0]) == 0: <add> raise ValueError("At least one target must be provided when passed.") <add> if isinstance(targets, str): <add> targets = [targets] <add> <add> targets_proc = [] <add> for target in targets: <add> target_enc = self.tokenizer.tokenize(target) <add> if len(target_enc) > 1 or target_enc[0] == self.tokenizer.unk_token: <add> logger.warning( <add> "The specified target token `{}` does not exist in the model vocabulary. Replacing with `{}`.".format( <add> target, target_enc[0] <add> ) <add> ) <add> targets_proc.append(target_enc[0]) <add> target_inds = np.array(self.tokenizer.convert_tokens_to_ids(targets_proc)) <add> <ide> for i in range(batch_size): <ide> input_ids = inputs["input_ids"][i] <ide> result = [] <ide> def __call__(self, *args, **kwargs): <ide> <ide> logits = outputs[i, masked_index.item(), :] <ide> probs = tf.nn.softmax(logits) <del> topk = tf.math.top_k(probs, k=self.topk) <del> values, predictions = topk.values.numpy(), topk.indices.numpy() <add> if targets is None: <add> topk = tf.math.top_k(probs, k=self.topk) <add> values, predictions = topk.values.numpy(), topk.indices.numpy() <add> else: <add> values = tf.gather_nd(probs, tf.reshape(target_inds, (-1, 1))) <add> sort_inds = tf.reverse(tf.argsort(values), [0]) <add> values = tf.gather_nd(values, tf.reshape(sort_inds, (-1, 1))).numpy() <add> predictions = target_inds[sort_inds.numpy()] <ide> else: <ide> masked_index = (input_ids == self.tokenizer.mask_token_id).nonzero() <ide> <ide> def __call__(self, *args, **kwargs): <ide> <ide> logits = outputs[i, masked_index.item(), :] <ide> probs = logits.softmax(dim=0) <del> values, predictions = probs.topk(self.topk) <add> if targets is None: <add> values, predictions = probs.topk(self.topk) <add> else: <add> values = probs[..., target_inds] <add> sort_inds = list(reversed(values.argsort(dim=-1))) <add> values = values[..., sort_inds] <add> predictions = target_inds[sort_inds] <ide> <ide> for v, p in zip(values.tolist(), predictions.tolist()): <ide> tokens = input_ids.numpy() <ide><path>tests/test_pipelines.py <ide> ], <ide> ] <ide> <add>expected_fill_mask_target_result = [ <add> [ <add> { <add> "sequence": "<s>My name is Patrick</s>", <add> "score": 0.004992353264242411, <add> "token": 3499, <add> "token_str": "ĠPatrick", <add> }, <add> { <add> "sequence": "<s>My name is Clara</s>", <add> "score": 0.00019297805556561798, <add> "token": 13606, <add> "token_str": "ĠClara", <add> }, <add> ] <add>] <add> <ide> SUMMARIZATION_KWARGS = dict(num_beams=2, min_length=2, max_length=5) <ide> <ide> <ide> def _test_mono_column_pipeline( <ide> for key in output_keys: <ide> self.assertIn(key, mono_result[0]) <ide> <del> multi_result = [nlp(input) for input in valid_inputs] <add> multi_result = [nlp(input, **kwargs) for input in valid_inputs] <ide> self.assertIsInstance(multi_result, list) <ide> self.assertIsInstance(multi_result[0], (dict, list)) <ide> <ide> def test_tf_fill_mask(self): <ide> nlp, valid_inputs, mandatory_keys, invalid_inputs, expected_check_keys=["sequence"] <ide> ) <ide> <add> @require_torch <add> def test_torch_fill_mask_with_targets(self): <add> valid_inputs = ["My name is <mask>"] <add> valid_targets = [[" Teven", " Patrick", " Clara"], [" Sam"]] <add> invalid_targets = [[], [""], ""] <add> for model_name in FILL_MASK_FINETUNED_MODELS: <add> nlp = pipeline(task="fill-mask", model=model_name, tokenizer=model_name, framework="pt") <add> for targets in valid_targets: <add> outputs = nlp(valid_inputs, targets=targets) <add> self.assertIsInstance(outputs, list) <add> self.assertEqual(len(outputs), len(targets)) <add> for targets in invalid_targets: <add> self.assertRaises(ValueError, nlp, valid_inputs, targets=targets) <add> <add> @require_tf <add> def test_tf_fill_mask_with_targets(self): <add> valid_inputs = ["My name is <mask>"] <add> valid_targets = [[" Teven", " Patrick", " Clara"], [" Sam"]] <add> invalid_targets = [[], [""], ""] <add> for model_name in FILL_MASK_FINETUNED_MODELS: <add> nlp = pipeline(task="fill-mask", model=model_name, tokenizer=model_name, framework="tf") <add> for targets in valid_targets: <add> outputs = nlp(valid_inputs, targets=targets) <add> self.assertIsInstance(outputs, list) <add> self.assertEqual(len(outputs), len(targets)) <add> for targets in invalid_targets: <add> self.assertRaises(ValueError, nlp, valid_inputs, targets=targets) <add> <ide> @require_torch <ide> @slow <ide> def test_torch_fill_mask_results(self): <ide> def test_torch_fill_mask_results(self): <ide> "My name is <mask>", <ide> "The largest city in France is <mask>", <ide> ] <add> valid_targets = [" Patrick", " Clara"] <ide> for model_name in LARGE_FILL_MASK_FINETUNED_MODELS: <ide> nlp = pipeline(task="fill-mask", model=model_name, tokenizer=model_name, framework="pt", topk=2,) <ide> self._test_mono_column_pipeline( <ide> def test_torch_fill_mask_results(self): <ide> expected_multi_result=expected_fill_mask_result, <ide> expected_check_keys=["sequence"], <ide> ) <add> self._test_mono_column_pipeline( <add> nlp, <add> valid_inputs[:1], <add> mandatory_keys, <add> expected_multi_result=expected_fill_mask_target_result, <add> expected_check_keys=["sequence"], <add> targets=valid_targets, <add> ) <ide> <ide> @require_tf <ide> @slow <ide> def test_tf_fill_mask_results(self): <ide> "My name is <mask>", <ide> "The largest city in France is <mask>", <ide> ] <add> valid_targets = [" Patrick", " Clara"] <ide> for model_name in LARGE_FILL_MASK_FINETUNED_MODELS: <ide> nlp = pipeline(task="fill-mask", model=model_name, tokenizer=model_name, framework="tf", topk=2) <ide> self._test_mono_column_pipeline( <ide> def test_tf_fill_mask_results(self): <ide> expected_multi_result=expected_fill_mask_result, <ide> expected_check_keys=["sequence"], <ide> ) <add> self._test_mono_column_pipeline( <add> nlp, <add> valid_inputs[:1], <add> mandatory_keys, <add> expected_multi_result=expected_fill_mask_target_result, <add> expected_check_keys=["sequence"], <add> targets=valid_targets, <add> ) <ide> <ide> @require_torch <ide> def test_torch_summarization(self):
2
Ruby
Ruby
limit => 1. references
230c5a060ba7fe3ac2f78f5975debd04e85167cb
<ide><path>activerecord/lib/active_record/base.rb <ide> def find_one(id, options) <ide> conditions = " AND (#{sanitize_sql(options[:conditions])})" if options[:conditions] <ide> options.update :conditions => "#{table_name}.#{primary_key} = #{quote(id,columns_hash[primary_key])}#{conditions}" <ide> <del> if result = find_initial(options) <add> # Use find_every(options).first since the primary key condition <add> # already ensures we have a single record. Using find_initial adds <add> # a superfluous :limit => 1. <add> if result = find_every(options).first <ide> result <ide> else <ide> raise RecordNotFound, "Couldn't find #{name} with ID=#{id}#{conditions}"
1
Python
Python
fix python 3 syntax errors (en masse)
c9202db93df8fded77dd098d7eb2e56dca1ccf42
<ide><path>research/neural_gpu/neural_gpu_trainer.py <ide> # ============================================================================== <ide> """Neural GPU.""" <ide> <add>from __future__ import print_function <add> <ide> import math <ide> import os <ide> import random <ide><path>research/neural_programmer/neural_programmer.py <ide> and performs training or evaluation as specified by the flag evaluator_job <ide> Author: aneelakantan (Arvind Neelakantan) <ide> """ <add>from __future__ import print_function <add> <ide> import time <ide> from random import Random <ide> import numpy as np
2
Text
Text
simplify cost function
c900cec85e4110b8610f49f8fd9990bffd51e360
<ide><path>guide/english/machine-learning/logistic-regression/index.md <ide> J(θ)=(1/m)∑Cost(hθ(x(i)),y(i)) , where summation is from i=1 to m. <ide> Where hθ(x) is = hypothetic value calculated in accordance with attributes and weights which are calculated and balanced via algorithm such as gradient descent. <ide> y = is the corresponding value from observation data set <ide> <del>Here cost function is not a proper sigmoid function in use but in place, two log functions which performs with greater efficiency without <del>penalizing the learning algorithms are used. <del>Cost(hθ(x),y)=−log(hθ(x)) if y = 1 <del>Cost(hθ(x),y)=−log(1−hθ(x)) if y = 0 <add>Here cost function is not a proper sigmoid function in use but in place, two log functions which performs with greater efficieny without penalizing the learning algorithms are used. <add>* Cost(hθ(x),y)=−log(hθ(x)) if y = 1 <add>* Cost(hθ(x),y)=−log(1−hθ(x)) if y = 0 <add> <add>Which we can simplify as: <add> <add>Cost(hθ(x),y) = −log(hθ(x)) − log(1 − hθ(x)) <ide> <ide> Refer to this article for clearing your basics https://www.analyticsvidhya.com/blog/2017/06/a-comprehensive-guide-for-linear-ridge-and-lasso-regression/ <ide>
1
Javascript
Javascript
fix a stray variable missed in 3d5587
ca4476adf97e8d869609ded000e660938783040d
<ide><path>packages/ember-states/lib/state_manager.js <ide> Ember.StateManager = Ember.State.extend( <ide> exitStates.shift(); <ide> } <ide> <del> currentState.pathsCache[name] = { <add> currentState.pathsCache[path] = { <ide> exitStates: exitStates, <ide> enterStates: enterStates, <ide> resolveState: resolveState
1
Ruby
Ruby
remove struct#to_h backport
758e223c45fdd41bdb397e3830553d13686c8dc1
<ide><path>actionpack/lib/action_controller/metal/params_wrapper.rb <ide> require 'active_support/core_ext/hash/slice' <ide> require 'active_support/core_ext/hash/except' <ide> require 'active_support/core_ext/module/anonymous' <del>require 'active_support/core_ext/struct' <ide> require 'action_dispatch/http/mime_type' <ide> <ide> module ActionController <ide><path>activesupport/lib/active_support/core_ext.rb <del>Dir["#{File.dirname(__FILE__)}/core_ext/*.rb"].each do |path| <add>DEPRECATED_FILES = ["#{File.dirname(__FILE__)}/core_ext/struct.rb"] <add>(Dir["#{File.dirname(__FILE__)}/core_ext/*.rb"] - DEPRECATED_FILES).each do |path| <ide> require path <ide> end <ide><path>activesupport/lib/active_support/core_ext/struct.rb <del># Backport of Struct#to_h from Ruby 2.0 <del>class Struct # :nodoc: <del> def to_h <del> Hash[members.zip(values)] <del> end <del>end unless Struct.instance_methods.include?(:to_h) <add>require 'active_support/deprecation' <add> <add>ActiveSupport::Deprecation.warn("This file is deprecated and will be removed in Rails 5.1 with no replacement.") <ide><path>activesupport/test/core_ext/struct_test.rb <del>require 'abstract_unit' <del>require 'active_support/core_ext/struct' <del> <del>class StructExt < ActiveSupport::TestCase <del> def test_to_h <del> x = Struct.new(:foo, :bar) <del> z = x.new(1, 2) <del> assert_equal({ foo: 1, bar: 2 }, z.to_h) <del> end <del>end
4
Python
Python
fix qa example for pt
1889e96c8c278a88cb55339e845800e1799f60da
<ide><path>src/transformers/file_utils.py <ide> def _prepare_output_docstrings(output_type, config_class): <ide> >>> tokenizer = {tokenizer_class}.from_pretrained('{checkpoint}') <ide> >>> model = {model_class}.from_pretrained('{checkpoint}', return_dict=True) <ide> <del> >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") <add> >>> question, text = "Who was Jim Henson?", "Jim Henson was a nice puppet" <add> >>> inputs = tokenizer(question, text, return_tensors='pt') <ide> >>> start_positions = torch.tensor([1]) <ide> >>> end_positions = torch.tensor([3]) <ide> <ide> >>> outputs = model(**inputs, start_positions=start_positions, end_positions=end_positions) <ide> >>> loss = outputs.loss <del> >>> start_scores = outputs.start_scores <del> >>> end_scores = outputs.end_scores <add> >>> start_scores = outputs.start_logits <add> >>> end_scores = outputs.end_logits <ide> """ <ide> <ide> PT_SEQUENCE_CLASSIFICATION_SAMPLE = r"""
1
Text
Text
fix typos and broken links in the docs
9a7182ba36d3a9f1e73f2d2cdc0011ae7837d672
<ide><path>docs/SUMMARY.md <ide> * [Usage](getting-started/usage.md) <ide> * [General](general/README.md) <ide> * [Responsive](general/responsive.md) <add> * [Pixel Ratio](general/device-pixel-ratio.md) <ide> * [Interactions](general/interactions/README.md) <ide> * [Events](general/interactions/events.md) <ide> * [Modes](general/interactions/modes.md) <ide><path>docs/axes/cartesian/README.md <ide> var myChart = new Chart(ctx, { <ide> data: { <ide> datasets: [{ <ide> data: [20, 50, 100, 75, 25, 0], <del> label: 'Left dataset' <add> label: 'Left dataset', <ide> <ide> // This binds the dataset to the left y axis <ide> yAxisID: 'left-y-axis' <ide> }, { <del> data: [0.1, 0.5, 1.0, 2.0, 1.5, 0] <del> label: 'Right dataset' <add> data: [0.1, 0.5, 1.0, 2.0, 1.5, 0], <add> label: 'Right dataset', <ide> <ide> // This binds the dataset to the right y axis <ide> yAxisID: 'right-y-axis', <ide><path>docs/axes/cartesian/linear.md <ide> The following options are provided by the linear scale. They are all located in <ide> <ide> Given the number of axis range settings, it is important to understand how they all interact with each other. <ide> <del>The `suggestedMax` and `suggestedMin` settings only change the data values that are used to scale the axis. These are useful for extending the range of the axis while maintaing the auto fit behaviour. <add>The `suggestedMax` and `suggestedMin` settings only change the data values that are used to scale the axis. These are useful for extending the range of the axis while maintaining the auto fit behaviour. <ide> <ide> ```javascript <ide> let minDataValue = Math.min(mostNegativeValue, options.ticks.suggestedMin); <ide> let chart = new Chart(ctx, { <ide> scales: { <ide> yAxes: [{ <ide> ticks: { <del> suggestedMin: 50 <add> suggestedMin: 50, <ide> suggestedMax: 100 <ide> } <ide> }] <ide><path>docs/axes/radial/linear.md <ide> The following options are provided by the linear scale. They are all located in <ide> <ide> Given the number of axis range settings, it is important to understand how they all interact with each other. <ide> <del>The `suggestedMax` and `suggestedMin` settings only change the data values that are used to scale the axis. These are useful for extending the range of the axis while maintaing the auto fit behaviour. <add>The `suggestedMax` and `suggestedMin` settings only change the data values that are used to scale the axis. These are useful for extending the range of the axis while maintaining the auto fit behaviour. <ide> <ide> ```javascript <ide> let minDataValue = Math.min(mostNegativeValue, options.ticks.suggestedMin); <ide> let chart = new Chart(ctx, { <ide> options: { <ide> scale: { <ide> ticks: { <del> suggestedMin: 50 <add> suggestedMin: 50, <ide> suggestedMax: 100 <ide> } <ide> } <ide><path>docs/axes/styling.md <ide> The tick configuration is nested under the scale configuration in the `ticks` ke <ide> | `fontSize` | `Number` | `12` | Font size for the tick labels. <ide> | `fontStyle` | `String` | `'normal'` | Font style for the tick labels, follows CSS font-style options (i.e. normal, italic, oblique, initial, inherit). <ide> | `reverse` | `Boolean` | `false` | Reverses order of tick labels. <del>| `minor` | `object` | `{}` | Minor ticks configuration. Ommited options are inherited from options above. <del>| `major` | `object` | `{}` | Major ticks configuration. Ommited options are inherited from options above. <add>| `minor` | `object` | `{}` | Minor ticks configuration. Omitted options are inherited from options above. <add>| `major` | `object` | `{}` | Major ticks configuration. Omitted options are inherited from options above. <ide> <ide> ## Minor Tick Configuration <ide> The minorTick configuration is nested under the ticks configuration in the `minor` key. It defines options for the minor tick marks that are generated by the axis. Omitted options are inherited from `ticks` configuration. <ide><path>docs/charts/line.md <ide> The `data` property of a dataset for a line chart can be passed in two formats. <ide> data: [20, 10] <ide> ``` <ide> <del>When the `data` array is an array of numbers, the x axis is generally a [category](../axes/cartesian/category.md#Category Axis). The points are placed onto the axis using their position in the array. When a line chart is created with a category axis, the `labels` property of the data object must be specified. <add>When the `data` array is an array of numbers, the x axis is generally a [category](../axes/cartesian/category.md#category-cartesian-axis). The points are placed onto the axis using their position in the array. When a line chart is created with a category axis, the `labels` property of the data object must be specified. <ide> <ide> ### Point[] <ide> <ide><path>docs/configuration/tooltip.md <ide> The tooltip configuration is passed into the `options.tooltips` namespace. The g <ide> | `footerFontSize` | `Number` | `12` | Footer font size <ide> | `footerFontStyle` | `String` | `'bold'` | Footer font style <ide> | `footerFontColor` | `Color` | `'#fff'` | Footer font color <del>| `footerSpacing` | `Number` | `2` | Spacing to add to top and bottom of each fotter line. <add>| `footerSpacing` | `Number` | `2` | Spacing to add to top and bottom of each footer line. <ide> | `footerMarginTop` | `Number` | `6` | Margin to add before drawing the footer. <ide> | `xPadding` | `Number` | `6` | Padding to add on left and right of tooltip. <ide> | `yPadding` | `Number` | `6` | Padding to add on top and bottom of tooltip. <ide><path>docs/developers/axes.md <ide> To work with Chart.js, custom scale types must implement the following interface <ide> <ide> // Get the pixel (x coordinate for horizontal axis, y coordinate for vertical axis) for a given value <ide> // @param index: index into the ticks array <del> // @param includeOffset: if true, get the pixel halway between the given tick and the next <add> // @param includeOffset: if true, get the pixel halfway between the given tick and the next <ide> getPixelForTick: function(index, includeOffset) {}, <ide> <ide> // Get the pixel (x coordinate for horizontal axis, y coordinate for vertical axis) for a given value <ide> // @param value : the value to get the pixel for <ide> // @param index : index into the data array of the value <ide> // @param datasetIndex : index of the dataset the value comes from <del> // @param includeOffset : if true, get the pixel halway between the given tick and the next <add> // @param includeOffset : if true, get the pixel halfway between the given tick and the next <ide> getPixelForValue: function(value, index, datasetIndex, includeOffset) {} <ide> <ide> // Get the value for a given pixel (x coordinate for horizontal axis, y coordinate for vertical axis) <ide><path>docs/getting-started/README.md <ide> var chart = new Chart(ctx, { <ide> <ide> It's that easy to get started using Chart.js! From here you can explore the many options that can help you customise your charts with scales, tooltips, labels, colors, custom actions, and much more. <ide> <del>There are many examples of Chart.js that are available in the `/samples` folder of `Chart.js.zip` that is attatched to every [release](https://github.com/chartjs/Chart.js/releases). <ide>\ No newline at end of file <add>There are many examples of Chart.js that are available in the `/samples` folder of `Chart.js.zip` that is attached to every [release](https://github.com/chartjs/Chart.js/releases). <ide>\ No newline at end of file <ide><path>docs/getting-started/installation.md <ide> https://www.jsdelivr.com/package/npm/chart.js?path=dist <ide> <ide> You can download the latest version of [Chart.js on GitHub](https://github.com/chartjs/Chart.js/releases/latest). <ide> <del>If you download or clone the repository, you must [build](../developers/contributing.md#building-chartjs) Chart.js to generate the dist files. Chart.js no longer comes with prebuilt release versions, so an alternative option to downloading the repo is **strongly** advised. <add>If you download or clone the repository, you must [build](../developers/contributing.md#building-and-testing) Chart.js to generate the dist files. Chart.js no longer comes with prebuilt release versions, so an alternative option to downloading the repo is **strongly** advised. <ide> <ide> # Selecting the Correct Build <ide>
10
Python
Python
fix bug in sparse_top_k_categorical_accuracy
02bc5010a04bb11c8e91835cc9775c8149dec754
<ide><path>keras/metrics.py <ide> def top_k_categorical_accuracy(y_true, y_pred, k=5): <ide> <ide> <ide> def sparse_top_k_categorical_accuracy(y_true, y_pred, k=5): <del> return K.mean(K.in_top_k(y_pred, K.cast(K.max(y_true, axis=-1), 'int32'), k), <add> # If the shape of y_true is (num_samples, 1), flatten to (num_samples,) <add> return K.mean(K.in_top_k(y_pred, K.cast(K.flatten(y_true), 'int32'), k), <ide> axis=-1) <ide> <ide> <ide><path>tests/keras/metrics_test.py <ide> def test_top_k_categorical_accuracy(): <ide> <ide> @pytest.mark.skipif((K.backend() == 'cntk'), <ide> reason='CNTK backend does not support top_k yet') <del>def test_sparse_top_k_categorical_accuracy(): <del> y_pred = K.variable(np.array([[0.3, 0.2, 0.1], [0.1, 0.2, 0.7]])) <del> y_true = K.variable(np.array([[1], [0]])) <add>@pytest.mark.parametrize('y_pred, y_true', [ <add> # Test correctness if the shape of y_true is (num_samples, 1) <add> (np.array([[0.3, 0.2, 0.1], [0.1, 0.2, 0.7]]), np.array([[1], [0]])), <add> # Test correctness if the shape of y_true is (num_samples,) <add> (np.array([[0.3, 0.2, 0.1], [0.1, 0.2, 0.7]]), np.array([1, 0])), <add>]) <add>def test_sparse_top_k_categorical_accuracy(y_pred, y_true): <add> y_pred = K.variable(y_pred) <add> y_true = K.variable(y_true) <ide> success_result = K.eval( <ide> metrics.sparse_top_k_categorical_accuracy(y_true, y_pred, k=3)) <ide>
2
Python
Python
remove unnecessary iterator in language.pipe
993758c58fba9d4611223f5dd6dcdb203cf67bba
<ide><path>spacy/language.py <ide> def pipe( <ide> <ide> DOCS: https://spacy.io/api/language#pipe <ide> """ <del> # raw_texts will be used later to stop iterator. <del> texts, raw_texts = itertools.tee(texts) <ide> if is_python2 and n_process != 1: <ide> user_warning(Warnings.W023) <ide> n_process = 1
1
Python
Python
simplify forking_enable selection
ffdec5efaeaa6ad37d812814a7b4153473da7929
<ide><path>celery/worker/__init__.py <ide> def on_timeout_cancel(R): <ide> def create(self, w, semaphore=None, max_restarts=None): <ide> threaded = not w.use_eventloop <ide> procs = w.min_concurrency <del> forking_enable = w.no_execv or not w.force_execv <add> forking_enable = w.no_execv if w.force_execv else True <ide> if not threaded: <ide> semaphore = w.semaphore = BoundedSemaphore(procs) <ide> w._quick_acquire = w.semaphore.acquire
1
Python
Python
fix python 2.6 in client/server mode
2a2c8938364938cbb0760614389d44b2820dd82a
<ide><path>glances/__init__.py <ide> def main(): <ide> server = GlancesServer(cached_time=core.cached_time, <ide> config=core.get_config(), <ide> args=args) <del> print("{} {}:{}".format(_("Glances server is running on"), args.bind, args.port)) <add> print(_("Glances server is running on {0}:{1}").format(args.bind, args.port)) <ide> <ide> # Set the server login/password (if -P/--password tag) <ide> if (args.password != ""): <ide><path>glances/core/glances_client.py <ide> def __init__(self, <ide> # Try to connect to the URI <ide> try: <ide> self.client = ServerProxy(uri) <del> except Exception as e: <del> print("{} {} ({})".format(_("Error: creating client socket"), uri, e)) <add> except Exception as err: <add> print(_("Error: Couldn't create socket {0}: {1}").format(uri, err)) <ide> sys.exit(2) <ide> <ide> def login(self): <ide> def login(self): <ide> try: <ide> client_version = self.client.init() <ide> except socket.error as err: <del> print("{} ({})".format(_("Error: Connection to server failed"), err)) <add> print(_("Error: Connection to server failed: {0}").format(err)) <ide> sys.exit(2) <ide> except ProtocolError as err: <ide> if (str(err).find(" 401 ") > 0): <del> print("{} ({})".format(_("Error: Connection to server failed"), _("Bad password"))) <add> print(_("Error: Connection to server failed: Bad password")) <ide> else: <del> print("{} ({})".format(_("Error: Connection to server failed"), err)) <add> print(_("Error: Connection to server failed: {0}").format(err)) <ide> sys.exit(2) <ide> <ide> # Test if client and server are "compatible" <ide> def login(self): <ide> self.screen = glancesCurses(args=self.args) <ide> <ide> # Debug <del> # print "Server version: {}\nClient version: {}\n".format(__version__, client_version) <add> # print "Server version: {0}\nClient version: {1}\n".format(__version__, client_version) <ide> return True <ide> else: <ide> return False
2
Text
Text
add xray focus
9d0cebcd9a4808c1da030da21a165429a58f3633
<ide><path>docs/focus/2018-03-12.md <ide> - Tree-sitter <ide> - Implemented some optimizations to make Tree-sitter parsers compile faster and produce smaller binaries (https://github.com/tree-sitter/tree-sitter/pull/137) (https://github.com/tree-sitter/tree-sitter/pull/140). <ide> - Xray <add> - Short week for a variety of reasons, but made progress on selections and decided on a pretty big change to our architecture. See the [Xray weekly update](https://github.com/atom/xray/blob/master/docs/updates/2018_03_12.md) for details. <ide> - Engineering Improvements <ide> - Begin a more robust solution to locating the correct Python binary [atom/atom#16885](https://github.com/atom/atom/pull/16885) [atom/apm#775](https://github.com/atom/apm/pull/775) [atom/dowsing-rod](https://github.com/atom/dowsing-rod) <ide> - Reactor Duty <del> <add> <ide> ## Focus for week ahead <ide> <ide> - Atom IDE <ide> - Tree-sitter <ide> - Work with Xray team to figure out how Tree-sitter will be used from Xray. <ide> - Xray <add> - We plan to translate some of our architectural decisions from last week into actual code. See the [Xray weekly update](https://github.com/atom/xray/blob/master/docs/updates/2018_03_12.md) for details. <ide> - Engineering Improvements <ide> - Reactor Duty
1
Javascript
Javascript
fix failing tests
e707ec0b1ecc61634062e9911eaf974958a449a9
<ide><path>src/core/ReactCompositeComponent.js <ide> var ReactCompositeComponentMixin = { <ide> continue; <ide> } <ide> var method = this.__reactAutoBindMap[autoBindKey]; <del> this[autoBindKey] = ReactErrorUtils.guard( <del> this._bindAutoBindMethod(method), <add> this[autoBindKey] = this._bindAutoBindMethod(ReactErrorUtils.guard( <add> method, <ide> this.constructor.displayName + '.' + autoBindKey <del> ); <add> )); <ide> } <ide> }, <ide> <ide><path>src/core/__tests__/ReactCompositeComponentError-test.js <ide> <ide> var React = require('React'); <ide> var ReactTestUtils = require('ReactTestUtils'); <del>var ReactErrorUtils; <add>var ReactErrorUtils = require('ReactErrorUtils'); <ide> <ide> describe('ReactCompositeComponent-error', function() { <ide> <del> beforeEach(function() { <del> ReactErrorUtils = require('ReactErrorUtils'); <del> }); <del> <ide> it('should be passed the component and method name', function() { <add> spyOn(ReactErrorUtils, 'guard'); <ide> var Component = React.createClass({ <ide> someHandler: function() {}, <ide> render: function() { <ide> return <div />; <ide> } <ide> }); <ide> <del> var instance = <Component />; <del> ReactTestUtils.renderIntoDocument(instance); <del> expect(ReactErrorUtils.guard.mock.calls[0][1]) <del> .toEqual('Component.someHandler'); <add> var instance = <Component />; <add> ReactTestUtils.renderIntoDocument(instance); <add> expect(ReactErrorUtils.guard.mostRecentCall.args[1]) <add> .toEqual('Component.someHandler'); <ide> }); <ide> <ide> });
2
Javascript
Javascript
multiline variable declarations
f9eee1f2939fe07f4fccf13571c64b965bcd5300
<ide><path>packages/ember-metal/lib/utils.js <ide> export function setMeta(obj, property, value) { <ide> */ <ide> export function metaPath(obj, path, writable) { <ide> Ember.deprecate("Ember.metaPath is deprecated and will be removed from future releases."); <del> var _meta = meta(obj, writable), keyName, value; <add> var _meta = meta(obj, writable); <add> var keyName, value; <ide> <ide> for (var i=0, l=path.length; i<l; i++) { <ide> keyName = path[i]; <ide> export function metaPath(obj, path, writable) { <ide> */ <ide> export function wrap(func, superFunc) { <ide> function superWrapper() { <del> var ret, sup = this && this.__nextSuper; <add> var ret; <add> var sup = this && this.__nextSuper; <ide> if(this) { this.__nextSuper = superFunc; } <ide> ret = apply(this, func, arguments); <ide> if(this) { this.__nextSuper = sup; } <ide> export function inspect(obj) { <ide> return obj + ''; <ide> } <ide> <del> var v, ret = []; <add> var v; <add> var ret = []; <ide> for(var key in obj) { <ide> if (obj.hasOwnProperty(key)) { <ide> v = obj[key];
1
Python
Python
add missing loss classes
ba78b1bf436c2e4d57b44fe7ded87ac2fef65c3d
<ide><path>keras/losses.py <ide> def get_config(self): <ide> class MeanSquaredError(LossFunctionWrapper): <ide> """Computes the mean of squares of errors between labels and predictions. <ide> <del> For example, if `y_true` is [0., 0., 1., 1.] and `y_pred` is [1., 1., 1., 0.] <del> then the mean squared error value is 3/4 (0.75). <del> <ide> Standalone usage: <ide> <ide> ```python <ide> def __init__(self, <ide> class MeanAbsoluteError(LossFunctionWrapper): <ide> """Computes the mean of absolute difference between labels and predictions. <ide> <del> For example, if `y_true` is [0., 0., 1., 1.] and `y_pred` is [1., 1., 1., 0.] <del> then the mean absolute error value is 3/4 (0.75). <del> <ide> Standalone usage: <ide> <ide> ```python <ide> def __init__(self, <ide> class MeanAbsolutePercentageError(LossFunctionWrapper): <ide> """Computes the mean absolute percentage error between `y_true` and `y_pred`. <ide> <del> For example, if `y_true` is [0., 0., 1., 1.] and `y_pred` is [1., 1., 1., 0.] <del> then the mean absolute percentage error value is 5e+08. <del> <ide> Standalone usage: <ide> <ide> ```python <ide> def __init__(self, <ide> class MeanSquaredLogarithmicError(LossFunctionWrapper): <ide> """Computes the mean squared logarithmic error between `y_true` and `y_pred`. <ide> <del> For example, if `y_true` is [0., 0., 1., 1.] and `y_pred` is [1., 1., 1., 0.] <del> then the mean squared logarithmic error value is 0.36034. <del> <ide> Standalone usage: <ide> <ide> ```python <ide> def __init__(self, <ide> from_logits=from_logits) <ide> <ide> <add>class Hinge(LossFunctionWrapper): <add> """Computes the hinge loss between `y_true` and `y_pred`. <add> <add> `y_true` values are expected to be -1 or 1. If binary (0 or 1) labels are <add> provided we will convert them to -1 or 1. <add> <add> Usage with the `compile` API: <add> <add> ```python <add> model = keras.Model(inputs, outputs) <add> model.compile('sgd', loss=keras.losses.Hinge()) <add> ``` <add> """ <add> <add> def __init__(self, <add> reduction=losses_utils.Reduction.SUM_OVER_BATCH_SIZE, <add> name='hinge'): <add> super(Hinge, self).__init__(hinge, name=name, reduction=reduction) <add> <add> <add>class SquaredHinge(LossFunctionWrapper): <add> """Computes the squared hinge loss between `y_true` and `y_pred`. <add> <add> `y_true` values are expected to be -1 or 1. If binary (0 or 1) labels are <add> provided we will convert them to -1 or 1. <add> <add> Usage with the `compile` API: <add> <add> ```python <add> model = keras.Model(inputs, outputs) <add> model.compile('sgd', loss=keras.losses.SquaredHinge()) <add> ``` <add> """ <add> <add> def __init__(self, <add> reduction=losses_utils.Reduction.SUM_OVER_BATCH_SIZE, <add> name='squared_hinge'): <add> super(SquaredHinge, self).__init__( <add> squared_hinge, name=name, reduction=reduction) <add> <add> <add>class CategoricalHinge(LossFunctionWrapper): <add> """Computes the categorical hinge loss between `y_true` and `y_pred`. <add> <add> Usage with the `compile` API: <add> <add> ```python <add> model = keras.Model(inputs, outputs) <add> model.compile('sgd', loss=keras.losses.CategoricalHinge()) <add> ``` <add> """ <add> <add> def __init__(self, <add> reduction=losses_utils.Reduction.SUM_OVER_BATCH_SIZE, <add> name='categorical_hinge'): <add> super(CategoricalHinge, self).__init__( <add> categorical_hinge, name=name, reduction=reduction) <add> <add> <add>class Poisson(LossFunctionWrapper): <add> """Computes the Poisson loss between `y_true` and `y_pred`. <add> <add> `loss = y_pred - y_true * log(y_pred)` <add> <add> Usage with the `compile` API: <add> <add> ```python <add> model = keras.Model(inputs, outputs) <add> model.compile('sgd', loss=keras.losses.Poisson()) <add> ``` <add> """ <add> <add> def __init__(self, <add> reduction=losses_utils.Reduction.SUM_OVER_BATCH_SIZE, <add> name='poisson'): <add> super(Poisson, self).__init__(poisson, name=name, reduction=reduction) <add> <add> <add>class LogCosh(LossFunctionWrapper): <add> """Computes the logarithm of the hyperbolic cosine of the prediction error. <add> <add> `logcosh = log((exp(x) + exp(-x))/2)`, <add> where x is the error (y_pred - y_true) <add> <add> Usage with the `compile` API: <add> <add> ```python <add> model = keras.Model(inputs, outputs) <add> model.compile('sgd', loss=keras.losses.LogCosh()) <add> ``` <add> """ <add> <add> def __init__(self, <add> reduction=losses_utils.Reduction.SUM_OVER_BATCH_SIZE, <add> name='logcosh'): <add> super(LogCosh, self).__init__(logcosh, name=name, reduction=reduction) <add> <add> <add>class KLDivergence(LossFunctionWrapper): <add> """Computes Kullback-Leibler divergence loss between `y_true` and `y_pred`. <add> <add> `loss = y_true * log(y_true / y_pred)` <add> <add> See: https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence <add> <add> Usage with the `compile` API: <add> <add> ```python <add> model = keras.Model(inputs, outputs) <add> model.compile('sgd', loss=keras.losses.KLDivergence()) <add> ``` <add> """ <add> <add> def __init__(self, <add> reduction=losses_utils.Reduction.SUM_OVER_BATCH_SIZE, <add> name='kullback_leibler_divergence'): <add> super(KLDivergence, self).__init__( <add> kullback_leibler_divergence, name=name, reduction=reduction) <add> <add> <add>class Huber(LossFunctionWrapper): <add> """Computes the Huber loss between `y_true` and `y_pred`. <add> <add> Given `x = y_true - y_pred`: <add> ``` <add> loss = 0.5 * x^2 if |x| <= d <add> loss = 0.5 * d^2 + d * (|x| - d) if |x| > d <add> ``` <add> where d is `delta`. See: https://en.wikipedia.org/wiki/Huber_loss <add> <add> Usage with the `compile` API: <add> <add> ```python <add> model = keras.Model(inputs, outputs) <add> model.compile('sgd', loss=keras.losses.Huber()) <add> ``` <add> <add> # Arguments <add> delta: A float, the point where the Huber loss function changes from a <add> quadratic to linear. <add> reduction: (Optional) Type of reduction to apply to loss. <add> name: Optional name for the op. <add> """ <add> def __init__(self, <add> delta=1.0, <add> reduction=losses_utils.Reduction.SUM_OVER_BATCH_SIZE, <add> name='huber_loss'): <add> super(Huber, self).__init__( <add> huber_loss, name=name, reduction=reduction, delta=delta) <add> <add> <ide> def mean_squared_error(y_true, y_pred): <ide> if not K.is_tensor(y_pred): <ide> y_pred = K.constant(y_pred) <ide> def _logcosh(x): <ide> return K.mean(_logcosh(y_pred - y_true), axis=-1) <ide> <ide> <add>def huber_loss(y_true, y_pred, delta=1.0): <add> error = y_pred - y_true <add> abs_error = K.abs(error) <add> quadratic = K.minimum(abs_error, delta) <add> linear = abs_error - quadratic <add> return 0.5 * K.square(quadratic) + delta * linear <add> <add> <ide> def categorical_crossentropy(y_true, y_pred, from_logits=False, label_smoothing=0): <ide> y_pred = K.constant(y_pred) if not K.is_tensor(y_pred) else y_pred <ide> y_true = K.cast(y_true, y_pred.dtype) <ide><path>tests/keras/losses_test.py <ide> from keras.utils.generic_utils import custom_object_scope <ide> <ide> <del>allobj = [losses.mean_squared_error, <del> losses.mean_absolute_error, <del> losses.mean_absolute_percentage_error, <del> losses.mean_squared_logarithmic_error, <del> losses.squared_hinge, <del> losses.hinge, <del> losses.categorical_crossentropy, <del> losses.binary_crossentropy, <del> losses.kullback_leibler_divergence, <del> losses.poisson, <del> losses.cosine_proximity, <del> losses.logcosh, <del> losses.categorical_hinge] <del> <del> <del>class MSE_MAE_loss: <add>all_functions = [losses.mean_squared_error, <add> losses.mean_absolute_error, <add> losses.mean_absolute_percentage_error, <add> losses.mean_squared_logarithmic_error, <add> losses.squared_hinge, <add> losses.hinge, <add> losses.categorical_crossentropy, <add> losses.binary_crossentropy, <add> losses.kullback_leibler_divergence, <add> losses.poisson, <add> losses.cosine_proximity, <add> losses.logcosh, <add> losses.categorical_hinge] <add>all_classes = [ <add> losses.Hinge, <add> losses.SquaredHinge, <add> losses.CategoricalHinge, <add> losses.Poisson, <add> losses.LogCosh, <add> losses.KLDivergence, <add> losses.Huber, <add> # losses.SparseCategoricalCrossentropy, <add> losses.BinaryCrossentropy, <add> losses.MeanSquaredLogarithmicError, <add> losses.MeanAbsolutePercentageError, <add> losses.MeanAbsoluteError, <add> losses.MeanSquaredError, <add>] <add> <add> <add>class MSE_MAE_loss(object): <ide> """Loss function with internal state, for testing serialization code.""" <add> <ide> def __init__(self, mse_fraction): <ide> self.mse_fraction = mse_fraction <ide> <ide> def get_config(self): <ide> return {'mse_fraction': self.mse_fraction} <ide> <ide> <del>class TestLossFunctions: <add>class TestLossFunctions(object): <ide> <del> def test_objective_shapes_3d(self): <add> @pytest.mark.parametrize('loss_fn', all_functions) <add> def test_objective_shapes_3d(self, loss_fn): <ide> y_a = K.variable(np.random.random((5, 6, 7))) <ide> y_b = K.variable(np.random.random((5, 6, 7))) <del> for obj in allobj: <del> objective_output = obj(y_a, y_b) <del> assert K.eval(objective_output).shape == (5, 6) <add> objective_output = loss_fn(y_a, y_b) <add> assert K.eval(objective_output).shape == (5, 6) <ide> <del> def test_objective_shapes_2d(self): <add> @pytest.mark.parametrize('loss_fn', all_functions) <add> def test_objective_shapes_2d(self, loss_fn): <ide> y_a = K.variable(np.random.random((6, 7))) <ide> y_b = K.variable(np.random.random((6, 7))) <del> for obj in allobj: <del> objective_output = obj(y_a, y_b) <del> assert K.eval(objective_output).shape == (6,) <add> objective_output = loss_fn(y_a, y_b) <add> assert K.eval(objective_output).shape == (6,) <ide> <ide> def test_cce_one_hot(self): <ide> y_a = K.variable(np.random.randint(0, 7, (5, 6))) <ide> def test_loss_wrapper(self): <ide> np.allclose(K.eval(loss), 16, atol=1e-2) <ide> <ide> <add>class TestLossClasses(object): <add> <add> @pytest.mark.parametrize('cls', all_classes) <add> def test_objective_shapes_3d(self, cls): <add> y_a = K.variable(np.random.random((5, 6, 7))) <add> y_b = K.variable(np.random.random((5, 6, 7))) <add> sw = K.variable(np.random.random((5, 6))) <add> obj_fn = cls(name='test') <add> objective_output = obj_fn(y_a, y_b, sample_weight=sw) <add> assert K.eval(objective_output).shape == () <add> <add> @pytest.mark.parametrize('cls', all_classes) <add> def test_objective_shapes_2d(self, cls): <add> y_a = K.variable(np.random.random((6, 7))) <add> y_b = K.variable(np.random.random((6, 7))) <add> sw = K.variable(np.random.random((6,))) <add> obj_fn = cls(name='test') <add> objective_output = obj_fn(y_a, y_b, sample_weight=sw) <add> assert K.eval(objective_output).shape == () <add> <add> <ide> class TestMeanSquaredError: <ide> <ide> def test_config(self): <ide> def test_sum_reduction(self): <ide> assert np.isclose(K.eval(loss), 227.69998, rtol=1e-3) <ide> <ide> <del>class TestMeanAbsoluteError: <add>class TestMeanAbsoluteError(object): <ide> <ide> def test_config(self): <ide> mae_obj = losses.MeanAbsoluteError( <ide> def test_sum_reduction(self): <ide> assert np.isclose(K.eval(loss), 25.29999, rtol=1e-3) <ide> <ide> <del>class TestMeanAbsolutePercentageError: <add>class TestMeanAbsolutePercentageError(object): <ide> <ide> def test_config(self): <ide> mape_obj = losses.MeanAbsolutePercentageError( <ide> def test_no_reduction(self): <ide> assert np.allclose(K.eval(loss), [621.8518, 352.6666], rtol=1e-3) <ide> <ide> <del>class TestMeanSquaredLogarithmicError: <add>class TestMeanSquaredLogarithmicError(object): <ide> <ide> def test_config(self): <ide> msle_obj = losses.MeanSquaredLogarithmicError( <ide> def test_zero_weighted(self): <ide> assert np.allclose(K.eval(loss), 0.0, rtol=1e-3) <ide> <ide> <del>class TestBinaryCrossentropy: <add>class TestBinaryCrossentropy(object): <ide> <ide> def test_config(self): <ide> bce_obj = losses.BinaryCrossentropy( <ide> def test_label_smoothing(self): <ide> assert np.isclose(K.eval(loss), expected_value, atol=1e-3) <ide> <ide> <del>class TestCategoricalCrossentropy: <add>class TestCategoricalCrossentropy(object): <ide> <ide> def test_config(self): <ide> cce_obj = losses.CategoricalCrossentropy( <ide> def test_label_smoothing(self): <ide> assert np.isclose(K.eval(loss), expected_value, atol=1e-3) <ide> <ide> <del>class TestSparseCategoricalCrossentropy: <add>class TestSparseCategoricalCrossentropy(object): <ide> <ide> def test_config(self): <ide> cce_obj = losses.SparseCategoricalCrossentropy(
2
Javascript
Javascript
check parent of poseobject instead of camera
9ed629301d0200448f335ce38b95a95c6a5f7363
<ide><path>src/renderers/webvr/WebVRManager.js <ide> function WebVRManager( renderer ) { <ide> cameraL.matrixWorldInverse.fromArray( frameData.leftViewMatrix ); <ide> cameraR.matrixWorldInverse.fromArray( frameData.rightViewMatrix ); <ide> <del> var parent = camera.parent; <add> var parent = poseObject.parent; <ide> <ide> if ( parent !== null ) { <ide>
1
Java
Java
expose methods to set position start|end
1227675e0a8000d6f6d5e46a9863e086446435af
<ide><path>ReactAndroid/src/main/java/com/facebook/csslayout/CSSNode.java <ide> import static com.facebook.csslayout.CSSLayout.POSITION_LEFT; <ide> import static com.facebook.csslayout.CSSLayout.POSITION_TOP; <ide> import static com.facebook.csslayout.Spacing.BOTTOM; <add>import static com.facebook.csslayout.Spacing.END; <ide> import static com.facebook.csslayout.Spacing.LEFT; <ide> import static com.facebook.csslayout.Spacing.RIGHT; <add>import static com.facebook.csslayout.Spacing.START; <ide> import static com.facebook.csslayout.Spacing.TOP; <ide> <ide> /** <ide> public void setPositionRight(float positionRight) { <ide> setPositionValue(RIGHT, positionRight); <ide> } <ide> <add> /** <add> * Get this node's position start, as defined by style. <add> */ <add> @Override <add> public float getPositionStart() { <add> return style.position.get(START); <add> } <add> <add> @Override <add> public void setPositionStart(float positionStart) { <add> setPositionValue(START, positionStart); <add> } <add> <add> /** <add> * Get this node's position end, as defined by style. <add> */ <add> @Override <add> public float getPositionEnd() { <add> return style.position.get(END); <add> } <add> <add> @Override <add> public void setPositionEnd(float positionEnd) { <add> setPositionValue(END, positionEnd); <add> } <add> <ide> /** <ide> * Get this node's width, as defined in the style. <ide> */ <ide><path>ReactAndroid/src/main/java/com/facebook/csslayout/CSSNodeAPI.java <ide> void measure( <ide> void setPositionLeft(float positionLeft); <ide> float getPositionRight(); <ide> void setPositionRight(float positionRight); <add> float getPositionStart(); <add> void setPositionStart(float positionStart); <add> float getPositionEnd(); <add> void setPositionEnd(float positionEnd); <ide> float getStyleWidth(); <ide> void setStyleWidth(float width); <ide> float getStyleHeight(); <ide><path>ReactAndroid/src/main/java/com/facebook/csslayout/CSSNodeJNI.java <ide> public void setPositionRight(float positionRight) { <ide> jni_CSSNodeStyleSetPositionRight(mNativePointer, positionRight); <ide> } <ide> <add> private native float jni_CSSNodeStyleGetPositionStart(int nativePointer); <add> @Override <add> public float getPositionStart() { <add> assertNativeInstance(); <add> return jni_CSSNodeStyleGetPositionStart(mNativePointer); <add> } <add> <add> private native void jni_CSSNodeStyleSetPositionStart(int nativePointer, float positionStart); <add> @Override <add> public void setPositionStart(float positionStart) { <add> assertNativeInstance(); <add> jni_CSSNodeStyleSetPositionStart(mNativePointer, positionStart); <add> } <add> <add> private native float jni_CSSNodeStyleGetPositionEnd(int nativePointer); <add> @Override <add> public float getPositionEnd() { <add> assertNativeInstance(); <add> return jni_CSSNodeStyleGetPositionEnd(mNativePointer); <add> } <add> <add> private native void jni_CSSNodeStyleSetPositionEnd(int nativePointer, float positionEnd); <add> @Override <add> public void setPositionEnd(float positionEnd) { <add> assertNativeInstance(); <add> jni_CSSNodeStyleSetPositionEnd(mNativePointer, positionEnd); <add> } <add> <ide> private native float jni_CSSNodeStyleGetWidth(int nativePointer); <ide> @Override <ide> public float getStyleWidth() {
3
Go
Go
return error if basename is expanded to blank
c9542d313e2a52807644742e5fd684bc2de9f507
<ide><path>builder/dockerfile/dispatchers.go <ide> func (d *dispatchRequest) getImageOrStage(name string, platform *specs.Platform) <ide> } <ide> return imageMount.Image(), nil <ide> } <del>func (d *dispatchRequest) getFromImage(shlex *shell.Lex, name string, platform *specs.Platform) (builder.Image, error) { <del> name, err := d.getExpandedString(shlex, name) <add>func (d *dispatchRequest) getFromImage(shlex *shell.Lex, basename string, platform *specs.Platform) (builder.Image, error) { <add> name, err := d.getExpandedString(shlex, basename) <ide> if err != nil { <ide> return nil, err <ide> } <add> // Empty string is interpreted to FROM scratch by images.GetImageAndReleasableLayer, <add> // so validate expanded result is not empty. <add> if name == "" { <add> return nil, errors.Errorf("base name (%s) should not be blank", basename) <add> } <add> <ide> return d.getImageOrStage(name, platform) <ide> } <ide> <ide><path>builder/dockerfile/dispatchers_test.go <ide> func TestFromWithArg(t *testing.T) { <ide> assert.Check(t, is.Len(sb.state.buildArgs.GetAllMeta(), 1)) <ide> } <ide> <add>func TestFromWithArgButBuildArgsNotGiven(t *testing.T) { <add> b := newBuilderWithMockBackend() <add> args := NewBuildArgs(make(map[string]*string)) <add> <add> metaArg := instructions.ArgCommand{} <add> cmd := &instructions.Stage{ <add> BaseName: "${THETAG}", <add> } <add> err := processMetaArg(metaArg, shell.NewLex('\\'), args) <add> <add> sb := newDispatchRequest(b, '\\', nil, args, newStagesBuildResults()) <add> assert.NilError(t, err) <add> err = initializeStage(sb, cmd) <add> assert.Error(t, err, "base name (${THETAG}) should not be blank") <add>} <add> <ide> func TestFromWithUndefinedArg(t *testing.T) { <ide> tag, expected := "sometag", "expectedthisid" <ide>
2
Javascript
Javascript
use strict equality in regression test
8badb6776123a5e56e0dd675e03c97d52746b279
<ide><path>test/sequential/test-regress-GH-877.js <ide> server.listen(common.PORT, '127.0.0.1', function() { <ide> }; <ide> <ide> var req = http.get(options, function(res) { <del> if (++responses == N) { <add> if (++responses === N) { <ide> server.close(); <ide> } <ide> res.resume(); <ide> server.listen(common.PORT, '127.0.0.1', function() { <ide> }); <ide> <ide> process.on('exit', function() { <del> assert.ok(responses == N); <add> assert.strictEqual(responses, N); <ide> assert.ok(maxQueued <= 10); <ide> });
1
Ruby
Ruby
remove default argument from make_relative_symlink
c2228c0d0f266b5984530ffc169ba247c5f18037
<ide><path>Library/Homebrew/keg.rb <ide> def resolve_any_conflicts dst, mode <ide> puts "Won't resolve conflicts for symlink #{dst} as it doesn't resolve into the Cellar" if ARGV.verbose? <ide> end <ide> <del> def make_relative_symlink dst, src, mode=OpenStruct.new <add> def make_relative_symlink dst, src, mode <ide> if dst.symlink? && dst.exist? && dst.resolved_path == src <ide> puts "Skipping; link already exists: #{dst}" if ARGV.verbose? <ide> return
1
Python
Python
pass trino hook params to dbapihook
1884f2227d1e41d7bb37246ece4da5d871036c1f
<ide><path>airflow/providers/trino/hooks/trino.py <ide> # specific language governing permissions and limitations <ide> # under the License. <ide> import os <del>from typing import Any, Iterable, Optional <add>from typing import Any, Callable, Iterable, Optional <ide> <ide> import trino <ide> from trino.exceptions import DatabaseError <ide> def get_isolation_level(self) -> Any: <ide> def _strip_sql(sql: str) -> str: <ide> return sql.strip().rstrip(';') <ide> <del> def get_records(self, hql, parameters: Optional[dict] = None): <add> def get_records(self, hql: str, parameters: Optional[dict] = None): <ide> """Get a set of records from Trino""" <ide> try: <ide> return super().get_records(self._strip_sql(hql), parameters) <ide> def get_first(self, hql: str, parameters: Optional[dict] = None) -> Any: <ide> except DatabaseError as e: <ide> raise TrinoException(e) <ide> <del> def get_pandas_df(self, hql, parameters=None, **kwargs): <add> def get_pandas_df(self, hql: str, parameters: Optional[dict] = None, **kwargs): # type: ignore[override] <ide> """Get a pandas dataframe from a sql query.""" <ide> import pandas <ide> <ide> def get_pandas_df(self, hql, parameters=None, **kwargs): <ide> df = pandas.DataFrame(**kwargs) <ide> return df <ide> <del> def run(self, hql, autocommit: bool = False, parameters: Optional[dict] = None, handler=None) -> None: <add> def run( <add> self, <add> hql: str, <add> autocommit: bool = False, <add> parameters: Optional[dict] = None, <add> handler: Optional[Callable] = None, <add> ) -> None: <ide> """Execute the statement against Trino. Can be used to create views.""" <del> return super().run(sql=self._strip_sql(hql), parameters=parameters) <add> return super().run( <add> sql=self._strip_sql(hql), autocommit=autocommit, parameters=parameters, handler=handler <add> ) <ide> <ide> def insert_rows( <ide> self, <ide> def insert_rows( <ide> ) <ide> commit_every = 0 <ide> <del> super().insert_rows(table, rows, target_fields, commit_every) <add> super().insert_rows(table, rows, target_fields, commit_every, replace) <ide><path>tests/providers/trino/hooks/test_trino.py <ide> def test_insert_rows(self, mock_insert_rows): <ide> rows = [("hello",), ("world",)] <ide> target_fields = None <ide> commit_every = 10 <del> self.db_hook.insert_rows(table, rows, target_fields, commit_every) <del> mock_insert_rows.assert_called_once_with(table, rows, None, 10) <add> replace = True <add> self.db_hook.insert_rows(table, rows, target_fields, commit_every, replace) <add> mock_insert_rows.assert_called_once_with(table, rows, None, 10, True) <ide> <ide> def test_get_first_record(self): <ide> statement = 'SQL' <ide> def test_get_pandas_df(self): <ide> <ide> self.cur.execute.assert_called_once_with(statement, None) <ide> <add> @patch('airflow.hooks.dbapi.DbApiHook.run') <add> def test_run(self, mock_run): <add> hql = "SELECT 1" <add> autocommit = False <add> parameters = {"hello": "world"} <add> handler = str <add> self.db_hook.run(hql, autocommit, parameters, handler) <add> mock_run.assert_called_once_with(sql=hql, autocommit=False, parameters=parameters, handler=str) <add> <ide> <ide> class TestTrinoHookIntegration(unittest.TestCase): <ide> @pytest.mark.integration("trino")
2
Java
Java
change this "try" to a try-with-resources
c0b4b5787fc7a685c82d237f09533c89eb6b1ab1
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java <ide> public int loadBeanDefinitions(EncodedResource encodedResource, @Nullable String <ide> <ide> Properties props = new Properties(); <ide> try { <del> InputStream is = encodedResource.getResource().getInputStream(); <del> try { <add> try (InputStream is = encodedResource.getResource().getInputStream()) { <ide> if (encodedResource.getEncoding() != null) { <ide> getPropertiesPersister().load(props, new InputStreamReader(is, encodedResource.getEncoding())); <ide> } <ide> else { <ide> getPropertiesPersister().load(props, is); <ide> } <ide> } <del> finally { <del> is.close(); <del> } <ide> return registerBeanDefinitions(props, prefix, encodedResource.getResource().getDescription()); <ide> } <ide> catch (IOException ex) { <ide><path>spring-context/src/main/java/org/springframework/context/support/ReloadableResourceBundleMessageSource.java <ide> protected PropertiesHolder refreshProperties(String filename, @Nullable Properti <ide> * @throws IOException if properties loading failed <ide> */ <ide> protected Properties loadProperties(Resource resource, String filename) throws IOException { <del> InputStream is = resource.getInputStream(); <ide> Properties props = newProperties(); <del> try { <add> try (InputStream is = resource.getInputStream()) { <ide> String resourceFilename = resource.getFilename(); <ide> if (resourceFilename != null && resourceFilename.endsWith(XML_SUFFIX)) { <ide> if (logger.isDebugEnabled()) { <ide> protected Properties loadProperties(Resource resource, String filename) throws I <ide> } <ide> return props; <ide> } <del> finally { <del> is.close(); <del> } <ide> } <ide> <ide> /** <ide><path>spring-context/src/main/java/org/springframework/context/support/ResourceBundleMessageSource.java <ide> import java.security.PrivilegedActionException; <ide> import java.security.PrivilegedExceptionAction; <ide> import java.text.MessageFormat; <del>import java.util.HashMap; <ide> import java.util.Locale; <ide> import java.util.Map; <ide> import java.util.MissingResourceException; <ide> public ResourceBundle newBundle(String baseName, Locale locale, String format, C <ide> if (encoding == null) { <ide> encoding = "ISO-8859-1"; <ide> } <del> try { <del> return loadBundle(new InputStreamReader(stream, encoding)); <del> } <del> finally { <del> stream.close(); <add> try (InputStreamReader bundleReader = new InputStreamReader(stream, encoding)) { <add> return loadBundle(bundleReader); <ide> } <ide> } <ide> else { <ide><path>spring-web/src/main/java/org/springframework/http/MediaTypeFactory.java <ide> public class MediaTypeFactory { <ide> * @return a multi-value map, mapping media types to file extensions. <ide> */ <ide> private static MultiValueMap<String, MediaType> parseMimeTypes() { <del> InputStream is = null; <del> try { <del> is = MediaTypeFactory.class.getResourceAsStream(MIME_TYPES_FILE_NAME); <add> try (InputStream is = MediaTypeFactory.class.getResourceAsStream(MIME_TYPES_FILE_NAME)) { <ide> BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.US_ASCII)); <ide> MultiValueMap<String, MediaType> result = new LinkedMultiValueMap<>(); <ide> String line; <ide> private static MultiValueMap<String, MediaType> parseMimeTypes() { <ide> catch (IOException ex) { <ide> throw new IllegalStateException("Could not load '" + MIME_TYPES_FILE_NAME + "'", ex); <ide> } <del> finally { <del> if (is != null) { <del> try { <del> is.close(); <del> } <del> catch (IOException ignore) { <del> } <del> } <del> } <ide> } <ide> <ide> /** <ide><path>spring-web/src/main/java/org/springframework/remoting/caucho/HessianExporter.java <ide> protected void doInvoke(HessianSkeleton skeleton, InputStream inputStream, Outpu <ide> OutputStream osToUse = outputStream; <ide> <ide> if (this.debugLogger != null && this.debugLogger.isDebugEnabled()) { <del> PrintWriter debugWriter = new PrintWriter(new CommonsLogWriter(this.debugLogger)); <del> @SuppressWarnings("resource") <del> HessianDebugInputStream dis = new HessianDebugInputStream(inputStream, debugWriter); <del> @SuppressWarnings("resource") <del> HessianDebugOutputStream dos = new HessianDebugOutputStream(outputStream, debugWriter); <del> dis.startTop2(); <del> dos.startTop2(); <del> isToUse = dis; <del> osToUse = dos; <add> try (PrintWriter debugWriter = new PrintWriter(new CommonsLogWriter(this.debugLogger))){ <add> @SuppressWarnings("resource") <add> HessianDebugInputStream dis = new HessianDebugInputStream(inputStream, debugWriter); <add> @SuppressWarnings("resource") <add> HessianDebugOutputStream dos = new HessianDebugOutputStream(outputStream, debugWriter); <add> dis.startTop2(); <add> dos.startTop2(); <add> isToUse = dis; <add> osToUse = dos; <add> } <ide> } <ide> <ide> if (!isToUse.markSupported()) {
5
Python
Python
remove useless code
4bb90a5bfd762269adeee772e233a733a6d318a9
<ide><path>keras/models.py <ide> def evaluate(self, X, y, batch_size=128, show_accuracy=False, verbose=1): <ide> else: <ide> return tot_score/len(batches) <ide> <del> def save(self, fpath): <del> import cPickle <del> import types <del> <del> weights = [] <del> for l in self.layers: <del> weights.append(l.get_weights()) <del> <del> attributes = [] <del> for a in dir(l): <del> if a[:2] != '__' and a not in ['params', 'previous_layer', 'input']: <del> if type(getattr(l, a)) != types.MethodType: <del> attributes.append((a, getattr(l, a))) <del> <del> print('Pickle model...') <del> cPickle.dump(self, open(fpath + '.pkl', 'w')) <del> print('Pickle weights...') <del> cPickle.dump(weights, open(fpath + '.h5', 'w')) <del> <del> #save_weights_to_hdf5(fpath + '.h5', weights) <del> <ide> <ide> <ide>
1
Ruby
Ruby
add opt shortcuts to formula
452d671008db6d61b78e18f25db0c7308b8a24a2
<ide><path>Library/Homebrew/formula.rb <ide> def opt_prefix <ide> Pathname.new("#{HOMEBREW_PREFIX}/opt/#{name}") <ide> end <ide> <add> def opt_bin; opt_prefix+'bin' end <add> def opt_include; opt_prefix+'include' end <add> def opt_lib; opt_prefix+'lib' end <add> def opt_libexec; opt_prefix+'libexec' end <add> def opt_sbin; opt_prefix+'sbin' end <add> def opt_share; opt_prefix+'share' end <add> <ide> # Can be overridden to selectively disable bottles from formulae. <ide> # Defaults to true so overridden version does not have to check if bottles <ide> # are supported.
1
Ruby
Ruby
remove outdated comment
3b1a1962f7cd4bd44a5e4de0098129ee1dce6dc6
<ide><path>Library/Homebrew/formula.rb <ide> def brew <ide> stage do <ide> begin <ide> patch <del> # we allow formulae to do anything they want to the Ruby process <del> # so load any deps before this point! And exit asap afterwards <ide> yield self <ide> ensure <ide> cp Dir["config.log", "CMakeCache.txt"], HOMEBREW_LOGS+name
1
Python
Python
remove todos that will never fulfill
3b56ba8d1134724c87a670e9d95a34d320c223d8
<ide><path>official/modeling/tf_utils.py <ide> def is_special_none_tensor(tensor): <ide> return tensor.shape.ndims == 0 and tensor.dtype == tf.int32 <ide> <ide> <del># TODO(hongkuny): consider moving custom string-map lookup to keras api. <ide> def get_activation(identifier): <ide> """Maps a identifier to a Python function, e.g., "relu" => `tf.nn.relu`. <ide> <ide><path>official/nlp/bert/model_training_utils.py <ide> def _run_evaluation(current_training_step, test_iterator): <ide> for metric in model.metrics: <ide> training_summary[metric.name] = _float_metric_value(metric) <ide> if eval_metrics: <del> # TODO(hongkuny): Cleans up summary reporting in text. <ide> training_summary['last_train_metrics'] = _float_metric_value( <ide> train_metrics[0]) <ide> training_summary['eval_metrics'] = _float_metric_value(eval_metrics[0]) <ide><path>official/nlp/transformer/transformer.py <ide> def create_model(params, is_train): <ide> logits = tf.keras.layers.Lambda(lambda x: x, name="logits", <ide> dtype=tf.float32)(logits) <ide> model = tf.keras.Model([inputs, targets], logits) <del> # TODO(reedwm): Can we do this loss in float16 instead of float32? <ide> loss = metrics.transformer_loss( <ide> logits, targets, label_smoothing, vocab_size) <ide> model.add_loss(loss) <ide> def _get_symbols_to_logits_fn(self, max_decode_length, training): <ide> decoder_self_attention_bias = model_utils.get_decoder_self_attention_bias( <ide> max_decode_length, dtype=self.params["dtype"]) <ide> <del> # TODO(b/139770046): Refactor code with better naming of i. <ide> def symbols_to_logits_fn(ids, i, cache): <ide> """Generate logits for next potential IDs. <ide> <ide><path>official/nlp/transformer/transformer_main.py <ide> def train(self): <ide> callbacks = [cb for cb in callbacks <ide> if isinstance(cb, keras_utils.TimeHistory)] <ide> <del> # TODO(b/139418525): Refactor the custom training loop logic. <ide> @tf.function <ide> def train_steps(iterator, steps): <ide> """Training steps function for TPU runs. <ide> def _load_weights_if_possible(self, model, init_weight_path=None): <ide> """Loads model weights when it is provided.""" <ide> if init_weight_path: <ide> logging.info("Load weights: {}".format(init_weight_path)) <del> # TODO(b/139414977): Having the same variable restoring method for both <del> # TPU and GPU. <ide> if self.use_tpu: <ide> checkpoint = tf.train.Checkpoint( <ide> model=model, optimizer=self._create_optimizer())
4
Ruby
Ruby
fix example url in text helper
b214ddd1c986a466923fd8a2f3dddff5bfe28637
<ide><path>actionpack/lib/action_view/helpers/text_helper.rb <ide> module TextHelper <ide> # if logged_in <ide> # concat "Logged in!" <ide> # else <del> # concat link_to('login', :action => login) <add> # concat link_to('login', :action => :login) <ide> # end <ide> # # will either display "Logged in!" or a login link <ide> # %>
1
Ruby
Ruby
prefer composition over inheritence
6ea781c9a7913ddf75ecdb26a273e194df95b2dc
<ide><path>actionpack/lib/action_dispatch/http/headers.rb <ide> module ActionDispatch <ide> module Http <del> class Headers < ::Hash <add> class Headers <add> include Enumerable <add> <ide> @@env_cache = Hash.new { |h,k| h[k] = "HTTP_#{k.upcase.gsub(/-/, '_')}" } <ide> <ide> def initialize(*args) <del> <del> if args.size == 1 && args[0].is_a?(Hash) <del> super() <del> update(args[0]) <del> else <del> super <del> end <add> @headers = args.first || {} <ide> end <ide> <ide> def [](header_name) <del> super env_name(header_name) <add> @headers[env_name(header_name)] <ide> end <ide> <add> def []=(k,v); @headers[k] = v; end <add> def key?(k); @headers.key? k; end <add> alias :include? :key? <add> <ide> def fetch(header_name, default=nil, &block) <del> super env_name(header_name), default, &block <add> @headers.fetch env_name(header_name), default, &block <add> end <add> <add> def each(&block) <add> @headers.each(&block) <ide> end <ide> <ide> private <ide> # Converts a HTTP header name to an environment variable name if it is <ide> # not contained within the headers hash. <ide> def env_name(header_name) <del> include?(header_name) ? header_name : @@env_cache[header_name] <add> @headers.include?(header_name) ? header_name : @@env_cache[header_name] <ide> end <ide> end <ide> end <ide><path>actionpack/test/dispatch/header_test.rb <ide> def setup <ide> ) <ide> end <ide> <add> def test_each <add> headers = [] <add> @headers.each { |pair| headers << pair } <add> assert_equal [["HTTP_CONTENT_TYPE", "text/plain"]], headers <add> end <add> <add> def test_setter <add> @headers['foo'] = "bar" <add> assert_equal "bar", @headers['foo'] <add> end <add> <add> def test_key? <add> assert @headers.key?('HTTP_CONTENT_TYPE') <add> assert @headers.include?('HTTP_CONTENT_TYPE') <add> end <add> <ide> test "content type" do <ide> assert_equal "text/plain", @headers["Content-Type"] <ide> assert_equal "text/plain", @headers["content-type"]
2
Python
Python
add missing region to scrape prices script
a250cce9b07a6bbbcdeafafb9828ed73c7c3ab8d
<ide><path>contrib/scrape-ec2-prices.py <ide> 'us-west-2': 'ec2_us_west_oregon', <ide> 'eu-west-1': 'ec2_eu_west', <ide> 'eu-west-2': 'ec2_eu_west_london', <add> 'eu-west-3': 'ec2_eu_west_3', <ide> 'eu-ireland': 'ec2_eu_west', <ide> 'eu-central-1': 'ec2_eu_central', <ide> 'ca-central-1': 'ec2_ca_central_1',
1
Text
Text
translate documentation to italian
a4ec19500a75a38334e5886922e3c4e59b33a2f0
<ide><path>docs/docs/01-why-react.it-IT.md <add>--- <add>id: why-react-it-IT <add>title: Perché React? <add>permalink: why-react-it-IT.html <add>next: displaying-data-it-IT.html <add>--- <add>React è una libreria JavaScript per creare interfacce utente scritta da Facebook e Instagram. A molti piace pensare a React come alla **V** di **[MVC](https://it.wikipedia.org/wiki/Model-View-Controller)**. <add> <add>Abbiamo costruito React per risolvere un problema: **costruire applicazioni di grandi dimensioni con dati che cambiano nel tempo**. <add> <add>## Semplice <add> <add>Dichiara semplicemente come la tua app debba apparire in ogni istante, e React gestirà automaticamente tutti gli aggiornamenti della UI quando i dati sottostanti cambiano. <add> <add>## Dichiarativo <add> <add>Quando i dati cambiano, React preme idealmente il bottone "aggiorna", e sa come aggiornare soltanto le parti che sono cambiate. <add> <add>## Costruisci Componenti Componibili <add> <add>React è basato interamente sulla costruzione di componenti riutilizzabili. Infatti, con React l'*unica* cosa che fai è costruire componenti. Dal momento che sono così incapsulati, i componenti facilitano il riutilizzo del codice, la verifica e la separazione dei concetti. <add> <add>## Dagli Cinque Minuti <add> <add>React sfida molte convenzioni, e a prima vista alcune delle idee potrebbero sembrare folli. [Dagli cinque minuti](https://signalvnoise.com/posts/3124-give-it-five-minutes) mentre leggi questa guida; quelle idee folli hanno funzionato per costruire migliaia di componenti sia dentro che fuori da Facebook e Instagram. <add> <add>## Per Approfondire <add> <add>Puoi approfondire le nostre motivazioni per la costruzione di React leggendo [questo articolo del blog](/react/blog/2013/06/05/why-react.html). <ide><path>docs/docs/02-displaying-data.it-IT.md <add>--- <add>id: displaying-data-it-IT <add>title: Visualizzare Dati <add>permalink: displaying-data-it-IT.html <add>prev: why-react-it-IT.html <add>next: jsx-in-depth-it-IT.html <add>--- <add> <add>L'attività più basilare che puoi effettuare con una UI è mostrare dei dati. React rende visualizzare dati semplice e mantiene automaticamente l'interfaccia aggiornata quando i dati cambiano. <add> <add> <add>## Per Cominciare <add> <add>Diamo un'occhiata ad un esempio davvero semplice. Creiamo un file dal nome `hello-react.html` con il codice seguente: <add> <add>```html <add><!DOCTYPE html> <add><html> <add> <head> <add> <meta charset="UTF-8" /> <add> <title>Hello React</title> <add> <script src="https://fb.me/react-{{site.react_version}}.js"></script> <add> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script> <add> </head> <add> <body> <add> <div id="example"></div> <add> <script type="text/babel"> <add> <add> // ** Il tuo codice va qui! ** <add> <add> </script> <add> </body> <add></html> <add>``` <add> <add>Nel resto della documentazione, ci concentreremo soltanto sul codice JavaScript e assumeremo che sia inserito in un modello come quello qui sopra. Sostituisci il commento segnaposto qui sopra con il seguente codice JSX: <add> <add>```javascript <add>var HelloWorld = React.createClass({ <add> render: function() { <add> return ( <add> <p> <add> Ciao, <input type="text" placeholder="Scrivi il tuo nome" />! <add> È il {this.props.date.toTimeString()} <add> </p> <add> ); <add> } <add>}); <add> <add>setInterval(function() { <add> React.render( <add> <HelloWorld date={new Date()} />, <add> document.getElementById('example') <add> ); <add>}, 500); <add>``` <add> <add> <add>## Aggiornamenti Reattivi <add> <add>Apri `hello-react.html` in un browser web e scrivi il tuo nome nel campo di testo. Osserva che React cambia soltanto la stringa di testo dell'ora nella UI — ogni input che inserisci nel campo di testo rimane, anche se non hai scritto alcun codice che gestisce questo comportamento. React lo capisce da solo al tuo posto e fa la cosa giusta. <add> <add>La maniera in cui siamo in grado di capirlo è che React non manipola il DOM a meno che non sia necessario. **Utilizza un DOM interno fittizio e veloce per effettuare confronti ed effettuare le mutazioni del DOM più efficienti al tuo posto.** <add> <add>Gli input di questo componente sono chiamati `props` — breve per "properties". Sono passati come attributi nella sintassi JSX. Puoi pensare ad essi come immutabili nel contesto del componente, ovvero, **non assegnare mai `this.props`**. <add> <add> <add>## I Componenti Sono Come Funzioni <add> <add>I componenti React sono molto semplici. Puoi immaginarli come semplici funzioni che ricevono in ingresso `props` e `state` (discusso in seguito) e rendono HTML. Fatta questa premessa, i componenti sono molto semplici da descrivere. <add> <add>> Nota: <add>> <add>> **Una limitazione**: i componenti React possono rendere soltanto un singolo nodo radice. Se desideri restituire nodi multipli, essi *devono* essere avvolti in un singolo nodo radice. <add> <add> <add>## Sintassi JSX <add> <add>Crediamo fermamente che i componenti sono la maniera corretta di separare i concetti anziché i "modelli" e la "logica di presentazione." Pensiamo che il markup e il codice che lo genera siano intimamente collegati. Inoltre, la logica di presentazione è solitamente molto complessa e usare un linguaggio di modello per esprimerla risulta dispendioso. <add> <add>Abbiamo scoperto che la migliore soluzione a questo problema è generare HTML e un albero di componenti direttamente dal codice JavaScript in maniera da poter utilizzare tutta la potenza espressiva di un vero linguaggio di programmazione per costruire UI. <add> <add>Per rendere il compito più facile, abbiamo aggiunto una semplice e **opzionale** sintassi simile all'HTML per creare questi nodi di albero React. <add> <add>**JSX ti permette di creare oggetti JavaScript usando una sintassi HTML.** Per generare un collegamento in React usando puro JavaScript puoi scrivere: <add> <add>`React.createElement('a', {href: 'https://facebook.github.io/react/'}, 'Ciao!')` <add> <add>Con JSX ciò diventa: <add> <add>`<a href="https://facebook.github.io/react/">Ciao!</a>` <add> <add>Abbiamo scoperto che questo ha reso la costruzione di applicazioni React più semplice e i designer tendono a preferire la sintassi, ma ciascuno ha un diverso flusso di lavoro, quindi **JSX non è richiesto per utilizzare React.** <add> <add>JSX è di dimensioni contenute. Per maggiori informazioni, consulta [JSX in profondità](/react/docs/jsx-in-depth-it-IT.html). Oppure osserva la trasformazione in tempo reale sulla [REPL di Babel](https://babeljs.io/repl/). <add> <add>JSX è simile all'HTML, ma non proprio identico. Consulta la guida [JSX gotchas](/react/docs/jsx-gotchas-it-IT.html) per alcune differenze fondamentali. <add> <add>[Babel offre una varietà di strumenti per cominciare a usare JSX](http://babeljs.io/docs/setup/), dagli strumenti a riga di comando alle integrazioni in Ruby on Rails. Scegli lo strumento che funziona meglio per te. <add> <add> <add>## React senza JSX <add> <add>JSX è completamente opzionale; non è necessario utilizzare JSX con React. Puoi creare elementi React in puro JavaScript usando `React.createElement`, che richiede un nome di tag o di componente, un oggetto di proprietà e un numero variabile di argomenti che rappresentano nodi figli opzionali. <add> <add>```javascript <add>var child1 = React.createElement('li', null, 'Primo Contenuto di Testo'); <add>var child2 = React.createElement('li', null, 'Secondo Contenuto di Testo'); <add>var root = React.createElement('ul', { className: 'my-list' }, child1, child2); <add>React.render(root, document.getElementById('example')); <add>``` <add> <add>Per comodità, puoi creare funzioni factory scorciatoia per costruire elementi da componenti personalizzati. <add> <add>```javascript <add>var Factory = React.createFactory(ComponentClass); <add>... <add>var root = Factory({ custom: 'prop' }); <add>React.render(root, document.getElementById('example')); <add>``` <add> <add>React possiede già delle factory predefinite per i tag HTML comuni: <add> <add>```javascript <add>var root = React.DOM.ul({ className: 'my-list' }, <add> React.DOM.li(null, 'Contenuto di Testo') <add> ); <add>``` <ide><path>docs/docs/02.1-jsx-in-depth.it-IT.md <add>--- <add>id: jsx-in-depth-it-IT <add>title: JSX in Profondità <add>permalink: jsx-in-depth-it-IT.html <add>prev: displaying-data-it-IT.html <add>next: jsx-spread-it-IT.html <add>--- <add> <add>[JSX](https://facebook.github.io/jsx/) è un'estensione della sintassi JavaScript che somiglia all'XML. Puoi usare una semplice trasformazione sintattica di JSX con React. <add> <add>## Perché JSX? <add> <add>Non devi per forza utilizzare JSX con React. Puoi anche usare semplice JS. Tuttavia, raccomandiamo di utilizzare JSX perché usa una sintassi concisa e familiare per definire strutture ad albero dotate di attributi. <add> <add>È più familiare a sviluppatori occasionali come i designer. <add> <add>L'XML ha i benefici di tag di apertura e chiusura bilanciati. Ciò rende la lettura di grandi strutture ad albero più semplice di chiamate a funzione o oggetti letterali. <add> <add>Non altera la semantica di JavaScript. <add> <add>## Tag HTML o Componenti React <add> <add>React può sia rendere tag HTML (stringhe) che componenti React (classi). <add> <add>Per rendere untag HTML, usa nomi di tag minuscoli in JSX: <add> <add>```javascript <add>var myDivElement = <div className="foo" />; <add>React.render(myDivElement, document.getElementById('example')); <add>``` <add> <add>Per rendere un componente React, definisci una variabile locale che comincia con una lettera maiuscola: <add> <add>```javascript <add>var MyComponent = React.createClass({/*...*/}); <add>var myElement = <MyComponent someProperty={true} />; <add>React.render(myElement, document.getElementById('example')); <add>``` <add> <add>Il JSX di React utilizza la convenzione maiuscolo o minuscolo per distinguere tra classi di componenti locali e tag HTML. <add> <add>> Nota: <add>> <add>> Poiché JSX è JavaScript, gli identificatori come `class` e `for` sono sconsigliati <add>> come nomi di attributi XML. Invece, i componenti DOM React si aspettano nomi di proprietà <add>> come `className` e `htmlFor` rispettivamente. <add> <add>## La Trasformazione <add> <add>Il JSX di React viene trasformato da una sintassi XML a JavaScript nativo. Gli elementi XML, gli attributi e i figli sono trasformati in argomenti passati a `React.createElement`. <add> <add>```javascript <add>var Nav; <add>// Input (JSX): <add>var app = <Nav color="blue" />; <add>// Output (JS): <add>var app = React.createElement(Nav, {color:"blue"}); <add>``` <add> <add>Osserva che per utilizzare `<Nav />`, la variabile `Nav` deve essere visibile. <add> <add>JSX permette anche di specificare i figli usando una sintassi XML: <add> <add>```javascript <add>var Nav, Profile; <add>// Input (JSX): <add>var app = <Nav color="blue"><Profile>click</Profile></Nav>; <add>// Output (JS): <add>var app = React.createElement( <add> Nav, <add> {color:"blue"}, <add> React.createElement(Profile, null, "click") <add>); <add>``` <add> <add>JSX inferirà il [displayName](/react/docs/component-specs-it-IT.html#displayname) della classe dall'assegnazione delle variabile, quando il valore di displayName è indefinito: <add> <add>```javascript <add>// Input (JSX): <add>var Nav = React.createClass({ }); <add>// Output (JS): <add>var Nav = React.createClass({displayName: "Nav", }); <add>``` <add> <add>Usa la [REPL di Babel](https://babeljs.io/repl/) per provare il JSX e vedere come viene trasformato <add>in JavaScript nativo, e il <add>[convertitore da HTML a JSX](/react/html-jsx.html) per convertire il tuo HTML esistente a <add>JSX. <add> <add>Se desideri utilizzare JSX, la guida [Primi Passi](/react/docs/getting-started-it-IT.html) ti mostra come impostare la compilazione. <add> <add>> Nota: <add>> <add>> L'espressione JSX viene sempre valutata come un ReactElement. Le implementazioni <add>> attuali potrebbero differire. Un modo ottimizzato potrebbe porre il <add>> ReactElement in linea come un oggetto letterale per evitare il codice di validazione in <add>> `React.createElement`. <add> <add>## Namespace dei Componenti <add> <add>Se stai costruendo un componente che ha parecchi figli, come ad esempio un modulo, potresti facilmente trovarti con una quantità di dichiarazioni di variabili: <add> <add>```javascript <add>// Imbarazzante blocco di dichiarazioni di variabili <add>var Form = MyFormComponent; <add>var FormRow = Form.Row; <add>var FormLabel = Form.Label; <add>var FormInput = Form.Input; <add> <add>var App = ( <add> <Form> <add> <FormRow> <add> <FormLabel /> <add> <FormInput /> <add> </FormRow> <add> </Form> <add>); <add>``` <add> <add>Per rendere tutto ciò più semplice e leggibile, *i componenti con un namespace* ti permettono di usare un componente che dispone di altri componenti come proprietà: <add> <add>```javascript <add>var Form = MyFormComponent; <add> <add>var App = ( <add> <Form> <add> <Form.Row> <add> <Form.Label /> <add> <Form.Input /> <add> </Form.Row> <add> </Form> <add>); <add>``` <add> <add>Per fare ciò, devi semplicemente creare i tuoi *"sub-componenti"* come proprietà del componente principale: <add> <add>```javascript <add>var MyFormComponent = React.createClass({ ... }); <add> <add>MyFormComponent.Row = React.createClass({ ... }); <add>MyFormComponent.Label = React.createClass({ ... }); <add>MyFormComponent.Input = React.createClass({ ... }); <add>``` <add> <add>JSX gestirà il tutto correttamente al momento di compilare il tuo codice. <add> <add>```javascript <add>var App = ( <add> React.createElement(Form, null, <add> React.createElement(Form.Row, null, <add> React.createElement(Form.Label, null), <add> React.createElement(Form.Input, null) <add> ) <add> ) <add>); <add>``` <add> <add>> Nota: <add>> <add>> Questa funzionalità è disponibile nella [v0.11](/react/blog/2014/07/17/react-v0.11.html#jsx) e successive. <add> <add>## Espressioni JavaScript <add> <add>### Expressioni come Attributi <add> <add>Per usare un'espressione JavaScript come valore di un attributo, racchiudi l'espressione in un paio <add>di parentesi graffe (`{}`) anziché doppi apici (`""`). <add> <add>```javascript <add>// Input (JSX): <add>var person = <Person name={window.isLoggedIn ? window.name : ''} />; <add>// Output (JS): <add>var person = React.createElement( <add> Person, <add> {name: window.isLoggedIn ? window.name : ''} <add>); <add>``` <add> <add>### Attributi Booleani <add> <add>Omettere il valore di un attributo fa in modo che JSX lo tratti come `true`. Per passare `false` occorre utilizzare un'espressione come attributo. Ciò capita spesso quando si usano elementi di moduli HTML, con attributi come `disabled`, `required`, `checked` e `readOnly`. <add> <add>```javascript <add>// Queste due forme sono equivalenti in JSX per disabilitare un bottone <add><input type="button" disabled />; <add><input type="button" disabled={true} />; <add> <add>// E queste due forme sono equivalenti in JSX per non disabilitare un bottone <add><input type="button" />; <add><input type="button" disabled={false} />; <add>``` <add> <add>### Expressioni per Figli <add> <add>Similmente, espressioni JavaScript possono essere utilizzate per rappresentare figli: <add> <add>```javascript <add>// Input (JSX): <add>var content = <Container>{window.isLoggedIn ? <Nav /> : <Login />}</Container>; <add>// Output (JS): <add>var content = React.createElement( <add> Container, <add> null, <add> window.isLoggedIn ? React.createElement(Nav) : React.createElement(Login) <add>); <add>``` <add> <add>### Commenti <add> <add>È facile aggiungere commenti al tuo codice JSX; sono semplici espressioni JS. Devi soltanto prestare attenzione a porre `{}` attorno ai commenti quando ti trovi dentro la sezione figli di un tag. <add> <add>```javascript <add>var content = ( <add> <Nav> <add> {/* commento figlio, racchiuso in {} */} <add> <Person <add> /* commento <add> su più <add> righe */ <add> name={window.isLoggedIn ? window.name : ''} // fine del commento su una riga <add> /> <add> </Nav> <add>); <add>``` <add> <add>> NOTA: <add>> <add>> JSX è simile all'HTML, ma non esattamente identico. Consulta la guida [JSX gotchas](/react/docs/jsx-gotchas-it-IT.html) per le differenze fondamentali. <ide><path>docs/docs/02.2-jsx-spread.it-IT.md <add>--- <add>id: jsx-spread-it-IT <add>title: Attributi Spread JSX <add>permalink: jsx-spread-it-IT.html <add>prev: jsx-in-depth-it-IT.html <add>next: jsx-gotchas-it-IT.html <add>--- <add> <add>Se sai in anticipo che tutte le proprietà che desideri assegnare ad un componente, usare JSX è facile: <add> <add>```javascript <add> var component = <Component foo={x} bar={y} />; <add>``` <add> <add>## Le Props Mutevoli sono il Male <add> <add>Se non sai quali proprietà desideri impostare, potresti essere tentato di aggiungerle all'oggetto in seguito: <add> <add>```javascript <add> var component = <Component />; <add> component.props.foo = x; // male <add> component.props.bar = y; // altrettanto male <add>``` <add> <add>Questo è un anti-pattern perché significa che non possiamo aiutarti a verificare i propTypes per tempo. Ciò significa che i tuoi errori di propTypes finiscono per avere uno stack trace indecifrabile. <add> <add>Le props dovrebbero essere considerate immutabili. Mutare l'oggetto props altrove potrebbe causare conseguenze inattese, quindi a questo punto dovrebbe essere idealmente considerato un oggetto congelato. <add> <add>## Attributi Spread <add> <add>Adesso puoi utilizzare una nuova caratteristica di JSX chiamata attributi spread: <add> <add>```javascript <add> var props = {}; <add> props.foo = x; <add> props.bar = y; <add> var component = <Component {...props} />; <add>``` <add> <add>Le proprietà dell'oggetto che passi al componente sono copiate nelle sue props. <add> <add>Puoi usarlo più volte o combinarlo con altri attributi. L'ordine in cui sono specificati è rilevante. Attributi successivi ridefiniscono quelli precedentemente impostati. <add> <add>```javascript <add> var props = { foo: 'default' }; <add> var component = <Component {...props} foo={'override'} />; <add> console.log(component.props.foo); // 'override' <add>``` <add> <add>## Cos'è la strana notazione `...`? <add> <add>L'operatore `...` (o operatore spread) è già supportato per gli [array in ES6](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator). Esiste anche una proposta per ES7 per le proprietà [Spread e Rest di Object](https://github.com/sebmarkbage/ecmascript-rest-spread). Stiamo prendendo spunto da questi standard supportati o in corso di sviluppo per fornire una sintassi più pulita a JSX. <ide><path>docs/docs/02.3-jsx-gotchas.it-IT.md <add>--- <add>id: jsx-gotchas-it-IT <add>title: JSX Gotchas <add>permalink: jsx-gotchas-it-IT.html <add>prev: jsx-spread-it-IT.html <add>next: interactivity-and-dynamic-uis-it-IT.html <add>--- <add> <add>JSX somiglia all'HTML ma ci sono delle differenze importanti da tenere in considerazione. <add> <add>> Nota: <add>> <add>> Per le differenze del DOM, come l'attributo `style` in linea, consulta [here](/react/docs/dom-differences-it-IT.html). <add> <add>## Entità HTML <add> <add>Puoi inserire entità HTML nel testo letterale in JSX: <add> <add>```javascript <add><div>Primo &middot; Secondo</div> <add>``` <add> <add>Se desideri visualizzare un'entità HTML all'interno di un contenuto dinamico, avrai problemi con il doppio escape, poiché React effettua in maniera predefinita l'escape di tutte le stringhe visualizzate per prevenire un'ampia gamma di attacchi XSS. <add> <add>```javascript <add>// Male: Mostra "Primo &middot; Secondo" <add><div>{'Primo &middot; Secondo'}</div> <add>``` <add> <add>Esistono molte maniere di aggirare questo problema. La più facile è scrivere i caratteri Unicode direttamente in JavaScript. Dovrai assicurarti che il file sia salvato come UTF-8 e che le appropriate direttive UTF-8 siano impostate in modo che il browser li visualizzi correttamente. <add> <add>```javascript <add><div>{'Primo · Secondo'}</div> <add>``` <add> <add>Un'alternativa più sicura consiste nel trovare il [codice Unicode corrispondente all'entità](http://www.fileformat.info/info/unicode/char/b7/index.htm) e usarlo all'interno di una stringa JavaScript. <add> <add>```javascript <add><div>{'Primo \u00b7 Secondo'}</div> <add><div>{'Primo ' + String.fromCharCode(183) + ' Secondo'}</div> <add>``` <add> <add>Puoi usare array misti con stringhe ed elementi JSX. <add> <add>```javascript <add><div>{['Primo ', <span>&middot;</span>, ' Secondo']}</div> <add>``` <add> <add>Come ultima risorsa, puoi sempre [inserire HTML nativo](/react/tips/dangerously-set-inner-html.html). <add> <add>```javascript <add><div dangerouslySetInnerHTML={{'{{'}}__html: 'Primo &middot; Secondo'}} /> <add>``` <add> <add> <add>## Attributi HTML Personalizzati <add> <add>Se passi proprietà che non esistono nella specifica HTML ad elementi HTML nativi, React li ignorerà. Se vuoi usare un attributo personalizzato, devi prefiggerlo con `data-`. <add> <add>```javascript <add><div data-custom-attribute="foo" /> <add>``` <add> <add>Gli attributi per [l'Accessibilità del Web](http://www.w3.org/WAI/intro/aria) che iniziano per `aria-` saranno gestiti correttamente. <add> <add>```javascript <add><div aria-hidden={true} /> <add>``` <ide><path>docs/docs/03-interactivity-and-dynamic-uis.it-IT.md <add>--- <add>id: interactivity-and-dynamic-uis-it-IT <add>title: Interattività e UI Dinamiche <add>permalink: interactivity-and-dynamic-uis-it-IT.html <add>prev: jsx-gotchas-it-IT.html <add>next: multiple-components-it-IT.html <add>--- <add> <add>Hai già [imparato a mostrare dati](/react/docs/displaying-data-it-IT.html) con React. Adesso vediamo come rendere le nostre UI interattive. <add> <add> <add>## Un Esempio Semplice <add> <add>```javascript <add>var LikeButton = React.createClass({ <add> getInitialState: function() { <add> return {liked: false}; <add> }, <add> handleClick: function(event) { <add> this.setState({liked: !this.state.liked}); <add> }, <add> render: function() { <add> var text = this.state.liked ? 'mi piace' : 'non mi piace'; <add> return ( <add> <p onClick={this.handleClick}> <add> You {text} this. Click to toggle. <add> </p> <add> ); <add> } <add>}); <add> <add>React.render( <add> <LikeButton />, <add> document.getElementById('example') <add>); <add>``` <add> <add> <add>## Gestione degli Eventi ed Eventi Sintetici <add> <add>Con React devi semplicemente passare il tuo gestore di eventi come una proprietà camelCased in modo simile a come faresti nel normale HTML. React si assicura che tutti gli eventi si comportano in maniera identica in IE8 e successivi implementando un sistema di eventi sintetici. Ovvero, React sa come propagare e catturare eventi secondo la specifica, e garantisce che gli eventi passati ai tuoi gestori di eventi siano consistenti con la [specifica W3C](http://www.w3.org/TR/DOM-Level-3-Events/), qualunque browser tu stia utilizzando. <add> <add> <add>## Dietro le Quinte: Binding Automatico e Delega degli Eventi <add> <add>Dietro le quinte, React esegue alcune operazioni per mantenere il tuo codice ad alte prestazioni e facile da comprendere. <add> <add>**Binding automatico:** Quando crei le callback in JavaScript, solitamente devi fare il binding esplicito del metodo alla sua istanza, in modo che il valore di `this` sia corretto. Con React, ogni metodo è automaticamente legato alla propria istanza del componente (eccetto quando si usa la sintassi delle classi ES6). React immagazzina il metodo legato in maniera tale da essere estremamente efficiente in termini di CPU e memoria. Ti permette anche di scrivere meno codice! <add> <add>**Delega degli eventi:** React non associa realmente i gestori di eventi ai nodi stessi. Quando React si avvia, comincia ad ascoltare tutti gli eventi a livello globale usando un singolo event listener. Quando un componente viene montato o smontato, i gestori di eventi sono semplicemente aggiunti o rimossi da un mapping interno. Quando si verifica un evento, React sa come inoltrarlo utilizzando questo mapping. Quando non ci sono più gestori di eventi rimasti nel mapping, i gestori di eventi di React sono semplici operazioni fittizie. Per saperne di più sul perché questo approccio è veloce, leggi [l'eccellente articolo sul blog di David Walsh](http://davidwalsh.name/event-delegate). <add> <add> <add>## I Componenti Sono Macchine a Stati Finiti <add> <add>React considera le UI come semplici macchine a stati finiti. Pensando alla UI come in uno di tanti stati diversi e visualizzando questi stati, è facile mantenere la UI consistente. <add> <add>In React, aggiorni semplicemente lo stato di un componente, e quindi visualizzi una nuova UI basata su questo nuovo stato. React si occupa di aggiornare il DOM al tuo posto nella maniera più efficiente. <add> <add> <add>## Come Funziona lo Stato <add> <add>Una maniera comune di informare React di un cambiamento nei dati è chiamare `setState(data, callback)`. Questo metodo effettua il merge di `data` in `this.state` e ridisegna il componente. Quando il componente ha terminato la fase di ri-rendering, la `callback` opzionale viene invocata. Nella maggior parte dei casi non avrai bisogno di fornire una `callback` dal momento che React si occuperà di mantenere la UI aggiornata per te. <add> <add> <add>## Quali Componenti Devono Avere uno Stato? <add> <add>La maggior parte dei tuoi componenti dovrebbero semplicemente ricevere dei dati da `props` e visualizzarli. Tuttavia, a volte hai bisogno di reagire all'input dell'utente, una richiesta al server o il trascorrere del tempo. In questi casi utilizzi lo stato. <add> <add>**Prova a mantenere il maggior numero possibile dei tuoi componenti privi di stato.** Facendo ciò, isolerai lo stato nel suo luogo logicamente corretto e minimizzerai la ridondanza, rendendo più semplice ragionare sulla tua applicazione. <add> <add>Un pattern comune è quello di creare diversi componenti privi di stato che mostrano semplicemente dati, e di avere un componente dotato di stato al di sopra di essi nella gerarchia, che passa il proprio stato ai suoi figli tramite le `props`. Il componente dotato di stato incapsula tutta la logica di interazione, mentre i componenti privi di stato si occupano della visualizzazione dei dati in maniera dichiarativa. <add> <add> <add>## Cosa *Dovrebbe* Contenere lo Stato? <add> <add>**Lo stato dovrebbe contenere dati che i gestori di eventi del componente possono modificare per scatenare un aggiornamento della UI.** In applicazioni reali, questi dati tendono ad essere molto limitati e serializzabili come JSON. Quando costruisci un componente dotato di stato, pensa alla minima rappresentazione possibile del suo stato, e conserva solo quelle proprietà in `this.state`. All'interno di `render()` calcola quindi ogni altra informazione necessaria basandoti sullo stato. Ti accorgerai che pensare e scrivere applicazioni in questo modo porta alla scrittura dell'applicazione più corretta, dal momento che aggiungere valori ridondanti o calcolati allo stato significherebbe doverli mantenere sincronizzati esplicitamente, anziché affidarti a React perché li calcoli al tuo posto. <add> <add>## Cosa *Non Dovrebbe* Contenere lo Stato? <add> <add>`this.state` dovrebbe contenere soltanto la quantità minima di dati indispensabile a rappresentare lo stato della tua UI. In quanto tale, non dovrebbe contenere: <add> <add>* **Dati calcolati:** Non preoccuparti di precalcolare valori basati sullo stato — è più semplice assicurarti che la tua UI sia consistente se effettui tutti i calcoli all'interno di `render()`. Per esempio, se lo stato contiene un array di elementi di una lista, e vuoi mostrare il numero di elementi come stringa, mostra semplicemente `this.state.listItems.length + ' elementi nella lista'` nel tuo metodo `render()` anziché conservarlo nello stato. <add>* **Componenti React:** Costruiscili in `render()` basandoti sulle proprietà e sullo stato del componente. <add>* **Dati duplicati dalle proprietà:** Prova ad utilizzare le proprietà come fonte di verità ove possibile. Un uso valido dello stato per i valori delle proprietà è conservarne il valore precedente quando le proprietà cambiano nel tempo. <ide><path>docs/docs/04-multiple-components.it-IT.md <add>--- <add>id: multiple-components-it-IT <add>title: Componenti Multipli <add>permalink: multiple-components-it-IT.html <add>prev: interactivity-and-dynamic-uis-it-IT.html <add>next: reusable-components-it-IT.html <add>--- <add> <add>Finora abbiamo visto come scrivere un singolo componente per mostrare dati e gestire l'input dell'itente. Adesso esaminiamo una delle migliori caratteristiche di React: la componibilità. <add> <add> <add>## Motivazione: Separazione dei Concetti <add> <add>Costruendo componenti modulari che riutilizzano altri componenti con interfacce ben definite, ottieni gli stessi benefici che otterresti usando funzioni o classi. Nello specifico, puoi *separare i diversi concetti* della tua applicazione nel modo che preferisci semplicemente costruendo nuovi componenti. Costruendo una libreria di componenti personalizzati per la tua applicazione, stai esprimendo la tua UI in una maniera che si adatta meglio al tuo dominio. <add> <add> <add>## Esepmio di Composizione <add> <add>Creiamo un semplice componente Avatar che mostra una foto del profilo e un nome utente usando la Graph API di Facebook. <add> <add>```javascript <add>var Avatar = React.createClass({ <add> render: function() { <add> return ( <add> <div> <add> <ProfilePic username={this.props.username} /> <add> <ProfileLink username={this.props.username} /> <add> </div> <add> ); <add> } <add>}); <add> <add>var ProfilePic = React.createClass({ <add> render: function() { <add> return ( <add> <img src={'https://graph.facebook.com/' + this.props.username + '/picture'} /> <add> ); <add> } <add>}); <add> <add>var ProfileLink = React.createClass({ <add> render: function() { <add> return ( <add> <a href={'https://www.facebook.com/' + this.props.username}> <add> {this.props.username} <add> </a> <add> ); <add> } <add>}); <add> <add>React.render( <add> <Avatar username="pwh" />, <add> document.getElementById('example') <add>); <add>``` <add> <add> <add>## Possesso <add> <add>Nell'esempio precedente, le istanze di `Avatar` *posseggono* instanze di `ProfilePic` e `ProfileLink`. In React, **un proprietario è il componente che imposta le `props` di altri componenti**. Più formalmente, se un componente `X` è creato nel metodo `render()` del componente `Y`, si dice che `X` è *di proprietà di* `Y`. Come discusso in precedenza, un componente non può mutare le sue `props` — sono sempre consistenti con il valore che il suo proprietario ha impostato. Questa invariante fondamentale porta a UI la cui consistenza può essere garantita. <add> <add>È importante distinguere tra la relazione di proprietario-proprietà e la relazione genitore-figlio. La relazione proprietario-proprietà è specifica di React, mentre la relazione genitore-figlio è semplicemente quella che conosci e ami del DOM. Nell'esempio precedente, `Avatar` possiede il `div`, le istanze di `ProfilePic` e `ProfileLink`, e `div` è il **genitore** (ma non il proprietario) delle istanze di `ProfilePic` e `ProfileLink`. <add> <add> <add>## Figli <add> <add>Quando crei un'istanza di un componente React, puoi includere componenti React aggiuntivi o espressioni JavaScript tra i tag di apertura e chiusura come segue: <add> <add>```javascript <add><Parent><Child /></Parent> <add>``` <add> <add>`Parent` può accedere ai propri figli leggendo la speciale proprietà `this.props.children`. **`this.props.children` è una struttura dati opaca:** usa le [utilità React.Children](/react/docs/top-level-api.html#react.children) per manipolare i figli. <add> <add> <add>### Riconciliazione dei Figli <add> <add>**La riconciliazione è il processo per il quale React aggiorna il DOM ad ogni passata di rendering.** In generale, i figli sono riconciliati secondo l'ordine in cui sono mostrati. Per esempio, supponiamo che due passate di rendering generino rispettivamente il markup seguente: <add> <add>```html <add>// Prima passata di rendering <add><Card> <add> <p>Paragrafo 1</p> <add> <p>Paragrafo 2</p> <add></Card> <add>// Seconda passata di rendering <add><Card> <add> <p>Paragrafo 2</p> <add></Card> <add>``` <add> <add>Intuitivamente, `<p>Paragrafo 1</p>` è stato rimosso. Invece, React riconcilierà il DOM cambiando il testo contenuto nel primo figlio e distruggerà l'ultimo figlio. React reconcilia secondo l'*ordine* dei figli. <add> <add> <add>### Figli Dotati di Stato <add> <add>Per molti componenti, questo non è un grande problema. Tuttavia, per i componenti dotati di stato che mantengono dati in `this.state` attraverso le diverse passate di rendering, questo può essere problematico. <add> <add>In molti casi, questo problema può essere aggirato nascondendo gli elementi anziché distruggendoli: <add> <add>```html <add>// Prima passata di rendering <add><Card> <add> <p>Paragrafo 1</p> <add> <p>Paragrafo 2</p> <add></Card> <add>// Seconda passata di rendering <add><Card> <add> <p style={{'{{'}}display: 'none'}}>Paragrafo 1</p> <add> <p>Paragrafo 2</p> <add></Card> <add>``` <add> <add> <add>### Figli Dinamici <add> <add>La situazione si complica quando i figli sono rimescolati (come nei risultati della ricerca) o se nuovi componenti sono aggiunti all'inizio della lista (come negli stream). In questi casi quando l'identità e lo stato di ogni figlio deve essere preservato attraverso passate di rendering, puoi unicamente identificare ciascun figlio assegnandogli una proprietà `key`: <add> <add>```javascript <add> render: function() { <add> var results = this.props.results; <add> return ( <add> <ol> <add> {results.map(function(result) { <add> return <li key={result.id}>{result.text}</li>; <add> })} <add> </ol> <add> ); <add> } <add>``` <add> <add>Quando React riconcilia i figli dotati di `key`, si assicurerà che ciascun figlio con la proprietà `key` sia riordinato (anziché clobbered) o distrutto (anziché riutilizzato). <add> <add>La proprietà `key` dovrebbe *sempre* essere fornita direttamente all'elemento del componente nell'array, non al contenitore HTML di ciascun componente dell'array: <add> <add>```javascript <add>// SBAGLIATO! <add>var ListItemWrapper = React.createClass({ <add> render: function() { <add> return <li key={this.props.data.id}>{this.props.data.text}</li>; <add> } <add>}); <add>var MyComponent = React.createClass({ <add> render: function() { <add> return ( <add> <ul> <add> {this.props.results.map(function(result) { <add> return <ListItemWrapper data={result}/>; <add> })} <add> </ul> <add> ); <add> } <add>}); <add>``` <add>```javascript <add>// Corretto :) <add>var ListItemWrapper = React.createClass({ <add> render: function() { <add> return <li>{this.props.data.text}</li>; <add> } <add>}); <add>var MyComponent = React.createClass({ <add> render: function() { <add> return ( <add> <ul> <add> {this.props.results.map(function(result) { <add> return <ListItemWrapper key={result.id} data={result}/>; <add> })} <add> </ul> <add> ); <add> } <add>}); <add>``` <add> <add>Puoi anche assegnare chiavi ai figli passandogli un oggetto ReactFragment. Leggi [Frammenti con Chiave](create-fragment.html) per maggiori dettagli. <add> <add>## Flusso dei Dati <add> <add>In React, i dati fluiscono dal proprietario al componente posseduto attraverso le `props` come discusso in precedenza. Questo è a tutti gli effetti un binding di dati unidirezionale: i proprietari legano le proprietà dei componenti di loro proprietà a dei valori che il proprietario stesso ha calcolato in base ai propri `props` o `state`. Dal momento che questo processo avviene ricorsivamente, i cambiamenti dei dati vengono riflessi automaticamente ovunque vengano usati. <add> <add> <add>## Una Nota sulle Prestazioni <add> <add>Ti starai chiedendo che cambiare i dati sia un'operazione costosa in presenza di un gran numero di nodi sotto un proprietario. La buona notizia è che JavaScript è veloce e i metodi `render()` tendono ad essere molto semplici, quindi in molte applicazioni questo è un processo estremamente veloce. Inoltre, il collo di bottiglia è quasi sempre la mutazione del DOM e non l'esecuzione di JS. React ottimizzerà tutto per te usando il raggruppamento e osservando i cambiamenti. <add> <add>Tuttavia, a volte vorrai avere un controllo più raffinato sulle tue prestazioni. In tal caso, ridefinisci il metodo `shouldComponentUpdate()` per restituire false quando vuoi che React salti il trattamento di un sottoalbero. Consulta [la documentazione di riferimento di React](/react/docs/component-specs.html) per maggiori informazioni. <add> <add>> Nota: <add>> <add>> Se `shouldComponentUpdate()` restituisce false quando i dati sono effettivamente cambiati, React non è in grado di mantenere la tua UI in sincronia. Assicurati di usare questa tecnica con cognizione di causa, e soltanto in presenza di problemi percettibili di prestazioni. Non sottovalutare l'estrema velocità di esecuzione di JavaScript se paragonata a quella del DOM. <ide><path>docs/docs/05-reusable-components.it-IT.md <add>--- <add>id: reusable-components-it-IT <add>title: Componenti Riutilizzabili <add>permalink: reusable-components-it-IT.html <add>prev: multiple-components-it-IT.html <add>next: transferring-props-it-IT.html <add>--- <add> <add>Quando disegni interfacce, separa gli elementi comuni di design (bottoni, campi dei moduli, componenti di layout, etc.) in componenti riutilizzabili con interfacce ben definite. In questo modo, la prossima volta che dovrai costruire una nuova UI, puoi scrivere molto meno codice. Ciò significa tempi di sviluppo più brevi, meno bachi, e meno byte trasferiti sulla rete. <add> <add> <add>## Validazione delle Proprietà <add> <add>Mentre la tua applicazione cresce, è utile assicurarsi che i tuoi componenti vengano usati correttamente. Ciò viene fatto permettendoti di specificare i `propTypes`. `React.PropTypes` esporta una gamma di validatori che possono essere usati per assicurarsi che i dati che ricevi siano validi. Quando ad una proprietà è assegnato un valore non valido, sarà mostrato un avvertimento nella console JavaScript. Nota che per motivi di prestazioni, `propTypes` è utilizzato soltanto nella modalità di sviluppo. Di seguito trovi un esempio che documenta i diversi validatori che vengono forniti: <add> <add>```javascript <add>React.createClass({ <add> propTypes: { <add> // Puoi dichiarare che una proprietà è uno specifico tipo primitivo JS. In <add> // maniera predefinita, questi sono tutti opzionali. <add> optionalArray: React.PropTypes.array, <add> optionalBool: React.PropTypes.bool, <add> optionalFunc: React.PropTypes.func, <add> optionalNumber: React.PropTypes.number, <add> optionalObject: React.PropTypes.object, <add> optionalString: React.PropTypes.string, <add> <add> // Tutto ciò che può essere mostrato: numeri, stringhe, elementi, o un array <add> // (o frammento) contenente questi tipi. <add> optionalNode: React.PropTypes.node, <add> <add> // Un elemento React. <add> optionalElement: React.PropTypes.element, <add> <add> // Puoi anche dichiarare che una proprietà è un'istanza di una classe. Questo <add> // validatore usa l'operatore instanceof di JS. <add> optionalMessage: React.PropTypes.instanceOf(Message), <add> <add> // Puoi assicurarti che la tua proprietà sia ristretta a valori specifici <add> // trattandoli come una enumerazione. <add> optionalEnum: React.PropTypes.oneOf(['News', 'Photos']), <add> <add> // Un oggetto che può essere di uno tra diversi tipi <add> optionalUnion: React.PropTypes.oneOfType([ <add> React.PropTypes.string, <add> React.PropTypes.number, <add> React.PropTypes.instanceOf(Message) <add> ]), <add> <add> // Un array di un tipo specificato <add> optionalArrayOf: React.PropTypes.arrayOf(React.PropTypes.number), <add> <add> // Un oggetto con proprietà dai valori di un tipo specificato <add> optionalObjectOf: React.PropTypes.objectOf(React.PropTypes.number), <add> <add> // Un oggetto che accetta una forma particolare <add> optionalObjectWithShape: React.PropTypes.shape({ <add> color: React.PropTypes.string, <add> fontSize: React.PropTypes.number <add> }), <add> <add> // Puoi concatenare ciascuna delle precedenti con `isRequired` per assicurarti <add> // che venga mostrato un avvertimento se la proprietà non viene impostata. <add> requiredFunc: React.PropTypes.func.isRequired, <add> <add> // Un valore di un tipo qualsiasi <add> requiredAny: React.PropTypes.any.isRequired, <add> <add> // Puoi inoltre specificare un validatore personalizzato. Deve restituire un <add> // oggetto di tipo Error se la validazione fallisce. Non lanciare eccezioni <add> // o utilizzare `console.warn`, in quanto non funzionerebbe all'interno di <add> // `oneOfType`. <add> customProp: function(props, propName, componentName) { <add> if (!/matchme/.test(props[propName])) { <add> return new Error('Validazione fallita!'); <add> } <add> } <add> }, <add> /* ... */ <add>}); <add>``` <add> <add> <add>## Valori Predefiniti delle Proprietà <add> <add>React ti permette di definire valori predefiniti per le tue `props` in una maniera molto dichiarativa: <add> <add>```javascript <add>var ComponentWithDefaultProps = React.createClass({ <add> getDefaultProps: function() { <add> return { <add> value: 'valore predefinito' <add> }; <add> } <add> /* ... */ <add>}); <add>``` <add> <add>Il risultato di `getDefaultProps()` sarà conservato e usato per assicurarsi che `this.props.value` avrà sempre un valore se non è stato specificato dal componente proprietario. Ciò ti permette di utilizzare in sicurezza le tue proprietà senza dover scrivere codice fragile e ripetitivo per gestirlo da te. <add> <add> <add>## Trasferire le Proprietà: Una Scorciatoia <add> <add>Un tipo comune di componente React è uno che estende un elemento basico HTML in maniera semplice. Spesso vorrai copiare qualsiasi attributo HTML passato al tuo componente all'elemento HTML sottostante per risparmiare del codice. Puoi usare la sintassi _spread_ di JSX per ottenerlo: <add> <add>```javascript <add>var CheckLink = React.createClass({ <add> render: function() { <add> // Questo prende ciascuna proprietà passata a CheckLink e la copia su <a> <add> return <a {...this.props}>{'√ '}{this.props.children}</a>; <add> } <add>}); <add> <add>React.render( <add> <CheckLink href="/checked.html"> <add> Clicca qui! <add> </CheckLink>, <add> document.getElementById('example') <add>); <add>``` <add> <add>## Figlio Singolo <add> <add>Con `React.PropTypes.element` puoi specificare che solo un figlio unico possa essere passato come figli ad un componente. <add> <add>```javascript <add>var MyComponent = React.createClass({ <add> propTypes: { <add> children: React.PropTypes.element.isRequired <add> }, <add> <add> render: function() { <add> return ( <add> <div> <add> {this.props.children} // Questo deve essere esattamente un elemento oppure lancerà un'eccezione. <add> </div> <add> ); <add> } <add> <add>}); <add>``` <add> <add>## Mixin <add> <add>I componenti sono la maniera migliore di riutilizzare il codice in React, ma a volte componenti molto diversi possono condividere funzionalità comune. Questi sono a volte chiamate [responsabilità trasversali](https://en.wikipedia.org/wiki/Cross-cutting_concern). React fornisce i `mixin` per risolvere questo problema. <add> <add>Un caso d'uso comune è un componente che desidera aggiornarsi ad intervalli di tempo. È facile usare `setInterval()`, ma è anche importante cancellare la chiamata ripetuta quando non è più necessaria per liberare memoria. React fornisce dei [metodi del ciclo di vita](/react/docs/working-with-the-browser.html#component-lifecycle) che ti permettono di sapere quando un componente sta per essere creato o distrutto. Creiamo un semplice mixin che usa questi metodi per fornire una facile funzione `setInterval()` che sarà automaticamente rimossa quando il tuo componente viene distrutto. <add> <add>```javascript <add>var SetIntervalMixin = { <add> componentWillMount: function() { <add> this.intervals = []; <add> }, <add> setInterval: function() { <add> this.intervals.push(setInterval.apply(null, arguments)); <add> }, <add> componentWillUnmount: function() { <add> this.intervals.forEach(clearInterval); <add> } <add>}; <add> <add>var TickTock = React.createClass({ <add> mixins: [SetIntervalMixin], // Usa il mixin <add> getInitialState: function() { <add> return {seconds: 0}; <add> }, <add> componentDidMount: function() { <add> this.setInterval(this.tick, 1000); // Chiama un metodo del mixin <add> }, <add> tick: function() { <add> this.setState({seconds: this.state.seconds + 1}); <add> }, <add> render: function() { <add> return ( <add> <p> <add> React has been running for {this.state.seconds} seconds. <add> </p> <add> ); <add> } <add>}); <add> <add>React.render( <add> <TickTock />, <add> document.getElementById('example') <add>); <add>``` <add> <add>Una caratteristica interessante dei mixin è che, se un componente usa molteplici mixin e diversi mixin definiscono lo stesso metodo del ciclo di vita (cioè diversi mixin desiderano effettuare una pulizia quando il componente viene distrutto), viene garantito che tutti i metodi del ciclo di vita verranno chiamati. I metodi definiti nei mixin vengono eseguiti nell'ordine in cui i mixin sono elencati, seguiti da una chiamata al metodo definito nel componente. <add> <add>## Classi ES6 <add> <add>Puoi anche definire le tue classi React come pure classi JavaScript. Per esempio, usando la sintassi delle classi ES6: <add> <add>```javascript <add>class HelloMessage extends React.Component { <add> render() { <add> return <div>Ciao {this.props.name}</div>; <add> } <add>} <add>React.render(<HelloMessage name="Sebastian" />, mountNode); <add>``` <add> <add>L'API è simile a `React.createClass` con l'eccezione del metodo `getInitialState`. Anziché fornire un metodo `getInitialState` a parte, imposti la tua proprietà `state` nel costruttore. <add> <add>Un'altra differenza è che `propTypes` e `defaultProps` sono definite come proprietà del costruttore anziché nel corpo della classe. <add> <add>```javascript <add>export class Counter extends React.Component { <add> constructor(props) { <add> super(props); <add> this.state = {count: props.initialCount}; <add> } <add> tick() { <add> this.setState({count: this.state.count + 1}); <add> } <add> render() { <add> return ( <add> <div onClick={this.tick.bind(this)}> <add> Click: {this.state.count} <add> </div> <add> ); <add> } <add>} <add>Counter.propTypes = { initialCount: React.PropTypes.number }; <add>Counter.defaultProps = { initialCount: 0 }; <add>``` <add> <add>### Niente Binding Automatico <add> <add>I metodi seguono la stessa semantica delle classi ES6 regolari, ciò significa che non effettuano il binding automatico di `this` all'istanza. Dovrai pertanto usare esplicitamente `.bind(this)` oppure [le funzioni freccia](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) `=>`. <add> <add>### Niente Mixin <add> <add>Sfortunatamente, ES6 è stato lanciato senza alcun supporto per i mixin. Di conseguenza non vi è alcun supporto per i mixin quando usi React con le classi ES6. Stiamo lavorando per rendere più semplice il supporto dei relativi casi d'uso senza ricorrere ai mixin. <add> <add> <add> <add>## Funzioni Prive di Stato <add> <add>Puoi anche definire le tue classi React come semplici funzioni JavaScript. Ad esempio usando la sintassi della funzione priva di stato: <add> <add>```javascript <add>function HelloMessage(props) { <add> return <div>Ciao {props.name}</div>; <add>} <add>React.render(<HelloMessage name="Sebastian" />, mountNode); <add>``` <add> <add>Oppure usando la nuova sintassi freccia di ES6: <add> <add>```javascript <add>var HelloMessage = (props) => <div>Ciao {props.name}</div>; <add>React.render(<HelloMessage name="Sebastian" />, mountNode); <add>``` <add> <add> <add>Questa API semplificata dei componenti è intesa per i componenti che sono pure funzioni dele proprietà. Questi componenti non devono trattenere stato interno, non hanno istanze di supporto, e non posseggono metodi di ciclo di vita. Sono pure trasformate funzionali del loro input, con zero codice boilerplate. <add> <add>> NOTA: <add>> <add>> Poiché le funzioni prive di stato non hanno un'istanza di supporto, non puoi assegnare un ref a un componente creato con una funzione priva di stato. Normalmente questo non è un problema, poiché le funzioni prive di stato non forniscono un'API imperativa. Senza un'API imperativa, non puoi comunque fare molto con un'istanza. Tuttavia, se un utente desidera trovare il nodo DOM di un componente creato con una funzione priva di stato, occorre avvolgere il componente in un altro componente dotato di stato (ad es. un componente classe ES6) e assegnare il ref al componente dotato di stato. <add> <add>In un mondo ideale, la maggior parte dei tuoi componenti sarebbero funzioni prive di stato poiché questi componenti privi di stato seguono un percorso più rapido all'interno del core di React. Questo è un pattern raccomandato, quando possibile. <ide><path>docs/docs/06-transferring-props.it-IT.md <add>--- <add>id: transferring-props-it-IT <add>title: Trasferimento delle Proprietà <add>permalink: transferring-props-it-IT.html <add>prev: reusable-components-it-IT.html <add>next: forms-it-IT.html <add>--- <add> <add>Un pattern comune in React è l'uso di un'astrazione per esporre un componente. Il componente esterno espone una semplice proprietà per effettuare un'azione che può richiedere un'implementazione più complessa. <add> <add>Puoi usare gli [attributi spread di JSX](/react/docs/jsx-spread.html) per unire le vecchie props con valori aggiuntivi: <add> <add>```javascript <add><Component {...this.props} more="values" /> <add>``` <add> <add>Se non usi JSX, puoi usare qualsiasi helper come l'API `Object.assign` di ES6, o il metodo `_.extend` di Underscore: <add> <add>```javascript <add>React.createElement(Component, Object.assign({}, this.props, { more: 'values' })); <add>``` <add> <add>Nel resto di questo tutorial vengono illustrate le best practices, usando JSX e sintassi sperimentale di ES7. <add> <add>## Trasferimento Manuale <add> <add>Nella maggior parte dei casi dovresti esplicitamente passare le proprietà. Ciò assicura che venga esposto soltanto un sottoinsieme dell'API interna, del cui funzionamento si è certi. <add> <add>```javascript <add>var FancyCheckbox = React.createClass({ <add> render: function() { <add> var fancyClass = this.props.checked ? 'FancyChecked' : 'FancyUnchecked'; <add> return ( <add> <div className={fancyClass} onClick={this.props.onClick}> <add> {this.props.children} <add> </div> <add> ); <add> } <add>}); <add>React.render( <add> <FancyCheckbox checked={true} onClick={console.log.bind(console)}> <add> Ciao mondo! <add> </FancyCheckbox>, <add> document.getElementById('example') <add>); <add>``` <add> <add>E se aggiungessimo una proprietà `name`? O una proprietà `title`? O `onMouseOver`? <add> <add>## Trasferire con `...` in JSX <add> <add>> NOTA: <add>> <add>> La sintassi `...` fa parte della proposta Object Rest Spread. Questa proposta è in processo di diventare uno standard. Consulta la sezione [Proprietà Rest e Spread ...](/react/docs/transferring-props.html#rest-and-spread-properties-...) di seguito per maggiori dettagli. <add> <add>A volte passare manualmente ciascuna proprietà può essere noioso e fragile. In quei casi puoi usare l'[assegnamento destrutturante](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) con le proprietà residue per estrarre un insieme di proprietà sconosciute. <add> <add>Elenca tutte le proprietà che desideri consumare, seguite da `...other`. <add> <add>```javascript <add>var { checked, ...other } = this.props; <add>``` <add> <add>Ciò assicura che vengano passate tutte le proprietà TRANNE quelle che stai consumando tu stesso. <add> <add>```javascript <add>var FancyCheckbox = React.createClass({ <add> render: function() { <add> var { checked, ...other } = this.props; <add> var fancyClass = checked ? 'FancyChecked' : 'FancyUnchecked'; <add> // `other` contiene { onClick: console.log } ma non la proprietà checked <add> return ( <add> <div {...other} className={fancyClass} /> <add> ); <add> } <add>}); <add>React.render( <add> <FancyCheckbox checked={true} onClick={console.log.bind(console)}> <add> Ciao mondo! <add> </FancyCheckbox>, <add> document.getElementById('example') <add>); <add>``` <add> <add>> NOTA: <add>> <add>> Nell'esempio precedente, la proprietà `checked` è anche un attributo DOM valido. Se non utilizzassi la destrutturazione in questo modo, potresti inavvertitamente assegnarlo al `div`. <add> <add>Usa sempre il pattern di destrutturazione quando trasferisci altre proprietà sconosciute in `other`. <add> <add>```javascript <add>var FancyCheckbox = React.createClass({ <add> render: function() { <add> var fancyClass = this.props.checked ? 'FancyChecked' : 'FancyUnchecked'; <add> // ANTI-PATTERN: `checked` sarebbe passato al componente interno <add> return ( <add> <div {...this.props} className={fancyClass} /> <add> ); <add> } <add>}); <add>``` <add> <add>## Consumare e Trasferire la Stessa Proprietà <add> <add>Se il tuo componente desidera consumare una proprietà, ma anche passarla ad altri, puoi passarla esplicitamente mediante `checked={checked}`. Questo è preferibile a passare l'intero oggetto `this.props` dal momento che è più facile effettuarne il linting e il refactoring. <add> <add>```javascript <add>var FancyCheckbox = React.createClass({ <add> render: function() { <add> var { checked, title, ...other } = this.props; <add> var fancyClass = checked ? 'FancyChecked' : 'FancyUnchecked'; <add> var fancyTitle = checked ? 'X ' + title : 'O ' + title; <add> return ( <add> <label> <add> <input {...other} <add> checked={checked} <add> className={fancyClass} <add> type="checkbox" <add> /> <add> {fancyTitle} <add> </label> <add> ); <add> } <add>}); <add>``` <add> <add>> NOTA: <add>> <add>> L'ordine è importante. Mettendo il `{...other}` prima delle tue proprietà JSX ti assicuri che il consumatore del tuo componente non possa ridefinirle. Nell'esempio precedente, abbiamo garantito che l'elemento input sarà del tipo `"checkbox"`. <add> <add>## Proprietà Rest e Spread `...` <add> <add>Le proprietà Rest ti permettono di estrarre le proprietà residue di un oggetto in un nuovo oggetto. Vengono escluse tutte le altre proprietà elencate nel pattern di destrutturazione. <add> <add>Questa è un'implementazione sperimentale di una [proposta ES7](https://github.com/sebmarkbage/ecmascript-rest-spread). <add> <add>```javascript <add>var { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 }; <add>x; // 1 <add>y; // 2 <add>z; // { a: 3, b: 4 } <add>``` <add> <add>> Nota: <add>> <add>> Questa proposta ha raggiunto lo stadio 2 ed è attivata in modo predefinito in Babel. Vecchie versioni di Babel potrebbero richiedere l'abilitazione esplicita di questa trasformazione con `babel --optional es7.objectRestSpread` <add> <add>## Trasferire con Underscore <add> <add>Se non usi JSX, puoi usare una libreria per ottenere il medesimo pattern. Underscore supporta `_.omit` per omettere delle proprietà ed `_.extend` per copiare le proprietà in un nuovo oggetto. <add> <add>```javascript <add>var FancyCheckbox = React.createClass({ <add> render: function() { <add> var checked = this.props.checked; <add> var other = _.omit(this.props, 'checked'); <add> var fancyClass = checked ? 'FancyChecked' : 'FancyUnchecked'; <add> return ( <add> React.DOM.div(_.extend({}, other, { className: fancyClass })) <add> ); <add> } <add>}); <add>``` <ide><path>docs/docs/07-forms.it-IT.md <add>--- <add>id: forms-it-IT <add>title: Moduli <add>permalink: forms-it-IT.html <add>prev: transferring-props-it-IT.html <add>next: working-with-the-browser-it-IT.html <add>--- <add> <add>I componenti dei moduli come `<input>`, `<textarea>` e `<option>` differiscono dagli altri componenti nativi poiché possono essere alterati tramite interazione dell'utente. Questi componenti forniscono interfacce che rendono più semplice gestire i moduli in risposta all'interazione dell'utente. <add> <add>Per maggiori informazioni sugli eventi dell'elemento `<form>` consulta [Eventi dei Moduli](/react/docs/events.html#form-events). <add> <add>## Proprietà Interattive <add> <add>I componenti dei moduli supportano un numero di proprietà che vengono modificate dall'interazione dell'utente: <add> <add>* `value`, supportato dai elementi `<input>` e `<textarea>`. <add>* `checked`, supportato dagli elementi `<input>` dal tipo `checkbox` o `radio`. <add>* `selected`, supportato dagli elementi `<option>`. <add> <add>In HTML, in valore di `<textarea>` è impostato tramite un nodo di testo figlio. In React, devi invece usare la proprietà `value`. <add> <add>I componenti dei moduli ti permettono di reagire ai cambiamenti impostando una callback come proprietà `onChange`. La proprietà `onChange` funziona in tutti i browser e viene scatenata in risposta all'interazione dell'utente quando: <add> <add>* Il `value` di `<input>` o `<textarea>` cambia. <add>* Lo stato `checked` di `<input>` cambia. <add>* Lo stato `selected` di `<option>` cambia. <add> <add>Come tutti gli eventi DOM, la proprietà `onChange` è supportata su tutti i componenti nativi e può essere usata per gestire la propagazione di eventi di cambiamento. <add> <add>> Nota: <add>> <add>> Per `<input>` e `<textarea>`, `onChange` rimpiazza — e dovrebbe generalmente essere utilizzata in sostituzione — il gestore di eventi [`oninput`](https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/oninput) nativo del DOM. <add> <add> <add>## Componenti Controllati <add> <add>Un `<input>` il cui `value` è impostato è un componente *controllato*. In un `<input>` controllato, il valore dell'elemento visualizzato si riflette sempre nella sua proprietà `value`. Ad esempio: <add> <add>```javascript <add> render: function() { <add> return <input type="text" value="Ciao!" />; <add> } <add>``` <add> <add>Ciò visualizzerà un input che ha sempre il valore di `value` impostato a `Ciao!`. Ciascuna immissione dell'utente non avrà effetto sull'elemento visualizzato poiché React ha dichiarato il suo `value` pari a `Ciao!`. Se volessi aggiornare il `value` in risposta all'input dell'utente, puoi usare l'evento `onChange`: <add> <add>```javascript <add> getInitialState: function() { <add> return {value: 'Ciao!'}; <add> }, <add> handleChange: function(event) { <add> this.setState({value: event.target.value}); <add> }, <add> render: function() { <add> var value = this.state.value; <add> return <input type="text" value={value} onChange={this.handleChange} />; <add> } <add>``` <add> <add>In questo esempio, stiamo semplicemente accettando il valore più recente fornito dall'utente e aggiornando la proprietà `value` del componente `<input>`. Questo pattern semplifica l'implementazione di interfacce che rispondono o validano l'interazione dell'utente. Ad esempio: <add> <add>```javascript <add> handleChange: function(event) { <add> this.setState({value: event.target.value.substr(0, 140)}); <add> } <add>``` <add> <add>Così si può accettare l'input dell'utente ma ne tronca il valore ai primi 140 caratteri. <add> <add>### Potenziali Problemi con Checkbox e Radio Button <add> <add>Fai attenzione che, allo scopo di normalizzare la gestione del cambiamento degli elementi checkbox e radio button, React usa un evento `click` al posto di un evento `change`. Nella maggior parte dei casi questo funziona nel modo previsto, tranne quando viene usato `preventDefault` in un gestore dell'evento `change`. `preventDefault` impedisce al browser di aggiornare visualmente l'input, anche se `checked` cambia il suo valore. Questo può essere evitato rimuovendo la chiamata a `preventDefault`, oppure effettuando il cambio del valore di `checked` tramite `setTimeout`. <add> <add> <add>## Componenti Non Controllati <add> <add>Un `<input>` che non fornisce un `value` (o lo imposta a `null`) è un componente *non controllato*. In un `<input>` non controllato, il valore dell'elemento visualizzato rifletterà l'input dell'utente. Ad esempio: <add> <add>```javascript <add> render: function() { <add> return <input type="text" />; <add> } <add>``` <add> <add>Questo visualizzerà un campo di input il cui valore iniziale è vuoto. Ciascun input dell'utente si rifletterà immediatamente nell'elemento visualizzato. Se desideri reagire ai cambiamenti del valore, puoi usare il gestore di eventi `onChange` proprio come con i componenti controllati. <add> <add>### Valore Predefinito <add> <add>Se desideri inizializzare il componente con un valore non vuoto, puoi fornire una proprietà `defaultValue`. Ad esempio: <add> <add>```javascript <add> render: function() { <add> return <input type="text" defaultValue="Ciao!" />; <add> } <add>``` <add> <add>Questo esempio funzionerà in maniera simile all'esempio precedente sui **Componenti Controllati**. <add> <add>Similmente, `<input>` supporta `defaultChecked` e `<select>` supporta `defaultValue`. <add> <add>> Nota: <add>> <add>> Le proprietà `defaultValue` e `defaultChecked` sono usate soltanto durante il rendering iniziale. Se devi aggiornare il valore in un rendering successivo, dovrai usare un [componente controllato](#controlled-components). <add> <add> <add>## Argomenti Avanzati <add> <add> <add>### Perché Componenti Controllati? <add> <add>Usare componenti di moduli come `<input>` in React presenta una difficoltà aggiuntiva, assente quando si scrive un modulo tradizionale in HTML. Ad esempio, in HTML: <add> <add>```html <add> <input type="text" name="title" value="Senza titolo" /> <add>``` <add> <add>Questo visualizza un campo di input *inizializzato* con il valore `Senza titolo`. Quando l'utente modifica il campo, la *proprietà* `value` del nodo cambierà. Tuttavia, `node.getAttribute('value')` restituirà ancora il valore usato durante l'inizializzazione, `Senza titolo`. <add> <add>Diversamente dall'HTML, i componenti React devono rappresentare lo stato della vista in ciascun momento e non soltanto durante l'inizializzazione. Ad esempio, in React: <add> <add>```javascript <add> render: function() { <add> return <input type="text" name="title" value="Senza titolo" />; <add> } <add>``` <add> <add>Dal momento che questo metodo descrive la vista in ogni momento, il valore del campo di testo deve *sempre* essere `Senza titolo`. <add> <add> <add>### Perché il Valore della Textarea? <add> <add>In HTML, il valore di `<textarea>` è solitamente impostato usando un nodo di testo figlio: <add> <add>```html <add> <!-- antipattern: NON FARLO! --> <add> <textarea name="description">Questa è la descrizione.</textarea> <add>``` <add> <add>Per l'HTML, questo approccio permette agli sviluppatori di fornire facilmente valori su più righe. Tuttavia, dal momento che React è JavaScript, non abbiamo limitazioni sulle stringhe e possiamo usare `\n` se desideriamo andare a capo. In un mondo in cui abbiamo `value` e `defaultValue`, il ruolo giocato dal nodo figlio è ambiguo. Per questa ragione, non dovresti utilizzare il nodo figlio quando imposti il valore delle `<textarea>`: <add> <add>```javascript <add> <textarea name="description" value="Questa è la descrizione." /> <add>``` <add> <add>Se tuttavia decidi di *usare* il nodo di testo figlio, questo si comporterà come `defaultValue`. <add> <add> <add>### Perché il Value di Select? <add> <add>L'elemento `<option>` selezionato in un elemento HTML `<select>` è normalmente specificato attraverso l'attributo `selected` dell'opzione stessa. In React, allo scopo di rendere i componenti più semplici da manipolare, viene invece adottato il formato seguente: <add> <add>```javascript <add> <select value="B"> <add> <option value="A">Arancia</option> <add> <option value="B">Banana</option> <add> <option value="C">Ciliegia</option> <add> </select> <add>``` <add> <add>Per creare un componente non controllato, viene invece usato `defaultValue`. <add> <add>> Nota: <add>> <add>> Puoi passare un array come valore dell'attributo `value`, se desideri selezionare più opzioni in un tag `select` a scelta multipla: `<select multiple={true} value={['B', 'C']}>`. <ide><path>docs/docs/08-working-with-the-browser.it-IT.md <add>--- <add>id: working-with-the-browser-it-IT <add>title: Lavorare con il Browser <add>permalink: working-with-the-browser-it-IT.html <add>prev: forms-it-IT.html <add>next: more-about-refs-it-IT.html <add>--- <add> <add>React offre potenti astrazioni che ti liberano in molti casi dal compito di manipolare direttamente il DOM, ma a volte potresti avere bisogno di accedere alle API sottostanti, ad esempio per lavorare con una libreria di terze parti o altro codice preesistente. <add> <add> <add>## Il DOM Virtuale <add> <add>React è così veloce perché non interagisce direttamente con il DOM. React gestisce una rappresentazione veloce del DOM in memoria. I metodi `render()` restituiscono una *descrizione* del DOM, e React può confrontare questa descrizione con la rappresentazione in memoria per calcolare la maniera più veloce di aggiornare il browser. <add> <add>In aggiunta, React implementa un intero sistema di eventi sintetici che fa in modo che tutti gli oggetti evento siano conformi alle specifiche W3C nonostante le incompatibilità dei browser, e ciascun evento si propaga in maniera consistente ed efficiente in ogni browser. Puoi anche utilizzare alcuni eventi HTML5 in IE8! <add> <add>Nella maggior parte dei casi è sufficiente rimanere nel mondo del "browser fittizio" di React poiché più efficiente e facile da concepire. Tuttavia, a volte potresti aver bisogno di accedere alle API sottostanti, ad esempio per lavorare con una libreria di terze parti come un plugin jQuery. React fornisce convenienti vie di fuga perché tu possa utilizzare direttamente le API DOM sottostanti. <add> <add> <add>## I Ref e findDOMNode() <add> <add>Per interagire con il browser, avrai bisogno di un riferimento a un nodo DOM. Puoi assegnare un attributo `ref` a ciascun elemento, ciò ti permette di fare riferimento all'**istanza di supporto** del componente. Questo è utile se devi invocare funzioni imperative sul componente, oppure desideri accedere ai nodi DOM sottostanti. Per saperne di piu sui ref, incluso la maniera di usarli con efficacia, leggi la nostra documentazione [riferimenti a componenti](/react/docs/more-about-refs-it-IT.html). <add> <add> <add>## Ciclo di Vita del Componente <add> <add>I componenti hanno tree fasi principali del ciclo di vita: <add> <add>* **Montaggio:** Un componente sta venendo inserito nel DOM. <add>* **Aggiornamento:** Viene effettuato nuovamente il rendering del componente per determinare se il DOM vada aggiornato. <add>* **Smontaggio:** Un componente sta venendo rimosso dal DOM. <add> <add>React offre metodi del ciclo di vita che puoi specificare per inserirti in questo processo. Offriamo dei metodi il cui nome inizia per **will**, chiamati immediatamente prima che qualcosa accada, o per **did** che sono chiamati immediatamente dopo che qualcosa è accaduto. <add> <add> <add>### Montaggio <add> <add>* `getInitialState(): object` è invocato prima che un componente viene montato. Componenti dotati di stato dovrebbero implementare questo metodo e restituire lo stato iniziale. <add>* `componentWillMount()` è invocato immediatamente prima che si effettui il montaggio. <add>* `componentDidMount()` è invocato immediatamente dopo che il montaggio è avvenuto. L'inizializzazione che richiede l'esistenza di nodi DOM dovrebbe avvenire in questo metodo. <add> <add> <add>### Aggiornamento <add> <add>* `componentWillReceiveProps(object nextProps)` è invocato quando un componente montato riceve nuove proprietà. Questo metodo dovrebbe essere utilizzato per confrontare `this.props` e `nextProps` per effettuare transizioni di stato utilizzando `this.setState()`. <add>* `shouldComponentUpdate(object nextProps, object nextState): boolean` è invocato quando un componente decide se i cambiamenti debbano risultare in un aggiornamento del DOM. Implementa questo metodo come un'ottimizzazione per confrontare `this.props` con `nextProps` e `this.state` con `nextState`, e restituisci `false` se React debba rimandare l'aggiornamento. <add>* `componentWillUpdate(object nextProps, object nextState)` è invocato immediatamente prima che l'aggiornamento avvenga. Non puoi chiamare `this.setState()` al suo interno. <add>* `componentDidUpdate(object prevProps, object prevState)` è invocato immediatamente dopo che l'aggiornamento è avvenuto. <add> <add> <add>### Smontaggio <add> <add>* `componentWillUnmount()` è invocato immediatamente prima che un componente venga smontato e distrutto. Puoi effettuare operazioni di pulizia al suo interno. <add> <add> <add>### Metodi Montati <add> <add>Componenti compositi _montati_ supportano anche i seguenti metodi: <add> <add>* `findDOMNode(): DOMElement` può essere invocato su ciascun componente montato per ottenere un riferimento al suo nodo DOM. <add>* `forceUpdate()` può essere invocato su ciascun componente montato quando si è certi che un aspetto interno del componente è cambiato senza usare `this.setState()`. <add> <add> <add>## Supporto per i Browser e Polyfill <add> <add>A Facebook supportiamo vecchi browser, incluso IE8. Abbiamo impiegato per un lungo tempo i polyfill per consentirci di scrivere JS con un occhio al futuro. Ciò significa che non abbiamo una quantità di hack sparsi nel nostro codice e possiamo tuttavia aspettarci che il nostro codice "semplicemente funzioni". Ad esempio, anziché usare `+new Date()`, possiamo scrivere `Date.now()`. Dal momento che la versione open source di React è la stessa che usiamo internamente, vi abbiamo applicato la stessa filosofia di scrivere JS guardando avanti. <add> <add>In aggiunta a questa filosofia, abbiamo anche deciso, in qualità di autori di una libreria JS, non dovremmo fornire i polyfill assieme alla nostra libreria. Se ciascuna libreria facesse ciò, con buona probabilità invieresti lo stesso polyfill diverse volte, cosa che potrebbe risultare in una rilevante quantità di codice inutilizzato. Se il tuo prodotto deve supportare vecchi browser, con buona probabilità stai già usando qualcosa come [es5-shim](https://github.com/es-shims/es5-shim). <add> <add> <add>### Polyfill Richiesti per Supportare Vecchi Browser <add> <add>`es5-shim.js` tratto da [es5-shim di kriskowal](https://github.com/es-shims/es5-shim) fornisce le seguenti API indispensabili a React: <add> <add>* `Array.isArray` <add>* `Array.prototype.every` <add>* `Array.prototype.forEach` <add>* `Array.prototype.indexOf` <add>* `Array.prototype.map` <add>* `Date.now` <add>* `Function.prototype.bind` <add>* `Object.keys` <add>* `String.prototype.split` <add>* `String.prototype.trim` <add> <add>`es5-sham.js`, anch'esso tratto da [es5-shim di kriskowal](https://github.com/es-shims/es5-shim), provides the following that React needs: <add> <add>* `Object.create` <add>* `Object.freeze` <add> <add>La build non minificata di React richiede le seguenti API tratte da [console-polyfill di paulmillr](https://github.com/paulmillr/console-polyfill). <add> <add>* `console.*` <add> <add>Quando si usano elementi HTML5 in IE8 incluso `<section>`, `<article>`, `<nav>`, `<header>` e `<footer>`, è inoltre necessario includere [html5shiv](https://github.com/aFarkas/html5shiv) o uno script equivalente. <add> <add> <add>### Problemi Cross-browser <add> <add>Nonostante React sia molto buono ad astrarre le differenze tra browser, alcuni browser sono limitati o presentano comportamenti scorretti per i quali non abbiamo potuto trovare un rimedio. <add> <add> <add>#### Evento onScroll su IE8 <add> <add>Su IE8 l'evento `onScroll` non viene propagato, e IE8 non possiede una API per definire gestori di eventi nella fase di cattura dell'evento, con il risultato che React non ha alcun modo di reagire a questi eventi. <add>Al momento i gestori di questo evento vengono ignorati su IE8. <add> <add>Leggi la issue [onScroll doesn't work in IE8](https://github.com/facebook/react/issues/631) su GitHub per maggiori informazioni. <ide><path>docs/docs/08.1-more-about-refs.it-IT.md <add>--- <add>id: more-about-refs-it-IT <add>title: Riferimenti ai Componenti <add>permalink: more-about-refs-it-IT.html <add>prev: working-with-the-browser-it-IT.html <add>next: tooling-integration-it-IT.html <add>--- <add>Dopo aver costruito il tuo componente, potresti trovarti nella situazione di volere invocare dei metodi sulle istanze di componenti restituite da `render()`. Nella maggior parte dei casi, questo non è necessario poiché il flusso di dati reattivo assicura sempre che le proprietà più recenti siano assegnate a ciascun figlio prodotto da `render()`. Tuttavia, esistono dei casi in cui potrebbe essere necessario o desiderabile, quindi React fornisce una via d'uscita conosciuta come `refs`. Queste `refs` (riferimenti) sono particolarmente utili quando vuoi: trovare il markup DOM prodotto da un componente (ad esempio, per posizionarlo in modo assoluto), usare componenti React in una più ampia applicazione non-React, oppure effettuare la transizione del tuo codice a React. <add> <add>Vediamo come ottenere un ref, e quindi passiamo ad un esempio completo. <add> <add>## Il ref restituito da React.render <add> <add>Da non confondersi con il metodo `render()` che definisci sul tuo componente (il quale restituisce un elemento DOM virtuale), [React.render()](/react/docs/top-level-api-it-IT.html#react.render) restituisce un riferimento all'**istanza di supporto** del tuo componente (o `null` per i [componenti privi di stato](/react/docs/reusable-components.html#stateless-functions)). <add> <add> <add>```js <add>var myComponent = React.render(<MyComponent />, myContainer); <add>``` <add> <add>Tieni a mente, tuttavia, che JSX non restituisce un'istanza di un componente! È solo un **ReactElement**: una rappresentazione leggera che istruisce React su come il componente montato debba apparire. <add> <add>```js <add>var myComponentElement = <MyComponent />; // Questo è un semplice ReactElement. <add> <add>// Qui va del codice... <add> <add>var myComponentInstance = React.render(myComponentElement, myContainer); <add>myComponentInstance.doSomething(); <add>``` <add> <add>> Nota: <add>> <add>> Questo deve essere usato soltanto al livello più alto. All'interno dei componenti, lascia che i tuoi `props` e `state` gestiscano la comunicazione con i componenti figli, oppure utilizza uno degli altri metodi per ottenere un ref (attributo stringa o callback). <add> <add> <add>## L'Attributo ref Come Callback <add> <add>React supporta un attributo speciale che puoi assegnare a qualsiasi componente. L'attributo `ref` può essere una funzione callback, che sarà eseguita immediatamente dopo che il componente viene montato. Il componente referenziato sarà passato come parametro, e la funzione callback può utilizzare il componente immediatamente, oppure conservarne un riferimento per un uso successivo, o entrambe. <add> <add>È semplice come aggiungere un attributo `ref` a qualsiasi cosa restituita da `render` usando una funzione freccia di ES6: <add> <add>```js <add> render: function() { <add> return ( <add> <TextInput <add> ref={function(input) { <add> if (input != null) { <add> input.focus(); <add> } <add> }} /> <add> ); <add> }, <add>``` <add> <add>oppure usando una funzione freccia ES6: <add> <add>```js <add> render: function() { <add> return <TextInput ref={(c) => this._input = c} />; <add> }, <add> componentDidMount: function() { <add> this._input.focus(); <add> }, <add>``` <add> <add>Nota che quando il componente referenziato viene smontato e quando il valore di ref cambia, ref sarà chiamata con `null` come argomento. Ciò impedisce i memory leak nel caso in cui l'istanza venga conservata, come nel primo esempio. Nota che quando assegni il valore di ref a un'espressione di funzione in linea come negli esempi precedenti, React vede un oggetto funzione diverso ogni volta e pertanto in occasione di ciascun aggiornamento, ref verrà chiamata con `null` immediatamente prima di essere chiamata con l'istanza del componente. <add> <add>Puoi accedere al nodo DOM del componente direttamente chiamando `React.findDOMNode(argomentoDellaTuaCallback)`. <add> <add> <add>## L'Attributo ref Come Stringa <add> <add>React supporta anche l'uso di una stringa (anziché una callback) come proprietà ref su qualsiasi componente, sebbene allo stato attuale questo approccio sia quasi esclusivamente superato. <add> <add>1. Assegna un attributo `ref` a qualsiasi cosa restituita da `render` come: <add> <add> ```html <add> <input ref="myInput" /> <add> ``` <add> <add>2. Altrove nel codice (tipicamente in un gestore di eventi), accedi all'**istanza di supporto** tramite `this.refs` come segue: <add> <add> ```javascript <add> this.refs.myInput <add> ``` <add> <add> Puoi accedere direttamente al nodo DOM del componente chiamando `React.findDOMNode(this.refs.myInput)`. <add> <add> <add>## Un Esempio Completo <add>Per ottenere un riferimento a un componente React, puoi usare `this` per ottenere il componente React attuale, oppure usare un ref per ottenere un riferimento a un componente di tua proprietà. Il funzionamento è il seguente: <add> <add>```javascript <add>var MyComponent = React.createClass({ <add> handleClick: function() { <add> // Assegna il focus esplicitamente al campo di testo usando l'API DOM nativa. <add> this.myTextInput.focus(); <add> }, <add> render: function() { <add> // L'attributo ref aggiunge un riferimento al componente a this.refs quando <add> // il componente viene montato <add> return ( <add> <div> <add> <input type="text" ref={(ref) => this.myTextInput = ref} /> <add> <input <add> type="button" <add> value="Assegna il focus al campo di testo" <add> onClick={this.handleClick} <add> /> <add> </div> <add> ); <add> } <add>}); <add> <add>React.render( <add> <MyComponent />, <add> document.getElementById('example') <add>); <add>``` <add> <add>In questo esempio, otteniamo un riferimento all'**istanza di supporto** del campo di testo e vi invochiamo il metodo `focus()` quando il bottone viene cliccato. <add> <add>Per componenti compositi, il riferimento si riferisce a un'istanza della classe del componente, quindi puoi invocare ogni metodo definito in tale classe. Se devi accedere al nodo DOM sottostante per il componente, puoi usare [React.findDOMNode](/react/docs/top-level-api-it-IT.html#react.finddomnode). <add> <add>## Riassunto <add> <add>I riferimenti `ref` sono la maniera corretta di inviare un messaggio a una precisa istanza di un figlio in una maniera che sarebbe impraticabile attraverso le normali proprietà `props` e `state` di React. Tuttavia, esse non dovrebbero essere la tua astrazione principale per far fluire i dati attraverso la tua applicazione. In modo predefinito, usa il flusso dati di React e utilizza i `ref` per casi d'uso che sono intrinsecamente non reattivi. <add> <add>### Benefici: <add> <add>- Puoi definire ogni metodo pubblico nelle classi dei tuoi componenti (come un metodo per reimpostare un Typeahead) e chiamare tali metodi pubblici attraverso i riferimenti (come ad esempio `this.refs.myTypeahead.reset()`). <add>- Effettuare misure sul DOM richiede quasi sempre l'accesso ad un componente "nativo" come `<input />` accedendo il suo nodo DOM sottostante attraverso `React.findDOMNode(this.refs.myInput)`. I riferimenti sono uno degli unici metodi praticabili per fare ciò in maniera affidabile. <add>- I riferimenti sono gestiti automaticamente per te! Se un figlio è distrutto, anche il suo riferimento è distrutto. Pertanto non preoccuparti del consumo di memoria (a meno che tu non faccia qualcosa di folle per conservare un riferimento). <add> <add>### Precauzioni: <add> <add>- *Non accedere mai* ai riferimenti dentro il metodo render di un componente - oppure mentre il metodo render di qualsiasi componente è in esecuzione ovunque nella pila di chiamate. <add>- Se vuoi preservare la resilienza al Crushing del compilatore Google Closure Compiler, assicurati di non accedere mai come proprietà a ciò che è stato specificato come stringa. Ciò significa che devi accedere come `this.refs['myRefString']` se il tuo ref è stato definito come `ref="myRefString"`. <add>- Se non hai ancora programmato parecchie applicazioni con React, la tua prima inclinazione è solitamente di provare a utilizzare i riferimenti per "fare succedere qualcosa" nella tua applicazione. Se questo è il tuo caso, fermati un momento e pensa in maniera critica al luogo corretto nella gerarchia dei componenti in cui lo `state` debba trovarsi. Spesso ti accorgerai che il luogo corretto per "possedere" lo stato si trova a un livello più alto nella gerarchia. Posizionare lì lo stato spesso elimina ogni necessità di usare i `ref` per "fare accadere qualcosa" – al contrario, il flusso dei dati solitamente otterrà lo scopo desiderato. <add>- I ref non possono essere assegnati a [funzioni prive di stato](/react/docs/reusable-components-it-IT.html#stateless-functions), poiché il componente non possiede un'istanza di supporto. Puoi tuttavia racchiudere un componente privo di stato in un componente composito standard e assegnare il ref al componente composito. <ide><path>docs/docs/09-tooling-integration.it-IT.md <add>--- <add>id: tooling-integration-it-IT <add>title: Integrazione con Strumenti <add>permalink: tooling-integration-it-IT.html <add>prev: more-about-refs-it-IT.html <add>next: addons-it-IT.html <add>--- <add> <add>Ciascun progetto utilizza un sistema differente per la build e il deploy di JavaScript. Abbiamo provato a rendere React il più possibile indipendente dall'ambiente di sviluppo. <add> <add>## React <add> <add>### React hosted su un CDN <add> <add>Offriamo versioni di React su CDN [nella nostra pagina dei download](/react/downloads.html). Questi file precompilati usano il formato dei moduli UMD. Inserirli con un semplice tag `<script>` inietterà una variabile globale `React` nel tuo ambiente. Questo approccio dovrebbe funzionare senza alcuna configurazione in ambienti CommonJS ed AMD. <add> <add> <add>### Usare il ramo master <add> <add>Abbiamo istruzioni per compilare dal ramo `master` [nel nostro repositorio GitHub](https://github.com/facebook/react). Costruiamo un albero di moduli CommonJS sotto `build/modules` che puoi inserire in ogni ambiente o strumento di packaging che supporta CommonJS. <add> <add>## JSX <add> <add>### Trasformazione di JSX nel browser <add> <add>Se preferisci usare JSX, Babel fornisce un [trasformatore ES6 e JSX nel browser per lo sviluppo](http://babeljs.io/docs/usage/browser/) chiamato browser.js che può essere incluso da una release npm `babel-core` oppure da [CDNJS](http://cdnjs.com/libraries/babel-core). Includi un tag `<script type="text/babel">` per scatenare il trasformatore JSX. <add> <add>> Nota: <add>> <add>> Il trasformatore JSX nel browser è piuttosto grande e risulta in calcoli aggiuntivi lato client che possono essere evitati. Non utilizzare in produzione — vedi la sezione successiva. <add> <add> <add>### In Produzione: JSX Precompilato <add> <add>Se hai [npm](https://www.npmjs.com/), puoi eseguire `npm install -g babel`. Babel include il supporto per React v0.12 e v0.13. I tag sono automaticamente trasformati negli equivalenti `React.createElement(...)`, `displayName` è automaticamente desunto e aggiunto a tutte le classi React.createClass. <add> <add>Questo strumento tradurrà i file che usano la sintassi JSX a file in semplice JavaScript che possono essere eseguiti direttamente dal browser. Inoltre, osserverà le directory per te e trasformerà automaticamente i file quando vengono modificati; ad esempio: `babel --watch src/ --out-dir lib/`. <add> <add>In maniera predefinita, vengono trasformati i file JSX con un'estensione `.js`. Esegui `babel --help` per maggiori informazioni su come usare Babel. <add> <add>Output di esempio: <add> <add>``` <add>$ cat test.jsx <add>var HelloMessage = React.createClass({ <add> render: function() { <add> return <div>Ciao {this.props.name}</div>; <add> } <add>}); <add> <add>React.render(<HelloMessage name="John" />, mountNode); <add>$ babel test.jsx <add>"use strict"; <add> <add>var HelloMessage = React.createClass({ <add> displayName: "HelloMessage", <add> <add> render: function render() { <add> return React.createElement( <add> "div", <add> null, <add> "Hello ", <add> this.props.name <add> ); <add> } <add>}); <add> <add>React.render(React.createElement(HelloMessage, { name: "John" }), mountNode); <add>``` <add> <add> <add>### Progetti Open Source Utili <add> <add>La comunità open source ha creato strumenti che integrano JSX con diversi editor e sistemi di build. Consulta [integrazioni JSX ](https://github.com/facebook/react/wiki/Complementary-Tools#jsx-integrations) per una lista completa. <ide><path>docs/docs/10-addons.it-IT.md <add>--- <add>id: addons-it-IT <add>title: Add-ons <add>permalink: addons-it-IT.html <add>prev: tooling-integration-it-IT.html <add>next: animation-it-IT.html <add>--- <add> <add>`React.addons` è il luogo in cui parcheggiamo utili strumenti per costruire applicazioni React. **Questi strumenti devono essere considerati sperimentali** ma saranno eventualmente inclusi nel nucleo o una libreria ufficiale di utilities: <add> <add>- [`TransitionGroup` e `CSSTransitionGroup`](animation-it-IT.html), per gestire animazioni e transizioni che sono solitamente difficili da implementare, come ad esempio prima della rimozione di un componente. <add>- [`LinkedStateMixin`](two-way-binding-helpers-it-IT.html), per semplificare la coordinazione tra lo stato del componente e l'input dell'utente in un modulo. <add>- [`cloneWithProps`](clone-with-props-it-IT.html), per eseguire una copia superficiale di componenti React e cambiare le loro proprietà. <add>- [`createFragment`](create-fragment-it-IT.html), per creare un insieme di figli con chiavi esterne. <add>- [`update`](update-it-IT.html), una funzione di utilità che semplifica la gestione di dati immutabili in JavaScript. <add>- [`PureRenderMixin`](pure-render-mixin-it-IT.html), un aiuto per incrementare le prestazioni in certe situazioni. <add> <add>Gli add-ons elencati di seguito si trovano esclusivamente nella versione di sviluppo (non minificata) di React: <add> <add>- [`TestUtils`](test-utils-it-IT.html), semplici helper per scrivere dei test case (soltanto nella build non minificata). <add>- [`Perf`](perf-it-IT.html), per misurare le prestazioni e fornirti suggerimenti per l'ottimizzazione. <add> <add>Per ottenere gli add-on, usa `react-with-addons.js` (e la sua controparte non minificata) anziché il solito `react.js`. <add> <add>Quandi si usa il pacchetto react di npm, richiedi semplicemente `require('react/addons')` anziché `require('react')` per ottenere React con tutti gli add-on. <ide><path>docs/docs/10.1-animation.it-IT.md <add>--- <add>id: animation-it-IT <add>title: Animazioni <add>permalink: animation-it-IT.html <add>prev: addons-it-IT.html <add>next: two-way-binding-helpers-it-IT.html <add>--- <add> <add>React offre un componente addon `ReactTransitionGroup` come una API di basso livello per le animazioni, e un `ReactCSSTransitionGroup` per implementare facilmente animazioni e transizioni CSS di base. <add> <add>## API di Alto Livello: `ReactCSSTransitionGroup` <add> <add>`ReactCSSTransitionGroup` è basato su `ReactTransitionGroup` ed è una maniera semplice di effettuare transizioni e animazioni CSS quando un componente React viene aggiunto o rimosso dal DOM. È ispirato all'eccellente libreria [ng-animate](http://www.nganimate.org/). <add> <add>### Per Cominciare <add> <add>`ReactCSSTransitionGroup` è l'interfaccia a `ReactTransitions`. Questo è un semplice elemento che racchiude tutti i componenti che desideri animare. Ecco un esempio in cui facciamo apparire e scomparire gli elementi di una lista. <add> <add>```javascript{28-30} <add>var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup; <add> <add>var TodoList = React.createClass({ <add> getInitialState: function() { <add> return {items: ['ciao', 'mondo', 'clicca', 'qui']}; <add> }, <add> handleAdd: function() { <add> var newItems = <add> this.state.items.concat([prompt('Scrivi del testo')]); <add> this.setState({items: newItems}); <add> }, <add> handleRemove: function(i) { <add> var newItems = this.state.items; <add> newItems.splice(i, 1); <add> this.setState({items: newItems}); <add> }, <add> render: function() { <add> var items = this.state.items.map(function(item, i) { <add> return ( <add> <div key={item} onClick={this.handleRemove.bind(this, i)}> <add> {item} <add> </div> <add> ); <add> }.bind(this)); <add> return ( <add> <div> <add> <button onClick={this.handleAdd}>Aggiungi Elemento</button> <add> <ReactCSSTransitionGroup transitionName="example" transitionEnterTimeout={500} transitionLeaveTimeout={300} > <add> {items} <add> </ReactCSSTransitionGroup> <add> </div> <add> ); <add> } <add>}); <add>``` <add>> Nota: <add>> <add>> Devi fornire [l'attributo `key`](/react/docs/multiple-components.html#dynamic-children) per tutti i figli di `ReactCSSTransitionGroup`, anche quando stai visualizzando un singolo elemento. Questo è il modo in cui React determina quali figli sono stati aggiunti, rimossi, o sono rimasti. <add> <add>In questo componente, quando un nuovo elemento viene aggiunto a `ReactCSSTransitionGroup` riceverà la classe CSS `example-enter` e la classe CSS `example-enter-active` allo scatto successivo. Questa è una convenzione basata sul valore della proprietà `transitionName`. <add> <add>Puoi usare queste classi per scatenare una animazione o transizione CSS. Ad esempio, prova ad aggiungere questo CSS e aggiungere un nuovo elemento alla lista: <add> <add>```css <add>.example-enter { <add> opacity: 0.01; <add>} <add> <add>.example-enter.example-enter-active { <add> opacity: 1; <add> transition: opacity 500ms ease-in; <add>} <add> <add>.example-leave { <add> opacity: 1; <add>} <add> <add>.example-leave.example-leave-active { <add> opacity: 0.01; <add> transition: opacity 300ms ease-in; <add>} <add>``` <add> <add>Ti accorgerai che la durata delle animazioni devono essere specificate sia nel CSS che nel metodo render; questo suggerisce a React quando rimuovere le classi di animazione dall'elemento e -- se sta venendo rimosso -- quando rimuovere l'elemento dal DOM. <add> <add>### Animare il Montaggio Iniziale <add> <add>`ReactCSSTransitionGroup` fornisce la proprietà opzionale `transitionAppear`, per aggiungere una fase aggiuntiva di transizione al montaggio iniziale del componente. In genere non c'è alcuna fase di transizione al montaggio iniziale in quanto il valore predefinito di `transitionAppear` è `false`. L'esempio seguente passa la proprietà `transitionAppear` con il valore `true`. <add> <add>```javascript{3-5} <add> render: function() { <add> return ( <add> <ReactCSSTransitionGroup transitionName="example" transitionAppear={true} transitionAppearTimeout={500}> <add> <h1>Dissolvenza al Montaggio Iniziale</h1> <add> </ReactCSSTransitionGroup> <add> ); <add> } <add>``` <add> <add>Durante il montaggio iniziale `ReactCSSTransitionGroup` otterrà la classe CSS `example-appear` e la classe CSS `example-appear-active` allo scatto successivo. <add> <add>```css <add>.example-appear { <add> opacity: 0.01; <add>} <add> <add>.example-appear.example-appear-active { <add> opacity: 1; <add> transition: opacity .5s ease-in; <add>} <add>``` <add> <add>Al montaggio iniziale, tutti i figli di `ReactCSSTransitionGroup` saranno marcati come `appear` ma non `enter`. Tuttavia, tutti i figli aggiunti in seguito ad un `ReactCSSTransitionGroup` esistente saranno marcati come `enter` ma non `appear`. <add> <add>> Nota: <add>> <add>> La proprietà `transitionAppear` è stata aggiunta a `ReactCSSTransitionGroup` nella versione `0.13`. Per mantenere la compatibilità con le versioni precedenti, il valore predefinito è impostato a `false`. <add> <add>### Classi Personalizzate <add> <add>È anche possibile usare nomi di classi personalizzate per ciascuna delle fasi delle tue transizioni. Anziché passare una stringa come valore di `transitionName` puoi assegnare un oggetto che contiene i nomi delle classi `enter` o `leave`, oppure un oggetto contenente i nomi delle classi per `enter`, `enter-active`, `leave-active`e `leave`. Se vengono forniti soltanto i nomi delle classi enter e leave, le classi per enter-active e leave-active saranno determinate aggiungendo il suffisso '-active' ai rispettivi nomi delle classi. Ecco due esempi che usano le classi personalizzate: <add> <add>```javascript <add> ... <add> <ReactCSSTransitionGroup <add> transitionName={ { <add> enter: 'enter', <add> enterActive: 'enterActive', <add> leave: 'leave', <add> leaveActive: 'leaveActive', <add> appear: 'appear', <add> appearActive: 'appearActive' <add> } }> <add> {item} <add> </ReactCSSTransitionGroup> <add> <add> <ReactCSSTransitionGroup <add> transitionName={ { <add> enter: 'enter', <add> leave: 'leave', <add> appear: 'appear' <add> } }> <add> {item2} <add> </ReactCSSTransitionGroup> <add> ... <add>``` <add> <add>### I Gruppi di Animazioni Devono Essere Montati per Funzionare <add> <add>Per applicare le transizioni ai suoi figli, il `ReactCSSTransitionGroup` deve già essere montato nel DOM oppure la proprietà `transitionAppear` deve essere impostata a `true`. L'esempio seguente non funziona, poiché `ReactCSSTransitionGroup` sta venendo montato assieme al nuovo elemento, anziché il nuovo elemento venire montato dentro di esso. Confronta questo esempio con la sezione precedente [Per Cominciare](#getting-started) per notare la differenza. <add> <add>```javascript{12-15} <add> render: function() { <add> var items = this.state.items.map(function(item, i) { <add> return ( <add> <div key={item} onClick={this.handleRemove.bind(this, i)}> <add> <ReactCSSTransitionGroup transitionName="example"> <add> {item} <add> </ReactCSSTransitionGroup> <add> </div> <add> ); <add> }, this); <add> return ( <add> <div> <add> <button onClick={this.handleAdd}>Aggiungi Elemento</button> <add> {items} <add> </div> <add> ); <add> } <add>``` <add> <add>### Animare Uno o Nessun Elemento <add> <add>Nell'esempio precedente, abbiamo visualizzato una lista di elementi in `ReactCSSTransitionGroup`. Tuttavia, i figli di `ReactCSSTransitionGroup` possono anche essere un solo o nessun elemento. Questo rende possibile animare un singolo elemento che viene aggiunto o rimosso. Similarmente, puoi animare un nuovo elemento che sistituisce l'elemento corrente. Ad esempio, possiamo implementare un semplice carosello di immagini come segue: <add> <add>```javascript{10-12} <add>var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup; <add> <add>var ImageCarousel = React.createClass({ <add> propTypes: { <add> imageSrc: React.PropTypes.string.isRequired <add> }, <add> render: function() { <add> return ( <add> <div> <add> <ReactCSSTransitionGroup transitionName="carousel" transitionEnterTimeout={300} transitionLeaveTimeout={300}> <add> <img src={this.props.imageSrc} key={this.props.imageSrc} /> <add> </ReactCSSTransitionGroup> <add> </div> <add> ); <add> } <add>}); <add>``` <add> <add>### Disattivare le Animazioni <add> <add>Se lo desideri, puoi disattivare le animazioni `enter` o `leave`. Ad esempio, a volte potresti volere un'animazione per `enter` ma non una per `leave`, ma `ReactCSSTransitionGroup` attende che l'animazione sia completata prima di rimuovere il tuo nodo DOM. Puoi aggiungere le proprietà `transitionEnter={false}` o `transitionLeave={false}` a `ReactCSSTransitionGroup` per disattivare le rispettive animazioni. <add> <add>> Nota: <add>> <add>> Quando si usa `ReactCSSTransitionGroup`, non c'è alcun modo per cui i tuoi componenti vengano avvisati quando la transizione è terminata o per effettuare una logica complessa durante l'animazione. Se vuoi un controllo più fine, puoi usare la API di basso livello `ReactTransitionGroup` che fornisce degli hook che puoi utilizzare per effettuare transizioni personalizzate. <add> <add>## API di Basso Livello: `ReactTransitionGroup` <add> <add>`ReactTransitionGroup` è la base per le animazioni. È accessibile come `React.addons.TransitionGroup`. Quando vi sono aggiunti o rimossi dichiarativamente dei figli (come negli esempi precedenti) degli speciali hook del ciclo di vita sono invocati su di essi. <add> <add>### `componentWillAppear(callback)` <add> <add>Viene chiamato allo stesso momento di `componentDidMount()` per i componenti inizialmente montati in un `TransitionGroup`. Bloccherà l'esecuzione di altre animazioni finché `callback` non viene chiamata. Viene chiamata solo durante il rendering iniziale di un `TransitionGroup`. <add> <add>### `componentDidAppear()` <add> <add>Viene chiamato dopo che la funzione `callback` passata a `componentWillAppear` è stata chiamata. <add> <add>### `componentWillEnter(callback)` <add> <add>Viene chiamato allo stesso momento di `componentDidMount()` per i componenti aggiunti ad un `TransitionGroup` esistente. Bloccherà l'esecuzione di altre animazioni finché `callback` non viene chiamata. Non viene chiamata durante il rendering iniziale di un `TransitionGroup`. <add> <add>### `componentDidEnter()` <add> <add>Viene chiamato dopo che la funzione `callback` passata a `componentWillEnter` è stata chiamata. <add> <add>### `componentWillLeave(callback)` <add> <add>Viene chiamato quando il figlio è stato rimosso dal `ReactTransitionGroup`. Nonostante il figlio sia stato rimosso, `ReactTransitionGroup` lo manterrà nel DOM finché `callback` non viene chiamata. <add> <add>### `componentDidLeave()` <add> <add>Viene chiamato quando la `callback` `willLeave` viene chiamata (contemporaneamente a `componentWillUnmount`). <add> <add>### Rendering di un Componente Diverso <add> <add>In maniera predefinita, `ReactTransitionGroup` viene visualizzato come uno `span`. Puoi cambiare questo comportamento fornento una proprietà `component`. Ad esempio, ecco come puoi visualizzare un `<ul>`: <add> <add>```javascript{1} <add><ReactTransitionGroup component="ul"> <add> ... <add></ReactTransitionGroup> <add>``` <add> <add>È possibile utilizzare ciascun componente DOM che React può visualizzare. Tuttavia, `component` non deve necessariamente essere un componente DOM. Può infatti essere qualunque componente React; anche componenti scritti da te! <add> <add>> Nota: <add>> <add>> Prima della v0.12, quando venivano usati componenti DOM, la proprietà `component` doveva essere un riferimento a `React.DOM.*`. Dal momento che il componente è semplicemente passato a `React.createElement`, deve ora essere una stringa. Per componenti compositi si deve passare il metodo factory. <add> <add>Ciascuna proprietà aggiuntiva definita dall'utente diverrà una proprietà del componente visualizzato. Ad esempio, ecco come visualizzeresti un `<ul>` con una classe CSS: <add> <add>```javascript{1} <add><ReactTransitionGroup component="ul" className="animated-list"> <add> ... <add></ReactTransitionGroup> <add>``` <ide><path>docs/docs/10.2-form-input-binding-sugar.it-IT.md <add>--- <add>id: two-way-binding-helpers-it-IT <add>title: Helper Per Binding Bidirezionali <add>permalink: two-way-binding-helpers-it-IT.html <add>prev: animation-it-IT.html <add>next: test-utils-it-IT.html <add>--- <add> <add>`ReactLink` è una maniera semplice di esprimere binding bidirezionali con React. <add> <add>> Nota: <add>> <add>> Se hai poca esperienza del framework, nota che `ReactLink` non è necessario per molte applicazioni e dovrebbe essere utilizzato con cautela. <add> <add>In React, i dati fluiscono in una direzione: dal proprietario ai figli. Questo poiché i dati fluiscono in una sola direzione nel [modello di computazione di Von Neumann](https://en.wikipedia.org/wiki/Von_Neumann_architecture). Puoi pensare ad esso come "binding unidirezionale dei dati." <add> <add>Tuttavia, esistono parecchie applicazioni che richiedono di leggere dati e farli fluire nuovamente nel tuo programma. Ad esempio, quando sviluppi dei moduli, vorrai spesso aggiornare uno `state` di React quando ricevi un input dall'utente. O forse vuoi effettuare il layout in JavaScript e reagire ai cambiamenti nelle dimensioni di alcuni elementi DOM. <add> <add>In React, questo verrebbe implementato ascoltando un evento "change", leggendo la tua fonte di dati (solitamente il DOM) e chiamando `setState()` su uno dei tuoi componenti. "Chiudere il ciclo del flusso dei dati" esplicitamente conduce a programmi più comprensibili e mantenibili. Consulta [la nostra documentazione sui moduli](/react/docs/forms.html) per maggiori informazioni. <add> <add>Il binding bidirezionale -- assicurarsi implicitamente che alcuni valori nel DOM siano sempre consistenti con degli `state` in React -- è più conciso e supporta un'ampia varietà di applicazioni. Abbiamo fornito `ReactLink`: zucchero sintattico per impostare il pattern del ciclo del flusso di dati descritto in predecenza, ovvero "collegare" una fonte di dati con lo `state` di React. <add> <add>> Nota: <add>> <add>> `ReactLink` è soltanto uno strato di astrazione e convenzioni attorno al pattern `onChange`/`setState()`. Non cambia fondamentalmente la maniera in cui i dati fluiscono all'interno della tua applicazione React. <add> <add>## ReactLink: Prima e Dopo <add> <add>Ecco un semplice esempio di modulo che non utilizza `ReactLink`: <add> <add>```javascript <add>var NoLink = React.createClass({ <add> getInitialState: function() { <add> return {message: 'Ciao!'}; <add> }, <add> handleChange: function(event) { <add> this.setState({message: event.target.value}); <add> }, <add> render: function() { <add> var message = this.state.message; <add> return <input type="text" value={message} onChange={this.handleChange} />; <add> } <add>}); <add>``` <add> <add>Ciò funziona molto bene e il flusso di dati è molto chiaro. Tuttavia, in presenza di un gran numero di campi del modulo può risultare assai prolisso. Utilizziamo `ReactLink` per risparmiarci la scrittura di un po' di codice: <add> <add>```javascript{2,7} <add>var WithLink = React.createClass({ <add> mixins: [React.addons.LinkedStateMixin], <add> getInitialState: function() { <add> return {message: 'Ciao!'}; <add> }, <add> render: function() { <add> return <input type="text" valueLink={this.linkState('message')} />; <add> } <add>}); <add>``` <add> <add>`LinkedStateMixin` aggiunge un metodo chiamato `linkState()` al tuo componente React. `linkState()` restituisce un oggetto `ReactLink` contenente il valore attuae dello stato React e una callback per cambiarlo. <add> <add>Gli oggetti `ReactLink` possono essere passati su e giù nell'albero come proprietà, quindi è facile (ed esplicito) impostare un binding bidirezionale tra un componente in profondità nella gerarchia e dello stato che si trova più in alto nella gerarchia. <add> <add>Nota che i checkbox hanno un comportamento speciale riguardo il loro attributo `value`, che è il valore che sarà inviato all'inoltro del modulo se il checkbox è spuntato (il valore predefinito è `on`). L'attributo `value` non è aggiornato quando il checkbox viene spuntato o deselezionato. Per i checkbox occorre usare `checkedLink` anziché `valueLink`: <add>``` <add><input type="checkbox" checkedLink={this.linkState('booleanValue')} /> <add>``` <add> <add> <add>## Dietro le Quinte <add> <add>Ci sono due ambiti in `ReactLink`: il posto in cui crei l'istanza di `ReactLink` e il posto in cui la utilizzi. Per dimostrare quanto sia semplice usare `ReactLink`, riscriviamo ciascun ambito separatamente perché sia più esplicito. <add> <add>### ReactLink Senza LinkedStateMixin <add> <add>```javascript{5-7,9-12} <add>var WithoutMixin = React.createClass({ <add> getInitialState: function() { <add> return {message: 'Ciao!'}; <add> }, <add> handleChange: function(newValue) { <add> this.setState({message: newValue}); <add> }, <add> render: function() { <add> var valueLink = { <add> value: this.state.message, <add> requestChange: this.handleChange <add> }; <add> return <input type="text" valueLink={valueLink} />; <add> } <add>}); <add>``` <add> <add>Come puoi vedere, gli oggetti `ReactLink` sono semplici oggetti che hanno due proprietà: `value` e `requestChange`. `LinkedStateMixin` è altrettanto semplice: popola semplicemente questi campi con un valore da `this.state` e una callback che invoca `this.setState()`. <add> <add>### ReactLink Senza valueLink <add> <add>```javascript <add>var WithoutLink = React.createClass({ <add> mixins: [React.addons.LinkedStateMixin], <add> getInitialState: function() { <add> return {message: 'Ciao!'}; <add> }, <add> render: function() { <add> var valueLink = this.linkState('message'); <add> var handleChange = function(e) { <add> valueLink.requestChange(e.target.value); <add> }; <add> return <input type="text" value={valueLink.value} onChange={handleChange} />; <add> } <add>}); <add>``` <add> <add>La proprietà `valueLink` è anche abbastanza semplice. Gestisce semplicemente l'evento `onChange` e invoca `this.props.valueLink.requestChange()`, e inoltre utilizza `this.props.valueLink.value` anziché `this.props.value`. Tutto qua! <ide><path>docs/docs/10.3-class-name-manipulation.it-IT.md <add>--- <add>id: class-name-manipulation-it-IT <add>title: Manipolazione del Nome di Classe <add>permalink: class-name-manipulation-it-IT.html <add>prev: two-way-binding-helpers-it-IT.html <add>next: test-utils-it-IT.html <add>--- <add> <add>> NOTA: <add>> <add>> Questo modulo esiste adesso in forma separata come [JedWatson/classnames](https://github.com/JedWatson/classnames) ed è indipendente da React. Questo add-on verrà quindi rimosso nell'immediato futuro. <add> <add>`classSet()` è una elegante utility per manipolare facilmente la stringa dell'attributo `class` del DOM. <add> <add>Ecco uno scenario comune e la sua soluzione senza `classSet()`: <add> <add>```javascript <add>// all'interno di un componente React `<Message />` <add>render: function() { <add> var classString = 'message'; <add> if (this.props.isImportant) { <add> classString += ' message-important'; <add> } <add> if (this.props.isRead) { <add> classString += ' message-read'; <add> } <add> // 'message message-important message-read' <add> return <div className={classString}>Fantastico, vediamoci lì.</div>; <add>} <add>``` <add> <add>Questo può facilmente diventare noioso, in quanto assegnare stringhe per nomi di classi può essere difficile da leggere e soggetto ad errori. `classSet()` risolve questo problema: <add> <add>```javascript <add>render: function() { <add> var cx = React.addons.classSet; <add> var classes = cx({ <add> 'message': true, <add> 'message-important': this.props.isImportant, <add> 'message-read': this.props.isRead <add> }); <add> // same final string, but much cleaner <add> return <div className={classes}>Fantastico, vediamoci lì.</div>; <add>} <add>``` <add> <add>Quando usi `classSet()`, passa un oggetto le cui chiavi sono i nomi di classe CSS di cui potresti o meno avere bisogno. Valori di verità risulteranno nell'inclusione della chiave nella stringa risultante. <add> <add>`classSet()` ti permette inoltre di passare nomi di classe che devono essere concatenati come argomenti: <add> <add>```javascript <add>render: function() { <add> var cx = React.addons.classSet; <add> var importantModifier = 'message-important'; <add> var readModifier = 'message-read'; <add> var classes = cx('message', importantModifier, readModifier); <add> // Final string is 'message message-important message-read' <add> return <div className={classes}>Fantastico, vediamoci lì.</div>; <add>} <add>``` <add> <add>Niente più hack per concatenare le stringhe! <ide><path>docs/docs/10.4-test-utils.it-IT.md <add>--- <add>id: test-utils-it-IT <add>title: Utilità di Test <add>permalink: test-utils-it-IT.html <add>prev: two-way-binding-helpers-it-IT.html <add>next: clone-with-props-it-IT.html <add>--- <add> <add>`React.addons.TestUtils` semplifica la validazione dei componenti React nel framework di test di tua scelta (noi utilizziamo [Jest](https://facebook.github.io/jest/)). <add> <add>### Simulate <add> <add>```javascript <add>Simulate.{eventName}( <add> DOMElement element, <add> [object eventData] <add>) <add>``` <add> <add>Simula l'inoltro di un evento su un nodo DOM con dei dati dell'evento opzionali `eventData`. **Questa è probabilmente l'utilità più essenziale in `ReactTestUtils`.** <add> <add>**Cliccare un elemento** <add> <add>```javascript <add>var node = React.findDOMNode(this.refs.button); <add>React.addons.TestUtils.Simulate.click(node); <add>``` <add> <add>**Cambiare il valore di un campo di input e in seguito premere INVIO** <add> <add>```javascript <add>var node = React.findDOMNode(this.refs.input); <add>node.value = 'giraffe' <add>React.addons.TestUtils.Simulate.change(node); <add>React.addons.TestUtils.Simulate.keyDown(node, {key: "Enter", keyCode: 13, which: 13}); <add>``` <add> <add>*nota che dovrai fornire tu stesso ciascuna proprietà dell'evento utilizzata nel tuo componente (ad es. keyCode, which, etc...) in quanto React non crea alcuna di esse per te* <add> <add>`Simulate` possiede un metodo per ciascun evento che React comprende. <add> <add>### renderIntoDocument <add> <add>```javascript <add>ReactComponent renderIntoDocument( <add> ReactElement instance <add>) <add>``` <add> <add>Effettua il rendering di un componente in un nodo DOM staccato dal documento. **Questa funzione richiede la presenza del DOM.** <add> <add>### mockComponent <add> <add>```javascript <add>object mockComponent( <add> function componentClass, <add> [string mockTagName] <add>) <add>``` <add> <add>Passa il mock di un componente a questo metodo per aumentarlo con metodi utili che gli permettono di essere utilizzato come un componente React fantoccio. Anziché essere visualizzato come al solito, il componente diventerà un semplice `<div>` (o qualsiasi altro tag se fornito come valore di `mockTagName`) contenente ciascun figlio fornito. <add> <add>### isElement <add> <add>```javascript <add>boolean isElement( <add> ReactElement element <add>) <add>``` <add> <add>Restituisce `true` se `element` è un qualunque ReactElement. <add> <add>### isElementOfType <add> <add>```javascript <add>boolean isElementOfType( <add> ReactElement element, <add> function componentClass <add>) <add>``` <add> <add>Restituisce `true` se `element` è un ReactElement il cui tipo è la classe React `componentClass`. <add> <add>### isDOMComponent <add> <add>```javascript <add>boolean isDOMComponent( <add> ReactComponent instance <add>) <add>``` <add> <add>Restituisce `true` se `instance` è un componente DOM (come ad esempio `<div>` o `<span>`). <add> <add>### isCompositeComponent <add> <add>```javascript <add>boolean isCompositeComponent( <add> ReactComponent instance <add>) <add>``` <add> <add>Restituisce `true` se `instance` è un componente composito (creato tramite `React.createClass()`). <add> <add>### isCompositeComponentWithType <add> <add>```javascript <add>boolean isCompositeComponentWithType( <add> ReactComponent instance, <add> function componentClass <add>) <add>``` <add> <add>Restituisce `true` se `instance` è un componente composito (creato tramite `React.createClass()`) il cui tipo è una classe React dal nome `componentClass`. <add> <add>### findAllInRenderedTree <add> <add>```javascript <add>array findAllInRenderedTree( <add> ReactComponent tree, <add> function test <add>) <add>``` <add> <add>Attraversa tutti i componenti in `tree` e accumula tutti i componenti per i quali `test(component)` è `true`. Non è molto utile usata da sola, ma diventa ptente se usata come primitiva per altre utilità di test. <add> <add>### scryRenderedDOMComponentsWithClass <add> <add>```javascript <add>array scryRenderedDOMComponentsWithClass( <add> ReactComponent tree, string className <add>) <add>``` <add> <add>Trova tutte le istanze di componenti nell'albero visualizzato che sono componenti DOM il cui nome di classe corrisponde a `className`. <add> <add>### findRenderedDOMComponentWithClass <add> <add>```javascript <add>ReactComponent findRenderedDOMComponentWithClass( <add> ReactComponent tree, <add> string className <add>) <add>``` <add> <add>Simile a `scryRenderedDOMComponentsWithClass()` ma si aspetta di trovare un solo risultato, e restituisce quel solo risultato, oppure lancia un'eccezione se viene trovato qualunque altro numero di occorrenze diverso da uno. <add> <add>### scryRenderedDOMComponentsWithTag <add> <add>```javascript <add>array scryRenderedDOMComponentsWithTag( <add> ReactComponent tree, <add> string tagName <add>) <add>``` <add> <add>Trova tutte le istanze di componenti nell'albero visualizzato che sono componenti DOM il cui nome di tag corrisponde a `tagName`. <add> <add>### findRenderedDOMComponentWithTag <add> <add>```javascript <add>ReactComponent findRenderedDOMComponentWithTag( <add> ReactComponent tree, <add> string tagName <add>) <add>``` <add> <add>Simile a `scryRenderedDOMComponentsWithTag()` ma si aspetta di trovare un solo risultato, e restituisce quel solo risultato, oppure lancia un'eccezione se viene trovato qualunque altro numero di occorrenze diverso da uno. <add> <add>### scryRenderedComponentsWithType <add> <add>```javascript <add>array scryRenderedComponentsWithType( <add> ReactComponent tree, <add> function componentClass <add>) <add>``` <add> <add>Trova tutte le istanze di componenti il cui tipo corrisponde a `componentClass`. <add> <add>### findRenderedComponentWithType <add> <add>```javascript <add>ReactComponent findRenderedComponentWithType( <add> ReactComponent tree, function componentClass <add>) <add>``` <add> <add>Simile a `scryRenderedComponentsWithType()` si aspetta di trovare un solo risultato, oppure lancia un'eccezione se viene trovato qualunque altro numero di occorrenze diverso da uno. <add> <add> <add>## Rendering superficiale <add> <add>Il rendering superficiale è una caratteristica sperimentale che ti permette di effettuare il rendering di un componente "ad un livello di profondità" e asserire dei fatti su ciò che viene restituito dal suo metodo render, senza preoccuparti del comportamento dei componenti figli, i quali non sono né istanziati né viene effettuato il rendering. Questo non richiede la presenza di un DOM. <add> <add>```javascript <add>ReactShallowRenderer createRenderer() <add>``` <add> <add>Chiama questo metodo nei tuoi test per creare un renderer superficiale. Puoi pensare ad esso come un "luogo" in cui effettuare il rendering del componente che stai validando, dove può rispondere ad eventi e aggiornarsi. <add> <add>```javascript <add>shallowRenderer.render( <add> ReactElement element <add>) <add>``` <add> <add>Simile a `React.render`. <add> <add>```javascript <add>ReactComponent shallowRenderer.getRenderOutput() <add>``` <add> <add>Dopo che `render` è stato chiamato, restituisce un output di cui è stato effettuato un rendering superficiale. Puoi quindi iniziare ad asserire fatti sull'output. Ad esempio, se il metodo render del tuo componente resituisce: <add> <add>```javascript <add><div> <add> <span className="heading">Titolo</span> <add> <Subcomponent foo="bar" /> <add></div> <add>``` <add> <add>Allora puoi asserire: <add> <add>```javascript <add>result = renderer.getRenderOutput(); <add>expect(result.type).toBe('div'); <add>expect(result.props.children).toEqual([ <add> <span className="heading">Titolo</span>, <add> <Subcomponent foo="bar" /> <add>]); <add>``` <add> <add>La validazione superficiale ha al momento alcune limitazioni, in particolare non supporta i riferimenti. Stiamo rilasciando questa caratteristica in anticipo e gradiremmo ascoltare il parere della comunità React per la direzione in cui debba evolvere. <ide><path>docs/docs/10.5-clone-with-props.it-IT.md <add>--- <add>id: clone-with-props-it-IT <add>title: Clonare ReactElements <add>permalink: clone-with-props-it-IT.html <add>prev: test-utils-it-IT.html <add>next: create-fragment-it-IT.html <add>--- <add> <add>> Nota: <add>> `cloneWithProps` è deprecato. Usa [React.cloneElement](top-level-api.html#react.cloneelement) al suo posto. <add> <add>In rare condizioni, potresti voler creare una copia di un elemento React con proprietà diverse da quelle dell'elemento originale. Un esempio è clonare gli elementi passati come `this.props.children` ed effettuarne il rendering con proprietà diverse: <add> <add>```js <add>var _makeBlue = function(element) { <add> return React.addons.cloneWithProps(element, {style: {color: 'blue'}}); <add>}; <add> <add>var Blue = React.createClass({ <add> render: function() { <add> var blueChildren = React.Children.map(this.props.children, _makeBlue); <add> return <div>{blueChildren}</div>; <add> } <add>}); <add> <add>React.render( <add> <Blue> <add> <p>Questo testo è blu.</p> <add> </Blue>, <add> document.getElementById('container') <add>); <add>``` <add> <add>`cloneWithProps` non trasferisce gli attributi `key` o `ref` agli elementi clonati. Le proprietà `className` e `style` sono automaticamente riunite. <ide><path>docs/docs/10.6-create-fragment.it-IT.md <add>--- <add>id: create-fragment-it-IT <add>title: Frammenti con Chiave <add>permalink: create-fragment-it-IT.html <add>prev: clone-with-props-it-IT.html <add>next: update-it-IT.html <add>--- <add> <add>In molti casi, puoi utilizzare la proprietà `key` per specificare chiavi sugli elementi che restituisci da `render`. Tuttavia, questo approccio fallisce in una situazione: se hai due insiemi di figli che devi riordinare, non esiste alcun modo di assegnare una chiave a ciascuno di essi senza aggiungere un elemento contenitore. <add> <add>Ovvero, se hai un componente come il seguente: <add> <add>```js <add>var Swapper = React.createClass({ <add> propTypes: { <add> // `leftChildren` e `rightChildren` possono essere una stringa, un elemento, un array, etc. <add> leftChildren: React.PropTypes.node, <add> rightChildren: React.PropTypes.node, <add> <add> swapped: React.PropTypes.bool <add> } <add> render: function() { <add> var children; <add> if (this.props.swapped) { <add> children = [this.props.rightChildren, this.props.leftChildren]; <add> } else { <add> children = [this.props.leftChildren, this.props.rightChildren]; <add> } <add> return <div>{children}</div>; <add> } <add>}); <add>``` <add> <add>I figli saranno smontati e rimontati nel momento in cui cambi la proprietà `swapped` poiché non ci sono chiavi che marcano i due insiemi di figli. <add> <add>Per risolvere questo problema, puoi utilizzare `React.addons.createFragment` per dare una chiave a ciascun insieme di figli. <add> <add>#### `ReactFragment React.addons.createFragment(object children)` <add> <add>Anziché creare array, scriviamo: <add> <add>```js <add>if (this.props.swapped) { <add> children = React.addons.createFragment({ <add> right: this.props.rightChildren, <add> left: this.props.leftChildren <add> }); <add>} else { <add> children = React.addons.createFragment({ <add> left: this.props.leftChildren, <add> right: this.props.rightChildren <add> }); <add>} <add>``` <add> <add>Le chiavi degli oggetti passati (ovvero, `left` e `right`) sono usate come chiavi per l'intero insieme di figli, e l'ordine delle chiavi dell'oggetto è utilizzato per determinare l'ordine dei figli visualizzati. Con questo cambiamento, i due insiemi di figli saranno correttamente riordinati nel DOM senza bisogno di smontaggio. <add> <add>Il valore di ritorno di `createFragment` deve essere trattato come un oggetto opaco; puoi usare gli helper `React.Children` per iterare su un frammento ma non dovresti accedervi direttamente. Nota anche che ci stiamo affidando al motore JavaScript per preservare l'ordine dell'enumerazione degli oggetti, che non viene garantito dalla specifica ma è implementato dai principali browser e macchine virtuali per oggetti con chiavi non numeriche. <add> <add>> **Nota:** <add>> <add>> In un futuro, `createFragment` potrebbe essere sostituito da una API quale <add>> <add>> ```js <add>> return ( <add>> <div> <add>> <x:frag key="right">{this.props.rightChildren}</x:frag>, <add>> <x:frag key="left">{this.props.leftChildren}</x:frag> <add>> </div> <add>> ); <add>> ``` <add>> <add>> che ti permette di assegnare chiavi direttamente in JSX senza aggiungere elementi contenitore. <ide><path>docs/docs/10.7-update.it-IT.md <add>--- <add>id: update-it-IT <add>title: Helper per l'Immutabilità <add>permalink: update-it-IT.html <add>prev: create-fragment-it-IT.html <add>next: pure-render-mixin-it-IT.html <add>--- <add> <add>React ti permette di usare qualunque stile per la gestione dei dati che desideri, incluso la mutazione. Tuttavia, se puoi usare dati immutabili in parti critiche per le prestazioni della tua applicazione è facile implementare rapidamente un metodo `shouldComponentUpdate()` che aumenta significativamente la velocità della tua applicazione. <add> <add>Avere a che fare con dati immutabili in JavaScript è più difficile che in linguaggi progettati a tale scopo, come [Clojure](http://clojure.org/). Tuttavia, abbiamo fornito un semplice helper per l'immutabilità, `update()`, che rende avere a che fare con questo tipo di dati molto più semplice, *senza* cambiare fondamentalmente la rappresentazione dei tuoi dati. Se puoi anche dare un'occhiata alla libreria [Immutable-js](https://facebook.github.io/immutable-js/docs/) di Facebook e la sezione [Prestazioni Avanzate](/react/docs/advanced-performance.html) per maggiori dettagli su Immutable-js. <add> <add>## L'idea fondamentale <add> <add>Se muti i tuoi dati nella seguente maniera: <add> <add>```js <add>myData.x.y.z = 7; <add>// oppure... <add>myData.a.b.push(9); <add>``` <add> <add>non hai modo di determinare quali dati siano cambiati dal momento che la copia precedente è stata sovrascritta. Invece, devi creare una nuova copia di `myData` e cambiare solo le parti che vanno cambiate. Allora puoi confrontare la vecchia copia di `myData` con la nuova in `shouldComponentUpdate()` usando l'operatore di uguaglianza stretta `===`: <add> <add>```js <add>var newData = deepCopy(myData); <add>newData.x.y.z = 7; <add>newData.a.b.push(9); <add>``` <add> <add>Sfortunatamente, le copie profonde sono costose, e a volte impossibili. Puoi alleviare questa limitazione copiando soltanto gli oggetti che devono essere cambiati e riutilizzando gli oggetti che nonsono cambiati. Sfortunatamente, nel JavaScript odierno questa può essere un'operazione difficoltosa: <add> <add>```js <add>var newData = extend(myData, { <add> x: extend(myData.x, { <add> y: extend(myData.x.y, {z: 7}), <add> }), <add> a: extend(myData.a, {b: myData.a.b.concat(9)}) <add>}); <add>``` <add> <add>Mentre questo codice ha prestazioni accettabili (dal momento che effettua soltanto una copia superficiale di `log n` oggetti e riutilizza i rimanenti), è una gran scocciatura da scrivere. Guarda quanta ripetizione! Questo non è soltanto fastidioso, ma offre una grande superficie di attacco per i bachi. <add> <add>`update()` fornisce un semplice zucchero sintattico attorno a questo pattern per rendere più semplice la scrittura di questo codice. Questo codice diventa: <add> <add>```js <add>var newData = React.addons.update(myData, { <add> x: {y: {z: {$set: 7}}}, <add> a: {b: {$push: [9]}} <add>}); <add>``` <add> <add>Mentre la sintassi richiede qualche tempo per abituarsi (anche se è ispirata dal [linguaggio di query di MongoDB](http://docs.mongodb.org/manual/core/crud-introduction/#query)) non c'è ridondanza, può essere analizzato staticamente e non richiede la scrittura di più codice della versione mutativa. <add> <add>Le chiavi con il prefisso `$` sono chiamate *comandi*. La struttura dati che stanno "mutando" viene chiamata *bersaglio*. <add> <add>## Comandi disponibili <add> <add> * `{$push: array}` invoca `push()` sul bersagio passando ciascun elemento di `array`. <add> * `{$unshift: array}` invoca `unshift()` sul bersagio passando ciascun elemento di `array`. <add> * `{$splice: array of arrays}` per ogni elemento di `arrays` invoca `splice()` sul bersaglio con i parametri forniti dall'elemento. <add> * `{$set: any}` sostituisce l'intero bersaglio. <add> * `{$merge: object}` unisce le chiavi di `object` con il bersaglio. <add> * `{$apply: function}` passa il valore attuale alla funzione e lo aggiorna con il nuovo valore da essa restituito. <add> <add>## Esempi <add> <add>### Semplice inserimento in coda <add> <add>```js <add>var initialArray = [1, 2, 3]; <add>var newArray = update(initialArray, {$push: [4]}); // => [1, 2, 3, 4] <add>``` <add>`initialArray` is still `[1, 2, 3]`. <add> <add>### Collezioni annidate <add> <add>```js <add>var collection = [1, 2, {a: [12, 17, 15]}]; <add>var newCollection = update(collection, {2: {a: {$splice: [[1, 1, 13, 14]]}}}); <add>// => [1, 2, {a: [12, 13, 14, 15]}] <add>``` <add>Questo accede all'indice `2` di `collection`, alla chiave `a`, ed effettua lo splice di un elemento a partire dall'indice `1` (per rimuovere `17`) e al contempo inserisce `13` e `14`. <add> <add>### Aggiornare un valore basandosi sul suo valore attuale <add> <add>```js <add>var obj = {a: 5, b: 3}; <add>var newObj = update(obj, {b: {$apply: function(x) {return x * 2;}}}); <add>// => {a: 5, b: 6} <add>// Questa è una forma equivalente, ma diventa prolissa per profonde collezioni annidate: <add>var newObj2 = update(obj, {b: {$set: obj.b * 2}}); <add>``` <add> <add>### Unione (superficiale) <add> <add>```js <add>var obj = {a: 5, b: 3}; <add>var newObj = update(obj, {$merge: {b: 6, c: 7}}); // => {a: 5, b: 6, c: 7} <add>``` <ide><path>docs/docs/10.8-pure-render-mixin.it-IT.md <add>--- <add>id: pure-render-mixin-it-IT <add>title: PureRenderMixin <add>permalink: pure-render-mixin-it-IT.html <add>prev: update-it-IT.html <add>next: perf-it-IT.html <add>--- <add> <add>Se la funzione render del tuo componente React è "pura" (in altre parole, visualizza lo stesso risultato a partire dagli stessi proprietà e stato), puoi usare questo mixin per un incremento di prestazioni in alcuni casi. <add> <add>Esempio: <add> <add>```js <add>var PureRenderMixin = require('react/addons').addons.PureRenderMixin; <add>React.createClass({ <add> mixins: [PureRenderMixin], <add> <add> render: function() { <add> return <div className={this.props.className}>foo</div>; <add> } <add>}); <add>``` <add> <add>Dietro le quinte, il mixin implementa [shouldComponentUpdate](/react/docs/component-specs.html#updating-shouldcomponentupdate), nel quale confronta i valori attuali di `this.props` e `this.state` con i successivi e restituisce `false` se l'uguaglianza è verificata. <add> <add>> Nota: <add>> <add>> Questo confronto tra gli oggetti è soltanto superficiale. Se questi contengono strutture dati complesse, può causare dei falsi negativi per differenze in profondità. Effettua il mix in componenti la cui struttura di `this.props` e `this.state` sia semplice, oppure utilizza `forceUpdate()` quando si ha la certezza che le strutture dati siano cambiate in profondità. In alternativa, considera l'utilizzo di [oggetti immutabili](https://facebook.github.io/immutable-js/) per facilitare il confronto rapido di oggetti annidati. <add>> <add>> Inoltre, `shouldComponentUpdate` rimanda gli aggiornamenti per l'intero sotto albero di componenti. Assicurati che tutti i componenti figli siano anch'essi "puri". <ide><path>docs/docs/10.9-perf.it-IT.md <add>--- <add>id: perf-it-IT <add>title: Strumenti per la Performance <add>permalink: perf-it-IT.html <add>prev: pure-render-mixin-it-IT.html <add>next: advanced-performance-it-IT.html <add>--- <add> <add>React è solitamente assai veloce. Tuttavia, in situazioni nelle quali devi spremere fino all'ultima goccia di prestazioni dalla tua applicazione, fornisce un hook [shouldComponentUpdate](/react/docs/component-specs.html#updating-shouldcomponentupdate) nel quale puoi aggiungere controlli di ottimizzazione per l'algoritmo di confronto di React. <add> <add>Oltre a darti una panoramica sulle prestazioni generali della tua applicazione, ReactPerf è uno strumento di profilazione che ti dice esattamente dove è necessario aggiungere questi hook. <add> <add>> Nota: <add>> <add>> La build di sviluppo di React è più lenta della build di produzione, per via di tutta la logica aggiuntiva per fornire, ad esempio, gli avvisi amichevoli di React nella console (eliminati dalla build di produzione). Pertanto, il profilatore serve soltanto ad indicare le parti _relativamente_ costose della tua applicazione. <add> <add>## API Generale <add> <add>L'oggetto `Perf` documentato di seguito è esposto come `React.addons.Perf` quando si usa la build `react-with-addons.js` in modalità di sviluppo. <add> <add>### `Perf.start()` and `Perf.stop()` <add>Avvia/interrompe la misurazione. Le operazioni React intermedie sono registrate per analisi in seguito. Le operazioni che hanno impiegato un tempo trascurabile vengono ignorate. <add> <add>Dopo l'interruzione, dovrai chiamare `Perf.getLastMeasurements()` (descritta in seguito) per ottenere le misurazioni. <add> <add>### `Perf.printInclusive(measurements)` <add>Stampa il tempo complessivo impiegato. Se non vengono passati argomenti, stampa tutte le misurazioni dall'ultima registrazione. Stampa una tabella gradevolmente formattata nella console, come segue: <add> <add>![](/react/img/docs/perf-inclusive.png) <add> <add>### `Perf.printExclusive(measurements)` <add>I tempi "esclusivi" non includono il tempo impiegato a montare i componenti: processare le proprietà, `getInitialState`, chiamare `componentWillMount` e `componentDidMount`, etc. <add> <add>![](/react/img/docs/perf-exclusive.png) <add> <add>### `Perf.printWasted(measurements)` <add> <add>**La parte più utile in assoluto del profilatore**. <add> <add>Il tempo "sprecato" è impiegato nei componenti che non hanno di fatto visualizzato nulla, ad es. il rendering è rimasto inalterato, quindi il DOM non è stato toccato. <add> <add>![](/react/img/docs/perf-wasted.png) <add> <add>### `Perf.printDOM(measurements)` <add>Stampa le manipolazioni sottostanti del DOM, ad es. "imposta innerHTML" e "rimuovi". <add> <add>![](/react/img/docs/perf-dom.png) <add> <add>## API Avanzata <add> <add>I metodi di stampa precedenti utilizzano `Perf.getLastMeasurements()` per effettuare una gradevole stampa dei risultati. <add> <add>### `Perf.getLastMeasurements()` <add>Ottieni l'array delle misurazioni dall'ultima sessione di avvio-interruzione. L'array contiene oggetti, ciascuno dei quali assomiglia a quanto segue: <add> <add>```js <add>{ <add> // I termini "inclusive" ed "exclusive" sono spiegati in seguito <add> "exclusive": {}, <add> // '.0.0' è l'identificativo React del nodo <add> "inclusive": {".0.0": 0.0670000008540228, ".0": 0.3259999939473346}, <add> "render": {".0": 0.036999990697950125, ".0.0": 0.010000003385357559}, <add> // Numero di istanze <add> "counts": {".0": 1, ".0.0": 1}, <add> // Scritture sul DOM <add> "writes": {}, <add> // Informazioni aggiuntive per il debug <add> "displayNames": { <add> ".0": {"current": "App", "owner": "<root>"}, <add> ".0.0": {"current": "Box", "owner": "App"} <add> }, <add> "totalTime": 0.48499999684281647 <add>} <add>``` <ide><path>docs/docs/11-advanced-performance.it-IT.md <add>--- <add>id: advanced-performance-it-IT <add>title: Performance Avanzata <add>permalink: advanced-performance-it-IT.html <add>prev: perf-it-IT.html <add>--- <add> <add>Una tra le prime domande che la gente si pone quando considera React per un progetto è se l'applicazione sarà altrettanto veloce e scattante di una versione equivalente non basata su React. L'idea di ripetere il rendering di un intero sottoalbero di componenti in risposta a ciascun cambiamento dello stato rende la gente curiosa se questo processo influisce negativamente sulle prestazioni. React utilizza diverse tecniche intelligenti per minimizzare il numero di operazioni costose sul DOM richieste dall'aggiornamento della UI. <add> <add>## Evitare di riconciliare il DOM <add> <add>React fa uso di un *DOM virtuale*, che è un descrittore di un sottoalbero DOM visualizzato nel browser. Questa rappresentazione parallela permette a React di evitare di creare nodi DOM e accedere nodi esistenti, che è di gran lunga più lento di operazioni su oggetti JavaScript. Quando le proprietà di un componente o il suo stato cambiano, React decide se un'aggiornamento effettivo del DOM sia necessario costruendo un nuovo virtual DOM e confrontandolo con quello vecchio. Solo nel caso in cui non siano uguali, React [riconcilierà](/react/docs/reconciliation.html) il DOM, applicando il minor numero di mutamenti possibile. <add> <add>In aggiunta a questo, React offre una funzione per il ciclo di vita del componente, `shouldComponentUpdate`, che viene scatenata prima che il processo di ri-rendering cominci (il confronto del DOM virtuale e una possibile eventuale riconciliazione del DOM), dando allo sviluppatore la possibilità di cortocircuitare questo processo. L'implementazione predefinita di questa funzione restituisce `true`, lasciando che React effettui l'aggiornamento: <add> <add>```javascript <add>shouldComponentUpdate: function(nextProps, nextState) { <add> return true; <add>} <add>``` <add> <add>Tieni in mente che React invocherà questa funzione abbastanza spesso, quindi l'implementazione deve essere veloce. <add> <add>Supponiamo che hai un'applicazione di messaggistica con parecchi thread di conversazioni. Supponi che solo uno dei thread sia cambiato. Se implementassimo `shouldComponentUpdate` sul componente `ChatThread`, React potrebbe saltare la fase di rendering per gli altri thread: <add> <add>```javascript <add>shouldComponentUpdate: function(nextProps, nextState) { <add> // TODO: restituisci true se il thread attuale è diverso <add> // da quello precedente. <add>} <add>``` <add> <add>Quindi, riassumendo, React evita di effettuare operazioni costose sul DOM richieste a riconciliare sottoalberi del DOM, permettendo all'utente di cortocircuitare il processo usando `shouldComponentUpdate`, e, per i casi in cui si debba aggiornare, confrontando i DOM virtuali. <add> <add>## shouldComponentUpdate in azione <add> <add>Ecco un sottoalbero di componenti. Per ciascuno di essi viene indicato cosa `shouldComponentUpdate` ha restituito e se i DOM virtuali siano equivalenti o meno. Infine, il colore del cerchio indica se il componente sia stato riconciliato o meno. <add> <add><figure><img src="/react/img/docs/should-component-update.png" /></figure> <add> <add>Nell'esempio precedente, dal momento che `shouldComponentUpdate` ha restituito `false` per il sottoalbero di radice C2, React non ha avuto bisogno di generare il nuovo DOM virtuale, e quindi non ha nemmeno avuto bisogno di riconciliare il DOM. Nota che React non ha nemmeno avuto bisogno di invocare `shouldComponentUpdate` su C4 e C5. <add> <add>Per C1 e C3, `shouldComponentUpdate` ha restituito `true`, quindi React è dovuto scendere giù fino alle foglie e controllarle. Per C6 ha restituito `true`; dal momento che i DOM virtuali non erano equivalenti, ha dovuto riconciliare il DOM. <add>L'ultimo caso interessante è C8. Per questo nodo React ha dovuto calcolare il DOM virtuale, ma dal momento che era uguale al vecchio, non ha dovuto riconciliare il suo DOM. <add> <add>Nota che React ha dovuto effettuare mutazioni del DOM soltanto per C6, che era inevitabile. Per C8, lo ha evitato confrontando i DOM virtuali, e per il sottoalbero di C2 e C7, non ha neppure dovuto calcolare il DOM virtuale in quanto è stato esonerato da `shouldComponentUpdate`. <add> <add>Quindi, come dovremmo implementare `shouldComponentUpdate`? Supponiamo di avere un componente che visualizza soltanto un valore stringa: <add> <add>```javascript <add>React.createClass({ <add> propTypes: { <add> value: React.PropTypes.string.isRequired <add> }, <add> <add> render: function() { <add> return <div>{this.props.value}</div>; <add> } <add>}); <add>``` <add> <add>Potremmo facilmente implementare `shouldComponentUpdate` come segue: <add> <add>```javascript <add>shouldComponentUpdate: function(nextProps, nextState) { <add> return this.props.value !== nextProps.value; <add>} <add>``` <add> <add>Finora tutto a posto, maneggiare queste semplici strutture proprietà e stato è molto facile. Potremmo anche generalizzare un'implementazione basata sull'uguaglianza superficiale e farne il mix dentro i componenti. Infatti, React fornisce già una tale implementazione: [PureRenderMixin](/react/docs/pure-render-mixin.html). <add> <add>Ma che succede se le proprietà o lo stato del tuo componente sono strutture dati mutevoli? Supponiamo che la proprietà che il componente riceve sia, anziché una stringa come `'bar'`, un oggetto JavaScript che contiene una stringa, come `{ foo: 'bar' }`: <add> <add>```javascript <add>React.createClass({ <add> propTypes: { <add> value: React.PropTypes.object.isRequired <add> }, <add> <add> render: function() { <add> return <div>{this.props.value.foo}</div>; <add> } <add>}); <add>``` <add> <add>L'implementazione di `shouldComponentUpdate` che avevamo prima non funzionerebbe sempre come ci aspettiamo: <add> <add>```javascript <add>// assumiamo che this.props.value sia { foo: 'bar' } <add>// assumiamo che nextProps.value sia { foo: 'bar' }, <add>// ma questo riferimento è diverso da this.props.value <add>this.props.value !== nextProps.value; // true <add>``` <add> <add>Il problema è che `shouldComponentUpdate` restituirà `true` quando la proprietà non è in realtà cambiata. Per risolvere questo problema, potremmo proporre questa implementazione alternativa: <add> <add>```javascript <add>shouldComponentUpdate: function(nextProps, nextState) { <add> return this.props.value.foo !== nextProps.value.foo; <add>} <add>``` <add> <add>In breve, abbiamo finito per effettuare un confronto in profondità per assicurarci di accorgerci correttamente dei cambiamenti. In termini di prestazioni, questo approccio è molto costoso. Non scala in quanto dovremmo scrivere codice diverso per valutare l'uguaglianza in profondità per ciascun modello. Inoltre, potrebbe anche non funzionare per nulla se non gestiamo correttamente i riferimenti agli oggetti. Supponiamo che il componente sia usato da un genitore: <add> <add>```javascript <add>React.createClass({ <add> getInitialState: function() { <add> return { value: { foo: 'bar' } }; <add> }, <add> <add> onClick: function() { <add> var value = this.state.value; <add> value.foo += 'bar'; // ANTI-PATTERN! <add> this.setState({ value: value }); <add> }, <add> <add> render: function() { <add> return ( <add> <div> <add> <InnerComponent value={this.state.value} /> <add> <a onClick={this.onClick}>Click me</a> <add> </div> <add> ); <add> } <add>}); <add>``` <add> <add>La prima volta che viene effettuato il rendering del componente interno, la sua proprietà value avrà il valore `{ foo: 'bar' }`. Se l'utente clicca l'ancora, lo stato del componente genitore sarà aggiornato a `{ value: { foo: 'barbar' } }`, scatenando il processo di ri-rendering sul componente interno, il quale riceverà `{ foo: 'barbar' }` come il nuovo valore della proprietà. <add> <add>Il problema è che, dal momento che il genitore e il componente interno condividono un riferimento allo stesso oggetto, quando l'oggetto viene modificato nella riga 2 della funzione `onClick`, la proprietà che il componente interno possedeva cambierà anch'essa. Quindi, quando il processo di ri-rendering inizia, e `shouldComponentUpdate` viene invocato, `this.props.value.foo` sarà uguale a `nextProps.value.foo`, perché infatti, `this.props.value` si riferisce allo stesso oggetto di `nextProps.value`. <add> <add>Di conseguenza, dal momento che non ci accorgiamo del cambiamento della proprietà e cortocircuitiamo il processo di ri-rendering, la UI non sarà aggiornata da `'bar'` a `'barbar'`. <add> <add>## Immutable-js viene in nostro soccorso <add> <add>[Immutable-js](https://github.com/facebook/immutable-js) è una libreria di collezioni JavaScript scritta da Lee Byron, che Facebook ha recentemente rilasciato come open source. Fornisce collezioni *immutabili e persistenti* attraverso *condivisione strutturale*. Vediamo cosa significano queste proprietà: <add> <add>* *Immutabile*: una volta creata, una collezione non può essere alterata in un momento successivo. <add>* *Persistente*: nuove collezioni possono essere create da una collezione precedente e una mutazione come un assegnamento. La collezione originale è ancora valida dopo che la nuova collezione è stata creata. <add>* *Condivisione Strutturale*: nuove collezioni sono create riutilizzando quanto più possibile della stessa struttura della collezione originale, riducendo le operazioni di copia al minimo, per ottenere efficienza spaziale e prestazioni accettabili. Se la nuova collezione è identica all'originale, l'originale è spesso restituita. <add> <add>L'immutabilità ci permette di tenere traccia dei cambiamenti in modo economico; un cambiamento risulterà sempre in un nuovo oggetto, quindi dobbiamo soltanto controllare se il riferimento all'oggeto sia cambiato. Ad esempio, in questo codice regolare JavaScript: <add> <add>```javascript <add>var x = { foo: "bar" }; <add>var y = x; <add>y.foo = "baz"; <add>x === y; // true <add>``` <add> <add>Sebbene `y` sia stato modificato, dal momento che si tratta di un riferimento allo stesso oggetto di `x`, questo confronto restituisce `true`. Tuttavia, questo codice potrebbe essere scritto usando immutable-js come segue: <add> <add>```javascript <add>var SomeRecord = Immutable.Record({ foo: null }); <add>var x = new SomeRecord({ foo: 'bar' }); <add>var y = x.set('foo', 'baz'); <add>x === y; // false <add>``` <add> <add>In questo caso, poiché un nuovo riferimento è restituito quando si modifica `x`, possiamo assumere in tutta sicurezza che `x` sia cambiato. <add> <add>Un'altra maniera possibile di tener traccia dei cambiamenti potrebbe essere il dirty checking, ovvero usare un flag impostato dai metodi setter. Un problema con questo approccio è che ti forza ad usare i setter e scrivere un sacco di codice aggiuntivo, oppure instrumentare in qualche modo le tue classi. In alternativa, puoi effettuare una copia profonda dell'oggetto immediatamente prima della mutazione ed effettuare un confronto in profondità per determinare se vi è stato un cambiamento oppure no. Un problema con questo approccio è che sia deepCopy che deepCompare sono operazioni costose. <add> <add>Quindi, le strutture dati Immutable ti forniscono una maniera economica e concisa di osservare i cambiamenti degli oggetti, che è tutto ciò che ci serve per implementare `shouldComponentUpdate`. Pertanto, se modelliamo gli attributi delle proprietà e dello stato usando le astrazioni fornite da immutable-js saremo in grado di usare `PureRenderMixin` e ottenere un grande aumento di prestazioni. <add> <add>## Immutable-js e Flux <add> <add>Se stai usando [Flux](https://facebook.github.io/flux/), dovresti cominciare a scrivere i tuoi store usando immutable-js. Dài un'occhiata alla [API completa](https://facebook.github.io/immutable-js/docs/#/). <add> <add>Vediamo una delle possibili maniere di modellare l'esempio dei thread usando strutture dati Immutable. Anzitutto, dobbiamo definire un `Record` per ciascuna delle entità che desideriamo modellare. I Record sono semplicemente contenitori immutabili che contengono valori per un insieme specifico di campi: <add> <add>```javascript <add>var User = Immutable.Record({ <add> id: undefined, <add> name: undefined, <add> email: undefined <add>}); <add> <add>var Message = Immutable.Record({ <add> timestamp: new Date(), <add> sender: undefined, <add> text: '' <add>}); <add>``` <add> <add>La funzione `Record` riceve un oggetto che definisce i campi che l'oggetto possiede e i loro valori predefiniti. <add> <add>Lo *store* dei messaggi potrebbe tenere traccia degli utenti e dei messaggi usando due liste: <add> <add>```javascript <add>this.users = Immutable.List(); <add>this.messages = Immutable.List(); <add>``` <add> <add>Dovrebbe essere abbastanza banale implementare funzioni che gestiscono ciascun tipo di *payload*. Ad esempio, quando lo store vede un payload che rappresenta un messaggio, possiamo semplicemente creare un nuovo record e metterlo in coda alla lista di messaggi: <add> <add>```javascript <add>this.messages = this.messages.push(new Message({ <add> timestamp: payload.timestamp, <add> sender: payload.sender, <add> text: payload.text <add>}); <add>``` <add> <add>Nota che dal momento che le strutture dati sono immutabili, dobbiamo assegnare il valore di ritorno del metodo push a `this.messages`. <add> <add>Dal punto di vista di React, se usiamo strutture dati immutable-js anche per contenere lo stato del componente, possiamo fare il mix di `PureRenderMixin` in tutti i nostri componenti e cortocircuitare il processo di ri-rendering. <ide><path>docs/docs/complementary-tools.it-IT.md <add>--- <add>id: complementary-tools-it-IT <add>title: Strumenti Complementari <add>permalink: complementary-tools-it-IT.html <add>prev: videos-it-IT.html <add>next: examples-it-IT.html <add>--- <add> <add>Questa pagina è stata spostata sul [wiki di GitHub](https://github.com/facebook/react/wiki/Complementary-Tools). <ide><path>docs/docs/conferences.it-IT.md <add>--- <add>id: conferences-it-IT <add>title: Conferenze <add>permalink: conferences-it-IT.html <add>prev: thinking-in-react-it-IT.html <add>next: videos-it-IT.html <add>--- <add> <add>### React.js Conf 2015 <add>28 e 29 Gennaio <add> <add>[Sito web](http://conf.reactjs.com/) - [Agenda](http://conf.reactjs.com/schedule.html) - [Video](https://www.youtube-nocookie.com/playlist?list=PLb0IAmt7-GS1cbw4qonlQztYV1TAW0sCr) <add> <add><iframe width="650" height="315" src="//www.youtube-nocookie.com/embed/KVZ-P-ZI6W4?list=PLb0IAmt7-GS1cbw4qonlQztYV1TAW0sCr" frameborder="0" allowfullscreen></iframe> <add> <add>### ReactEurope 2015 <add>2 e 3 Luglio <add> <add>[Sito web](http://www.react-europe.org/) - [Agenda](http://www.react-europe.org/#schedule) <ide><path>docs/docs/examples.it-IT.md <add>--- <add>id: examples-it-IT <add>title: Esempi <add>permalink: examples-it-IT.html <add>prev: complementary-tools-it-IT.html <add>--- <add> <add>Questa pagina è stata spostata sul [wiki di GitHub](https://github.com/facebook/react/wiki/Examples). <ide><path>docs/docs/flux-overview.it-IT.md <add>--- <add>id: flux-overview-it-IT <add>title: Architettura di un'Applicazione Flux <add>permalink: flux-overview-it-IT.html <add>--- <add> <add>Questa pagina è stata spostata sul sito di Flux. [Leggila qui](https://facebook.github.io/flux/docs/overview.html). <ide><path>docs/docs/flux-todo-list.it-IT.md <add>--- <add>id: flux-todo-list-it-IT <add>title: Tutorial TodoMVC Flux <add>permalink: flux-todo-list-it-IT.html <add>--- <add> <add>Questa pagina è stata spostata sul sito di Flux. [Leggila qui](https://facebook.github.io/flux/docs/todo-list.html). <ide><path>docs/docs/getting-started.it-IT.md <add>--- <add>id: getting-started-it-IT <add>title: Primi Passi <add>permalink: getting-started-it-IT.html <add>next: tutorial-it-IT.html <add>redirect_from: "docs/index.html" <add>--- <add> <add>## JSFiddle <add> <add>La maniera più semplice di cominciare ad hackerare con React è usare i seguenti esempi di Hello World su JSFiddle: <add> <add> * **[React JSFiddle](https://jsfiddle.net/reactjs/69z2wepo/)** <add> * [React JSFiddle senza JSX](https://jsfiddle.net/reactjs/5vjqabv3/) <add> <add>## Starter Kit <add> <add>Scarica lo starter kit per cominciare. <add> <add><div class="buttons-unit downloads"> <add> <a href="/react/downloads/react-{{site.react_version}}.zip" class="button"> <add> Scarica lo Starter Kit {{site.react_version}} <add> </a> <add></div> <add> <add>Nella directory principale dello starter kit, crea `helloworld.html` con il seguente contenuto. <add> <add>```html <add><!DOCTYPE html> <add><html> <add> <head> <add> <meta charset="UTF-8" /> <add> <title>Ciao React!</title> <add> <script src="build/react.js"></script> <add> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script> <add> </head> <add> <body> <add> <div id="example"></div> <add> <script type="text/babel"> <add> React.render( <add> <h1>Cial, mondo!</h1>, <add> document.getElementById('example') <add> ); <add> </script> <add> </body> <add></html> <add>``` <add> <add>La sintassi XML all'interno di JavaScript è chiamata JSX; dài un'occhiata alla [sintassi JSX](/react/docs/jsx-in-depth.html) per saperne di più. Allo scopo di tradurla in puro JavaScript usiamo `<script type="text/babel">` e includiamo Babel per effettuare la trasformazione effettiva nel browser. <add> <add>### File Separato <add> <add>Il tuo codice React JSX può trovarsi in un file a parte. Crea il seguente `src/helloworld.js`. <add> <add>```javascript <add>React.render( <add> <h1>Ciao, mondo!</h1>, <add> document.getElementById('example') <add>); <add>``` <add> <add>Quindi fai riferimento ad esso da `helloworld.html`: <add> <add>```html{10} <add><script type="text/babel" src="src/helloworld.js"></script> <add>``` <add> <add>Nota che in alcuni browsers (Chrome, ad esempio) falliranno nel caricamento del file a meno che non sia servito tramite HTTP. <add> <add>### Trasformazione Offline <add> <add>Anzitutto installa gli strumenti da riga di comando di [Babel](http://babeljs.io/) (è richiesto [npm](https://www.npmjs.com/)): <add> <add>``` <add>npm install --global babel <add>``` <add> <add>Quindi, traduci il tuo file `src/helloworld.js` a semplice JavaScript: <add> <add>``` <add>babel src --watch --out-dir build <add> <add>``` <add> <add>Il file `build/helloworld.js` è generato automaticamente ogni qualvolta effettui un cambiamento. Leggi la [documentazione di Babel CLI](http://babeljs.io/docs/usage/cli/) per un uso più avanzato. <add> <add>```javascript{2} <add>React.render( <add> React.createElement('h1', null, 'Ciao, mondo!'), <add> document.getElementById('example') <add>); <add>``` <add> <add> <add>Aggiorna il tuo file HTML come segue: <add> <add>```html{7,11} <add><!DOCTYPE html> <add><html> <add> <head> <add> <meta charset="UTF-8" /> <add> <title>Ciao React!</title> <add> <script src="build/react.js"></script> <add> <!-- Non c'è bisogno di Babel! --> <add> </head> <add> <body> <add> <div id="example"></div> <add> <script src="build/helloworld.js"></script> <add> </body> <add></html> <add>``` <add> <add>## Vuoi CommonJS? <add> <add>Se vuoi usare React con [browserify](http://browserify.org/), [webpack](https://webpack.github.io/), o un altro sistema modulare compatibile con CommonJS, usa il [pacchetto npm `react`](https://www.npmjs.com/package/react). In aggiunta, lo strumento di build `jsx` può essere integrato in quasi tutti i sistemi di packaging (non soltanto CommonJS) assai facilmente. <add> <add>## Passi Successivi <add> <add>Dài un'occhiata [al tutorial](/react/docs/tutorial-it-IT.html) e agli altri esempi nella directory `examples` dello starter kit per saperne di più. <add> <add>Abbiamo anche un wiki al quale la comunità contribuisce con [flussi di lavoro, componenti UI, routing, gestione dati etc.](https://github.com/facebook/react/wiki/Complementary-Tools) <add> <add>In bocca al lupo, e benvenuto/a! <ide><path>docs/docs/ref-01-top-level-api.it-IT.md <add>--- <add>id: top-level-api-it-IT <add>title: API di Livello Elevato <add>permalink: top-level-api-it-IT.html <add>next: component-api-it-IT.html <add>redirect_from: "/docs/reference.html" <add>--- <add> <add>## React <add> <add>`React` è il punto di ingresso alla libreria React. Se stai usando uno dei pacchetti precompilati, è disponibile come variabile globale; se stai usando i moduli CommonJS puoi richiederlo con `require()`. <add> <add> <add>### React.Component <add> <add>```javascript <add>class Component <add>``` <add> <add>Questa è la classe base per i componenti React quando sono definiti usando le classi ES6. Vedi [Componenti Riutilizzabili](/react/docs/reusable-components.html#es6-classes) per usare le classi ES6 con React. Per i metodi forniti dalla classe base, vedi la [API dei Componenti](/react/docs/component-api.html). <add> <add> <add>### React.createClass <add> <add>```javascript <add>ReactClass createClass(object specification) <add>``` <add> <add>Crea la classe di un componente, data una specifica. Un componente implementa un metodo `render` che restituisce **un singolo** figlio. Tale figlio può avere una struttura di fogli arbitrariamente profonda. Una cosa che rende i componenti diversi dalle classi prototipiche standard è che non hai bisogno di chiamare `new` su di esse. Sono delle convenienti astrazioni che costruiscono (attraverso `new`) istanze dietro le quinte per te. <add> <add>Per maggiori informazioni sull'oggetto specifica, vedi [Specifiche dei Componenti e Ciclo di Vita](/react/docs/component-specs.html). <add> <add> <add>### React.createElement <add> <add>```javascript <add>ReactElement createElement( <add> string/ReactClass type, <add> [object props], <add> [children ...] <add>) <add>``` <add> <add>Crea e restituisce un nuovo `ReactElement` del tipo desiderato. L'argomento `type` può essere una stringa contenente il nome di un tag HTML (ad es. 'div', 'span', etc), oppure una `ReactClass` (creata attraverso `React.createClass`). <add> <add> <add>### React.cloneElement <add> <add>``` <add>ReactElement cloneElement( <add> ReactElement element, <add> [object props], <add> [children ...] <add>) <add>``` <add> <add>Clona e restituisce un nuovo `ReactElement` usando `element` come punto di partenza. L'elemento risultante avrà le proprietà dell'elemento originale, con le nuove proprietà unite in maniera superficiale. I figli esistenti sono sostituiti dai figli passati come `children`. Diversamente da `React.addons.cloneWithProps`, `key` e `ref` dell'elemento originale saranno preservati. Non esiste alcun comportamento speciale per riunire le proprietà (diversamente da `cloneWithProps`). Vedi l'[articolo del blog sulla v0.13 RC2](/react/blog/2015/03/03/react-v0.13-rc2.html) per maggiori dettagli. <add> <add> <add>### React.createFactory <add> <add>```javascript <add>factoryFunction createFactory( <add> string/ReactClass type <add>) <add>``` <add> <add>Restituisce una funzione che produce ReactElements di un tipo desiderato. Come `React.createElement`, <add>l'argomento `type` può essere sia la stringa contenente il nome di un tag HTML (ad es. 'div', 'span', etc), oppure una <add>`ReactClass`. <add> <add> <add>### React.render <add> <add>```javascript <add>ReactComponent render( <add> ReactElement element, <add> DOMElement container, <add> [function callback] <add>) <add>``` <add> <add>Effettua il rendering di un ReactElement nel DOM all'interno dell'elemento `container` fornito e restituisce un [riferimento](/react/docs/more-about-refs-it-IT.html) al componente (oppure restituisce `null` per i [componenti privi di stato](/react/docs/reusable-components-it-IT.html#stateless-functions)). <add> <add>Se il rendering del ReactElement è stato precedentemente effettuato all'interno di `container`, questa operazione effettuerà un aggiornamento su di esso e modificherà il DOM in modo necessario a riflettere il più recente componente React. <add> <add>Se la callback opzionale è fornita, sarà eseguita dopo che il rendering o l'aggiornamento del componente sono stati effettuati. <add> <add>> Nota: <add>> <add>> `React.render()` controlla i contenuti del nodo contenitore che viene passato come argomento `container`. Gli elementi DOM <add>> esistenti al suo interno sono sostituiti quando viene chiamata la prima volta. Le chiamate successive usano l'algoritmo di <add>> differenza di React per aggiornamenti efficienti. <add>> <add>> `React.render()` non modifica il nodo contenitore (modifica soltanto i figli del contenitore). In <add>> futuro potrebbe essere possibile inserire un componente in un nodo DOM esistente senza sovrascrivere i figli esistenti. <add> <add> <add>### React.unmountComponentAtNode <add> <add>```javascript <add>boolean unmountComponentAtNode(DOMElement container) <add>``` <add> <add>Rimuove un componente React montato nel DOM e ripulisce i suoi gestori di evento e lo stato. Se nessun componente è stato montato nel contenitore `container`, chiamare questa funzione non ha alcun effetto. Restituisce `true` se il componente è stato smontato e `false` se non è stato trovato un componente da smontare. <add> <add> <add>### React.renderToString <add> <add>```javascript <add>string renderToString(ReactElement element) <add>``` <add> <add>Effettua il rendering di un ReactElement come il suo HTML iniziale. Questo dovrebe essere utilizzato soltanto lato server. React restituirà una stringa di HTML. Puoi usare questo metodo per generare HTML sul server e inviare il markup come risposta alla richiesta iniziale per un più rapido caricamento della pagina, e permettere ai motori di ricerca di effettuare il crawling della tua pagina per ottimizzazione SEO. <add> <add>Se chiami `React.render()` su un nodo che possiede già questo markup generato lato server, React lo preserverà e vi attaccherà soltanto i gestori di eventi, permettendoti di avere una esperienza di primo caricamento altamente efficiente. <add> <add> <add>### React.renderToStaticMarkup <add> <add>```javascript <add>string renderToStaticMarkup(ReactElement element) <add>``` <add> <add>Simile a `renderToString`, eccetto che non crea attributi DOM aggiuntivi come `data-react-id`, che React utilizza internamente. Questo è utile se vuoi usare React come un semplice generatore di pagine statiche, in quanto eliminare gli attributi aggiuntivi può risparmiare parecchi byte. <add> <add> <add>### React.isValidElement <add> <add>```javascript <add>boolean isValidElement(* object) <add>``` <add> <add>Verifica che `object` sia un ReactElement. <add> <add> <add>### React.findDOMNode <add> <add>```javascript <add>DOMElement findDOMNode(ReactComponent component) <add>``` <add>Se questo componente è stato montato nel DOM, restituisce il corrispondente elemento DOM nativo del browser. Questo metodo è utile per leggere i valori dal DOM, come i valori dei campi dei moduli ed effettuare misure sul DOM. Quando `render` restituisce `null` o `false`, `findDOMNode` restituisce `null`. <add> <add>> Nota: <add>> <add>> `findDOMNode()` è una via di fuga usata per accedere al nodo DOM sottostante. Nella maggior parte dei casi, l'uso di questa via di fuga è scoraggiato perché viola l'astrazione del componente. Tuttavia, esistono delle situazioni in cui questo è necessario (ad esempio, potresti aver bisogno di trovare un nodo DOM per posizionarlo in maniera assoluta oppure determinarne la larghezza visualizzata misurata in pixel). <add> <add>> <add>> `findDOMNode()` funziona soltanto su componenti montati (cioè, componenti che sono stati posizionati nel DOM). Se provi a chiamarlo su un componente che non è stato ancora montato (come chiamare `findDOMNode()` in `render()` su un componente che deve ancora essere creato) lancerà un'eccezione. <add> <add>### React.DOM <add> <add>`React.DOM` fornisce convenienti utilità che espongono `React.createElement` per componenti del DOM. Questi dovrebbero essere usate soltanto quando non si utilizza JSX. Ad esempio, `React.DOM.div(null, 'Ciao Mondo!')` <add> <add> <add>### React.PropTypes <add> <add>`React.PropTypes` include tipi che possono essere usati con l'oggetto `propTypes` di un componente per validare le proprietà passate ai tuoi componenti. Per maggiori informazioni su `propTypes`, vedi [Componenti Riutilizzabili](/react/docs/reusable-components.html). <add> <add> <add>### React.Children <add> <add>`React.Children` fornisce utilitià per gestire la struttura dati opaca `this.props.children`. <add> <add>#### React.Children.map <add> <add>```javascript <add>object React.Children.map(object children, function fn [, object thisArg]) <add>``` <add> <add>Invoca `fn` su ciascuno dei diretti discendenti contenuti in `children`, con `this` impostato a `thisArg`. Se `children` è un oggetto annidato o un array, esso verrà attraversato: ad `fn` non saranno mai passati gli oggetti contenitori. Se `children` è `null` o `undefined` restituisce `null` o `undefined` anziché un oggetto vuoto. <add> <add>#### React.Children.forEach <add> <add>```javascript <add>React.Children.forEach(object children, function fn [, object thisArg]) <add>``` <add> <add>Come `React.Children.map()` con la differenza che non restituisce un oggetto. <add> <add>#### React.Children.count <add> <add>```javascript <add>number React.Children.count(object children) <add>``` <add> <add>Restituisce il numero totale di componenti in `children`, uguale al numero di volte che una callback passata a `map` o `forEach` verrebbe invocata. <add> <add>#### React.Children.only <add> <add>```javascript <add>object React.Children.only(object children) <add>``` <add> <add>Restituisce il figlio unico contenuto in `children`, altrimenti lancia un'eccezione. <ide><path>docs/docs/ref-02-component-api.it-IT.md <add>--- <add>id: component-api-it-IT <add>title: API dei Componenti <add>permalink: component-api-it-IT.html <add>prev: top-level-api-it-IT.html <add>next: component-specs-it-IT.html <add>--- <add> <add>## React.Component <add> <add>Istanze di un React Component sono create internamente a React durante il rendering. Queste istanze sono riutilizzate in rendering successivi, e possono essere accedute dai metodi del tuo componente come `this`. L'unica maniera di ottenere un riferimento a una istanza di un React Component fuori da React è conservare il valore restituito da `React.render`. All'interno di altri Component, puoi utilizzare [i ref](/react/docs/more-about-refs.html) per ottenere il medesimo risultato. <add> <add> <add>### setState <add> <add>```javascript <add>setState( <add> function|object nextState, <add> [function callback] <add>) <add>``` <add>Effettua una combinazione di `nextState` nello stato attuale. Questo è il metodo principale che va usato per scatenare aggiornamenti della UI da gestori di eventi e callback di richieste al server. <add> <add>Il primo argomento può essere un oggetto (contenente zero o più chiavi da aggiornare) o una funzione (con argomenti `state` e `props`) che restituisce un oggetto contenente chiavi da aggiornare. <add> <add>Ecco come utilizzarla passando un oggetto: <add> <add>```javascript <add>setState({mykey: 'my new value'}); <add>``` <add> <add>È anche possibile passare una funzione con la firma `function(state, props)`. Questo può essere utile in certi casi quando desideri accodare un aggiornamento atomico che consulta i valori precedenti di state+props prima di impostare i nuovi valori. Ad esempio, supponi che vogliamo incrementare un valore nello stato: <add> <add>```javascript <add>setState(function(previousState, currentProps) { <add> return {myInteger: previousState.myInteger + 1}; <add>}); <add>``` <add> <add>Il secondo parametro (opzionale) è una funzione callback che verrà eseguita quando `setState` ha terminato e il rendering del componente è stato effettuato. <add> <add>> Note: <add>> <add>> *MAI* modificare `this.state` direttamente, in quanto chiamare `setState()` successivamente potrebbe sovrascrivere la modifica fatta. Tratta `this.state` come se fosse immutabile. <add>> <add>> `setState()` non cambia immediatamente `this.state`, ma crea una transizione di stato in corso. Accedere `this.state` subito dopo aver chiamato questo metodo potrebbe potenzialmente restituire il valore precedente. <add>> <add>> Non viene garantita alcuna sincronicità per le chiamate di `setState`, e le chiamate stesse potrebbero essere raggruppate per migliorare le prestazioni. <add>> <add>> `setState()` scatena sempre un ri-rendering a meno che la logica di rendering condizionale venga implementata in `shouldComponentUpdate()`. Se oggetti mutabili sono usati e la logica non può essere implementata in `shouldComponentUpdate()`, chiamare `setState()` solo quando il nuovo stato differisce dal precedente eviterà ri-rendering superflui. <add> <add> <add>### replaceState <add> <add>```javascript <add>replaceState( <add> object nextState, <add> [function callback] <add>) <add>``` <add> <add>Come `setState()`, ma elimina ogni chiave preesistente che non si trova in `nextState`. <add> <add>> Nota: <add>> <add>> Questo metodo non è disponibile il componenti `class` ES6 che estendono `React.Component`. Potrebbe essere eliminato del tutto in una versione futura di React. <add> <add> <add>### forceUpdate <add> <add>```javascript <add>forceUpdate( <add> [function callback] <add>) <add>``` <add> <add>In modo predefinito, quando lo stato o le proprietà del tuo componente cambiano, ne verrà effettuato il ri-rendering. Tuttavia, se questi cambiano implicitamente (ad es.: dati profondi all'interno di un oggetto cambiano senza che l'oggetto stesso cambi) o se il tuo metodo `render()` dipende da altri dati, puoi istruire React perché riesegua `render()` chiamando `forceUpdate()`. <add> <add>Chiamare `forceUpdate()` causerà la chiamata di `render()` sul componente, saltando l'esecuzione di `shouldComponentUpdate()`. Questo scatenerà i normali metodi del ciclo di vita per i componenti figli, incluso il metodo `shouldComponentUpdate()` di ciascun figlio. React tuttavia aggiornerà il DOM soltanto se il markup effettivamente cambia. <add> <add>Normalmente dovresti cercare di evitare l'uso di `forceUpdate()` e leggere soltanto `this.props` e `this.state` all'interno di `render()`. Ciò rende il tuo componente "puro" e la tua applicazione molto più semplice ed efficiente. <add> <add> <add>### getDOMNode <add> <add>```javascript <add>DOMElement getDOMNode() <add>``` <add> <add>Se questo componente è stato montato nel DOM, restituisce il corrispondente elemento DOM nativo del browser. Questo metodo è utile per leggere valori dal DOM, come valori dei campi dei moduli ed effettuare misure sul DOM. Quando `render` restituisce `null` o `false`, `this.getDOMNode()` restituisce `null`. <add> <add>> Nota: <add>> <add>> getDOMNode è deprecato ed è stato sostituito da [React.findDOMNode()](/react/docs/top-level-api.html#react.finddomnode). <add>> <add>> Questo metodo non è disponibile il componenti `class` ES6 che estendono `React.Component`. Potrebbe essere eliminato del tutto in una versione futura di React. <add> <add> <add>### isMounted <add> <add>```javascript <add>bool isMounted() <add>``` <add> <add>`isMounted()` restituisce `true` se il rendering del componente è stato effettuato nel DOM, `false` altrimenti. Puoi usare questo metodo come guardia per chiamate asincrone a `setState()` o `forceUpdate()`. <add> <add>> Nota: <add>> <add>> Questo metodo non è disponibile il componenti `class` ES6 che estendono `React.Component`. Potrebbe essere eliminato del tutto in una versione futura di React. <add> <add> <add>### setProps <add> <add>```javascript <add>setProps( <add> object nextProps, <add> [function callback] <add>) <add>``` <add> <add>Quando stai integrando con un'applicazione JavaScript esterna puoi voler segnalare un cambiamento a un componente React il cui rendering è stato effettuato con `React.render()`. <add> <add>Chiamare `setProps()` su un componente al livello radice cambierà le sue proprietà e scatenerà un ri-rendering. Inoltre, puoi fornire una funzione callback opzionale che verrà eseguita quando `setProps` ha terminato e il rendering del componente è terminato. <add> <add>> Nota: <add>> <add>> Quando possibile, l'approccio dichiarativo di invocare nuovamente `React.render()` sullo stesso nodo è preferibile. Quest'ultimo tende a rendere gli aggiornamenti più comprensibili. (Non vi è una differenza significativa di prestazioni tra i due approcci.) <add>> <add>> Questo metodo può essere chiamato soltanto su un componente al livello radice. Ovvero, è disponibile soltanto sul componente passato direttamente a `React.render()` e nessuno dei suoi figli. Se il tuo intento è usare `setProps()` su un componente figlio, approfitta degli aggiornamenti reattivi e passa la nuova proprietà al componente figlio quando viene creato in `render()`. <add>> <add>> Questo metodo non è disponibile il componenti `class` ES6 che estendono `React.Component`. Potrebbe essere eliminato del tutto in una versione futura di React. <add> <add>### replaceProps <add> <add>```javascript <add>replaceProps( <add> object nextProps, <add> [function callback] <add>) <add>``` <add> <add>Come `setProps()` ma elimina ogni proprietà preesistente anziché riunire i due oggetti. <add> <add>> Nota: <add>> <add>> Questo metodo non è disponibile il componenti `class` ES6 che estendono `React.Component`. Potrebbe essere eliminato del tutto in una versione futura di React. <ide><path>docs/docs/ref-03-component-specs.it-IT.md <add>--- <add>id: component-specs-it-IT <add>title: Specifica dei Componenti e Ciclo di Vita <add>permalink: component-specs-it-IT.html <add>prev: component-api-it-IT.html <add>next: tags-and-attributes-it-IT.html <add>--- <add> <add>## Specifica dei Componenti <add> <add>Quando crei una classe di componente invocando `React.createClass()`, devi fornire un oggetto specifica che contiene un metodo `render` che può contenere opzionalmete altri metodi del ciclo di vita descritti di seguito. <add> <add>> Nota: <add>> <add>> È anche possibile usare pure classi JavaScript come classi di componente. Queste classi possono implementare la maggior parte degli stessi metodi, sebbene vi siano delle differenze. Per maggiori informazioni su queste differenze, leggi la nostra documentazione sulle [classi ES6](/react/docs/reusable-components.html#es6-classes). <add> <add>### render <add> <add>```javascript <add>ReactElement render() <add>``` <add> <add>Il metodo `render()` è richiesto. <add> <add>Quando viene chiamato, dovrebbe esaminare `this.props` e `this.state` e restituire un singolo elemento figlio. Questo elemento figlio può essere sia una rappresentazione virtuale di un componente DOM nativo (come `<div />` o `React.DOM.div()`) o un altro componente composito che hai definito tu stesso. <add> <add>Puoi anche restituire `null` o `false` per indicare che desideri che non venga visualizzato nulla. Dietro le quinte, React visualizza un tag `<noscript>` per lavorare con il nostro attuale algoritmo di differenza. Quando si restituisce `null` o `false`, `React.findDOMNode(this)` restituirà `null`. <add> <add>La funzione `render()` dovrebbe essere *pura*, nel senso che non modifica lo stato del componente, restituisce lo stesso risultato ogni volta che viene invocato, e non legge o scrive il DOM o interagisce in altro modo con il browser (ad es. usando `setTimeout`). Se devi interagire con il browser, effettua le tue operazioni in `componentDidMount()` o negli altri metodi del ciclo di vita. Mantenere `render()` puro rende il rendering lato server più praticabile e rende i componenti più facili da comprendere. <add> <add> <add>### getInitialState <add> <add>```javascript <add>object getInitialState() <add>``` <add> <add>Invocato una volta prima che il componente venga montato. Il valore di ritorno sarà usato come il valore iniziale di `this.state`. <add> <add> <add>### getDefaultProps <add> <add>```javascript <add>object getDefaultProps() <add>``` <add> <add>Invocato una volta e conservato quando la classe è creata. I valori nella mappa saranno impostati in `this.props` se tale proprietà non è specificata dal componente genitore (ad es. usando un controllo `in`). <add> <add>Questo metodo è invocato prima che un'istanza sia creata e quindi non può dipendere da `this.props`. Inoltre, tieni presente che ogni oggetto complesso restituito da `getDefaultProps()` sarà condiviso tra le diverse istanze, non copiato. <add> <add> <add>### propTypes <add> <add>```javascript <add>object propTypes <add>``` <add> <add>L'oggetto `propTypes` ti permette di validare le proprietà passate ai tuoi componenti. Per maggiori informazioni su `propTypes`, leggi [Componenti Riutilizzabili](/react/docs/reusable-components-it-IT.html). <add> <add> <add>### mixins <add> <add>```javascript <add>array mixins <add>``` <add> <add>L'array `mixins` ti permette di usare i mixin per condividere il comportamento tra componenti multipli. Per maggiori informazioni sui mixin, leggi [Componenti Riutilizzabili](/react/docs/reusable-components-it-IT.html). <add> <add> <add>### statics <add> <add>```javascript <add>object statics <add>``` <add> <add>L'oggetto `statics` ti permette di definire metodi statici che possono essere chiamati sulla classe del componente. Ad esempio: <add> <add>```javascript <add>var MyComponent = React.createClass({ <add> statics: { <add> customMethod: function(foo) { <add> return foo === 'bar'; <add> } <add> }, <add> render: function() { <add> } <add>}); <add> <add>MyComponent.customMethod('bar'); // true <add>``` <add> <add>I metodi definiti in questo blocco sono _statici_, ovvero puoi eseguirli prima che un'istanza del componente venga creata, e i metodi non hanno accesso alle proprietà e lo stato dei tuoi componenti. Se desideri confrontare i valori delle proprietà in un metodo statico, devi farle passare dal chiamante al metodo statico tramite un argomento. <add> <add> <add>### displayName <add> <add>```javascript <add>string displayName <add>``` <add> <add>La stringa `displayName` viene usata nei messaggi di debug. JSX imposta questo valore automaticamente; vedi [JSX in Profondità](/react/docs/jsx-in-depth-it-IT.html#the-transform). <add> <add> <add>## Metodi del Ciclo di Vita <add> <add>Vari metodi vengono eseguiti durante precisi momenti del ciclo di vita di un componente. <add> <add> <add>### Montaggio: componentWillMount <add> <add>```javascript <add>componentWillMount() <add>``` <add> <add>Invocato una volta, sia sul client che sul server, immediatamente prima che il rendering iniziale abbia luogo. Se chiami `setState` all'interno di questo metodo, `render()` vedrà lo stato aggiornato e sarà eseguito solo una volta nonostante il cambiamento di stato. <add> <add> <add>### Montaggio: componentDidMount <add> <add>```javascript <add>componentDidMount() <add>``` <add> <add>Invocato una volta, solo sul client (e non sul server), immediatamente dopo che il rendering iniziale ha avuto luogo. A questo punto del ciclo di vita, il componente ha una rappresentazione DOM che puoi accedere attraverso `React.findDOMNode(this)`. Il metodo `componentDidMount()` dei componenti figli è invocato prima di quello dei componenti genitori. <add> <add>Se desideri integrare con altri framework JavaScript, impostare dei timer usando `setTimeout` o `setInterval`, oppure inviare richieste AJAX, effettua tali operazioni in questo metodo. <add> <add> <add>### Aggiornamento: componentWillReceiveProps <add> <add>```javascript <add>componentWillReceiveProps( <add> object nextProps <add>) <add>``` <add> <add>Invocato quando un componente sta ricevendo nuove proprietà. Questo metodo non viene chiamato durante il rendering iniziale. <add> <add>Usa questo metodo come opportunità per reagire a una transizione di proprietà prima che `render()` venga chiamato, aggiornando lo stato usando `this.setState()`. I vecchi valori delle proprietà possono essere letti tramite `this.props`. Chiamare `this.setState()` all'interno di questa funzione non scatenerà un rendering addizionale. <add> <add>```javascript <add>componentWillReceiveProps: function(nextProps) { <add> this.setState({ <add> likesIncreasing: nextProps.likeCount > this.props.likeCount <add> }); <add>} <add>``` <add> <add>> Nota: <add>> <add>> Non esiste un metodo analogo `componentWillReceiveState`. Una imminente transizione delle proprietà potrebbe causare un cambiamento di stato, ma il contrario non è vero. Se devi effettuare delle operazioni in risposta a un cambiamento di stato, usa `componentWillUpdate`. <add> <add> <add>### Aggiornamento: shouldComponentUpdate <add> <add>```javascript <add>boolean shouldComponentUpdate( <add> object nextProps, object nextState <add>) <add>``` <add> <add>Invocato prima del rendering quando vengono ricevuti nuove proprietà o un nuovo stato. Questo metodo non viene chiamato per il rendering iniziale o quando viene usato `forceUpdate`. <add> <add>Usa questo metodo come opportunità per restituire `false` quando si è certi che la transizione alle nuove proprietà e al nuovo stato non richieda un aggiornamento del componente. <add> <add>```javascript <add>shouldComponentUpdate: function(nextProps, nextState) { <add> return nextProps.id !== this.props.id; <add>} <add>``` <add> <add>Se `shouldComponentUpdate` restituisce false, allora `render()` sarà saltato completamente fino al prossimo cambiamento di stato. Inoltre, `componentWillUpdate` e `componentDidUpdate` non verranno chiamati. <add> <add>In modo predefinito, `shouldComponentUpdate` restituisce sempre `true` per evitare bachi subdoli quando `state` viene modificato direttamente, ma se hai l'accortezza di trattare sempre `state` come immutabile e accedere a `props` e `state` in sola lettura in `render()`, allora puoi tranquillamente ridefinire `shouldComponentUpdate` con un'implementazione che confronta i vecchi valori di props e state con quelli nuovi. <add> <add>Se le prestazioni diventano un collo di bottiglia, specialmente in presenza di decine o centinaia di componenti, usa `shouldComponentUpdate` per accelerare la tua applicazione. <add> <add> <add>### Aggiornamento: componentWillUpdate <add> <add>```javascript <add>componentWillUpdate( <add> object nextProps, object nextState <add>) <add>``` <add> <add>Invocato immediatamente prima del rendering quando nuove proprietà o un nuovo stato vengono ricevuti. Questo metodo non viene chiamato per il rendering iniziale. <add> <add>Usa questo metodo come opportunità per effettuare la preparazione prima che si verifichi un aggiornamento. <add> <add>> Nota: <add>> <add>> *Non puoi* usare `this.setState()` in questo metodo. Se devi aggiornare lo stato in risposta al cambiamento di una proprietà, usa `componentWillReceiveProps`. <add> <add> <add>### Aggiornamento: componentDidUpdate <add> <add>```javascript <add>componentDidUpdate( <add> object prevProps, object prevState <add>) <add>``` <add> <add>Invocato immediatamente dopo che gli aggiornamenti del componente sono stati trasmessi al DOM. Questo metodo non viene chiamato per il rendering iniziale. <add> <add>Usa questo metodo come opportunità per operare sul DOM quando il componente è stato the component has been updated. <add> <add> <add>### Smontaggio: componentWillUnmount <add> <add>```javascript <add>componentWillUnmount() <add>``` <add> <add>Invocato immediatamente prima che un componente venga smontato dal DOM. <add> <add>Effettua la necessaria pulizia in questo metodo, come invalidare i timer o ripulire ciascun elemento DOM creato all'interno di `componentDidMount`. <ide><path>docs/docs/ref-04-tags-and-attributes.it-IT.md <add>--- <add>id: tags-and-attributes-it-IT <add>title: Tag e Attributi <add>permalink: tags-and-attributes-it-IT.html <add>prev: component-specs-it-IT.html <add>next: events-it-IT.html <add>--- <add> <add>## Tag Supportati <add> <add>React tenta di supportare tutti gli elementi comuni. Se hai bisogno di un elemento che non è elencato di seguito, per favore [apri una issue](https://github.com/facebook/react/issues/new). <add> <add>### Elementi HTML <add> <add>I seguenti elementi HTML sono supportati: <add> <add>``` <add>a abbr address area article aside audio b base bdi bdo big blockquote body br <add>button canvas caption cite code col colgroup data datalist dd del details dfn <add>dialog div dl dt em embed fieldset figcaption figure footer form h1 h2 h3 h4 h5 <add>h6 head header hr html i iframe img input ins kbd keygen label legend li link <add>main map mark menu menuitem meta meter nav noscript object ol optgroup option <add>output p param picture pre progress q rp rt ruby s samp script section select <add>small source span strong style sub summary sup table tbody td textarea tfoot th <add>thead time title tr track u ul var video wbr <add>``` <add> <add>### Elementi SVG <add> <add>I seguenti elementi SVG sono supportati: <add> <add>``` <add>circle clipPath defs ellipse g line linearGradient mask path pattern polygon polyline <add>radialGradient rect stop svg text tspan <add>``` <add> <add>Potresti trovare utile [react-art](https://github.com/facebook/react-art), una libreria di disegno per React che può disegnare su Canvas, SVG oppure VML (per IE8). <add> <add> <add>## Attributi Supportati <add> <add>React supporta tutti gli attributi `data-*` e `aria-*`, oltre a ciascun attributo nelle liste seguenti. <add> <add>> Nota: <add>> <add>> Tutti gli attributi sono camel-cased, e gli attributi `class` e `for` sono resi come `className` e `htmlFor` rispettivamente, per adeguarsi alla specifica delle API del DOM. <add> <add>Per una lista di eventi, consulta gli [Eventi Supportati](/react/docs/events.html). <add> <add>### Attributi HTML <add> <add>Questi attributi standard sono supportati: <add> <add>``` <add>accept acceptCharset accessKey action allowFullScreen allowTransparency alt <add>async autoComplete autoFocus autoPlay capture cellPadding cellSpacing charSet <add>challenge checked classID className cols colSpan content contentEditable contextMenu <add>controls coords crossOrigin data dateTime defer dir disabled download draggable <add>encType form formAction formEncType formMethod formNoValidate formTarget frameBorder <add>headers height hidden high href hrefLang htmlFor httpEquiv icon id inputMode <add>keyParams keyType label lang list loop low manifest marginHeight marginWidth max <add>maxLength media mediaGroup method min minlength multiple muted name noValidate open <add>optimum pattern placeholder poster preload radioGroup readOnly rel required role <add>rows rowSpan sandbox scope scoped scrolling seamless selected shape size sizes <add>span spellCheck src srcDoc srcSet start step style summary tabIndex target title <add>type useMap value width wmode wrap <add>``` <add> <add>In aggiunta, i seguenti attributi non-standard sono supportati: <add> <add>- `autoCapitalize autoCorrect` per Mobile Safari. <add>- `property` per i meta tag [Open Graph](http://ogp.me/). <add>- `itemProp itemScope itemType itemRef itemID` per i [microdata HTML5](http://schema.org/docs/gs.html). <add>- `unselectable` per Internet Explorer. <add>- `results autoSave` per campi di input del tipo `search` in WebKit/Blink. <add> <add>Esiste anche l'attributo specifico di React `dangerouslySetInnerHTML` ([maggiori informazioni](/react/docs/special-non-dom-attributes.html)), usato per inserire direttamente stringhe di HTML in un componente. <add> <add>### Attributi SVG <add> <add>``` <add>clipPath cx cy d dx dy fill fillOpacity fontFamily <add>fontSize fx fy gradientTransform gradientUnits markerEnd <add>markerMid markerStart offset opacity patternContentUnits <add>patternUnits points preserveAspectRatio r rx ry spreadMethod <add>stopColor stopOpacity stroke strokeDasharray strokeLinecap <add>strokeOpacity strokeWidth textAnchor transform version <add>viewBox x1 x2 x xlinkActuate xlinkArcrole xlinkHref xlinkRole <add>xlinkShow xlinkTitle xlinkType xmlBase xmlLang xmlSpace y1 y2 y <add>``` <ide><path>docs/docs/ref-05-events.it-IT.md <add>--- <add>id: events-it-IT <add>title: Sistema di Eventi <add>permalink: events-it-IT.html <add>prev: tags-and-attributes-it-IT.html <add>next: dom-differences-it-IT.html <add>--- <add> <add>## SyntheticEvent <add> <add>Ai tuoi gestori di eventi saranno passate istanze di `SyntheticEvent`, un involucro cross-browser attorno all'evento nativo del browser. Possiede la stessa interfaccia dell'evento nativo del browser, incluso `stopPropagation()` e `preventDefault()`, con l'eccezione che gli eventi funzionano in modo identico su tutti i browser. <add> <add>Se ti trovi nella situazione di avere bisogno dell'evento sottostante del browser per qualunque ragione, usa semplicemente l'attributo `nativeEvent` per ottenerlo. Ogni oggetto `SyntheticEvent` ha i seguenti attributi: <add> <add>```javascript <add>boolean bubbles <add>boolean cancelable <add>DOMEventTarget currentTarget <add>boolean defaultPrevented <add>number eventPhase <add>boolean isTrusted <add>DOMEvent nativeEvent <add>void preventDefault() <add>boolean isDefaultPrevented() <add>void stopPropagation() <add>boolean isPropagationStopped() <add>DOMEventTarget target <add>number timeStamp <add>string type <add>``` <add> <add>> Nota: <add>> <add>> A partire dalla v0.14, restituire `false` da un gestore di eventi non fermerà più la propagazione dell'evento. Invece, `e.stopPropagation()` o `e.preventDefault()` devono essere invocati manualmente, in maniera appropriata. <add> <add>## Riutilizzo degli eventi <add> <add>Gli oggetti `SyntheticEvent` sono gestiti come un pool. Ciò significa che ciascun oggetto `SyntheticEvent` sarà riutilizzato e tutte le sue proprietà annullate dopo che la callback dell'evento è stata invocata. <add>Ciò avviene per ragioni di performance. <add>Per questo motivo non potrai accedere all'evento in maniera asincrona. <add> <add>```javascript <add>function onClick(event) { <add> console.log(event); // => oggetto annullato. <add> console.log(event.type); // => "click" <add> var eventType = event.type; // => "click" <add> <add> setTimeout(function() { <add> console.log(event.type); // => null <add> console.log(eventType); // => "click" <add> }, 0); <add> <add> this.setState({clickEvent: event}); // Non funzionerà. this.state.clickEvent conterrà soltanto valori null. <add> this.setState({eventType: event.type}); // Puoi sempre esportare le singole proprietà dell'evento. <add>} <add>``` <add> <add>> Nota: <add>> <add>> Se vuoi accedere alle proprietà dell'evento in maniera asincrona, devi invocare `event.persist()` sull'evento, che rimuoverà l'evento sintetico dal pool e permetterà ai riferimenti all'evento di essere mantenuti nel codice dell'utente. <add> <add>## Eventi Supportati <add> <add>React normalizza gli eventi in modo che abbiano proprietà consistenti su browser differenti. <add> <add>I gestori di eventi seguenti sono scatenati da un evento nella fase di propagazione. Per registrare un gestore di eventi per la fase di cattura, aggiungi il suffisso `Capture` al nome dell'evento; ad esempio, anziché usare `onClick`, useresti `onClickCapture` per gestire l'evento click nella fase di cattura. <add> <add> <add>### Eventi della Clipboard <add> <add>Nomi degli eventi: <add> <add>``` <add>onCopy onCut onPaste <add>``` <add> <add>Proprietà: <add> <add>```javascript <add>DOMDataTransfer clipboardData <add>``` <add> <add> <add>### Eventi di Tastiera <add> <add>Nomi degli eventi: <add> <add>``` <add>onKeyDown onKeyPress onKeyUp <add>``` <add> <add>Proprietà: <add> <add>```javascript <add>boolean altKey <add>Number charCode <add>boolean ctrlKey <add>function getModifierState(key) <add>String key <add>Number keyCode <add>String locale <add>Number location <add>boolean metaKey <add>boolean repeat <add>boolean shiftKey <add>Number which <add>``` <add> <add> <add>### Eventi del Focus <add> <add>Nomi degli eventi: <add> <add>``` <add>onFocus onBlur <add>``` <add> <add>Proprietà: <add> <add>```javascript <add>DOMEventTarget relatedTarget <add>``` <add> <add> <add>### Eventi dei Moduli <add> <add>Nomi degli eventi: <add> <add>``` <add>onChange onInput onSubmit <add>``` <add> <add>Per maggiori informazioni sull'evento onChange, leggi [Moduli](/react/docs/forms.html). <add> <add> <add>### Eventi del Mouse <add> <add>Nomi degli eventi: <add> <add>``` <add>onClick onContextMenu onDoubleClick onDrag onDragEnd onDragEnter onDragExit <add>onDragLeave onDragOver onDragStart onDrop onMouseDown onMouseEnter onMouseLeave <add>onMouseMove onMouseOut onMouseOver onMouseUp <add>``` <add> <add>Gli eventi `onMouseEnter` e `onMouseLeave` vengono propagati dal componente che viene abbandonato a quello in cui viene effettuato l'ingresso anziché seguire la propagazione ordinaria, e non posseggono una fase di cattura. <add> <add>Proprietà: <add> <add>```javascript <add>boolean altKey <add>Number button <add>Number buttons <add>Number clientX <add>Number clientY <add>boolean ctrlKey <add>function getModifierState(key) <add>boolean metaKey <add>Number pageX <add>Number pageY <add>DOMEventTarget relatedTarget <add>Number screenX <add>Number screenY <add>boolean shiftKey <add>``` <add> <add> <add>### Eventi del Tocco <add> <add>Nomi degli eventi: <add> <add>``` <add>onTouchCancel onTouchEnd onTouchMove onTouchStart <add>``` <add> <add>Proprietà: <add> <add>```javascript <add>boolean altKey <add>DOMTouchList changedTouches <add>boolean ctrlKey <add>function getModifierState(key) <add>boolean metaKey <add>boolean shiftKey <add>DOMTouchList targetTouches <add>DOMTouchList touches <add>``` <add> <add> <add>### Eventi UI <add> <add>Nomi degli eventi: <add> <add>``` <add>onScroll <add>``` <add> <add>Proprietà: <add> <add>```javascript <add>Number detail <add>DOMAbstractView view <add>``` <add> <add> <add>### Eventi della Rotellina <add> <add>Nomi degli eventi: <add> <add>``` <add>onWheel <add>``` <add> <add>Proprietà: <add> <add>```javascript <add>Number deltaMode <add>Number deltaX <add>Number deltaY <add>Number deltaZ <add>``` <add> <add>### Eventi dei Media <add> <add>Nomi degli eventi: <add> <add>``` <add>onAbort onCanPlay onCanPlayThrough onDurationChange onEmptied onEncrypted onEnded onError onLoadedData onLoadedMetadata onLoadStart onPause onPlay onPlaying onProgress onRateChange onSeeked onSeeking onStalled onSuspend onTimeUpdate onVolumeChange onWaiting <add>``` <add> <add>### Eventi delle Immagini <add> <add>Nomi degli eventi: <add> <add>``` <add>onLoad onError <add>``` <ide><path>docs/docs/ref-06-dom-differences.it-IT.md <add>--- <add>id: dom-differences-it-IT <add>title: Differenze del DOM <add>permalink: dom-differences-it-IT.html <add>prev: events-it-IT.html <add>next: special-non-dom-attributes-it-IT.html <add>--- <add> <add>React ha implementato eventi indipendenti dal browser e un sistema DOM per ragioni di prestazioni e compatibilità cross-browser. Abbiamo colto l'occasione di dare una ripulita ad alcuni aspetti trascurati nelle implementazioni del DOM nei browser. <add> <add>* Tutte le proprietà e attributi del DOM (incluso i gestori di eventi) dovrebbero essere camelCased per essere consistenti con lo stile standard JavaScript. Abbiamo intenzionalmente deviato dalla specifica perché la specifica stessa è inconsistente. **Tuttavia**, gli attributi `data-*` e `aria-*` [sono conformi alle specifiche](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes#data-*) e dovrebbero essere soltanto in minuscolo. <add>* L'attributo `style` accetta un oggetto JavaScript con proprietà camelCased anziché una stringa CSS. Questo è consistente con la proprietà DOM `style` di JavaScript, è più efficiente, e previene falle nella sicurezza XSS. <add>* Tutti gli oggetti evento sono conformi con la specifica W3C, e tutti gli eventi (incluso il submit) si propagano correttamente secondo la specifica W3C. Consulta il [Sistema degli Eventi](/react/docs/events.html) per maggiori dettagli. <add>* L'evento `onChange` si comporta come ti aspetteresti: questo evento è emesso ogni qualvolta il valore di un campo di un modulo cambia anziché, in maniera inconsistente, quando il campo perde il focus. Abbiamo intenzionalmente deviato dal comportamento corrente dei browser perché `onChange` è un nome incorretto per questo comportamento e React dipende dall'emissione di questo evento in tempo reale in risposta all'input dell'utente. Leggi [Moduli](/react/docs/forms.html) per maggiori dettagli. <add>* Attributi dei campi di modulo come `value` e `checked`, oppure `textarea`. [Maggiori dettagli](/react/docs/forms.html). <ide><path>docs/docs/ref-07-special-non-dom-attributes.it-IT.md <add>--- <add>id: special-non-dom-attributes-it-IT <add>title: Attributi Speciali Non-DOM <add>permalink: special-non-dom-attributes-it-IT.html <add>prev: dom-differences-it-IT.html <add>next: reconciliation-it-IT.html <add>--- <add> <add>Oltre alle [Differenze del DOM](/react/docs/dom-differences.html), React offre alcuni attributi che semplicemente non esistono nel DOM. <add> <add>- `key`: un identificatore univoco opzionale. Quando il tuo componente viene riordinato durante i passaggi di `render`, potrebbe essere distrutto e ricreato in base all'algoritmo di calcolo delle differenze. Assegnargli una chiave che persiste assicura che il componente venga preservato. Scopri maggiori dettagli [qui](/react/docs/multiple-components.html#dynamic-children). <add>- `ref`: leggi [qui](/react/docs/more-about-refs.html). <add>- `dangerouslySetInnerHTML`: Offre l'abilità di inserire HTML grezzo, principalmente per cooperare con librerie di manipolazione di stringhe DOM. Scopri maggiori dettagli [qui](/react/tips/dangerously-set-inner-html.html). <ide><path>docs/docs/ref-08-reconciliation.it-IT.md <add>--- <add>id: reconciliation-it-IT <add>title: Riconciliazione <add>permalink: reconciliation-it-IT.html <add>prev: special-non-dom-attributes-it-IT.html <add>next: glossary-it-IT.html <add>--- <add> <add>La decisione chiave del design di React è fare in modo che l'API sembri ripetere il rendering dell'intera applicazione per ciascun aggiornamento. Ciò rende la scrittura delle applicazione molto più semplice, ma è anche una sfida incredibile per renderlo trattabile. Questo articolo spiega come siamo riusciti a trasformare, tramite potenti euristiche, un problema O(n<sup>3</sup>) in uno O(n). <add> <add> <add>## Motivazione <add> <add>Generare il minimo numero di operazioni necessarie a trasformare un albero in un altro è un problema complesso e ben noto. Gli [algoritmi dello stato dell'arte](http://grfia.dlsi.ua.es/ml/algorithms/references/editsurvey_bille.pdf) hanno una complessità dell'ordine di O(n<sup>3</sup>) dove n è il numero di nodi dell'albero. <add> <add>Ciò significa che visualizzare 1000 nodi richiederebbe un numero di confronti dell'ordine del miliardo. Ciò è decisamente troppo costoso per il nostro caso d'uso. Per mettere questo numero in prospettiva, le CPU oggi giorno eseguono approssimativamente 3 miliardi di istruzioni al secondo. Quindi anche con l'implementazione più efficiente, non saremmo in grado di calcolare la differenza in meno di un secondo. <add> <add>Dal momento che un algoritmo ottimo non è trattabile, implementiamo un algoritmo O(n) non ottimale usando euristiche basate su due assunzioni: <add> <add>1. Due componenti della stessa classe genereranno alberi simili e due componenti di classi diverse genereranno alberi diversi. <add>2. È possibile fornire una chiave unica per gli elementi che sia stabile durante rendering differenti. <add> <add>In pratica, queste assunzioni sono eccezionalmente veloci per quasi tutti i casi d'uso pratici. <add> <add> <add>## Differenza a coppie <add> <add>Per effettuare la differenza di due alberi, dobbiamo prima essere capaci di effettuare la differenza tra due nodi. Esistono tre diversi casi da considerare. <add> <add> <add>### Tipi di Nodo Differenti <add> <add>Se il tipo di nodo è differente, React li tratterà come due sottoalberi diversi, getterà via il primo e costruirà e inserirà il secondo. <add> <add>```xml <add>renderA: <div /> <add>renderB: <span /> <add>=> [removeNode <div />], [insertNode <span />] <add>``` <add> <add>La stessa logica è usata per i componenti personalizzati. Se non sono dello stesso tipo, React non proverà neppure a confrontare ciò che visualizzano. Rimuoverà soltanto il primo dal DOM e inserirà il secondo. <add> <add>```xml <add>renderA: <Header /> <add>renderB: <Content /> <add>=> [removeNode <Header />], [insertNode <Content />] <add>``` <add> <add>Possedere questa conoscenza di alto livello è un aspetto molto importante del perché l'algoritmo di differenza di React è sia veloce che preciso. Ciò fornisce una buona euristica per potare rapidamente gran parte dell'albero e concentrarsi su parti che hanno una buona probabilità di essere simili. <add> <add>È molto improbabile che un elemento `<Header>` generi un DOM che somigli a quello generato da un elemento `<Content>`. Anziché perdere tempo provando a confrontare queste due strutture, React semplicemente ricostruisce l'albero da zero. <add> <add>Come corollario, se c'è un elemento `<Header>` nella stessa posizione in due rendering consecutivi, ti puoi aspettare di trovare una struttura molto simile che vale la pena di esplorare. <add> <add> <add>### Nodi DOM <add> <add>Quando vengono confrontati nodi DOM, guardiamo gli attributi di entrambi e decidiamo quali di essi sono cambiati in un tempo lineare. <add> <add>```xml <add>renderA: <div id="before" /> <add>renderB: <div id="after" /> <add>=> [replaceAttribute id "after"] <add>``` <add> <add>Anziché trattare lo stile come una stringa opaca, viene rappresentato come un oggetto chiave-valore. Ciò ci permette di aggiornare solo le proprietà che sono cambiate. <add> <add>```xml <add>renderA: <div style={{'{{'}}color: 'red'}} /> <add>renderB: <div style={{'{{'}}fontWeight: 'bold'}} /> <add>=> [removeStyle color], [addStyle font-weight 'bold'] <add>``` <add> <add>Dopo che gli attributi sono stati aggiornati, effettuiamo un confronto ricorsivo su ciascuno dei nodi figli. <add> <add> <add>### Componenti Personalizzati <add> <add>We decided that the two custom components are the same. Since components are stateful, we cannot just use the new component and call it a day. React takes all the attributes from the new component and calls `component[Will/Did]ReceiveProps()` on the previous one. <add> <add>The previous component is now operational. Its `render()` method is called and the diff algorithm restarts with the new result and the previous result. <add> <add> <add>## List-wise diff <add> <add>### Problematic Case <add> <add>In order to do children reconciliation, React adopts a very naive approach. It goes over both lists of children at the same time and generates a mutation whenever there's a difference. <add> <add>For example if you add an element at the end: <add> <add>```xml <add>renderA: <div><span>first</span></div> <add>renderB: <div><span>first</span><span>second</span></div> <add>=> [insertNode <span>second</span>] <add>``` <add> <add>Inserting an element at the beginning is problematic. React is going to see that both nodes are spans and therefore run into a mutation mode. <add> <add>```xml <add>renderA: <div><span>first</span></div> <add>renderB: <div><span>second</span><span>first</span></div> <add>=> [replaceAttribute textContent 'second'], [insertNode <span>first</span>] <add>``` <add> <add>There are many algorithms that attempt to find the minimum sets of operations to transform a list of elements. [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance) can find the minimum using single element insertion, deletion and substitution in O(n<sup>2</sup>). Even if we were to use Levenshtein, this doesn't find when a node has moved into another position and algorithms to do that have much worse complexity. <add> <add>### Keys <add> <add>In order to solve this seemingly intractable issue, an optional attribute has been introduced. You can provide for each child a key that is going to be used to do the matching. If you specify a key, React is now able to find insertion, deletion, substitution and moves in O(n) using a hash table. <add> <add> <add>```xml <add>renderA: <div><span key="first">first</span></div> <add>renderB: <div><span key="second">second</span><span key="first">first</span></div> <add>=> [insertNode <span>second</span>] <add>``` <add> <add>In practice, finding a key is not really hard. Most of the time, the element you are going to display already has a unique id. When that's not the case, you can add a new ID property to your model or hash some parts of the content to generate a key. Remember that the key only has to be unique among its siblings, not globally unique. <add> <add> <add>## Trade-offs <add> <add>It is important to remember that the reconciliation algorithm is an implementation detail. React could re-render the whole app on every action; the end result would be the same. We are regularly refining the heuristics in order to make common use cases faster. <add> <add>In the current implementation, you can express the fact that a sub-tree has been moved amongst its siblings, but you cannot tell that it has moved somewhere else. The algorithm will re-render that full sub-tree. <add> <add>Because we rely on two heuristics, if the assumptions behind them are not met, performance will suffer. <add> <add>1. The algorithm will not try to match sub-trees of different components classes. If you see yourself alternating between two components classes with very similar output, you may want to make it the same class. In practice, we haven't found this to be an issue. <add> <add>2. If you don't provide stable keys (by using Math.random() for example), all the sub-trees are going to be re-rendered every single time. By giving the users the choice to choose the key, they have the ability to shoot themselves in the foot. <ide><path>docs/docs/ref-09-glossary.it-IT.md <add>--- <add>id: glossary-it-IT <add>title: Terminologia del DOM (Virtuale) <add>permalink: glossary-it-IT.html <add>prev: reconciliation-it-IT.html <add>--- <add> <add>Nella terminologia di React, esistono cinque tipi base che è importante distinguere: <add> <add>- [ReactElement / ReactElement Factory](#react-elements) <add>- [ReactNode](#react-nodes) <add>- [ReactComponent / ReactComponent Class](#react-components) <add> <add>## Elementi React <add> <add>Il tipo primario in React è il `ReactElement`. Possiede quattro proprietà: `type`, `props`, `key` e `ref`. Non possiede alcun metodo e non espone nulla sul prototype. <add> <add>Puoi creare uno di questi oggetti attraverso `React.createElement`. <add> <add>```javascript <add>var root = React.createElement('div'); <add>``` <add> <add>Per effettuare il rendering di un nuovo albero nel DOM, crei dei `ReactElement` ande li passi a `React.render` assieme a un `Element` DOM regolare (`HTMLElement` o `SVGElement`). I `ReactElement` non vanno confusi con gli `Element` del DOM. Un `ReactElement` è una rappresentazione leggera, priva di stato, immutabile e virtuale di un `Element` del DOM. È un DOM virtuale. <add> <add>```javascript <add>React.render(root, document.getElementById('example')); <add>``` <add> <add>Per aggiungere proprietà ad un elemento DOM, passa un oggetto di proprietà come secondo argomento, e i figli come terzo argomento. <add> <add>```javascript <add>var child = React.createElement('li', null, 'Contenuto di Testo'); <add>var root = React.createElement('ul', { className: 'my-list' }, child); <add>React.render(root, document.getElementById('example')); <add>``` <add> <add>Se usi React JSX, allora questi `ReactElement` verranno creati per te. Questa espressione è equivalente: <add> <add>```javascript <add>var root = <ul className="my-list"> <add> <li>Contenuto di Testo</li> <add> </ul>; <add>React.render(root, document.getElementById('example')); <add>``` <add> <add>### Le Factory <add> <add>Una factory di `ReactElement` è semplicemente una funzione che genera un `ReactElement` con una particolare proprietà `type`. React ha uno helper integrato per permetterti di creare factory. La sua implementazione è semplicemente: <add> <add>```javascript <add>function createFactory(type) { <add> return React.createElement.bind(null, type); <add>} <add>``` <add> <add>Ti permette di creare una conveniente scorciatoia anziché scrivere ogni volta `React.createElement('div')`. <add> <add>```javascript <add>var div = React.createFactory('div'); <add>var root = div({ className: 'my-div' }); <add>React.render(root, document.getElementById('example')); <add>``` <add> <add>React possiede già factory integrate per tag HTML comuni: <add> <add>```javascript <add>var root = React.DOM.ul({ className: 'my-list' }, <add> React.DOM.li(null, 'Contenuto di Testo') <add> ); <add>``` <add> <add>Se stai usando JSX non hai bisogno di factory. JSX fornisce già una conveniente scorciatoia per creare `ReactElement`. <add> <add> <add>## Nodi React <add> <add>Un `ReactNode` può essere uno tra: <add> <add>- `ReactElement` <add>- `string` (ovvero `ReactText`) <add>- `number` (ovvero `ReactText`) <add>- Array di `ReactNode` (ovvero `ReactFragment`) <add> <add>Questi sono usati come proprietà di altri `ReactElement` per rappresentare i figli. Effettivamente creano un albero di `ReactElement`. <add> <add> <add>## Componenti React <add> <add>Puoi usare React usando soltanto `ReactElement`, ma per avvantaggiarti seriamente di React vorrai usare i `ReactComponent` per creare incapsulamento con uno stato incluso. <add> <add>Una classe `ReactComponent` è semplicemente una classe JavaScript (o una "funzione costruttore"). <add> <add>```javascript <add>var MyComponent = React.createClass({ <add> render: function() { <add> ... <add> } <add>}); <add>``` <add> <add>Quando questo costruttore è invocato, ci si aspetta che restituisca un oggetto con almeno un metodo `render`. Questo oggetto è chiamato `ReactComponent`. <add> <add>```javascript <add>var component = new MyComponent(props); // non farlo mai! <add>``` <add> <add>Per scopi diversi dai test, *non chiamerai mai* questo costruttore direttamente. React lo chiamerà per te. <add> <add>Invece, passa una classe `ReactComponent` a `createElement` per ottenere un `ReactElement`. <add> <add>```javascript <add>var element = React.createElement(MyComponent); <add>``` <add> <add>OPPURE usando JSX: <add> <add>```javascript <add>var element = <MyComponent />; <add>``` <add> <add>Quando `element` viene passato a `React.render`, React chiamerà il costruttore al tuo posto e creerà un`ReactComponent`, che verrà restituito. <add> <add>```javascript <add>var component = React.render(element, document.getElementById('example')); <add>``` <add> <add>Se chiami ripetutamente `React.render` con lo stesso tipo di `ReactElement` e lo stesso `Element` DOM come contenitore, ti restituirà sempre la stessa istanza. Questa istanza è dotata di stato. <add> <add>```javascript <add>var componentA = React.render(<MyComponent />, document.getElementById('example')); <add>var componentB = React.render(<MyComponent />, document.getElementById('example')); <add>componentA === componentB; // true <add>``` <add> <add>Questo è il motivo per cui non dovresti mai costruire la tua istanza. Invece, `ReactElement` è un `ReactComponent` virtuale prima che venga costruito. Un vecchio `ReactElement` e uno nuovo possono essere confrontati per vedere se una nuova istanza di `ReactComponent` è stata creata o quella esistente è stata riutilizzata. <add> <add>Ci si aspetta che il metodo `render` di un `ReactComponent` restituisca un altro `ReactElement`. Ciò permette a questi componenti di essere composti. In ultima analisi, il rendering si risolve in un `ReactElement` con un tag `string` che viene istanziato come un `Element` DOM e viene inserito nel documento. <add> <add> <add>## Definizioni Formali dei Tipi <add> <add>### Punto di Entrata <add> <add>``` <add>React.render = (ReactElement, HTMLElement | SVGElement) => ReactComponent; <add>``` <add> <add>### Nodi ed Elementi <add> <add>``` <add>type ReactNode = ReactElement | ReactFragment | ReactText; <add> <add>type ReactElement = ReactComponentElement | ReactDOMElement; <add> <add>type ReactDOMElement = { <add> type : string, <add> props : { <add> children : ReactNodeList, <add> className : string, <add> etc. <add> }, <add> key : string | boolean | number | null, <add> ref : string | null <add>}; <add> <add>type ReactComponentElement<TProps> = { <add> type : ReactClass<TProps>, <add> props : TProps, <add> key : string | boolean | number | null, <add> ref : string | null <add>}; <add> <add>type ReactFragment = Array<ReactNode | ReactEmpty>; <add> <add>type ReactNodeList = ReactNode | ReactEmpty; <add> <add>type ReactText = string | number; <add> <add>type ReactEmpty = null | undefined | boolean; <add>``` <add> <add>### Classi e Componenti <add> <add>``` <add>type ReactClass<TProps> = (TProps) => ReactComponent<TProps>; <add> <add>type ReactComponent<TProps> = { <add> props : TProps, <add> render : () => ReactElement <add>}; <add>``` <ide><path>docs/docs/thinking-in-react.it-IT.md <add>--- <add>id: thinking-in-react-it-IT <add>title: Pensare in React <add>prev: tutorial-it-IT.html <add>next: conferences-it-IT.html <add>redirect_from: 'blog/2013/11/05/thinking-in-react.html' <add>--- <add> <add>di Pete Hunt <add> <add>React è, a mio parere, la maniera più adeguata di costruire veloci applicazioni Web di grandi dimensioni con JavaScript. Ha scalato molto bene per noi a Facebook e Instagram. <add> <add>Una delle molte parti migliori di React è come ti fa pensare alle applicazioni mentre le costruisci. In questo articolo vi guiderò attraverso il processo di pensiero per la costruzione di una tabella di dati di prodotti che possono essere cercati usando React. <add> <add>## Comincia con un mock <add> <add>Immagina di possedere già una API JSON e un mock prodotto dai nostri designer. I nostri designer apparentemente non sono molto capaci perché il mock ha questo aspetto: <add> <add>![Mockup](/react/img/blog/thinking-in-react-mock.png) <add> <add>La nostra API JSON restituisce dei dati che somigliano a quanto segue: <add> <add>``` <add>[ <add> {category: "Sporting Goods", price: "$49.99", stocked: true, name: "Football"}, <add> {category: "Sporting Goods", price: "$9.99", stocked: true, name: "Baseball"}, <add> {category: "Sporting Goods", price: "$29.99", stocked: false, name: "Basketball"}, <add> {category: "Electronics", price: "$99.99", stocked: true, name: "iPod Touch"}, <add> {category: "Electronics", price: "$399.99", stocked: false, name: "iPhone 5"}, <add> {category: "Electronics", price: "$199.99", stocked: true, name: "Nexus 7"} <add>]; <add>``` <add> <add>## Passo 1: suddividi la UI in una gerarchia di componenti <add> <add>La prima azione che vorrai compiere è disegnare dei rettangoli attorno a ciascun componente (e subcomponenti) nel mock e dare un nome a ciascuno di essi. Se stai lavorando con i designer, potrebbero averlo già fatto, quindi parla anzitutto con loro! I nomi dei loro layer di Photoshop potrebbero finire per diventare i nomi dei tuoi componenti React! <add> <add>Come fai tuttavia a sapere cosa dovrebbe essere un componente a sé? Usa una delle tecniche per decidere se devi creare un nuovo oggetto o una nuova funzione. Una di tali tecniche è il [principio della singola responsibilità](https://en.wikipedia.org/wiki/Single_responsibility_principle), ovvero, un componente dovrebbe idealmente servire a un solo scopo. Se finisce per crescere, dovrebbe essere decomposto in componenti più piccoli. <add> <add>Dal momento che stai spesso mostrando un modello di dati JSON all'utente, ti accorgerai che se il tuo modello è stato costruito correttamente, la tua UI (e quindi anche la struttura dei tuoi componenti) si adatterà facilmente. Ciò accade perché le UI e i modelli di dati tendono ad aderire alla medesima *architettura dell'informazione*, che significa che il compito di separare la tua UI in componenti è spesso banale. Suddividila semplicemente in componenti che rappresentano esattamente un frammento del tuo modello di dati. <add> <add>![Diagramma dei componenti](/react/img/blog/thinking-in-react-components.png) <add> <add>Vedrai che abbiamo in tutto cinque componenti nella nostra semplice applicazione. Ho scritto in corsivo i dati che ciascun componente rappresenta. <add> <add> 1. **`FilterableProductTable` (arancione):** contiene l'intero esempio <add> 2. **`SearchBar` (blu):** riceve tutti gli *input dell'utente* <add> 3. **`ProductTable` (verde):** mostra e filtra la *collezione dei dati* basandosi sull'*input dell'utente* <add> 4. **`ProductCategoryRow` (turchese):** mostra un titolo per ciascuna *categoria* <add> 5. **`ProductRow` (rosso):** mostra una riga per ciascun *prodotto* <add> <add>Se osservi la `ProductTable`, ti accorgerai che l'intestazione della tabella (che contiene le etichette "Name" e "Price") non è un componente a sé. Questa è una questione di gusti, e ci sono ragioni valide per ciascun approccio. Per questo esempio, l'ho lasciata parte di `ProductTable` perché fa parte della visualizzazione della *collezione dei dati* che è la responsabilità di `ProductTable`. Tuttavia, se questa intestazione cresce fino a diventare complessa (cioè se dovessimo aggiungere la possibilità di riordinare i dati), avrebbe certamente senso renderla un componente `ProductTableHeader` a sé. <add> <add>Adesso che abbiamo identificato i componenti nel nostro mock, organizziamoli in una gerarchia. Questo è un compito facile. I componenti che appaiono all'interno di un altro componente nel the mock devono apparire come figli nella gerarchia: <add> <add> * `FilterableProductTable` <add> * `SearchBar` <add> * `ProductTable` <add> * `ProductCategoryRow` <add> * `ProductRow` <add> <add>## Passo 2: Costruisci una versione statica in React <add> <add><iframe width="100%" height="300" src="https://jsfiddle.net/reactjs/yun1vgqb/embedded/" allowfullscreen="allowfullscreen" frameborder="0"></iframe> <add> <add>Adesso che hai la tua gerarchia di componenti, è venuto il momento di implementare la tua applicazione. La maniera più semplice è costruire una versione che prende il tuo modello di dati e visualizza la UI ma non è interattiva. È buona norma disaccoppiare questi processi perché costruire una versione statica richiede la scrittura di parecchio codice e poco pensare, mentre aggiungere l'interattività richiede un parecchio pensare ma non un granché di scrittura. Vedremo perché. <add> <add>Per costruire una versione statica della tua applicazione dhe visualizzi il tuo modello dei dati, vorrai costruire componenti che riutilizano altri componenti e passano loro dati usando le *props*. Le *props* sono una maniera di passare dati da genitore a figlio. Se hai dimestichezza con il concetto di *state*, **non usare lo stato** per costruire questa versione statica. Lo stato è riservato solo per l'interattività, cioè dati che cambiano nel tempo. Dal momento che questa è una versione statica dell'applicazione, non ne avrai bisogno. <add> <add>Puoi costruire dall'alto in basso, o dal basso in alto. Ovvero, puoi cominciare a costruire i componenti più in alto nella gerarchia (cioè cominciare con `FilterableProductTable`) oppure con quelli più in basso (`ProductRow`). In esempi più semplici, è solitamente più facile andare dall'alto in basso, mentre in progetti più grandi è più facile andare dal basso in alto e scrivere test mentre costruisci. <add> <add>Alla fine di questo passo avrai una libreria di componenti riutilizzabili che visualizzano il tuo modello dati. I componenti avranno soltanto metodi `render()` dal momento che questa è una versione statica della tua applicazione. Il componente al vertice della gerarchia (`FilterableProductTable`) prenderà il tuo modello dati come una proprietà. Se apporti un cambiamento al tuo modello dati sottostante e chiami nuovamente `React.render()`, la UI sarà aggiornata. È facile vedere come la tua UI viene aggiornata e dove applicare cambiamenti dal momento che non c'è nulla di complicato. Il **flusso dati unidirezionale** di React (detto anche *binding unidirezionale*) mantiene tutto modulare e veloce. <add> <add>Fai riferimento alla [documentazione React](/react/docs/) se hai bisogno di aiuto nell'eseguire questo passo. <add> <add>### Un breve intermezzo: proprietà oppure stato <add> <add>Esistono due tipi di dati "modello" in React: proprietà e stato. È importante capire la distinzione tra i due; scorri [la documentazione ufficiale di React](/react/docs/interactivity-and-dynamic-uis.html) se non hai ben chiara la differenza. <add> <add>## Passo 3: Identifica la rappresentazione minima (ma completa) dello stato della UI <add> <add>Per rendere la tua UI interattiva, hai bisogno di poter scatenare cambiamenti al tuo modello dati sottostante. React lo rende facile tramite lo **stato**. <add> <add>Per costruire correttamente la tua applicaizone, devi prima pensare all'insieme minimo di stato mutevole di cui la tua applicazione ha bisogno. La chiave qui è il principio DRY: *Don't Repeat Yourself (Non ripeterti)*. Una volta compresa la rappresentazione minima in assoluto dello stato della tua applicazione e calcola tutto lil resto sul momento. Ad esempio, se stai costruendo una lista di cose da fare, mantieni un array delle cose da fare; non tenere una variabile di stato separata per il conteggio. Invece, quando vuoi visualizzare il conteggio degli elementi, prendi semplicemente la lunghezza dell'arraiy delle cose da fare. <add> <add>Pensa a tutti gli elementi di dati nella nostra applicazione di esempio. Abbiamo: <add> <add> * La lista originaria dei prodotti <add> * Il testo di ricerca che l'utente ha introdotto <add> * Il valore del checkbox <add> * La lista filtrata dei prodotti <add> <add>Rivediamo ciascuno di essi e capiamo se si tratta di stato. Chiediti queste tre semplici domande su ciascun elemento di dati: <add> <add> 1. Viene passato da un genitore attraverso le proprietà? Se sì, probabilmente non è stato. <add> 2. Cambia nel tempo? Se no, probabilmente non è stato. <add> 3. Puoi calcolarlo basandoti su altro stato o proprietà del tuo componente? Se sì, non è stato. <add> <add>La lista originaria di prodotti viene passata come proprietà, quindi non si tratta di stato. Il testo di ricerca e la checkbox sembrano essere stato perché cambiano nel tempo e non possono essere ricavate da altri dati. Infine, la lista filtrata di prodotti non è stato, perché può essere calcolata combinando la lista originaria dei prodotti con il testo di ricerca e il valore della checkbox. <add> <add>Quindi, per concludere, il nostro stato è: <add> <add> * Il testo di ricerca che l'utente ha introdotto <add> * Il valore del checkbox <add> <add>## Passo 4: Identifica dove debba risiedere il tuo stato <add> <add><iframe width="100%" height="300" src="https://jsfiddle.net/reactjs/zafjbw1e/embedded/" allowfullscreen="allowfullscreen" frameborder="0"></iframe> <add> <add>OK, abbiamo dunque identificato quale sia l'insieme minimo dello stato dell'applicazione. Successivamente, dobbiamo identificare quale componente muta, o *possiede*, questo stato. <add> <add>Ricorda: React è basato esclusivamente su flusso dati unidirezionale verso il basso della gerarchia dei componenti. Potrebbe non essere immediatamente chiaro quale componente debba possedere quale stato. **Questa è spesso la parte più difficile da capire per i principianti,** quindi segui questi passi per capirlo: <add> <add>Per ogni elemento dello stato nella tua applicazione: <add> <add> * Identifica ciascun componente che visualizza qualcosa basato su quello stato. <add> * Trova un componente proprietario comune (un singolo componente più in alto nella gerarchia di ciascun componente che ha bisogno dello stato). <add> * Il proprietario comune o un altro componente più in alto nella gerarchia deve possedere lo stato. <add> * Se non riesci a trovare un componente per cui abbia senso possedere lo stato, crea un nuovo componente con il solo scopo di contenere lo stato e aggiungilo da qualche parte nella gerarchia sopra il componente proprietario comune. <add> <add>Applichiamo questa strategia per la nostra applicazione: <add> <add> * `ProductTable` deve filtrare la lista dei prodotti basandosi sullo stato e `SearchBar` deve visualizzare il testo di ricerca e lo stato della checkbox. <add> * Il componente proprietario comune è `FilterableProductTable`. <add> * Ha concettualmente senso che il testo di ricerca e lo stato della checkbox appartengano a `FilterableProductTable` <add> <add>Bene, abbiamo deciso che il nostro stato appartenga a `FilterableProductTable`. Anzitutto aggiungiamo un metodo `getInitialState()` a `FilterableProductTable` che restituisce `{filterText: '', inStockOnly: false}` per riflettere lo stato iniziale della tua applicazione. Dunque, passiamo `filterText` e `inStockOnly` a `ProductTable` e `SearchBar` come una proprietà. Infine, usiamo queste proprietà per filtrare le righe in `ProductTable` e impostare i valori dei campi del modulo in `SearchBar`. <add> <add>Puoi cominciare a vedere come si comporterà la tua applicazione: imposta `filterText` a `"ball"` e aggiorna la tua applicazione. Vedrai che la tabella dei dati è correttamente aggiornata. <add> <add>## Passo 5: Aggiungi il flusso dati inverso <add> <add><iframe width="100%" height="300" src="https://jsfiddle.net/reactjs/n47gckhr/embedded/" allowfullscreen="allowfullscreen" frameborder="0"></iframe> <add> <add>Finora abbiamo costruito un'applicazione che visualizza correttamente come una funzione di proprietà e stato che fluiscono verso il basso della gerarchia. Adesso è il momento di supportare il flusso dei dati nella direzione opposta: i componenti del modulo in profondità nella gerarchia devono aggiornare lo stato in `FilterableProductTable`. <add> <add>React rende questo flusso dati esplicito per rendere più semplice la comprensione di come funziona la tua applicazione, ma richiede leggermente più codice di un tradizionale binding bidirezionale dei dati. React offre un add-on chiamato `ReactLink` per rendere questo pattern altrettanto conveniente del binding bidirezionale ma, per gli scopi di questo articolo, faremo tutto in modo esplicito. <add> <add>Se provi a scrivere o spunti la casella nella versione attuale dell'esempio, vedrai che React ignora il tuo input. Questo è un comportamento intenzionale, in quanto abbiamo impostato la proprietà `value` del campo `input` perché sia sempre uguale al valore di `state` passato da `FilterableProductTable`. <add> <add>Pensiamo a cosa vogliamo che accada. Vogliamo assicurarci che quando l'utente cambia il modulo noi aggiorniamo lo stato per riflettere l'input dell'utente. Dal momento che i componenti devono soltanto aggiornare il proprio stato, `FilterableProductTable` passerà una callback a `SearchBar` che sarà eseguita quando lo stato debba essere aggiornato. Possiamo utilizzare l'evento `onChange` sui campi di input per esserne notificati. E la callback passata da `FilterableProductTable` chiamerà `setState()`, e l'applicazione verrà aggiornata. <add> <add>Anche se sembra complesso, si tratta realmente di poche righe di codice. Inoltre, il flusso dati attraverso l'applicazione è davvero esplicito. <add> <add>## Tutto qui <add> <add>Speriamo che questo ti abbia dato un'idea di come pensare a costruire componenti e applicazioni con React. Mentre potrebbe richiedere leggermente più codice di quanto si sia abituati a scrivere, ricorda che il codice è letto più spesso di quanto sia scritto, ed è estremamente facile leggere codice così esplicito e modulare. Mentre ti avvii a costruire grandi librerie di componenti, apprezzerai questa chiarezza e modularità, e con il riutilizzo del codice le tue righe di codice cominceranno a ridursi. :) <ide><path>docs/docs/tutorial.it-IT.md <add>--- <add>id: tutorial-it-IT <add>title: Tutorial <add>prev: getting-started-it-IT.html <add>next: thinking-in-react-it-IT.html <add>--- <add> <add>Costruiremo una semplice ma realistica casella dei commenti che puoi inserire in un blog, una versione base dei commenti in tempo reale offerti da Disqus, LiveFyre o Facebook. <add> <add>Forniremo: <add> <add>* Una vista di tutti i commenti <add>* Un modulo per inviare un commento <add>* Hook perché tu fornisca un backend personalizzato <add> <add>Avrà anche un paio di caratteristiche interessanti: <add> <add>* **Commenti ottimistici:** i commenti appaiono nella lista prima che vengano salvati sul server, in modo da sembrare più veloce. <add>* **Aggiornamenti in tempo reale:** i commenti degli altri utenti sono aggiunti alla vista dei commenti in tempo reale. <add>* **Formattazione Markdown:** gli utenti possono utilizzare il Markdown per formattare il proprio testo. <add> <add>### Vuoi saltare tutto questo e vedere semplicemente il sorgente? <add> <add>[It's all on GitHub.](https://github.com/reactjs/react-tutorial) <add> <add>### Eseguire un server <add> <add>Per cominciare questo tutorial dobbiamo richiedere un server in esecuzione. Questo servirà puramente come un endpoint per le API che useremo per ottenere e salvare i dati. Per rendere questo compito il più semplice possibile, abbiamo creato un seplice server in un numero di linguaggi di scripting che fa esattamente ciò che ci serve. **Puoi [leggere il sorgente](https://github.com/reactjs/react-tutorial/) o [scaricare un file zip](https://github.com/reactjs/react-tutorial/archive/master.zip) contenente tutto ciò che ti serve per cominciare.** <add> <add>Per semplicità, il server che eseguiremo usa un file `JSON` come database. Non è ciò che eseguiresti in produzione, ma rende più facile simulare ciò che faresti per consumare una API. Non appena avvii il server, supporterà il nostro endpoint API e servirà anche le pagine statiche di cui abbiamo bisogno. <add> <add>### Per Cominciare <add> <add>Per questo tutorial renderemo il tutto il più semplice possibile. Incluso nel pacchetto del server discusso in precedenza si trova un file HTML su cui lavoreremo. Apri `public/index.html` nel tuo editor preferito. Dovrebbe apparire simile a quanto segue (con qualche piccola differenza, aggiungeremo un tag `<script>` aggiuntivo in seguito): <add> <add>```html <add><!-- index.html --> <add><!DOCTYPE html> <add><html> <add> <head> <add> <meta charset="utf-8" /> <add> <title>React Tutorial</title> <add> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/{{site.react_version}}/react.js"></script> <add> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script> <add> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <add> </head> <add> <body> <add> <div id="content"></div> <add> <script type="text/babel" src="scripts/example.js"></script> <add> <script type="text/babel"> <add> // To get started with this tutorial running your own code, simply remove <add> // the script tag loading scripts/example.js and start writing code here. <add> </script> <add> </body> <add></html> <add>``` <add> <add>Nel resto di questo tutorial, scriveremo il nostro codice JavaScript in questo tag script. Non disponiamo di alcun aggiornamento in tempo reale avanzato, quindi dovremo aggiornare il browser per vedere gli aggiornamenti dopo il salvataggio. Segui il tuo progresso aprendo `http://localhost:3000` nel tuo browser (dopo aver avviato il server). Quando carichi la pagina per la prima volta senza apportare cambiamenti, vedrai il risultato finale di ciò che ci apprestiamo a costruire. Quando sei pronto per cominciare a lavorare, elimina il tag `<script>` precedente e quindi sei pronto a continuare. <add> <add>> Nota: <add>> <add>> Abbiamo incluso jQuery perché vogliamo semplificare il codice delle nostre chiamate ajax future, ma **NON** è richiesto per far funzionare React. <add> <add>### Il tuo primo componente <add> <add>In React ciò che importa sono i componenti modulari e componibili. Per il nostro esempio della casella dei commenti, avremo la seguente struttura dei componenti: <add> <add>``` <add>- CommentBox <add> - CommentList <add> - Comment <add> - CommentForm <add>``` <add> <add>Costruiamo il componente `CommentBox`, che consiste in un semplice `<div>`: <add> <add>```javascript <add>// tutorial1.js <add>var CommentBox = React.createClass({ <add> render: function() { <add> return ( <add> <div className="commentBox"> <add> Ciao, mondo! Sono un CommentBox. <add> </div> <add> ); <add> } <add>}); <add>React.render( <add> <CommentBox />, <add> document.getElementById('content') <add>); <add>``` <add> <add>Nota che i nomi degli elementi nativi HTML cominciano con una lettera minuscola, mentre i nomi di classe personalizzati di React cominciano con una lettera maiuscola. <add> <add>#### Sintassi JSX <add> <add>La prima cosa che noterai è la sintassi simile a XML nel tuo JavaScript. Abbiamo un semplice preprocessore che traduce lo zucchero sintattico a questo semplice JavaScript: <add> <add>```javascript <add>// tutorial1-raw.js <add>var CommentBox = React.createClass({displayName: 'CommentBox', <add> render: function() { <add> return ( <add> React.createElement('div', {className: "commentBox"}, <add> "Ciao, mondo! Sono un CommentBox." <add> ) <add> ); <add> } <add>}); <add>React.render( <add> React.createElement(CommentBox, null), <add> document.getElementById('content') <add>); <add>``` <add> <add>Il suo uso è opzionale ma abbiamo trovato la sintassi JSX più facile da usare del semplice JavaScript. Leggi maggiori dettagli sull'[articolo sulla sintassi JSX](/react/docs/jsx-in-depth.html). <add> <add>#### Cosa sta succedendo? <add> <add>Passiamo dei metodi in un oggetto JavaScript a `React.createClass()` per creare un nuovo componente React. Il più importante di questi metodi è chiamato `render` il quale restituisce un albero di componenti React che saranno eventualmente visualizzati come HTML. <add> <add>I tag `<div>` non sono veri nodi DOM; sono istanze dei componenti React `div`. Puoi pensare a questi come marcatori o a elementi di dati che React sa come gestire. React è **sicuro**. Non stiamo generando stringhe HTML quindi la protezione XSS è predefinita. <add> <add>Non devi necessariamente restituire semplice HTML. Puoi anche restituire un albero di componenti costruiti da te (o da qualcun altro). Questo è ciò che rende React **componibile**: una caratteristica chiave dei front-end manutenibili. <add> <add>`React.render()` istanzia il componente radice, avvia il framework, e inietta il markup in un elemento DOM nativo, fornito come secondo argomento. <add> <add>## Comporre componenti <add> <add>Costruiamo degli scheletri per `CommentList` e `CommentForm` che saranno, nuovamente, dei semplici `<div>`. Aggiungi questi due componenti al tuo file, mantenendo la dichiarazione esistente di `CommentBox` e la chiamata a `React.render`: <add> <add>```javascript <add>// tutorial2.js <add>var CommentList = React.createClass({ <add> render: function() { <add> return ( <add> <div className="commentList"> <add> Hello, world! I am a CommentList. <add> </div> <add> ); <add> } <add>}); <add> <add>var CommentForm = React.createClass({ <add> render: function() { <add> return ( <add> <div className="commentForm"> <add> Hello, world! I am a CommentForm. <add> </div> <add> ); <add> } <add>}); <add>``` <add> <add>Successivamente, aggiorna il componente `CommentBox` per utilizzare questi due nuovi componenti: <add> <add>```javascript{6-8} <add>// tutorial3.js <add>var CommentBox = React.createClass({ <add> render: function() { <add> return ( <add> <div className="commentBox"> <add> <h1>Commenti</h1> <add> <CommentList /> <add> <CommentForm /> <add> </div> <add> ); <add> } <add>}); <add>``` <add> <add>Nota come stiamo mescolando tag HTML e i componenti che abbiamo costruito. I componenti HTML sono componenti regolari React, proprio come quelli che definisci, con una differenza. Il compilatore JSX riscriverà automaticamente i tag HTML come espressioni `React.createElement(tagName)` e lascerà tutto il resto inalterato. Questo è per impedire che il namespace globale venga inquinato. <add> <add>### Usare le proprietà <add> <add>Creiamo il componente `Comment`, che dipenderà dai dati passatigli dal suo genitore. I dati passati da un componente genitore sono disponibili come una 'proprietà' nel componente figlio. Queste 'proprietà' sono accessibili attraverso `this.props`. Usando le proprietà, saremo in grado di leggere i dati passati al componente `Comment` dal componente `CommentList`, e visualizzare del markup: <add> <add>```javascript <add>// tutorial4.js <add>var Comment = React.createClass({ <add> render: function() { <add> return ( <add> <div className="comment"> <add> <h2 className="commentAuthor"> <add> {this.props.author} <add> </h2> <add> {this.props.children} <add> </div> <add> ); <add> } <add>}); <add>``` <add> <add>Racchiudendo un'espressione JavaScript dentro parentesi graffe all'interno di JSX (sia come attributo che come figlio), puoi inserire del testo o componenti React all'interno dell'albero. Accediamo per nome ad attributi passati al componente tramite chiavi in `this.props` e ciascun elemento annidato come `this.props.children`. <add> <add>### Proprietà dei Componenti <add> <add>Adesso che abbiamo definito il componente `Comment`, vogliamo passargli il nome dell'autore e il testo del commento. Questo ci permette di riutilizzare lo stesso codice per ciascun commento individuale. Ora aggiungiamo dei commenti all'interno del nostro `CommentList`: <add> <add>```javascript{6-7} <add>// tutorial5.js <add>var CommentList = React.createClass({ <add> render: function() { <add> return ( <add> <div className="commentList"> <add> <Comment author="Pete Hunt">Questo è un commento</Comment> <add> <Comment author="Jordan Walke">Questo è un *altro* commento</Comment> <add> </div> <add> ); <add> } <add>}); <add>``` <add> <add>Nota che abbiamo passato dei dati dal componente genitore `CommentList` al componente figlio `Comment`. Ad esempio, abbiamo passato *Pete Hunt* (tramite un attributo) e *Questo è un commento* (tramite un nodo figlio simil-XML) al primo `Comment`. Come detto in precedenza, il componente `Comment` accederà a queste 'proprietà' attraverso `this.props.author` e `this.props.children`. <add> <add>### Aggiungiamo il Markdown <add> <add>Il Markdown è una maniera semplice di formattare il tuo testo in linea. Ad esempio, racchiudendo il testo con asterischi gli aggiungerà dell'enfasi. <add> <add>Per prima cosa, aggiungiamo la libreria di terze parti **marked** alla tua applicazione. Questa è una libreria JavaScript che prende il testo Markdown e lo converte in HTML nativo. Per fare ciò è richiesto un tag script nel tag head (che abbiamo già incluso nel playground React): <add> <add>```html{8} <add><!-- index.html --> <add><head> <add> <meta charset="utf-8" /> <add> <title>React Tutorial</title> <add> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/{{site.react_version}}/react.js"></script> <add> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script> <add> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <add> <script src="https://cdnjs.cloudflare.com/ajax/libs/marked/0.3.2/marked.min.js"></script> <add></head> <add>``` <add> <add>Successivamente, convertiamo il testo del commento da Markdown e scriviamolo: <add> <add>```javascript{9} <add>// tutorial6.js <add>var Comment = React.createClass({ <add> render: function() { <add> return ( <add> <div className="comment"> <add> <h2 className="commentAuthor"> <add> {this.props.author} <add> </h2> <add> {marked(this.props.children.toString())} <add> </div> <add> ); <add> } <add>}); <add>``` <add> <add>Tutto ciò che stiamo facendo qui è chiamare la libreria marked. Dobbiamo convertire `this.props.children` dal testo racchiuso di React a una stringa che marked è in grado di capire, quindi vi chiamiamo esplicitamente `toString()`. <add> <add>Ma c'è un problema! I nostri commenti visualizzati appaiono come segue nel browser: "`<p>`Questo è un `<em>`altro`</em>` commento`</p>`". Noi vogliamo che questi tag vengano in realtà visualizzati come HTML. <add> <add>Questo è il risultato della protezione di React da parte di un [attacco XSS](https://en.wikipedia.org/wiki/Cross-site_scripting). C'è una maniera di aggirare questo comportamento, ma il framework ti avvisa di non farlo: <add> <add>```javascript{4,10} <add>// tutorial7.js <add>var Comment = React.createClass({ <add> rawMarkup: function() { <add> var rawMarkup = marked(this.props.children.toString(), {sanitize: true}); <add> return { __html: rawMarkup }; <add> }, <add> <add> render: function() { <add> return ( <add> <div className="comment"> <add> <h2 className="commentAuthor"> <add> {this.props.author} <add> </h2> <add> <span dangerouslySetInnerHTML={this.rawMarkup()} /> <add> </div> <add> ); <add> } <add>}); <add>``` <add> <add>Questa è una speciale API che rende intenzionalmente difficile inserire HTML nativo, ma per marked ci avvantaggeremo di questa possibilità. <add> <add>**Ricorda:** usando questa funzionalità stai assumendo che marked sia sicuro. In questo caso, passiamo `sanitize: true` che istruisce marked a fare l'escape di ogni markup HTML nel sorgente, anziché restituirlo inalterato. <add> <add>### Collega il modello dei dati <add> <add>Finora abbiamo inserito i commenti direttamente nel codice sorgente. Invece, visualizziamo un pacchetto di dati JSON nella lista dei commenti. In seguito questi verranno restituiti dal server, ma per adesso scriviamoli nel tuo sorgente: <add> <add>```javascript <add>// tutorial8.js <add>var data = [ <add> {author: "Pete Hunt", text: "Questo è un commento"}, <add> {author: "Jordan Walke", text: "Questo è un *altro* commento"} <add>]; <add>``` <add> <add>Dobbiamo inserire questi dati in `CommentList` in maniera modulare. Modifica `CommentBox` e la chiamata a `React.render()` per passare questi dati a `CommentList` tramite proprietà: <add> <add>```javascript{7,15} <add>// tutorial9.js <add>var CommentBox = React.createClass({ <add> render: function() { <add> return ( <add> <div className="commentBox"> <add> <h1>Commenti</h1> <add> <CommentList data={this.props.data} /> <add> <CommentForm /> <add> </div> <add> ); <add> } <add>}); <add> <add>React.render( <add> <CommentBox data={data} />, <add> document.getElementById('content') <add>); <add>``` <add> <add>Adesso che i dati sono disponibili in `CommentList`, visualizziamo i commenti dinamicamente: <add> <add>```javascript{4-10,13} <add>// tutorial10.js <add>var CommentList = React.createClass({ <add> render: function() { <add> var commentNodes = this.props.data.map(function (comment) { <add> return ( <add> <Comment author={comment.author}> <add> {comment.text} <add> </Comment> <add> ); <add> }); <add> return ( <add> <div className="commentList"> <add> {commentNodes} <add> </div> <add> ); <add> } <add>}); <add>``` <add> <add>Tutto qui! <add> <add>### Richiedere dati dal server <add> <add>Sostituiamo i dati scritti nel codice con dati dinamici ottenuti dal server. Rimuoveremo le proprietà dei dati e le sostituiremo con uno URL da richiedere: <add> <add>```javascript{3} <add>// tutorial11.js <add>React.render( <add> <CommentBox url="/api/comments" />, <add> document.getElementById('content') <add>); <add>``` <add> <add>Questo componente differisce dal precedente perché dovrà effettuare un nuovo rendering di se stesso. Il componente non avrà dati finché la risposta del server non sia disponibile, e a quel punto il componente potrebbe dover visualizzare dei nuovi commenti. <add> <add>Nota: il codice non funzionerà a questo passo. <add> <add>### Stato reattivo <add> <add>Finora, basandosi sulle sue proprietà, ogni componente si è visualizzato solo una volta. I valori di `props` sono immutabili: sono passati dal genitore e sono "posseduti" dal genitore. Per implementare le interazioni, introduciamo uno **stato** mutevole nel componente. `this.state` è privato al componente e può essere cambiato chiamando `this.setState()`. Quando lo stato si aggiorna, il componente effettua nuovamente il rendering di se stesso. <add> <add>I metodi `render()` sono scritti dichiarativamente come funzioni di `this.props` e `this.state`. Il framework garantisce che la UI sia sempre consistente con gli input. <add> <add>Quando il server ci fornisce i dati, dovremo cambiare i dati dei commenti in nostro possesso. Aggiungiamo un array di dati dei commenti al componente `CommentBox` come il suo stato: <add> <add>```javascript{3-5,10} <add>// tutorial12.js <add>var CommentBox = React.createClass({ <add> getInitialState: function() { <add> return {data: []}; <add> }, <add> render: function() { <add> return ( <add> <div className="commentBox"> <add> <h1>Commenti</h1> <add> <CommentList data={this.state.data} /> <add> <CommentForm /> <add> </div> <add> ); <add> } <add>}); <add>``` <add> <add>`getInitialState()` viene eseguito esattamente una volta durante il ciclo di vita del componente e imposta lo stato iniziale del componente stesso. <add> <add>#### Aggiornare lo stato <add>Quando il componente è creato per la prima volta, vogliamo richiedere tramite GET del JSON dal server e aggiornare lo stato per riflettere i dati più recenti. Useremo jQuery per effettuare una richiesta asincrona al server che abbiamo avviato in precedenza per richiedere i dati che ci servono. Somiglieranno a qualcosa di simile: <add> <add>```json <add>[ <add> {"author": "Pete Hunt", "text": "Questo è un commento"}, <add> {"author": "Jordan Walke", "text": "Questo è un *altro* commento"} <add>] <add>``` <add> <add>```javascript{6-18} <add>// tutorial13.js <add>var CommentBox = React.createClass({ <add> getInitialState: function() { <add> return {data: []}; <add> }, <add> componentDidMount: function() { <add> $.ajax({ <add> url: this.props.url, <add> dataType: 'json', <add> cache: false, <add> success: function(data) { <add> this.setState({data: data}); <add> }.bind(this), <add> error: function(xhr, status, err) { <add> console.error(this.props.url, status, err.toString()); <add> }.bind(this) <add> }); <add> }, <add> render: function() { <add> return ( <add> <div className="commentBox"> <add> <h1>Commenti</h1> <add> <CommentList data={this.state.data} /> <add> <CommentForm /> <add> </div> <add> ); <add> } <add>}); <add>``` <add> <add>Qui, `componentDidMount` è un metodo chiamato automaticamente da React quando un componente viene visualizzato. La chiave agli aggiornamenti dinamici è la chiamata a `this.setState()`. Sostituiamo il vecchio array di commenti con il nuovo ottenuto dal server e la UI si aggiorna automaticamente. Per via di questa reattività, è richiesto soltanto un piccolo cambiamento per aggiungere gli aggiornamenti in tempo reale. Qui useremo un semplice polling, ma potrai facilmente usare WebSockets o altre tecnologie. <add> <add>```javascript{3,15,20-21,35} <add>// tutorial14.js <add>var CommentBox = React.createClass({ <add> loadCommentsFromServer: function() { <add> $.ajax({ <add> url: this.props.url, <add> dataType: 'json', <add> cache: false, <add> success: function(data) { <add> this.setState({data: data}); <add> }.bind(this), <add> error: function(xhr, status, err) { <add> console.error(this.props.url, status, err.toString()); <add> }.bind(this) <add> }); <add> }, <add> getInitialState: function() { <add> return {data: []}; <add> }, <add> componentDidMount: function() { <add> this.loadCommentsFromServer(); <add> setInterval(this.loadCommentsFromServer, this.props.pollInterval); <add> }, <add> render: function() { <add> return ( <add> <div className="commentBox"> <add> <h1>Commenti</h1> <add> <CommentList data={this.state.data} /> <add> <CommentForm /> <add> </div> <add> ); <add> } <add>}); <add> <add>React.render( <add> <CommentBox url="/api/comments" pollInterval={2000} />, <add> document.getElementById('content') <add>); <add> <add>``` <add> <add>Tutto ciò che abbiamo fatto finora è spostare la chiamata AJAX in un metodo a parte e chiamarlo quando il componente viene caricato per la prima volta e successivamente ogni 2 secondi. Prova ad eseguire questa versione nel tuo browser e a cambiare il file `comments.json` (si trova nella stessa directory del tuo server); entro 2 secondi i cambiamenti saranno visibili! <add> <add>### Aggiungere nuovi commenti <add> <add>È giunto il momento di costruire il modulo. Il nostro componente `CommentForm` deve chiedere all'utente il nome e un testo del commento, e inviare una richiesta al server per salvare il commento. <add> <add>```javascript{5-9} <add>// tutorial15.js <add>var CommentForm = React.createClass({ <add> render: function() { <add> return ( <add> <form className="commentForm"> <add> <input type="text" placeholder="Il tuo nome" /> <add> <input type="text" placeholder="Di' qualcosa..." /> <add> <input type="submit" value="Invia" /> <add> </form> <add> ); <add> } <add>}); <add>``` <add> <add>Rendiamo il modulo interattivo. Quando l'utente invia il modulo, dobbiamo ripulirlo, inviare una richiesta al server, e aggiornare la lista dei commenti. Per cominciare, ascoltiamo l'evento `submit` del modulo e ripuliamolo. <add> <add>```javascript{3-14,16-19} <add>// tutorial16.js <add>var CommentForm = React.createClass({ <add> handleSubmit: function(e) { <add> e.preventDefault(); <add> var author = React.findDOMNode(this.refs.author).value.trim(); <add> var text = React.findDOMNode(this.refs.text).value.trim(); <add> if (!text || !author) { <add> return; <add> } <add> // TODO: invia la richiesta al server <add> React.findDOMNode(this.refs.author).value = ''; <add> React.findDOMNode(this.refs.text).value = ''; <add> return; <add> }, <add> render: function() { <add> return ( <add> <form className="commentForm" onSubmit={this.handleSubmit}> <add> <input type="text" placeholder="Il tuo nome" ref="author" /> <add> <input type="text" placeholder="Di' qualcosa..." ref="text" /> <add> <input type="submit" value="Invia" /> <add> </form> <add> ); <add> } <add>}); <add>``` <add> <add>##### Eventi <add> <add>React assegna i gestori degli eventi ai componenti usando una convenzione di nomi camelCased. Assegnamo un gestore `onSubmit` al modulo in maniera che ripulisca i campi del modulo quando il modulo stesso è inviato con un input valido. <add> <add>Chiamiamo `preventDefault()` sull'evento per prevenire l'azione predefinita del browser per l'invio del modulo. <add> <add>##### Refs <add> <add>Usiamo l'attributo `ref` per assegnare un nome a un componente figlio e `this.refs` per riferirsi al componente. Possiamo chiamare `React.findDOMNode(component)` su di un componente per ottenere l'elemento nativo del DOM del browser. <add> <add>##### Callback come proprietà <add> <add>Quando un utente invia un commento, dobbiamo aggiornare la lista dei commenti per includere il nuovo commento. Ha senso posizionare questa logica in `CommentBox` dal momento che `CommentBox` possiede lo stato che rappresenta la lista dei commenti. <add> <add>Dobbiamo passare i dati dal componente figlio su fino al suo genitore. Lo facciamo nel metodo `render` del nostro genitore passando una nuova callback (`handleCommentSubmit`) al figlio, legandola all'evento `onCommentSubmit` del figlio. Quando questo evento viene emesso, la callback verrà eseguita: <add> <add>```javascript{16-18,31} <add>// tutorial17.js <add>var CommentBox = React.createClass({ <add> loadCommentsFromServer: function() { <add> $.ajax({ <add> url: this.props.url, <add> dataType: 'json', <add> cache: false, <add> success: function(data) { <add> this.setState({data: data}); <add> }.bind(this), <add> error: function(xhr, status, err) { <add> console.error(this.props.url, status, err.toString()); <add> }.bind(this) <add> }); <add> }, <add> handleCommentSubmit: function(comment) { <add> // TODO: invia al server e aggiorna la lista <add> }, <add> getInitialState: function() { <add> return {data: []}; <add> }, <add> componentDidMount: function() { <add> this.loadCommentsFromServer(); <add> setInterval(this.loadCommentsFromServer, this.props.pollInterval); <add> }, <add> render: function() { <add> return ( <add> <div className="commentBox"> <add> <h1>Commenti</h1> <add> <CommentList data={this.state.data} /> <add> <CommentForm onCommentSubmit={this.handleCommentSubmit} /> <add> </div> <add> ); <add> } <add>}); <add>``` <add> <add>Chiamiamo la callback da `CommentForm` quando l'utente invia il modulo: <add> <add>```javascript{10} <add>// tutorial18.js <add>var CommentForm = React.createClass({ <add> handleSubmit: function(e) { <add> e.preventDefault(); <add> var author = React.findDOMNode(this.refs.author).value.trim(); <add> var text = React.findDOMNode(this.refs.text).value.trim(); <add> if (!text || !author) { <add> return; <add> } <add> this.props.onCommentSubmit({author: author, text: text}); <add> React.findDOMNode(this.refs.author).value = ''; <add> React.findDOMNode(this.refs.text).value = ''; <add> return; <add> }, <add> render: function() { <add> return ( <add> <form className="commentForm" onSubmit={this.handleSubmit}> <add> <input type="text" placeholder="Il tuo nome" ref="author" /> <add> <input type="text" placeholder="Di' qualcosa..." ref="text" /> <add> <input type="submit" value="Invia" /> <add> </form> <add> ); <add> } <add>}); <add>``` <add> <add>Adesso che le callback sono al loro posto, non ci resta che inviare al server e aggiornare la lista: <add> <add>```javascript{17-28} <add>// tutorial19.js <add>var CommentBox = React.createClass({ <add> loadCommentsFromServer: function() { <add> $.ajax({ <add> url: this.props.url, <add> dataType: 'json', <add> cache: false, <add> success: function(data) { <add> this.setState({data: data}); <add> }.bind(this), <add> error: function(xhr, status, err) { <add> console.error(this.props.url, status, err.toString()); <add> }.bind(this) <add> }); <add> }, <add> handleCommentSubmit: function(comment) { <add> $.ajax({ <add> url: this.props.url, <add> dataType: 'json', <add> type: 'POST', <add> data: comment, <add> success: function(data) { <add> this.setState({data: data}); <add> }.bind(this), <add> error: function(xhr, status, err) { <add> console.error(this.props.url, status, err.toString()); <add> }.bind(this) <add> }); <add> }, <add> getInitialState: function() { <add> return {data: []}; <add> }, <add> componentDidMount: function() { <add> this.loadCommentsFromServer(); <add> setInterval(this.loadCommentsFromServer, this.props.pollInterval); <add> }, <add> render: function() { <add> return ( <add> <div className="commentBox"> <add> <h1>Commenti</h1> <add> <CommentList data={this.state.data} /> <add> <CommentForm onCommentSubmit={this.handleCommentSubmit} /> <add> </div> <add> ); <add> } <add>}); <add>``` <add> <add>### Ottimizzazione: aggiornamenti ottimistici <add> <add>La nostra applicazione è adesso completa, ma aspettare che la richiesta completi prima di vedere il commento apparire nella lista la fa sembrare lenta. Possiamo aggiungere ottimisticamente questo commento alla lista per fare apparire l'applicazione più veloce. <add> <add>```javascript{17-19} <add>// tutorial20.js <add>var CommentBox = React.createClass({ <add> loadCommentsFromServer: function() { <add> $.ajax({ <add> url: this.props.url, <add> dataType: 'json', <add> cache: false, <add> success: function(data) { <add> this.setState({data: data}); <add> }.bind(this), <add> error: function(xhr, status, err) { <add> console.error(this.props.url, status, err.toString()); <add> }.bind(this) <add> }); <add> }, <add> handleCommentSubmit: function(comment) { <add> var comments = this.state.data; <add> var newComments = comments.concat([comment]); <add> this.setState({data: newComments}); <add> $.ajax({ <add> url: this.props.url, <add> dataType: 'json', <add> type: 'POST', <add> data: comment, <add> success: function(data) { <add> this.setState({data: data}); <add> }.bind(this), <add> error: function(xhr, status, err) { <add> console.error(this.props.url, status, err.toString()); <add> }.bind(this) <add> }); <add> }, <add> getInitialState: function() { <add> return {data: []}; <add> }, <add> componentDidMount: function() { <add> this.loadCommentsFromServer(); <add> setInterval(this.loadCommentsFromServer, this.props.pollInterval); <add> }, <add> render: function() { <add> return ( <add> <div className="commentBox"> <add> <h1>Commenti</h1> <add> <CommentList data={this.state.data} /> <add> <CommentForm onCommentSubmit={this.handleCommentSubmit} /> <add> </div> <add> ); <add> } <add>}); <add>``` <add> <add>### Congratulazioni! <add> <add>Hai appena costruito una casella di commenti in pochi semplici passi. Leggi maggiori dettagli sul [perché usare React](/react/docs/why-react.html), o approfondisci [la guida di riferimento dell'API](/react/docs/top-level-api.html) e comincia ad hackerare! In bocca al lupo! <ide><path>docs/docs/videos.it-IT.md <add>--- <add>id: videos-it-IT <add>title: Video <add>permalink: videos-it-IT.html <add>prev: conferences-it-IT.html <add>next: complementary-tools-it-IT.html <add>--- <add> <add>### Riconsiderare le best practice - JSConf.eu <add> <add><iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/x7cQ3mrcKaY" frameborder="0" allowfullscreen></iframe> <add> <add>"A Facebook e Instagram, con React stiamo provando a spingerci oltre i limiti di ciò che è possibile realizzare sul web. Il mio talk comincerà con una breve introduzione al framework, e poi approfondirà tre argomenti controversi: Gettare via la nozione dei template e costruire le viste con JavaScript, effettuare il “ri-rendering” dell'intera applicazione quando i dati cambiano, e un'implementazione leggera del DOM e degli eventi." -- [Pete Hunt](http://www.petehunt.net/) <add> <add>* * * <add> <add>### Pensare in react - tagtree.tv <add> <add>Un video di [tagtree.tv](http://tagtree.tv/) che espone i principi di [Pensare in React](/react/docs/thinking-in-react.html) mentre costruisci una semplice applicazione <add><figure>[![](/react/img/docs/thinking-in-react-tagtree.png)](http://tagtree.tv/thinking-in-react)</figure> <add> <add>* * * <add> <add>### I Segreti del DOM Virtuale - MtnWest JS <add> <add><iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/h3KksH8gfcQ" frameborder="0" allowfullscreen></iframe> <add> <add>"In questo talk discuterò perché abbiamo costruito un DOM virtuale, i vantaggi rispetto ad altri sistemi, e la sua rilevanza per il futuro della tecnologia dei browser." -- [Pete Hunt](http://www.petehunt.net/) <add> <add>* * * <add> <add>### Pensare in grande con React ### <add> <add>"Sulla carta, tutti questi framework JS sembrano promettenti: implementazioni pulite, design veloce del codice, esecuzione perfetta. Ma che succede quando metti Javascript sotto stress? Che succede se gli dài in pasto 6 megabyte di codice? In questo talk investigheremo come si comporta React in situazioni di stress elevato, e come ha aiutato il nostro team a costruire codice sicuro ad una scala enorme." <add><figure>[![](https://i.vimeocdn.com/video/481670116_650.jpg)](https://skillsmatter.com/skillscasts/5429-going-big-with-react#video)</figure> <add> <add>* * * <add> <add>### CodeWinds <add> <add>[Pete Hunt](http://www.petehunt.net/) ha parlato con [Jeff Barczewski](http://jeff.barczewski.com/) a proposito di React nell'Episodio 4 di CodeWinds. <add><figure>[![](/react/img/docs/codewinds-004.png)](http://codewinds.com/4)</figure> <add> <add><table width="100%"><tr><td> <add>02:08 - Cos'è React e perché usarlo?<br /> <add>03:08 - La relazione simbiotica di ClojureScript e React<br /> <add>04:54 - La storia di React e il perché è stato creato<br /> <add>09:43 - Aggiornare una pagina web con React senza usare data binding<br /> <add>13:11 - Usare il DOM virtuale per cambiare il DOM del browser<br /> <add>13:57 - Programmare con React, rendering in HTML, canvas, ed altro<br /> <add>16:45 - Lavorare con i designer. Paragone con Ember ed AngularJS<br /> <add>21:45 - Il Compilatore JSX che unisce HTML e il javascript di React<br /> <add>23:50 - Autobuilding JSX e strumenti nel browser per React<br /> <add>24:50 - Trucchi e suggerimenti per lavorare con React, primi passi<br /> <add></td><td> <add>27:17 - Rendering HTML lato server con Node.js. Rendering backend<br /> <add>29:20 - React evoluto tramite sopravvivenza del più adatto a Facebook<br /> <add>30:15 - Idee per avere lo stato sul server e il client, usando web sockets.<br /> <add>32:05 - React-multiutente - stato mutevole distribuito usando Firebase<br /> <add>33:03 - Miglior debug con React usando le transizioni di stato, ripetere eventi<br /> <add>34:08 - Differenze con i Web Components<br /> <add>34:25 - Compagnie rilevanti che usano React<br /> <add>35:16 - Si può creare un plugin backend di React per generare PDF?<br /> <add>36:30 - Futuro di React, cosa viene dopo?<br /> <add>39:38 - Contribuire e ricevere aiuto<br /> <add></td></tr></table> <add> <add>[Leggi le note dell'episodio](http://codewinds.com/4) <add> <add>* * * <add> <add>### JavaScript Jabber <add> <add>[Pete Hunt](http://www.petehunt.net/) e [Jordan Walke](https://github.com/jordwalke) hanno parlato di React in JavaScript Jabber 73. <add><figure>[![](/react/img/docs/javascript-jabber.png)](http://javascriptjabber.com/073-jsj-react-with-pete-hunt-and-jordan-walke/#content)</figure> <add> <add><table width="100%"><tr><td> <add>01:34 – Introduzione di Pete Hunt<br /> <add>02:45 – Introduzione di Jordan Walke<br /> <add>04:15 – React<br /> <add>06:38 – 60 Frame Al Secondo<br /> <add>09:34 – Data Binding<br /> <add>12:31 – Performance<br /> <add>17:39 – Algoritmo di Differenza<br /> <add>19:36 – Manipolazione del DOM <add></td><td> <add>23:06 – Supporto per node.js<br /> <add>24:03 – rendr<br /> <add>26:02 – JSX<br /> <add>30:31 – requestAnimationFrame<br /> <add>34:15 – React e le Applicazioni<br /> <add>38:12 – Utenti React Khan Academy<br /> <add>39:53 – Farlo funzionare <add></td></tr></table> <add> <add>[Leggi la trascrizione completa](http://javascriptjabber.com/073-jsj-react-with-pete-hunt-and-jordan-walke/) <add> <add>* * * <add> <add>### Introduzione a React.js - Facebook Seattle <add> <add><iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/XxVg_s8xAms" frameborder="0" allowfullscreen></iframe> <add> <add>Di [Tom Occhino](http://tomocchino.com/) e [Jordan Walke](https://github.com/jordwalke) <add> <add>* * * <add> <add>### Backbone + React + Middleman Screencast <add><iframe width="650" height="488" src="https://www.youtube-nocookie.com/embed/iul1fWHVU6A" frameborder="0" allowfullscreen></iframe> <add> <add>Backbone è una grande maniera di interfacciare una API REST con React. Questo screencast mostra come integrare i due usando [Backbone-React-Component](https://github.com/magalhas/backbone-react-component). Middleman è il framework utilizzato in questo esempio, ma può essere facilmente sostituito con altri framework. Si può trovare un template supportato per questo esempio [qui](https://github.com/jbhatab/middleman-backbone-react-template). -- [Open Minded Innovations](http://www.openmindedinnovations.com/) <add> <add>* * * <add> <add>### Sviluppare Interfacce Utente Con React - Super VanJS <add> <add><iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/1OeXsL5mr4g" frameborder="0" allowfullscreen></iframe> <add> <add>Di [Steven Luscher](https://github.com/steveluscher) <add> <add>* * * <add> <add>### Introduzione a React - LAWebSpeed meetup <add> <add><iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/SMMRJif5QW0" frameborder="0" allowfullscreen></iframe> <add> <add>Di [Stoyan Stefanov](http://www.phpied.com/) <add> <add>* * * <add> <add>### React, o come rendere la vita più semplice - FrontEnd Dev Conf '14 <add> <add><iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/YJNUK0EA_Jo" frameborder="0" allowfullscreen></iframe> <add> <add>**In Russo** di [Alexander Solovyov](http://solovyov.net/) <add> <add>* * * <add> <add>### "Programmazione funzionale del DOM" - Meteor DevShop 11 <add> <add><iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/qqVbr_LaCIo" frameborder="0" allowfullscreen></iframe> <add> <add>* * * <add> <add>### "Ripensare lo Sviluppo di Applicazioni Web a Facebook" - Facebook F8 Conference 2014 <add> <add><iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/nYkdrAPrdcw" frameborder="0" allowfullscreen></iframe> <add> <add>* * * <add> <add>### React e Flux: Costruire Applicazioni con un Flusso Dati Unidirezionale - Forward JS 2014 <add> <add><iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/i__969noyAM" frameborder="0" allowfullscreen></iframe> <add> <add>Gli ingegneri di Facebook [Bill Fisher](https://twitter.com/fisherwebdev) e [Jing Chen](https://twitter.com/jingc) parlano di Flux e React, e di come usare un'architettura dell'applicazione con un flusso di dati unidirezionale rende gran parte del loro codice più pulito. <add> <add>* * * <add> <add>### Rendering Lato Server di Applicazioni Isomorfiche a SoundCloud <add> <add><iframe src="https://player.vimeo.com/video/108488724" width="650" height="365" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe> <add> <add>[Andres Suarez](https://github.com/zertosh) ci accompagna alla scoperta di come [SoundCloud](https://developers.soundcloud.com/blog/) usa React e Flux per il rendering lato server. <add> <add>[Slide e codice d'esempio](https://github.com/zertosh/ssr-demo-kit) <add> <add>* * * <add> <add>### Introduzione a React Native (+Playlist) - React.js Conf 2015 <add> <add><iframe width="650" height="366" src="https://www.youtube-nocookie.com/embed/KVZ-P-ZI6W4?list=PLb0IAmt7-GS1cbw4qonlQztYV1TAW0sCr" frameborder="0" allowfullscreen></iframe> <add> <add>[Tom Occhino](https://twitter.com/tomocchino) ripercorre il passato e il presente di React nel 2015, e ci mostra dove è diretto nell'immediato futuro.
42
Javascript
Javascript
fix polar area legends
7edcc0659bf3295532974d1d3569f3454290e8e7
<ide><path>src/charts/Chart.PolarArea.js <ide> <ide> var defaultConfig = { <ide> aspectRatio: 1, <del> legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i = 0; i < data.datasets[0].data.length; i++){%><li><span style=\"background-color:<%=data.datasets[0].backgroundColor[i]%>\"><%if(data.labels && i < data.labels.length){%><%=data.labels[i]%><%}%></span></li><%}%></ul>", <add> legendCallback: function(chart) { <add> var text = []; <add> text.push('<ul class="' + chart.id + '-legend">'); <add> <add> if (chart.data.datasets.length) { <add> for (var i = 0; i < chart.data.datasets[0].data.length; ++i) { <add> text.push('<li><span style="background-color:' + chart.data.datasets[0].backgroundColor[i] + '">'); <add> if (chart.data.labels[i]) { <add> text.push(chart.data.labels[i]); <add> } <add> text.push('</span></li>'); <add> } <add> } <add> <add> text.push('</ul>'); <add> return text.join(""); <add> } <ide> }; <ide> <ide> Chart.PolarArea = function(context, config) {
1
Mixed
Javascript
fix typos with misspell
62aaae02656ed14859588dc7edfe34118337e161
<ide><path>CHANGELOG.md <ide> ### 1.13.10 (September 6, 2015) <ide> <ide> - [#12104](https://github.com/emberjs/ember.js/pull/12104) [BUGFIX] Ensure `concatenatedProperties` are not stomped. <del>- [#12256](https://github.com/emberjs/ember.js/pull/12256) [BUGFIX] Ensure concat streams unsubscribe properly. Fixes memory leak with attributes specified within quotes in the template (i.e. `<div data-foo="{{somethign}}"></div>`). <add>- [#12256](https://github.com/emberjs/ember.js/pull/12256) [BUGFIX] Ensure concat streams unsubscribe properly. Fixes memory leak with attributes specified within quotes in the template (i.e. `<div data-foo="{{something}}"></div>`). <ide> - [#12272](https://github.com/emberjs/ember.js/pull/12272) [BUGFIX] Update HTMLBars to fix memory leak when an `{{each}}` is inside an `{{if}}`. <ide> <ide> ### 1.13.9 (August 22, 2015) <ide> * `removeAttribute` fix for IE <11 and SVG. <ide> * Disable `cloneNodes` in IE8. <ide> * Improve HTML validation and error messages thrown. <del> * Fix a number of template compliation issues in IE8. <add> * Fix a number of template compilation issues in IE8. <ide> * Use the correct namespace in `parseHTML` (fixes various issues that occur <ide> when changing to and from alternate namespaces). <ide> * Ensure values are converted to `String`'s when setting attributes (fixes issues in IE10 & IE11). <ide> Clearly, `component-a` has subscribed to `some-other-component`'s `action`. Prev <ide> ### Ember 1.6.0 (July, 7, 2014) <ide> <ide> * [BREAKING BUGFIX] An empty array is treated as falsy value in `bind-attr` to be in consistent <del> with `if` helper. Breaking for apps that relies on the previous behaviour which treats an empty <add> with `if` helper. Breaking for apps that relies on the previous behavior which treats an empty <ide> array as truthy value in `bind-attr`. <ide> * [BUGFIX] Ensure itemController's do not leak by tying them to the parent controller lifecycle. <ide> * [BUGFIX] Spaces in brace expansion throws an error. <ide> Clearly, `component-a` has subscribed to `some-other-component`'s `action`. Prev <ide> * Various enhancements to bound helpers: adds multiple property support to bound helpers, adds bind-able options hash properties, adds {{unbound}} helper support to render unbound form of helpers. <ide> * Add App.inject <ide> * Add Ember.EnumberableUtils.intersection <del>* Deprecate Controller#controllerFor in favour of Controller#needs <add>* Deprecate Controller#controllerFor in favor of Controller#needs <ide> * Adds `bubbles` property to Ember.TextField <ide> * Allow overriding of Ember.Router#handleURL <ide> * Allow libraries loaded before Ember to tie into Ember load hooks <ide> Clearly, `component-a` has subscribed to `some-other-component`'s `action`. Prev <ide> * Add `action` support to Ember.TextField <ide> * Warn about using production builds in localhost <ide> * Update Metamorph <del>* Deprecate Ember.alias in favour of Ember.aliasMethod <add>* Deprecate Ember.alias in favor of Ember.aliasMethod <ide> * Add Ember.computed.alias <ide> * Allow chaining on DeferredMixin#then <ide> * ArrayController learned itemControllerClass. <ide><path>CONTRIBUTING.md <ide> original notice. <ide> * If you submit a feature request as an issue, you will be invited to follow the <ide> [instructions in this document](https://github.com/emberjs/ember.js/blob/master/CONTRIBUTING.md#requesting-a-feature) <ide> and the issue will be closed <del>* Issues that become inactive will be labelled accordingly <add>* Issues that become inactive will be labeled accordingly <ide> to inform the original poster and Ember contributors that the issue <ide> should be closed since the issue is no longer actionable. The issue <ide> can be reopened at a later time if needed, e.g. becomes actionable again. <ide><path>packages/container/lib/container.js <ide> Container.prototype = { <ide> <ide> /** <ide> Given a fullName return a corresponding instance. <del> The default behaviour is for lookup to return a singleton instance. <add> The default behavior is for lookup to return a singleton instance. <ide> The singleton is scoped to the container, allowing multiple containers <ide> to all have their own locally scoped singletons. <ide> ```javascript <ide><path>packages/container/lib/registry.js <ide> Registry.prototype = { <ide> }, <ide> <ide> /** <del> A hook to enable custom fullName normalization behaviour <add> A hook to enable custom fullName normalization behavior <ide> <ide> @private <ide> @method normalizeFullName <ide><path>packages/ember-glimmer/lib/components/link-to.js <ide> <ide> any passed value to `disabled` will disable it except `undefined`. <ide> to ensure that only `true` disable the `link-to` component you can <del> override the global behaviour of `Ember.LinkComponent`. <add> override the global behavior of `Ember.LinkComponent`. <ide> <ide> ```javascript <ide> Ember.LinkComponent.reopen({ <ide><path>packages/ember-glimmer/lib/helpers/action.js <ide> export const ACTION = symbol('ACTION'); <ide> Two options can be passed to the `action` helper when it is used in this way. <ide> <ide> * `target=someProperty` will look to `someProperty` instead of the current <del> context for the `actions` hash. This can be useful when targetting a <add> context for the `actions` hash. This can be useful when targeting a <ide> service for actions. <ide> * `value="target.value"` will read the path `target.value` off the first <ide> argument to the action when it is called and rewrite the first argument <ide><path>packages/ember-glimmer/lib/helpers/get.js <ide> import { <ide> Dynamically look up a property on an object. The second argument to `{{get}}` <ide> should have a string value, although it can be bound. <ide> <del> For example, these two usages are equivilent: <add> For example, these two usages are equivalent: <ide> <ide> ```handlebars <ide> {{person.height}} <ide><path>packages/ember-glimmer/lib/renderer.js <ide> class Renderer { <ide> } <ide> <ide> getElement(view) { <del> // overriden in the subclasses <add> // overridden in the subclasses <ide> } <ide> <ide> getBounds(view) { <ide><path>packages/ember-glimmer/lib/syntax.js <ide> function refineBlockSyntax(sexp, builder) { <ide> <ide> export const experimentalMacros = []; <ide> <del>// This is a private API to allow for expiremental macros <add>// This is a private API to allow for experimental macros <ide> // to be created in user space. Registering a macro should <ide> // should be done in an initializer. <ide> export function registerMacros(macro) { <ide><path>packages/ember-glimmer/tests/integration/components/attrs-lookup-test.js <ide> moduleFor('Components test: attrs lookup', class extends RenderingTest { <ide> assert.equal(instance.get('second'), 'second', 'matches known value'); <ide> } <ide> <del> ['@test bound computed properties can be overriden in extensions, set during init, and passed in as attrs']() { <add> ['@test bound computed properties can be overridden in extensions, set during init, and passed in as attrs']() { <ide> let FooClass = Component.extend({ <ide> attributeBindings: ['style'], <ide> style: computed('height', 'color', function() { <ide><path>packages/ember-glimmer/tests/integration/components/contextual-components-test.js <ide> moduleFor('Components test: contextual components', class extends RenderingTest <ide> assert.ok(!isEmpty(instance), 'a instance was created'); <ide> assert.equal(previousInstance, undefined, 'no previous component exists'); <ide> assert.equal(initCount, 1, 'the component was constructed exactly 1 time'); <del> assert.equal(this.$().text(), 'open', 'the componet text is "open"'); <add> assert.equal(this.$().text(), 'open', 'the components text is "open"'); <ide> <ide> this.runTask(() => this.rerender()); <ide> <ide> assert.ok(!isEmpty(instance), 'the component instance exists'); <ide> assert.equal(previousInstance, undefined, 'no previous component exists'); <ide> assert.equal(initCount, 1, 'the component was constructed exactly 1 time'); <del> assert.equal(this.$().text(), 'open', 'the componet text is "open"'); <add> assert.equal(this.$().text(), 'open', 'the components text is "open"'); <ide> <ide> this.runTask(() => this.context.set('isOpen', false)); <ide> <ide> moduleFor('Components test: contextual components', class extends RenderingTest <ide> assert.ok(!isEmpty(instance), 'the component instance exists'); <ide> assert.equal(previousInstance, undefined, 'no previous component exists'); <ide> assert.equal(initCount, 1, 'the component was constructed exactly 1 time'); <del> assert.equal(this.$().text(), 'open', 'the componet text is "open"'); <add> assert.equal(this.$().text(), 'open', 'the components text is "open"'); <ide> } <ide> <ide> ['@test GH#13982 contextual component ref is stable even when bound params change (bound name param)'](assert) { <ide> moduleFor('Components test: contextual components', class extends RenderingTest <ide> assert.ok(!isEmpty(instance), 'a instance was created'); <ide> assert.equal(previousInstance, undefined, 'no previous component exists'); <ide> assert.equal(initCount, 1, 'the component was constructed exactly 1 time'); <del> assert.equal(this.$().text(), 'open', 'the componet text is "open"'); <add> assert.equal(this.$().text(), 'open', 'the components text is "open"'); <ide> <ide> this.runTask(() => this.rerender()); <ide> <ide> assert.ok(!isEmpty(instance), 'the component instance exists'); <ide> assert.equal(previousInstance, undefined, 'no previous component exists'); <ide> assert.equal(initCount, 1, 'the component was constructed exactly 1 time'); <del> assert.equal(this.$().text(), 'open', 'the componet text is "open"'); <add> assert.equal(this.$().text(), 'open', 'the components text is "open"'); <ide> <ide> this.runTask(() => this.context.set('isOpen', false)); <ide> <ide> moduleFor('Components test: contextual components', class extends RenderingTest <ide> assert.ok(!isEmpty(instance), 'the component instance exists'); <ide> assert.equal(previousInstance, undefined, 'no previous component exists'); <ide> assert.equal(initCount, 1, 'the component was constructed exactly 1 time'); <del> assert.equal(this.$().text(), 'open', 'the componet text is "open"'); <add> assert.equal(this.$().text(), 'open', 'the components text is "open"'); <ide> } <ide> <ide> ['@test GH#13982 contextual component ref is recomputed when component name param changes'](assert) { <ide><path>packages/ember-glimmer/tests/integration/components/curly-components-test.js <ide> moduleFor('Components test: curly components', class extends RenderingTest { <ide> this.assertComponentElement(this.firstChild, { attrs: { role: 'main' } }); <ide> } <ide> <del> ['@test `template` specified in component is overriden by block']() { <add> ['@test `template` specified in component is overridden by block']() { <ide> this.registerComponent('with-template', { <ide> ComponentClass: Component.extend({ <ide> template: compile('Should not be used') <ide><path>packages/ember-metal/lib/run_loop.js <ide> run.end = function() { <ide> will be resolved on the target object at the time the scheduled item is <ide> invoked allowing you to change the target function. <ide> @param {Object} [arguments*] Optional arguments to be passed to the queued method. <del> @return {*} Timer information for use in cancelling, see `run.cancel`. <add> @return {*} Timer information for use in canceling, see `run.cancel`. <ide> @public <ide> */ <ide> run.schedule = function(/* queue, target, method */) { <ide> run.sync = function() { <ide> target at the time the method is invoked. <ide> @param {Object} [args*] Optional arguments to pass to the timeout. <ide> @param {Number} wait Number of milliseconds to wait. <del> @return {*} Timer information for use in cancelling, see `run.cancel`. <add> @return {*} Timer information for use in canceling, see `run.cancel`. <ide> @public <ide> */ <ide> run.later = function(/*target, method*/) { <ide> run.later = function(/*target, method*/) { <ide> If you pass a string it will be resolved on the <ide> target at the time the method is invoked. <ide> @param {Object} [args*] Optional arguments to pass to the timeout. <del> @return {Object} Timer information for use in cancelling, see `run.cancel`. <add> @return {Object} Timer information for use in canceling, see `run.cancel`. <ide> @public <ide> */ <ide> run.once = function(...args) { <ide> run.once = function(...args) { <ide> If you pass a string it will be resolved on the <ide> target at the time the method is invoked. <ide> @param {Object} [args*] Optional arguments to pass to the timeout. <del> @return {Object} Timer information for use in cancelling, see `run.cancel`. <add> @return {Object} Timer information for use in canceling, see `run.cancel`. <ide> @public <ide> */ <ide> run.scheduleOnce = function(/*queue, target, method*/) { <ide> run.scheduleOnce = function(/*queue, target, method*/) { <ide> If you pass a string it will be resolved on the <ide> target at the time the method is invoked. <ide> @param {Object} [args*] Optional arguments to pass to the timeout. <del> @return {Object} Timer information for use in cancelling, see `run.cancel`. <add> @return {Object} Timer information for use in canceling, see `run.cancel`. <ide> @public <ide> */ <ide> run.next = function(...args) { <ide> run.next = function(...args) { <ide> // will be executed since we passed in true (immediate) <ide> }, 100, true); <ide> <del> // the 100ms delay until this method can be called again will be cancelled <add> // the 100ms delay until this method can be called again will be canceled <ide> run.cancel(debounceImmediate); <ide> ``` <ide> <ide> @method cancel <ide> @param {Object} timer Timer object to cancel <del> @return {Boolean} true if cancelled or false/undefined if it wasn't found <add> @return {Boolean} true if canceled or false/undefined if it wasn't found <ide> @public <ide> */ <ide> run.cancel = function(timer) { <ide> run.cancel = function(timer) { <ide> @param {Number} wait Number of milliseconds to wait. <ide> @param {Boolean} immediate Trigger the function on the leading instead <ide> of the trailing edge of the wait interval. Defaults to false. <del> @return {Array} Timer information for use in cancelling, see `run.cancel`. <add> @return {Array} Timer information for use in canceling, see `run.cancel`. <ide> @public <ide> */ <ide> run.debounce = function() { <ide> run.debounce = function() { <ide> @param {Number} spacing Number of milliseconds to space out requests. <ide> @param {Boolean} immediate Trigger the function on the leading instead <ide> of the trailing edge of the wait interval. Defaults to true. <del> @return {Array} Timer information for use in cancelling, see `run.cancel`. <add> @return {Array} Timer information for use in canceling, see `run.cancel`. <ide> @public <ide> */ <ide> run.throttle = function() { <ide><path>packages/ember-metal/tests/accessors/get_test.js <ide> testBoth('should call unknownProperty on watched values if the value is undefine <ide> equal(get(obj, 'foo'), 'FOO', 'should return value from unknown'); <ide> }); <ide> <del>QUnit.test('warn on attemps to call get with no arguments', function() { <add>QUnit.test('warn on attempts to call get with no arguments', function() { <ide> expectAssertion(function() { <ide> get('aProperty'); <ide> }, /Get must be called with two arguments;/i); <ide> }); <ide> <del>QUnit.test('warn on attemps to call get with only one argument', function() { <add>QUnit.test('warn on attempts to call get with only one argument', function() { <ide> expectAssertion(function() { <ide> get('aProperty'); <ide> }, /Get must be called with two arguments;/i); <ide> }); <ide> <del>QUnit.test('warn on attemps to call get with more then two arguments', function() { <add>QUnit.test('warn on attempts to call get with more then two arguments', function() { <ide> expectAssertion(function() { <ide> get({}, 'aProperty', true); <ide> }, /Get must be called with two arguments;/i); <ide><path>packages/ember-metal/tests/events_test.js <ide> QUnit.test('a listener added as part of a mixin may be overridden', function() { <ide> SecondMixin.apply(obj); <ide> <ide> sendEvent(obj, 'bar'); <del> equal(triggered, 0, 'should not invoke from overriden property'); <add> equal(triggered, 0, 'should not invoke from overridden property'); <ide> <ide> sendEvent(obj, 'baz'); <ide> equal(triggered, 1, 'should invoke from subclass property'); <ide><path>packages/ember-metal/tests/injected_property_test.js <ide> QUnit.test('injected properties should be overridable', function() { <ide> <ide> set(obj, 'foo', 'bar'); <ide> <del> equal(get(obj, 'foo'), 'bar', 'should return the overriden value'); <add> equal(get(obj, 'foo'), 'bar', 'should return the overridden value'); <ide> }); <ide> <ide> QUnit.test('getting on an object without an owner or container should fail assertion', function() { <ide><path>packages/ember-metal/tests/mixin/observer_test.js <ide> testBoth('observing chain with property in mixin after', function(get, set) { <ide> equal(get(obj, 'count'), 1, 'should invoke observer after change'); <ide> }); <ide> <del>testBoth('observing chain with overriden property', function(get, set) { <add>testBoth('observing chain with overridden property', function(get, set) { <ide> let obj2 = { baz: 'baz' }; <ide> let obj3 = { baz: 'foo' }; <ide> <ide><path>packages/ember-routing/lib/ext/controller.js <ide> ControllerMixin.reopen({ <ide> `this.category` and `this.page`. <ide> By default, Ember coerces query parameter values using `toggleProperty`. <ide> This behavior may lead to unexpected results. <del> To explicity configure a query parameter property so it coerces as expected, you must define a type property: <add> To explicitly configure a query parameter property so it coerces as expected, you must define a type property: <ide> ```javascript <ide> queryParams: [{ <ide> category: { <ide><path>packages/ember-routing/lib/system/router.js <ide> const EmberRouter = EmberObject.extend(Evented, { <ide> * `history` - use the browser's history API to make the URLs look just like any standard URL <ide> * `hash` - use `#` to separate the server part of the URL from the Ember part: `/blog/#/posts/new` <ide> * `none` - do not store the Ember URL in the actual browser URL (mainly used for testing) <del> * `auto` - use the best option based on browser capabilites: `history` if possible, then `hash` if possible, otherwise `none` <add> * `auto` - use the best option based on browser capabilities: `history` if possible, then `hash` if possible, otherwise `none` <ide> <ide> Note: If using ember-cli, this value is defaulted to `auto` by the `locationType` setting of `/config/environment.js` <ide> <ide> const EmberRouter = EmberObject.extend(Evented, { <ide> <ide> /** <ide> Returns the meta information for the query params of a given route. This <del> will be overriden to allow support for lazy routes. <add> will be overridden to allow support for lazy routes. <ide> <ide> @private <ide> @method _getQPMeta <ide><path>packages/ember-runtime/lib/mixins/container_proxy.js <ide> let containerProxyMixin = { <ide> /** <ide> Given a fullName return a corresponding instance. <ide> <del> The default behaviour is for lookup to return a singleton instance. <add> The default behavior is for lookup to return a singleton instance. <ide> The singleton is scoped to the container, allowing multiple containers <ide> to all have their own locally scoped singletons. <ide> <ide><path>packages/ember-runtime/tests/system/array_proxy/arranged_content_test.js <ide> QUnit.test('firstObject - returns first arranged object', function() { <ide> }); <ide> <ide> QUnit.test('arrangedContentArray{Will,Did}Change are called when the arranged content changes', function() { <del> // The behaviour covered by this test may change in the future if we decide <add> // The behavior covered by this test may change in the future if we decide <ide> // that built-in array methods are not overridable. <ide> <ide> let willChangeCallCount = 0; <ide><path>packages/ember-runtime/tests/system/array_proxy/content_change_test.js <ide> QUnit.test('The ArrayProxy doesn\'t explode when assigned a destroyed object', f <ide> }); <ide> <ide> QUnit.test('arrayContent{Will,Did}Change are called when the content changes', function() { <del> // The behaviour covered by this test may change in the future if we decide <add> // The behavior covered by this test may change in the future if we decide <ide> // that built-in array methods are not overridable. <ide> <ide> let willChangeCallCount = 0; <ide><path>packages/ember-views/lib/mixins/text_support.js <ide> const KEY_EVENTS = { <ide> `TextSupport` is a shared mixin used by both `Ember.TextField` and <ide> `Ember.TextArea`. `TextSupport` adds a number of methods that allow you to <ide> specify a controller action to invoke when a certain event is fired on your <del> text field or textarea. The specifed controller action would get the current <add> text field or textarea. The specified controller action would get the current <ide> value of the field passed in as the only argument unless the value of <ide> the field is empty. In that case, the instance of the field itself is passed <ide> in as the only argument. <ide><path>packages/ember-views/lib/system/utils.js <ide> export function getViewClientRects(view) { <ide> `getViewBoundingClientRect` provides information about the position of the <ide> bounding border box edges of a view relative to the viewport. <ide> <del> It is only intended to be used by development tools like the Ember Inpsector <add> It is only intended to be used by development tools like the Ember Inspector <ide> and may not work on older browsers. <ide> <ide> @private <ide><path>packages/ember/tests/routing/basic_test.js <ide> QUnit.test('Generated route should be an instance of App.Route if provided', fun <ide> ok(generatedRoute instanceof App.Route, 'should extend the correct route'); <ide> }); <ide> <del>QUnit.test('Nested index route is not overriden by parent\'s implicit index route', function() { <add>QUnit.test('Nested index route is not overridden by parent\'s implicit index route', function() { <ide> Router.map(function() { <ide> this.route('posts', function() { <ide> this.route('index', { path: ':category' }); <ide><path>packages/ember/tests/routing/query_params_test.js <ide> moduleFor('Query Params - main', class extends QueryParamTestCase { <ide> this.assertCurrentPath('/', 'QP did not update due to being overriden'); <ide> <ide> this.setAndFlush(indexController, 'c', false); <del> this.assertCurrentPath('/?c=false', 'QP updated with overriden param'); <add> this.assertCurrentPath('/?c=false', 'QP updated with overridden param'); <ide> }); <ide> } <ide> <ide><path>packages/external-helpers/lib/external-helpers-dev.js <ide> export function defaults(obj, defaults) { <ide> <ide> export const possibleConstructorReturn = (function (self, call) { <ide> if (!self) { <del> throw new ReferenceError(`this hasn't been initialised - super() hasn't been called`); <add> throw new ReferenceError(`this hasn't been initialized - super() hasn't been called`); <ide> } <ide> return call && (typeof call === 'object' || typeof call === 'function') ? call : self; <ide> });
27
Text
Text
add lance to collaborators
0b9e135c3eaf9b83671b1ecbaa1aa4ba700a8add
<ide><path>README.md <ide> information about the governance of the Node.js project, see <ide> * [joaocgreis](https://github.com/joaocgreis) - **João Reis** &lt;reis@janeasystems.com&gt; <ide> * [julianduque](https://github.com/julianduque) - **Julian Duque** &lt;julianduquej@gmail.com&gt; <ide> * [JungMinu](https://github.com/JungMinu) - **Minwoo Jung** &lt;jmwsoft@gmail.com&gt; <add>* [lance](https://github.com/lance) - **Lance Ball** &lt;lball@redhat.com&gt; <ide> * [lxe](https://github.com/lxe) - **Aleksey Smolenchuk** &lt;lxe@lxe.co&gt; <ide> * [matthewloring](https://github.com/matthewloring) - **Matthew Loring** &lt;mattloring@google.com&gt; <ide> * [mcollina](https://github.com/mcollina) - **Matteo Collina** &lt;matteo.collina@gmail.com&gt;
1
Java
Java
resolve collection element types during conversion
5a1f924ac328827c31ced745a65867d4a1feca17
<ide><path>spring-core/src/main/java/org/springframework/core/convert/ClassDescriptor.java <ide> /* <del> * Copyright 2002-2011 the original author or authors. <add> * Copyright 2002-2012 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> <ide> import java.lang.annotation.Annotation; <ide> <add>import org.springframework.core.GenericCollectionTypeResolver; <add> <ide> /** <ide> * @author Keith Donald <add> * @author Phillip Webb <ide> * @since 3.1 <ide> */ <ide> class ClassDescriptor extends AbstractDescriptor { <ide> public Annotation[] getAnnotations() { <ide> } <ide> <ide> @Override <add> @SuppressWarnings({ "unchecked", "rawtypes" }) <ide> protected Class<?> resolveCollectionElementType() { <del> return null; <add> return GenericCollectionTypeResolver.getCollectionType((Class) getType()); <ide> } <ide> <ide> @Override <add> @SuppressWarnings({ "unchecked", "rawtypes" }) <ide> protected Class<?> resolveMapKeyType() { <del> return null; <add> return GenericCollectionTypeResolver.getMapKeyType((Class) getType()); <ide> } <ide> <ide> @Override <add> @SuppressWarnings({ "unchecked", "rawtypes" }) <ide> protected Class<?> resolveMapValueType() { <del> return null; <add> return GenericCollectionTypeResolver.getMapValueType((Class) getType()); <ide> } <ide> <ide> @Override <ide><path>spring-core/src/test/java/org/springframework/core/convert/TypeDescriptorTests.java <ide> import java.util.Collection; <ide> import java.util.Date; <ide> import java.util.HashMap; <add>import java.util.HashSet; <ide> import java.util.List; <ide> import java.util.Map; <ide> <ide> public void testUpCastNotSuper() throws Exception { <ide> } <ide> } <ide> <add> @Test <add> public void elementTypeForCollectionSubclass() throws Exception { <add> @SuppressWarnings("serial") <add> class CustomSet extends HashSet<String> { <add> } <add> <add> assertEquals(TypeDescriptor.valueOf(CustomSet.class).getElementTypeDescriptor(), TypeDescriptor.valueOf(String.class)); <add> assertEquals(TypeDescriptor.forObject(new CustomSet()).getElementTypeDescriptor(), TypeDescriptor.valueOf(String.class)); <add> } <add> <add> @Test <add> public void elementTypeForMapSubclass() throws Exception { <add> @SuppressWarnings("serial") <add> class CustomMap extends HashMap<String, Integer> { <add> } <add> <add> assertEquals(TypeDescriptor.valueOf(CustomMap.class).getMapKeyTypeDescriptor(), TypeDescriptor.valueOf(String.class)); <add> assertEquals(TypeDescriptor.valueOf(CustomMap.class).getMapValueTypeDescriptor(), TypeDescriptor.valueOf(Integer.class)); <add> assertEquals(TypeDescriptor.forObject(new CustomMap()).getMapKeyTypeDescriptor(), TypeDescriptor.valueOf(String.class)); <add> assertEquals(TypeDescriptor.forObject(new CustomMap()).getMapValueTypeDescriptor(), TypeDescriptor.valueOf(Integer.class)); <add> } <add> <ide> }
2
Text
Text
update documentation of `order`
5d94cacb91b96083485781f22d6b0dc44efaad9e
<ide><path>docs/charts/bar.md <ide> the color of the bars is generally set this way. <ide> | ---- | ---- <ide> | `clip` | How to clip relative to chartArea. Positive value allows overflow, negative value clips that many pixels inside chartArea. `0` = clip at chartArea. Clipping can also be configured per side: `clip: {left: 5, top: false, right: -2, bottom: 0}` <ide> | `label` | The label for the dataset which appears in the legend and tooltips. <del>| `order` | The drawing order of dataset. Also affects order for stacking, tooltip, and legend. <add>| `order` | The drawing order of dataset. Also affects order for stacking, tooltip and legend. <ide> | `xAxisID` | The ID of the x axis to plot this dataset on. <ide> | `yAxisID` | The ID of the y axis to plot this dataset on. <ide> <ide><path>docs/charts/bubble.md <ide> The bubble chart allows a number of properties to be specified for each dataset. <ide> | ---- | ---- <ide> | `clip` | How to clip relative to chartArea. Positive value allows overflow, negative value clips that many pixels inside chartArea. `0` = clip at chartArea. Clipping can also be configured per side: `clip: {left: 5, top: false, right: -2, bottom: 0}` <ide> | `label` | The label for the dataset which appears in the legend and tooltips. <del>| `order` | The drawing order of dataset. <add>| `order` | The drawing order of dataset. Also affects order for tooltip and legend. <ide> <ide> ### Styling <ide> <ide><path>docs/charts/line.md <ide> The line chart allows a number of properties to be specified for each dataset. T <ide> | ---- | ---- <ide> | `clip` | How to clip relative to chartArea. Positive value allows overflow, negative value clips that many pixels inside chartArea. `0` = clip at chartArea. Clipping can also be configured per side: `clip: {left: 5, top: false, right: -2, bottom: 0}` <ide> | `label` | The label for the dataset which appears in the legend and tooltips. <del>| `order` | The drawing order of dataset. Also affects order for stacking, tooltip, and legend. <add>| `order` | The drawing order of dataset. Also affects order for stacking, tooltip and legend. <ide> | `xAxisID` | The ID of the x axis to plot this dataset on. <ide> | `yAxisID` | The ID of the y axis to plot this dataset on. <ide> <ide><path>docs/charts/mixed.md <ide> At this point we have a chart rendering how we'd like. It's important to note th <ide> <ide> ## Drawing order <ide> <del> By default, datasets are drawn so that first one is top-most. This can be altered by specifying `order` option to datasets. `order` defaults to `0`. <add> By default, datasets are drawn so that first one is top-most. This can be altered by specifying `order` option to datasets. `order` defaults to `0`. Note that this also affects stacking, legend and tooltip. So its essentially the same as reordering the datasets. <ide> <ide> ```javascript <ide> var mixedChart = new Chart(ctx, { <ide> var mixedChart = new Chart(ctx, { <ide> label: 'Bar Dataset', <ide> data: [10, 20, 30, 40], <ide> // this dataset is drawn below <del> order: 1 <add> order: 2 <ide> }, { <ide> label: 'Line Dataset', <ide> data: [10, 10, 10, 10], <ide> type: 'line', <ide> // this dataset is drawn on top <del> order: 2 <add> order: 1 <ide> }], <ide> labels: ['January', 'February', 'March', 'April'] <ide> }, <ide><path>docs/configuration/legend.md <ide> The chart legend displays data about the datasets that are appearing on the chart. <ide> <ide> ## Configuration options <add> <ide> The legend configuration is passed into the `options.legend` namespace. The global options for the chart legend is defined in `Chart.defaults.global.legend`. <ide> <ide> | Name | Type | Default | Description <ide> The legend configuration is passed into the `options.legend` namespace. The glob <ide> | `textDirection` | `string` | canvas' default | This will force the text direction `'rtl'|'ltr` on the canvas for rendering the legend, regardless of the css specified on the canvas <ide> <ide> ## Position <add> <ide> Position of the legend. Options are: <add> <ide> * `'top'` <ide> * `'left'` <ide> * `'bottom'` <ide> * `'right'` <ide> <ide> ## Align <add> <ide> Alignment of the legend. Options are: <add> <ide> * `'start'` <ide> * `'center'` <ide> * `'end'` <ide> var chart = new Chart(ctx, { <ide> It can be common to want to trigger different behaviour when clicking an item in the legend. This can be easily achieved using a callback in the config object. <ide> <ide> The default legend click handler is: <add> <ide> ```javascript <ide> function(e, legendItem) { <ide> var index = legendItem.datasetIndex;
5
PHP
PHP
remove unused variable, micro optimisation
90660350d77cb93055f0a3fca6698a62f4b258f4
<ide><path>src/I18n/Formatter/SprintfFormatter.php <ide> class SprintfFormatter implements FormatterInterface { <ide> * @return string The formatted message <ide> */ <ide> public function format($locale, $message, array $vars) { <del> $isString = is_string($message); <del> if ($isString && isset($vars['_singular'])) { <add> if (is_string($message) && isset($vars['_singular'])) { <ide> $message = [$vars['_singular'], $message]; <ide> unset($vars['_singular']); <del> $isString = false; <ide> } <ide> <ide> if (is_string($message)) {
1
Javascript
Javascript
remove references to simple_property
49bd20f915892c3e6d002a4794eaacba7112b7e9
<ide><path>packages/ember-metal/lib/mixin.js <ide> function mergeMixins(mixins, m, descs, values, base) { <ide> } else { <ide> // impl super if needed... <ide> if (isMethod(value)) { <del> ovalue = descs[key] === Ember.SIMPLE_PROPERTY && values[key]; <add> ovalue = descs[key] === undefined && values[key]; <ide> if (!ovalue) { ovalue = base[key]; } <ide> if ('function' !== typeof ovalue) { ovalue = null; } <ide> if (ovalue) { <ide><path>packages/ember-metal/lib/properties.js <ide> var extractValue = function(obj, keyName, watching) { <ide> }); <ide> <ide> // define a simple property <del> Ember.defineProperty(contact, 'lastName', Ember.SIMPLE_PROPERTY, 'Jolley'); <add> Ember.defineProperty(contact, 'lastName', undefined, 'Jolley'); <ide> <ide> // define a computed property <ide> Ember.defineProperty(contact, 'fullName', Ember.computed(function() { <ide><path>packages/ember-metal/lib/watching.js <ide> var guidFor = Ember.guidFor, <ide> get = Ember.get, <ide> set = Ember.set, <ide> normalizeTuple = Ember.normalizeTuple.primitive, <del> SIMPLE_PROPERTY = Ember.SIMPLE_PROPERTY, <ide> GUID_KEY = Ember.GUID_KEY, <ide> META_KEY = Ember.META_KEY, <ide> notifyObservers = Ember.notifyObservers, <ide><path>packages/ember-metal/tests/binding/connect_test.js <ide> testBoth('Connecting a binding between two objects through property defined afte <ide> performTest(binding, a, b, get, set, function () { <ide> binding.connect(a); <ide> <del> Ember.defineProperty(a, 'b', Ember.SIMPLE_PROPERTY, b); <add> Ember.defineProperty(a, 'b', undefined, b); <ide> }); <ide> }); <ide> <ide><path>packages/ember-metal/tests/properties_test.js <ide> module('Ember.defineProperty'); <ide> test('toString', function() { <ide> <ide> var obj = {}; <del> Ember.defineProperty(obj, 'toString', Ember.SIMPLE_PROPERTY, function() { return 'FOO'; }); <add> Ember.defineProperty(obj, 'toString', undefined, function() { return 'FOO'; }); <ide> equal(obj.toString(), 'FOO', 'should replace toString'); <ide> }); <ide><path>packages/ember-metal/tests/watching/watch_test.js <ide> test("watching a chain then defining the property", function () { <ide> var foo = {bar: 'bar'}; <ide> Ember.watch(obj, 'foo.bar'); <ide> <del> Ember.defineProperty(obj, 'foo', Ember.SIMPLE_PROPERTY, foo); <add> Ember.defineProperty(obj, 'foo', undefined, foo); <ide> Ember.set(foo, 'bar', 'baz'); <ide> <ide> deepEqual(willKeys, ['bar', 'foo.bar'], 'should have invoked willChange with bar, foo.bar'); <ide> test("watching a chain then defining the nested property", function () { <ide> var baz = {baz: 'baz'}; <ide> Ember.watch(obj, 'foo.bar.baz'); <ide> <del> Ember.defineProperty(bar, 'bar', Ember.SIMPLE_PROPERTY, baz); <add> Ember.defineProperty(bar, 'bar', undefined, baz); <ide> Ember.set(baz, 'baz', 'BOO'); <ide> <ide> deepEqual(willKeys, ['baz', 'foo.bar.baz'], 'should have invoked willChange with bar, foo.bar');
6