content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Javascript
Javascript
fix lint errors
17eaed7f99098ee236e5341d93bfacbcc66a989b
<ide><path>server/boot/a-extendUserIdent.js <ide> export default function({ models }) { <ide> return Observable.throw( <ide> new Error( <ide> dedent` <del> Your GitHub is already associated with another account. You may have accidentally created a duplicate account. <del> No worries, though. We can fix this real quick. Please email us with your GitHub username: team@freecodecamp.com. <add>Your GitHub is already associated with another account. <add>You may have accidentally created a duplicate account. <add>No worries, though. We can fix this real quick. <add>Please email us with your GitHub username: team@freecodecamp.com. <ide> `.split('/n').join(' ') <ide> ) <ide> );
1
Mixed
Python
fix some typos in official/
c1f35955d64a89ed2e2ca919eb84873c581d9441
<ide><path>official/legacy/image_classification/efficientnet/tfhub_export.py <ide> def export_tfhub(model_path, hub_destination, model_name): <ide> image_input = tf.keras.layers.Input( <ide> shape=(None, None, 3), name="image_input", dtype=tf.float32) <ide> x = image_input * 255.0 <del> ouputs = efficientnet_model.efficientnet(x, config) <del> hub_model = tf.keras.Model(image_input, ouputs) <add> outputs = efficientnet_model.efficientnet(x, config) <add> hub_model = tf.keras.Model(image_input, outputs) <ide> ckpt = tf.train.Checkpoint(model=hub_model) <ide> ckpt.restore(model_path).assert_existing_objects_matched() <ide> hub_model.save( <ide><path>official/legacy/transformer/data_download.py <ide> def download_and_extract(path, url, input_filename, target_filename): <ide> Full paths to extracted input and target files. <ide> <ide> Raises: <del> OSError: if the the download/extraction fails. <add> OSError: if the download/extraction fails. <ide> """ <ide> # Check if extracted files already exist in path <ide> input_file = find_file(path, input_filename) <ide><path>official/modeling/optimization/lr_schedule.py <ide> def _make_offset_wrapper(new_class_name: str, base_lr_class): <ide> """Generates a offset wrapper of learning rate schedule. <ide> <del> It will returns a subclass of the the `base_lr_class`, the subclass takes an <add> It will returns a subclass of the `base_lr_class`, the subclass takes an <ide> `offset` argument in the constructor. When the new class instance is called, <ide> the behavior is: <ide> new_class_object(step) = base_lr_class_object(step - offset) <ide><path>official/nlp/data/train_sentencepiece.py <ide> <ide> FLAGS = flags.FLAGS <ide> flags.DEFINE_string("output_model_path", None, <del> "Path to save the the sentencepiece model.") <add> "Path to save the sentencepiece model.") <ide> flags.mark_flag_as_required("output_model_path") <ide> <ide> flags.DEFINE_string("tfds_dir", None, "Directory of the tfds.") <ide><path>official/nlp/docs/train.md <ide> pip3 install --user -r official/requirements.txt <ide> <ide> <details> <ide> <del>This example fine-tunes BERT-base from TF-Hub on the the Multi-Genre Natural <add>This example fine-tunes BERT-base from TF-Hub on the Multi-Genre Natural <ide> Language Inference (MultiNLI) corpus using TPUs. <ide> <ide> Firstly, you can prepare the fine-tuning data using <ide><path>official/nlp/modeling/layers/README.md <ide> assemble new `tf.keras` layers or models. <ide> ["Big Bird: Transformers for Longer Sequences"](https://arxiv.org/abs/2007.14062). <ide> <ide> * [CachedAttention](attention.py) implements an attention layer with cache <del> used for auto-agressive decoding. <add> used for auto-aggressive decoding. <ide> <ide> * [KernelAttention](kernel_attention.py) implements a group of attention <ide> mechansim that express the self-attention as a linear dot-product of <ide><path>official/nlp/modeling/layers/gaussian_process.py <ide> def reset_covariance_matrix(self): <ide> """Resets covariance matrix of the GP layer. <ide> <ide> This function is useful for reseting the model's covariance matrix at the <del> begining of a new epoch. <add> beginning of a new epoch. <ide> """ <ide> self._gp_cov_layer.reset_precision_matrix() <ide> <ide> def reset_precision_matrix(self): <ide> """Resets precision matrix to its initial value. <ide> <ide> This function is useful for reseting the model's covariance matrix at the <del> begining of a new epoch. <add> beginning of a new epoch. <ide> """ <ide> precision_matrix_reset_op = self.precision_matrix.assign( <ide> self.initial_precision_matrix) <ide><path>official/nlp/modeling/layers/reuse_attention.py <ide> def _build_attention(self, rank): <ide> """Builds multi-head dot-product attention computations. <ide> <ide> This function builds attributes necessary for `_compute_attention` to <del> costomize attention computation to replace the default dot-product <add> customize attention computation to replace the default dot-product <ide> attention. <ide> <ide> Args: <ide><path>official/nlp/modeling/ops/beam_search.py <ide> def _grow_alive_seq(state): <ide> candidate_log_probs = _log_prob_from_logits(logits) <ide> <ide> # Calculate new log probabilities if each of the alive sequences were <del> # extended # by the the candidate IDs. <add> # extended # by the candidate IDs. <ide> # Shape [batch_size, beam_size, vocab_size] <ide> log_probs = candidate_log_probs + tf.expand_dims(alive_log_probs, axis=2) <ide> <ide><path>official/projects/edgetpu/nlp/modeling/edgetpu_layers.py <ide> def _build_attention(self, rank): <ide> """Builds multi-head dot-product attention computations. <ide> <ide> This function builds attributes necessary for `_compute_attention` to <del> costomize attention computation to replace the default dot-product <add> customize attention computation to replace the default dot-product <ide> attention. <ide> <ide> Args: <ide><path>official/projects/edgetpu/vision/tasks/image_classification.py <ide> def train_step(self, <ide> """Does forward and backward. <ide> <ide> Args: <del> inputs: A tuple of of input tensors of (features, labels). <add> inputs: A tuple of input tensors of (features, labels). <ide> model: A tf.keras.Model instance. <ide> optimizer: The optimizer for this training step. <ide> metrics: A nested structure of metrics objects. <ide> def validation_step(self, <ide> """Runs validatation step. <ide> <ide> Args: <del> inputs: A tuple of of input tensors of (features, labels). <add> inputs: A tuple of input tensors of (features, labels). <ide> model: A tf.keras.Model instance. <ide> metrics: A nested structure of metrics objects. <ide> <ide><path>official/projects/video_ssl/modeling/video_ssl_model.py <ide> def __init__(self, <ide> hidden_dim: `int` number of hidden units in MLP. <ide> hidden_layer_num: `int` number of hidden layers in MLP. <ide> hidden_norm_args: `dict` for batchnorm arguments in MLP. <del> projection_dim: `int` number of ouput dimension for MLP. <add> projection_dim: `int` number of output dimension for MLP. <ide> input_specs: `tf.keras.layers.InputSpec` specs of the input tensor. <ide> dropout_rate: `float` rate for dropout regularization. <ide> aggregate_endpoints: `bool` aggregate all end ponits or only use the <ide><path>official/projects/yt8m/dataloaders/yt8m_input.py <ide> <ide> <ide> def resize_axis(tensor, axis, new_size, fill_value=0): <del> """Truncates or pads a tensor to new_size on on a given axis. <add> """Truncates or pads a tensor to new_size on a given axis. <ide> <ide> Truncate or extend tensor such that tensor.shape[axis] == new_size. If the <ide> size increases, the padding will be performed at the end, using fill_value. <ide><path>official/vision/beta/projects/centernet/README.md <ide> heatmaps (one heatmap for each class) is needed to predict the object. CenterNet <ide> proves that this can be done without a significant difference in accuracy. <ide> <ide> <del>## Enviroment setup <add>## Environment setup <ide> <ide> The code can be run on multiple GPUs or TPUs with different distribution <ide> strategies. See the TensorFlow distributed training <ide><path>official/vision/beta/projects/simclr/README.md <ide> An illustration of SimCLR (from <a href="https://ai.googleblog.com/2020/04/advancing-self-supervised-and-semi.html">our blog here</a>). <ide> </div> <ide> <del>## Enviroment setup <add>## Environment setup <ide> <ide> The code can be run on multiple GPUs or TPUs with different distribution <ide> strategies. See the TensorFlow distributed training <ide><path>official/vision/beta/projects/yolo/losses/yolo_loss.py <ide> def _compute_loss(self, true_counts, inds, y_true, boxes, classes, y_pred): <ide> grid_points = tf.stop_gradient(grid_points) <ide> anchor_grid = tf.stop_gradient(anchor_grid) <ide> <del> # Split all the ground truths to use as seperate items in loss computation. <add> # Split all the ground truths to use as separate items in loss computation. <ide> (true_box, ind_mask, true_class) = tf.split(y_true, [4, 1, 1], axis=-1) <ide> true_conf = tf.squeeze(true_conf, axis=-1) <ide> true_class = tf.squeeze(true_class, axis=-1) <ide><path>official/vision/beta/projects/yolo/modeling/layers/nn_blocks.py <ide> class CSPStack(tf.keras.layers.Layer): <ide> make it a cross stage partial. Added for ease of use. you should be able <ide> to wrap any layer stack with a CSP independent of wether it belongs <ide> to the Darknet family. if filter_scale = 2, then the blocks in the stack <del> passed into the the CSP stack should also have filters = filters/filter_scale <add> passed into the CSP stack should also have filters = filters/filter_scale <ide> Cross Stage Partial networks (CSPNets) were proposed in: <ide> <ide> [1] Chien-Yao Wang, Hong-Yuan Mark Liao, I-Hau Yeh, Yueh-Hua Wu, <ide><path>official/vision/data/create_coco_tf_record.py <ide> def generate_coco_panoptics_masks(segments_info, mask_path, <ide> represent "stuff" and "things" classes respectively. <ide> <ide> Returns: <del> A dict with with keys: [u'semantic_segmentation_mask', u'category_mask', <add> A dict with keys: [u'semantic_segmentation_mask', u'category_mask', <ide> u'instance_mask']. The dict contains 'category_mask' and 'instance_mask' <ide> only if `include_panoptic_eval_masks` is set to True. <ide> """ <ide><path>official/vision/examples/starter/example_task.py <ide> def train_step(self, <ide> between output from Parser and input used here. <ide> <ide> Args: <del> inputs: A tuple of of input tensors of (features, labels). <add> inputs: A tuple of input tensors of (features, labels). <ide> model: A tf.keras.Model instance. <ide> optimizer: The optimizer for this training step. <ide> metrics: A nested structure of metrics objects. <ide> def validation_step(self, <ide> """Runs validatation step. <ide> <ide> Args: <del> inputs: A tuple of of input tensors of (features, labels). <add> inputs: A tuple of input tensors of (features, labels). <ide> model: A tf.keras.Model instance. <ide> metrics: A nested structure of metrics objects. <ide> <ide><path>official/vision/ops/box_ops.py <ide> def bbox_overlap(boxes, gt_boxes): <ide> tf.transpose(gt_invalid_mask, [0, 2, 1])) <ide> iou = tf.where(padding_mask, -tf.ones_like(iou), iou) <ide> <del> # Fills -1 for for invalid (-1) boxes. <add> # Fills -1 for invalid (-1) boxes. <ide> boxes_invalid_mask = tf.less( <ide> tf.reduce_max(boxes, axis=-1, keepdims=True), 0.0) <ide> iou = tf.where(boxes_invalid_mask, -tf.ones_like(iou), iou) <ide><path>official/vision/tasks/image_classification.py <ide> def train_step(self, <ide> """Does forward and backward. <ide> <ide> Args: <del> inputs: A tuple of of input tensors of (features, labels). <add> inputs: A tuple of input tensors of (features, labels). <ide> model: A tf.keras.Model instance. <ide> optimizer: The optimizer for this training step. <ide> metrics: A nested structure of metrics objects. <ide> def validation_step(self, <ide> """Runs validatation step. <ide> <ide> Args: <del> inputs: A tuple of of input tensors of (features, labels). <add> inputs: A tuple of input tensors of (features, labels). <ide> model: A tf.keras.Model instance. <ide> metrics: A nested structure of metrics objects. <ide> <ide><path>official/vision/utils/object_detection/balanced_positive_negative_sampler.py <ide> def _get_num_pos_neg_samples(self, sorted_indices_tensor, sample_size): <ide> sorted_indices_tensor: A sorted int32 tensor of shape [N] which contains <ide> the signed indices of the examples where the sign is based on the label <ide> value. The examples that cannot be sampled are set to 0. It samples <del> atmost sample_size*positive_fraction positive examples and remaining <add> at most sample_size*positive_fraction positive examples and remaining <ide> from negative examples. <ide> sample_size: Size of subsamples. <ide>
22
Javascript
Javascript
add documentation on .focus and .blur
bb98fddbec357e3966be3f599c79266de8ccbe9f
<ide><path>Libraries/Components/TextInput/TextInput.js <ide> const DataDetectorTypes = [ <ide> * AppRegistry.registerComponent('AwesomeProject', () => UselessTextInput); <ide> * ``` <ide> * <add> * Two methods exposed via the native element are .focus() and .blur() that <add> * will focus or blur the TextInput programmatically. <add> * <ide> * Note that some props are only available with `multiline={true/false}`. <ide> * Additionally, border styles that apply to only one side of the element <ide> * (e.g., `borderBottomColor`, `borderLeftWidth`, etc.) will not be applied if
1
Ruby
Ruby
simplify implementation of `mysqldatabasetasks`
a37d03c4b08451765acc721b51a4b5b7eab7e8cc
<ide><path>activerecord/lib/active_record/railties/jdbcmysql_error.rb <del># frozen_string_literal: true <del> <del>#FIXME Remove if ArJdbcMysql will give. <del>module ArJdbcMySQL #:nodoc: <del> class Error < StandardError #:nodoc: <del> attr_accessor :error_number, :sql_state <del> <del> def initialize(msg) <del> super <del> @error_number = nil <del> @sql_state = nil <del> end <del> <del> # Mysql gem compatibility <del> alias_method :errno, :error_number <del> alias_method :error, :message <del> end <del>end <ide><path>activerecord/lib/active_record/tasks/mysql_database_tasks.rb <ide> module ActiveRecord <ide> module Tasks # :nodoc: <ide> class MySQLDatabaseTasks # :nodoc: <del> ACCESS_DENIED_ERROR = 1045 <del> <ide> delegate :connection, :establish_connection, to: ActiveRecord::Base <ide> <ide> def initialize(configuration) <ide> def create <ide> else <ide> raise <ide> end <del> rescue error_class => error <del> if error.respond_to?(:errno) && error.errno == ACCESS_DENIED_ERROR <del> $stdout.print error.message <del> establish_connection root_configuration_without_database <del> connection.create_database configuration["database"], creation_options <del> if configuration["username"] != "root" <del> connection.execute grant_statement.gsub(/\s+/, " ").strip <del> end <del> establish_connection configuration <del> else <del> raise <del> end <ide> end <ide> <ide> def drop <ide> def creation_options <ide> end <ide> end <ide> <del> def error_class <del> if configuration["adapter"].include?("jdbc") <del> require "active_record/railties/jdbcmysql_error" <del> ArJdbcMySQL::Error <del> elsif defined?(Mysql2) <del> Mysql2::Error <del> else <del> StandardError <del> end <del> end <del> <del> def grant_statement <del> <<-SQL <del>GRANT ALL PRIVILEGES ON `#{configuration['database']}`.* <del> TO '#{configuration['username']}'@'localhost' <del>IDENTIFIED BY '#{configuration['password']}' WITH GRANT OPTION; <del> SQL <del> end <del> <del> def root_configuration_without_database <del> configuration_without_database.merge( <del> "username" => "root", <del> "password" => root_password <del> ) <del> end <del> <del> def root_password <del> $stdout.print "Please provide the root password for your MySQL installation\n>" <del> $stdin.gets.strip <del> end <del> <ide> def prepare_command_options <ide> args = { <ide> "host" => "--host", <ide><path>activerecord/test/cases/tasks/mysql_rake_test.rb <ide> def test_create_when_database_exists_outputs_info_to_stderr <ide> end <ide> end <ide> <del> class MysqlDBCreateAsRootTest < ActiveRecord::TestCase <add> class MysqlDBCreateWithInvalidPermissionsTest < ActiveRecord::TestCase <ide> def setup <ide> @connection = stub("Connection", create_database: true) <ide> @error = Mysql2::Error.new("Invalid permissions") <ide> def setup <ide> "password" => "wossname" <ide> } <ide> <del> $stdin.stubs(:gets).returns("secret\n") <del> $stdout.stubs(:print).returns(nil) <del> @error.stubs(:errno).returns(1045) <ide> ActiveRecord::Base.stubs(:connection).returns(@connection) <del> ActiveRecord::Base.stubs(:establish_connection). <del> raises(@error). <del> then.returns(true) <add> ActiveRecord::Base.stubs(:establish_connection).raises(@error) <ide> <ide> $stdout, @original_stdout = StringIO.new, $stdout <ide> $stderr, @original_stderr = StringIO.new, $stderr <ide> def teardown <ide> $stdout, $stderr = @original_stdout, @original_stderr <ide> end <ide> <del> def test_root_password_is_requested <del> assert_permissions_granted_for("pat") <del> $stdin.expects(:gets).returns("secret\n") <del> <del> ActiveRecord::Tasks::DatabaseTasks.create @configuration <del> end <del> <del> def test_connection_established_as_root <del> assert_permissions_granted_for("pat") <del> ActiveRecord::Base.expects(:establish_connection).with( <del> "adapter" => "mysql2", <del> "database" => nil, <del> "username" => "root", <del> "password" => "secret" <del> ) <del> <del> ActiveRecord::Tasks::DatabaseTasks.create @configuration <del> end <del> <del> def test_database_created_by_root <del> assert_permissions_granted_for("pat") <del> @connection.expects(:create_database). <del> with("my-app-db", {}) <del> <del> ActiveRecord::Tasks::DatabaseTasks.create @configuration <del> end <del> <del> def test_grant_privileges_for_normal_user <del> assert_permissions_granted_for("pat") <del> ActiveRecord::Tasks::DatabaseTasks.create @configuration <del> end <del> <del> def test_do_not_grant_privileges_for_root_user <del> @configuration["username"] = "root" <del> @configuration["password"] = "" <del> ActiveRecord::Tasks::DatabaseTasks.create @configuration <del> end <del> <del> def test_connection_established_as_normal_user <del> assert_permissions_granted_for("pat") <del> ActiveRecord::Base.expects(:establish_connection).returns do <del> ActiveRecord::Base.expects(:establish_connection).with( <del> "adapter" => "mysql2", <del> "database" => "my-app-db", <del> "username" => "pat", <del> "password" => "secret" <del> ) <del> <del> raise @error <del> end <del> <del> ActiveRecord::Tasks::DatabaseTasks.create @configuration <del> end <del> <del> def test_raises_error_when_other_errors <del> @error.stubs(:errno).returns(42) <del> <add> def test_raises_error <ide> assert_raises(Mysql2::Error) do <ide> ActiveRecord::Tasks::DatabaseTasks.create @configuration <ide> end <ide> end <del> <del> private <del> <del> def assert_permissions_granted_for(db_user) <del> db_name = @configuration["database"] <del> db_password = @configuration["password"] <del> @connection.expects(:execute).with("GRANT ALL PRIVILEGES ON `#{db_name}`.* TO '#{db_user}'@'localhost' IDENTIFIED BY '#{db_password}' WITH GRANT OPTION;") <del> end <ide> end <ide> <ide> class MySQLDBDropTest < ActiveRecord::TestCase
3
Javascript
Javascript
remove unsupported property "optimize"
9879466df6e0c167e8ebfb4594bcf42aaf49265c
<ide><path>test/Examples.test.js <ide> describe("Examples", function() { <ide> <ide> function processOptions(options) { <ide> options.context = examplePath; <del> options.optimize = options.optimize || {}; <ide> options.output = options.output || {}; <ide> options.output.pathInfo = true; <ide> options.output.path = path.join(examplePath, "js");
1
Text
Text
fix a typo in the code of testing guide
54c1cdf4ce36fd4d0a5e7036d61ad35a9e8841e3
<ide><path>guides/source/testing.md <ide> instance variable: <ide> <ide> ```ruby <ide> # setting a HTTP Header <del>@request.headers["Accepts"] = "text/plain, text/html" <add>@request.headers["Accept"] = "text/plain, text/html" <ide> get :index # simulate the request with custom header <ide> <ide> # setting a CGI variable
1
Python
Python
remove unused import
31a303c38f42649972755fdacf6f27de62e79000
<ide><path>keras/layers/core.py <ide> import numpy as np <ide> <ide> from .. import activations, initializations <del>from ..utils.theano_utils import shared_zeros, floatX, shared_scalar <add>from ..utils.theano_utils import shared_zeros, floatX <ide> from ..utils.generic_utils import make_tuple <ide> from .. import regularizers <ide> from .. import constraints
1
PHP
PHP
remove unused parameter
9f80004920a396d8a6e9e1c46c58155657d4158a
<ide><path>lib/Cake/Test/Case/Utility/SetTest.php <ide> public function testRemove() { <ide> 'files' => array('name' => 'files') <ide> ); <ide> <del> $result = Set::remove($a, 'files', array('name' => 'files')); <add> $result = Set::remove($a, 'files'); <ide> $expected = array( <ide> 'pages' => array('name' => 'page') <ide> ); <ide> public function testRemove() { <ide> ) <ide> ); <ide> <del> $result = Set::remove($a, 'pages.1.vars', array('title' => 'page title')); <add> $result = Set::remove($a, 'pages.1.vars'); <ide> $expected = array( <ide> 'pages' => array( <ide> 0 => array('name' => 'main'), <ide> public function testRemove() { <ide> ); <ide> $this->assertEquals($expected, $result); <ide> <del> $result = Set::remove($a, 'pages.2.vars', array('title' => 'page title')); <add> $result = Set::remove($a, 'pages.2.vars'); <ide> $expected = $a; <ide> $this->assertEquals($expected, $result); <ide> }
1
Text
Text
create model-card for lordtt13/emo-mobilebert
dc4755c6d59238ffea4843d06610a29c522257fb
<ide><path>model_cards/lordtt13/emo-mobilebert/README.md <add>--- <add>language: en <add>datasets: <add>- emo <add>--- <add> <add>## Emo-MobileBERT: a thin version of BERT LARGE, trained on the EmoContext Dataset from scratch <add> <add>### Details of MobileBERT <add> <add>The **MobileBERT** model was presented in [MobileBERT: a Compact Task-Agnostic BERT for Resource-Limited Devices](https://arxiv.org/abs/2004.02984) by *Zhiqing Sun, Hongkun Yu, Xiaodan Song, Renjie Liu, Yiming Yang, Denny Zhou* and here is the abstract: <add> <add>Natural Language Processing (NLP) has recently achieved great success by using huge pre-trained models with hundreds of millions of parameters. However, these models suffer from heavy model sizes and high latency such that they cannot be deployed to resource-limited mobile devices. In this paper, we propose MobileBERT for compressing and accelerating the popular BERT model. Like the original BERT, MobileBERT is task-agnostic, that is, it can be generically applied to various downstream NLP tasks via simple fine-tuning. Basically, MobileBERT is a thin version of BERT_LARGE, while equipped with bottleneck structures and a carefully designed balance between self-attentions and feed-forward networks. To train MobileBERT, we first train a specially designed teacher model, an inverted-bottleneck incorporated BERT_LARGE model. Then, we conduct knowledge transfer from this teacher to MobileBERT. Empirical studies show that MobileBERT is 4.3x smaller and 5.5x faster than BERT_BASE while achieving competitive results on well-known benchmarks. On the natural language inference tasks of GLUE, MobileBERT achieves a GLUEscore o 77.7 (0.6 lower than BERT_BASE), and 62 ms latency on a Pixel 4 phone. On the SQuAD v1.1/v2.0 question answering task, MobileBERT achieves a dev F1 score of 90.0/79.2 (1.5/2.1 higher than BERT_BASE). <add> <add>### Details of the downstream task (Emotion Recognition) - Dataset 📚 <add> <add>SemEval-2019 Task 3: EmoContext Contextual Emotion Detection in Text <add> <add>In this dataset, given a textual dialogue i.e. an utterance along with two previous turns of context, the goal was to infer the underlying emotion of the utterance by choosing from four emotion classes: <add> <add> - sad 😢 <add> - happy 😃 <add> - angry 😡 <add> - others <add> <add>### Model training <add> <add>The training script is present [here](https://github.com/lordtt13/transformers-experiments/blob/master/Custom%20Tasks/emo-mobilebert.ipynb). <add> <add>### Pipelining the Model <add> <add>```python <add>from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline <add> <add>tokenizer = AutoTokenizer.from_pretrained("lordtt13/emo-mobilebert") <add> <add>model = AutoModelForSequenceClassification.from_pretrained("lordtt13/emo-mobilebert") <add> <add>nlp_sentence_classif = transformers.pipeline('sentiment-analysis', model = model, tokenizer = tokenizer) <add>nlp_sentence_classif("I've never had such a bad day in my life") <add># Output: [{'label': 'sad', 'score': 0.93153977394104}] <add>``` <add> <add>> Created by [Tanmay Thakur](https://github.com/lordtt13) | [LinkedIn](https://www.linkedin.com/in/tanmay-thakur-6bb5a9154/)
1
Ruby
Ruby
load all records in relation#inspect
d8ca791f48ea096d0e19bdc0ef1d021764a79f20
<ide><path>activerecord/lib/active_record/relation.rb <ide> def values <ide> end <ide> <ide> def inspect <del> limit = [limit_value, 11].compact.min <del> entries = loaded? ? to_a.take(limit) : limit(limit) <del> <del> entries.map!(&:inspect) <add> entries = to_a.take([limit_value, 11].compact.min).map!(&:inspect) <ide> entries[10] = '...' if entries.size == 11 <ide> <ide> "#<#{self.class.name} [#{entries.join(', ')}]>"
1
PHP
PHP
use getrequest() instead of request
698ad5d27beed9dd9c8fa6a1ec5ad2278dd5bf15
<ide><path>src/Controller/Component/CsrfComponent.php <ide> class CsrfComponent extends Component <ide> */ <ide> public function initialize(array $config) <ide> { <del> if ($this->getController()->request->getParam('_csrfToken') !== false) { <add> if ($this->getController()->getRequest()->getParam('_csrfToken') !== false) { <ide> triggerWarning('CSRF token already defined. Disable CsrfComponent if you use CsrfProtectionMiddleware.'); <ide> } <ide> }
1
PHP
PHP
remove extra indentation
3792fb19746b65b3455ca43ee1bba793fbc1f04e
<ide><path>src/TestSuite/TestCase.php <ide> public function deprecated($callable) <ide> { <ide> $errorLevel = error_reporting(); <ide> error_reporting(E_ALL ^ E_USER_DEPRECATED); <del> $callable(); <add> $callable(); <ide> error_reporting($errorLevel); <ide> } <ide>
1
PHP
PHP
remove requestaction from requesthandlercomponent
0930645a43092da6c4d06f4e4eecc5191d25c02a
<ide><path>lib/Cake/Controller/Component/RequestHandlerComponent.php <ide> use Cake\Core\App; <ide> use Cake\Core\Configure; <ide> use Cake\Error; <del>use Cake\Routing\RequestActionTrait; <ide> use Cake\Routing\Router; <ide> use Cake\Utility\Inflector; <ide> use Cake\Utility\Xml; <ide> */ <ide> class RequestHandlerComponent extends Component { <ide> <del> use RequestActionTrait; <del> <ide> /** <ide> * The layout that will be switched to for Ajax requests <ide> * <ide> public function beforeRedirect(Controller $controller, $url, $status = null, $ex <ide> $code = key($statusCode); <ide> $this->response->statusCode($code); <ide> } <del> $this->response->body($this->requestAction($url, array('return', 'bare' => false))); <add> $this->response->body($controller->requestAction($url, array('return', 'bare' => false))); <ide> $this->response->send(); <ide> $this->_stop(); <ide> }
1
Text
Text
update triaging guidelines
41e648a47f70c8e82cfbb11012c83255d051d528
<ide><path>TRIAGING.md <ide> # Triage new issues/PRs on github <ide> <ide> This document shows the steps the Angular team is using to triage issues. <del>The labels are used later on for planning releases. <add>The labels are used later on for [planning releases](#assigning-work). <ide> <del>## Tips ## <ide> <del>* Label "resolution:*" <del> * these tags can be used for labeling a closed issue/PR with a reason why it was closed. (we can add reasons as we need them, right there are only a few rejection reasons. it doesn't make sense to label issues that were fixed or prs that were merged) <add>## Automatic processing <ide> <add>We have tools (e.g. [Mary Poppins]) that automatically add comments and labels to issues and PRs. <add>The following is done automatically so you don't have to worry about it: <ide> <del>## Automatic processing ## <add>* Label `cla: yes` or `cla: no` for pull requests <add>* Label `GH: *` <add> * `PR` - issue is a PR <add> * `issue` - otherwise <ide> <del>We have automatic tools (e.g. Mary Poppins) that automatically add comments / labels to issues and PRs. <del>The following is done automatically and should not be done manually: <ide> <del>* Label "cla: yes" or "cla: no" for pull requests <add>## Triaging Process <ide> <del>## Process ## <add>This process based on the idea of minimizing user pain <add>[from this blog post](http://www.lostgarden.com/2008/05/improving-bug-triage-with-user-pain.html). <ide> <del>1. Open list of [non triaged issues](https://github.com/angular/angular.js/issues?direction=desc&milestone=none&page=1&sort=created&state=open) <add>1. Open the list of [non triaged issues](https://github.com/angular/angular.js/issues?direction=desc&milestone=none&page=1&sort=created&state=open) <add> * Sort by submit date, with the newest issues first <add> * You don't have to do issues in order; feel free to pick and choose issues as you please. <add> * You can triage older issues as well <add> * Triage to your heart's content <ide> 1. Assign yourself: Pick an issue that is not assigned to anyone and assign it to you <del>1. Assign milestone: <del> * "Docs only" milestone - for documentation PR -> **Done**. <del> * Current/next milestone - regressions <del> * 1.2.x - everything else <del>1. Label "GH: *" (to be automated via Mary Poppins) <del> * PR - issue is a PR <del> * issue - otherwise <add> <add>1. Understandable? - verify if the description of the request is clear. <add> * If not, [close it][] according to the instructions below and go to the last step. <add>1. Duplicate? <add> * If you've seen this issue before [close it][], and go to the last step. <add> * Check if there are comments that link to a dupe. If so verify that this is indeed a dupe, [close it][], and go to the last step. <ide> 1. Bugs: <del> * Label "Type: Bug" <del> * Label "Type: Regression" - if the bug is a regression <del> * Duplicate? - Check if there are comments pointing out that this is a dupe, if they do exist verify that this is indeed a dupe and close it and go to the last step <del> * Reproducible? - Steps to reproduce the bug are clear, if not ask for clarification (ideally plunker or fiddle) <del> * Reproducible on master? - http://code.angularjs.org/snapshot/ <add> * Label `Type: Bug` <add> * Reproducible? - Steps to reproduce the bug are clear. If they are not, <add> * Reproducible on master? - <http://code.angularjs.org/snapshot/> <ide> <ide> 1. Non bugs: <del> * Label "Type: Feature" or "Type: Chore" or "Type: Perf" <del> * Label "needs: breaking change" - if needed <del> * Label "needs: public api" - if a new public api is needed <del> * Understandable? - verify if the description of the request is clear. if not ask for clarification <del> * Goals of angular core? - Often new features should be implemented as a third-party module rather than an addition to the core. <del> <del>1. Label "component: *" <add> * Label `Type: Feature`, `Type: Chore`, or `Type: Perf` <add> * Belongs in core? – Often new features should be implemented as a third-party module rather than an addition to the core. <add> If this doesn't belong, [close it][], and go to the last step. <add> * Label `needs: breaking change` - if needed <add> * Label `needs: public api` - if the issue requires introduction of a new public API <add>1. Label `browser: *` - if the issue **only** affects a certain browser <add>1. Label `frequency: *` – How often does this issue come up? How many developers does this affect? <add> * low - obscure issue affecting a handful of developers <add> * moderate - impacts a common usage pattern <add> * high - impacts most or all Angular apps <add>1. Label `severity: *` - How bad is the issue? <add> * security issue <add> * regression <add> * memory leak <add> * broken expected use - it's hard or impossible for a developer using Angular to accomplish something that Angular should be able to do <add> * confusing - unexpected or inconsistent behavior; hard-to-debug <add> * inconvenience - causes ugly/boilerplate code in apps <add>1. Label `component: *` <ide> * In rare cases, it's ok to have multiple components. <del>1. Label "impact: *" <del> * small - obscure issue affecting one or handful of developers <del> * medium - impacts some usage patterns <del> * large - impacts most or all of angular apps <del>1. Label "complexity: *" <del> * small - trivial change <del> * medium - non-trivial but straightforward change <del> * large - changes to many components in angular or any changes to $compile, ngRepeat or other "fun" components <del>1. Label "PRs plz!" for "GH: issue" <del> * if complexity is small or medium and the problem as well as solution are well captured in the issue <del>1. Label "origin: google" for issues from Google <del>1. Label "high priority" for security issues, major performance regressions or memory leaks <add>1. Label `PRs plz!` - These issues are good targets for PRs from the open source community. Apply to issues where the problem and solution are well defined in the comments, and it's not too complex. <add>1. Label `origin: google` for issues from Google <add> <add>1. Assign a milestone: <add> * Current 1.x.y milestone - regressions and urgent bugs only <add> * Backlog - fixes; changes that should go into a patch release <add> * Ice Box - new features; changes that belong inß a major/minor release <ide> <ide> 1. Unassign yourself from the issue <ide> <ide> <add>## Tips <add> <add>* Label `resolution: *` <add> * these tags can be used for labeling a closed issue/PR with a reason why it was closed. <add> * Right now there are only a few rejection reasons, but we can add more as needed. Feel free to suggest one to a core team member. We don't use this label for issues that were fixed or PRs that were merged. <add> <add> <add>## Closing an Issue or PR <add> <add>We're grateful to anyone who takes the time to submit an issue, even if we ultimately decide not to act on it. <add>Be kind and respectful as you close issues. Be sure to follow the [code of conduct][]. <add> <add>1. Always thank the person who submitted it. <add>1. If it's a duplicate, link to the older or more descriptive issue that supersedes the one you are closing. <add>1. Let them know if there's some way for them to follow-up. <add> * When the issue is unclear or reproducible, note that you'll reopen it if they can clarify or provide a better example. Mention [plunker] or [fiddle] for examples. Watch your notifications and follow-up if they do provide clarification. :) <add> * If appropriate, suggest implementing a feature as a third-party module. <add> <add>If in doubt, ask a core team member what to do. <add>[Brian](https://github.com/btford) is probably the person to ask. <add>You can mention him in the relevant thread like this: `@btford`. <add> <add>**Example:** <add> <add>> Thanks for submitting this issue! <add>> Unfortunately, we don't think this functionality belongs in core. <add>> The good news is that you could easily implement this as a third-party module and publish it on Bower and/or npm. <add> <add> <add>## Assigning Work <add> <add>These criteria are then used to calculate a "user pain" score. <add>Work is assigned weekly to core team members starting with the highest pain, descending down to the lowest. <add> <add>``` <add>pain = severity × frequency <add>``` <add> <add>**severity:** <add> <add>- security issue (6) <add>- regression (5) <add>- memory leak (4) <add>- broken expected use (3) <add>- confusing (2) <add>- inconvenience (1) <add> <add>**frequency:** <add> <add>- low (1) <add>- moderate (2) <add>- high (3) <add> <add>**Note:** Security issues, regressions, and memory leaks should almost always be set to `frequency: high`. <add> <add> <ide> [![Analytics](https://ga-beacon.appspot.com/UA-8594346-11/angular.js/TRIAGING.md?pixel)](https://github.com/igrigorik/ga-beacon) <add> <add> <add>[close it]: #closing-an-issue-or-pr <add>[code of conduct]: https://github.com/angular/code-of-conduct/blob/master/CODE_OF_CONDUCT.md <add>[Mary Poppins]: https://github.com/btford/mary-poppins <add>[plunker]: http://plnkr.co/ <add>[fiddle]: http://jsfiddle.net/
1
Javascript
Javascript
fix code style/grammar on synthetic event warning
42602a8922398901c4e29c1958993190f74e3249
<ide><path>src/renderers/dom/client/syntheticEvents/SyntheticEvent.js <ide> assign(SyntheticEvent.prototype, { <ide> this.defaultPrevented = true; <ide> var event = this.nativeEvent; <ide> if (__DEV__) { <del> warning(event, <del> 'This Synthetic event is reused for performance reasons. If you\'re seeing this, ' + <del> 'you\'re calling `preventDefault` on a released/nullified Synthetic event. ' + <del> 'This is a no-op. See https://facebook.github.io/react/docs/events.html#event-pooling ' + <del> 'for more information.' <add> warning( <add> event, <add> 'This synthetic event is reused for performance reasons. If you\'re ' + <add> 'seeing this, you\'re calling `preventDefault` on a ' + <add> 'released/nullified synthetic event. This is a no-op. See ' + <add> 'https://fb.me/react-event-pooling for more information.' <ide> ); <ide> } <del> if (!event) return; <add> if (!event) { <add> return; <add> } <ide> <ide> if (event.preventDefault) { <ide> event.preventDefault(); <ide> assign(SyntheticEvent.prototype, { <ide> stopPropagation: function() { <ide> var event = this.nativeEvent; <ide> if (__DEV__) { <del> warning(event, <del> 'This Synthetic event is reused for performance reasons. If you\'re seeing this, ' + <del> 'you\'re calling `stopPropagation` on a released/nullified Synthetic event. ' + <del> 'This is a no-op. See https://facebook.github.io/react/docs/events.html#event-pooling ' + <del> 'for more information.' <add> warning( <add> event, <add> 'This synthetic event is reused for performance reasons. If you\'re ' + <add> 'seeing this, you\'re calling `stopPropagation` on a ' + <add> 'released/nullified synthetic event. This is a no-op. See ' + <add> 'https://fb.me/react-event-pooling for more information.' <ide> ); <ide> } <del> if (!event) return; <add> if (!event) { <add> return; <add> } <ide> <ide> if (event.stopPropagation) { <ide> event.stopPropagation(); <ide><path>src/renderers/dom/client/syntheticEvents/__tests__/SyntheticEvent-test.js <ide> describe('SyntheticEvent', function() { <ide> expect(syntheticEvent.isPersistent()).toBe(true); <ide> }); <ide> <del> it('should warn if the Synthetic event has been released when calling `preventDefault`', function() { <add> it('should warn if the synthetic event has been released when calling `preventDefault`', function() { <ide> spyOn(console, 'error'); <ide> var syntheticEvent = createEvent({}); <ide> SyntheticEvent.release(syntheticEvent); <ide> syntheticEvent.preventDefault(); <ide> expect(console.error.calls.length).toBe(1); <ide> expect(console.error.argsForCall[0][0]).toBe( <del> 'Warning: ' + <del> 'This Synthetic event is reused for performance reasons. If you\'re seeing this, ' + <del> 'you\'re calling `preventDefault` on a released/nullified Synthetic event. ' + <del> 'This is a no-op. See https://facebook.github.io/react/docs/events.html#event-pooling ' + <del> 'for more information.' <add> 'Warning: This synthetic event is reused for performance reasons. If ' + <add> 'you\'re seeing this, you\'re calling `preventDefault` on a ' + <add> 'released/nullified synthetic event. This is a no-op. See ' + <add> 'https://fb.me/react-event-pooling for more information.' <ide> ); <ide> }); <ide> <del> it('should warn if the Synthetic event has been released when calling `stopPropagation`', function() { <add> it('should warn if the synthetic event has been released when calling `stopPropagation`', function() { <ide> spyOn(console, 'error'); <ide> var syntheticEvent = createEvent({}); <ide> SyntheticEvent.release(syntheticEvent); <ide> syntheticEvent.stopPropagation(); <ide> expect(console.error.calls.length).toBe(1); <ide> expect(console.error.argsForCall[0][0]).toBe( <del> 'Warning: ' + <del> 'This Synthetic event is reused for performance reasons. If you\'re seeing this, ' + <del> 'you\'re calling `stopPropagation` on a released/nullified Synthetic event. ' + <del> 'This is a no-op. See https://facebook.github.io/react/docs/events.html#event-pooling ' + <del> 'for more information.' <add> 'Warning: This synthetic event is reused for performance reasons. If ' + <add> 'you\'re seeing this, you\'re calling `stopPropagation` on a ' + <add> 'released/nullified synthetic event. This is a no-op. See ' + <add> 'https://fb.me/react-event-pooling for more information.' <ide> ); <ide> }); <ide> });
2
Text
Text
fix broken documentation links
f2682537e0fa91bb415be1a64e6bc85275129141
<ide><path>docs/api-guide/views.md <ide> Each of these decorators takes a single argument which must be a list or tuple o <ide> <ide> [cite]: http://reinout.vanrees.org/weblog/2011/08/24/class-based-views-usage.html <ide> [cite2]: http://www.boredomandlaziness.org/2012/05/djangos-cbvs-are-not-mistake-but.html <del>[settings]: api-guide/settings.md <del>[throttling]: api-guide/throttling.md <add>[settings]: settings.md <add>[throttling]: throttling.md
1
Python
Python
break some long lines
70e34252dc224ace1192cb8534fd55442afe3dfe
<ide><path>numpy/ma/tests/test_extras.py <ide> def test_union1d(self): <ide> control = array([1, 2, 3, 4, 5, 7, -1], mask=[0, 0, 0, 0, 0, 0, 1]) <ide> assert_equal(test, control) <ide> <del> # Tests gh-10340, arguments to union1d should be flattened if they are not already 1D <add> # Tests gh-10340, arguments to union1d should be <add> # flattened if they are not already 1D <ide> x = array([[0, 1, 2], [3, 4, 5]], mask=[[0, 0, 0], [0, 0, 1]]) <ide> y = array([0, 1, 2, 3, 4], mask=[0, 0, 0, 0, 1]) <ide> ez = array([0, 1, 2, 3, 4, 5], mask=[0, 0, 0, 0, 0, 1])
1
Javascript
Javascript
implement text decorations in rendering layer
ac8a9083856e52748a0e31a79843117d52b963a7
<ide><path>spec/text-editor-component-spec.js <ide> describe('TextEditorComponent', () => { <ide> }) <ide> }) <ide> <add> describe('text decorations', () => { <add> it('injects spans with custom class names and inline styles based on text decorations', async () => { <add> const {component, element, editor} = buildComponent() <add> <add> const markerLayer = editor.addMarkerLayer() <add> <add> const marker1 = markerLayer.markBufferRange([[0, 2], [2, 7]]) <add> const marker2 = markerLayer.markBufferRange([[0, 2], [3, 8]]) <add> const marker3 = markerLayer.markBufferRange([[1, 13], [2, 7]]) <add> <add> editor.decorateMarker(marker1, {type: 'text', class: 'a', style: {color: 'red'}}) <add> editor.decorateMarker(marker2, {type: 'text', class: 'b', style: {color: 'blue'}}) <add> editor.decorateMarker(marker3, {type: 'text', class: 'c', style: {color: 'green'}}) <add> await component.getNextUpdatePromise() <add> <add> expect(textContentOnRowMatchingSelector(component, 0, '.a')).toBe(editor.lineTextForScreenRow(0).slice(2)) <add> expect(textContentOnRowMatchingSelector(component, 1, '.a')).toBe(editor.lineTextForScreenRow(1)) <add> expect(textContentOnRowMatchingSelector(component, 2, '.a')).toBe(editor.lineTextForScreenRow(2).slice(0, 7)) <add> expect(textContentOnRowMatchingSelector(component, 3, '.a')).toBe('') <add> <add> expect(textContentOnRowMatchingSelector(component, 0, '.b')).toBe(editor.lineTextForScreenRow(0).slice(2)) <add> expect(textContentOnRowMatchingSelector(component, 1, '.b')).toBe(editor.lineTextForScreenRow(1)) <add> expect(textContentOnRowMatchingSelector(component, 2, '.b')).toBe(editor.lineTextForScreenRow(2)) <add> expect(textContentOnRowMatchingSelector(component, 3, '.b')).toBe(editor.lineTextForScreenRow(3).slice(0, 8)) <add> <add> expect(textContentOnRowMatchingSelector(component, 0, '.c')).toBe('') <add> expect(textContentOnRowMatchingSelector(component, 1, '.c')).toBe(editor.lineTextForScreenRow(1).slice(13)) <add> expect(textContentOnRowMatchingSelector(component, 2, '.c')).toBe(editor.lineTextForScreenRow(2).slice(0, 7)) <add> expect(textContentOnRowMatchingSelector(component, 3, '.c')).toBe('') <add> <add> for (const span of element.querySelectorAll('.a:not(.c)')) { <add> expect(span.style.color).toBe('red') <add> } <add> for (const span of element.querySelectorAll('.b:not(.c):not(.a)')) { <add> expect(span.style.color).toBe('blue') <add> } <add> for (const span of element.querySelectorAll('.c')) { <add> expect(span.style.color).toBe('green') <add> } <add> <add> marker2.setHeadScreenPosition([3, 10]) <add> await component.getNextUpdatePromise() <add> expect(textContentOnRowMatchingSelector(component, 3, '.b')).toBe(editor.lineTextForScreenRow(3).slice(0, 10)) <add> }) <add> <add> function textContentOnRowMatchingSelector (component, row, selector) { <add> return Array.from(lineNodeForScreenRow(component, row).querySelectorAll(selector)) <add> .map((span) => span.textContent) <add> .join('') <add> } <add> }) <add> <ide> describe('mouse input', () => { <ide> describe('on the lines', () => { <ide> it('positions the cursor on single-click', async () => { <ide><path>src/text-editor-component.js <ide> class TextEditorComponent { <ide> cursors: [], <ide> overlays: [], <ide> customGutter: new Map(), <del> blocks: new Map() <add> blocks: new Map(), <add> text: [] <ide> } <ide> this.decorationsToMeasure = { <ide> highlights: new Map(), <ide> cursors: new Map() <ide> } <add> this.textDecorationsByMarker = new Map() <add> this.textDecorationBoundaries = [] <ide> this.pendingScrollTopRow = this.props.initialScrollTopRow <ide> this.pendingScrollLeftColumn = this.props.initialScrollLeftColumn <ide> <ide> class TextEditorComponent { <ide> tileEndRow, <ide> screenLines: this.renderedScreenLines.slice(tileStartRow - startRow, tileEndRow - startRow), <ide> lineDecorations: this.decorationsToRender.lines.slice(tileStartRow - startRow, tileEndRow - startRow), <add> textDecorations: this.decorationsToRender.text.slice(tileStartRow - startRow, tileEndRow - startRow), <ide> blockDecorations: this.decorationsToRender.blocks.get(tileStartRow), <ide> highlightDecorations: this.decorationsToRender.highlights.get(tileStartRow), <ide> displayLayer, <ide> class TextEditorComponent { <ide> this.decorationsToRender.overlays.length = 0 <ide> this.decorationsToRender.customGutter.clear() <ide> this.decorationsToRender.blocks = new Map() <add> this.decorationsToRender.text = [] <ide> this.decorationsToMeasure.highlights.clear() <ide> this.decorationsToMeasure.cursors.clear() <add> this.textDecorationsByMarker.clear() <add> this.textDecorationBoundaries.length = 0 <ide> <ide> const decorationsByMarker = <ide> this.props.model.decorationManager.decorationPropertiesByMarkerForScreenRowRange( <ide> class TextEditorComponent { <ide> this.addDecorationToRender(decoration.type, decoration, marker, screenRange, reversed) <ide> } <ide> }) <add> <add> this.populateTextDecorationsToRender() <ide> } <ide> <ide> addDecorationToRender (type, decoration, marker, screenRange, reversed) { <ide> class TextEditorComponent { <ide> case 'block': <ide> this.addBlockDecorationToRender(decoration, screenRange, reversed) <ide> break <add> case 'text': <add> this.addTextDecorationToRender(decoration, screenRange, marker) <add> break <ide> } <ide> } <ide> } <ide> class TextEditorComponent { <ide> decorations.push(decoration) <ide> } <ide> <add> addTextDecorationToRender (decoration, screenRange, marker) { <add> if (screenRange.isEmpty()) return <add> <add> let decorationsForMarker = this.textDecorationsByMarker.get(marker) <add> if (!decorationsForMarker) { <add> decorationsForMarker = [] <add> this.textDecorationsByMarker.set(marker, decorationsForMarker) <add> this.textDecorationBoundaries.push({position: screenRange.start, starting: [marker]}) <add> this.textDecorationBoundaries.push({position: screenRange.end, ending: [marker]}) <add> } <add> decorationsForMarker.push(decoration) <add> } <add> <add> populateTextDecorationsToRender () { <add> // Sort all boundaries in ascending order of position <add> this.textDecorationBoundaries.sort((a, b) => a.position.compare(b.position)) <add> <add> // Combine adjacent boundaries with the same position <add> for (let i = 0; i < this.textDecorationBoundaries.length;) { <add> const boundary = this.textDecorationBoundaries[i] <add> const nextBoundary = this.textDecorationBoundaries[i + 1] <add> if (nextBoundary && nextBoundary.position.isEqual(boundary.position)) { <add> if (nextBoundary.starting) { <add> if (boundary.starting) { <add> boundary.starting.push(...nextBoundary.starting) <add> } else { <add> boundary.starting = nextBoundary.starting <add> } <add> } <add> <add> if (nextBoundary.ending) { <add> if (boundary.ending) { <add> boundary.ending.push(...nextBoundary.ending) <add> } else { <add> boundary.ending = nextBoundary.ending <add> } <add> } <add> <add> this.textDecorationBoundaries.splice(i + 1, 1) <add> } else { <add> i++ <add> } <add> } <add> <add> const renderedStartRow = this.getRenderedStartRow() <add> const containingMarkers = [] <add> <add> // Iterate over boundaries to build up text decorations. <add> for (let i = 0; i < this.textDecorationBoundaries.length; i++) { <add> const boundary = this.textDecorationBoundaries[i] <add> <add> // If multiple markers start here, sort them by order of nesting (markers ending later come first) <add> if (boundary.starting && boundary.starting.length > 1) { <add> boundary.starting.sort((a, b) => a.compare(b)) <add> } <add> <add> // If multiple markers start here, sort them by order of nesting (markers starting earlier come first) <add> if (boundary.ending && boundary.ending.length > 1) { <add> boundary.ending.sort((a, b) => b.compare(a)) <add> } <add> <add> // Remove markers ending here from containing markers array <add> if (boundary.ending) { <add> for (let j = boundary.ending.length - 1; j >= 0; j--) { <add> containingMarkers.splice(containingMarkers.lastIndexOf(boundary.ending[j]), 1) <add> } <add> } <add> // Add markers starting here to containing markers array <add> if (boundary.starting) containingMarkers.push(...boundary.starting) <add> <add> // Determine desired className and style based on containing markers <add> let className, style <add> for (let j = 0; j < containingMarkers.length; j++) { <add> const marker = containingMarkers[j] <add> const decorations = this.textDecorationsByMarker.get(marker) <add> for (let k = 0; k < decorations.length; k++) { <add> const decoration = decorations[k] <add> if (decoration.class) { <add> if (className) { <add> className += ' ' + decoration.class <add> } else { <add> className = decoration.class <add> } <add> } <add> if (decoration.style) { <add> if (style) { <add> Object.assign(style, decoration.style) <add> } else { <add> style = Object.assign({}, decoration.style) <add> } <add> } <add> } <add> } <add> <add> // Add decoration start with className/style for current position's column, <add> // and also for the start of every row up until the next decoration boundary <add> this.addTextDecorationStart(boundary.position.row, boundary.position.column, className, style) <add> const nextBoundary = this.textDecorationBoundaries[i + 1] <add> if (nextBoundary) { <add> for (let row = boundary.position.row + 1; row <= nextBoundary.position.row; row++) { <add> this.addTextDecorationStart(row, 0, className, style) <add> } <add> } <add> } <add> } <add> <add> addTextDecorationStart (row, column, className, style) { <add> const renderedStartRow = this.getRenderedStartRow() <add> let decorationStarts = this.decorationsToRender.text[row - renderedStartRow] <add> if (!decorationStarts) { <add> decorationStarts = [] <add> this.decorationsToRender.text[row - renderedStartRow] = decorationStarts <add> } <add> decorationStarts.push({column, className, style}) <add> } <add> <ide> updateAbsolutePositionedDecorations () { <ide> this.updateHighlightsToRender() <ide> this.updateCursorsToRender() <ide> class LinesTileComponent { <ide> <ide> createLines () { <ide> const { <del> tileStartRow, screenLines, lineDecorations, <add> tileStartRow, screenLines, lineDecorations, textDecorations, <ide> displayLayer, lineNodesByScreenLineId, textNodesByScreenLineId <ide> } = this.props <ide> <ide> class LinesTileComponent { <ide> screenLine: screenLines[i], <ide> screenRow: tileStartRow + i, <ide> lineDecoration: lineDecorations[i], <add> textDecorations: textDecorations[i], <ide> displayLayer, <ide> lineNodesByScreenLineId, <ide> textNodesByScreenLineId <ide> class LinesTileComponent { <ide> <ide> updateLines (oldProps, newProps) { <ide> var { <del> screenLines, tileStartRow, lineDecorations, <add> screenLines, tileStartRow, lineDecorations, textDecorations, <ide> displayLayer, lineNodesByScreenLineId, textNodesByScreenLineId <ide> } = newProps <ide> <ide> class LinesTileComponent { <ide> screenLine: newScreenLine, <ide> screenRow: tileStartRow + newScreenLineIndex, <ide> lineDecoration: lineDecorations[newScreenLineIndex], <add> textDecorations: textDecorations[newScreenLineIndex], <ide> displayLayer, <ide> lineNodesByScreenLineId, <ide> textNodesByScreenLineId <ide> class LinesTileComponent { <ide> var lineComponent = this.lineComponents[lineComponentIndex] <ide> lineComponent.update({ <ide> screenRow: tileStartRow + newScreenLineIndex, <del> lineDecoration: lineDecorations[newScreenLineIndex] <add> lineDecoration: lineDecorations[newScreenLineIndex], <add> textDecorations: textDecorations[newScreenLineIndex] <ide> }) <ide> <ide> oldScreenLineIndex++ <ide> class LinesTileComponent { <ide> screenLine: newScreenLines[newScreenLineIndex], <ide> screenRow: tileStartRow + newScreenLineIndex, <ide> lineDecoration: lineDecorations[newScreenLineIndex], <add> textDecorations: textDecorations[newScreenLineIndex], <ide> displayLayer, <ide> lineNodesByScreenLineId, <ide> textNodesByScreenLineId <ide> class LinesTileComponent { <ide> screenLine: newScreenLines[newScreenLineIndex], <ide> screenRow: tileStartRow + newScreenLineIndex, <ide> lineDecoration: lineDecorations[newScreenLineIndex], <add> textDecorations: textDecorations[newScreenLineIndex], <ide> displayLayer, <ide> lineNodesByScreenLineId, <ide> textNodesByScreenLineId <ide> class LinesTileComponent { <ide> return true <ide> } <ide> <add> if (oldProps.textDecorations.length !== newProps.textDecorations.length) return true <add> for (let i = 0; i < oldProps.textDecorations.length; i++) { <add> if (!textDecorationsEqual(oldProps.textDecorations[i], newProps.textDecorations[i])) return true <add> } <add> <ide> return false <ide> } <ide> } <ide> <ide> class LineComponent { <ide> constructor (props) { <del> const { <del> displayLayer, <del> screenLine, screenRow, <del> lineNodesByScreenLineId, textNodesByScreenLineId <del> } = props <add> const {screenRow, screenLine, lineNodesByScreenLineId} = props <ide> this.props = props <ide> this.element = document.createElement('div') <ide> this.element.className = this.buildClassName() <ide> this.element.dataset.screenRow = screenRow <ide> lineNodesByScreenLineId.set(screenLine.id, this.element) <add> this.appendContents() <add> } <add> <add> update (newProps) { <add> if (this.props.lineDecoration !== newProps.lineDecoration) { <add> this.props.lineDecoration = newProps.lineDecoration <add> this.element.className = this.buildClassName() <add> } <add> <add> if (this.props.screenRow !== newProps.screenRow) { <add> this.props.screenRow = newProps.screenRow <add> this.element.dataset.screenRow = newProps.screenRow <add> } <add> <add> if (!textDecorationsEqual(this.props.textDecorations, newProps.textDecorations)) { <add> this.props.textDecorations = newProps.textDecorations <add> this.element.firstChild.remove() <add> this.appendContents() <add> } <add> } <add> <add> destroy () { <add> const {lineNodesByScreenLineId, textNodesByScreenLineId, screenLine} = this.props <add> if (lineNodesByScreenLineId.get(screenLine.id) === this.element) { <add> lineNodesByScreenLineId.delete(screenLine.id) <add> textNodesByScreenLineId.delete(screenLine.id) <add> } <add> <add> this.element.remove() <add> } <add> <add> appendContents () { <add> const {displayLayer, screenLine, textDecorations, textNodesByScreenLineId} = this.props <ide> <ide> const textNodes = [] <ide> textNodesByScreenLineId.set(screenLine.id, textNodes) <ide> <ide> const {lineText, tags} = screenLine <del> let startIndex = 0 <ide> let openScopeNode = document.createElement('span') <ide> this.element.appendChild(openScopeNode) <add> <add> let decorationIndex = 0 <add> let column = 0 <add> let activeClassName = null <add> let activeStyle = null <add> let nextDecoration = textDecorations ? textDecorations[decorationIndex] : null <add> if (nextDecoration && nextDecoration.column === 0) { <add> ({className: activeClassName, style: activeStyle} = nextDecoration) <add> nextDecoration = textDecorations[++decorationIndex] <add> } <add> <ide> for (let i = 0; i < tags.length; i++) { <ide> const tag = tags[i] <ide> if (tag !== 0) { <ide> class LineComponent { <ide> openScopeNode.appendChild(newScopeNode) <ide> openScopeNode = newScopeNode <ide> } else { <del> const textNode = document.createTextNode(lineText.substr(startIndex, tag)) <del> startIndex = startIndex + tag <del> openScopeNode.appendChild(textNode) <del> textNodes.push(textNode) <add> const nextTokenColumn = column + tag <add> while (nextDecoration && nextDecoration.column <= nextTokenColumn) { <add> const text = lineText.substring(column, nextDecoration.column) <add> this.appendTextNode(textNodes, openScopeNode, text, activeClassName, activeStyle) <add> ,({column, className: activeClassName, style: activeStyle} = nextDecoration) <add> nextDecoration = textDecorations[++decorationIndex] <add> } <add> <add> const text = lineText.substring(column, nextTokenColumn) <add> this.appendTextNode(textNodes, openScopeNode, text, activeClassName, activeStyle) <add> column = nextTokenColumn <ide> } <ide> } <ide> } <ide> <del> if (startIndex === 0) { <add> if (column === 0) { <ide> const textNode = document.createTextNode(' ') <ide> this.element.appendChild(textNode) <ide> textNodes.push(textNode) <ide> class LineComponent { <ide> } <ide> } <ide> <del> update (newProps) { <del> if (this.props.lineDecoration !== newProps.lineDecoration) { <del> this.props.lineDecoration = newProps.lineDecoration <del> this.element.className = this.buildClassName() <del> } <del> <del> if (this.props.screenRow !== newProps.screenRow) { <del> this.props.screenRow = newProps.screenRow <del> this.element.dataset.screenRow = newProps.screenRow <del> } <del> } <del> <del> destroy () { <del> const {lineNodesByScreenLineId, textNodesByScreenLineId, screenLine} = this.props <del> if (lineNodesByScreenLineId.get(screenLine.id) === this.element) { <del> lineNodesByScreenLineId.delete(screenLine.id) <del> textNodesByScreenLineId.delete(screenLine.id) <add> appendTextNode (textNodes, openScopeNode, text, activeClassName, activeStyle) { <add> if (activeClassName || activeStyle) { <add> const decorationNode = document.createElement('span') <add> if (activeClassName) decorationNode.className = activeClassName <add> if (activeStyle) Object.assign(decorationNode.style, activeStyle) <add> openScopeNode.appendChild(decorationNode) <add> openScopeNode = decorationNode <ide> } <ide> <del> this.element.remove() <add> const textNode = document.createTextNode(text) <add> openScopeNode.appendChild(textNode) <add> textNodes.push(textNode) <ide> } <ide> <ide> buildClassName () { <ide> function clientRectForRange (textNode, startIndex, endIndex) { <ide> return rangeForMeasurement.getBoundingClientRect() <ide> } <ide> <add>function textDecorationsEqual (oldDecorations, newDecorations) { <add> if (!oldDecorations && newDecorations) return false <add> if (oldDecorations && !newDecorations) return false <add> if (oldDecorations && newDecorations) { <add> if (oldDecorations.length !== newDecorations.length) return false <add> for (let j = 0; j < oldDecorations.length; j++) { <add> if (oldDecorations[j].column !== newDecorations[j].column) return false <add> if (oldDecorations[j].className !== newDecorations[j].className) return false <add> if (!objectsEqual(oldDecorations[j].style, newDecorations[j].style)) return false <add> } <add> } <add> return true <add>} <add> <ide> function arraysEqual (a, b) { <ide> if (a.length !== b.length) return false <ide> for (let i = 0, length = a.length; i < length; i++) { <ide> function arraysEqual (a, b) { <ide> return true <ide> } <ide> <add>function objectsEqual (a, b) { <add> if (!a && b) return false <add> if (a && !b) return false <add> if (a && b) { <add> for (key in a) { <add> if (a[key] !== b[key]) return false <add> } <add> for (key in b) { <add> if (a[key] !== b[key]) return false <add> } <add> } <add> return true <add>} <add> <ide> function constrainRangeToRows (range, startRow, endRow) { <ide> if (range.start.row < startRow || range.end.row >= endRow) { <ide> range = range.copy()
2
Ruby
Ruby
extend stdlib queue for the test queue
2187b5f2f1d383b7a46baf72334c9a3332a23e84
<ide><path>railties/lib/rails/queueing.rb <ide> module Queueing <ide> # <ide> # Jobs are run in a separate thread to catch mistakes where code <ide> # assumes that the job is run in the same thread. <del> class TestQueue <del> attr_reader :contents <del> <del> def initialize <del> @contents = [] <del> end <del> <add> class TestQueue < ::Queue <ide> def drain <ide> # run the jobs in a separate thread so assumptions of synchronous <ide> # jobs are caught in test mode. <del> t = Thread.new do <del> while job = @contents.shift <del> job.run <del> end <del> end <del> t.join <del> end <del> <del> # implement the Queue API <del> def push(object) <del> @contents << object <add> Thread.new { pop.run until empty? }.join <ide> end <ide> end <ide> <ide><path>railties/test/queueing/test_queue_test.rb <ide> <ide> class TestQueueTest < ActiveSupport::TestCase <ide> class Job <del> attr_reader :id <del> def initialize(id, &block) <del> @id = id <add> def initialize(&block) <ide> @block = block <ide> end <ide> <ide> def run <ide> end <ide> <ide> def setup <add> #@queue = Rails::Queueing::TestQueue.new <ide> @queue = Rails::Queueing::TestQueue.new <ide> end <ide> <ide> def test_contents <del> assert_equal [], @queue.contents <del> job = Job.new(1) <add> assert @queue.empty? <add> job = Job.new <ide> @queue.push job <del> assert_equal [job], @queue.contents <add> refute @queue.empty? <add> assert_equal job, @queue.pop <ide> end <ide> <ide> def test_order <ide> processed = [] <ide> <del> job1 = Job.new(1) { processed << 1 } <del> job2 = Job.new(2) { processed << 2 } <add> job1 = Job.new { processed << 1 } <add> job2 = Job.new { processed << 2 } <ide> <ide> @queue.push job1 <ide> @queue.push job2 <ide> def test_drain <ide> t = nil <ide> ran = false <ide> <del> job = Job.new(1) do <add> job = Job.new do <ide> ran = true <ide> t = Thread.current <ide> end <ide> <ide> @queue.push job <ide> @queue.drain <ide> <del> assert_equal [], @queue.contents <add> assert @queue.empty? <ide> assert ran, "The job runs synchronously when the queue is drained" <ide> assert_not_equal t, Thread.current <ide> end
2
Text
Text
remove stale video from nest anchor element
3fbe1ebc0523bf442a9ae868b58ef55e530049fe
<ide><path>curriculum/challenges/english/01-responsive-web-design/basic-html-and-html5/nest-an-anchor-element-within-a-paragraph.md <ide> id: bad87fee1348bd9aede08817 <ide> title: Nest an Anchor Element within a Paragraph <ide> challengeType: 0 <del>videoUrl: 'https://scrimba.com/p/pVMPUv/cb6k8Cb' <ide> forumTopicId: 18244 <ide> dashedName: nest-an-anchor-element-within-a-paragraph <ide> ---
1
Ruby
Ruby
fix typo in actionableerror [skip ci]
99fd13d967ff1d21675bf1cebf375878e4575cda
<ide><path>activesupport/lib/active_support/actionable_error.rb <ide> # frozen_string_literal: true <ide> <ide> module ActiveSupport <del> # Actionable errors let's you define actions to resolve an error. <add> # Actionable errors lets you define actions to resolve an error. <ide> # <ide> # To make an error actionable, include the <tt>ActiveSupport::ActionableError</tt> <ide> # module and invoke the +action+ class macro to define the action. An action
1
Ruby
Ruby
add caution and restyle components
e90bbbdd837ffc83dccbd05528c4f1521e3956ee
<ide><path>actionpack/lib/action_controller/assertions.rb <ide> def assert_dom_not_equal(expected, actual, message="") <ide> end <ide> <ide> # ensures that the passed record is valid by active record standards. returns the error messages if not <del> def assert_valid(record) <add> def assert_valid(record) <ide> clean_backtrace do <ide> assert record.valid?, record.errors.full_messages.join("\n") <ide> end <ide><path>actionpack/lib/action_controller/components.rb <ide> module ActionController #:nodoc: <del> # Components allows you to call other actions for their rendered response while executing another action. You can either delegate <add> # Components allow you to call other actions for their rendered response while executing another action. You can either delegate <ide> # the entire response rendering or you can mix a partial response in with your other content. <ide> # <ide> # class WeblogController < ActionController::Base <ide> # # Performs a method and then lets hello_world output its render <ide> # def delegate_action <ide> # do_other_stuff_before_hello_world <del> # render_component :controller => "greeter", :action => "hello_world", :params => { "person" => "david" } <add> # render_component :controller => "greeter", :action => "hello_world", :params => { :person => "david" } <ide> # end <ide> # end <ide> # <ide> # class GreeterController < ActionController::Base <ide> # def hello_world <del> # render_text "#{@params['person']} says, Hello World!" <add> # render :text => "#{params[:person]} says, Hello World!" <ide> # end <ide> # end <ide> # <ide> module ActionController #:nodoc: <ide> # <%= render_component :controller => "greeter", :action => "hello_world" %> <ide> # <ide> # It is also possible to specify the controller as a class constant, bypassing the inflector <del> # code to compute the controller class at runtime. Therefore, <add> # code to compute the controller class at runtime: <ide> # <ide> # <%= render_component :controller => GreeterController, :action => "hello_world" %> <del> # <del> # would work as well and be slightly faster. <add> # <add> # == When to use components <add> # <add> # Components should be used with care. They're significantly slower than simply splitting reusable parts into partials and <add> # conceptually more complicated. Don't use components as a way of separating concerns inside a single application. Instead, <add> # reserve components to those rare cases where you truly have reusable view and controller elements that can be employed <add> # across many applications at once. <add> # <add> # So to repeat: Components are a special-purpose approach that can often be replaced with better use of partials and filters. <ide> module Components <ide> def self.included(base) #:nodoc: <ide> base.extend(ClassMethods) <ide> module ClassMethods <ide> def uses_component_template_root <ide> path_of_calling_controller = File.dirname(caller[0].split(/:\d+:/).first) <ide> path_of_controller_root = path_of_calling_controller.sub(/#{controller_path.split("/")[0..-2]}$/, "") # " (for ruby-mode) <add> <ide> self.template_root = path_of_controller_root <ide> end <ide> end <ide> def render_component(options) #:doc: <ide> def render_component_as_string(options) #:doc: <ide> component_logging(options) do <ide> response = component_response(options, false) <add> <ide> if redirected = response.redirected_to <del> render_component_as_string redirected <add> render_component_as_string(redirected) <ide> else <ide> response.body <ide> end <del> end <add> end <ide> end <del> <add> <ide> private <del> def component_response(options, reuse_response) <del> c_class = component_class(options) <del> c_request = request_for_component(c_class.controller_name, options) <del> c_response = reuse_response ? @response : @response.dup <del> c_class.process(c_request, c_response, self) <add> def component_response(options, reuse_response) <add> klass = component_class(options) <add> request = request_for_component(klass.controller_name, options) <add> response = reuse_response ? @response : @response.dup <add> <add> klass.process(request, response, self) <add> end <add> <add> # determine the controller class for the component request <add> def component_class(options) <add> if controller = options[:controller] <add> controller.is_a?(Class) ? controller : "#{controller.camelize}Controller".constantize <add> else <add> self.class <add> end <add> end <add> <add> # Create a new request object based on the current request. <add> # The new request inherits the session from the current request, <add> # bypassing any session options set for the component controller's class <add> def request_for_component(controller_name, options) <add> request = @request.dup <add> request.session = @request.session <add> <add> request.instance_variable_set( <add> :@parameters, <add> (options[:params] || {}).with_indifferent_access.regular_update( <add> "controller" => controller_name, "action" => options[:action], "id" => options[:id] <add> ) <add> ) <add> <add> request <ide> end <del> <del> # determine the controller class for the component request <del> def component_class(options) <del> if controller = options[:controller] <del> if controller.is_a? Class <del> controller <del> else <del> "#{controller.camelize}Controller".constantize <del> end <add> <add> def component_logging(options) <add> if logger <add> logger.info "Start rendering component (#{options.inspect}): " <add> result = yield <add> logger.info "\n\nEnd of component rendering" <add> result <ide> else <del> self.class <add> yield <ide> end <ide> end <del> <del> # Create a new request object based on the current request. <del> # The new request inherits the session from the current request, <del> # bypassing any session options set for the component controller's class <del> def request_for_component(controller_name, options) <del> sub_request = @request.dup <del> sub_request.session = @request.session <del> sub_request.instance_variable_set(:@parameters, <del> (options[:params] || {}).with_indifferent_access.regular_update( <del> "controller" => controller_name, "action" => options[:action], "id" => options[:id]) <del> ) <del> sub_request <del> end <del> <del> <del> def component_logging(options) <del> unless logger then yield else <del> logger.info("Start rendering component (#{options.inspect}): ") <del> result = yield <del> logger.info("\n\nEnd of component rendering") <del> result <del> end <del> end <ide> end <ide> end <ide> end <ide><path>actionpack/lib/action_controller/filters.rb <ide> module ActionController #:nodoc: <ide> module Filters #:nodoc: <del> def self.append_features(base) <del> super <add> def self.included(base) <ide> base.extend(ClassMethods) <ide> base.send(:include, ActionController::Filters::InstanceMethods) <ide> end
3
Text
Text
reword devops guide
2d647b1638b3f9a0efe5b8e08568d8c13a73d7b2
<ide><path>docs/devops.md <ide> Let us know, if you have feedback or queries, and we will be happy to clarify. <ide> <ide> ## How do we build, test and deploy the codebase? <ide> <del>Our codebase is continuously built, tested and deployed to **separate sets of infrastructure (Servers, Databases, CDNs, etc.)**. <add>Our codebase is continuously built, tested and deployed to **separate sets of infrastructure (Servers, Databases, CDNs, etc.)**. <ide> <del>This involves three steps to be followed in sequence: <add>This involves three steps to be followed in sequence: <ide> <ide> First, new changes are merged into our primary development branch (`master`) in form of pull requests. Next, these changes are run through a series of automated tests. And finally, once the tests pass we release the changes (or update them if needed) to deployments on our infrastructure. <ide> <ide> And that's it, this will automatically trigger a build on the build pipeline for <ide> <ide> Here are some additional steps that need to be followed by a freeCodeCamp.org Staff developer. To prevent any accidental pushes we have a couple of manual approval steps configured on the pipelines. <ide> <del>Once a build artifact is ready on the `production-current` branch, it will trigger a release on the release pipeline. <add>Once a build artifact is ready on the `production-current` branch, it will trigger a release on the release pipeline. <ide> <del>Next, freeCodeCamp.org developer staff team will receive an email. They can either *approve* or *reject* the release. Approval or rejection depends, if changes were nicely working and tested on the staging application. Each approval lasts only for 4 hours to avoid queuing up. Post the limit it gets auto rejected, wherein a staff will re-trigger the release pipeline manually. <add>Next, the freeCodeCamp.org developer staff team will receive an email. They can either *approve* or *reject* the release. If the changes are working nicely and have been tested on the staging application, then it can be approved. This must happen within 4 hours of the release being triggered or it will automatically get rejected. If this happens a staff member will need to re-trigger the release pipeline manually. <ide> <ide> For staff use: <ide>
1
PHP
PHP
use full namespaces in docblocks
7c5acaa81ea76c0ceb64c0281c70ccffbad9410b
<ide><path>src/Event/EventDispatcherTrait.php <ide> namespace Cake\Event; <ide> <ide> /** <del> * Implements EventDispatcherInterface. <add> * Implements Cake\Event\EventDispatcherInterface. <ide> * <ide> */ <ide> trait EventDispatcherTrait <ide><path>src/Event/EventManagerTrait.php <ide> /** <ide> * Provides the event manager interface features for usage in classes that require it. <ide> * <del> * @deprecated 3.0.10 Use EventDispatcherTrait instead. <add> * @deprecated 3.0.10 Use Cake\Event\EventDispatcherTrait instead. <ide> */ <ide> trait EventManagerTrait <ide> {
2
Go
Go
ensure container name on register
a9ed238bb76774c142107b3f06e8c9e9a1e59e65
<ide><path>runtime.go <ide> func (runtime *Runtime) Register(container *Container) error { <ide> if err := validateID(container.ID); err != nil { <ide> return err <ide> } <add> if err := runtime.ensureName(container); err != nil { <add> return err <add> } <ide> <ide> // init the wait lock <ide> container.waitLock = make(chan struct{}) <ide> func (runtime *Runtime) Register(container *Container) error { <ide> return nil <ide> } <ide> <add>func (runtime *Runtime) ensureName(container *Container) error { <add> if container.Name == "" { <add> name, err := generateRandomName(runtime) <add> if err != nil { <add> name = container.ShortID() <add> } <add> container.Name = name <add> <add> if err := container.ToDisk(); err != nil { <add> utils.Debugf("Error saving container name %s", err) <add> } <add> if !runtime.containerGraph.Exists(name) { <add> if _, err := runtime.containerGraph.Set(name, container.ID); err != nil { <add> utils.Debugf("Setting default id - %s", err) <add> } <add> } <add> } <add> return nil <add>} <add> <ide> func (runtime *Runtime) LogToDisk(src *utils.WriteBroadcaster, dst, stream string) error { <ide> log, err := os.OpenFile(dst, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0600) <ide> if err != nil { <ide> func (runtime *Runtime) Commit(container *Container, repository, tag, comment, a <ide> return img, nil <ide> } <ide> <del>func (runtime *Runtime) getFullName(name string) string { <add>func (runtime *Runtime) getFullName(name string) (string, error) { <add> if name == "" { <add> return "", fmt.Errorf("Container name cannot be empty") <add> } <ide> if name[0] != '/' { <ide> name = "/" + name <ide> } <del> return name <add> return name, nil <ide> } <ide> <ide> func (runtime *Runtime) GetByName(name string) (*Container, error) { <del> entity := runtime.containerGraph.Get(runtime.getFullName(name)) <add> fullName, err := runtime.getFullName(name) <add> if err != nil { <add> return nil, err <add> } <add> entity := runtime.containerGraph.Get(fullName) <ide> if entity == nil { <ide> return nil, fmt.Errorf("Could not find entity for %s", name) <ide> } <ide> func (runtime *Runtime) GetByName(name string) (*Container, error) { <ide> } <ide> <ide> func (runtime *Runtime) Children(name string) (map[string]*Container, error) { <del> name = runtime.getFullName(name) <add> name, err := runtime.getFullName(name) <add> if err != nil { <add> return nil, err <add> } <ide> children := make(map[string]*Container) <ide> <del> err := runtime.containerGraph.Walk(name, func(p string, e *gograph.Entity) error { <add> err = runtime.containerGraph.Walk(name, func(p string, e *gograph.Entity) error { <ide> c := runtime.Get(e.ID()) <ide> if c == nil { <ide> return fmt.Errorf("Could not get container for name %s and id %s", e.ID(), p) <ide><path>runtime_test.go <ide> func init() { <ide> <ide> func setupBaseImage() { <ide> config := &DaemonConfig{ <del> Root: unitTestStoreBase, <add> Root: unitTestStoreBase, <ide> AutoRestart: false, <ide> BridgeIface: unitTestNetworkBridge, <ide> } <ide> func TestGetAllChildren(t *testing.T) { <ide> } <ide> } <ide> } <add> <add>func TestGetFullName(t *testing.T) { <add> runtime := mkRuntime(t) <add> defer nuke(runtime) <add> <add> name, err := runtime.getFullName("testing") <add> if err != nil { <add> t.Fatal(err) <add> } <add> if name != "/testing" { <add> t.Fatalf("Expected /testing got %s", name) <add> } <add> if _, err := runtime.getFullName(""); err == nil { <add> t.Fatal("Error should not be nil") <add> } <add>} <ide><path>server.go <ide> func (srv *Server) ContainerDestroy(name string, removeVolume, removeLink bool) <ide> if container == nil { <ide> return fmt.Errorf("No such link: %s", name) <ide> } <del> name = srv.runtime.getFullName(name) <add> name, err := srv.runtime.getFullName(name) <add> if err != nil { <add> return err <add> } <ide> parent, n := path.Split(name) <ide> if parent == "/" { <ide> return fmt.Errorf("Conflict, cannot remove the default name of the container")
3
Javascript
Javascript
increase test coverage for lib/zlib.js
3eea668c7a5b5b89ed052c8bdeda4f5b6277f311
<ide><path>lib/zlib.js <ide> function Zlib(opts, mode) { <ide> opts.finishFlush : constants.Z_FINISH; <ide> <ide> if (opts.chunkSize) { <del> if (opts.chunkSize < constants.Z_MIN_CHUNK || <del> opts.chunkSize > constants.Z_MAX_CHUNK) { <add> if (opts.chunkSize < constants.Z_MIN_CHUNK) { <ide> throw new Error('Invalid chunk size: ' + opts.chunkSize); <ide> } <ide> } <ide><path>test/parallel/test-zlib-deflate-constructors.js <add>'use strict'; <add> <add>require('../common'); <add> <add>const zlib = require('zlib'); <add>const assert = require('assert'); <add> <add>// Work with and without `new` keyword <add>assert.ok(zlib.Deflate() instanceof zlib.Deflate); <add>assert.ok(new zlib.Deflate() instanceof zlib.Deflate); <add> <add>assert.ok(zlib.DeflateRaw() instanceof zlib.DeflateRaw); <add>assert.ok(new zlib.DeflateRaw() instanceof zlib.DeflateRaw); <add> <add>// Throws if `opts.chunkSize` is invalid <add>assert.throws( <add> () => { new zlib.Deflate({chunkSize: -Infinity}); }, <add> /^Error: Invalid chunk size: -Infinity$/ <add>); <add> <add>// Confirm that maximum chunk size cannot be exceeded because it is `Infinity`. <add>assert.strictEqual(zlib.constants.Z_MAX_CHUNK, Infinity); <add> <add>// Throws if `opts.windowBits` is invalid <add>assert.throws( <add> () => { new zlib.Deflate({windowBits: -Infinity}); }, <add> /^Error: Invalid windowBits: -Infinity$/ <add>); <add> <add>assert.throws( <add> () => { new zlib.Deflate({windowBits: Infinity}); }, <add> /^Error: Invalid windowBits: Infinity$/ <add>); <add> <add>// Throws if `opts.level` is invalid <add>assert.throws( <add> () => { new zlib.Deflate({level: -Infinity}); }, <add> /^Error: Invalid compression level: -Infinity$/ <add>); <add> <add>assert.throws( <add> () => { new zlib.Deflate({level: Infinity}); }, <add> /^Error: Invalid compression level: Infinity$/ <add>); <add> <add>// Throws a RangeError if `level` invalid in `Deflate.prototype.params()` <add>assert.throws( <add> () => { new zlib.Deflate().params(-Infinity); }, <add> /^RangeError: Invalid compression level: -Infinity$/ <add>); <add> <add>assert.throws( <add> () => { new zlib.Deflate().params(Infinity); }, <add> /^RangeError: Invalid compression level: Infinity$/ <add>); <add> <add>// Throws if `opts.memLevel` is invalid <add>assert.throws( <add> () => { new zlib.Deflate({memLevel: -Infinity}); }, <add> /^Error: Invalid memLevel: -Infinity$/ <add>); <add> <add>assert.throws( <add> () => { new zlib.Deflate({memLevel: Infinity}); }, <add> /^Error: Invalid memLevel: Infinity$/ <add>); <add> <add>// Does not throw if opts.strategy is valid <add>assert.doesNotThrow( <add> () => { new zlib.Deflate({strategy: zlib.constants.Z_FILTERED}); } <add>); <add> <add>assert.doesNotThrow( <add> () => { new zlib.Deflate({strategy: zlib.constants.Z_HUFFMAN_ONLY}); } <add>); <add> <add>assert.doesNotThrow( <add> () => { new zlib.Deflate({strategy: zlib.constants.Z_RLE}); } <add>); <add> <add>assert.doesNotThrow( <add> () => { new zlib.Deflate({strategy: zlib.constants.Z_FIXED}); } <add>); <add> <add>assert.doesNotThrow( <add> () => { new zlib.Deflate({ strategy: zlib.constants.Z_DEFAULT_STRATEGY}); } <add>); <add> <add>// Throws if opts.strategy is invalid <add>assert.throws( <add> () => { new zlib.Deflate({strategy: 'this is a bogus strategy'}); }, <add> /^Error: Invalid strategy: this is a bogus strategy$/ <add>); <add> <add>// Throws TypeError if `strategy` is invalid in `Deflate.prototype.params()` <add>assert.throws( <add> () => { new zlib.Deflate().params(0, 'I am an invalid strategy'); }, <add> /^TypeError: Invalid strategy: I am an invalid strategy$/ <add>); <add> <add>// Throws if opts.dictionary is not a Buffer <add>assert.throws( <add> () => { new zlib.Deflate({dictionary: 'not a buffer'}); }, <add> /^Error: Invalid dictionary: it should be a Buffer instance$/ <add>);
2
Javascript
Javascript
adjust nomenclature (es)
7d147d6c95af8880eba20192483e6495eb08dd37
<ide><path>src/locale/es.js <ide> <ide> import moment from '../moment'; <ide> <del>var monthsShortDot = 'ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.'.split('_'), <del> monthsShort = 'ene_feb_mar_abr_may_jun_jul_ago_sep_oct_nov_dic'.split('_'); <add>var monthsShortDot = 'Ene._Feb._Mar._Abr._May._Jun._Jul._Ago._Sep._Oct._Nov._Dic.'.split('_'), <add> monthsShort = 'Ene_Feb_Mar_Abr_May_Jun_Jul_Ago_Sep_Oct_Nov_Dic'.split('_'); <ide> <ide> export default moment.defineLocale('es', { <del> months : 'enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre'.split('_'), <add> months : 'Enero_Febrero_Marzo_Abril_Mayo_Junio_Julio_Agosto_Septiembre_Octubre_Noviembre_Diciembre'.split('_'), <ide> monthsShort : function (m, format) { <ide> if (/-MMM-/.test(format)) { <ide> return monthsShort[m.month()]; <ide> } else { <ide> return monthsShortDot[m.month()]; <ide> } <ide> }, <del> weekdays : 'domingo_lunes_martes_miércoles_jueves_viernes_sábado'.split('_'), <del> weekdaysShort : 'dom._lun._mar._mié._jue._vie._sáb.'.split('_'), <add> weekdays : 'Domingo_Lunes_Martes_Miércoles_Jueves_Viernes_Sábado'.split('_'), <add> weekdaysShort : 'Dom._Lun._Mar._Mié._Jue._Vie._Sáb.'.split('_'), <ide> weekdaysMin : 'Do_Lu_Ma_Mi_Ju_Vi_Sá'.split('_'), <ide> longDateFormat : { <ide> LT : 'H:mm',
1
Python
Python
update docstrings for crontab constructor
a83cc6e5ffe5addf90ae538b734b8b5555c10b16
<ide><path>celery/task/schedules.py <ide> class crontab(schedule): <ide> :class:`PeriodicTask` to add cron-like scheduling. <ide> <ide> Like a :manpage:`cron` job, you can specify units of time of when <del> you would like the task to execute. While not a full implementation <del> of cron's features, it should provide a fair degree of common scheduling <del> needs. <add> you would like the task to execute. It is a reasonably complete <add> implementation of cron's features, so it should provide a fair <add> degree of scheduling needs. <ide> <del> You can specify a minute, an hour, and/or a day of the week. <add> You can specify a minute, an hour, and/or a day of the week in any <add> of the following formats: <ide> <ide> .. attribute:: minute <ide> <del> An integer from 0-59 that represents the minute of an hour of when <del> execution should occur. <add> - A (list of) integers from 0-59 that represent the minutes of <add> an hour of when execution should occur; or <add> - A string representing a crontab pattern. This may get pretty <add> advanced, like `minute="*/15"` (for every quarter) or <add> `minute="1,13,30-45,50-59/2"`. <ide> <ide> .. attribute:: hour <ide> <del> An integer from 0-23 that represents the hour of a day of when <del> execution should occur. <add> - A (list of) integers from 0-23 that represent the hours of <add> a day of when execution should occur; or <add> - A string representing a crontab pattern. This may get pretty <add> advanced, like `hour="*/3"` (for every three hours) or <add> `hour="0,8-17/2"` (at midnight, and every two hours during <add> office hours). <ide> <ide> .. attribute:: day_of_week <ide> <del> An integer from 0-6, where Sunday = 0 and Saturday = 6, that <del> represents the day of week that execution should occur. <add> - A (list of) integers from 0-6, where Sunday = 0 and Saturday = <add> 6, that represent the days of a week that execution should <add> occur. <add> - A string representing a crontab pattern. This may get pretty <add> advanced, like `day_of_week="1-5"` (for weekdays only). <add> (Beware that `day_of_week="*/2"` does not literally mean <add> "every two days", but "every day that is divisible by two"!) <ide> <ide> """ <ide>
1
Text
Text
fix hook mistypes and links to types
45fa216ee533abc189d4b9bf0fc8f40430af7ef4
<ide><path>doc/api/esm.md <ide> CommonJS modules loaded. <ide> <ide> ### Hooks <ide> <del>#### <code>resolve</code> hook <add>#### `resolve(specifier, context, defaultResolve)` <ide> <ide> > Note: The loaders API is being redesigned. This hook may disappear or its <ide> > signature may change. Do not rely on the API described below. <ide> <add>* `specifier` {string} <add>* `context` {Object} <add> * `conditions` {string[]} <add> * `parentURL` {string} <add>* `defaultResolve` {Function} <add>* Returns: {Object} <add> * `url` {string} <add> <ide> The `resolve` hook returns the resolved file URL for a given module specifier <ide> and parent URL. The module specifier is the string in an `import` statement or <ide> `import()` expression, and the parent URL is the URL of the module that imported <ide> Node.js module specifier resolution behavior_ when calling `defaultResolve`, the <ide> /** <ide> * @param {string} specifier <ide> * @param {{ <add> * conditions: !Array<string>, <ide> * parentURL: !(string | undefined), <del> * conditions: !(Array<string>), <ide> * }} context <ide> * @param {Function} defaultResolve <del> * @returns {!(Promise<{ url: string }>)} <add> * @returns {Promise<{ url: string }>} <ide> */ <ide> export async function resolve(specifier, context, defaultResolve) { <ide> const { parentURL = null } = context; <ide> export async function resolve(specifier, context, defaultResolve) { <ide> } <ide> ``` <ide> <del>#### <code>getFormat</code> hook <add>#### `getFormat(url, context, defaultGetFormat)` <ide> <ide> > Note: The loaders API is being redesigned. This hook may disappear or its <ide> > signature may change. Do not rely on the API described below. <ide> <add>* `url` {string} <add>* `context` {Object} <add>* `defaultGetFormat` {Function} <add>* Returns: {Object} <add> * `format` {string} <add> <ide> The `getFormat` hook provides a way to define a custom method of determining how <ide> a URL should be interpreted. The `format` returned also affects what the <ide> acceptable forms of source values are for a module when parsing. This can be one <ide> of the following: <ide> <del>| `format` | Description | Acceptable Types For `source` Returned by `getSource` or `transformSource` | <del>| --- | --- | --- | <del>| `'builtin'` | Load a Node.js builtin module | Not applicable | <del>| `'commonjs'` | Load a Node.js CommonJS module | Not applicable | <del>| `'json'` | Load a JSON file | { [ArrayBuffer][], [string][], [TypedArray][] } | <del>| `'module'` | Load an ES module | { [ArrayBuffer][], [string][], [TypedArray][] } | <del>| `'wasm'` | Load a WebAssembly module | { [ArrayBuffer][], [string][], [TypedArray][] } | <add>| `format` | Description | Acceptable Types For `source` Returned by `getSource` or `transformSource` | <add>| ------------ | ------------------------------ | -------------------------------------------------------------------------- | <add>| `'builtin'` | Load a Node.js builtin module | Not applicable | <add>| `'commonjs'` | Load a Node.js CommonJS module | Not applicable | <add>| `'json'` | Load a JSON file | { [`string`][], [`ArrayBuffer`][], [`TypedArray`][] } | <add>| `'module'` | Load an ES module | { [`string`][], [`ArrayBuffer`][], [`TypedArray`][] } | <add>| `'wasm'` | Load a WebAssembly module | { [`ArrayBuffer`][], [`TypedArray`][] } | <ide> <ide> Note: These types all correspond to classes defined in ECMAScript. <ide> <del>* The specific [ArrayBuffer][] object is a [SharedArrayBuffer][]. <del>* The specific [string][] object is not the class constructor, but an instance. <del>* The specific [TypedArray][] object is a [Uint8Array][]. <add>* The specific [`ArrayBuffer`][] object is a [`SharedArrayBuffer`][]. <add>* The specific [`TypedArray`][] object is a [`Uint8Array`][]. <ide> <ide> Note: If the source value of a text-based format (i.e., `'json'`, `'module'`) is <ide> not a string, it will be converted to a string using [`util.TextDecoder`][]. <ide> export async function getFormat(url, context, defaultGetFormat) { <ide> } <ide> ``` <ide> <del>#### <code>getSource</code> hook <add>#### `getSource(url, context, defaultGetSource)` <ide> <ide> > Note: The loaders API is being redesigned. This hook may disappear or its <ide> > signature may change. Do not rely on the API described below. <ide> <add>* `url` {string} <add>* `context` {Object} <add> * `format` {string} <add>* `defaultGetSource` {Function} <add>* Returns: {Object} <add> * `source` {string|SharedArrayBuffer|Uint8Array} <add> <ide> The `getSource` hook provides a way to define a custom method for retrieving <ide> the source code of an ES module specifier. This would allow a loader to <ide> potentially avoid reading files from disk. <ide> potentially avoid reading files from disk. <ide> * @param {string} url <ide> * @param {{ format: string }} context <ide> * @param {Function} defaultGetSource <del> * @returns {Promise<{ source: !(SharedArrayBuffer | string | Uint8Array) }>} <add> * @returns {Promise<{ source: !(string | SharedArrayBuffer | Uint8Array) }>} <ide> */ <ide> export async function getSource(url, context, defaultGetSource) { <ide> const { format } = context; <ide> export async function getSource(url, context, defaultGetSource) { <ide> } <ide> ``` <ide> <del>#### <code>transformSource</code> hook <add>#### `transformSource(source, context, defaultTransformSource)` <ide> <ide> > Note: The loaders API is being redesigned. This hook may disappear or its <ide> > signature may change. Do not rely on the API described below. <ide> <add>* `source` {string|SharedArrayBuffer|Uint8Array} <add>* `context` {Object} <add> * `format` {string} <add> * `url` {string} <add>* Returns: {Object} <add> * `source` {string|SharedArrayBuffer|Uint8Array} <add> <ide> The `transformSource` hook provides a way to modify the source code of a loaded <ide> ES module file after the source string has been loaded but before Node.js has <ide> done anything with it. <ide> unknown-to-Node.js file extensions. See the [transpiler loader example][] below. <ide> <ide> ```js <ide> /** <del> * @param {!(SharedArrayBuffer | string | Uint8Array)} source <add> * @param {!(string | SharedArrayBuffer | Uint8Array)} source <ide> * @param {{ <del> * url: string, <ide> * format: string, <add> * url: string, <ide> * }} context <ide> * @param {Function} defaultTransformSource <del> * @returns {Promise<{ source: !(SharedArrayBuffer | string | Uint8Array) }>} <add> * @returns {Promise<{ source: !(string | SharedArrayBuffer | Uint8Array) }>} <ide> */ <ide> export async function transformSource(source, context, defaultTransformSource) { <ide> const { url, format } = context; <ide> export async function transformSource(source, context, defaultTransformSource) { <ide> } <ide> ``` <ide> <del>#### <code>getGlobalPreloadCode</code> hook <add>#### `getGlobalPreloadCode()` <ide> <ide> > Note: The loaders API is being redesigned. This hook may disappear or its <ide> > signature may change. Do not rely on the API described below. <ide> <add>* Returns: {string} <add> <ide> Sometimes it can be necessary to run some code inside of the same global scope <ide> that the application will run in. This hook allows to return a string that will <ide> be ran as sloppy-mode script on startup. <ide> success! <ide> [`import`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import <ide> [`module.createRequire()`]: modules.html#modules_module_createrequire_filename <ide> [`module.syncBuiltinESMExports()`]: modules.html#modules_module_syncbuiltinesmexports <del>[`transformSource` hook]: #esm_code_transformsource_code_hook <del>[ArrayBuffer]: https://www.ecma-international.org/ecma-262/6.0/#sec-arraybuffer-constructor <del>[SharedArrayBuffer]: https://tc39.es/ecma262/#sec-sharedarraybuffer-constructor <del>[string]: https://www.ecma-international.org/ecma-262/6.0/#sec-string-constructor <del>[TypedArray]: https://www.ecma-international.org/ecma-262/6.0/#sec-typedarray-objects <del>[Uint8Array]: https://www.ecma-international.org/ecma-262/6.0/#sec-uint8array <add>[`transformSource` hook]: #esm_transformsource_source_context_defaulttransformsource <add>[`ArrayBuffer`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer <add>[`SharedArrayBuffer`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer <add>[`string`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String <add>[`TypedArray`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray <add>[`Uint8Array`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array <ide> [`util.TextDecoder`]: util.html#util_class_util_textdecoder <ide> [import an ES or CommonJS module for its side effects only]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#Import_a_module_for_its_side_effects_only <ide> [special scheme]: https://url.spec.whatwg.org/#special-scheme
1
Text
Text
linkify some links
b6cbe1afa250fe7f717033f5e25b9c5f7557dcc8
<ide><path>docs/Releases.md <ide> If this is a major or minor release (e.g. X.0.0 or X.Y.0) then there are a few m <ide> 1. Before creating the tag you should delete any `odisabled` code, make any <ide> `odeprecated` code `odisabled` and add any new `odeprecations` that are <ide> desired. <del>2. Write up a release notes blog post to https://brew.sh <del> e.g. https://github.com/Homebrew/brew.sh/pull/319. <add>2. Write up a release notes blog post to <https://brew.sh> <add> e.g. [brew.sh#319](https://github.com/Homebrew/brew.sh/pull/319). <ide> This should use `brew release-notes` as input but have the wording adjusted <ide> to be more human readable and explain not just what has changed but why. <ide> 3. When the release has shipped and the blog post has been merged, tweet the <del> blog post as the @MacHomebrew Twitter account or tweet it yourself and <del> retweet it with the @MacHomebrew Twitter account (credentials are in <del> 1Password). <add> blog post as the [@MacHomebrew Twitter account](https://twitter.com/MacHomebrew) <add> or tweet it yourself and retweet it with the @MacHomebrew Twitter account <add> (credentials are in 1Password). <ide> 4. Send the email to the Homebrew TinyLetter email list (credentials are in <ide> 1Password). <ide> 5. Consider whether to submit it to other sources e.g. Hacker News, Reddit.
1
Python
Python
fix extra links in gannt view
1fbe8d8bee164de81e8ac9332e1d49f0de03b3e0
<ide><path>airflow/www/views.py <ide> def gantt(self, session=None): <ide> # https://issues.apache.org/jira/browse/AIRFLOW-2143 <ide> try_count = ti.prev_attempted_tries <ide> gantt_bar_items.append((ti.task_id, ti.start_date, end_date, ti.state, try_count)) <del> tasks.append(alchemy_to_dict(ti)) <add> d = alchemy_to_dict(ti) <add> d['extraLinks'] = dag.get_task(ti.task_id).extra_links <add> tasks.append(d) <ide> <ide> tf_count = 0 <ide> try_count = 1 <ide> def gantt(self, session=None): <ide> prev_task_id = tf.task_id <ide> gantt_bar_items.append((tf.task_id, start_date, end_date, State.FAILED, try_count)) <ide> tf_count = tf_count + 1 <add> task = dag.get_task(tf.task_id) <ide> d = alchemy_to_dict(tf) <ide> d['state'] = State.FAILED <del> d['operator'] = dag.get_task(tf.task_id).task_type <add> d['operator'] = task.task_type <ide> d['try_number'] = try_count <add> d['extraLinks'] = task.extra_links <ide> tasks.append(d) <ide> <ide> data = { <ide><path>tests/www/test_views.py <ide> def test_global_extra_links_works(self, get_dag_function): <ide> 'error': None <ide> }) <ide> <add> @mock.patch('airflow.www.views.dagbag.get_dag') <add> def test_extra_link_in_gantt_view(self, get_dag_function): <add> get_dag_function.return_value = self.dag <add> <add> exec_date = dates.days_ago(2) <add> start_date = datetime(2020, 4, 10, 2, 0, 0) <add> end_date = exec_date + timedelta(seconds=30) <add> <add> with create_session() as session: <add> for task in self.dag.tasks: <add> ti = TaskInstance(task=task, execution_date=exec_date, state="success") <add> ti.start_date = start_date <add> ti.end_date = end_date <add> session.add(ti) <add> <add> url = 'gantt?dag_id={}&execution_date={}'.format(self.dag.dag_id, exec_date) <add> resp = self.client.get(url, follow_redirects=True) <add> <add> self.check_content_in_response('"extraLinks":', resp) <add> <add> extra_links_grps = re.search(r'extraLinks\": \[(\".*?\")\]', resp.get_data(as_text=True)) <add> extra_links = extra_links_grps.group(0) <add> self.assertIn('airflow', extra_links) <add> self.assertIn('github', extra_links) <add> <ide> @mock.patch('airflow.www.views.dagbag.get_dag') <ide> def test_operator_extra_link_override_global_extra_link(self, get_dag_function): <ide> get_dag_function.return_value = self.dag
2
Text
Text
fix typo in one of the links
2e5c2e16457648a8a9d07948feb549f124d9e463
<ide><path>docs/how-to-work-on-coding-challenges.md <ide> Challenge solution code. <ide> <ide> Creating and Editing Challenges: <ide> <del>1. [Challenge Style Guide](style-guide-for-curriclum-challenges.md) - how to create and format challenges <add>1. [Challenge Style Guide](style-guide-for-curriculum-challenges.md) - how to create and format challenges <ide> <ide> 2. [Challenge types](https://github.com/freeCodeCamp/learn/blob/a5cb25704168aa37f59a582f0bb5a19b7bd89b46/utils/challengeTypes.js) - what the numeric challenge type values mean (enum). <ide> <del>3. [Contributing to FreeCodeCamp - Writing ES6 Challenge Tests ](https://www.youtube.com/watch?v=iOdD84OSfAE#t=2h49m55s) - a video following [Ethan Arrowood](https://twitter.com/ArrowoodTech) as he contributes to the old version of the curriculum <ide>\ No newline at end of file <add>3. [Contributing to FreeCodeCamp - Writing ES6 Challenge Tests ](https://www.youtube.com/watch?v=iOdD84OSfAE#t=2h49m55s) - a video following [Ethan Arrowood](https://twitter.com/ArrowoodTech) as he contributes to the old version of the curriculum
1
Python
Python
update setup.py metadata
e4e35296fb4a6af49c18dc814629a6acfdbe96a2
<ide><path>setup.py <ide> setup( <ide> name="transformers", <ide> version="2.0.0", <del> author="Thomas Wolf, Lysandre Debut, Victor Sanh, Julien Chaumond, Google AI Language Team Authors, Open AI team Authors", <add> author="Thomas Wolf, Lysandre Debut, Victor Sanh, Julien Chaumond, Google AI Language Team Authors, Open AI team Authors, Facebook AI Authors, Carnegie Mellon University Authors", <ide> author_email="thomas@huggingface.co", <del> description="Repository of pre-trained NLP Transformer models: BERT & RoBERTa, GPT & GPT-2, Transformer-XL, XLNet and XLM", <add> description="State-of-the-art Natural Language Processing for TensorFlow 2.0 and PyTorch", <ide> long_description=open("README.md", "r", encoding='utf-8').read(), <ide> long_description_content_type="text/markdown", <del> keywords='NLP deep learning transformer pytorch BERT GPT GPT-2 google openai CMU', <add> keywords='NLP deep learning transformer pytorch tensorflow BERT GPT GPT-2 google openai CMU', <ide> license='Apache', <ide> url="https://github.com/huggingface/transformers", <ide> packages=find_packages(exclude=["*.tests", "*.tests.*",
1
Python
Python
add numpyconfig.h to the install
d42ab1598a44cb00bffcc907605013eca012dbf9
<ide><path>numpy/core/setup.py <ide> def generate_numpyconfig_h(ext, build_dir): <ide> print target_f.read() <ide> target_f.close() <ide> print 'EOF' <add> config.add_data_files((header_dir, target)) <ide> return target <ide> <ide> def generate_api_func(module_name):
1
Javascript
Javascript
fix typo in injector documentation
271d2bed3afacc780b40af8b692c40a031d79f9d
<ide><path>src/auto/injector.js <ide> * // create an injector <ide> * var $injector = angular.injector(['ng']); <ide> * <del> * // use the injector to kick of your application <add> * // use the injector to kick off your application <ide> * // use the type inference to auto inject arguments, or use implicit injection <ide> * $injector.invoke(function($rootScope, $compile, $document){ <ide> * $compile($document)($rootScope);
1
Ruby
Ruby
remove osx-gcc from brew-doctor
b5268a877e1de7c31e7f0b7e3abdfde61c5131ad
<ide><path>Library/Homebrew/cmd/doctor.rb <ide> def check_missing_deps <ide> <ide> def check_git_status <ide> HOMEBREW_REPOSITORY.cd do <del> cmd = `git status -s Library/Homebrew/`.chomp <add> cmd = `git status -s Library/Homebrew/ 2> /dev/null`.chomp <ide> if system "/usr/bin/which -s git" and File.directory? '.git' and not cmd.empty? <ide> ohai "You have uncommitted modifications to Homebrew's core." <ide> puts "Unless you know what you are doing, you should run:" <ide> def check_for_enthought_python <ide> EOS <ide> end <ide> <del>def check_for_osx_gcc_installer <del> # Use the existence of Carbon headers to make a guess as to whether <del> # the osx-gcc-installer was used in lieu of Xcode. <del> unless File.exist? "/System/Library/Frameworks/Carbon.framework/Headers/Carbon.h" <del> puts <<-EOS.undent <del> It appears that you are using the osx-gcc-installer. <del> <del> This is unsupported, and software that require headers and other <del> resources that are normally provided by Xcode will fail to compile. <del> <del> We recommend that you install Xcode. <del> <del> EOS <del> end <del>end <del> <ide> module Homebrew extend self <ide> def doctor <ide> old_stdout = $stdout <ide> def doctor <ide> check_for_leopard_ssl <ide> check_git_version <ide> check_for_enthought_python <del> check_for_osx_gcc_installer <ide> ensure <ide> $stdout = old_stdout <ide> end
1
Javascript
Javascript
remove isnode call from map polyfill
f377926677987c018a48f1aefb7745413467eacc
<ide><path>Libraries/vendor/core/Map.js <ide> <ide> const _shouldPolyfillES6Collection = require('_shouldPolyfillES6Collection'); <ide> const guid = require('guid'); <del>const isNode = require('fbjs/lib/isNode'); <ide> const toIterator = require('toIterator'); <ide> <ide> module.exports = (function(global, undefined) { <ide> module.exports = (function(global, undefined) { <ide> SECRET_SIZE_PROP = '$size' + guid(); <ide> } <ide> <del> // In oldIE we use the DOM Node `uniqueID` property to get create the hash. <del> const OLD_IE_HASH_PREFIX = 'IE_HASH_'; <del> <ide> class Map { <ide> /** <ide> * 23.1.1.1 <ide> module.exports = (function(global, undefined) { <ide> } <ide> } <ide> <del> /** <del> * IE has a `uniqueID` set on every DOM node. So we construct the hash from <del> * this uniqueID to avoid memory leaks and the IE cloneNode bug where it <del> * clones properties in addition to the attributes. <del> * <del> * @param {object} node <del> * @return {?string} <del> */ <del> function getIENodeHash(node) { <del> let uniqueID; <del> switch (node.nodeType) { <del> case 1: // Element <del> uniqueID = node.uniqueID; <del> break; <del> case 9: // Document <del> uniqueID = node.documentElement.uniqueID; <del> break; <del> default: <del> return null; <del> } <del> <del> if (uniqueID) { <del> return OLD_IE_HASH_PREFIX + uniqueID; <del> } else { <del> return null; <del> } <del> } <del> <ide> const getHash = (function() { <ide> const propIsEnumerable = Object.prototype.propertyIsEnumerable; <ide> const hashProperty = '__MAP_POLYFILL_INTERNAL_HASH__'; <ide> module.exports = (function(global, undefined) { <ide> o.propertyIsEnumerable[hashProperty] <ide> ) { <ide> return o.propertyIsEnumerable[hashProperty]; <del> } else if (!isES5 && isNode(o) && getIENodeHash(o)) { <del> return getIENodeHash(o); <ide> } else if (!isES5 && o[hashProperty]) { <ide> return o[hashProperty]; <ide> } <ide> module.exports = (function(global, undefined) { <ide> } else if (o.propertyIsEnumerable) { <ide> // Since we can't define a non-enumerable property on the object <ide> // we'll hijack one of the less-used non-enumerable properties to <del> // save our hash on it. Addiotionally, since this is a function it <add> // save our hash on it. Additionally, since this is a function it <ide> // will not show up in `JSON.stringify` which is what we want. <ide> o.propertyIsEnumerable = function() { <ide> return propIsEnumerable.apply(this, arguments); <ide> }; <ide> o.propertyIsEnumerable[hashProperty] = hashCounter; <del> } else if (isNode(o)) { <del> // At this point we couldn't get the IE `uniqueID` to use as a hash <del> // and we couldn't use a non-enumerable property to exploit the <del> // dontEnum bug so we simply add the `hashProperty` on the node <del> // itself. <del> o[hashProperty] = hashCounter; <ide> } else { <ide> throw new Error('Unable to set a non-enumerable property on object.'); <ide> }
1
PHP
PHP
fix logic around marking services resolved or not
d17b2c1a462273606438f3a42b16747d75e8d7f1
<ide><path>src/Illuminate/Container/Container.php <ide> public function bound($abstract) <ide> return isset($this[$abstract]) || isset($this->instances[$abstract]); <ide> } <ide> <add> /** <add> * Determine if the given abstract type has been resolved. <add> * <add> * @param string $abstract <add> * @return bool <add> */ <add> public function resolved($abstract) <add> { <add> return isset($this->resolved[$abstract]) || isset($this->instances[$abstract]); <add> } <add> <ide> /** <ide> * Determine if a given string is an alias. <ide> * <ide> public function bind($abstract, $concrete = null, $shared = false) <ide> $concrete = $this->getClosure($abstract, $concrete); <ide> } <ide> <del> $bound = $this->bound($abstract); <del> <ide> $this->bindings[$abstract] = compact('concrete', 'shared'); <ide> <del> // If the abstract type was already bound in this container, we will fire the <add> // If the abstract type was already resolved in this container, we will fire the <ide> // rebound listener so that any objects which have already gotten resolved <ide> // can have their copy of the object updated via the listener callbacks. <del> if ($bound) <add> if ($this->resolved($abstract)) <ide> { <ide> $this->rebound($abstract); <ide> } <ide> public function make($abstract, $parameters = array()) <ide> { <ide> $abstract = $this->getAlias($abstract); <ide> <del> $this->resolved[$abstract] = true; <del> <ide> // If an instance of the type is currently being managed as a singleton we'll <ide> // just return an existing instance instead of instantiating new instances <ide> // so the developer can keep using the same objects instance every time. <ide> public function make($abstract, $parameters = array()) <ide> <ide> $this->fireResolvingCallbacks($abstract, $object); <ide> <add> $this->resolved[$abstract] = true; <add> <ide> return $object; <ide> } <ide> <ide><path>src/Illuminate/Foundation/Application.php <ide> public function make($abstract, $parameters = array()) <ide> return parent::make($abstract, $parameters); <ide> } <ide> <add> /** <add> * Determine if the given abstract type has been bound. <add> * <add> * (Overriding Container::bound) <add> * <add> * @param string $abstract <add> * @return bool <add> */ <add> public function bound($abstract) <add> { <add> return isset($this->deferredServices[$abstract]) || parent::bound($abstract); <add> } <add> <add> /** <add> * "Extend" an abstract type in the container. <add> * <add> * (Overriding Container::extend) <add> * <add> * @param string $abstract <add> * @param Closure $closure <add> * @return void <add> * <add> * @throws \InvalidArgumentException <add> */ <add> public function extend($abstract, Closure $closure) <add> { <add> $abstract = $this->getAlias($abstract); <add> <add> if (isset($this->deferredServices[$abstract])) <add> { <add> $this->loadDeferredProvider($abstract); <add> } <add> <add> return parent::extend($abstract, $closure); <add> } <add> <ide> /** <ide> * Register a "before" application filter. <ide> *
2
Javascript
Javascript
remove extraneous semicolon
b2a701ead2c659ac5c6656191beb02ebf7bffe02
<ide><path>d3.js <ide> function d3_dispatch_event(dispatch) { <ide> }; <ide> <ide> return event; <del>}; <add>} <ide> // TODO align <ide> d3.format = function(specifier) { <ide> var match = d3_format_re.exec(specifier), <ide><path>src/core/dispatch.js <ide> function d3_dispatch_event(dispatch) { <ide> }; <ide> <ide> return event; <del>}; <add>}
2
Go
Go
use diffsize instead of size in v1 push
741924384ee7a617af1a0275e2dc674e86b9d0d9
<ide><path>distribution/push_v1.go <ide> func (p *v1Pusher) pushImage(v1Image v1Image, ep string) (checksum string, err e <ide> defer arch.Close() <ide> <ide> // don't care if this fails; best effort <del> size, _ := l.Size() <add> size, _ := l.DiffSize() <ide> <ide> // Send the layer <ide> logrus.Debugf("rendered layer for %s of [%d] size", v1ID, size)
1
Ruby
Ruby
support optional collation in create_table output
e4ca7d7048d5434b02b8a9b6a3bc917264da3792
<ide><path>activerecord/test/cases/adapters/mysql2/table_options_test.rb <ide> def teardown <ide> test "table options with CHARSET" do <ide> @connection.create_table "mysql_table_options", force: true, options: "CHARSET=latin1" <ide> output = dump_table_schema("mysql_table_options") <del> expected = /create_table "mysql_table_options", charset: "latin1", force: :cascade/ <add> expected = /create_table "mysql_table_options", charset: "latin1"(?:, collation: "\w+")?, force: :cascade/ <ide> assert_match expected, output <ide> end <ide>
1
PHP
PHP
move tests closer to the code being tested
3e187427dc4501824431cb835b3e7647925ef4fe
<ide><path>tests/TestCase/ORM/Association/HasManyTest.php <ide> public function testSaveStrategy() <ide> $this->assertSame(HasMany::SAVE_REPLACE, $association->saveStrategy()); <ide> }); <ide> } <add> <add> /** <add> * Test that save works with replace saveStrategy and are not deleted once they are not null <add> * <add> * @return void <add> */ <add> public function testSaveReplaceSaveStrategy() <add> { <add> $authors = $this->getTableLocator()->get('Authors'); <add> $authors->hasMany('Articles', ['saveStrategy' => HasMany::SAVE_REPLACE]); <add> <add> $entity = $authors->newEntity([ <add> 'name' => 'mylux', <add> 'articles' => [ <add> ['title' => 'One Random Post', 'body' => 'The cake is not a lie'], <add> ['title' => 'Another Random Post', 'body' => 'The cake is nice'], <add> ['title' => 'One more random post', 'body' => 'The cake is forever'] <add> ] <add> ], ['associated' => ['Articles']]); <add> <add> $entity = $authors->save($entity, ['associated' => ['Articles']]); <add> $sizeArticles = count($entity->articles); <add> $this->assertEquals($sizeArticles, $authors->Articles->find('all')->where(['author_id' => $entity['id']])->count()); <add> <add> $articleId = $entity->articles[0]->id; <add> unset($entity->articles[0]); <add> $entity->setDirty('articles', true); <add> <add> $authors->save($entity, ['associated' => ['Articles']]); <add> <add> $this->assertEquals($sizeArticles - 1, $authors->Articles->find('all')->where(['author_id' => $entity['id']])->count()); <add> $this->assertTrue($authors->Articles->exists(['id' => $articleId])); <add> } <add> <add> /** <add> * Test that save works with replace saveStrategy, replacing the already persisted entities even if no new entities are passed <add> * <add> * @return void <add> */ <add> public function testSaveReplaceSaveStrategyNotAdding() <add> { <add> $authors = $this->getTableLocator()->get('Authors'); <add> $authors->hasMany('Articles', ['saveStrategy' => 'replace']); <add> <add> $entity = $authors->newEntity([ <add> 'name' => 'mylux', <add> 'articles' => [ <add> ['title' => 'One Random Post', 'body' => 'The cake is not a lie'], <add> ['title' => 'Another Random Post', 'body' => 'The cake is nice'], <add> ['title' => 'One more random post', 'body' => 'The cake is forever'] <add> ] <add> ], ['associated' => ['Articles']]); <add> <add> $entity = $authors->save($entity, ['associated' => ['Articles']]); <add> $sizeArticles = count($entity->articles); <add> $this->assertCount($sizeArticles, $authors->Articles->find('all')->where(['author_id' => $entity['id']])); <add> <add> $entity->set('articles', []); <add> <add> $entity = $authors->save($entity, ['associated' => ['Articles']]); <add> <add> $this->assertCount(0, $authors->Articles->find('all')->where(['author_id' => $entity['id']])); <add> } <add> <add> /** <add> * Test that save works with append saveStrategy not deleting or setting null anything <add> * <add> * @return void <add> */ <add> public function testSaveAppendSaveStrategy() <add> { <add> $authors = $this->getTableLocator()->get('Authors'); <add> $authors->hasMany('Articles', ['saveStrategy' => 'append']); <add> <add> $entity = $authors->newEntity([ <add> 'name' => 'mylux', <add> 'articles' => [ <add> ['title' => 'One Random Post', 'body' => 'The cake is not a lie'], <add> ['title' => 'Another Random Post', 'body' => 'The cake is nice'], <add> ['title' => 'One more random post', 'body' => 'The cake is forever'] <add> ] <add> ], ['associated' => ['Articles']]); <add> <add> $entity = $authors->save($entity, ['associated' => ['Articles']]); <add> $sizeArticles = count($entity->articles); <add> <add> $this->assertEquals($sizeArticles, $authors->Articles->find('all')->where(['author_id' => $entity['id']])->count()); <add> <add> $articleId = $entity->articles[0]->id; <add> unset($entity->articles[0]); <add> $entity->setDirty('articles', true); <add> <add> $authors->save($entity, ['associated' => ['Articles']]); <add> <add> $this->assertEquals($sizeArticles, $authors->Articles->find('all')->where(['author_id' => $entity['id']])->count()); <add> $this->assertTrue($authors->Articles->exists(['id' => $articleId])); <add> } <add> <add> /** <add> * Test that save has append as the default save strategy <add> * <add> * @return void <add> */ <add> public function testSaveDefaultSaveStrategy() <add> { <add> $authors = $this->getTableLocator()->get('Authors'); <add> $authors->hasMany('Articles', ['saveStrategy' => 'append']); <add> $this->assertEquals('append', $authors->getAssociation('articles')->getSaveStrategy()); <add> } <add> <add> /** <add> * Test that the associated entities are unlinked and deleted when they are dependent <add> * <add> * @return void <add> */ <add> public function testSaveReplaceSaveStrategyDependent() <add> { <add> $authors = $this->getTableLocator()->get('Authors'); <add> $authors->hasMany('Articles', ['saveStrategy' => 'replace', 'dependent' => true]); <add> <add> $entity = $authors->newEntity([ <add> 'name' => 'mylux', <add> 'articles' => [ <add> ['title' => 'One Random Post', 'body' => 'The cake is not a lie'], <add> ['title' => 'Another Random Post', 'body' => 'The cake is nice'], <add> ['title' => 'One more random post', 'body' => 'The cake is forever'] <add> ] <add> ], ['associated' => ['Articles']]); <add> <add> $entity = $authors->save($entity, ['associated' => ['Articles']]); <add> $sizeArticles = count($entity->articles); <add> $this->assertEquals($sizeArticles, $authors->Articles->find('all')->where(['author_id' => $entity['id']])->count()); <add> <add> $articleId = $entity->articles[0]->id; <add> unset($entity->articles[0]); <add> $entity->setDirty('articles', true); <add> <add> $authors->save($entity, ['associated' => ['Articles']]); <add> <add> $this->assertEquals($sizeArticles - 1, $authors->Articles->find('all')->where(['author_id' => $entity['id']])->count()); <add> $this->assertFalse($authors->Articles->exists(['id' => $articleId])); <add> } <add> <add> /** <add> * Test that the associated entities are unlinked and deleted when they have a not nullable foreign key <add> * <add> * @return void <add> */ <add> public function testSaveReplaceSaveStrategyNotNullable() <add> { <add> $articles = $this->getTableLocator()->get('Articles'); <add> $articles->hasMany('Comments', ['saveStrategy' => HasMany::SAVE_REPLACE]); <add> <add> $article = $articles->newEntity([ <add> 'title' => 'Bakeries are sky rocketing', <add> 'body' => 'All because of cake', <add> 'comments' => [ <add> [ <add> 'user_id' => 1, <add> 'comment' => 'That is true!' <add> ], <add> [ <add> 'user_id' => 2, <add> 'comment' => 'Of course' <add> ] <add> ] <add> ], ['associated' => ['Comments']]); <add> <add> $article = $articles->save($article, ['associated' => ['Comments']]); <add> $commentId = $article->comments[0]->id; <add> $sizeComments = count($article->comments); <add> <add> $this->assertEquals($sizeComments, $articles->Comments->find('all')->where(['article_id' => $article->id])->count()); <add> $this->assertTrue($articles->Comments->exists(['id' => $commentId])); <add> <add> unset($article->comments[0]); <add> $article->setDirty('comments', true); <add> $article = $articles->save($article, ['associated' => ['Comments']]); <add> <add> $this->assertEquals($sizeComments - 1, $articles->Comments->find('all')->where(['article_id' => $article->id])->count()); <add> $this->assertFalse($articles->Comments->exists(['id' => $commentId])); <add> } <add> <add> /** <add> * Test that the associated entities are unlinked and deleted when they have a not nullable foreign key <add> * <add> * @return void <add> */ <add> public function testSaveReplaceSaveStrategyAdding() <add> { <add> $articles = $this->getTableLocator()->get('Articles'); <add> $articles->hasMany('Comments', ['saveStrategy' => HasMany::SAVE_REPLACE]); <add> <add> $article = $articles->newEntity([ <add> 'title' => 'Bakeries are sky rocketing', <add> 'body' => 'All because of cake', <add> 'comments' => [ <add> [ <add> 'user_id' => 1, <add> 'comment' => 'That is true!' <add> ], <add> [ <add> 'user_id' => 2, <add> 'comment' => 'Of course' <add> ] <add> ] <add> ], ['associated' => ['Comments']]); <add> <add> $article = $articles->save($article, ['associated' => ['Comments']]); <add> $commentId = $article->comments[0]->id; <add> $sizeComments = count($article->comments); <add> $articleId = $article->id; <add> <add> $this->assertEquals($sizeComments, $articles->Comments->find('all')->where(['article_id' => $article->id])->count()); <add> $this->assertTrue($articles->Comments->exists(['id' => $commentId])); <add> <add> unset($article->comments[0]); <add> $article->comments[] = $articles->Comments->newEntity([ <add> 'user_id' => 1, <add> 'comment' => 'new comment' <add> ]); <add> <add> $article->setDirty('comments', true); <add> $article = $articles->save($article, ['associated' => ['Comments']]); <add> <add> $this->assertEquals($sizeComments, $articles->Comments->find('all')->where(['article_id' => $article->id])->count()); <add> $this->assertFalse($articles->Comments->exists(['id' => $commentId])); <add> $this->assertTrue($articles->Comments->exists(['comment' => 'new comment', 'article_id' => $articleId])); <add> } <add> <add> /** <add> * Tests that dependent, non-cascading deletes are using the association <add> * conditions for deleting associated records. <add> * <add> * @return void <add> */ <add> public function testHasManyNonCascadingUnlinkDeleteUsesAssociationConditions() <add> { <add> $Articles = $this->getTableLocator()->get('Articles'); <add> $Comments = $Articles->hasMany('Comments', [ <add> 'dependent' => true, <add> 'cascadeCallbacks' => false, <add> 'saveStrategy' => HasMany::SAVE_REPLACE, <add> 'conditions' => [ <add> 'Comments.published' => 'Y' <add> ] <add> ]); <add> <add> $article = $Articles->newEntity([ <add> 'title' => 'Title', <add> 'body' => 'Body', <add> 'comments' => [ <add> [ <add> 'user_id' => 1, <add> 'comment' => 'First comment', <add> 'published' => 'Y' <add> ], <add> [ <add> 'user_id' => 1, <add> 'comment' => 'Second comment', <add> 'published' => 'Y' <add> ] <add> ] <add> ]); <add> $article = $Articles->save($article); <add> $this->assertNotEmpty($article); <add> <add> $comment3 = $Comments->getTarget()->newEntity([ <add> 'article_id' => $article->get('id'), <add> 'user_id' => 1, <add> 'comment' => 'Third comment', <add> 'published' => 'N' <add> ]); <add> $comment3 = $Comments->getTarget()->save($comment3); <add> $this->assertNotEmpty($comment3); <add> <add> $this->assertEquals(3, $Comments->getTarget()->find()->where(['Comments.article_id' => $article->get('id')])->count()); <add> <add> unset($article->comments[1]); <add> $article->setDirty('comments', true); <add> <add> $article = $Articles->save($article); <add> $this->assertNotEmpty($article); <add> <add> // Given the association condition of `'Comments.published' => 'Y'`, <add> // it is expected that only one of the three linked comments are <add> // actually being deleted, as only one of them matches the <add> // association condition. <add> $this->assertEquals(2, $Comments->getTarget()->find()->where(['Comments.article_id' => $article->get('id')])->count()); <add> } <add> <add> /** <add> * Tests that non-dependent, non-cascading deletes are using the association <add> * conditions for updating associated records. <add> * <add> * @return void <add> */ <add> public function testHasManyNonDependentNonCascadingUnlinkUpdateUsesAssociationConditions() <add> { <add> $Authors = $this->getTableLocator()->get('Authors'); <add> $Authors->associations()->removeAll(); <add> $Articles = $Authors->hasMany('Articles', [ <add> 'dependent' => false, <add> 'cascadeCallbacks' => false, <add> 'saveStrategy' => HasMany::SAVE_REPLACE, <add> 'conditions' => [ <add> 'Articles.published' => 'Y' <add> ] <add> ]); <add> <add> $author = $Authors->newEntity([ <add> 'name' => 'Name', <add> 'articles' => [ <add> [ <add> 'title' => 'First article', <add> 'body' => 'First article', <add> 'published' => 'Y' <add> ], <add> [ <add> 'title' => 'Second article', <add> 'body' => 'Second article', <add> 'published' => 'Y' <add> ] <add> ] <add> ]); <add> $author = $Authors->save($author); <add> $this->assertNotEmpty($author); <add> <add> $article3 = $Articles->getTarget()->newEntity([ <add> 'author_id' => $author->get('id'), <add> 'title' => 'Third article', <add> 'body' => 'Third article', <add> 'published' => 'N' <add> ]); <add> $article3 = $Articles->getTarget()->save($article3); <add> $this->assertNotEmpty($article3); <add> <add> $this->assertEquals(3, $Articles->getTarget()->find()->where(['Articles.author_id' => $author->get('id')])->count()); <add> <add> $article2 = $author->articles[1]; <add> unset($author->articles[1]); <add> $author->setDirty('articles', true); <add> <add> $author = $Authors->save($author); <add> $this->assertNotEmpty($author); <add> <add> // Given the association condition of `'Articles.published' => 'Y'`, <add> // it is expected that only one of the three linked articles are <add> // actually being unlinked (nulled), as only one of them matches the <add> // association condition. <add> $this->assertEquals(2, $Articles->getTarget()->find()->where(['Articles.author_id' => $author->get('id')])->count()); <add> $this->assertNull($Articles->get($article2->get('id'))->get('author_id')); <add> $this->assertEquals($author->get('id'), $Articles->get($article3->get('id'))->get('author_id')); <add> } <ide> } <ide><path>tests/TestCase/ORM/TableTest.php <ide> public function testSavePrimaryKeyEntityExists() <ide> $this->assertSame($entity, $table->save($entity)); <ide> } <ide> <del> /** <del> * Test that save works with replace saveStrategy and are not deleted once they are not null <del> * <del> * @return void <del> */ <del> public function testSaveReplaceSaveStrategy() <del> { <del> $authors = new Table( <del> [ <del> 'table' => 'authors', <del> 'alias' => 'Authors', <del> 'connection' => $this->connection, <del> 'entityClass' => 'Cake\ORM\Entity', <del> ] <del> ); <del> <del> $authors->hasMany('Articles', ['saveStrategy' => 'replace']); <del> <del> $entity = $authors->newEntity([ <del> 'name' => 'mylux', <del> 'articles' => [ <del> ['title' => 'One Random Post', 'body' => 'The cake is not a lie'], <del> ['title' => 'Another Random Post', 'body' => 'The cake is nice'], <del> ['title' => 'One more random post', 'body' => 'The cake is forever'] <del> ] <del> ], ['associated' => ['Articles']]); <del> <del> $entity = $authors->save($entity, ['associated' => ['Articles']]); <del> $sizeArticles = count($entity->articles); <del> $this->assertEquals($sizeArticles, $authors->Articles->find('all')->where(['author_id' => $entity['id']])->count()); <del> <del> $articleId = $entity->articles[0]->id; <del> unset($entity->articles[0]); <del> $entity->setDirty('articles', true); <del> <del> $authors->save($entity, ['associated' => ['Articles']]); <del> <del> $this->assertEquals($sizeArticles - 1, $authors->Articles->find('all')->where(['author_id' => $entity['id']])->count()); <del> $this->assertTrue($authors->Articles->exists(['id' => $articleId])); <del> } <del> <del> /** <del> * Test that save works with replace saveStrategy, replacing the already persisted entities even if no new entities are passed <del> * <del> * @return void <del> */ <del> public function testSaveReplaceSaveStrategyNotAdding() <del> { <del> $authors = new Table( <del> [ <del> 'table' => 'authors', <del> 'alias' => 'Authors', <del> 'connection' => $this->connection, <del> 'entityClass' => 'Cake\ORM\Entity', <del> ] <del> ); <del> <del> $authors->hasMany('Articles', ['saveStrategy' => 'replace']); <del> <del> $entity = $authors->newEntity([ <del> 'name' => 'mylux', <del> 'articles' => [ <del> ['title' => 'One Random Post', 'body' => 'The cake is not a lie'], <del> ['title' => 'Another Random Post', 'body' => 'The cake is nice'], <del> ['title' => 'One more random post', 'body' => 'The cake is forever'] <del> ] <del> ], ['associated' => ['Articles']]); <del> <del> $entity = $authors->save($entity, ['associated' => ['Articles']]); <del> $sizeArticles = count($entity->articles); <del> $this->assertCount($sizeArticles, $authors->Articles->find('all')->where(['author_id' => $entity['id']])); <del> <del> $entity->set('articles', []); <del> <del> $entity = $authors->save($entity, ['associated' => ['Articles']]); <del> <del> $this->assertCount(0, $authors->Articles->find('all')->where(['author_id' => $entity['id']])); <del> } <del> <del> /** <del> * Test that save works with append saveStrategy not deleting or setting null anything <del> * <del> * @return void <del> */ <del> public function testSaveAppendSaveStrategy() <del> { <del> $authors = new Table( <del> [ <del> 'table' => 'authors', <del> 'alias' => 'Authors', <del> 'connection' => $this->connection, <del> 'entityClass' => 'Cake\ORM\Entity', <del> ] <del> ); <del> <del> $authors->hasMany('Articles', ['saveStrategy' => 'append']); <del> <del> $entity = $authors->newEntity([ <del> 'name' => 'mylux', <del> 'articles' => [ <del> ['title' => 'One Random Post', 'body' => 'The cake is not a lie'], <del> ['title' => 'Another Random Post', 'body' => 'The cake is nice'], <del> ['title' => 'One more random post', 'body' => 'The cake is forever'] <del> ] <del> ], ['associated' => ['Articles']]); <del> <del> $entity = $authors->save($entity, ['associated' => ['Articles']]); <del> $sizeArticles = count($entity->articles); <del> <del> $this->assertEquals($sizeArticles, $authors->Articles->find('all')->where(['author_id' => $entity['id']])->count()); <del> <del> $articleId = $entity->articles[0]->id; <del> unset($entity->articles[0]); <del> $entity->setDirty('articles', true); <del> <del> $authors->save($entity, ['associated' => ['Articles']]); <del> <del> $this->assertEquals($sizeArticles, $authors->Articles->find('all')->where(['author_id' => $entity['id']])->count()); <del> $this->assertTrue($authors->Articles->exists(['id' => $articleId])); <del> } <del> <del> /** <del> * Test that save has append as the default save strategy <del> * <del> * @return void <del> */ <del> public function testSaveDefaultSaveStrategy() <del> { <del> $authors = new Table( <del> [ <del> 'table' => 'authors', <del> 'alias' => 'Authors', <del> 'connection' => $this->connection, <del> 'entityClass' => 'Cake\ORM\Entity', <del> ] <del> ); <del> $authors->hasMany('Articles', ['saveStrategy' => 'append']); <del> $this->assertEquals('append', $authors->getAssociation('articles')->getSaveStrategy()); <del> } <del> <del> /** <del> * Test that the associated entities are unlinked and deleted when they are dependent <del> * <del> * @return void <del> */ <del> public function testSaveReplaceSaveStrategyDependent() <del> { <del> $authors = new Table( <del> [ <del> 'table' => 'authors', <del> 'alias' => 'Authors', <del> 'connection' => $this->connection, <del> 'entityClass' => 'Cake\ORM\Entity', <del> ] <del> ); <del> <del> $authors->hasMany('Articles', ['saveStrategy' => 'replace', 'dependent' => true]); <del> <del> $entity = $authors->newEntity([ <del> 'name' => 'mylux', <del> 'articles' => [ <del> ['title' => 'One Random Post', 'body' => 'The cake is not a lie'], <del> ['title' => 'Another Random Post', 'body' => 'The cake is nice'], <del> ['title' => 'One more random post', 'body' => 'The cake is forever'] <del> ] <del> ], ['associated' => ['Articles']]); <del> <del> $entity = $authors->save($entity, ['associated' => ['Articles']]); <del> $sizeArticles = count($entity->articles); <del> $this->assertEquals($sizeArticles, $authors->Articles->find('all')->where(['author_id' => $entity['id']])->count()); <del> <del> $articleId = $entity->articles[0]->id; <del> unset($entity->articles[0]); <del> $entity->setDirty('articles', true); <del> <del> $authors->save($entity, ['associated' => ['Articles']]); <del> <del> $this->assertEquals($sizeArticles - 1, $authors->Articles->find('all')->where(['author_id' => $entity['id']])->count()); <del> $this->assertFalse($authors->Articles->exists(['id' => $articleId])); <del> } <del> <del> /** <del> * Test that the associated entities are unlinked and deleted when they have a not nullable foreign key <del> * <del> * @return void <del> */ <del> public function testSaveReplaceSaveStrategyNotNullable() <del> { <del> $articles = new Table( <del> [ <del> 'table' => 'articles', <del> 'alias' => 'Articles', <del> 'connection' => $this->connection, <del> 'entityClass' => 'Cake\ORM\Entity', <del> ] <del> ); <del> <del> $articles->hasMany('Comments', ['saveStrategy' => 'replace']); <del> <del> $article = $articles->newEntity([ <del> 'title' => 'Bakeries are sky rocketing', <del> 'body' => 'All because of cake', <del> 'comments' => [ <del> [ <del> 'user_id' => 1, <del> 'comment' => 'That is true!' <del> ], <del> [ <del> 'user_id' => 2, <del> 'comment' => 'Of course' <del> ] <del> ] <del> ], ['associated' => ['Comments']]); <del> <del> $article = $articles->save($article, ['associated' => ['Comments']]); <del> $commentId = $article->comments[0]->id; <del> $sizeComments = count($article->comments); <del> <del> $this->assertEquals($sizeComments, $articles->Comments->find('all')->where(['article_id' => $article->id])->count()); <del> $this->assertTrue($articles->Comments->exists(['id' => $commentId])); <del> <del> unset($article->comments[0]); <del> $article->setDirty('comments', true); <del> $article = $articles->save($article, ['associated' => ['Comments']]); <del> <del> $this->assertEquals($sizeComments - 1, $articles->Comments->find('all')->where(['article_id' => $article->id])->count()); <del> $this->assertFalse($articles->Comments->exists(['id' => $commentId])); <del> } <del> <del> /** <del> * Test that the associated entities are unlinked and deleted when they have a not nullable foreign key <del> * <del> * @return void <del> */ <del> public function testSaveReplaceSaveStrategyAdding() <del> { <del> $articles = new Table( <del> [ <del> 'table' => 'articles', <del> 'alias' => 'Articles', <del> 'connection' => $this->connection, <del> 'entityClass' => 'Cake\ORM\Entity', <del> ] <del> ); <del> <del> $articles->hasMany('Comments', ['saveStrategy' => 'replace']); <del> <del> $article = $articles->newEntity([ <del> 'title' => 'Bakeries are sky rocketing', <del> 'body' => 'All because of cake', <del> 'comments' => [ <del> [ <del> 'user_id' => 1, <del> 'comment' => 'That is true!' <del> ], <del> [ <del> 'user_id' => 2, <del> 'comment' => 'Of course' <del> ] <del> ] <del> ], ['associated' => ['Comments']]); <del> <del> $article = $articles->save($article, ['associated' => ['Comments']]); <del> $commentId = $article->comments[0]->id; <del> $sizeComments = count($article->comments); <del> $articleId = $article->id; <del> <del> $this->assertEquals($sizeComments, $articles->Comments->find('all')->where(['article_id' => $article->id])->count()); <del> $this->assertTrue($articles->Comments->exists(['id' => $commentId])); <del> <del> unset($article->comments[0]); <del> $article->comments[] = $articles->Comments->newEntity([ <del> 'user_id' => 1, <del> 'comment' => 'new comment' <del> ]); <del> <del> $article->setDirty('comments', true); <del> $article = $articles->save($article, ['associated' => ['Comments']]); <del> <del> $this->assertEquals($sizeComments, $articles->Comments->find('all')->where(['article_id' => $article->id])->count()); <del> $this->assertFalse($articles->Comments->exists(['id' => $commentId])); <del> $this->assertTrue($articles->Comments->exists(['comment' => 'new comment', 'article_id' => $articleId])); <del> } <del> <del> /** <del> * Tests that dependent, non-cascading deletes are using the association <del> * conditions for deleting associated records. <del> * <del> * @return void <del> */ <del> public function testHasManyNonCascadingUnlinkDeleteUsesAssociationConditions() <del> { <del> $Articles = $this->getTableLocator()->get('Articles'); <del> $Comments = $Articles->hasMany('Comments', [ <del> 'dependent' => true, <del> 'cascadeCallbacks' => false, <del> 'saveStrategy' => HasMany::SAVE_REPLACE, <del> 'conditions' => [ <del> 'Comments.published' => 'Y' <del> ] <del> ]); <del> <del> $article = $Articles->newEntity([ <del> 'title' => 'Title', <del> 'body' => 'Body', <del> 'comments' => [ <del> [ <del> 'user_id' => 1, <del> 'comment' => 'First comment', <del> 'published' => 'Y' <del> ], <del> [ <del> 'user_id' => 1, <del> 'comment' => 'Second comment', <del> 'published' => 'Y' <del> ] <del> ] <del> ]); <del> $article = $Articles->save($article); <del> $this->assertNotEmpty($article); <del> <del> $comment3 = $Comments->getTarget()->newEntity([ <del> 'article_id' => $article->get('id'), <del> 'user_id' => 1, <del> 'comment' => 'Third comment', <del> 'published' => 'N' <del> ]); <del> $comment3 = $Comments->getTarget()->save($comment3); <del> $this->assertNotEmpty($comment3); <del> <del> $this->assertEquals(3, $Comments->getTarget()->find()->where(['Comments.article_id' => $article->get('id')])->count()); <del> <del> unset($article->comments[1]); <del> $article->setDirty('comments', true); <del> <del> $article = $Articles->save($article); <del> $this->assertNotEmpty($article); <del> <del> // Given the association condition of `'Comments.published' => 'Y'`, <del> // it is expected that only one of the three linked comments are <del> // actually being deleted, as only one of them matches the <del> // association condition. <del> $this->assertEquals(2, $Comments->getTarget()->find()->where(['Comments.article_id' => $article->get('id')])->count()); <del> } <del> <del> /** <del> * Tests that non-dependent, non-cascading deletes are using the association <del> * conditions for updating associated records. <del> * <del> * @return void <del> */ <del> public function testHasManyNonDependentNonCascadingUnlinkUpdateUsesAssociationConditions() <del> { <del> $Authors = $this->getTableLocator()->get('Authors'); <del> $Authors->associations()->removeAll(); <del> $Articles = $Authors->hasMany('Articles', [ <del> 'dependent' => false, <del> 'cascadeCallbacks' => false, <del> 'saveStrategy' => HasMany::SAVE_REPLACE, <del> 'conditions' => [ <del> 'Articles.published' => 'Y' <del> ] <del> ]); <del> <del> $author = $Authors->newEntity([ <del> 'name' => 'Name', <del> 'articles' => [ <del> [ <del> 'title' => 'First article', <del> 'body' => 'First article', <del> 'published' => 'Y' <del> ], <del> [ <del> 'title' => 'Second article', <del> 'body' => 'Second article', <del> 'published' => 'Y' <del> ] <del> ] <del> ]); <del> $author = $Authors->save($author); <del> $this->assertNotEmpty($author); <del> <del> $article3 = $Articles->getTarget()->newEntity([ <del> 'author_id' => $author->get('id'), <del> 'title' => 'Third article', <del> 'body' => 'Third article', <del> 'published' => 'N' <del> ]); <del> $article3 = $Articles->getTarget()->save($article3); <del> $this->assertNotEmpty($article3); <del> <del> $this->assertEquals(3, $Articles->getTarget()->find()->where(['Articles.author_id' => $author->get('id')])->count()); <del> <del> $article2 = $author->articles[1]; <del> unset($author->articles[1]); <del> $author->setDirty('articles', true); <del> <del> $author = $Authors->save($author); <del> $this->assertNotEmpty($author); <del> <del> // Given the association condition of `'Articles.published' => 'Y'`, <del> // it is expected that only one of the three linked articles are <del> // actually being unlinked (nulled), as only one of them matches the <del> // association condition. <del> $this->assertEquals(2, $Articles->getTarget()->find()->where(['Articles.author_id' => $author->get('id')])->count()); <del> $this->assertNull($Articles->get($article2->get('id'))->get('author_id')); <del> $this->assertEquals($author->get('id'), $Articles->get($article3->get('id'))->get('author_id')); <del> } <del> <ide> /** <ide> * Test that saving a new entity with a Primary Key set does not call exists when checkExisting is false. <ide> *
2
Text
Text
add links for the mp3 files
5aa83c96536e59ed7f36f83d82a90223baa557e6
<ide><path>curriculum/challenges/english/03-front-end-development-libraries/front-end-development-libraries-projects/build-a-drum-machine.md <ide> You can use any mix of HTML, JavaScript, CSS, Bootstrap, SASS, React, Redux, and <ide> <ide> **User Story #7:** When a `.drum-pad` is triggered, a string describing the associated audio clip is displayed as the inner text of the `#display` element (each string must be unique). <ide> <add>Here are some audio samples you can use for your drum machine: <add> <add>- [Heater 1](https://s3.amazonaws.com/freecodecamp/drums/Heater-1.mp3) <add>- [Heater 2](https://s3.amazonaws.com/freecodecamp/drums/Heater-2.mp3) <add>- [Heater 3](https://s3.amazonaws.com/freecodecamp/drums/Heater-3.mp3) <add>- [Heater 4](https://s3.amazonaws.com/freecodecamp/drums/Heater-4_1.mp3) <add>- [Clap](https://s3.amazonaws.com/freecodecamp/drums/Heater-6.mp3) <add>- [Open-HH](https://s3.amazonaws.com/freecodecamp/drums/Dsc_Oh.mp3) <add>- [Kick-n'-Hat](https://s3.amazonaws.com/freecodecamp/drums/Kick_n_Hat.mp3) <add>- [Kick](https://s3.amazonaws.com/freecodecamp/drums/RP4_KICK_1.mp3) <add>- [Closed-HH](https://s3.amazonaws.com/freecodecamp/drums/Cev_H2.mp3) <add> <ide> You can build your project by <a href='https://codepen.io/pen?template=MJjpwO' target='_blank' rel="noopener noreferrer nofollow">using this CodePen template</a> and clicking `Save` to create your own pen. Or you can use this CDN link to run the tests in any environment you like: `https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js` <ide> <ide> Once you're done, submit the URL to your working project with all its tests passing.
1
Ruby
Ruby
consolidate testing of update_all type casting
58d38d6df2d7f1c1730a3f691a78b3037defa9e7
<ide><path>activerecord/test/cases/adapters/postgresql/array_test.rb <ide> def test_attribute_for_inspect_for_array_field <ide> assert_equal("[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...]", record.attribute_for_inspect(:ratings)) <ide> end <ide> <del> def test_update_all <del> pg_array = PgArray.create! tags: ["one", "two", "three"] <del> <del> PgArray.update_all tags: ["four", "five"] <del> assert_equal ["four", "five"], pg_array.reload.tags <del> <del> PgArray.update_all tags: [] <del> assert_equal [], pg_array.reload.tags <del> end <del> <ide> def test_escaping <ide> unknown = 'foo\\",bar,baz,\\' <ide> tags = ["hello_#{unknown}"] <ide><path>activerecord/test/cases/adapters/postgresql/hstore_test.rb <ide> def test_multiline <ide> assert_cycle("a\nb" => "c\nd") <ide> end <ide> <del> def test_update_all <del> hstore = Hstore.create! tags: { "one" => "two" } <del> <del> Hstore.update_all tags: { "three" => "four" } <del> assert_equal({ "three" => "four" }, hstore.reload.tags) <del> <del> Hstore.update_all tags: { } <del> assert_equal({ }, hstore.reload.tags) <del> end <del> <ide> class TagCollection <ide> def initialize(hash); @hash = hash end <ide> def to_hash; @hash end <ide><path>activerecord/test/cases/adapters/postgresql/json_test.rb <ide> def test_yaml_round_trip_with_store_accessors <ide> assert_equal "320×480", y.resolution <ide> end <ide> <del> def test_update_all <del> json = JsonDataType.create! payload: { "one" => "two" } <del> <del> JsonDataType.update_all payload: { "three" => "four" } <del> assert_equal({ "three" => "four" }, json.reload.payload) <del> <del> JsonDataType.update_all payload: { } <del> assert_equal({ }, json.reload.payload) <del> end <del> <ide> def test_changes_in_place <ide> json = JsonDataType.new <ide> assert_not json.changed? <ide><path>activerecord/test/cases/relation_test.rb <ide> def test_relation_merging_with_merged_joins_as_strings <ide> posts_with_special_comments_with_ratings = Post.group("posts.id").joins(:special_comments).merge(special_comments_with_ratings) <ide> assert_equal 3, authors(:david).posts.merge(posts_with_special_comments_with_ratings).count.length <ide> end <add> <add> class EnsureRoundTripTypeCasting < ActiveRecord::Type::Value <add> def type <add> :string <add> end <add> <add> def type_cast_from_database(value) <add> raise value unless value == "type cast for database" <add> "type cast from database" <add> end <add> <add> def type_cast_for_database(value) <add> raise value unless value == "value from user" <add> "type cast for database" <add> end <add> end <add> <add> class UpdateAllTestModel < ActiveRecord::Base <add> self.table_name = 'posts' <add> <add> attribute :body, EnsureRoundTripTypeCasting.new <add> end <add> <add> def test_update_all_goes_through_normal_type_casting <add> UpdateAllTestModel.update_all(body: "value from user", type: nil) # No STI <add> <add> assert_equal "type cast from database", UpdateAllTestModel.first.body <add> end <ide> end <ide> end
4
Javascript
Javascript
fix my git mistake, adding d3.min.js back
24de130f4e1df2e04a6e751a4b586e1bf66af927
<ide><path>d3.min.js <add>(function(){function bU(){return"circle"}function bT(){return 64}function bR(a){return a.endAngle}function bQ(a){return a.startAngle}function bP(a){return a.radius}function bO(a){return a.target}function bN(a){return a.source}function bM(){return 0}function bL(a,b,c){a.push("C",bH(bI,b),",",bH(bI,c),",",bH(bJ,b),",",bH(bJ,c),",",bH(bK,b),",",bH(bK,c))}function bH(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3]}function bG(a){var b,c=-1,d=a.length,e=d+4,f,g=[],h=[];while(++c<4)f=a[c%d],g.push(f[0]),h.push(f[1]);b=[bH(bK,g),",",bH(bK,h)],--c;while(++c<e)f=a[c%d],g.shift(),g.push(f[0]),h.shift(),h.push(f[1]),bL(b,g,h);return b.join("")}function bF(a){if(a.length<3)return by(a);var b=[],c=1,d=a.length,e=a[0],f=e[0],g=e[1],h=[f,f,f,(e=a[1])[0]],i=[g,g,g,e[1]];b.push(f,",",g),bL(b,h,i);while(++c<d)e=a[c],h.shift(),h.push(e[0]),i.shift(),i.push(e[1]),bL(b,h,i);c=-1;while(++c<2)h.shift(),h.push(e[0]),i.shift(),i.push(e[1]),bL(b,h,i);return b.join("")}function bE(a,b){var c=[],d=(1-b)/2,e,f=a[0],g=a[1],h=1,i=a.length;while(++h<i)e=f,f=g,g=a[h],c.push([d*(g[0]-e[0]),d*(g[1]-e[1])]);return c}function bD(a,b){if(b.length<1||a.length!=b.length&&a.length!=b.length+2)return by(a);var c=a.length!=b.length,d="",e=a[0],f=a[1],g=b[0],h=g,i=1;c&&(d+="Q"+(f[0]-g[0]*2/3)+","+(f[1]-g[1]*2/3)+","+f[0]+","+f[1],e=a[1],i=2);if(b.length>1){h=b[1],f=a[i],i++,d+="C"+(e[0]+g[0])+","+(e[1]+g[1])+","+(f[0]-h[0])+","+(f[1]-h[1])+","+f[0]+","+f[1];for(var j=2;j<b.length;j++,i++)f=a[i],h=b[j],d+="S"+(f[0]-h[0])+","+(f[1]-h[1])+","+f[0]+","+f[1]}if(c){var k=a[i];d+="Q"+(f[0]+h[0]*2/3)+","+(f[1]+h[1]*2/3)+","+k[0]+","+k[1]}return d}function bC(a,b,c){return a.length<3?by(a):a[0]+bD(a,bE(a,b))}function bB(a,b){return a.length<3?by(a):a[0]+bD((a.push(a[0]),a),bE([a[a.length-2]].concat(a,[a[1]]),b))}function bA(a){var b=[],c=0,d=a.length,e=a[0];b.push(e[0],",",e[1]);while(++c<d)b.push("H",(e=a[c])[0],"V",e[1]);return b.join("")}function bz(a){var b=[],c=0,d=a.length,e=a[0];b.push(e[0],",",e[1]);while(++c<d)b.push("V",(e=a[c])[1],"H",e[0]);return b.join("")}function by(a){var b=[],c=0,d=a.length,e=a[0];b.push(e[0],",",e[1]);while(++c<d)b.push("L",(e=a[c])[0],",",e[1]);return b.join("")}function bw(a){return a[1]}function bv(a){return a[0]}function bu(a,b,c,d){var e=[],f=-1,g=b.length,h=typeof c=="function",i=typeof d=="function",j;if(h&&i)while(++f<g)e.push([c.call(a,j=b[f],f),d.call(a,j,f)]);else if(h)while(++f<g)e.push([c.call(a,b[f],f),d]);else if(i)while(++f<g)e.push([c,d.call(a,b[f],f)]);else while(++f<g)e.push([c,d]);return e}function bt(a){return a.endAngle}function bs(a){return a.startAngle}function br(a){return a.outerRadius}function bq(a){return a.innerRadius}function bj(a){return function(b){return-Math.pow(-b,a)}}function bi(a){return function(b){return Math.pow(b,a)}}function bh(a){return-Math.log(-a)/Math.LN10}function bg(a){return Math.log(a)/Math.LN10}function be(){var a=null,b=$;while(b)b=b.flush?a?a.next=b.next:$=b.next:(a=b).next;a||(ba=0)}function bd(){var a,b=Date.now(),c=null,d=$;while(d)a=b-d.then,a>d.delay&&(d.flush=d.callback(a)),d=(c=d).next;be(),ba&&bf(bd)}function bc(){ba=1,_=0,bf(bd)}function bb(a,b){var c=Date.now(),d=!1,e=c+b,f,g=$;if(!!isFinite(b)){while(g){if(g.callback==a)g.then=c,g.delay=b,d=!0;else{var h=g.then+g.delay;h<e&&(e=h)}f=g,g=g.next}d||($={callback:a,then:c,delay:b,next:$}),ba||(clearTimeout(_),_=setTimeout(bc,Math.max(24,e-c)))}}function Z(a){return typeof a=="function"?function(b,c,d){return d3.interpolate(d,String(a.call(this,b,c)))}:(a=String(a),function(b,c,d){return d3.interpolate(d,a)})}function Y(a){function n(b){var h=!0,l=-1;a.each(function(){if(i[++l]!=2){var a=(b-j[l])/k[l],n=this.__transition__,o,p,q=e[l];if(a<1){h=!1;if(a<0)return}else a=1;if(i[l]){if(!n||n.active!=c){i[l]=2;return}}else{if(!n||n.active>c){i[l]=2;return}i[l]=1,g.start.dispatch.apply(this,arguments),q=e[l]={},n.active=c;for(p in d)q[p]=d[p].apply(this,arguments)}o=m(a);for(p in d)q[p].call(this,o);if(a==1){i[l]=2;if(n.active==c){var r=n.owner;r==c&&(delete this.__transition__,f&&this.parentNode.removeChild(this)),X=c,g.end.dispatch.apply(this,arguments),X=0,n.owner=r}}}});return h}var b={},c=X||++W,d={},e=[],f=!1,g=d3.dispatch("start","end"),i=[],j=[],k=[],l,m=d3.ease("cubic-in-out");a.each(function(){(this.__transition__||(this.__transition__={})).owner=c}),b.delay=function(c){var d=Infinity,e=-1;typeof c=="function"?a.each(function(a,b){var f=j[++e]=+c.apply(this,arguments);f<d&&(d=f)}):(d=+c,a.each(function(a,b){j[++e]=d})),bb(n,d);return b},b.duration=function(c){var d=-1;typeof c=="function"?(l=0,a.each(function(a,b){var e=k[++d]=+c.apply(this,arguments);e>l&&(l=e)})):(l=+c,a.each(function(a,b){k[++d]=l}));return b},b.ease=function(a){m=typeof a=="function"?a:d3.ease.apply(d3,arguments);return b},b.attrTween=function(a,c){function f(b,d){var e=c.call(this,b,d,this.getAttributeNS(a.space,a.local));return function(b){this.setAttributeNS(a.space,a.local,e(b))}}function e(b,d){var e=c.call(this,b,d,this.getAttribute(a));return function(b){this.setAttribute(a,e(b))}}d["attr."+a]=a.local?f:e;return b},b.attr=function(a,c){return b.attrTween(a,Z(c))},b.styleTween=function(a,c,e){function f(b,d){var f=c.call(this,b,d,window.getComputedStyle(this,null).getPropertyValue(a));return function(b){this.style.setProperty(a,f(b),e)}}arguments.length<3&&(e=null),d["style."+a]=f;return b},b.style=function(a,c,d){arguments.length<3&&(d=null);return b.styleTween(a,Z(c),d)},b.select=function(b){var c,d=Y(a.select(b)).ease(m);c=-1,d.delay(function(a,b){return j[++c]}),c=-1,d.duration(function(a,b){return k[++c]});return d},b.selectAll=function(b){var c,d=Y(a.selectAll(b)).ease(m);c=-1,d.delay(function(a,b){return j[b?c:++c]}),c=-1,d.duration(function(a,b){return k[b?c:++c]});return d},b.remove=function(){f=!0;return b},b.each=function(a,c){g[a].add(c);return b},b.call=h;return b.delay(0).duration(250)}function V(a){return{__data__:a}}function U(a){arguments.length||(a=d3.ascending);return function(b,c){return a(b&&b.__data__,c&&c.__data__)}}function T(a){function b(b){var c=[],d,e,f,g;for(var h=0,i=a.length;h<i;h++){f=a[h],c.push(d=[]),d.parentNode=f.parentNode;for(var j=0,k=f.length;j<k;j++)(g=f[j])?(d.push(e=b(f.parentNode)),e.__data__=g.__data__):d.push(null)}return S(c)}a.append=function(a){function d(b){return b.appendChild(document.createElementNS(a.space,a.local))}function c(b){return b.appendChild(document.createElement(a))}a=d3.ns.qualify(a);return b(a.local?d:c)},a.insert=function(a,c){function e(b){return b.insertBefore(document.createElementNS(a.space,a.local),P(c,b))}function d(b){return b.insertBefore(document.createElement(a),P(c,b))}a=d3.ns.qualify(a);return b(a.local?e:d)};return a}function S(a){function d(b){for(var c=0,d=a.length;c<d;c++){var e=a[c];for(var f=0,g=e.length;f<g;f++){var h=e[f];if(h)return b.call(h,h.__data__,f)}}return null}function c(b){var c=[],d,e,f;for(var g=0,h=a.length;g<h;g++){e=a[g];for(var i=0,j=e.length;i<j;i++)if(f=e[i])c.push(d=b(f)),d.parentNode=f}return S(c)}function b(b){var c=[],d,e,f,g;for(var h=0,i=a.length;h<i;h++){f=a[h],c.push(d=[]),d.parentNode=f.parentNode;for(var j=0,k=f.length;j<k;j++)(g=f[j])?(d.push(e=b(g)),e&&"__data__"in g&&(e.__data__=g.__data__)):d.push(null)}return S(c)}a.select=function(a){return b(function(b){return P(a,b)})},a.selectAll=function(a){return c(function(b){return Q(a,b)})},a.filter=function(b){var c=[],d,e,f;for(var g=0,h=a.length;g<h;g++){e=a[g],c.push(d=[]),d.parentNode=e.parentNode;for(var i=0,j=e.length;i<j;i++)(f=e[i])&&b.call(f,f.__data__,i)&&d.push(f)}return S(c)},a.map=function(b){var c,d;for(var e=0,f=a.length;e<f;e++){c=a[e];for(var g=0,h=c.length;g<h;g++)if(d=c[g])d.__data__=b.call(d,d.__data__,g)}return a},a.data=function(b,c){function g(a,b){var g=0,h=a.length,i=b.length,j=Math.min(h,i),k=Math.max(h,i),l=[],m=[],n=[],o,p;if(c){var q={},r=[],s,t=b.length;for(g=0;g<h;g++)s=c.call(o=a[g],o.__data__,g),s in q?n[t++]=a[g]:q[s]=o,r.push(s);for(g=0;g<i;g++)o=q[s=c.call(b,p=b[g],g)],o?(o.__data__=p,l[g]=o,m[g]=n[g]=null):(m[g]=V(p),l[g]=n[g]=null),delete q[s];for(g=0;g<h;g++)r[g]in q&&(n[g]=a[g])}else{for(;g<j;g++)o=a[g],p=b[g],o?(o.__data__=p,l[g]=o,m[g]=n[g]=null):(m[g]=V(p),l[g]=n[g]=null);for(;g<i;g++)m[g]=V(b[g]),l[g]=n[g]=null;for(;g<k;g++)n[g]=a[g],m[g]=l[g]=null}m.parentNode=l.parentNode=n.parentNode=a.parentNode,d.push(m),e.push(l),f.push(n)}var d=[],e=[],f=[],h=-1,i=a.length,j;if(typeof b=="function")while(++h<i)g(j=a[h],b.call(j,j.parentNode.__data__,h));else while(++h<i)g(j=a[h],b);var k=S(e);k.enter=function(){return T(d)},k.exit=function(){return S(f)};return k},a.each=function(b){for(var c=0,d=a.length;c<d;c++){var e=a[c];for(var f=0,g=e.length;f<g;f++){var h=e[f];h&&b.call(h,h.__data__,f)}}return a},a.empty=function(){return!d(function(){return!0})},a.node=function(){return d(function(){return this})},a.attr=function(b,c){function j(){var a=c.apply(this,arguments);a==null?this.removeAttributeNS(b.space,b.local):this.setAttributeNS(b.space,b.local,a)}function i(){var a=c.apply(this,arguments);a==null?this.removeAttribute(b):this.setAttribute(b,a)}function h(){this.setAttributeNS(b.space,b.local,c)}function g(){this.setAttribute(b,c)}function f(){this.removeAttributeNS(b.space,b.local)}function e(){this.removeAttribute(b)}b=d3.ns.qualify(b);if(arguments.length<2)return d(b.local?function(){return this.getAttributeNS(b.space,b.local)}:function(){return this.getAttribute(b)});return a.each(c==null?b.local?f:e:typeof c=="function"?b.local?j:i:b.local?h:g)},a.classed=function(b,c){function i(){(c.apply(this,arguments)?f:h).call(this)}function h(){var a=g(this.className.replace(e," "));this.className=a.length?a:null}function f(){var a=this.className;e.lastIndex=0,e.test(a)||(this.className=g(a+" "+b))}var e=new RegExp("(^|\\s+)"+d3.requote(b)+"(\\s+|$)","g");if(arguments.length<2)return d(function(){e.lastIndex=0;return e.test(this.className)});return a.each(typeof c=="function"?i:c?f:h)},a.style=function(b,c,e){function h(){var a=c.apply(this,arguments);a==null?this.style.removeProperty(b):this.style.setProperty(b,a,e)}function g(){this.style.setProperty(b,c,e)}function f(){this.style.removeProperty(b)}arguments.length<3&&(e=null);if(arguments.length<2)return d(function(){return window.getComputedStyle(this,null).getPropertyValue(b)});return a.each(c==null?f:typeof c=="function"?h:g)},a.property=function(b,c){function g(){var a=c.apply(this,arguments);a==null?delete this[b]:this[b]=a}function f(){this[b]=c}function e(){delete this[b]}b=d3.ns.qualify(b);if(arguments.length<2)return d(function(){return this[b]});return a.each(c==null?e:typeof c=="function"?g:f)},a.text=function(b){function f(){var a=b.apply(this,arguments);a!=null&&this.appendChild(document.createTextNode(a))}function e(){this.appendChild(document.createTextNode(b))}function c(){while(this.lastChild)this.removeChild(this.lastChild)}if(arguments.length<1)return d(function(){return this.textContent});a.each(c);return b==null?a:a.each(typeof b=="function"?f:e)},a.html=function(b){function e(){this.innerHTML=b.apply(this,arguments)}function c(){this.innerHTML=b}if(arguments.length<1)return d(function(){return this.innerHTML});return a.each(typeof b=="function"?e:c)},a.append=function(a){function d(b){return b.appendChild(document.createElementNS(a.space,a.local))}function c(b){return b.appendChild(document.createElement(a))}a=d3.ns.qualify(a);return b(a.local?d:c)},a.insert=function(a,c){function e(b){return b.insertBefore(document.createElementNS(a.space,a.local),P(c,b))}function d(b){return b.insertBefore(document.createElement(a),P(c,b))}a=d3.ns.qualify(a);return b(a.local?e:d)},a.remove=function(){return a.each(function(){var a=this.parentNode;a&&a.removeChild(this)})},a.sort=function(b){b=U.apply(this,arguments);for(var c=0,d=a.length;c<d;c++){var e=a[c];e.sort(b);for(var f=1,g=e.length,h=e[0];f<g;f++){var i=e[f];i&&(h&&h.parentNode.insertBefore(i,h.nextSibling),h=i)}}return a},a.on=function(b,c){var d=b.indexOf("."),e=d==-1?b:b.substring(0,d),f="__on"+b;return a.each(function(a,b){function d(d){var e=d3.event;d3.event=d;try{c.call(this,a,b)}finally{d3.event=e}}this[f]&&this.removeEventListener(e,this[f],!1),c&&this.addEventListener(e,this[f]=d,!1)})},a.transition=function(){return Y(a)},a.call=h;return a}function O(a,b,c){function g(a){return Math.round(f(a)*255)}function f(a){a>360?a-=360:a<0&&(a+=360);if(a<60)return d+(e-d)*a/60;if(a<180)return e;if(a<240)return d+(e-d)*(240-a)/60;return d}var d,e;a=a%360,a<0&&(a+=360),b=b<0?0:b>1?1:b,c=c<0?0:c>1?1:c,e=c<=.5?c*(1+b):c+b-c*b,d=2*c-e;return E(g(a+120),g(a),g(a-120))}function N(){return"hsl("+this.h+","+this.s*100+"%,"+this.l*100+"%)"}function M(a,b,c){return{h:a,s:b,l:c,toString:N}}function J(a){var b=parseFloat(a);return a.charAt(a.length-1)=="%"?Math.round(b*2.55):b}function I(a,b,c){var d=Math.min(a/=255,b/=255,c/=255),e=Math.max(a,b,c),f=e-d,g,h,i=(e+d)/2;f?(h=i<.5?f/(e+d):f/(2-e-d),a==e?g=(b-c)/f+(b<c?6:0):b==e?g=(c-a)/f+2:g=(a-b)/f+4,g*=60):h=g=0;return M(g,h,i)}function H(a,b,c){var d=0,e=0,f=0,g,h,i;g=/([a-z]+)\((.*)\)/i.exec(a);if(g){h=g[2].split(",");switch(g[1]){case"hsl":return c(parseFloat(h[0]),parseFloat(h[1])/100,parseFloat(h[2])/100);case"rgb":return b(J(h[0]),J(h[1]),J(h[2]))}}if(i=K[a])return b(i.r,i.g,i.b);a!=null&&a.charAt(0)=="#"&&(a.length==4?(d=a.charAt(1),d+=d,e=a.charAt(2),e+=e,f=a.charAt(3),f+=f):a.length==7&&(d=a.substring(1,3),e=a.substring(3,5),f=a.substring(5,7)),d=parseInt(d,16),e=parseInt(e,16),f=parseInt(f,16));return b(d,e,f)}function G(a){return a<16?"0"+a.toString(16):a.toString(16)}function F(){return"#"+G(this.r)+G(this.g)+G(this.b)}function E(a,b,c){return{r:a,g:b,b:c,toString:F}}function D(a){return a in C||/\bcolor\b/.test(a)?d3.interpolateRgb:d3.interpolate}function z(a){return a<1/2.75?7.5625*a*a:a<2/2.75?7.5625*(a-=1.5/2.75)*a+.75:a<2.5/2.75?7.5625*(a-=2.25/2.75)*a+.9375:7.5625*(a-=2.625/2.75)*a+.984375}function y(a){a||(a=1.70158);return function(b){return b*b*((a+1)*b-a)}}function x(a,b){var c;arguments.length<2&&(b=.45),arguments.length<1?(a=1,c=b/4):c=b/(2*Math.PI)*Math.asin(1/a);return function(d){return 1+a*Math.pow(2,10*-d)*Math.sin((d-c)*2*Math.PI/b)}}function w(a){return 1-Math.sqrt(1-a*a)}function v(a){return a?Math.pow(2,10*(a-1))-.001:0}function u(a){return 1-Math.cos(a*Math.PI/2)}function t(a){return function(b){return Math.pow(b,a)}}function s(a){return a}function r(a){return function(b){return.5*(b<.5?a(2*b):2-a(2-2*b))}}function q(a){return function(b){return 1-a(1-b)}}function l(a){var b=a.lastIndexOf("."),c=b>=0?a.substring(b):(b=a.length,""),d=[];while(b>0)d.push(a.substring(b-=3,b+3));return d.reverse().join(",")+c}function j(a){var b={},c=[];b.add=function(a){for(var d=0;d<c.length;d++)if(c[d].listener==a)return b;c.push({listener:a,on:!0});return b},b.remove=function(a){for(var d=0;d<c.length;d++){var e=c[d];if(e.listener==a){e.on=!1,c=c.slice(0,d).concat(c.slice(d+1));break}}return b},b.dispatch=function(){var a=c;for(var b=0,d=a.length;b<d;b++){var e=a[b];e.on&&e.listener.apply(this,arguments)}};return b}function h(a){a.apply(this,(arguments[0]=this,arguments));return this}function g(a){return a.replace(/(^\s+)|(\s+$)/g,"").replace(/\s+/g," ")}function f(a){return a==null}function e(a){return typeof a=="function"?a:function(){return a}}function c(a){return Array.prototype.slice.call(a)}function b(a){var b=-1,c=a.length,d=[];while(++b<c)d.push(a[b]);return d}d3={version:"1.10.1"},Date.now||(Date.now=function(){return+(new Date)}),Object.create||(Object.create=function(a){function b(){}b.prototype=a;return new b});var a=c;try{a(document.documentElement.childNodes)[0].nodeType}catch(d){a=b}d3.rebind=function(a,b){return function(){var c=b.apply(a,arguments);return arguments.length?a:c}},d3.ascending=function(a,b){return a<b?-1:a>b?1:0},d3.descending=function(a,b){return b<a?-1:b>a?1:0},d3.min=function(a,b){var c=0,d=a.length,e=a[0],f;if(arguments.length==1)while(++c<d)e>(f=a[c])&&(e=f);else{e=b(a[0]);while(++c<d)e>(f=b(a[c]))&&(e=f)}return e},d3.max=function(a,b){var c=0,d=a.length,e=a[0],f;if(arguments.length==1)while(++c<d)e<(f=a[c])&&(e=f);else{e=b(e);while(++c<d)e<(f=b(a[c]))&&(e=f)}return e},d3.nest=function(){function g(a,d){if(d>=b.length)return a;var e=[],f=c[d++],h;for(h in a)e.push({key:h,values:g(a[h],d)});f&&e.sort(function(a,b){return f(a.key,b.key)});return e}function f(c,g){if(g>=b.length)return e?e.call(a,c):d?c.sort(d):c;var h=-1,i=c.length,j=b[g++],k,l,m={};while(++h<i)(k=j(l=c[h]))in m?m[k].push(l):m[k]=[l];for(k in m)m[k]=f(m[k],g);return m}var a={},b=[],c=[],d,e;a.map=function(a){return f(a,0)},a.entries=function(a){return g(f(a,0),0)},a.key=function(c){b.push(c);return a},a.sortKeys=function(d){c[b.length-1]=d;return a},a.sortValues=function(b){d=b;return a},a.rollup=function(b){e=b;return a};return a},d3.keys=function(a){var b=[];for(var c in a)b.push(c);return b},d3.values=function(a){var b=[];for(var c in a)b.push(a[c]);return b},d3.entries=function(a){var b=[];for(var c in a)b.push({key:c,value:a[c]});return b},d3.merge=function(a){return Array.prototype.concat.apply([],a)},d3.split=function(a,b){var c=[],d=[],e,g=-1,h=a.length;arguments.length<2&&(b=f);while(++g<h)b.call(d,e=a[g],g)?d=[]:(d.length||c.push(d),d.push(e));return c},d3.range=function(a,b,c){arguments.length==1&&(b=a,a=0),c==null&&(c=1);if((b-a)/c==Infinity)throw new Error("infinite range");var d=[],e=-1,f;if(c<0)while((f=a+c*++e)>b)d.push(f);else while((f=a+c*++e)<b)d.push(f);return d},d3.requote=function(a){return a.replace(i,"\\$&")};var i=/[\\\^\$\*\+\?\[\]\(\)\.\{\}]/g;d3.xhr=function(a,b,c){var d=new XMLHttpRequest;arguments.length<3?c=b:b&&d.overrideMimeType&&d.overrideMimeType(b),d.open("GET",a,!0),d.onreadystatechange=function(){d.readyState==4&&c(d.status<300?d:null)},d.send(null)},d3.text=function(a,b,c){function d(a){c(a&&a.responseText)}arguments.length<3&&(c=b,b=null),d3.xhr(a,b,d)},d3.json=function(a,b){d3.text(a,"application/json",function(a){b(a?JSON.parse(a):null)})},d3.html=function(a,b){d3.text(a,"text/html",function(a){if(a!=null){var c=document.createRange();c.selectNode(document.body),a=c.createContextualFragment(a)}b(a)})},d3.xml=function(a,b,c){function d(a){c(a&&a.responseXML)}arguments.length<3&&(c=b,b=null),d3.xhr(a,b,d)},d3.ns={prefix:{svg:"http://www.w3.org/2000/svg",xhtml:"http://www.w3.org/1999/xhtml",xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"},qualify:function(a){var b=a.indexOf(":");return b<0?a:{space:d3.ns.prefix[a.substring(0,b)],local:a.substring(b+1)}}},d3.dispatch=function(a){var b={},c;for(var d=0,e=arguments.length;d<e;d++)c=arguments[d],b[c]=j(c);return b},d3.format=function(a){var b=k.exec(a),c=b[1]||" ",d=b[3]||"",e=b[5],f=+b[6],g=b[7],h=b[8],i=b[9];h&&(h=h.substring(1)),e&&(c="0",g&&(f-=Math.floor((f-1)/4))),i=="d"&&(h="0");return function(a){var b=+a,j=b<0&&(b=-b)?"−":d;if(i=="d"&&b%1)return"";h?a=b.toFixed(h):a=""+b;if(e){var k=a.length+j.length;k<f&&(a=Array(f-k+1).join(c)+a),g&&(a=l(a)),a=j+a}else{g&&(a=l(a)),a=j+a;var k=a.length;k<f&&(a=Array(f-k+1).join(c)+a)}return a}};var k=/(?:([^{])?([<>=^]))?([+\- ])?(#)?(0)?([0-9]+)?(,)?(\.[0-9]+)?([a-zA-Z%])?/,m=t(2),n=t(3),o={linear:function(){return s},poly:t,quad:function(){return m},cubic:function(){return n},sin:function(){return u},exp:function(){return v},circle:function(){return w},elastic:x,back:y,bounce:function(){return z}},p={"in":function(a){return a},out:q,"in-out":r,"out-in":function(a){return r(q(a))}};d3.ease=function(a){var b=a.indexOf("-"),c=b>=0?a.substring(0,b):a,d=b>=0?a.substring(b+1):"in";return p[d](o[c].apply(null,Array.prototype.slice.call(arguments,1)))},d3.event=null,d3.interpolate=function(a,b){if(typeof b=="number")return d3.interpolateNumber(+a,b);if(typeof b=="string")return b in K||/^(#|rgb\(|hsl\()/.test(b)?d3.interpolateRgb(String(a),b):d3.interpolateString(String(a),b);if(b instanceof Array)return d3.interpolateArray(a,b);return d3.interpolateObject(a,b)},d3.interpolateNumber=function(a,b){b-=a;return function(c){return a+b*c}},d3.interpolateRound=function(a,b){b-=a;return function(c){return Math.round(a+b*c)}},d3.interpolateString=function(a,b){var c,d,e,f=0,g=0,h=[],i=[],j,k;for(d=0;c=A.exec(b);++d)c.index&&h.push(b.substring(f,g=c.index)),i.push({i:h.length,x:c[0]}),h.push(null),f=A.lastIndex;f<b.length&&h.push(b.substring(f));for(d=0,j=i.length;(c=A.exec(a))&&d<j;++d){k=i[d];if(k.x==c[0]){if(k.i)if(h[k.i+1]==null){h[k.i-1]+=k.x,h.splice(k.i,1);for(e=d+1;e<j;++e)i[e].i--}else{h[k.i-1]+=k.x+h[k.i+1],h.splice(k.i,2);for(e=d+1;e<j;++e)i[e].i-=2}else if(h[k.i+1]==null)h[k.i]=k.x;else{h[k.i]=k.x+h[k.i+1],h.splice(k.i+1,1);for(e=d+1;e<j;++e)i[e].i--}i.splice(d,1),j--,d--}else k.x=d3.interpolateNumber(parseFloat(c[0]),parseFloat(k.x))}while(d<j)k=i.pop(),h[k.i+1]==null?h[k.i]=k.x:(h[k.i]=k.x+h[k.i+1],h.splice(k.i+1,1)),j--;if(h.length==1)return h[0]==null?i[0].x:function(){return b};return function(a){for(d=0;d<j;++d)h[(k=i[d]).i]=k.x(a);return h.join("")}},d3.interpolateRgb=function(a,b){a=d3.rgb(a),b=d3.rgb(b);var c=a.r,d=a.g,e=a.b,f=b.r-c,g=b.g-d,h=b.b-e;return function(a){return"rgb("+Math.round(c+f*a)+","+Math.round(d+g*a)+","+Math.round(e+h*a)+")"}},d3.interpolateHsl=function(a,b){a=d3.hsl(a),b=d3.hsl(b);var c=a.h,d=a.s,e=a.l,f=b.h-c,g=b.s-d,h=b.l-e;return function(a){return O(c+f*a,d+g*a,e+h*a).toString()}},d3.interpolateArray=function(a,b){var c=[],d=[],e=a.length,f=b.length,g=Math.min(a.length,b.length),h;for(h=0;h<g;++h)c.push(d3.interpolate(a[h],b[h]));for(;h<e;++h)d[h]=a[h];for(;h<f;++h)d[h]=b[h];return function(a){for(h=0;h<g;++h)d[h]=c[h](a);return d}},d3.interpolateObject=function(a,b){var c={},d={},e;for(e in a)e in b?c[e]=D(e)(a[e],b[e]):d[e]=a[e];for(e in b)e in a||(d[e]=b[e]);return function(a){for(e in c)d[e]=c[e](a);return d}};var A=/[-+]?(?:\d+\.\d+|\d+\.|\.\d+|\d+)(?:[eE][-]?\d+)?/g,B=/[-+]?\d*\.?\d*(?:[eE][-]?\d+)?(.*)/,C={background:1,fill:1,stroke:1};d3.rgb=function(a,b,c){return arguments.length==1?H(""+a,E,O):E(~~a,~~b,~~c)};var K={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgreen:"#90ee90",lightgrey:"#d3d3d3",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370db",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"};for(var L in K)K[L]=H(K[L],E,O);d3.hsl=function(a,b,c){return arguments.length==1?H(""+a,I,M):M(+a,+b,+c)};var P=function(a,b){return b.querySelector(a)},Q=function(b,c){return a(c.querySelectorAll(b))};typeof Sizzle=="function"&&(P=function(a,b){return Sizzle(a,b)[0]},Q=function(a,b){return Sizzle.uniqueSort(Sizzle(a,b))});var R=S([[document]]);R[0].parentNode=document.documentElement,d3.select=function(a){return typeof a=="string"?R.select(a):S([[a]])},d3.selectAll=function(b){return typeof b=="string"?R.selectAll(b):S([a(b)])},d3.transition=R.transition;var W=0,X=0,$=null,_=0,ba;d3.timer=function(a){bb(a,0)};var bf=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(a){setTimeout(a,17)};d3.scale={},d3.scale.linear=function(){function k(c){var d=Math.min(a,b),e=Math.max(a,b),f=e-d,g=Math.pow(10,Math.floor(Math.log(f/c)/Math.LN10)),h=c/(f/g);h<=.15?g*=10:h<=.35?g*=5:h<=.75&&(g*=2);return{start:Math.ceil(d/g)*g,stop:Math.floor(e/g)*g+g*.5,step:g}}function j(b){b=(b-a)*e;return h(i?Math.max(0,Math.min(1,b)):b)}var a=0,b=1,c=0,d=1,e=1,f=1,g=d3.interpolate,h=g(c,d),i=!1;j.invert=function(b){return(b-c)*f+a},j.clamp=function(a){if(!arguments.length)return i;i=a;return j},j.domain=function(g){if(!arguments.length)return[a,b];a=+g[0],b=+g[1],e=1/(b-a),f=(b-a)/(d-c);return j},j.range=function(e){if(!arguments.length)return[c,d];c=e[0],d=e[1],f=(b-a)/(d-c),h=g(c,d);return j},j.rangeRound=function(a){return j.range(a).interpolate(d3.interpolateRound)},j.interpolate=function(a){if(!arguments.length)return g;h=(g=a)(c,d);return j},j.ticks=function(a){var b=k(a);return d3.range(b.start,b.stop,b.step)},j.tickFormat=function(a){var b=Math.max(0,-Math.floor(Math.log(k(a).step)/Math.LN10+.01));return d3.format(",."+b+"f")};return j},d3.scale.log=function(){function d(c){return a(b(c))}var a=d3.scale.linear(),b=bg,c=b.pow;d.invert=function(b){return c(a.invert(b))},d.domain=function(e){if(!arguments.length)return a.domain().map(c);b=(e[0]||e[1])<0?bh:bg,c=b.pow,a.domain(e.map(b));return d},d.range=d3.rebind(d,a.range),d.rangeRound=d3.rebind(d,a.rangeRound),d.interpolate=d3.rebind(d,a.interpolate),d.clamp=d3.rebind(d,a.clamp),d.ticks=function(){var d=a.domain(),e=[];if(d.every(isFinite)){var f=Math.floor(d[0]),g=Math.ceil(d[1]),h=c(d[0]),i=c(d[1]);if(b===bh){e.push(c(f));for(;f++<g;)for(var j=9;j>0;j--)e.push(c(f)*j)}else{for(;f<g;f++)for(var j=1;j<10;j++)e.push(c(f)*j);e.push(c(f))}for(f=0;e[f]<h;f++);for(g=e.length;e[g-1]>i;g--);e=e.slice(f,g)}return e},d.tickFormat=function(){return function(a){return a.toPrecision(1)}};return d},bg.pow=function(a){return Math.pow(10,a)},bh.pow=function(a){return-Math.pow(10,-a)},d3.scale.pow=function(){function f(b){return a(d(b))}var a=d3.scale.linear(),b=d3.scale.linear(),c=1,d=Number,e=d;f.invert=function(b){return e(a.invert(b))},f.domain=function(g){if(!arguments.length)return a.domain().map(e);var h=(g[0]||g[1])<0?bj:bi;d=h(c),e=h(1/c),a.domain(g.map(d)),b.domain(g);return f},f.range=d3.rebind(f,a.range),f.rangeRound=d3.rebind(f,a.rangeRound),f.interpolate=d3.rebind(f,a.interpolate),f.clamp=d3.rebind(f,a.clamp),f.ticks=b.ticks,f.tickFormat=b.tickFormat,f.exponent=function(a){if(!arguments.length)return c;var b=f.domain();c=a;return f.domain(b)};return f},d3.scale.sqrt=function(){return d3.scale.pow().exponent(.5)},d3.scale.ordinal=function(){function e(d){var e=d in b?b[d]:b[d]=a.push(d)-1;return c[e%c.length]}var a=[],b={},c=[],d=0;e.domain=function(c){if(!arguments.length)return a;a=c,b={};var d=-1,f=-1,g=a.length;while(++d<g)c=a[d],c in b||(b[c]=++f);return e},e.range=function(a){if(!arguments.length)return c;c=a;return e},e.rangePoints=function(b,f){arguments.length<2&&(f=0);var g=b[0],h=b[1],i=(h-g)/(a.length-1+f);c=a.length==1?[(g+h)/2]:d3.range(g+i*f/2,h+i/2,i),d=0;return e},e.rangeBands=function(b,f){arguments.length<2&&(f=0);var g=b[0],h=b[1],i=(h-g)/(a.length+f);c=d3.range(g+i*f,h,i),d=i*(1-f);return e},e.rangeRoundBands=function(b,f){arguments.length<2&&(f=0);var g=b[0],h=b[1],i=h-g,j=Math.floor(i/(a.length+f)),k=i-(a.length-f)*j;c=d3.range(g+Math.round(k/2),h,j),d=Math.round(j*(1-f));return e},e.rangeBand=function(){return d};return e},d3.scale.category10=function(){return d3.scale.ordinal().range(bk)},d3.scale.category20=function(){return d3.scale.ordinal().range(bl)},d3.scale.category20b=function(){return d3.scale.ordinal().range(bm)},d3.scale.category20c=function(){return d3.scale.ordinal().range(bn)};var bk=["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"],bl=["#1f77b4","#aec7e8","#ff7f0e","#ffbb78","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5","#8c564b","#c49c94","#e377c2","#f7b6d2","#7f7f7f","#c7c7c7","#bcbd22","#dbdb8d","#17becf","#9edae5"],bm=["#393b79","#5254a3","#6b6ecf","#9c9ede","#637939","#8ca252","#b5cf6b","#cedb9c","#8c6d31","#bd9e39","#e7ba52","#e7cb94","#843c39","#ad494a","#d6616b","#e7969c","#7b4173","#a55194","#ce6dbd","#de9ed6"],bn=["#3182bd","#6baed6","#9ecae1","#c6dbef","#e6550d","#fd8d3c","#fdae6b","#fdd0a2","#31a354","#74c476","#a1d99b","#c7e9c0","#756bb1","#9e9ac8","#bcbddc","#dadaeb","#636363","#969696","#bdbdbd","#d9d9d9"];d3.scale.quantile=function(){function f(a){return b[e(a)]}function e(a){if(isNaN(a=+a))return NaN;var b=0,d=c.length-1;while(b<=d){var e=b+d>>1,f=c[e];if(f<a)b=e+1;else if(f>a)d=e-1;else return e}return d<0?0:d}function d(){var d=-1,e=c.length=b.length,f=a.length/e;while(++d<e)c[d]=a[~~(d*f)]}var a=[],b=[],c=[];f.domain=function(b){if(!arguments.length)return a;a=b.filter(function(a){return!isNaN(a)}).sort(d3.ascending),d();return f},f.range=function(a){if(!arguments.length)return b;b=a,d();return f},f.quantiles=function(){return c};return f},d3.scale.quantize=function(){function f(b){return e[Math.max(0,Math.min(d,Math.floor(c*(b-a))))]}var a=0,b=1,c=2,d=1,e=[0,1];f.domain=function(d){if(!arguments.length)return[a,b];a=d[0],b=d[1],c=e.length/(b-a);return f},f.range=function(g){if(!arguments.length)return e;e=g,c=e.length/(b-a),d=e.length-1;return f};return f},d3.svg={},d3.svg.arc=function(){function f(){var e=a.apply(this,arguments),f=b.apply(this,arguments),g=c.apply(this,arguments)+bo,h=d.apply(this,arguments)+bo,i=h-g,j=i<Math.PI?"0":"1",k=Math.cos(g),l=Math.sin(g),m=Math.cos(h),n=Math.sin(h);return i>=bp?e?"M0,"+f+"A"+f+","+f+" 0 1,1 0,"+ -f+"A"+f+","+f+" 0 1,1 0,"+f+"M0,"+e+"A"+e+","+e+" 0 1,1 0,"+ -e+"A"+e+","+e+" 0 1,1 0,"+e+"Z":"M0,"+f+"A"+f+","+f+" 0 1,1 0,"+ -f+"A"+f+","+f+" 0 1,1 0,"+f+"Z":e?"M"+f*k+","+f*l+"A"+f+","+f+" 0 "+j+",1 "+f*m+","+f*n+"L"+e*m+","+e*n+"A"+e+","+e+" 0 "+j+",0 "+e*k+","+e*l+"Z":"M"+f*k+","+f*l+"A"+f+","+f+" 0 "+j+",1 "+f*m+","+f*n+"L0,0"+"Z"}var a=bq,b=br,c=bs,d=bt;f.innerRadius=function(b){if(!arguments.length)return a;a=e(b);return f},f.outerRadius=function(a){if(!arguments.length)return b;b=e(a);return f},f.startAngle=function(a){if(!arguments.length)return c;c=e(a);return f},f.endAngle=function(a){if(!arguments.length)return d;d=e(a);return f},f.centroid=function(){var e=(a.apply(this,arguments)+b.apply(this,arguments))/2,f=(c.apply(this,arguments)+d.apply(this,arguments))/2+bo;return[Math.cos(f)*e,Math.sin(f)*e]};return f};var bo=-Math.PI/2,bp=2*Math.PI-1e-6;d3.svg.line=function(){function f(c){return c.length<1?null:"M"+d(bu(this,c,a,b),e)}var a=bv,b=bw,c="linear",d=bx[c],e=.7;f.x=function(b){if(!arguments.length)return a;a=b;return f},f.y=function(a){if(!arguments.length)return b;b=a;return f},f.interpolate=function(a){if(!arguments.length)return c;d=bx[c=a];return f},f.tension=function(a){if(!arguments.length)return e;e=a;return f};return f};var bx={linear:by,"step-before":bz,"step-after":bA,basis:bF,"basis-closed":bG,cardinal:bC,"cardinal-closed":bB},bI=[0,2/3,1/3,0] <add>,bJ=[0,1/3,2/3,0],bK=[0,1/6,2/3,1/6];d3.svg.area=function(){function g(d){return d.length<1?null:"M"+e(bu(this,d,a,c),f)+"L"+e(bu(this,d,a,b).reverse(),f)+"Z"}var a=bv,b=bM,c=bw,d="linear",e=bx[d],f=.7;g.x=function(b){if(!arguments.length)return a;a=b;return g},g.y0=function(a){if(!arguments.length)return b;b=a;return g},g.y1=function(a){if(!arguments.length)return c;c=a;return g},g.interpolate=function(a){if(!arguments.length)return d;e=bx[d=a];return g},g.tension=function(a){if(!arguments.length)return f;f=a;return g};return g},d3.svg.chord=function(){function k(a,b,c,d){return"Q 0,0 "+d}function j(a,b){return"A"+a+","+a+" 0 0,1 "+b}function i(a,b){return a.a0==b.a0&&a.a1==b.a1}function h(a,b,e,g){var h=b.call(a,e,g),i=c.call(a,h,g),j=d.call(a,h,g)+bo,k=f.call(a,h,g)+bo;return{r:i,a0:j,a1:k,p0:[i*Math.cos(j),i*Math.sin(j)],p1:[i*Math.cos(k),i*Math.sin(k)]}}function g(c,d){var e=h(this,a,c,d),f=h(this,b,c,d);return"M"+e.p0+j(e.r,e.p1)+(i(e,f)?k(e.r,e.p1,e.r,e.p0):k(e.r,e.p1,f.r,f.p0)+j(f.r,f.p1)+k(f.r,f.p1,e.r,e.p0))+"Z"}var a=bN,b=bO,c=bP,d=bs,f=bt;g.radius=function(a){if(!arguments.length)return c;c=e(a);return g},g.source=function(b){if(!arguments.length)return a;a=e(b);return g},g.target=function(a){if(!arguments.length)return b;b=e(a);return g},g.startAngle=function(a){if(!arguments.length)return d;d=e(a);return g},g.endAngle=function(a){if(!arguments.length)return f;f=e(a);return g};return g},d3.svg.mouse=function(a){var b=(a.ownerSVGElement||a).createSVGPoint();if(bS<0&&(window.scrollX||window.scrollY)){var c=d3.select(document.body).append("svg:svg").style("position","absolute").style("top",0).style("left",0),d=c[0][0].getScreenCTM();bS=!d.f&&!d.e,c.remove()}bS?(b.x=d3.event.pageX,b.y=d3.event.pageY):(b.x=d3.event.clientX,b.y=d3.event.clientY),b=b.matrixTransform(a.getScreenCTM().inverse());return[b.x,b.y]};var bS=/WebKit/.test(navigator.userAgent)?-1:0;d3.svg.symbol=function(){function c(c,d){return(bV[a.call(this,c,d)]||bV.circle)(b.call(this,c,d))}var a=bU,b=bT;c.type=function(b){if(!arguments.length)return a;a=e(b);return c},c.size=function(a){if(!arguments.length)return b;b=e(a);return c};return c},d3.svg.symbolTypes=["circle","cross","diamond","square","triangle-down","triangle-up"];var bV={circle:function(a){var b=Math.sqrt(a/Math.PI);return"M0,"+b+"A"+b+","+b+" 0 1,1 0,"+ -b+"A"+b+","+b+" 0 1,1 0,"+b+"Z"},cross:function(a){var b=Math.sqrt(a/5)/2;return"M"+ -3*b+","+ -b+"H"+ -b+"V"+ -3*b+"H"+b+"V"+ -b+"H"+3*b+"V"+b+"H"+b+"V"+3*b+"H"+ -b+"V"+b+"H"+ -3*b+"Z"},diamond:function(a){var b=Math.sqrt(a/(2*bX)),c=b*bX;return"M0,"+ -b+"L"+c+",0"+" 0,"+b+" "+ -c+",0"+"Z"},square:function(a){var b=Math.sqrt(a)/2;return"M"+ -b+","+ -b+"L"+b+","+ -b+" "+b+","+b+" "+ -b+","+b+"Z"},"triangle-down":function(a){var b=Math.sqrt(a/bW),c=b*bW/2;return"M0,"+c+"L"+b+","+ -c+" "+ -b+","+ -c+"Z"},"triangle-up":function(a){var b=Math.sqrt(a/bW),c=b*bW/2;return"M0,"+ -c+"L"+b+","+c+" "+ -b+","+c+"Z"}},bW=Math.sqrt(3),bX=Math.tan(30*Math.PI/180)})() <ide>\ No newline at end of file
1
Text
Text
fix markdown conversion with marked
47ce8ecacb8223a4350a2b59e6e0d31597e5796c
<ide><path>docs/docs/tutorial.ja-JP.md <ide> Markdown はインラインでテキストをフォーマットする簡単な <ide> <ide> ```javascript{2,10} <ide> // tutorial6.js <del>var converter = new Showdown.converter(); <ide> var Comment = React.createClass({ <ide> render: function() { <ide> return ( <ide> <div className="comment"> <ide> <h2 className="commentAuthor"> <ide> {this.props.author} <ide> </h2> <del> {converter.makeHtml(this.props.children.toString())} <add> {marked(this.props.children.toString())} <ide> </div> <ide> ); <ide> } <ide> var Comment = React.createClass({ <ide> <ide> ```javascript{5,11} <ide> // tutorial7.js <del>var converter = new Showdown.converter(); <ide> var Comment = React.createClass({ <ide> render: function() { <del> var rawMarkup = converter.makeHtml(this.props.children.toString()); <add> var rawMarkup = marked(this.props.children.toString(), {sanitize: true}); <ide> return ( <ide> <div className="comment"> <ide> <h2 className="commentAuthor">
1
Python
Python
use print() function on both python 2 and 3
b507783bc116d6703f374d1d096b057df51191be
<ide><path>tools/genv8constants.py <ide> # ustack helper. <ide> # <ide> <add>from __future__ import print_function <ide> import re <ide> import subprocess <ide> import sys <ide> import errno <ide> <ide> if len(sys.argv) != 3: <del> print "usage: objsym.py outfile libv8_base.a" <add> print("usage: objsym.py outfile libv8_base.a") <ide> sys.exit(2); <ide> <ide> outfile = file(sys.argv[1], 'w'); <ide> bufsize=-1, stdout=subprocess.PIPE).stdout; <ide> except OSError, e: <ide> if e.errno == errno.ENOENT: <del> print ''' <add> print(''' <ide> Node.js compile error: could not find objdump <ide> <ide> Check that GNU binutils are installed and included in PATH <del> ''' <add> ''') <ide> else: <del> print 'problem running objdump: ', e.strerror <add> print('problem running objdump: ', e.strerror) <ide> <ide> sys.exit() <ide> <ide><path>tools/gyp_node.py <ide> #!/usr/bin/env python <add>from __future__ import print_function <ide> import os <ide> import sys <ide> <ide> def run_gyp(args): <ide> <ide> rc = gyp.main(args) <ide> if rc != 0: <del> print 'Error running GYP' <add> print('Error running GYP') <ide> sys.exit(rc) <ide> <ide> <ide><path>tools/icu/icutrim.py <ide> # Usage: <ide> # Use "-h" to get help options. <ide> <add>from __future__ import print_function <ide> import sys <ide> import shutil <ide> # for utf-8 <ide> <ide> for opt in [ "datfile", "filterfile", "tmpdir", "outfile" ]: <ide> if optVars[opt] is None: <del> print "Missing required option: %s" % opt <add> print("Missing required option: %s" % opt) <ide> sys.exit(1) <ide> <ide> if options.verbose>0: <del> print "Options: "+str(options) <add> print("Options: "+str(options)) <ide> <ide> if (os.path.isdir(options.tmpdir) and options.deltmpdir): <ide> if options.verbose>1: <del> print "Deleting tmp dir %s.." % (options.tmpdir) <add> print("Deleting tmp dir %s.." % (options.tmpdir)) <ide> shutil.rmtree(options.tmpdir) <ide> <ide> if not (os.path.isdir(options.tmpdir)): <ide> os.mkdir(options.tmpdir) <ide> else: <del> print "Please delete tmpdir %s before beginning." % options.tmpdir <add> print("Please delete tmpdir %s before beginning." % options.tmpdir) <ide> sys.exit(1) <ide> <ide> if options.endian not in ("big","little","host"): <del> print "Unknown endianness: %s" % options.endian <add> print("Unknown endianness: %s" % options.endian) <ide> sys.exit(1) <ide> <ide> if options.endian is "host": <ide> options.endian = endian <ide> <ide> if not os.path.isdir(options.tmpdir): <del> print "Error, tmpdir not a directory: %s" % (options.tmpdir) <add> print("Error, tmpdir not a directory: %s" % (options.tmpdir)) <ide> sys.exit(1) <ide> <ide> if not os.path.isfile(options.filterfile): <del> print "Filterfile doesn't exist: %s" % (options.filterfile) <add> print("Filterfile doesn't exist: %s" % (options.filterfile)) <ide> sys.exit(1) <ide> <ide> if not os.path.isfile(options.datfile): <del> print "Datfile doesn't exist: %s" % (options.datfile) <add> print("Datfile doesn't exist: %s" % (options.datfile)) <ide> sys.exit(1) <ide> <ide> if not options.datfile.endswith(".dat"): <del> print "Datfile doesn't end with .dat: %s" % (options.datfile) <add> print("Datfile doesn't end with .dat: %s" % (options.datfile)) <ide> sys.exit(1) <ide> <ide> outfile = os.path.join(options.tmpdir, options.outfile) <ide> <ide> if os.path.isfile(outfile): <del> print "Error, output file does exist: %s" % (outfile) <add> print("Error, output file does exist: %s" % (outfile)) <ide> sys.exit(1) <ide> <ide> if not options.outfile.endswith(".dat"): <del> print "Outfile doesn't end with .dat: %s" % (options.outfile) <add> print("Outfile doesn't end with .dat: %s" % (options.outfile)) <ide> sys.exit(1) <ide> <ide> dataname=options.outfile[0:-4] <ide> def runcmd(tool, cmd, doContinue=False): <ide> cmd = tool + " " + cmd <ide> <ide> if(options.verbose>4): <del> print "# " + cmd <add> print("# " + cmd) <ide> <ide> rc = os.system(cmd) <ide> if rc is not 0 and not doContinue: <del> print "FAILED: %s" % cmd <add> print("FAILED: %s" % cmd) <ide> sys.exit(1) <ide> return rc <ide> <ide> def runcmd(tool, cmd, doContinue=False): <ide> config["variables"]["locales"]["only"] = options.locales.split(',') <ide> <ide> if (options.verbose > 6): <del> print config <add> print(config) <ide> <ide> if(config.has_key("comment")): <del> print "%s: %s" % (options.filterfile, config["comment"]) <add> print("%s: %s" % (options.filterfile, config["comment"])) <ide> <ide> ## STEP 1 - copy the data file, swapping endianness <ide> ## The first letter of endian_letter will be 'b' or 'l' for big or little <ide> def runcmd(tool, cmd, doContinue=False): <ide> itemset = set(items) <ide> <ide> if (options.verbose>1): <del> print "input file: %d items" % (len(items)) <add> print("input file: %d items" % (len(items))) <ide> <ide> # list of all trees <ide> trees = {} <ide> def queueForRemoval(tree): <ide> return <ide> mytree = trees[tree] <ide> if(options.verbose>0): <del> print "* %s: %d items" % (tree, len(mytree["locs"])) <add> print("* %s: %d items" % (tree, len(mytree["locs"]))) <ide> # do varible substitution for this tree here <ide> if type(config["trees"][tree]) == str or type(config["trees"][tree]) == unicode: <ide> treeStr = config["trees"][tree] <ide> if(options.verbose>5): <del> print " Substituting $%s for tree %s" % (treeStr, tree) <add> print(" Substituting $%s for tree %s" % (treeStr, tree)) <ide> if(not config.has_key("variables") or not config["variables"].has_key(treeStr)): <del> print " ERROR: no variable: variables.%s for tree %s" % (treeStr, tree) <add> print(" ERROR: no variable: variables.%s for tree %s" % (treeStr, tree)) <ide> sys.exit(1) <ide> config["trees"][tree] = config["variables"][treeStr] <ide> myconfig = config["trees"][tree] <ide> if(options.verbose>4): <del> print " Config: %s" % (myconfig) <add> print(" Config: %s" % (myconfig)) <ide> # Process this tree <ide> if(len(myconfig)==0 or len(mytree["locs"])==0): <ide> if(options.verbose>2): <del> print " No processing for %s - skipping" % (tree) <add> print(" No processing for %s - skipping" % (tree)) <ide> else: <ide> only = None <ide> if myconfig.has_key("only"): <ide> def queueForRemoval(tree): <ide> thePool = "%spool.res" % (mytree["treeprefix"]) <ide> if (thePool in itemset): <ide> if(options.verbose>0): <del> print "Removing %s because tree %s is empty." % (thePool, tree) <add> print("Removing %s because tree %s is empty." % (thePool, tree)) <ide> remove.add(thePool) <ide> else: <del> print "tree %s - no ONLY" <add> print("tree %s - no ONLY") <ide> for l in range(len(mytree["locs"])): <ide> loc = mytree["locs"][l] <ide> if (only is not None) and not loc in only: <ide> # REMOVE loc <ide> toRemove = "%s%s%s" % (mytree["treeprefix"], loc, mytree["extension"]) <ide> if(options.verbose>6): <del> print "Queueing for removal: %s" % toRemove <add> print("Queueing for removal: %s" % toRemove) <ide> remove.add(toRemove) <ide> <ide> def addTreeByType(tree, mytree): <ide> if(options.verbose>1): <del> print "(considering %s): %s" % (tree, mytree) <add> print("(considering %s): %s" % (tree, mytree)) <ide> trees[tree] = mytree <ide> mytree["locs"]=[] <ide> for i in range(len(items)): <ide> def addTreeByType(tree, mytree): <ide> else: <ide> tree = treeprefix[0:-1] <ide> if(options.verbose>6): <del> print "procesing %s" % (tree) <add> print("procesing %s" % (tree)) <ide> trees[tree] = { "extension": ".res", "treeprefix": treeprefix, "hasIndex": True } <ide> # read in the resource list for the tree <ide> treelistfile = os.path.join(options.tmpdir,"%s.lst" % tree) <ide> def addTreeByType(tree, mytree): <ide> trees[tree]["locs"] = [treeitems[i].strip() for i in range(len(treeitems))] <ide> fi.close() <ide> if(not config.has_key("trees") or not config["trees"].has_key(tree)): <del> print " Warning: filter file %s does not mention trees.%s - will be kept as-is" % (options.filterfile, tree) <add> print(" Warning: filter file %s does not mention trees.%s - will be kept as-is" % (options.filterfile, tree)) <ide> else: <ide> queueForRemoval(tree) <ide> <ide> def removeList(count=0): <ide> global remove <ide> remove = remove - keep <ide> if(count > 10): <del> print "Giving up - %dth attempt at removal." % count <add> print("Giving up - %dth attempt at removal." % count) <ide> sys.exit(1) <ide> if(options.verbose>1): <del> print "%d items to remove - try #%d" % (len(remove),count) <add> print("%d items to remove - try #%d" % (len(remove),count)) <ide> if(len(remove)>0): <ide> oldcount = len(remove) <ide> hackerrfile=os.path.join(options.tmpdir, "REMOVE.err") <ide> removefile = os.path.join(options.tmpdir, "REMOVE.lst") <ide> fi = open(removefile, 'wb') <ide> for i in remove: <del> print >>fi, i <add> print(i, file=fi) <ide> fi.close() <ide> rc = runcmd("icupkg","-r %s %s 2> %s" % (removefile,outfile,hackerrfile),True) <ide> if rc is not 0: <ide> if(options.verbose>5): <del> print "## Damage control, trying to parse stderr from icupkg.." <add> print("## Damage control, trying to parse stderr from icupkg..") <ide> fi = open(hackerrfile, 'rb') <ide> erritems = fi.readlines() <ide> fi.close() <ide> def removeList(count=0): <ide> if m: <ide> toDelete = m.group(1) <ide> if(options.verbose > 5): <del> print "<< %s added to delete" % toDelete <add> print("<< %s added to delete" % toDelete) <ide> remove.add(toDelete) <ide> else: <del> print "ERROR: could not match errline: %s" % line <add> print("ERROR: could not match errline: %s" % line) <ide> sys.exit(1) <ide> if(options.verbose > 5): <del> print " now %d items to remove" % len(remove) <add> print(" now %d items to remove" % len(remove)) <ide> if(oldcount == len(remove)): <del> print " ERROR: could not add any mor eitems to remove. Fail." <add> print(" ERROR: could not add any mor eitems to remove. Fail.") <ide> sys.exit(1) <ide> removeList(count+1) <ide> <ide><path>tools/icu/shrink-icu-src.py <ide> #!/usr/bin/env python <add>from __future__ import print_function <ide> import optparse <ide> import os <ide> import re <ide> (options, args) = parser.parse_args() <ide> <ide> if os.path.isdir(options.icusmall): <del> print 'Deleting existing icusmall %s' % (options.icusmall) <add> print('Deleting existing icusmall %s' % (options.icusmall)) <ide> shutil.rmtree(options.icusmall) <ide> <ide> if not os.path.isdir(options.icusrc): <del> print 'Missing source ICU dir --icusrc=%s' % (options.icusrc) <add> print('Missing source ICU dir --icusrc=%s' % (options.icusrc)) <ide> sys.exit(1) <ide> <ide> <ide> def icu_ignore(dir, files): <ide> def icu_info(icu_full_path): <ide> uvernum_h = os.path.join(icu_full_path, 'source/common/unicode/uvernum.h') <ide> if not os.path.isfile(uvernum_h): <del> print ' Error: could not load %s - is ICU installed?' % uvernum_h <add> print(' Error: could not load %s - is ICU installed?' % uvernum_h) <ide> sys.exit(1) <ide> icu_ver_major = None <ide> matchVerExp = r'^\s*#define\s+U_ICU_VERSION_SHORT\s+"([^"]*)".*' <ide> def icu_info(icu_full_path): <ide> if m: <ide> icu_ver_major = m.group(1) <ide> if not icu_ver_major: <del> print ' Could not read U_ICU_VERSION_SHORT version from %s' % uvernum_h <add> print(' Could not read U_ICU_VERSION_SHORT version from %s' % uvernum_h) <ide> sys.exit(1) <ide> icu_endianness = sys.byteorder[0]; # TODO(srl295): EBCDIC should be 'e' <ide> return (icu_ver_major, icu_endianness) <ide> <ide> (icu_ver_major, icu_endianness) = icu_info(options.icusrc) <del>print "icudt%s%s" % (icu_ver_major, icu_endianness) <add>print("icudt%s%s" % (icu_ver_major, icu_endianness)) <ide> <ide> src_datafile = os.path.join(options.icutmp, "icusmdt%s.dat" % (icu_ver_major)) <ide> dst_datafile = os.path.join(options.icusmall, "source","data","in", "icudt%s%s.dat" % (icu_ver_major, icu_endianness)) <ide> <ide> if not os.path.isfile(src_datafile): <del> print "Could not find source datafile %s - did you build small-icu node?" % src_datafile <add> print("Could not find source datafile %s - did you build small-icu node?" % src_datafile) <ide> sys.exit(1) <ide> else: <del> print "will use small datafile %s" % (src_datafile) <del>print '%s --> %s' % (options.icusrc, options.icusmall) <add> print("will use small datafile %s" % (src_datafile)) <add>print('%s --> %s' % (options.icusrc, options.icusmall)) <ide> shutil.copytree(options.icusrc, options.icusmall, ignore=icu_ignore) <del>print '%s --> %s' % (src_datafile, dst_datafile) <add>print('%s --> %s' % (src_datafile, dst_datafile)) <ide> <ide> # now, make the data dir (since we ignored it) <ide> os.mkdir(os.path.join(os.path.join(options.icusmall, "source", "data"))) <ide> def icu_info(icu_full_path): <ide> readme_name = os.path.join(options.icusmall, "README-SMALL-ICU.txt" ) <ide> <ide> fi = open(readme_name, 'wb') <del>print >>fi, "Small ICU sources - auto generated by shrink-icu-src.py" <del>print >>fi, "" <del>print >>fi, "This directory contains the ICU subset used by --with-intl=small-icu (the default)" <del>print >>fi, "It is a strict subset of ICU %s source files with the following exception(s):" % (icu_ver_major) <del>print >>fi, "* %s : Reduced-size data file" % (dst_datafile) <del>print >>fi, "" <del>print >>fi, "" <del>print >>fi, "To rebuild this directory, see ../../tools/icu/README.md" <del>print >>fi, "" <add>print("Small ICU sources - auto generated by shrink-icu-src.py", file=fi) <add>print("", file=fi) <add>print("This directory contains the ICU subset used by --with-intl=small-icu (the default)", file=fi) <add>print("It is a strict subset of ICU %s source files with the following exception(s):" % (icu_ver_major), file=fi) <add>print("* %s : Reduced-size data file" % (dst_datafile), file=fi) <add>print("", file=fi) <add>print("", file=fi) <add>print("To rebuild this directory, see ../../tools/icu/README.md", file=fi) <add>print("", file=fi) <ide> fi.close() <ide><path>tools/run-valgrind.py <ide> # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE <ide> # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. <ide> <add>from __future__ import print_function <ide> from os import path <ide> import subprocess <ide> import sys <ide> ] <ide> <ide> if len(sys.argv) < 2: <del> print 'Please provide an executable to analyze.' <add> print('Please provide an executable to analyze.') <ide> sys.exit(1) <ide> <ide> executable = path.join(NODE_ROOT, sys.argv[1]) <ide> if not path.exists(executable): <del> print 'Cannot find the file specified: %s' % executable <add> print('Cannot find the file specified: %s' % executable) <ide> sys.exit(1) <ide> <ide> # Compute the command line. <ide><path>tools/specialize_node_d.py <ide> # Specialize node.d for given flavor (`freebsd`) and arch (`x64` or `ia32`) <ide> # <ide> <add>from __future__ import print_function <ide> import re <ide> import sys <ide> <ide> if len(sys.argv) != 5: <del> print "usage: specialize_node_d.py outfile src/node.d flavor arch" <add> print("usage: specialize_node_d.py outfile src/node.d flavor arch") <ide> sys.exit(2); <ide> <ide> outfile = file(sys.argv[1], 'w'); <ide><path>tools/test.py <ide> # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. <ide> <ide> <add>from __future__ import print_function <ide> import imp <ide> import logging <ide> import optparse <ide> def PrintFailureHeader(self, test): <ide> negative_marker = '[negative] ' <ide> else: <ide> negative_marker = '' <del> print "=== %(label)s %(negative)s===" % { <add> print("=== %(label)s %(negative)s===" % { <ide> 'label': test.GetLabel(), <ide> 'negative': negative_marker <del> } <del> print "Path: %s" % "/".join(test.path) <add> }) <add> print("Path: %s" % "/".join(test.path)) <ide> <ide> def Run(self, tasks): <ide> self.Starting() <ide> def EscapeCommand(command): <ide> class SimpleProgressIndicator(ProgressIndicator): <ide> <ide> def Starting(self): <del> print 'Running %i tests' % len(self.cases) <add> print('Running %i tests' % len(self.cases)) <ide> <ide> def Done(self): <del> print <add> print() <ide> for failed in self.failed: <ide> self.PrintFailureHeader(failed.test) <ide> if failed.output.stderr: <del> print "--- stderr ---" <del> print failed.output.stderr.strip() <add> print("--- stderr ---") <add> print(failed.output.stderr.strip()) <ide> if failed.output.stdout: <del> print "--- stdout ---" <del> print failed.output.stdout.strip() <del> print "Command: %s" % EscapeCommand(failed.command) <add> print("--- stdout ---") <add> print(failed.output.stdout.strip()) <add> print("Command: %s" % EscapeCommand(failed.command)) <ide> if failed.HasCrashed(): <del> print "--- %s ---" % PrintCrashed(failed.output.exit_code) <add> print("--- %s ---" % PrintCrashed(failed.output.exit_code)) <ide> if failed.HasTimedOut(): <del> print "--- TIMEOUT ---" <add> print("--- TIMEOUT ---") <ide> if len(self.failed) == 0: <del> print "===" <del> print "=== All tests succeeded" <del> print "===" <add> print("===") <add> print("=== All tests succeeded") <add> print("===") <ide> else: <del> print <del> print "===" <del> print "=== %i tests failed" % len(self.failed) <add> print() <add> print("===") <add> print("=== %i tests failed" % len(self.failed)) <ide> if self.crashed > 0: <del> print "=== %i tests CRASHED" % self.crashed <del> print "===" <add> print("=== %i tests CRASHED" % self.crashed) <add> print("===") <ide> <ide> <ide> class VerboseProgressIndicator(SimpleProgressIndicator): <ide> <ide> def AboutToRun(self, case): <del> print 'Starting %s...' % case.GetLabel() <add> print('Starting %s...' % case.GetLabel()) <ide> sys.stdout.flush() <ide> <ide> def HasRun(self, output): <ide> def HasRun(self, output): <ide> outcome = 'FAIL' <ide> else: <ide> outcome = 'pass' <del> print 'Done running %s: %s' % (output.test.GetLabel(), outcome) <add> print('Done running %s: %s' % (output.test.GetLabel(), outcome)) <ide> <ide> <ide> class DotsProgressIndicator(SimpleProgressIndicator): <ide> def HasRun(self, output): <ide> ("because:" in line or "reason:" in line): <ide> if not printed_file: <ide> printed_file = True <del> print '==== %s ====' % command <add> print('==== %s ====' % command) <ide> self.failed.append(output) <del> print ' %s' % line <add> print(' %s' % line) <ide> <ide> def Done(self): <ide> pass <ide> def HasRun(self, output): <ide> self.PrintFailureHeader(output.test) <ide> stdout = output.output.stdout.strip() <ide> if len(stdout): <del> print self.templates['stdout'] % stdout <add> print(self.templates['stdout'] % stdout) <ide> stderr = output.output.stderr.strip() <ide> if len(stderr): <del> print self.templates['stderr'] % stderr <del> print "Command: %s" % EscapeCommand(output.command) <add> print(self.templates['stderr'] % stderr) <add> print("Command: %s" % EscapeCommand(output.command)) <ide> if output.HasCrashed(): <del> print "--- %s ---" % PrintCrashed(output.output.exit_code) <add> print("--- %s ---" % PrintCrashed(output.output.exit_code)) <ide> if output.HasTimedOut(): <del> print "--- TIMEOUT ---" <add> print("--- TIMEOUT ---") <ide> <ide> def Truncate(self, str, length): <ide> if length and (len(str) > (length - 3)): <ide> def PrintProgress(self, name): <ide> } <ide> status = self.Truncate(status, 78) <ide> self.last_status_length = len(status) <del> print status, <add> print(status, end=' ') <ide> sys.stdout.flush() <ide> <ide> <ide> def __init__(self, cases, flaky_tests_mode): <ide> super(ColorProgressIndicator, self).__init__(cases, flaky_tests_mode, templates) <ide> <ide> def ClearLine(self, last_line_length): <del> print "\033[1K\r", <add> print("\033[1K\r", end=' ') <ide> <ide> <ide> class MonochromeProgressIndicator(CompactProgressIndicator): <ide> def __init__(self, cases, flaky_tests_mode): <ide> super(MonochromeProgressIndicator, self).__init__(cases, flaky_tests_mode, templates) <ide> <ide> def ClearLine(self, last_line_length): <del> print ("\r" + (" " * last_line_length) + "\r"), <add> print(("\r" + (" " * last_line_length) + "\r"), end=' ') <ide> <ide> <ide> PROGRESS_INDICATORS = { <ide> def KillTimedOutProcess(context, pid): <ide> <ide> <ide> def RunProcess(context, timeout, args, **rest): <del> if context.verbose: print "#", " ".join(args) <add> if context.verbose: print("#", " ".join(args)) <ide> popen_args = args <ide> prev_error_mode = SEM_INVALID_VALUE; <ide> if utils.IsWindows(): <ide> def ParseCondition(expr): <ide> """Parses a logical expression into an Expression object""" <ide> tokens = Tokenizer(expr).Tokenize() <ide> if not tokens: <del> print "Malformed expression: '%s'" % expr <add> print("Malformed expression: '%s'" % expr) <ide> return None <ide> scan = Scanner(tokens) <ide> ast = ParseLogicalExpression(scan) <ide> if not ast: <del> print "Malformed expression: '%s'" % expr <add> print("Malformed expression: '%s'" % expr) <ide> return None <ide> if scan.HasMore(): <del> print "Malformed expression: '%s'" % expr <add> print("Malformed expression: '%s'" % expr) <ide> return None <ide> return ast <ide> <ide> def ProcessOptions(options): <ide> if options.run == [""]: <ide> options.run = None <ide> elif len(options.run) != 2: <del> print "The run argument must be two comma-separated integers." <add> print("The run argument must be two comma-separated integers.") <ide> return False <ide> else: <ide> try: <ide> options.run = map(int, options.run) <ide> except ValueError: <del> print "Could not parse the integers from the run argument." <add> print("Could not parse the integers from the run argument.") <ide> return False <ide> if options.run[0] < 0 or options.run[1] < 0: <del> print "The run argument cannot have negative integers." <add> print("The run argument cannot have negative integers.") <ide> return False <ide> if options.run[0] >= options.run[1]: <del> print "The test group to run (n) must be smaller than number of groups (m)." <add> print("The test group to run (n) must be smaller than number of groups (m).") <ide> return False <ide> if options.J: <ide> # inherit JOBS from environment if provided. some virtualised systems <ide> # tends to exaggerate the number of available cpus/cores. <ide> cores = os.environ.get('JOBS') <ide> options.j = int(cores) if cores is not None else multiprocessing.cpu_count() <ide> if options.flaky_tests not in [RUN, SKIP, DONTCARE]: <del> print "Unknown flaky-tests mode %s" % options.flaky_tests <add> print("Unknown flaky-tests mode %s" % options.flaky_tests) <ide> return False <ide> return True <ide> <ide> def Main(): <ide> for mode in options.mode: <ide> vm = context.GetVm(arch, mode) <ide> if not exists(vm): <del> print "Can't find shell executable: '%s'" % vm <add> print("Can't find shell executable: '%s'" % vm) <ide> continue <ide> archEngineContext = Execute([vm, "-p", "process.arch"], context) <ide> vmArch = archEngineContext.stdout.rstrip() <ide> if archEngineContext.exit_code is not 0 or vmArch == "undefined": <del> print "Can't determine the arch of: '%s'" % vm <del> print archEngineContext.stderr.rstrip() <add> print("Can't determine the arch of: '%s'" % vm) <add> print(archEngineContext.stderr.rstrip()) <ide> continue <ide> env = { <ide> 'mode': mode, <ide> def Main(): <ide> if key in visited: <ide> continue <ide> visited.add(key) <del> print "--- begin source: %s ---" % test.GetLabel() <add> print("--- begin source: %s ---" % test.GetLabel()) <ide> source = test.GetSource().strip() <del> print source <del> print "--- end source: %s ---" % test.GetLabel() <add> print(source) <add> print("--- end source: %s ---" % test.GetLabel()) <ide> return 0 <ide> <ide> if options.warn_unused: <ide> for rule in globally_unused_rules: <del> print "Rule for '%s' was not used." % '/'.join([str(s) for s in rule.path]) <add> print("Rule for '%s' was not used." % '/'.join([str(s) for s in rule.path])) <ide> <ide> tempdir = os.environ.get('NODE_TEST_DIR') or options.temp_dir <ide> if tempdir: <ide> def Main(): <ide> os.makedirs(tempdir) <ide> except OSError as exception: <ide> if exception.errno != errno.EEXIST: <del> print "Could not create the temporary directory", options.temp_dir <add> print("Could not create the temporary directory", options.temp_dir) <ide> sys.exit(1) <ide> <ide> def should_keep(case): <ide> def should_keep(case): <ide> len(cases_to_run), <ide> options.run[1]) ] <ide> if len(cases_to_run) == 0: <del> print "No tests to run." <add> print("No tests to run.") <ide> return 1 <ide> else: <ide> try: <ide> def should_keep(case): <ide> result = 1 <ide> duration = time.time() - start <ide> except KeyboardInterrupt: <del> print "Interrupted" <add> print("Interrupted") <ide> return 1 <ide> <ide> if options.time: <ide> # Write the times to stderr to make it easy to separate from the <ide> # test output. <del> print <add> print() <ide> sys.stderr.write("--- Total time: %s ---\n" % FormatTime(duration)) <ide> timed_tests = [ t for t in cases_to_run if not t.duration is None ] <ide> timed_tests.sort(lambda a, b: a.CompareTime(b))
7
Go
Go
improve truncindex benchmarks
7eb425ccd167487b8424ff680e46216d99fa237a
<ide><path>pkg/truncindex/truncindex_test.go <ide> package truncindex <ide> <del>import "testing" <add>import ( <add> "math/rand" <add> "testing" <add> <add> "github.com/dotcloud/docker/utils" <add>) <ide> <ide> // Test the behavior of TruncIndex, an index for querying IDs from a non-conflicting prefix. <ide> func TestTruncIndex(t *testing.T) { <ide> func assertIndexGet(t *testing.T, index *TruncIndex, input, expectedResult strin <ide> } <ide> } <ide> <del>func BenchmarkTruncIndexAdd(b *testing.B) { <del> ids := []string{"banana", "bananaa", "bananab"} <add>func BenchmarkTruncIndexAdd100(b *testing.B) { <add> var testSet []string <add> for i := 0; i < 100; i++ { <add> testSet = append(testSet, utils.GenerateRandomID()) <add> } <ide> b.ResetTimer() <ide> for i := 0; i < b.N; i++ { <ide> index := NewTruncIndex([]string{}) <del> for _, id := range ids { <del> index.Add(id) <add> for _, id := range testSet { <add> if err := index.Add(id); err != nil { <add> b.Fatal(err) <add> } <add> } <add> } <add>} <add> <add>func BenchmarkTruncIndexAdd250(b *testing.B) { <add> var testSet []string <add> for i := 0; i < 250; i++ { <add> testSet = append(testSet, utils.GenerateRandomID()) <add> } <add> b.ResetTimer() <add> for i := 0; i < b.N; i++ { <add> index := NewTruncIndex([]string{}) <add> for _, id := range testSet { <add> if err := index.Add(id); err != nil { <add> b.Fatal(err) <add> } <add> } <add> } <add>} <add> <add>func BenchmarkTruncIndexAdd500(b *testing.B) { <add> var testSet []string <add> for i := 0; i < 500; i++ { <add> testSet = append(testSet, utils.GenerateRandomID()) <add> } <add> b.ResetTimer() <add> for i := 0; i < b.N; i++ { <add> index := NewTruncIndex([]string{}) <add> for _, id := range testSet { <add> if err := index.Add(id); err != nil { <add> b.Fatal(err) <add> } <add> } <add> } <add>} <add> <add>func BenchmarkTruncIndexGet100(b *testing.B) { <add> var testSet []string <add> var testKeys []string <add> for i := 0; i < 100; i++ { <add> testSet = append(testSet, utils.GenerateRandomID()) <add> } <add> index := NewTruncIndex([]string{}) <add> for _, id := range testSet { <add> if err := index.Add(id); err != nil { <add> b.Fatal(err) <add> } <add> l := rand.Intn(12) + 12 <add> testKeys = append(testKeys, id[:l]) <add> } <add> b.ResetTimer() <add> for i := 0; i < b.N; i++ { <add> for _, id := range testKeys { <add> if res, err := index.Get(id); err != nil { <add> b.Fatal(res, err) <add> } <add> } <add> } <add>} <add> <add>func BenchmarkTruncIndexGet250(b *testing.B) { <add> var testSet []string <add> var testKeys []string <add> for i := 0; i < 250; i++ { <add> testSet = append(testSet, utils.GenerateRandomID()) <add> } <add> index := NewTruncIndex([]string{}) <add> for _, id := range testSet { <add> if err := index.Add(id); err != nil { <add> b.Fatal(err) <add> } <add> l := rand.Intn(12) + 12 <add> testKeys = append(testKeys, id[:l]) <add> } <add> b.ResetTimer() <add> for i := 0; i < b.N; i++ { <add> for _, id := range testKeys { <add> if res, err := index.Get(id); err != nil { <add> b.Fatal(res, err) <add> } <ide> } <ide> } <ide> } <ide> <del>func BenchmarkTruncIndexNew(b *testing.B) { <del> ids := []string{"banana", "bananaa", "bananab"} <add>func BenchmarkTruncIndexGet500(b *testing.B) { <add> var testSet []string <add> var testKeys []string <add> for i := 0; i < 500; i++ { <add> testSet = append(testSet, utils.GenerateRandomID()) <add> } <add> index := NewTruncIndex([]string{}) <add> for _, id := range testSet { <add> if err := index.Add(id); err != nil { <add> b.Fatal(err) <add> } <add> l := rand.Intn(12) + 12 <add> testKeys = append(testKeys, id[:l]) <add> } <add> b.ResetTimer() <add> for i := 0; i < b.N; i++ { <add> for _, id := range testKeys { <add> if res, err := index.Get(id); err != nil { <add> b.Fatal(res, err) <add> } <add> } <add> } <add>} <add> <add>func BenchmarkTruncIndexNew100(b *testing.B) { <add> var testSet []string <add> for i := 0; i < 100; i++ { <add> testSet = append(testSet, utils.GenerateRandomID()) <add> } <add> b.ResetTimer() <add> for i := 0; i < b.N; i++ { <add> NewTruncIndex(testSet) <add> } <add>} <add> <add>func BenchmarkTruncIndexNew250(b *testing.B) { <add> var testSet []string <add> for i := 0; i < 250; i++ { <add> testSet = append(testSet, utils.GenerateRandomID()) <add> } <add> b.ResetTimer() <add> for i := 0; i < b.N; i++ { <add> NewTruncIndex(testSet) <add> } <add>} <add> <add>func BenchmarkTruncIndexNew500(b *testing.B) { <add> var testSet []string <add> for i := 0; i < 500; i++ { <add> testSet = append(testSet, utils.GenerateRandomID()) <add> } <ide> b.ResetTimer() <ide> for i := 0; i < b.N; i++ { <del> NewTruncIndex(ids) <add> NewTruncIndex(testSet) <ide> } <ide> }
1
Ruby
Ruby
add missing require
07d9adc2959931d540c7cb07e12a3d541a9e68e8
<ide><path>Library/Homebrew/test/test_cleaner.rb <ide> require 'testing_env' <ide> require 'cleaner' <add>require 'formula' <ide> <ide> class CleanerTestBall < Formula <ide> url "file:///#{TEST_FOLDER}/tarballs/testball-0.1.tbz"
1
Python
Python
fix longdouble machar problem (iterations too low)
0c7be2c208f3f173b3d8913e55aeb3b731fcf3f7
<ide><path>numpy/lib/machar.py <ide> def __init__(self, float_conv=float,int_conv=int, <ide> float_to_str - convert array float to str <ide> title - description of used floating point numbers <ide> """ <del> max_iter = range(1000) <add> max_iterN = 10000 <add> msg = "Did not converge after %d tries with %s" <ide> one = float_conv(1) <ide> two = one + one <ide> zero = one - one <ide> <ide> # Do we really need to do this? Aren't they 2 and 2.0? <ide> # Determine ibeta and beta <ide> a = one <del> for _ in max_iter: <add> for _ in xrange(max_iterN): <ide> a = a + a <ide> temp = a + one <ide> temp1 = temp - a <ide> if any(temp1 - one != zero): <ide> break <ide> else: <del> raise RuntimeError <add> raise RuntimeError, msg % (_, one.dtype) <ide> b = one <del> for _ in max_iter: <add> for _ in xrange(max_iterN): <ide> b = b + b <ide> temp = a + b <ide> itemp = int_conv(temp-a) <ide> if any(itemp != 0): <ide> break <ide> else: <del> raise RuntimeError <add> raise RuntimeError, msg % (_, one.dtype) <ide> ibeta = itemp <ide> beta = float_conv(ibeta) <ide> <ide> # Determine it and irnd <ide> it = -1 <ide> b = one <del> for _ in max_iter: <add> for _ in xrange(max_iterN): <ide> it = it + 1 <ide> b = b * beta <ide> temp = b + one <ide> temp1 = temp - b <ide> if any(temp1 - one != zero): <ide> break <ide> else: <del> raise RuntimeError <add> raise RuntimeError, msg % (_, one.dtype) <ide> <ide> betah = beta / two <ide> a = one <del> for _ in max_iter: <add> for _ in xrange(max_iterN): <ide> a = a + a <ide> temp = a + one <ide> temp1 = temp - a <ide> if any(temp1 - one != zero): <ide> break <ide> else: <del> raise RuntimeError <add> raise RuntimeError, msg % (_, one.dtype) <ide> temp = a + betah <ide> irnd = 0 <ide> if any(temp-a != zero): <ide> def __init__(self, float_conv=float,int_conv=int, <ide> for i in range(negep): <ide> a = a * betain <ide> b = a <del> for _ in max_iter: <add> for _ in xrange(max_iterN): <ide> temp = one - a <ide> if any(temp-one != zero): <ide> break <ide> def __init__(self, float_conv=float,int_conv=int, <ide> raise RuntimeError, "could not determine machine tolerance " \ <ide> "for 'negep', locals() -> %s" % (locals()) <ide> else: <del> raise RuntimeError <add> raise RuntimeError, msg % (_, one.dtype) <ide> negep = -negep <ide> epsneg = a <ide> <ide> # Determine machep and eps <ide> machep = - it - 3 <ide> a = b <ide> <del> for _ in max_iter: <add> for _ in xrange(max_iterN): <ide> temp = one + a <ide> if any(temp-one != zero): <ide> break <ide> a = a * beta <ide> machep = machep + 1 <ide> else: <del> raise RuntimeError <add> raise RuntimeError, msg % (_, one.dtype) <ide> eps = a <ide> <ide> # Determine ngrd <ide> def __init__(self, float_conv=float,int_conv=int, <ide> z = betain <ide> t = one + eps <ide> nxres = 0 <del> for _ in max_iter: <add> for _ in xrange(max_iterN): <ide> y = z <ide> z = y*y <ide> a = z*one # Check here for underflow <ide> def __init__(self, float_conv=float,int_conv=int, <ide> i = i + 1 <ide> k = k + k <ide> else: <del> raise RuntimeError <add> raise RuntimeError, msg % (_, one.dtype) <ide> if ibeta != 10: <ide> iexp = i + 1 <ide> mx = k + k <ide> def __init__(self, float_conv=float,int_conv=int, <ide> mx = iz + iz - 1 <ide> <ide> # Determine minexp and xmin <del> for _ in max_iter: <add> for _ in xrange(max_iterN): <ide> xmin = y <ide> y = y * betain <ide> a = y * one <ide> def __init__(self, float_conv=float,int_conv=int, <ide> else: <ide> break <ide> else: <del> raise RuntimeError <add> raise RuntimeError, msg % (_, one.dtype) <ide> minexp = -k <ide> <ide> # Determine maxexp, xmax
1
Python
Python
add conf file for sphinx-quickstart (doc)
5ab3f91fb2d4693edfe494b50efb5d2b4d36c644
<ide><path>docs/conf.py <add># -*- coding: utf-8 -*- <add># <add># Glances documentation build configuration file, created by <add># sphinx-quickstart on Tue Mar 25 19:57:21 2014. <add># <add># This file is execfile()d with the current directory set to its containing dir. <add># <add># Note that not all possible configuration values are present in this <add># autogenerated file. <add># <add># All configuration values have a default; values that are commented out <add># serve to show the default. <add> <add>import sys, os <add> <add># If extensions (or modules to document with autodoc) are in another directory, <add># add these directories to sys.path here. If the directory is relative to the <add># documentation root, use os.path.abspath to make it absolute, like shown here. <add>#sys.path.insert(0, os.path.abspath('.')) <add> <add># -- General configuration ----------------------------------------------------- <add> <add># If your documentation needs a minimal Sphinx version, state it here. <add>#needs_sphinx = '1.0' <add> <add># Add any Sphinx extension module names here, as strings. They can be extensions <add># coming with Sphinx (named 'sphinx.ext.*') or your custom ones. <add>extensions = [] <add> <add># Add any paths that contain templates here, relative to this directory. <add>templates_path = ['_templates'] <add> <add># The suffix of source filenames. <add>source_suffix = '.rst' <add> <add># The encoding of source files. <add>#source_encoding = 'utf-8-sig' <add> <add># The master toctree document. <add>master_doc = 'index' <add> <add># General information about the project. <add>project = u'Glances' <add>copyright = u'2014, Nicolas Hennion' <add> <add># The version info for the project you're documenting, acts as replacement for <add># |version| and |release|, also used in various other places throughout the <add># built documents. <add># <add># The short X.Y version. <add>version = '1.7.5' <add># The full version, including alpha/beta/rc tags. <add>release = '1.7.5' <add> <add># The language for content autogenerated by Sphinx. Refer to documentation <add># for a list of supported languages. <add>#language = None <add> <add># There are two options for replacing |today|: either, you set today to some <add># non-false value, then it is used: <add>#today = '' <add># Else, today_fmt is used as the format for a strftime call. <add>#today_fmt = '%B %d, %Y' <add> <add># List of patterns, relative to source directory, that match files and <add># directories to ignore when looking for source files. <add>exclude_patterns = ['_build'] <add> <add># The reST default role (used for this markup: `text`) to use for all documents. <add>#default_role = None <add> <add># If true, '()' will be appended to :func: etc. cross-reference text. <add>#add_function_parentheses = True <add> <add># If true, the current module name will be prepended to all description <add># unit titles (such as .. function::). <add>#add_module_names = True <add> <add># If true, sectionauthor and moduleauthor directives will be shown in the <add># output. They are ignored by default. <add>#show_authors = False <add> <add># The name of the Pygments (syntax highlighting) style to use. <add>pygments_style = 'sphinx' <add> <add># A list of ignored prefixes for module index sorting. <add>#modindex_common_prefix = [] <add> <add> <add># -- Options for HTML output --------------------------------------------------- <add> <add># The theme to use for HTML and HTML Help pages. See the documentation for <add># a list of builtin themes. <add>html_theme = 'default' <add> <add># Theme options are theme-specific and customize the look and feel of a theme <add># further. For a list of options available for each theme, see the <add># documentation. <add>#html_theme_options = {} <add> <add># Add any paths that contain custom themes here, relative to this directory. <add>#html_theme_path = [] <add> <add># The name for this set of Sphinx documents. If None, it defaults to <add># "<project> v<release> documentation". <add>#html_title = None <add> <add># A shorter title for the navigation bar. Default is the same as html_title. <add>#html_short_title = None <add> <add># The name of an image file (relative to this directory) to place at the top <add># of the sidebar. <add>#html_logo = None <add> <add># The name of an image file (within the static path) to use as favicon of the <add># docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 <add># pixels large. <add>#html_favicon = None <add> <add># Add any paths that contain custom static files (such as style sheets) here, <add># relative to this directory. They are copied after the builtin static files, <add># so a file named "default.css" will overwrite the builtin "default.css". <add>html_static_path = ['_static'] <add> <add># If not '', a 'Last updated on:' timestamp is inserted at every page bottom, <add># using the given strftime format. <add>#html_last_updated_fmt = '%b %d, %Y' <add> <add># If true, SmartyPants will be used to convert quotes and dashes to <add># typographically correct entities. <add>#html_use_smartypants = True <add> <add># Custom sidebar templates, maps document names to template names. <add>#html_sidebars = {} <add> <add># Additional templates that should be rendered to pages, maps page names to <add># template names. <add>#html_additional_pages = {} <add> <add># If false, no module index is generated. <add>#html_domain_indices = True <add> <add># If false, no index is generated. <add>#html_use_index = True <add> <add># If true, the index is split into individual pages for each letter. <add>#html_split_index = False <add> <add># If true, links to the reST sources are added to the pages. <add>#html_show_sourcelink = True <add> <add># If true, "Created using Sphinx" is shown in the HTML footer. Default is True. <add>#html_show_sphinx = True <add> <add># If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. <add>#html_show_copyright = True <add> <add># If true, an OpenSearch description file will be output, and all pages will <add># contain a <link> tag referring to it. The value of this option must be the <add># base URL from which the finished HTML is served. <add>#html_use_opensearch = '' <add> <add># This is the file name suffix for HTML files (e.g. ".xhtml"). <add>#html_file_suffix = None <add> <add># Output file base name for HTML help builder. <add>htmlhelp_basename = 'Glancesdoc' <add> <add> <add># -- Options for LaTeX output -------------------------------------------------- <add> <add>latex_elements = { <add># The paper size ('letterpaper' or 'a4paper'). <add>#'papersize': 'letterpaper', <add> <add># The font size ('10pt', '11pt' or '12pt'). <add>#'pointsize': '10pt', <add> <add># Additional stuff for the LaTeX preamble. <add>#'preamble': '', <add>} <add> <add># Grouping the document tree into LaTeX files. List of tuples <add># (source start file, target name, title, author, documentclass [howto/manual]). <add>latex_documents = [ <add> ('index', 'Glances.tex', u'Glances Documentation', <add> u'Nicolas Hennion', 'manual'), <add>] <add> <add># The name of an image file (relative to this directory) to place at the top of <add># the title page. <add>#latex_logo = None <add> <add># For "manual" documents, if this is true, then toplevel headings are parts, <add># not chapters. <add>#latex_use_parts = False <add> <add># If true, show page references after internal links. <add>#latex_show_pagerefs = False <add> <add># If true, show URL addresses after external links. <add>#latex_show_urls = False <add> <add># Documents to append as an appendix to all manuals. <add>#latex_appendices = [] <add> <add># If false, no module index is generated. <add>#latex_domain_indices = True <add> <add> <add># -- Options for manual page output -------------------------------------------- <add> <add># One entry per manual page. List of tuples <add># (source start file, name, description, authors, manual section). <add>man_pages = [ <add> ('index', 'glances', u'Glances Documentation', <add> [u'Nicolas Hennion'], 1) <add>] <add> <add># If true, show URL addresses after external links. <add>#man_show_urls = False <add> <add> <add># -- Options for Texinfo output ------------------------------------------------ <add> <add># Grouping the document tree into Texinfo files. List of tuples <add># (source start file, target name, title, author, <add># dir menu entry, description, category) <add>texinfo_documents = [ <add> ('index', 'Glances', u'Glances Documentation', <add> u'Nicolas Hennion', 'Glances', 'One line description of project.', <add> 'Miscellaneous'), <add>] <add> <add># Documents to append as an appendix to all manuals. <add>#texinfo_appendices = [] <add> <add># If false, no module index is generated. <add>#texinfo_domain_indices = True <add> <add># How to display URL addresses: 'footnote', 'no', or 'inline'. <add>#texinfo_show_urls = 'footnote'
1
PHP
PHP
fix unique bug
4b785c616169f5f621d1f87e9cbe75445ece7523
<ide><path>src/Illuminate/Bus/UniqueLock.php <add><?php <add> <add>namespace Illuminate\Bus; <add> <add>use Illuminate\Contracts\Cache\Repository as Cache; <add> <add>class UniqueLock <add>{ <add> /** <add> * The cache repository implementation. <add> * <add> * @var \Illuminate\Contracts\Cache\Repository <add> */ <add> protected $cache; <add> <add> /** <add> * Create a new unique lock manager instance. <add> * <add> * @param \Illuminate\Contracts\Cache\Repository $cache <add> * @return void <add> */ <add> public function __construct(Cache $cache) <add> { <add> $this->cache = $cache; <add> } <add> <add> /** <add> * Attempt to acquire a lock for the given job. <add> * <add> * @param mixed $job <add> * @return bool <add> */ <add> public function acquire($job) <add> { <add> $uniqueId = method_exists($job, 'uniqueId') <add> ? $job->uniqueId() <add> : ($job->uniqueId ?? ''); <add> <add> $cache = method_exists($job, 'uniqueVia') <add> ? $job->uniqueVia() <add> : $this->cache; <add> <add> return (bool) $cache->lock( <add> $key = 'laravel_unique_job:'.get_class($job).$uniqueId, <add> $job->uniqueFor ?? 0 <add> )->get(); <add> } <add>} <ide><path>src/Illuminate/Console/Scheduling/Schedule.php <ide> <ide> use Closure; <ide> use DateTimeInterface; <add>use Illuminate\Bus\UniqueLock; <ide> use Illuminate\Console\Application; <ide> use Illuminate\Container\Container; <ide> use Illuminate\Contracts\Bus\Dispatcher; <add>use Illuminate\Contracts\Cache\Repository as Cache; <ide> use Illuminate\Contracts\Container\BindingResolutionException; <add>use Illuminate\Contracts\Queue\ShouldBeUnique; <ide> use Illuminate\Contracts\Queue\ShouldQueue; <ide> use Illuminate\Queue\CallQueuedClosure; <ide> use Illuminate\Support\ProcessUtils; <ide> protected function dispatchToQueue($job, $queue, $connection) <ide> $job = CallQueuedClosure::create($job); <ide> } <ide> <add> if ($job instanceof ShouldBeUnique) { <add> return $this->dispatchUniqueJobToQueue($job, $queue, $connection); <add> } <add> <add> $this->getDispatcher()->dispatch( <add> $job->onConnection($connection)->onQueue($queue) <add> ); <add> } <add> <add> /** <add> * Dispatch the given unique job to the queue. <add> * <add> * @param object $job <add> * @param string|null $queue <add> * @param string|null $connection <add> * @return void <add> * <add> * @throws \RuntimeException <add> */ <add> protected function dispatchUniqueJobToQueue($job, $queue, $connection) <add> { <add> if (! Container::getInstance()->bound(Cache::class)) { <add> throw new RuntimeException('Cache driver not available. Scheduling unique jobs not supported.'); <add> } <add> <add> if (! (new UniqueLock(Container::getInstance()->make(Cache::class)))->acquire($job)) { <add> return; <add> } <add> <ide> $this->getDispatcher()->dispatch( <ide> $job->onConnection($connection)->onQueue($queue) <ide> ); <ide><path>src/Illuminate/Foundation/Bus/PendingDispatch.php <ide> <ide> namespace Illuminate\Foundation\Bus; <ide> <add>use Illuminate\Bus\UniqueLock; <ide> use Illuminate\Container\Container; <ide> use Illuminate\Contracts\Bus\Dispatcher; <ide> use Illuminate\Contracts\Cache\Repository as Cache; <ide> protected function shouldDispatch() <ide> return true; <ide> } <ide> <del> $uniqueId = method_exists($this->job, 'uniqueId') <del> ? $this->job->uniqueId() <del> : ($this->job->uniqueId ?? ''); <del> <del> $cache = method_exists($this->job, 'uniqueVia') <del> ? $this->job->uniqueVia() <del> : Container::getInstance()->make(Cache::class); <del> <del> return (bool) $cache->lock( <del> $key = 'laravel_unique_job:'.get_class($this->job).$uniqueId, <del> $this->job->uniqueFor ?? 0 <del> )->get(); <add> return (new UniqueLock(Container::getInstance()->make(Cache::class))) <add> ->acquire($this->job); <ide> } <ide> <ide> /** <ide><path>tests/Integration/Console/UniqueJobSchedulingTest.php <add><?php <add> <add>namespace Illuminate\Tests\Integration\Console; <add> <add>use Illuminate\Bus\Queueable; <add>use Illuminate\Console\Scheduling\Schedule; <add>use Illuminate\Contracts\Queue\ShouldBeUnique; <add>use Illuminate\Contracts\Queue\ShouldQueue; <add>use Illuminate\Foundation\Bus\Dispatchable; <add>use Illuminate\Queue\InteractsWithQueue; <add>use Illuminate\Support\Facades\Queue; <add>use Orchestra\Testbench\TestCase; <add> <add>class UniqueJobSchedulingTest extends TestCase <add>{ <add> public function testJobsPushedToQueue() <add> { <add> Queue::fake(); <add> $this->dispatch( <add> TestJob::class, <add> TestJob::class, <add> TestJob::class, <add> TestJob::class <add> ); <add> <add> Queue::assertPushed(TestJob::class, 4); <add> } <add> <add> public function testUniqueJobsPushedToQueue() <add> { <add> Queue::fake(); <add> $this->dispatch( <add> UniqueTestJob::class, <add> UniqueTestJob::class, <add> UniqueTestJob::class, <add> UniqueTestJob::class <add> ); <add> <add> Queue::assertPushed(UniqueTestJob::class, 1); <add> } <add> <add> private function dispatch(...$jobs) <add> { <add> /** @var \Illuminate\Console\Scheduling\Schedule $scheduler */ <add> $scheduler = $this->app->make(Schedule::class); <add> foreach ($jobs as $job) { <add> $scheduler->job($job)->name('')->everyMinute(); <add> } <add> $events = $scheduler->events(); <add> foreach ($events as $event) { <add> $event->run($this->app); <add> } <add> } <add>} <add> <add>class TestJob implements ShouldQueue <add>{ <add> use InteractsWithQueue, Queueable, Dispatchable; <add>} <add> <add>class UniqueTestJob extends TestJob implements ShouldBeUnique <add>{ <add>}
4
Ruby
Ruby
replace mocha#stubs with assert_called_with
d89937505867eac91830d34a97d55b08d48573fc
<ide><path>activerecord/test/cases/adapters/mysql2/active_schema_test.rb <ide> def test_remove_timestamps <ide> end <ide> <ide> def test_indexes_in_create <del> ActiveRecord::Base.connection.stubs(:data_source_exists?).with(:temp).returns(false) <add> assert_called_with( <add> ActiveRecord::Base.connection, <add> :data_source_exists?, <add> [:temp], <add> returns: false <add> ) do <add> expected = "CREATE TEMPORARY TABLE `temp` ( INDEX `index_temp_on_zip` (`zip`)) AS SELECT id, name, zip FROM a_really_complicated_query" <add> actual = ActiveRecord::Base.connection.create_table(:temp, temporary: true, as: "SELECT id, name, zip FROM a_really_complicated_query") do |t| <add> t.index :zip <add> end <ide> <del> expected = "CREATE TEMPORARY TABLE `temp` ( INDEX `index_temp_on_zip` (`zip`)) AS SELECT id, name, zip FROM a_really_complicated_query" <del> actual = ActiveRecord::Base.connection.create_table(:temp, temporary: true, as: "SELECT id, name, zip FROM a_really_complicated_query") do |t| <del> t.index :zip <add> assert_equal expected, actual <ide> end <del> <del> assert_equal expected, actual <ide> end <ide> <ide> private
1
Javascript
Javascript
pass conf to export function
a50e440cf1d6381b41471fe6fbcf8f761cd38e21
<ide><path>server/export.js <ide> import { renderToHTML } from './render' <ide> import { getAvailableChunks } from './utils' <ide> import { printAndExit } from '../lib/utils' <ide> <del>export default async function (dir, options) { <add>export default async function (dir, options, configuration) { <ide> dir = resolve(dir) <del> const config = getConfig(dir) <add> const config = configuration || getConfig(dir) <ide> const nextDir = join(dir, config.distDir) <ide> <ide> log(` using build directory: ${nextDir}`)
1
Javascript
Javascript
extract a test updating logic and logging
0a7ac8935e1e936130b73f78d7f7971c42975db9
<ide><path>client/src/templates/Challenges/redux/execute-challenge-saga.js <ide> const testWorker = new WorkerExecutor('test-evaluator'); <ide> const testTimeout = 5000; <ide> <ide> function* ExecuteChallengeSaga() { <del> const { js, bonfire, backend } = challengeTypes; <del> const { challengeType } = yield select(challengeMetaSelector); <del> switch (challengeType) { <del> case js: <del> case bonfire: <del> yield* ExecuteJSChallengeSaga(); <del> break; <del> case backend: <del> // yield* ExecuteBackendChallengeSaga(); <del> break; <del> default: <del> // yield* ExecuteDOMChallengeSaga(); <add> try { <add> const { js, bonfire, backend } = challengeTypes; <add> const { challengeType } = yield select(challengeMetaSelector); <add> <add> // TODO: ExecuteBackendChallengeSaga and ExecuteDOMChallengeSaga <add> if (challengeType !== js && challengeType !== bonfire) { <add> return; <add> } <add> <add> yield put(initLogs()); <add> yield put(initConsole('// running tests')); <add> <add> const tests = yield select(challengeTestsSelector); <add> let testResults; <add> switch (challengeType) { <add> case js: <add> case bonfire: <add> testResults = yield ExecuteJSChallengeSaga(tests); <add> break; <add> case backend: <add> // yield ExecuteBackendChallengeSaga(); <add> break; <add> default: <add> // yield ExecuteDOMChallengeSaga(); <add> } <add> <add> yield put(updateTests(testResults)); <add> yield put(updateConsole('// tests completed')); <add> yield put(logsToConsole('// console output')); <add> } catch (e) { <add> yield put(updateConsole(e)); <ide> } <ide> } <ide> <del>function* ExecuteJSChallengeSaga() { <del> yield put(initLogs()); <del> yield put(initConsole('// running tests')); <del> try { <del> const files = yield select(challengeFilesSelector); <del> const { code, solution } = yield call(buildJSFromFiles, files); <del> const tests = yield select(challengeTestsSelector); <del> const testResults = []; <del> for (const { text, testString } of tests) { <del> const newTest = { text, testString }; <add>function* ExecuteJSChallengeSaga(tests) { <add> const testResults = []; <add> const files = yield select(challengeFilesSelector); <add> const { code, solution } = yield call(buildJSFromFiles, files); <add> <add> for (const { text, testString } of tests) { <add> const newTest = { text, testString }; <add> try { <ide> const { pass, err, logs } = yield call( <ide> testWorker.execute, <ide> { script: solution + '\n' + testString, code }, <ide> testTimeout <ide> ); <add> for (const log of logs) { <add> yield put(updateLogs(log)); <add> } <ide> if (pass) { <ide> newTest.pass = true; <add> } else { <add> throw err; <add> } <add> } catch (err) { <add> newTest.message = text.replace(/<code>(.*?)<\/code>/g, '$1'); <add> if (err === 'timeout') { <add> newTest.err = 'Test timed out'; <add> newTest.message = `${newTest.message} (${newTest.err})`; <ide> } else { <ide> const { message, stack } = err; <ide> newTest.err = message + '\n' + stack; <ide> newTest.stack = stack; <del> newTest.message = text.replace(/<code>(.*?)<\/code>/g, '$1'); <del> yield put(updateConsole(newTest.message)); <ide> } <add> yield put(updateConsole(newTest.message)); <add> } finally { <ide> testResults.push(newTest); <del> for (const log of logs) { <del> yield put(updateLogs(log)); <del> } <del> // kill worker for independent tests <ide> yield call(testWorker.killWorker); <ide> } <del> yield put(updateTests(testResults)); <del> yield put(updateConsole('// tests completed')); <del> yield put(logsToConsole('// console output')); <del> } catch (e) { <del> if (e === 'timeout') { <del> yield put(updateConsole('Test timed out')); <del> } else { <del> yield put(updateConsole(e)); <del> } <del> } finally { <del> yield call(testWorker.killWorker); <ide> } <add> return testResults; <ide> } <ide> <ide> export function createExecuteChallengeSaga(types) {
1
Text
Text
fix misleading section on associations guide
91daacbbda9c923517ffc7d739e4f4e30e341d30
<ide><path>guides/source/association_basics.md <ide> Here are a few things you should know to make efficient use of Active Record ass <ide> All of the association methods are built around caching, which keeps the result of the most recent query available for further operations. The cache is even shared across methods. For example: <ide> <ide> ```ruby <del>author.books # retrieves books from the database <add>author.books.load # retrieves books from the database <ide> author.books.size # uses the cached copy of books <ide> author.books.empty? # uses the cached copy of books <ide> ``` <ide> <ide> But what if you want to reload the cache, because data might have been changed by some other part of the application? Just call `reload` on the association: <ide> <ide> ```ruby <del>author.books # retrieves books from the database <add>author.books.load # retrieves books from the database <ide> author.books.size # uses the cached copy of books <ide> author.books.reload.empty? # discards the cached copy of books <ide> # and goes back to the database
1
Ruby
Ruby
add check for gettext to brew_doctor
5fe0b108ad795f1877a843c08c72ba07002d31b1
<ide><path>Library/Homebrew/brew_doctor.rb <ide> def check_pkg_config_paths <ide> end <ide> end <ide> <add>def check_for_gettext <add> if File.exist? "#{HOMEBREW_PREFIX}/lib/libgettextlib.dylib" or <add> File.exist? "#{HOMEBREW_PREFIX}/lib/libintl.dylib" <add> puts <<-EOS.undent <add> gettext was detected in your PREFIX. <add> <add> The gettext provided by Homebrew is "keg-only", meaning it does not <add> get linked into your PREFIX by default. <add> <add> If you `brew link gettext` then a large number of brews that don't <add> otherwise have a `depends_on 'gettext'` will pick up gettext anyway <add> during the `./configure` step. <add> EOS <add> end <add>end <add> <ide> def brew_doctor <ide> read, write = IO.pipe <ide> <ide> def brew_doctor <ide> check_user_path <ide> check_which_pkg_config <ide> check_pkg_config_paths <add> check_for_gettext <ide> <ide> exit! 0 <ide> else
1
Ruby
Ruby
use the host environment variable for rails server
e17d7275f49a7286439d972f01b0fb42331dcdb7
<ide><path>railties/lib/rails/commands/server.rb <ide> def middleware <ide> def default_options <ide> super.merge({ <ide> Port: ENV.fetch('PORT', 3000).to_i, <add> Host: ENV.fetch('HOST', 'localhost').dup, <ide> DoNotReverseLookup: true, <ide> environment: (ENV['RAILS_ENV'] || ENV['RACK_ENV'] || "development").dup, <ide> daemonize: false, <ide><path>railties/test/commands/server_test.rb <ide> def test_environment_with_port <ide> end <ide> end <ide> <add> def test_environment_with_host <add> switch_env "HOST", "1.2.3.4" do <add> server = Rails::Server.new <add> assert_equal "1.2.3.4", server.options[:Host] <add> end <add> end <add> <ide> def test_caching_without_option <ide> args = [] <ide> options = Rails::Server::Options.new.parse!(args)
2
Python
Python
add more tests for elastichosts driver
9e626c8e476d27f7e7bf2e7891553e8a20943684
<ide><path>test/compute/test_elastichosts.py <ide> import unittest <ide> import httplib <ide> <del>from libcloud.compute.drivers.elastichosts import ElasticHostsBaseNodeDriver <add>from libcloud.compute.base import Node <add>from libcloud.compute.drivers.elastichosts import \ <add> (ElasticHostsBaseNodeDriver as ElasticHosts, <add> ElasticHostsException) <add>from libcloud.common.types import InvalidCredsError, MalformedResponseError <ide> <ide> from test import MockHttp <ide> from test.compute import TestCaseMixin <ide> from test.file_fixtures import ComputeFileFixtures <ide> <ide> class ElasticHostsTestCase(unittest.TestCase): <add> <ide> def setUp(self): <del> ElasticHostsBaseNodeDriver.connectionCls.conn_classes = (None, <add> ElasticHosts.connectionCls.conn_classes = (None, <ide> ElasticHostsHttp) <del> self.driver = ElasticHostsBaseNodeDriver('foo', 'bar') <add> ElasticHostsHttp.type = None <add> self.driver = ElasticHosts('foo', 'bar') <add> self.node = Node(id=72258, name=None, state=None, public_ip=None, <add> private_ip=None, driver=self.driver) <add> <add> def test_invalid_creds(self): <add> ElasticHostsHttp.type = 'UNAUTHORIZED' <add> try: <add> self.driver.list_nodes() <add> except InvalidCredsError, e: <add> self.assertEqual(True, isinstance(e, InvalidCredsError)) <add> else: <add> self.fail('test should have thrown') <add> <add> def test_malformed_response(self): <add> ElasticHostsHttp.type = 'MALFORMED' <add> try: <add> self.driver.list_nodes() <add> except MalformedResponseError: <add> pass <add> else: <add> self.fail('test should have thrown') <add> <add> def test_parse_error(self): <add> ElasticHostsHttp.type = 'PARSE_ERROR' <add> try: <add> self.driver.list_nodes() <add> except Exception, e: <add> self.assertTrue(str(e).find('X-Elastic-Error') != -1) <add> else: <add> self.fail('test should have thrown') <add> <add> def test_ex_set_node_configuration(self): <add> success = self.driver.ex_set_node_configuration(node=self.node, <add> name='name', <add> cpu='2') <add> <add> def test_ex_set_node_configuration_invalid_keys(self): <add> try: <add> self.driver.ex_set_node_configuration(node=self.node, foo='bar') <add> except ElasticHostsException: <add> pass <add> else: <add> self.fail('Invalid option specified, but an exception was not thrown') <ide> <ide> def test_list_nodes(self): <ide> nodes = self.driver.list_nodes() <ide> def test_list_images(self): <ide> self.assertEqual(size.id, '38df0986-4d85-4b76-b502-3878ffc80161') <ide> self.assertEqual(size.name, 'CentOS Linux 5.5') <ide> <del> def test_list_locations_response(self): <del> pass <del> <ide> def test_reboot_node(self): <ide> node = self.driver.list_nodes()[0] <ide> self.assertTrue(self.driver.reboot_node(node)) <ide> def test_destroy_node(self): <ide> node = self.driver.list_nodes()[0] <ide> self.assertTrue(self.driver.destroy_node(node)) <ide> <del> '''def test_create_node(self): <add> def test_create_node(self): <ide> sizes = self.driver.list_sizes() <ide> size = [s for s in sizes if \ <ide> s.id == 'large'][0] <ide> def test_destroy_node(self): <ide> i.id == '38df0986-4d85-4b76-b502-3878ffc80161'][0] <ide> <ide> self.assertTrue(self.driver.create_node(name="api.ivan.net.nz", <del> image=image, size=size))''' <add> image=image, size=size)) <ide> <ide> class ElasticHostsHttp(MockHttp): <ide> <ide> fixtures = ComputeFileFixtures('elastichosts') <ide> <add> def _servers_info_UNAUTHORIZED(self, method, url, body, headers): <add> return (httplib.UNAUTHORIZED, body, {}, httplib.responses[httplib.NO_CONTENT]) <add> <add> def _servers_info_MALFORMED(self, method, url, body, headers): <add> body = "{malformed: '" <add> return (httplib.OK, body, {}, httplib.responses[httplib.NO_CONTENT]) <add> <add> def _servers_info_PARSE_ERROR(self, method, url, body, headers): <add> return (505, body, {}, httplib.responses[httplib.NO_CONTENT]) <add> <ide> def _servers_b605ca90_c3e6_4cee_85f8_a8ebdf8f9903_reset(self, method, url, body, headers): <ide> return (httplib.NO_CONTENT, body, {}, httplib.responses[httplib.NO_CONTENT]) <ide> <ide> def _servers_info(self, method, url, body, headers): <ide> body = self.fixtures.load('servers_info.json') <ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK]) <ide> <add> def _servers_72258_set(self, method, url, body, headers): <add> body = '{}' <add> return (httplib.OK, body, {}, httplib.responses[httplib.OK]) <add> <ide> if __name__ == '__main__': <ide> sys.exit(unittest.main())
1
Ruby
Ruby
fix observer by acting on singleton class []
bad44e4f8f690039bd0db92ac25f10af536c6e71
<ide><path>activemodel/lib/active_model/observing.rb <ide> class << self <ide> def observe(*models) <ide> models.flatten! <ide> models.collect! { |model| model.respond_to?(:to_sym) ? model.to_s.camelize.constantize : model } <del> redefine_method(:observed_classes) { models } <add> singleton_class.redefine_method(:observed_classes) { models } <ide> end <ide> <ide> # Returns an array of Classes to observe. <ide><path>activemodel/test/cases/observing_test.rb <ide> def setup <ide> class ObserverTest < ActiveModel::TestCase <ide> def setup <ide> ObservedModel.observers = :foo_observer <del> FooObserver.instance_eval do <add> FooObserver.singleton_class.instance_eval do <ide> alias_method :original_observed_classes, :observed_classes <ide> end <ide> end <ide> <ide> def teardown <del> FooObserver.instance_eval do <add> FooObserver.singleton_class.instance_eval do <ide> undef_method :observed_classes <ide> alias_method :observed_classes, :original_observed_classes <ide> end <ide> def teardown <ide> end <ide> assert_equal :in_around_save, yielded_value <ide> end <add> <add> test "observe redefines observed_classes class method" do <add> class BarObserver < ActiveModel::Observer <add> observe :foo <add> end <add> <add> assert_equal [Foo], BarObserver.observed_classes <add> <add> BarObserver.observe(ObservedModel) <add> assert_equal [ObservedModel], BarObserver.observed_classes <add> end <ide> end
2
Python
Python
add tests for retrieving/updating reverse fks
24e14b7d53e43f1574971ff5b6eee6d0185df23a
<ide><path>rest_framework/tests/nested_relations.py <add>from copy import deepcopy <add>from django.db import models <add>from django.test import TestCase <add>from rest_framework import serializers <add> <add> <add># ForeignKey <add> <add>class ForeignKeyTarget(models.Model): <add> name = models.CharField(max_length=100) <add> <add> <add>class ForeignKeySource(models.Model): <add> name = models.CharField(max_length=100) <add> target = models.ForeignKey(ForeignKeyTarget, related_name='sources') <add> <add> <add>class ForeignKeySourceSerializer(serializers.ModelSerializer): <add> class Meta: <add> model = ForeignKeySource <add> <add> <add>class ForeignKeyTargetSerializer(serializers.ModelSerializer): <add> sources = ForeignKeySourceSerializer() <add> <add> class Meta: <add> model = ForeignKeyTarget <add> <add> <add>class ReverseForeignKeyTests(TestCase): <add> def setUp(self): <add> target = ForeignKeyTarget(name='target-1') <add> target.save() <add> new_target = ForeignKeyTarget(name='target-2') <add> new_target.save() <add> for idx in range(1, 4): <add> source = ForeignKeySource(name='source-%d' % idx, target=target) <add> source.save() <add> self.target_data = {'id': 1, 'name': u'target-1', 'sources': [ <add> {'id': 1, 'name': u'source-1', 'target': 1}, <add> {'id': 2, 'name': u'source-2', 'target': 1}, <add> {'id': 3, 'name': u'source-3', 'target': 1}, <add> ]} <add> self.new_target_data = {'id': 2, 'name': u'target-2', 'sources': []} <add> self.data = [self.target_data, self.new_target_data] <add> <add> def test_reverse_foreign_key_retrieve(self): <add> queryset = ForeignKeyTarget.objects.all() <add> serializer = ForeignKeyTargetSerializer(queryset) <add> self.assertEquals(serializer.data, self.data) <add> <add> def test_reverse_foreign_key_update(self): <add> data = deepcopy(self.target_data) <add> data['sources'][0]['name'] = 'source-1-changed' <add> data['sources'][2]['name'] = 'source-3-changed' <add> instance = ForeignKeyTarget.objects.get(pk=1) <add> serializer = ForeignKeyTargetSerializer(instance, data=data) <add> self.assertTrue(serializer.is_valid()) <add> self.assertEquals(serializer.data, data) <add> serializer.save() <add> <add> # Ensure target 1 is updated, and everything else is as expected <add> queryset = ForeignKeyTarget.objects.all() <add> serializer = ForeignKeyTargetSerializer(queryset) <add> expected = deepcopy(self.data) <add> expected[0]['sources'][0]['name'] = 'source-1-changed' <add> expected[0]['sources'][2]['name'] = 'source-3-changed' <add> self.assertEquals(serializer.data, expected)
1
PHP
PHP
enable asset timestamp for image submit buttons
30504ef32b0b3a101f860a02b2bed4ed8eef5b10
<ide><path>lib/Cake/View/Helper/FormHelper.php <ide> public function submit($caption = null, $options = array()) { <ide> } else { <ide> $url = $this->webroot(trim($caption, '/')); <ide> } <add> $url = $this->assetTimestamp($url); <ide> $tag = $this->Html->useTag('submitimage', $url, $options); <ide> } else { <ide> $options['value'] = $caption;
1
Text
Text
update chinese translation of redux
b378f110ca1b0e98972d80b274d2c0a104df869f
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/redux/combine-multiple-reducers.chinese.md <ide> id: 5a24c314108439a4d4036154 <ide> title: Combine Multiple Reducers <ide> challengeType: 6 <ide> isRequired: false <del>videoUrl: '' <del>localeTitle: 结合多个减速器 <add>forumTopicId: 301436 <add>localeTitle: 组合多个 Reduces <ide> --- <ide> <ide> ## Description <del><section id="description">当您的应用程序的状态开始变得更加复杂时,可能很容易将状态分成多个部分。相反,请记住Redux的第一个原则:所有应用程序状态都保存在商店中的单个状态对象中。因此,Redux提供减速器组合作为复杂状态模型的解决方案。您可以定义多个reducers来处理应用程序状态的不同部分,然后将这些reducer组合成一个根reducer。然后将根reducer传递给Redux <code>createStore()</code>方法。为了让我们将多个reducer组合在一起,Redux提供了<code>combineReducers()</code>方法。此方法接受一个对象作为参数,您可以在其中定义将键与特定reducer函数关联的属性。 Redux将使用您为密钥指定的名称作为相关状态的名称。通常,当每个应用程序状态以某种方式不同或唯一时,为每个应用程序状态创建一个减速器是一个好习惯。例如,在具有用户身份验证的笔记记录应用程序中,一个reducer可以处理身份验证,而另一个reducer处理用户正在提交的文本和备注。对于这样的应用程序,我们可能会像这样编写<code>combineReducers()</code>方法: <blockquote> const rootReducer = Redux.combineReducers({ <br> auth:authenticationReducer, <br>笔记:notesReducer <br> }); </blockquote>现在,关键<code>notes</code>将包含与我们的注释相关联的所有状态,并由<code>notesReducer</code>处理。这就是如何组合多个reducers来管理更复杂的应用程序状态。在此示例中,Redux存储中保存的状态将是包含<code>auth</code>和<code>notes</code>属性的单个对象。 </section> <add><section id='description'> <add>当你应用程序的状态开始变得越来越复杂时,将状态划分为多个部分可能是个更好的选择。相反,请记住 Redux 的第一个原则:所有应用程序状态都保存在 store 中的一个简单的 state 对象中。因此,Redux 提供 reducer 组合作为复杂状态模型的解决方案。定义多个 reducer 来处理应用程序状态的不同部分,然后将这些 reducer 组合成一个 root reducer。然后将 root reducer 传递给 Redux <code>createStore()</code>方法。 <add>为了让我们将可以将多个 reducer 组合在一起,Redux 提供了<code>combineReducers()</code>方法。该方法接受一个对象作为参数,在该参数中定义一个将键与特定 reducer 函数关联的属性。Redux 将使用你给的键值作为关联状态的名称。 <add>通常情况下,当它们在某种程度上是独一无二的,为每个应用程序的 state 创建一个减少器是一个很好的做法。例如,在一个带有用户身份验证的记笔记应用程序中,一个 reducer 可以处理身份验证而另一个处理用户提交的文本和注释。对于这样的应用程序,我们可能会编写<code>combineReducers()</code>方法,如下所示: <add> <add>```js <add>const rootReducer = Redux.combineReducers({ <add> auth: authenticationReducer, <add> notes: notesReducer <add>}); <add>``` <add> <add>现在,<code>notes</code>键将包含与我们的注释相关联的所有状态,并由我们的<code>notesReducer</code>处理。这就是如何组合多个 reducer 来管理更复杂的应用程序状态,在此示例中,Redux store 中保存的状态将是一个包含<code>auth</code>和<code>notes</code>属性的简单对象。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">代码编辑器中提供了<code>authReducer()</code> <code>counterReducer()</code>和<code>authReducer()</code>函数以及Redux存储。使用<code>Redux.combineReducers()</code>方法完成<code>rootReducer()</code>函数的<code>Redux.combineReducers()</code> 。指定<code>counterReducer</code>一键叫<code>count</code>和<code>authReducer</code>一个叫关键<code>auth</code> 。 </section> <add><section id='instructions'> <add>代码编辑器中提供了<code>counterReducer()</code>和<code>authReducer()</code>函数以及 Redux store。使用<code>Redux.combineReducers()</code>方法编写完成<code>rootReducer()</code>函数。将<code>counterReducer</code>分配给一个叫做<code>count</code>的键,将<code>authReducer</code>分配给一个叫做<code>auth</code>的键。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: <code>counterReducer</code>应该递增和递减<code>state</code> 。 <add> - text: <code>counterReducer</code>应该递增和递减<code>state</code>。 <ide> testString: 'assert((function() { const initialState = store.getState().count; store.dispatch({type: INCREMENT}); store.dispatch({type: INCREMENT}); const firstState = store.getState().count; store.dispatch({type: DECREMENT}); const secondState = store.getState().count; return firstState === initialState + 2 && secondState === firstState - 1 })());' <del> - text: <code>authReducer</code>应切换在<code>true</code>和<code>false</code>之间进行<code>authenticated</code>的<code>state</code> 。 <add> - text: <code>authenticated</code>的<code>state</code>值应该在<code>true</code>和<code>false</code>之间切换。 <ide> testString: 'assert((function() { store.dispatch({type: LOGIN}); const loggedIn = store.getState().auth.authenticated; store.dispatch({type: LOGOUT}); const loggedOut = store.getState().auth.authenticated; return loggedIn === true && loggedOut === false })());' <del> - text: 存储<code>state</code>应该有两个键: <code>count</code> ,它包含一个数字, <code>auth</code> ,它包含一个对象。 <code>auth</code>对象应具有<code>authenticated</code>属性,该属性包含布尔值。 <add> - text: store <code>state</code>应该有两个 key:一个是<code>count</code>,它包含一个数字。另一个<code>auth</code>,它包含一个对象。<code>auth</code>对象应该具有<code>authenticated</code>的属性,该属性的值应该为布尔值。 <ide> testString: "assert((function() { const state = store.getState(); return typeof state.auth === 'object' && typeof state.auth.authenticated === 'boolean' && typeof state.count === 'number' })());" <del> - text: 该<code>rootReducer</code>应该是结合了功能<code>counterReducer</code>和<code>authReducer</code> 。 <add> - text: <code>rootReducer</code>应该是一个合并了<code>counterReducer</code>和<code>authReducer</code>的函数。 <ide> testString: getUserInput => assert((function() { const noWhiteSpace = getUserInput('index').replace(/\s/g,''); return typeof rootReducer === 'function' && noWhiteSpace.includes('Redux.combineReducers') })()); <ide> <ide> ``` <ide> const authReducer = (state = {authenticated: false}, action) => { <ide> } <ide> }; <ide> <del>const rootReducer = // define the root reducer here <add>const rootReducer = // 在这里定义 root reducer <ide> <ide> const store = Redux.createStore(rootReducer); <ide> <ide> const store = Redux.createStore(rootReducer); <ide> ## Solution <ide> <section id='solution'> <ide> <add> <ide> ```js <del>// solution required <add>const INCREMENT = 'INCREMENT'; <add>const DECREMENT = 'DECREMENT'; <add> <add>const counterReducer = (state = 0, action) => { <add> switch(action.type) { <add> case INCREMENT: <add> return state + 1; <add> case DECREMENT: <add> return state - 1; <add> default: <add> return state; <add> } <add>}; <add> <add>const LOGIN = 'LOGIN'; <add>const LOGOUT = 'LOGOUT'; <add> <add>const authReducer = (state = {authenticated: false}, action) => { <add> switch(action.type) { <add> case LOGIN: <add> return { <add> authenticated: true <add> } <add> case LOGOUT: <add> return { <add> authenticated: false <add> } <add> default: <add> return state; <add> } <add>}; <add> <add>const rootReducer = Redux.combineReducers({ <add> count: counterReducer, <add> auth: authReducer <add>}); <add> <add>const store = Redux.createStore(rootReducer); <ide> ``` <ide> <del>/section> <add></section> <ide><path>curriculum/challenges/chinese/03-front-end-libraries/redux/copy-an-object-with-object.assign.chinese.md <ide> id: 5a24c314108439a4d403615b <ide> title: Copy an Object with Object.assign <ide> challengeType: 6 <ide> isRequired: false <del>videoUrl: '' <del>localeTitle: 使用Object.assign复制对象 <add>forumTopicId: 301437 <add>localeTitle: 使用 Object.assign 拷贝对象 <ide> --- <ide> <ide> ## Description <del><section id="description">最后几个挑战适用于数组,但是当状态是一个<code>object</code>时,有一些方法可以帮助强制执行状态不变性。处理对象的有用工具是<code>Object.assign()</code>实用程序。 <code>Object.assign()</code>接受目标对象和源对象,并将源对象中的属性映射到目标对象。任何匹配的属性都会被源对象中的属性覆盖。此行为通常用于通过将空对象作为第一个参数传递,然后传递要复制的对象来生成对象的浅副本。这是一个例子: <code>const newObject = Object.assign({}, obj1, obj2);</code>这将<code>newObject</code>创建为一个新<code>object</code> ,其中包含当前存在于<code>obj1</code>和<code>obj2</code>中的属性。 </section> <add><section id='description'> <add>最后几个挑战适用于数组,但是当状态是<code>object</code>时,有一些方法可以帮助强制执行状态不变性。处理对象的一个方法是<code>Object.assign()</code>。<code> Object.assign()</code>获取目标对象和源对象,并将源对象中的属性映射到目标对象。任何匹配的属性都会被源对象中的属性覆盖。通常用于通过传递一个空对象作为第一个参数,然后是要用复制的对象来制作对象的浅表副本。这是一个例子: <add><code>const newObject = Object.assign({}, obj1, obj2);</code> <add>这会创建<code>newObject</code>作为新的<code>object</code>,其中包含<code>obj1</code>和<code>obj2</code>中当前存在的属性。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions"> Redux状态和操作被修改为处理<code>state</code>的<code>object</code> 。编辑代码以返回类型为<code>ONLINE</code>操作的新<code>state</code>对象,该<code>status</code>属性将<code>status</code>属性设置为<code>online</code>字符串。尝试使用<code>Object.assign()</code>来完成挑战。 </section> <add><section id='instructions'> <add>Redux 状态和 action 被修改为处理<code>state</code>的<code>对象</code>。编辑代码以返回一个新的<code>state</code>对象,用于类型的 action<code>ONLINE</code>,它将<code>status</code>属性设置为字符串<code>online</code>。尝试使用<code>Object.assign()</code>来完成挑战。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: Redux存储应该存在并使用等效于第1行声明的<code>defaultState</code>对象的状态进行初始化。 <add> - text: Redux store 应该存在并使用与第 1 行声明的<code>defaultState</code>对象相同的状态进行初始化。 <ide> testString: 'assert((function() { const expectedState = { user: ''CamperBot'', status: ''offline'', friends: ''732,982'', community: ''freeCodeCamp'' }; const initialState = store.getState(); return DeepEqual(expectedState, initialState); })());' <ide> - text: <code>wakeUp</code>和<code>immutableReducer</code>都应该是函数。 <ide> testString: assert(typeof wakeUp === 'function' && typeof immutableReducer === 'function'); <del> - text: 调度<code>ONLINE</code>类型的操作应该将<code>status</code>中的属性<code>status</code>更新为<code>online</code>并且不应该改变状态。 <add> - text: dispatch 一个类型为<code>ONLINE</code>的 action 应该将状态<code>status</code>更新为<code>online</code>,并且不应该改变状态。 <ide> testString: 'assert((function() { const initialState = store.getState(); const isFrozen = DeepFreeze(initialState); store.dispatch({type: ''ONLINE''}); const finalState = store.getState(); const expectedState = { user: ''CamperBot'', status: ''online'', friends: ''732,982'', community: ''freeCodeCamp'' }; return isFrozen && DeepEqual(finalState, expectedState); })());' <del> - text: <code>Object.assign</code>应该用于返回新状态。 <add> - text: <code>Object.assign</code>应该被用于返回一个新状态。 <ide> testString: getUserInput => assert(getUserInput('index').includes('Object.assign')); <ide> <ide> ``` <ide> const defaultState = { <ide> const immutableReducer = (state = defaultState, action) => { <ide> switch(action.type) { <ide> case 'ONLINE': <del> // don't mutate state here or the tests will fail <add> // 不要在这里改变 state 否则测试会失败。 <ide> return <ide> default: <ide> return state; <ide> const wakeUp = () => { <ide> }; <ide> <ide> const store = Redux.createStore(immutableReducer); <del> <ide> ``` <ide> <ide> </div> <ide> const store = Redux.createStore(immutableReducer); <ide> ## Solution <ide> <section id='solution'> <ide> <add> <ide> ```js <del>// solution required <add>const defaultState = { <add> user: 'CamperBot', <add> status: 'offline', <add> friends: '732,982', <add> community: 'freeCodeCamp' <add>}; <add> <add>const immutableReducer = (state = defaultState, action) => { <add> switch(action.type) { <add> case 'ONLINE': <add> return Object.assign({}, state, { <add> status: 'online' <add> }); <add> default: <add> return state; <add> } <add>}; <add> <add>const wakeUp = () => { <add> return { <add> type: 'ONLINE' <add> } <add>}; <add> <add>const store = Redux.createStore(immutableReducer); <ide> ``` <ide> <del>/section> <add></section> <ide><path>curriculum/challenges/chinese/03-front-end-libraries/redux/create-a-redux-store.chinese.md <ide> id: 5a24c314108439a4d403614b <ide> title: Create a Redux Store <ide> challengeType: 6 <ide> isRequired: false <del>videoUrl: '' <del>localeTitle: 创建一个Redux商店 <add>forumTopicId: 301439 <add>localeTitle: 创建一个 Redux Store <ide> --- <ide> <ide> ## Description <del><section id="description"> Redux是一个状态管理框架,可以与许多不同的Web技术一起使用,包括React。在Redux中,有一个状态对象负责应用程序的整个状态。这意味着如果您有一个包含十个组件的React应用程序,并且每个组件都有自己的本地状态,则应用程序的整个状态将由Redux <code>store</code>的单个状态对象定义。这是学习Redux时理解的第一个重要原则:Redux商店是应用程序状态的唯一真实来源。这也意味着,只要您的应用程序的任何部分想要更新状态,它<strong>必须</strong>通过Redux商店执行此操作。单向数据流可以更轻松地跟踪应用程序中的状态管理。 </section> <add><section id='description'> <add>Redux 是一个状态管理框架,可以与包括 React 在内的许多不同的 Web 技术一起使用。 <add>在 Redux 中,有一个状态对象负责应用程序的整个状态,这意味着如果你有一个包含十个组件且每个组件都有自己的本地状态的 React 项目,那么这个项目的整个状态将通过 Redux<code>store</code>被定义为单个状态对象,这是学习 Redux 时要理解的第一个重要原则:Redux store 是应用程序状态的唯一真实来源。 <add>这也意味着,如果你的应用程序想要更新状态,只能通过 Redux store 执行,单向数据流可以更轻松地对应用程序中的状态进行监测管理。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions"> Redux <code>store</code>是一个保存和管理应用程序<code>state</code>的对象。 Redux对象上有一个名为<code>createStore()</code>的方法,您可以使用该方法创建Redux <code>store</code> 。此方法将<code>reducer</code>函数作为必需参数。 <code>reducer</code>函数将在稍后的挑战中介绍,并且已在代码编辑器中为您定义。它只是将<code>state</code>作为参数并返回<code>state</code> 。声明一个<code>store</code>变量并将其赋值给<code>createStore()</code>方法,并将<code>reducer</code>作为参数传入。 <strong>注意:</strong>编辑器中的代码使用ES6默认参数语法初始化此状态以保存值<code>5</code> 。如果您不熟悉默认参数,可以参考<a target="_blank" href="https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/es6/set-default-parameters-for-your-functions">课程</a>中涵盖此主题的<a target="_blank" href="https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/es6/set-default-parameters-for-your-functions">ES6部分</a> 。 </section> <add><section id='instructions'> <add>Redux <code>store</code>是一个保存和管理应用程序状态的<code>state</code>,你可以使用 Redux 对象中的<code>createStore()</code>来创建一个 redux<code>store</code>,此方法将<code>reducer</code>函数作为必需参数,<code>reducer</code>函数将在后面的挑战中介绍。该函数已在代码编辑器中为你定义,它只需将<code>state</code>作为参数并返回一个<code>state</code>即可。 <add>声明一个<code>store</code>变量并把它分配给<code>createStore()</code>方法,然后把<code>reducer</code>作为一个参数传入即可。 <add>注意: 编辑器中的代码使用 ES6 默认参数语法将 state 的值初始化为<code>5</code>, 如果你不熟悉默认参数,你可以参考<a target="_blank" href="http://beta.freecodecamp.com/en/challenges/es6/set-default-parameters-for-your-functions"> ES6 全部课程</a>,它里面涵盖了这个内容。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: redux商店存在。 <add> - text: redux store 应当存在。 <ide> testString: assert(typeof store.getState === 'function'); <del> - text: redux商店的状态值为5。 <add> - text: redux store 的 state 的值为 5。 <ide> testString: assert(store.getState()=== 5); <ide> <ide> ``` <ide> const reducer = (state = 5) => { <ide> return state; <ide> } <ide> <del>// Redux methods are available from a Redux object <del>// For example: Redux.createStore() <del>// Define the store here: <add>// Redux 方法可以从 Redux 对象获得 <add>// 例如: Redux.createStore() <add>// 在这里定义一个 store <add> <add> <ide> <ide> ``` <ide> <ide> const reducer = (state = 5) => { <ide> ## Solution <ide> <section id='solution'> <ide> <add> <ide> ```js <del>// solution required <add>const reducer = (state = 5) => { <add> return state; <add>} <add> <add>//Redux 方法可以从 Redux 对象获得 <add>// 例如: Redux.createStore() <add>// 在这里定义一个 store: <add> <add>const store = Redux.createStore(reducer); <ide> ``` <ide> <del>/section> <add></section> <ide><path>curriculum/challenges/chinese/03-front-end-libraries/redux/define-a-redux-action.chinese.md <ide> id: 5a24c314108439a4d403614d <ide> title: Define a Redux Action <ide> challengeType: 6 <ide> isRequired: false <del>videoUrl: '' <del>localeTitle: 定义Redux动作 <add>forumTopicId: 301440 <add>localeTitle: 定义一个 Redux Action <ide> --- <ide> <ide> ## Description <del><section id="description">由于Redux是一个状态管理框架,因此更新状态是其核心任务之一。在Redux中,所有状态更新都由调度操作触发。操作只是一个JavaScript对象,其中包含有关已发生的操作事件的信息。 Redux存储接收这些操作对象,然后相应地更新其状态。有时,Redux操作也会携带一些数据。例如,操作在用户登录后携带用户名。虽然数据是可选的,但操作必须带有<code>type</code>属性,该属性指定发生的操作的“类型”。将Redux操作视为信使,将有关应用程序中发生的事件的信息提供给Redux商店。然后,商店根据发生的操作开展更新状态的业务。 </section> <add><section id='description'> <add>由于 Redux 是一个状态管理框架,因此更新状态是其核心任务之一。在 Redux 中,所有状态更新都由 dispatch action 触发,action 只是一个 JavaScript 对象,其中包含有关已发生的 action 事件的信息。Redux store 接收这些 action 对象,然后更新相应的状态。有时,Redux action 也会携带一些数据。例如,在用户登录后携带用户名,虽然数据是可选的,但 action 必须带有<code>type</code>属性,该属性表示此 action 的类型。 <add>我们可以将 Redux action 视为信使,将有关应用程序中发生的事件信息提供给 Redux store,然后 store 根据发生的 action 进行状态的更新。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">编写Redux操作就像声明具有type属性的对象一样简单。声明一个对象<code>action</code>并为其设置一个属性<code>type</code>设置为字符串<code>&#39;LOGIN&#39;</code> 。 </section> <add><section id='instructions'> <add>编写 Redux action 就像声明具有 type 属性的对象一样简单,声明一个对象<code>action</code>并为它设置一个属性<code>type</code>,并将他的值设置成字符串<code>'LOGIN'</code>。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 应该存在一个操作对象。 <add> - text: 应该有一个 action 对象。 <ide> testString: assert((function() { return typeof action === 'object' })()); <del> - text: 该操作应具有值为<code>LOGIN</code>的键属性类型。 <add> - text: 该 action 的值应该为<code>LOGIN</code>。 <ide> testString: assert((function() { return action.type === 'LOGIN' })()); <ide> <ide> ``` <ide> tests: <ide> <div id='jsx-seed'> <ide> <ide> ```jsx <del>// Define an action here: <add>// 在此处定义 action <ide> <ide> ``` <ide> <ide> tests: <ide> ## Solution <ide> <section id='solution'> <ide> <add> <ide> ```js <del>// solution required <add>const action = { <add> type: 'LOGIN' <add>} <ide> ``` <ide> <del>/section> <add></section> <ide><path>curriculum/challenges/chinese/03-front-end-libraries/redux/define-an-action-creator.chinese.md <ide> id: 5a24c314108439a4d403614e <ide> title: Define an Action Creator <ide> challengeType: 6 <ide> isRequired: false <del>videoUrl: '' <del>localeTitle: 定义一个Action Creator <add>forumTopicId: 301441 <add>localeTitle: 定义一个 Action Creator <ide> --- <ide> <ide> ## Description <del><section id="description">创建操作后,下一步是将操作发送到Redux存储,以便它可以更新其状态。在Redux中,您可以定义动作创建器来完成此任务。动作创建者只是一个返回动作的JavaScript函数。换句话说,动作创建者创建表示动作事件的对象。 </section> <add><section id='description'> <add>创建 action 后要将 action 发送到 Redux store,以便它可以更新其状态。在 Redux 中,你可以定义动作创建器来完成此任务,action creator 只是一个返回动作的 JavaScript 函数,换句话说,action creator 创建表示动作事件的对象。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">定义一个名为<code>actionCreator()</code>的函数,该函数在调用时返回<code>action</code>对象。 </section> <add><section id='instructions'> <add>定义名为<code>actionCreator()</code>的函数,该函数在调用时返回<code>action</code>对象。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> localeTitle: 定义一个Action Creator <ide> tests: <ide> - text: 函数<code>actionCreator</code>应该存在。 <ide> testString: assert(typeof actionCreator === 'function'); <del> - text: 运行<code>actionCreator</code>函数应该返回操作对象。 <add> - text: 运行<code>actionCreator</code>函数应返回 action 对象。 <ide> testString: assert(typeof action === 'object'); <del> - text: 返回的操作应具有值为<code>LOGIN</code>的键属性类型。 <add> - text: 返回的 action 应具有值为<code>LOGIN</code>的键值类型。 <ide> testString: assert(action.type === 'LOGIN'); <ide> <ide> ``` <ide> tests: <ide> const action = { <ide> type: 'LOGIN' <ide> } <del>// Define an action creator here: <add>// 在此处定义 action creator <add> <ide> <ide> ``` <ide> <ide> const action = { <ide> ## Solution <ide> <section id='solution'> <ide> <add> <ide> ```js <del>// solution required <add>const action = { <add> type: 'LOGIN' <add>} <add>// 在此处定义 action creator: <add>const actionCreator = () => { <add> return action; <add>}; <ide> ``` <ide> <del>/section> <add></section> <ide><path>curriculum/challenges/chinese/03-front-end-libraries/redux/dispatch-an-action-event.chinese.md <ide> id: 5a24c314108439a4d403614f <ide> title: Dispatch an Action Event <ide> challengeType: 6 <ide> isRequired: false <del>videoUrl: '' <del>localeTitle: 派遣行动事件 <add>forumTopicId: 301442 <add>localeTitle: 分发 Action Event <ide> --- <ide> <ide> ## Description <del><section id="description"> <code>dispatch</code>方法是您用于将操作分派给Redux存储的方法。调用<code>store.dispatch()</code>并传递从操作创建者返回的值会将操作发送回商店。回想一下,动作创建者返回一个具有type属性的对象,该属性指定已发生的动作。然后,该方法将操作对象调度到Redux存储。根据之前的挑战示例,以下行是等效的,并且都调度<code>LOGIN</code>类型的操作: <blockquote> store.dispatch(actionCreator()); <br> store.dispatch({type:&#39;LOGIN&#39;}); </blockquote></section> <add><section id='description'> <add><code>dispatch</code>方法用于将 action 分派给 Redux store,调用<code>store.dispatch()</code>将从 action creator 返回的值发送回 store。 <add>action creator 返回一个具有 type 属性的对象,该属性指定已发生的 action,然后,该方法将 action 对象 dispatch 到 Redux store,根据之前的挑战示例,以下内容是等效的,并且都 dispatch 类型为<code>LOGIN</code>的 action: <add> <add>```js <add>store.dispatch(actionCreator()); <add>store.dispatch({ type: 'LOGIN' }); <add>``` <add> <add></section> <ide> <ide> ## Instructions <del><section id="instructions">代码编辑器中的Redux存储具有初始化状态,该状态是包含当前设置为<code>false</code>的<code>login</code>属性的对象。还有一个名为<code>loginAction()</code>的动作创建器,它返回<code>LOGIN</code>类型的动作。通过调用<code>dispatch</code>方法将<code>LOGIN</code>操作发送到Redux存储,并传入<code>loginAction()</code>创建的操作。 </section> <add><section id='instructions'> <add>代码编辑器中的 Redux store 具有初始化状态对象{login:'false'},还有一个名为<code>loginAction()</code>的 action creator,它返回类型为<code>LOGIN</code>的 action,然后通过调用<code>dispatch</code>方法将<code>LOGIN</code>的 action dispatch 给 Redux store,并传递<code>loginAction()</code>创建的 action。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 调用函数<code>loginAction</code>应该返回一个对象,其<code>type</code>属性设置为字符串<code>LOGIN</code> 。 <add> - text: '调用函数<code>loginAction</code>应该返回一个对象{type:"LOGIN"}。' <ide> testString: assert(loginAction().type === 'LOGIN'); <del> - text: 应使用属性<code>login</code>设置为<code>false</code>的对象初始化存储。 <add> - text: 'store 应该初始化一个对象 {login:false}。' <ide> testString: assert(store.getState().login === false); <del> - text: <code>store.dispatch()</code>方法应该用于调度<code>LOGIN</code>类型的操作。 <add> - text: <code>store.dispatch()</code>方法应该被用于 dispatch 一个类型为<code>LOGIN</code>的 action。 <ide> testString: "getUserInput => assert((function() { let noWhiteSpace = getUserInput('index').replace(/\\s/g,''); return noWhiteSpace.includes('store.dispatch(loginAction())') || noWhiteSpace.includes('store.dispatch({type: \\'LOGIN\\'})') === true })());" <ide> <ide> ``` <ide> const loginAction = () => { <ide> } <ide> }; <ide> <del>// Dispatch the action here: <add>// 在这里 dispatch action <ide> <ide> ``` <ide> <ide> const loginAction = () => { <ide> ## Solution <ide> <section id='solution'> <ide> <add> <ide> ```js <del>// solution required <add>const store = Redux.createStore( <add> (state = {login: false}) => state <add>); <add> <add>const loginAction = () => { <add> return { <add> type: 'LOGIN' <add> } <add>}; <add> <add>// Dispatch the action here: <add>store.dispatch(loginAction()); <ide> ``` <ide> <del>/section> <add></section> <ide><path>curriculum/challenges/chinese/03-front-end-libraries/redux/get-state-from-the-redux-store.chinese.md <ide> id: 5a24c314108439a4d403614c <ide> title: Get State from the Redux Store <ide> challengeType: 6 <ide> isRequired: false <del>videoUrl: '' <del>localeTitle: 从Redux商店获取状态 <add>forumTopicId: 301443 <add>localeTitle: 从 Redux Store 获取状态 <ide> --- <ide> <ide> ## Description <del><section id="description"> Redux存储对象提供了几种允许您与之交互的方法。例如,您可以使用<code>getState()</code>方法检索Redux存储对象中保存的当前<code>state</code> 。 </section> <add><section id='description'> <add>Redux store 对象提供了几种允许你与之交互的方法,你可以使用<code>getState()</code>方法检索 Redux store 对象中保存的当前的<code>state</code>。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">上一个挑战中的代码在代码编辑器中更简洁地重写。使用<code>store.getState()</code>从<code>store</code>检索<code>state</code> ,并将其分配给新变量<code>currentState</code> 。 </section> <add><section id='instructions'> <add>在代码编辑器中可以将上一个挑战中的代码更简洁地重写,在<code>store</code>中使用<code>store.getState()</code>检索<code>state</code>,并将其分配给新变量<code>currentState</code>。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 对于初始状态,redux存储的值应为5。 <add> - text: redux store 的 state 应该有一个初始值 5。 <ide> testString: assert(store.getState()===5); <del> - text: 应该存在一个变量<code>currentState</code> ,并且应该为其分配Redux存储的当前状态。 <add> - text: 应该存在一个变量<code>currentState</code>,并为其分配 Redux store 的当前状态。 <ide> testString: getUserInput => assert(currentState === 5 && getUserInput('index').includes('store.getState()')); <ide> <ide> ``` <ide> const store = Redux.createStore( <ide> (state = 5) => state <ide> ); <ide> <del>// change code below this line <add>// 更改此行下方的代码 <ide> <ide> ``` <ide> <ide> const store = Redux.createStore( <ide> ## Solution <ide> <section id='solution'> <ide> <add> <ide> ```js <del>// solution required <add>const store = Redux.createStore( <add> (state = 5) => state <add>); <add> <add>// 更改此行下方的代码 <add>const currentState = store.getState(); <ide> ``` <ide> <del>/section> <add></section> <ide><path>curriculum/challenges/chinese/03-front-end-libraries/redux/handle-an-action-in-the-store.chinese.md <ide> id: 5a24c314108439a4d4036150 <ide> title: Handle an Action in the Store <ide> challengeType: 6 <ide> isRequired: false <del>videoUrl: '' <del>localeTitle: 处理商店中的操作 <add>forumTopicId: 301444 <add>localeTitle: 在 Store 里处理 Action <ide> --- <ide> <ide> ## Description <del><section id="description">创建并分派操作后,Redux存储需要知道如何响应该操作。这是<code>reducer</code>功能的工作。 Redux中的Reducers负责响应操作而进行的状态修改。 <code>reducer</code>将<code>state</code>和<code>action</code>作为参数,并且它总是返回一个新<code>state</code> 。重要的是要看到这是减速器的<strong>唯一</strong>作用。它没有任何副作用 - 它从不调用API端点,它从来没有任何隐藏的意外。 reducer只是一个纯函数,它接受状态和动作,然后返回新状态。 Redux的另一个关键原则是<code>state</code>是只读的。换句话说, <code>reducer</code>函数必须<strong>始终</strong>返回一个新的<code>state</code>副本,而不是直接修改状态。 Redux不强制执行状态不变性,但是,您负责在reducer函数的代码中强制执行它。你将在以后的挑战中练习这一点。 </section> <add><section id='description'> <add>在一个 action 被创建并 dispatch 之后,Redux store 需要知道如何响应该操作。这就是<code>reducer</code>函数存在的意义。Redux 中的 Reducers 负责响应 action 然后进行状态的修改。<code>reducer</code>将<code>state</code>和<code>action</code>作为参数,并且它总是返回一个新的<code>state</code>。我们要知道这是 reducer 的<strong>唯一</strong>的作用。它不应有任何其他的作用:比如它不应调用 API 接口,也不应存在任何潜在的副作用。reducer 只是一个接受状态和动作,然后返回新状态的纯函数。 <add>Redux 的另一个关键原则是<code>state</code>是只读的。换句话说,<code>reducer</code>函数必须<strong>始终</strong>返回一个新的<code>state</code>,并且永远不会直接修改状态。Redux 不强制改变状态,但是你需要在你的 reducer 函数的代码中强制执行它,你将在以后的挑战中练习这一点。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">代码编辑器具有前面的示例以及为您启动<code>reducer</code>功能。填写<code>reducer</code>函数的主体,这样如果它收到<code>&#39;LOGIN&#39;</code>类型的动作,它将返回一个<code>login</code>设置为<code>true</code>的状态对象。否则,它返回当前<code>state</code> 。请注意,当前<code>state</code>和调度的<code>action</code>将传递给reducer,因此您可以使用<code>action.type</code>直接访问操作的类型。 </section> <add><section id='instructions'> <add>代码编辑器中具有前面的示例以及一个<code>reducer</code>函数。你需要完善<code>reducer</code>函数的内容,使得它如果收到类型为<code>'LOGIN'</code>的action,它将返回一个将<code>login</code>设置为<code>true</code>的 state 对象。否则,它就返回当前的<code>state</code>。请注意,当前<code>state</code>和dispatch的<code>action</code>将被传递给reducer,因此你可以使用<code>action.type</code>直接获取 action 的类型。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 调用函数<code>loginAction</code>应该返回一个对象,其type属性设置为字符串<code>LOGIN</code> 。 <add> - text: '调用<code>loginAction</code>函数应该返回一个对象 {type:"LOGIN"}。' <ide> testString: assert(loginAction().type === 'LOGIN'); <del> - text: 应使用属性<code>login</code>设置为<code>false</code>的对象初始化存储。 <add> - text: 'store 应该初始化一个对象 {login:false}。' <ide> testString: assert(store.getState().login === false); <del> - text: 调度<code>loginAction</code>应该将store状态中的<code>login</code>属性更新为<code>true</code> 。 <add> - text: dispatch <code>loginAction</code>后应将 store 中 state 的<code>login</code>值更新为<code>true</code>。 <ide> testString: assert((function() { const initialState = store.getState(); store.dispatch(loginAction()); const afterState = store.getState(); return initialState.login === false && afterState.login === true })()); <del> - text: 如果操作不是<code>LOGIN</code>类型,则存储应返回当前状态。 <add> - text: 如果 action 的类型不是<code>LOGIN</code>,那么 store 应返回当前的 state。 <ide> testString: 'assert((function() { store.dispatch({type: ''__TEST__ACTION__''}); let afterTest = store.getState(); return typeof afterTest === ''object'' && afterTest.hasOwnProperty(''login'') })());' <ide> <ide> ``` <ide> const defaultState = { <ide> }; <ide> <ide> const reducer = (state = defaultState, action) => { <del> // change code below this line <add> // 修改此行下方的代码 <ide> <del> // change code above this line <add> // 修改此行上方的代码 <ide> }; <ide> <ide> const store = Redux.createStore(reducer); <ide> const loginAction = () => { <ide> type: 'LOGIN' <ide> } <ide> }; <del> <ide> ``` <ide> <ide> </div> <ide> const loginAction = () => { <ide> ## Solution <ide> <section id='solution'> <ide> <add> <ide> ```js <del>// solution required <add>const defaultState = { <add> login: false <add>}; <add> <add>const reducer = (state = defaultState, action) => { <add> <add> if (action.type === 'LOGIN') { <add> return {login: true} <add> } <add> <add> else { <add> return state <add> } <add> <add>}; <add> <add>const store = Redux.createStore(reducer); <add> <add>const loginAction = () => { <add> return { <add> type: 'LOGIN' <add> } <add>}; <ide> ``` <ide> <del>/section> <add></section> <ide><path>curriculum/challenges/chinese/03-front-end-libraries/redux/never-mutate-state.chinese.md <ide> id: 5a24c314108439a4d4036158 <ide> title: Never Mutate State <ide> challengeType: 6 <ide> isRequired: false <del>videoUrl: '' <del>localeTitle: 从不改变国家 <add>forumTopicId: 301445 <add>localeTitle: 永不改变状态 <ide> --- <ide> <ide> ## Description <del><section id="description">这些最后的挑战描述了在Redux中实施状态不变性关键原则的几种方法。不可变状态意味着您永远不会直接修改状态,而是返回状态的新副本。如果你随着时间的推移拍摄了一个Redux应用程序状态的快照,你会看到<code>state 1</code> , <code>state 2</code> , <code>state 3</code> , <code>state 4</code> , <code>...</code>等等,其中每个状态可能与最后一个状态相似,但每个状态是一个独特的数据。事实上,这种不变性提供了您可能听说过的时间旅行调试等功能。 Redux不会在其商店或减少者中主动强制执行状态不变性,而责任落在程序员身上。幸运的是,JavaScript(尤其是ES6)提供了一些有用的工具,可用于强制执行状态的不变性,无论是<code>string</code> , <code>number</code> , <code>array</code>还是<code>object</code> 。请注意,字符串和数字是原始值,并且本质上是不可变的。换句话说,3总是3.您不能更改数字3的值。但是, <code>array</code>或<code>object</code>是可变的。实际上,您的状态可能包含<code>array</code>或<code>object</code> ,因为它们是用于表示许多类型信息的有用数据结构。 </section> <add><section id='description'> <add>这些最后的挑战描述了在 Redux 中强制执行状态不变性关键原则的几种方法。不可变状态意味着你永远不会直接修改状态,而是返回一个新的状态副本。 <add>如果你拍摄 Redux 应用程序状态的快照,你会看到类似<code>state 1</code>,<code>state 2</code>,<code>state 3</code>,<code>state 4</code>,<code>...</code>等等,每个状态可能与最后一个状态相似,但每个状态都是一个独特的数据。事实上,这种不变性是什么提供了你可能听说过的时间旅行调试等功能。 <add>Redux 并没有积极地在其 store 或者 reducer 中强制执行状态不变性,责任落在程序员身上。幸运的是,JavaScript(尤其是 ES6)提供了一些有用的工具,可以用来强制执行状态的不变性,无论是<code>string</code>,<code>number</code>,<code>array</code>或<code>object</code>。请注意,字符串和数字是原始值,并且本质上是不可变的。换句话说,3 总是 3,你不能改变数字 3 的值。然而,<code>array</code>或<code>object</code>是可变的。实际上,你的状态可能包括<code>array</code>或<code>object</code>,因为它们在表示许多类型信息的数据结构时非常有用。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">代码编辑器中有一个<code>store</code>和<code>reducer</code>器,用于管理待办事项。完成在<code>ADD_TO_DO</code>中写入<code>ADD_TO_DO</code>情况,以向状态附加新的待办事项。使用标准JavaScript或ES6可以通过几种方法实现此目的。看看是否可以找到一种方法来返回一个新数组,其中<code>action.todo</code>的项目附加到结尾。 </section> <add><section id='instructions'> <add>代码编辑器中有一个<code>store</code>和<code>reducer</code>,用于管理待办事项。完成在 reducer 中编写<code>ADD_TO_DO</code>的情况,使用标准 JavaScript 或 ES6 可以通过几种方法来实现这一目标。看看是否可以找到一种方法来返回一个新数组,其中来自<code>action.todo</code>的项目添加到数组的末尾。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: Redux存储应该存在并使用等于代码编辑器中的<code>todos</code>数组的状态进行初始化。 <add> - text: Redux store 应该在代码编辑器中存在并使用名字为<code>todos</code>的数组进行状态初始化。 <ide> testString: assert((function() { const todos = [ 'Go to the store', 'Clean the house', 'Cook dinner', 'Learn to code' ]; const initialState = store.getState(); return Array.isArray(initialState) && initialState.join(',') === todos.join(','); })()); <ide> - text: <code>addToDo</code>和<code>immutableReducer</code>都应该是函数。 <ide> testString: assert(typeof addToDo === 'function' && typeof immutableReducer === 'function'); <del> - text: 在Redux存储上调度<code>ADD_TO_DO</code>类型的操作应该添加<code>todo</code> ,不应该改变状态。 <add> - text: 在 Redux store 上 dispatch 一个类型为<code>ADD_TO_DO</code>的aciton应该添加一个<code>todo</code>项,并且不应该改变 state。 <ide> testString: assert((function() { const initialState = store.getState(); const isFrozen = DeepFreeze(initialState); store.dispatch(addToDo('__TEST__TO__DO__')); const finalState = store.getState(); const expectedState = [ 'Go to the store', 'Clean the house', 'Cook dinner', 'Learn to code', '__TEST__TO__DO__' ]; return( isFrozen && DeepEqual(finalState, expectedState)); })()); <ide> <ide> ``` <ide> tests: <ide> ```jsx <ide> const ADD_TO_DO = 'ADD_TO_DO'; <ide> <del>// A list of strings representing tasks to do: <add>// 一个字符串列表表示要做的任务 <ide> const todos = [ <ide> 'Go to the store', <ide> 'Clean the house', <ide> const todos = [ <ide> const immutableReducer = (state = todos, action) => { <ide> switch(action.type) { <ide> case ADD_TO_DO: <del> // don't mutate state here or the tests will fail <add> // 不要在这里改变 state,否则测试将失败 <ide> return <ide> default: <ide> return state; <ide> } <ide> }; <ide> <del>// an example todo argument would be 'Learn React', <add>// 一个 todo 的例子是 'Learn React', <ide> const addToDo = (todo) => { <ide> return { <ide> type: ADD_TO_DO, <ide> const addToDo = (todo) => { <ide> } <ide> <ide> const store = Redux.createStore(immutableReducer); <del> <ide> ``` <ide> <ide> </div> <ide> const store = Redux.createStore(immutableReducer); <ide> ## Solution <ide> <section id='solution'> <ide> <add> <ide> ```js <del>// solution required <add>const ADD_TO_DO = 'ADD_TO_DO'; <add> <add>// A list of strings representing tasks to do: <add>const todos = [ <add> 'Go to the store', <add> 'Clean the house', <add> 'Cook dinner', <add> 'Learn to code', <add>]; <add> <add>const immutableReducer = (state = todos, action) => { <add> switch(action.type) { <add> case ADD_TO_DO: <add> return state.concat(action.todo); <add> default: <add> return state; <add> } <add>}; <add> <add>// an example todo argument would be 'Learn React', <add>const addToDo = (todo) => { <add> return { <add> type: ADD_TO_DO, <add> todo <add> } <add>} <add> <add>const store = Redux.createStore(immutableReducer); <ide> ``` <ide> <del>/section> <add></section> <ide><path>curriculum/challenges/chinese/03-front-end-libraries/redux/register-a-store-listener.chinese.md <ide> id: 5a24c314108439a4d4036153 <ide> title: Register a Store Listener <ide> challengeType: 6 <ide> isRequired: false <del>videoUrl: '' <del>localeTitle: 注册商店监听器 <add>forumTopicId: 301446 <add>localeTitle: 注册 Store 监听器 <ide> --- <ide> <ide> ## Description <del><section id="description">您可以在Redux <code>store</code>对象上访问的另一种方法是<code>store.subscribe()</code> 。这允许您将监听器函数订阅到商店,只要针对商店调度操作,就会调用这些函数。此方法的一个简单用途是为您的商店订阅一个功能,只需在每次收到操作并更新商店时记录消息。 </section> <add><section id='description'> <add>在 Redux <code>store</code>对象上访问数据的另一种方法是<code>store.subscribe()</code>。这允许你将监听器函数订阅到 store,只要一个 action 被 dispatch 就会调用它们。这个方法的一个简单用途是为你的 store 订阅一个函数,它只是在每次收到一个 action 并且更新 store 时记录一条消息。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">编写一个回调函数,每次商店收到一个动作时,它会递增全局变量<code>count</code> ,并将此函数传递给<code>store.subscribe()</code>方法。您将看到<code>store.dispatch()</code>连续三次被调用,每次都直接传入一个操作对象。观察操作调度之间的控制台输出以查看更新。 </section> <add><section id='instructions'> <add>编写一个回调函数,每次 store 收到一个 action 时,它会递增全局变量<code>count</code>,并将此函数传递给<code>store.subscribe()</code>方法。你将会看到<code>store.dispatch()</code>连续三次被调用,每次都直接传入一个 action 对象。观察 dispatch action 之间的控制台输出,看看是否发生了更新。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 在商店上调度<code>ADD</code>操作应该将状态增加<code>1</code> 。 <add> - text: 在 store 上 dispatch <code>ADD</code> action 应该使计数器增加<code>1</code>。 <ide> testString: 'assert((function() { const initialState = store.getState(); store.dispatch({ type: ''ADD'' }); const newState = store.getState(); return newState === (initialState + 1); })());' <del> - text: 应该有一个使用<code>store.subscribe</code>订阅商店的监听器功能。 <add> - text: 应该有一个监听函数<code>store.subscribe</code>订阅 store。 <ide> testString: getUserInput => assert(getUserInput('index').includes('store.subscribe(')); <del> - text: <code>store.subscribe</code>的回调还应该在存储更新时增加全局<code>count</code>变量。 <add> - text: 在更新 store 时,<code>store.subscribe</code>应该在回调中使全局变量<code>count</code>增加。 <ide> testString: assert(store.getState() === count); <ide> <ide> ``` <ide> const reducer = (state = 0, action) => { <ide> <ide> const store = Redux.createStore(reducer); <ide> <del>// global count variable: <add>// 用于计数的全局变量: <ide> let count = 0; <ide> <del>// change code below this line <add>// 修改此行下方的代码 <ide> <del>// change code above this line <add>// 修改此行上方的代码 <ide> <ide> store.dispatch({type: ADD}); <ide> console.log(count); <ide> store.dispatch({type: ADD}); <ide> console.log(count); <ide> store.dispatch({type: ADD}); <ide> console.log(count); <del> <ide> ``` <ide> <ide> </div> <ide> console.log(count); <ide> <ide> ```jsx <ide> count = 0; <del> <ide> ``` <ide> <ide> </div> <ide> count = 0; <ide> ## Solution <ide> <section id='solution'> <ide> <add> <ide> ```js <del>// solution required <add>const ADD = 'ADD'; <add> <add>const reducer = (state = 0, action) => { <add> switch(action.type) { <add> case ADD: <add> return state + 1; <add> default: <add> return state; <add> } <add>}; <add> <add>const store = Redux.createStore(reducer); <add> let count = 0; <add>// change code below this line <add> <add>store.subscribe( () => <add> { <add> count++; <add> } <add>); <add> <add>// change code above this line <add> <add>store.dispatch({type: ADD}); <add>store.dispatch({type: ADD}); <add>store.dispatch({type: ADD}); <ide> ``` <ide> <del>/section> <add></section> <ide><path>curriculum/challenges/chinese/03-front-end-libraries/redux/remove-an-item-from-an-array.chinese.md <ide> id: 5a24c314108439a4d403615a <ide> title: Remove an Item from an Array <ide> challengeType: 6 <ide> isRequired: false <del>videoUrl: '' <add>forumTopicId: 301447 <ide> localeTitle: 从数组中删除项目 <ide> --- <ide> <ide> ## Description <del><section id="description">是时候练习从数组中删除项目了。扩展运算符也可以在这里使用。其他有用的JavaScript方法包括<code>slice()</code>和<code>concat()</code> 。 </section> <add><section id='description'> <add>是时候练习从数组中删除项目了。扩展运算符也可以在这里使用。其他有用的JavaScript方法包括<code>slice()</code>和<code>concat()</code>。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">修改了reducer和action creator,以根据项目的索引从数组中删除项目。完成编写reducer以便返回一个新的状态数组,并删除特定索引处的项。 </section> <add><section id='instructions'> <add>reducer 和 action creator 被修改为根据项目的索引从数组中删除一个项目。完成编写 reducer 以便返回一个新的状态数组,并删除特定索引处的项目。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 'Redux存储应该存在并初始化为等于<code>[0,1,2,3,4,5]</code>的状态' <add> - text: Redux store 应该存在并初始化一个<code>[0,1,2,3,4,5]</code>的状态。 <ide> testString: assert((function() { const initialState = store.getState(); return (Array.isArray(initialState) === true && DeepEqual(initialState, [0, 1, 2, 3, 4, 5])); })()); <del> - text: <code>removeItem</code>和<code>immutableReducer</code>都应该是函数。 <add> - text: <code>removeItem</code>和<code>immutableReducer</code>都应该是一个函数。 <ide> testString: assert(typeof removeItem === 'function' && typeof immutableReducer === 'function'); <del> - text: 调度<code>removeItem</code>动作创建者应该从状态中删除项目,不应该改变状态。 <add> - text: dispatch <code>removeItem</code> action creator 应该从 state 中删除项目,不应该改变 state。 <ide> testString: assert((function() { const initialState = store.getState(); const isFrozen = DeepFreeze(initialState); store.dispatch(removeItem(3)); const state_1 = store.getState(); store.dispatch(removeItem(2)); const state_2 = store.getState(); store.dispatch(removeItem(0)); store.dispatch(removeItem(0)); store.dispatch(removeItem(0)); const state_3 = store.getState(); return isFrozen && DeepEqual(state_1, [0, 1, 2, 4, 5]) && DeepEqual(state_2, [0, 1, 4, 5]) && DeepEqual(state_3, [5]); })()); <ide> <ide> ``` <ide> tests: <ide> const immutableReducer = (state = [0,1,2,3,4,5], action) => { <ide> switch(action.type) { <ide> case 'REMOVE_ITEM': <del> // don't mutate state here or the tests will fail <add> // 不要在这里改变 state 否则测试会失败。 <ide> return <ide> default: <ide> return state; <ide> const removeItem = (index) => { <ide> } <ide> <ide> const store = Redux.createStore(immutableReducer); <del> <ide> ``` <ide> <ide> </div> <ide> const store = Redux.createStore(immutableReducer); <ide> ## Solution <ide> <section id='solution'> <ide> <add> <ide> ```js <del>// solution required <add>const immutableReducer = (state = [0,1,2,3,4,5], action) => { <add> switch(action.type) { <add> case 'REMOVE_ITEM': <add> return [ <add> ...state.slice(0, action.index), <add> ...state.slice(action.index + 1) <add> ]; <add> default: <add> return state; <add> } <add>}; <add> <add>const removeItem = (index) => { <add> return { <add> type: 'REMOVE_ITEM', <add> index <add> } <add>} <add> <add>const store = Redux.createStore(immutableReducer); <ide> ``` <ide> <del>/section> <add></section> <ide><path>curriculum/challenges/chinese/03-front-end-libraries/redux/send-action-data-to-the-store.chinese.md <ide> id: 5a24c314108439a4d4036155 <ide> title: Send Action Data to the Store <ide> challengeType: 6 <ide> isRequired: false <del>videoUrl: '' <del>localeTitle: 将操作数据发送到商店 <add>forumTopicId: 301448 <add>localeTitle: 发送 Action Data 给 Store <ide> --- <ide> <ide> ## Description <del><section id="description">到目前为止,您已经学会了如何将操作分派给Redux存储,但到目前为止,这些操作还没有包含除<code>type</code>之外的任何信息。您还可以发送特定数据以及您的操作。事实上,这是非常常见的,因为动作通常源于一些用户交互,并倾向于携带一些数据。 Redux商店经常需要了解这些数据。 </section> <add><section id='description'> <add>到目前为止,你已经学会了如何将 action dispatch 给 Redux store,但到目前为止,这些 action 并未包含除 <code>type</code>之外的任何信息。你还可以发送特定数据和 action 一起。事实上,这是非常常见的,因为 action 通常源于一些用户交互,并且往往会携带一些数据,Redux store 经常需要知道这些数据。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">在代码编辑器中定义了一个基本的<code>notesReducer()</code>和一个<code>addNoteText()</code>动作创建器。完成<code>addNoteText()</code>函数的主体,以便它返回一个<code>action</code>对象。该对象应包含值为<code>ADD_NOTE</code>的<code>type</code>属性,以及设置为传递给action creator的<code>note</code>数据的<code>text</code>属性。当您致电操作创建者时,您将传递可以访问该对象的特定注释信息。接下来,完成在<code>notesReducer()</code>编写<code>switch</code>语句。您需要添加一个处理<code>addNoteText()</code>操作的案例。只要存在类型为<code>ADD_NOTE</code>的操作,就应该触发此情况,并且应该将传入<code>action</code>的<code>text</code>属性作为新<code>state</code> 。该操作将在代码底部发送。完成后,运行代码并观察控制台。这就是将特定于操作的数据发送到商店并在更新存储<code>state</code>时使用它所需的全部内容。 </section> <add><section id='instructions'> <add>在代码编辑器中定义了一个基础的<code>notesReducer()</code>和<code>addNoteText()</code> action creator。完成<code>addNoteText()</code>函数的主体,这样它就会返回一个<code>action</code>对象。该对象应该包含一个<code>type</code>属性,其值为<code>ADD_NOTE</code>,还有一个<code>text</code>属性通过 action creator 将值设置为<code>note</code>。当你调用 action creator 时,你需要传入可以访问该对象的特定注释信息。 <add>接下来,完成在<code>notesReducer()</code>中编写的<code>switch</code>语句。你需要添加一个处理<code>addNoteText()</code>操作的选项。只要存在<code>ADD_NOTE</code>类型的 action,就应该触发 case,并且它应该在传入的<code>action</code>上返回<code>text</code>属性作为新的<code>state</code> <add>这个 action 将在代码底部发送。一旦完成后,运行代码并观察控制台。这就是将特定于 action 的数据发送到 store 并在更新 store <code>state</code>时使用它所需的全部内容。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 动作创建者<code>addNoteText</code>应返回具有键<code>type</code>和<code>text</code>的对象。 <add> - text: action creator <code>addNoteText</code>应该返回一个包含<code>type</code>和<code>text</code>的对象。 <ide> testString: assert((function() { const addNoteFn = addNoteText('__TEST__NOTE'); return addNoteFn.type === ADD_NOTE && addNoteFn.text === '__TEST__NOTE' })()); <del> - text: 使用<code>addNoteText</code>操作创建程序调度<code>ADD_NOTE</code>类型的操作应将<code>state</code>更新为传递给操作创建者的字符串。 <add> - text: dispatch 一个 action creator 是<code>addNoteText</code>的action<code>ADD_NOTE</code>,应将<code>state</code>更新为 action creator 传递的字符串。 <ide> testString: assert((function() { const initialState = store.getState(); store.dispatch(addNoteText('__TEST__NOTE')); const newState = store.getState(); return initialState !== newState && newState === '__TEST__NOTE' })()); <ide> <ide> ``` <ide> const ADD_NOTE = 'ADD_NOTE'; <ide> <ide> const notesReducer = (state = 'Initial State', action) => { <ide> switch(action.type) { <del> // change code below this line <add> // 修改此行下方的代码 <ide> <del> // change code above this line <add> // 修改此行上方的代码 <ide> default: <ide> return state; <ide> } <ide> }; <ide> <ide> const addNoteText = (note) => { <del> // change code below this line <add> // 修改此行下方的代码 <ide> <del> // change code above this line <add> // 修改此行上方的代码 <ide> }; <ide> <ide> const store = Redux.createStore(notesReducer); <ide> <ide> console.log(store.getState()); <ide> store.dispatch(addNoteText('Hello!')); <ide> console.log(store.getState()); <del> <ide> ``` <ide> <ide> </div> <ide> console.log(store.getState()); <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add>const ADD_NOTE = 'ADD_NOTE'; <add> <add>const notesReducer = (state = 'Initial State', action) => { <add> switch(action.type) { <add> // change code below this line <add> case ADD_NOTE: <add> return action.text; <add> // change code above this line <add> default: <add> return state; <add> } <add>}; <add> <add>const addNoteText = (note) => { <add> // change code below this line <add> return { <add> type: ADD_NOTE, <add> text: note <add> } <add> // change code above this line <add>}; <add> <add>const store = Redux.createStore(notesReducer); <add> <add>console.log(store.getState()); <add>store.dispatch(addNoteText('Hello Redux!')); <add>console.log(store.getState()); <ide> ``` <ide> <del>/section> <add></section> <ide><path>curriculum/challenges/chinese/03-front-end-libraries/redux/use-a-switch-statement-to-handle-multiple-actions.chinese.md <ide> id: 5a24c314108439a4d4036151 <ide> title: Use a Switch Statement to Handle Multiple Actions <ide> challengeType: 6 <ide> isRequired: false <del>videoUrl: '' <del>localeTitle: 使用Switch语句处理多个操作 <add>forumTopicId: 301449 <add>localeTitle: 使用 Switch 语句处理多个 Actions <ide> --- <ide> <ide> ## Description <del><section id="description">您可以告诉Redux商店如何处理多种操作类型。假设您在Redux商店中管理用户身份验证。您希望在用户登录和注销时具有状态表示。您使用经过<code>authenticated</code>的属性的单个状态对象来表示它。您还需要动作创建者创建与用户登录和用户注销相对应的操作,以及操作对象本身。 </section> <add><section id='description'> <add>你可以定义 Redux store 如何处理多种 action 类型。比如你正在 Redux store 中进行用户身份验证,如果你希望用户在登录和注销时具有状态的响应,你可以使用具有<code>authenticated</code>属性的单个的 state 对象。你还需要使用 action creators 创建与用户登录和用户注销相对应的 action,以及 action 对象本身。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">代码编辑器为您设置了商店,操作和操作创建器。填写<code>reducer</code>函数以处理多个身份验证操作。在<code>reducer</code>使用JavaScript <code>switch</code>语句来响应不同的操作事件。这是编写Redux减速器的标准模式。 switch语句应该切换<code>action.type</code>并返回适当的身份验证状态。 <strong>注意:</strong>此时,不要担心状态不变性,因为在这个例子中它很小而且简单。对于每个操作,您可以返回一个新对象 - 例如, <code>{authenticated: true}</code> 。另外,不要忘记在switch语句中写一个返回当前<code>state</code>的<code>default</code>大小写。这很重要,因为一旦您的应用程序有多个Reducer,它们都会在执行操作调度时运行,即使操作与该reducer无关。在这种情况下,您需要确保返回当前<code>state</code> 。 </section> <add><section id='instructions'> <add>代码编辑器为你创建了 store、actions、action creators。通过编写<code>reducer</code>函数来处理多个身份验证操作。可以在<code>reducer</code>通过使用 JavaScript 的<code>switch</code>来响应不同的 action 事件。这是编写 Redux reducer 时的标准模式,switch 语句选择<code>action.type</code>中的一个值并返回相应的身份验证状态。 <add><strong>注意:</strong>&nbsp;此时,不要担心 state 的不变性,因为在这个示例中它很小而且很简单。所以对于每个操作你都可以返回一个新对象,比如<code>{authenticated:true}</code>。另外,不要忘记在 switch 语句中写一个<code>default</code> case,返回当前的<code>state</code>。这是很重要的,因为一旦你的程序有多个 reducer,当一个 action 被 dispatch 时它们都会运行,即使 action 与该 reducer 无关。在这种情况下,你要确保返回当前的<code>state</code> <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 调用函数<code>loginUser</code>应该返回一个对象,其type属性设置为字符串<code>LOGIN</code> 。 <add> - text: '调用<code>loginUser</code>函数应该返回一个 {type:"LOGIN"} 对象。' <ide> testString: assert(loginUser().type === 'LOGIN'); <del> - text: 调用函数<code>logoutUser</code>应该返回一个对象,其type属性设置为字符串<code>LOGOUT</code> 。 <add> - text: '调用<code>logoutUser</code>函数应该返回一个 {type:"LOGOUT"} 对象。' <ide> testString: assert(logoutUser().type === 'LOGOUT'); <del> - text: 应使用经过<code>authenticated</code>属性设置为<code>false</code>的对象初始化存储。 <add> - text: 'store 应该设置一个初始化对象 {authenticated:false}。' <ide> testString: assert(store.getState().authenticated === false); <del> - text: 调度<code>loginUser</code>应该将store状态中的<code>authenticated</code>属性更新为<code>true</code> 。 <add> - text: dispatch <code>loginUser</code>应该将 store 中的 state 的<code>authenticated</code>值更新为<code>true</code>。 <ide> testString: assert((function() { const initialState = store.getState(); store.dispatch(loginUser()); const afterLogin = store.getState(); return initialState.authenticated === false && afterLogin.authenticated === true })()); <del> - text: 调度<code>logoutUser</code>应将store状态中的<code>authenticated</code>属性更新为<code>false</code> 。 <add> - text: dispatch <code>logoutUser</code>应该将 store 中的 state 的<code>authenticated</code>值更新为<code>false</code>。 <ide> testString: assert((function() { store.dispatch(loginUser()); const loggedIn = store.getState(); store.dispatch(logoutUser()); const afterLogout = store.getState(); return loggedIn.authenticated === true && afterLogout.authenticated === false })()); <del> - text: <code>authReducer</code>函数应该使用<code>switch</code>语句处理多个动作类型。 <add> - text: <code>authReducer</code>函数应该使用<code>switch</code>语句处理多个 action 类型。 <ide> testString: getUserInput => assert( getUserInput('index').toString().includes('switch') && getUserInput('index').toString().includes('case') && getUserInput('index').toString().includes('default')); <ide> <ide> ``` <ide> const defaultState = { <ide> }; <ide> <ide> const authReducer = (state = defaultState, action) => { <del> // change code below this line <add>// 修改此行下方的代码 <ide> <del> // change code above this line <add>// 修改此行上方的代码 <ide> }; <ide> <ide> const store = Redux.createStore(authReducer); <ide> const logoutUser = () => { <ide> type: 'LOGOUT' <ide> } <ide> }; <del> <ide> ``` <ide> <ide> </div> <ide> const logoutUser = () => { <ide> ## Solution <ide> <section id='solution'> <ide> <add> <ide> ```js <del>// solution required <add>const defaultState = { <add> authenticated: false <add>}; <add> <add>const authReducer = (state = defaultState, action) => { <add> <add> switch (action.type) { <add> <add> case 'LOGIN': <add> return { <add> authenticated: true <add> } <add> <add> case 'LOGOUT': <add> return { <add> authenticated: false <add> } <add> <add> default: <add> return state; <add> <add> } <add> <add>}; <add> <add>const store = Redux.createStore(authReducer); <add> <add>const loginUser = () => { <add> return { <add> type: 'LOGIN' <add> } <add>}; <add> <add>const logoutUser = () => { <add> return { <add> type: 'LOGOUT' <add> } <add>}; <ide> ``` <ide> <del>/section> <add></section> <ide><path>curriculum/challenges/chinese/03-front-end-libraries/redux/use-const-for-action-types.chinese.md <ide> id: 5a24c314108439a4d4036152 <ide> title: Use const for Action Types <ide> challengeType: 6 <ide> isRequired: false <del>videoUrl: '' <del>localeTitle: 将const用于Action Types <add>forumTopicId: 301450 <add>localeTitle: 使用 const 声明 Action Types <ide> --- <ide> <ide> ## Description <del><section id="description">使用Redux时的一种常见做法是将操作类型指定为只读常量,然后在使用它们的任何地方引用这些常量。您可以重构您正在使用的代码,将操作类型编写为<code>const</code>声明。 </section> <add><section id='description'> <add>在使用 Redux 时的一个常见做法是将操作类型指定为只读,然后在任何使用它们的地方引用这些常量。你可以通过将 action types 使用<code>const</code>声明重构你正在使用的代码。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">将<code>LOGIN</code>和<code>LOGOUT</code>声明为<code>const</code>值,并将它们分别分配给字符串<code>&#39;LOGIN&#39;</code>和<code>&#39;LOGOUT&#39;</code> 。然后,编辑<code>authReducer()</code>和动作创建者以引用这些常量而不是字符串值。 <strong>注意:</strong>通常以全部大写形式写常量,这也是Redux中的标准做法。 </section> <add><section id='instructions'> <add>将<code>LOGIN</code>和<code>LOGOUT</code>声明为<code>const</code>类型的值,并为它们分别分配字符串<code>'LOGIN'</code>和<code>'LOGOUT'</code>。然后,编辑<code>authReducer()</code>和 action creators 来引用这些常量而不是字符串值。 <add><strong>注意:</strong>&nbsp;通常以全部大写形式写出常量,这也是 Redux 的标准做法。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 调用函数<code>loginUser</code>应该返回一个对象,其<code>type</code>属性设置为字符串<code>LOGIN</code> 。 <add> - text: '调用<code>loginUser</code>函数应该返回一个 {type:"LOGIN"} 对象。' <ide> testString: assert(loginUser().type === 'LOGIN'); <del> - text: 调用函数<code>logoutUser</code>应该返回一个对象,其<code>type</code>属性设置为字符串<code>LOGOUT</code> 。 <add> - text: '调用<code>logoutUser</code>函数应该返回一个 {type:\"LOGOUT\"} 对象。' <ide> testString: assert(logoutUser().type === 'LOGOUT'); <del> - text: 应使用属性<code>login</code>设置为<code>false</code>的对象初始化存储。 <add> - text: store 应该初始化一个对象 {login:false}。 <ide> testString: assert(store.getState().authenticated === false); <del> - text: 调度<code>loginUser</code>应该将store状态中的<code>login</code>属性更新为<code>true</code> 。 <add> - text: dispatch <code>loginUser</code>以后应将 store 中的 state 的<code>login</code>值更新为<code>true</code>。 <ide> testString: assert((function() { const initialState = store.getState(); store.dispatch(loginUser()); const afterLogin = store.getState(); return initialState.authenticated === false && afterLogin.authenticated === true })()); <del> - text: 调度<code>logoutUser</code>应将store状态中的<code>login</code>属性更新为<code>false</code> 。 <add> - text: dispatch <code>logoutUser</code>应将 store 中的 state 的<code>login</code>值更新为<code>false</code>。 <ide> testString: assert((function() { store.dispatch(loginUser()); const loggedIn = store.getState(); store.dispatch(logoutUser()); const afterLogout = store.getState(); return loggedIn.authenticated === true && afterLogout.authenticated === false })()); <del> - text: <code>authReducer</code>函数应该使用switch语句处理多个动作类型。 <add> - text: <code>authReducer</code>函数应该使用 switch 语句处理多个 action 类型。 <ide> testString: getUserInput => assert((function() { return typeof authReducer === 'function' && getUserInput('index').toString().includes('switch') && getUserInput('index').toString().includes('case') && getUserInput('index').toString().includes('default') })()); <del> - text: <code>LOGIN</code>和<code>LOGOUT</code>应声明为<code>const</code>值,并应分配<code>LOGIN</code>和<code>LOGOUT</code>字符串。 <del> testString: getUserInput => assert((function() { const noWhiteSpace = getUserInput('index').toString().replace(/\s/g,''); return (noWhiteSpace.includes('constLOGIN=\'LOGIN\'') || noWhiteSpace.includes('constLOGIN="LOGIN"')) && (noWhiteSpace.includes('constLOGOUT=\'LOGOUT\'') || noWhiteSpace.includes('constLOGOUT="LOGOUT"')) })()); <del> - text: 动作创建者和减速器应该引用<code>LOGIN</code>和<code>LOGOUT</code>常量。 <add> - text: '应该使用<code>const LOGIN="LOGIN"</code>和<code>const LOGOUT="LOGOUT"</code>的方式声明<code>LOGIN</code>和<code>LOGOUT</code>。' <add> testString: const noWhiteSpace = code.replace(/\s/g, ''); assert(/constLOGIN=(['"`])LOGIN\1/.test(noWhiteSpace) && /constLOGOUT=(['"`])LOGOUT\1/.test(noWhiteSpace)); <add> - text: action creator 和 reducer 中应该引用<code>LOGIN</code>和<code>LOGOUT</code>常量。 <ide> testString: getUserInput => assert((function() { const noWhiteSpace = getUserInput('index').toString().replace(/\s/g,''); return noWhiteSpace.includes('caseLOGIN:') && noWhiteSpace.includes('caseLOGOUT:') && noWhiteSpace.includes('type:LOGIN') && noWhiteSpace.includes('type:LOGOUT') })()); <ide> <ide> ``` <ide> tests: <ide> <div id='jsx-seed'> <ide> <ide> ```jsx <del>// change code below this line <add>// 修改此行下方的代码 <ide> <del>// change code above this line <add>// 修改此行上方的代码 <ide> <ide> const defaultState = { <ide> authenticated: false <ide> const logoutUser = () => { <ide> type: 'LOGOUT' <ide> } <ide> }; <del> <ide> ``` <ide> <ide> </div> <ide> const logoutUser = () => { <ide> ## Solution <ide> <section id='solution'> <ide> <add> <ide> ```js <del>// solution required <add>const LOGIN = 'LOGIN'; <add>const LOGOUT = 'LOGOUT'; <add> <add>const defaultState = { <add> authenticated: false <add>}; <add> <add>const authReducer = (state = defaultState, action) => { <add> <add> switch (action.type) { <add> <add> case LOGIN: <add> return { <add> authenticated: true <add> } <add> <add> case LOGOUT: <add> return { <add> authenticated: false <add> } <add> <add> default: <add> return state; <add> <add> } <add> <add>}; <add> <add>const store = Redux.createStore(authReducer); <add> <add>const loginUser = () => { <add> return { <add> type: LOGIN <add> } <add>}; <add> <add>const logoutUser = () => { <add> return { <add> type: LOGOUT <add> } <add>}; <ide> ``` <ide> <del>/section> <add></section> <ide><path>curriculum/challenges/chinese/03-front-end-libraries/redux/use-middleware-to-handle-asynchronous-actions.chinese.md <ide> id: 5a24c314108439a4d4036156 <ide> title: Use Middleware to Handle Asynchronous Actions <ide> challengeType: 6 <ide> isRequired: false <del>videoUrl: '' <add>forumTopicId: 301451 <ide> localeTitle: 使用中间件处理异步操作 <ide> --- <ide> <ide> ## Description <del><section id="description">到目前为止,这些挑战已经避免讨论异步操作,但它们是Web开发中不可避免的一部分。在某些时候,您需要在Redux应用程序中调用异步端点,那么如何处理这些类型的请求? Redux提供专门为此目的而设计的中间件,称为Redux Thunk中间件。以下是如何在Redux中使用它的简要说明。要包含Redux Thunk中间件,请将其作为参数传递给<code>Redux.applyMiddleware()</code> 。然后,此语句作为<code>createStore()</code>函数的第二个可选参数提供。看一下编辑器底部的代码,看看这个。然后,要创建异步操作,您将在动作创建器中返回一个函数,该函数将<code>dispatch</code>作为参数。在此函数中,您可以分派操作并执行异步请求。在此示例中,使用<code>setTimeout()</code>调用模拟异步请求。在启动任何异步行为之前调度操作是很常见的,这样您的应用程序状态就知道正在请求某些数据(例如,此状态可能会显示加载图标)。然后,一旦收到数据,就会发送另一个操作,该操作将数据作为有效负载以及操作完成的信息。请记住,您将<code>dispatch</code>作为参数传递给此特殊操作创建者。这是您用于分派操作的方法,您只需将操作直接传递给调度,中间件就可以处理其余操作。 </section> <add><section id='description'> <add>目前为止的挑战都在避免讨论异步操作,但它们是 Web 开发中不可避免的一部分。在某些时候,你需要在 Redux 应用程序中使用异步请求,那么如何处理这些类型的请求?Redux 中间件专为此目的而设计,称为 Redux Thunk 中间件。这里简要介绍如何在 Redux 中使用它。 <add>如果要使用 Redux Thunk 中间件,请将其作为参数传递给<code>Redux.applyMiddleware()</code>。然后将此函数作为第二个可选参数提供给<code>createStore()</code>函数,看一下编辑器底部的代码,然后,要创建一个异步的 action,你需要在 action creator 中返回一个以<code>dispatch</code>为参数的函数。在这个函数中,你可以 dispatch action 并执行异步请求。 <add>在此示例中,使用<code>setTimeout()</code>调用模拟异步请求。通常在执行异步行为之前 dispatch action,以便应用程序状态知道正在请求某些数据(例如,这个状态可以显示加载图标)。然后,一旦收到数据,就会发送另一个 action,这个 action 完成的时间将作为数据的一个有效值。 <add>请记住,你正在通过将<code>dispatch</code>作为参数传递给这个特殊的 action creator。你用于 dispatch 你的 action 时只需将 action 直接传递给 dispatch,中间件就可以处理其余的部分。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">在<code>handleAsync()</code>动作创建器中写入两个调度。调度<code>requestingData()</code>在之前<code>setTimeout()</code>模拟API调用)。然后,在收到(假装)数据后,调度<code>receivedData()</code>操作,传入此数据。现在您知道如何在Redux中处理异步操作。其他一切继续像以前一样。 </section> <add><section id='instructions'> <add>在<code>handleAsync()</code>的 action creator 中编写两个 dispatch 事件。在<code>setTimeout()</code>(模拟 API 调用)之前 dispatch<code>requestingData()</code>。然后在收到(模拟)数据后,dispatch<code>receivedData()</code>action,传入这些数据。现在你知道如何处理 Redux 中的异步操作,其他所有操作都继续像以前一样。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: <code>requestingData</code>操作创建者应返回类型等于<code>REQUESTING_DATA</code>值的对象。 <add> - text: <code>requesData</code> action creator 应返回类型和值都为<code>REQUESTING_DATA</code>的对象。 <ide> testString: assert(requestingData().type === REQUESTING_DATA); <del> - text: <code>receivedData</code>操作创建者应返回类型等于<code>RECEIVED_DATA</code>值的对象。 <add> - text: <code>receivedData</code> action creator 应返回类型和值都等于<code>RECEIVED_DATA</code>的对象。 <ide> testString: assert(receivedData('data').type === RECEIVED_DATA); <del> - text: <code>asyncDataReducer</code>应该是一个函数。 <add> - text: <code>asyncDataReducer</code>必须是个函数。 <ide> testString: assert(typeof asyncDataReducer === 'function'); <del> - text: 调度requestedData操作创建者应该将获取的store <code>state</code>属性更新为<code>true</code> 。 <add> - text: 分发 requestedData 后 action creator 应该将 store 中的<code>state</code>的 fetching 的值更新为 <code>true</code>。 <ide> testString: assert((function() { const initialState = store.getState(); store.dispatch(requestingData()); const reqState = store.getState(); return initialState.fetching === false && reqState.fetching === true })()); <del> - text: 调度<code>handleAsync</code>应调度数据请求操作,然后在延迟后调度接收的数据操作。 <add> - text: 如果要 dispatch <code>handleAsync</code> 应先 dispatch 数据请求的 action,然后在收到请求结果后再 dispatch 接收的数据 action。 <ide> testString: assert((function() { const noWhiteSpace = handleAsync.toString().replace(/\s/g,''); return noWhiteSpace.includes('dispatch(requestingData())') === true && noWhiteSpace.includes('dispatch(receivedData(data))') === true })()); <ide> <ide> ``` <ide> const receivedData = (data) => { return {type: RECEIVED_DATA, users: data.users} <ide> <ide> const handleAsync = () => { <ide> return function(dispatch) { <del> // dispatch request action here <add> // 在这里 dispatch 请求的 action <ide> <ide> setTimeout(function() { <ide> let data = { <ide> users: ['Jeff', 'William', 'Alice'] <ide> } <del> // dispatch received data action here <add> // 在这里 dispatch 接收到的数据 action <ide> <ide> }, 2500); <ide> } <ide> const store = Redux.createStore( <ide> asyncDataReducer, <ide> Redux.applyMiddleware(ReduxThunk.default) <ide> ); <del> <ide> ``` <ide> <ide> </div> <ide> const store = Redux.createStore( <ide> ## Solution <ide> <section id='solution'> <ide> <add> <ide> ```js <del>// solution required <add>const REQUESTING_DATA = 'REQUESTING_DATA' <add>const RECEIVED_DATA = 'RECEIVED_DATA' <add> <add>const requestingData = () => { return {type: REQUESTING_DATA} } <add>const receivedData = (data) => { return {type: RECEIVED_DATA, users: data.users} } <add> <add>const handleAsync = () => { <add> return function(dispatch) { <add> dispatch(requestingData()); <add> setTimeout(function() { <add> let data = { <add> users: ['Jeff', 'William', 'Alice'] <add> } <add> dispatch(receivedData(data)); <add> }, 2500); <add> } <add>}; <add> <add>const defaultState = { <add> fetching: false, <add> users: [] <add>}; <add> <add>const asyncDataReducer = (state = defaultState, action) => { <add> switch(action.type) { <add> case REQUESTING_DATA: <add> return { <add> fetching: true, <add> users: [] <add> } <add> case RECEIVED_DATA: <add> return { <add> fetching: false, <add> users: action.users <add> } <add> default: <add> return state; <add> } <add>}; <add> <add>const store = Redux.createStore( <add> asyncDataReducer, <add> Redux.applyMiddleware(ReduxThunk.default) <add>); <ide> ``` <ide> <del>/section> <add></section> <ide><path>curriculum/challenges/chinese/03-front-end-libraries/redux/use-the-spread-operator-on-arrays.chinese.md <ide> id: 5a24c314108439a4d4036159 <ide> title: Use the Spread Operator on Arrays <ide> challengeType: 6 <ide> isRequired: false <del>videoUrl: '' <del>localeTitle: 在阵列上使用Spread Operator <add>forumTopicId: 301452 <add>localeTitle: 在数组中使用扩展运算符 <ide> --- <ide> <ide> ## Description <del><section id="description"> ES6的一个解决方案是帮助在Redux中强制执行状态不变性,它是扩展运算符: <code>...</code>扩展运算符具有各种应用程序,其中一个非常适合于从现有阵列生成新阵列的先前挑战。这是相对较新的,但常用的语法。例如,如果你有一个数组<code>myArray</code>并且写: <code>let newArray = [...myArray];</code> <code>newArray</code>现在是<code>myArray</code>的克隆。两个阵列仍然分别存在于内存中。如果你执行像<code>newArray.push(5)</code>这样的变异, <code>myArray</code>不会改变。 <code>...</code>有效地<i>将</i> <code>myArray</code>的值<i>展开</i>到一个新数组中。要克隆数组但在新数组中添加其他值,可以编写<code>[...myArray, &#39;new value&#39;]</code> 。这将返回一个由<code>myArray</code>中的值和字符串<code>&#39;new value&#39;</code>组成的新数组作为最后一个值。扩展语法可以像这样在数组组合中多次使用,但重要的是要注意它只是生成数组的浅表副本。也就是说,它只为一维数组提供不可变的数组操作。 </section> <add><section id='description'> <add>ES6 中有助于在 Redux 中强制执行状态不变性的一个解决方案是扩展运算符:<code>...</code>。扩展运算符具有很多的应用,其中一种非常适合通过一个已有的数组生成一个新数组。这是相对较新的,但常用的语法。例如,如果你有一个数组<code>myArray</code>并写: <add><code>let newArray = [...myArray];</code> <add><code>newArray</code>现在是<code>myArray</code>的克隆。两个数组仍然在内存中单独存在。如果你执行像<code>newArray.push(5)</code>这样的突变,<code>myArray</code>不会改变。<code>...</code>有效<i>将<code>myArray</code>中的值</i>传播到新数组中。要克隆数组但在新数组中添加其他值,可以编写<code>[... myArray,'new value']</code>。这将返回一个由<code>中的值组成的新数组。</code>myArray</code>和字符串<code>'new value'</code>作为最后一个值。扩展语法可以像这样在数组组合中多次使用,但重要的是要注意它只做一个浅拷贝这就是说,它只为一维数组提供了不可变的数组操作。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">添加待办事项时,使用spread运算符返回新的状态副本。 </section> <add><section id='instructions'> <add>添加待办事项时,使用 spread 运算符返回新的状态副本。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 'Redux存储应该存在并初始化为等于<code>[Do not mutate state!]</code> 。' <add> - text: Redux store 应该存在并初始化一个<code>[Do not mutate state!]</code>的状态。 <ide> testString: assert((function() { const initialState = store.getState(); return ( Array.isArray(initialState) === true && initialState[0] === 'Do not mutate state!'); })()); <del> - text: <code>addToDo</code>和<code>immutableReducer</code>都应该是函数。 <add> - text: <code>addToDo</code>和<code>immutableReducer</code>都应该是一个函数。 <ide> testString: assert(typeof addToDo === 'function' && typeof immutableReducer === 'function'); <del> - text: 在Redux存储上调度<code>ADD_TO_DO</code>类型的操作应该添加<code>todo</code> ,不应该改变状态。 <add> - text: 在 Redux store 上 dispatch 一个类型为<code>ADD_TO_DO</code> aciton 应该添加一个<code>todo</code>项,并且不应该改变 state。 <ide> testString: assert((function() { const initialState = store.getState(); const isFrozen = DeepFreeze(initialState); store.dispatch(addToDo('__TEST__TO__DO__')); const finalState = store.getState(); const expectedState = [ 'Do not mutate state!', '__TEST__TO__DO__' ]; return( isFrozen && DeepEqual(finalState, expectedState)); })()); <del> - text: 应使用扩展运算符返回新状态。 <add> - text: 应使用扩展运算符返回新的 state。 <ide> testString: getUserInput => assert(getUserInput('index').includes('...state')); <ide> <ide> ``` <ide> tests: <ide> const immutableReducer = (state = ['Do not mutate state!'], action) => { <ide> switch(action.type) { <ide> case 'ADD_TO_DO': <del> // don't mutate state here or the tests will fail <add> // 不要在这里改变 state 否则测试会失败。 <ide> return <ide> default: <ide> return state; <ide> const addToDo = (todo) => { <ide> } <ide> <ide> const store = Redux.createStore(immutableReducer); <del> <ide> ``` <ide> <ide> </div> <ide> const store = Redux.createStore(immutableReducer); <ide> ## Solution <ide> <section id='solution'> <ide> <add> <ide> ```js <del>// solution required <add>const immutableReducer = (state = ['Do not mutate state!'], action) => { <add> switch(action.type) { <add> case 'ADD_TO_DO': <add> return [ <add> ...state, <add> action.todo <add> ]; <add> default: <add> return state; <add> } <add>}; <add> <add>const addToDo = (todo) => { <add> return { <add> type: 'ADD_TO_DO', <add> todo <add> } <add>} <add> <add>const store = Redux.createStore(immutableReducer); <ide> ``` <ide> <del>/section> <add></section> <ide><path>curriculum/challenges/chinese/03-front-end-libraries/redux/write-a-counter-with-redux.chinese.md <ide> id: 5a24c314108439a4d4036157 <ide> title: Write a Counter with Redux <ide> challengeType: 6 <ide> isRequired: false <del>videoUrl: '' <del>localeTitle: 用Redux写一个计数器 <add>forumTopicId: 301453 <add>localeTitle: 用 Redux 写一个计数器 <ide> --- <ide> <ide> ## Description <del><section id="description">现在您已经了解了Redux的所有核心原则!您已经了解了如何创建操作和操作创建器,创建Redux存储,针对存储分派操作以及使用纯reducer设计状态更新。您甚至已经了解了如何使用reducer组合管理复杂状态并处理异步操作。这些示例过于简单,但这些概念是Redux的核心原则。如果您理解它们,那么您已准备好开始构建自己的Redux应用程序。接下来的挑战涵盖了有关<code>state</code>不变性的一些细节,但首先,这里是对迄今为止所学到的所有内容的回顾。 </section> <add><section id='description'> <add>现在你已经了解了 Redux 的所有核心原则!你已经了解了如何创建 action 和 action creator,创建 Redux store,通过 store dispatch action,以及使用纯粹的 reducer 设计状态更新。你甚至已经看到过如何使用 reducer 组合管理复杂状态并处理异步操作。这些例子很简单,但这些概念是 Redux 的核心原则。如果你理解它们,你就可以开始构建自己的 Redux 应用了。接下来的挑战包括关于<code>state</code>不变性的一些细节,但是,这里是对你到目前为止学到的所有内容的回顾。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">在本课程中,您将从头开始使用Redux实现一个简单的计数器。代码编辑器中提供了基础知识,但您必须填写详细信息!使用提供的名称并定义<code>incAction</code>和<code>decAction</code>操作创建者, <code>decAction</code> <code>counterReducer()</code> , <code>INCREMENT</code>和<code>DECREMENT</code>操作类型,最后定义Redux <code>store</code> 。一旦完成,您应该能够发送<code>INCREMENT</code>或<code>DECREMENT</code>操作来增加或减少<code>store</code>保存的状态。祝你好运第一个Redux应用程序! </section> <add><section id='instructions'> <add>在本课程中,你将从头开始使用 Redux 实现一个简单的计数器。基本知识在代码编辑器中提供,但你必须完成详细的内容!使用提供给你的名称并定义<code>incAction</code>和<code>decActio</code> action creator <code>counterReducer()</code>,<code>INCREMENT</code>和<code>DECREMENT</code> action 类型,最后是 Redux <code>store</code>。一旦完成,你应该能够 dispatch <code>INCREMENT</code>或<code>DECREMENT</code>动作来增加或减少<code>store</code>中保存的状态。开始构建你的第一个 Redux 应用程序吧,祝你好运! <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 动作创建者<code>incAction</code>应返回<code>type</code>等于<code>INCREMENT</code>值的动作对象 <add> - text: 'action creator <code>incAction</code>应返回一个 action 对象 {type:"INCREMENT"}。' <ide> testString: assert(incAction().type ===INCREMENT); <del> - text: 动作创建者<code>decAction</code>应与返回动作对象<code>type</code>等于的值<code>DECREMENT</code> <add> - text: 'action creator <code>decAction</code>应返回一个 action 对象 {type:"DECREMENT"}。' <ide> testString: assert(decAction().type === DECREMENT); <del> - text: Redux存储应该以0 <code>state</code>初始化。 <add> - text: Redux store 应该将<code>state</code>初始化为 0。 <ide> testString: assert(store.getState() === 0); <del> - text: 在Redux存储上调度<code>incAction</code>应该将<code>state</code>增加1。 <add> - text: 在 Redux store 上 dispatch <code>incAction</code>应该将<code>state</code>增加 1。 <ide> testString: assert((function() { const initialState = store.getState(); store.dispatch(incAction()); const incState = store.getState(); return initialState + 1 === incState })()); <del> - text: 在Redux存储上调度<code>decAction</code>应该将<code>state</code>减1。 <add> - text: 在 Redux store 上 dispatch <code>decAction</code>应该将<code>state</code>减少 1。 <ide> testString: assert((function() { const initialState = store.getState(); store.dispatch(decAction()); const decState = store.getState(); return initialState - 1 === decState })()); <del> - text: <code>counterReducer</code>应该是一个函数 <add> - text: <code>counterReducer</code>必须是一个函数。 <ide> testString: assert(typeof counterReducer === 'function'); <ide> <ide> ``` <ide> tests: <ide> <div id='jsx-seed'> <ide> <ide> ```jsx <del>const INCREMENT = null; // define a constant for increment action types <del>const DECREMENT = null; // define a constant for decrement action types <del> <del>const counterReducer = null; // define the counter reducer which will increment or decrement the state based on the action it receives <add>const INCREMENT = null; // 为增量 action 类型定义一个常量 <add>const DECREMENT = null; // 为减量 action 类型定义一个常量 <ide> <del>const incAction = null; // define an action creator for incrementing <add>const counterReducer = null; // 定义计数器,它将根据收到的action增加或减少状态 <ide> <del>const decAction = null; // define an action creator for decrementing <add>const incAction = null; // 定义一个用于递增的 action creator <ide> <del>const store = null; // define the Redux store here, passing in your reducers <add>const decAction = null; // 定义一个用于递减的 action creator <ide> <add>const store = null; // 在这里定义一个 Redux store,传递你的 reducer <ide> ``` <ide> <ide> </div> <ide> const store = null; // define the Redux store here, passing in your reducers <ide> ## Solution <ide> <section id='solution'> <ide> <add> <ide> ```js <del>// solution required <add>const INCREMENT = 'INCREMENT'; <add>const DECREMENT = 'DECREMENT'; <add> <add>const counterReducer = (state = 0, action) => { <add> switch(action.type) { <add> case INCREMENT: <add> return state + 1; <add> case DECREMENT: <add> return state - 1; <add> default: <add> return state; <add> } <add>}; <add> <add>const incAction = () => { <add> return { <add> type: INCREMENT <add> } <add>}; <add> <add>const decAction = () => { <add> return { <add> type: DECREMENT <add> } <add>}; <add> <add>const store = Redux.createStore(counterReducer); <ide> ``` <ide> <del>/section> <add></section>
17
Ruby
Ruby
use appropriate pronoun in update message
81e3aa899d6146d4e0a36246513e3a72469334bc
<ide><path>Library/Homebrew/cmd/update-report.rb <ide> def update_report <ide> unless args.preinstall? <ide> outdated_formulae = Formula.installed.count(&:outdated?) <ide> outdated_casks = Cask::Caskroom.casks.count(&:outdated?) <add> update_pronoun = if (outdated_formulae + outdated_casks) == 1 <add> "it" <add> else <add> "them" <add> end <ide> msg = "" <ide> if outdated_formulae.positive? <ide> msg += "#{Tty.bold}#{outdated_formulae}#{Tty.reset} outdated #{"formula".pluralize(outdated_formulae)}" <ide> def update_report <ide> puts_stdout_or_stderr <ide> puts_stdout_or_stderr <<~EOS <ide> You have #{msg} installed. <del> You can update them with #{Tty.bold}brew upgrade#{Tty.reset}. <add> You can update #{update_pronoun} with #{Tty.bold}brew upgrade#{Tty.reset}. <ide> EOS <ide> end <ide> end
1
PHP
PHP
fix more tests
34b4d3537c39c9bbd45e81f89a45337b82c68135
<ide><path>tests/TestCase/Console/ShellTest.php <ide> public function testRunCommandMainMissingArgument() <ide> <ide> $io->expects($this->once()) <ide> ->method('error') <del> ->with('Error: Missing required arguments. The `filename` argument is required.'); <add> ->with('Error: Missing required argument. The `filename` argument is required.'); <ide> $result = $shell->runCommand([]); <ide> $this->assertFalse($result, 'Shell should fail'); <ide> } <ide><path>tests/TestCase/TestSuite/ConsoleIntegrationTestTraitTest.php <ide> public function testExecWithMissingRequiredArg() <ide> $this->exec('integration args_and_options'); <ide> <ide> $this->assertOutputEmpty(); <del> $this->assertErrorContains('Missing required arguments'); <add> $this->assertErrorContains('Missing required argument'); <ide> $this->assertErrorContains('`arg` argument is required'); <ide> $this->assertExitCode(Shell::CODE_ERROR); <ide> }
2
Python
Python
support tpu on resnet50 using keras compile/fit
fa5b66e54b5ad70317f2f6526048d7140ebcaea9
<ide><path>official/vision/image_classification/resnet_imagenet_main.py <ide> def run(flags_obj): <ide> num_gpus=flags_obj.num_gpus, <ide> num_workers=num_workers, <ide> all_reduce_alg=flags_obj.all_reduce_alg, <del> num_packs=flags_obj.num_packs) <add> num_packs=flags_obj.num_packs, <add> tpu_address=flags_obj.tpu) <ide> <ide> if strategy: <ide> # flags_obj.enable_get_next_as_optional controls whether enabling
1
PHP
PHP
remove expectedexceptionmessage comment
c0c2415bd109721de4fb9d7328f3f264241a1bd5
<ide><path>tests/Database/DatabaseEloquentModelTest.php <ide> public function testFindMethodCallsQueryBuilderCorrectly() <ide> <ide> /** <ide> * @expectedException Illuminate\Database\Eloquent\ModelNotFoundException <del> * @expectedExceptionMessage EloquentModelFindNotFoundStub model not found <ide> */ <ide> public function testFindOrFailMethodThrowsModelNotFoundException() <ide> {
1
Ruby
Ruby
provide channel information in item
c6907f911f12cff4374d78a6f080721675e1d232
<ide><path>Library/Homebrew/livecheck/strategy/sparkle.rb <ide> def self.match?(url) <ide> Item = Struct.new( <ide> # @api public <ide> :title, <add> # @api public <add> :channel, <ide> # @api private <ide> :pub_date, <ide> # @api public <ide> def self.items_from_content(content) <ide> os = enclosure["os"] <ide> end <ide> <add> channel = item.elements["channel"]&.text <ide> url ||= item.elements["link"]&.text <ide> short_version ||= item.elements["shortVersionString"]&.text&.strip <ide> version ||= item.elements["version"]&.text&.strip <ide> def self.items_from_content(content) <ide> <ide> data = { <ide> title: title, <add> channel: channel, <ide> pub_date: pub_date, <ide> url: url, <ide> bundle_version: bundle_version, <ide><path>Library/Homebrew/test/livecheck/strategy/sparkle_spec.rb <ide> EOS <ide> <ide> appcast_with_omitted_items = appcast_xml.sub("</item>", "</item>\n#{extra_items}") <add> beta_channel_item = appcast_xml.sub( <add> first_item, <add> first_item.sub( <add> "</title", <add> "</title>\n<sparkle:channel>beta</sparkle:channel>", <add> ), <add> ) <ide> no_versions_item = <ide> appcast_xml <ide> .sub(second_item, "") <ide> { <ide> appcast: appcast_xml, <ide> appcast_with_omitted_items: appcast_with_omitted_items, <add> beta_channel_item: beta_channel_item, <ide> no_versions_item: no_versions_item, <ide> no_items: no_items, <ide> undefined_namespace: undefined_namespace_xml, <ide> let(:title_regex) { /Version\s+v?(\d+(?:\.\d+)+)\s*$/i } <ide> <ide> let(:items) { <del> { <add> items = { <ide> appcast: [ <ide> Homebrew::Livecheck::Strategy::Sparkle::Item.new( <ide> title: item_hash[0][:title], <ide> ), <ide> ], <ide> } <add> <add> beta_channel_item = items[:appcast][0].clone <add> beta_channel_item.channel = "beta" <add> items[:beta_channel_item] = [beta_channel_item, items[:appcast][1].clone] <add> <add> items <ide> } <ide> <ide> let(:versions) { [items[:appcast][0].nice_version] } <ide> expect(first_item.short_version).to eq(item_hash[0][:short_version]) <ide> expect(first_item.version).to eq(item_hash[0][:version]) <ide> <add> expect(sparkle.items_from_content(xml[:beta_channel_item])).to eq(items[:beta_channel_item]) <ide> expect(sparkle.items_from_content(xml[:no_versions_item])).to eq(items[:no_versions_item]) <ide> end <ide> end <ide> it "returns an array of version strings when given content" do <ide> expect(sparkle.versions_from_content(xml[:appcast])).to eq(versions) <ide> expect(sparkle.versions_from_content(xml[:appcast_with_omitted_items])).to eq(versions) <add> expect(sparkle.versions_from_content(xml[:beta_channel_item])).to eq(versions) <ide> expect(sparkle.versions_from_content(xml[:no_versions_item])).to eq([]) <ide> expect(sparkle.versions_from_content(xml[:undefined_namespace])).to eq(versions) <ide> end <ide> items.map { |item| item.nice_version&.sub("1", "0") } <ide> end, <ide> ).to eq(subbed_items) <add> <add> expect( <add> sparkle.versions_from_content(xml[:beta_channel_item]) do |items| <add> items.find { |item| item.channel.nil? }&.nice_version <add> end, <add> ).to eq([items[:appcast][1].nice_version]) <ide> end <ide> <ide> it "returns an array of version strings when given content, a regex, and a block" do
2
Text
Text
fix text inconsistency
35f24c60856867b984ba5ecc16493cec5b347987
<ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/basic-javascript/declare-javascript-variables.english.md <ide> forumTopicId: 17556 <ide> <section id='description'> <ide> In computer science, <dfn>data</dfn> is anything that is meaningful to the computer. JavaScript provides eight different <dfn>data types</dfn> which are <code>undefined</code>, <code>null</code>, <code>boolean</code>, <code>string</code>, <code>symbol</code>, <code>bigint</code>, <code>number</code>, and <code>object</code>. <ide> For example, computers distinguish between numbers, such as the number <code>12</code>, and <code>strings</code>, such as <code>"12"</code>, <code>"dog"</code>, or <code>"123 cats"</code>, which are collections of characters. Computers can perform mathematical operations on a number, but not on a string. <del><dfn>Variables</dfn> allow computers to store and manipulate data in a dynamic fashion. They do this by using a "label" to point to the data rather than using the data itself. Any of the seven data types may be stored in a variable. <add><dfn>Variables</dfn> allow computers to store and manipulate data in a dynamic fashion. They do this by using a "label" to point to the data rather than using the data itself. Any of the eight data types may be stored in a variable. <ide> <code>Variables</code> are similar to the x and y variables you use in mathematics, which means they're a simple name to represent the data we want to refer to. Computer <code>variables</code> differ from mathematical variables in that they can store different values at different times. <ide> We tell JavaScript to create or <dfn>declare</dfn> a variable by putting the keyword <code>var</code> in front of it, like so: <ide>
1
Text
Text
add 2.11.1 to changelog.md
e891373c5bc5e56b9468f63bb6185ea9dccb3748
<ide><path>CHANGELOG.md <ide> - [#14852](https://github.com/emberjs/ember.js/pull/14852) [PERF] only `LOG_TRANSITIONS` and `LOG_TRANSITIONS_INTERNAL` in debug <ide> - [#14854](https://github.com/emberjs/ember.js/pull/14854) [PER] only `LOG_ACTIVE_GENERATION` and `LOG_RESOLVER` in debug <ide> <add>### 2.11.1 (February 16, 2017) <add> <add>- [#14762](https://github.com/emberjs/ember.js/pull/14762) [BUGFIX] Make ember-template-compiler handle {{input}} helpers with sub-expression "type" <add>- [#14791](https://github.com/emberjs/ember.js/pull/14791) [BUGFIX] exempt routes that share a controller from duplicate assertion <add>- [#14860](https://github.com/emberjs/ember.js/pull/14860) [BUGFIX] Add back `mainContext` to loader #14859 (fixes issue with non ember-cli template compilation). <add>- [#14878](https://github.com/emberjs/ember.js/pull/14878) [DOC] Fix yuidoc package paths to ensure RSVP is properly included in API documentation. <add>- [#14910](https://github.com/emberjs/ember.js/pull/14910) [BUGFIX] Include blueprints in NPM release, to ensure `ember-source` blueprints are used over `ember-cli-legacy-blueprints`. <add>- [e94799c](https://github.com/emberjs/ember.js/commit/e94799c54cd464f5ba3642dec83f0000a52eb3b6) [BUGFIX] Update to `route-recognizer@0.2.9` to prevent errors for duplicate route name definitions in `Router.map`. <add> <ide> <ide> ### 2.11.0 (January 23, 2017) <ide>
1
Text
Text
remove garbage file
df45fdb43fdf0af775a8f9403c8e718434ca2cdd
<ide><path>hangover.md <del> <del> test("routeless transitionTo in mid-transition uses transition's destination route for query params, not the router's current route", function() { <del> expect(2); <del> Router.map(function() { <del> this.resource('woot', { path: '/woot' }, function() { <del> this.route('yeah'); <del> }); <del> }); <del> <del> App.WootYeahController = Ember.Controller.extend({ <del> queryParams: ['foo'], <del> foo: 'lol' <del> }); <del> <del> var redirectCount = 0; <del> App.WootRoute = Ember.Route.extend({ <del> redirect: function() { <del> redirectCount++; <del> // Keep transitioning to WootYeah but alter its <del> // query params to foo: 'yeah' <del> this.transitionTo({ queryParams: { foo: 'yeah' } }); <del> } <del> }); <del> <del> bootApplication(); <del> <del> Ember.run(router, 'transitionTo', 'woot.yeah'); <del> equal(router.get('location.path'), "/woot/yeah?woot.yeah[foo]=yeah"); <del> equal(redirectCount, 1, "redirect was only run once"); <del> });
1
PHP
PHP
remove closure version and update docs
c07d4b2f51ad17a8c9f65130bad710356b45e478
<ide><path>lib/Cake/Cache/CacheRegistry.php <ide> protected function _throwMissingClassError($class, $plugin) { <ide> * Create the cache engine instance. <ide> * <ide> * Part of the template method for Cake\Utility\ObjectRegistry::load() <del> * @param string|CacheEngine $class The classname or object to make, or a closure factory. <add> * @param string|CacheEngine $class The classname or object to make. <ide> * @param array $settings An array of settings to use for the cache engine. <ide> * @return CacheEngine The constructed CacheEngine class. <ide> * @throws Cake\Error\Exception when an object doesn't implement <ide><path>lib/Cake/Log/LogEngineRegistry.php <ide> protected function _throwMissingClassError($class, $plugin) { <ide> * Create the logger instance. <ide> * <ide> * Part of the template method for Cake\Utility\ObjectRegistry::load() <del> * @param string|LogInterface|Closure $class The classname or object to make, or a closure factory <add> * @param string|LogInterface $class The classname or object to make. <ide> * @param array $settings An array of settings to use for the logger. <ide> * @return LogEngine The constructed logger class. <ide> * @throws Cake\Error\Exception when an object doesn't implement <ide> * the correct interface. <ide> */ <ide> protected function _create($class, $settings) { <del> $isObject = is_object($class); <del> if ($isObject && $class instanceof \Closure) { <del> $instance = $class(); <del> } elseif ($isObject) { <add> if (is_object($class)) { <ide> $instance = $class; <ide> } <ide>
2
Python
Python
add a test for ticket
cb5a27eacb0165752fc5ab82633911d90df28af4
<ide><path>numpy/core/tests/test_regression.py <ide> def test_refcount_error_in_clip(self): <ide> # Check the final string: <ide> assert_(y == "[0 0]") <ide> <add> def test_searchsorted_wrong_dtype(self): <add> # Ticket #2189, it used to segfault, so we check that it raises the <add> # proper exception. <add> a = np.array([('a', 1)], dtype='S1, int') <add> assert_raises(TypeError, np.searchsorted, a, 1.2) <add> <ide> if __name__ == "__main__": <ide> run_module_suite()
1
Text
Text
add i18n issue template
7ecb039176a019924cbd0cfb2b7dfd4744859763
<ide><path>.github/ISSUE_TEMPLATE/i18n.md <add>--- <add>name: 🌐 Translating a new language? <add>about: Start a new translation effort in your language <add>title: '[i18n-<languageCode>] Translating docs to <languageName>' <add>labels: WIP <add>assignees: '' <add> <add>--- <add> <add><!-- <add>Note: Please search to see if an issue already exists for the language you are trying to translate. <add>--> <add> <add>Hi! <add> <add>Let's bring the documentation to all the <languageName>-speaking community 🌐 (currently 0 out of 267 complete) <add> <add>Who would want to translate? Please follow the 🤗 [TRANSLATING guide](https://github.com/huggingface/transformers/blob/main/docs/TRANSLATING.md). Here is a list of the files ready for translation. Let us know in this issue if you'd like to translate any, and we'll add your name to the list. <add> <add>Some notes: <add> <add>* Please translate using an informal tone (imagine you are talking with a friend about transformers 🤗). <add>* Please translate in a gender-neutral way. <add>* Add your translations to the folder called `<languageCode>` inside the [source folder](https://github.com/huggingface/transformers/tree/main/docs/source). <add>* Register your translation in `<languageCode>/_toctree.yml`; please follow the order of the [English version](https://github.com/huggingface/transformers/blob/main/docs/source/en/_toctree.yml). <add>* Once you're finished, open a pull request and tag this issue by including #issue-number in the description, where issue-number is the number of this issue. Please ping @ArthurZucker, @sgugger for review. <add>* 🙋 If you'd like others to help you with the translation, you can also post in the 🤗 [forums](https://discuss.huggingface.co/). <add> <add>## Get Started section <add> <add>- [ ] [index.mdx](https://github.com/huggingface/transformers/blob/main/docs/source/en/index.mdx) https://github.com/huggingface/transformers/pull/20180 <add>- [ ] [quicktour.mdx](https://github.com/huggingface/transformers/blob/main/docs/source/en/quicktour.mdx) (waiting for initial PR to go through) <add>- [ ] [installation.mdx](https://github.com/huggingface/transformers/blob/main/docs/source/en/installation.mdx). <add> <add>## Tutorial section <add>- [ ] [pipeline_tutorial.mdx](https://github.com/huggingface/transformers/blob/main/docs/source/en/pipeline_tutorial.mdx) <add>- [ ] [autoclass_tutorial.mdx](https://github.com/huggingface/transformers/blob/master/docs/source/autoclass_tutorial.mdx) <add>- [ ] [preprocessing.mdx](https://github.com/huggingface/transformers/blob/main/docs/source/en/preprocessing.mdx) <add>- [ ] [training.mdx](https://github.com/huggingface/transformers/blob/main/docs/source/en/training.mdx) <add>- [ ] [accelerate.mdx](https://github.com/huggingface/transformers/blob/main/docs/source/en/accelerate.mdx) <add>- [ ] [model_sharing.mdx](https://github.com/huggingface/transformers/blob/main/docs/source/en/model_sharing.mdx) <add>- [ ] [multilingual.mdx](https://github.com/huggingface/transformers/blob/main/docs/source/en/multilingual.mdx) <add> <add><!-- <add>Keep on adding more as you go 🔥 <add>-->
1
Text
Text
add .validate() example
5d4ea3d23fdb173b4109a64b2d4231d93d394387
<ide><path>docs/api-guide/serializers.md <ide> Your `validate_<fieldname>` methods should either just return the `attrs` dictio <ide> <ide> ### Object-level validation <ide> <del>To do any other validation that requires access to multiple fields, add a method called `.validate()` to your `Serializer` subclass. This method takes a single argument, which is the `attrs` dictionary. It should raise a `ValidationError` if necessary, or just return `attrs`. <add>To do any other validation that requires access to multiple fields, add a method called `.validate()` to your `Serializer` subclass. This method takes a single argument, which is the `attrs` dictionary. It should raise a `ValidationError` if necessary, or just return `attrs`. For example: <add> <add> from rest_framework import serializers <add> <add> class EventSerializer(serializers.Serializer): <add> description = serializers.CahrField(max_length=100) <add> start = serializers.DateTimeField() <add> finish = serializers.DateTimeField() <add> <add> def validate(self, attrs): <add> """ <add> Check that the start is before the stop. <add> """ <add> if attrs['start'] < attrs['finish']: <add> raise serializers.ValidationError("finish must occur after start") <add> return attrs <ide> <ide> ## Saving object state <ide>
1
Javascript
Javascript
simplify syntax so we can extract more easily
20cab0721d99214c468abe9fbd187344663f8007
<ide><path>packages/ember-application/lib/system/application.js <ide> Ember.Application = Ember.Namespace.extend( <ide> var injections = get(this.constructor, 'injections'), <ide> namespace = this; <ide> <del> if (!router && Ember.Router.detect(namespace['Router'])) { <del> router = namespace['Router'].create(); <add> if (!router && Ember.Router.detect(this.Router)) { <add> router = this.Router.create(); <ide> this._createdRouter = router; <ide> } <ide>
1
Javascript
Javascript
update three references
4ce187587f62686b5bc29d323e3a133ffd0d2513
<ide><path>examples/jsm/loaders/LUT3dlLoader.js <ide> import { <ide> UnsignedByteType, <ide> ClampToEdgeWrapping, <ide> LinearFilter, <del>} from '//unpkg.com/three@0.120.1/build/three.module.js'; <add>} from '../../../build/three.module.js'; <ide> <ide> export class LUT3dlLoader extends Loader { <ide> <ide><path>examples/jsm/loaders/LUTCubeLoader.js <ide> import { <ide> UnsignedByteType, <ide> ClampToEdgeWrapping, <ide> LinearFilter, <del>} from '//unpkg.com/three@0.120.1/build/three.module.js'; <add>} from '../../../build/three.module.js'; <ide> <ide> export class LUTCubeLoader extends Loader { <ide>
2
PHP
PHP
image()
a451a2bacc2518fa0d54b780e4324bb3be560aad
<ide><path>src/Illuminate/Http/Testing/FileFactory.php <ide> <ide> namespace Illuminate\Http\Testing; <ide> <add>use Illuminate\Support\Str; <add> <ide> class FileFactory <ide> { <ide> /** <ide> public function create($name, $kilobytes = 0) <ide> */ <ide> public function image($name, $width = 10, $height = 10) <ide> { <del> return new File($name, $this->generateImage($width, $height)); <add> $type = Str::endsWith($name, ['.jpg', '.jpeg']) ? 'jpeg' : 'png'; <add> <add> return new File($name, $this->generateImage($width, $height, $type)); <ide> } <ide> <ide> /** <ide> public function image($name, $width = 10, $height = 10) <ide> * @param int $height <ide> * @return resource <ide> */ <del> protected function generateImage($width, $height) <add> protected function generateImage($width, $height, $type) <ide> { <del> return tap(tmpfile(), function ($temp) use ($width, $height) { <add> return tap(tmpfile(), function ($temp) use ($width, $height, $type) { <ide> ob_start(); <ide> <del> imagepng(imagecreatetruecolor($width, $height)); <add> $image = imagecreatetruecolor($width, $height); <add> <add> switch ($type) { <add> case 'jpeg': <add> imagejpeg($image); <add> break; <add> case 'png': <add> imagepng($image); <add> break; <add> } <ide> <ide> fwrite($temp, ob_get_clean()); <ide> }); <ide><path>tests/Http/HttpTestingFileFactoryTest.php <add><?php <add> <add>namespace Illuminate\Tests\Http; <add> <add>use PHPUnit\Framework\TestCase; <add>use Illuminate\Http\Testing\FileFactory; <add> <add>class HttpTestingFileFactoryTest extends TestCase <add>{ <add> public function testImagePng() <add> { <add> $image = (new FileFactory)->image('test.png', 15, 20); <add> <add> $info = getimagesize($image->getRealPath()); <add> <add> $this->assertSame('image/png', $info['mime']); <add> $this->assertSame(15, $info[0]); <add> $this->assertSame(20, $info[1]); <add> } <add> <add> public function testImageJpeg() <add> { <add> $image = (new FileFactory)->image('test.jpeg', 15, 20); <add> <add> $info = getimagesize($image->getRealPath()); <add> <add> $this->assertSame('image/jpeg', $info['mime']); <add> $this->assertSame(15, $info[0]); <add> $this->assertSame(20, $info[1]); <add> } <add>}
2
Mixed
Ruby
add a separation option for the excerpt function
963c50eca87373bed403358c076b377ad62454ef
<ide><path>actionpack/CHANGELOG.md <ide> ## Rails 4.0.0 (unreleased) ## <ide> <add>* Add `separation` option for `ActionView::Helpers::TextHelper.excerpt`. *Guirec Corbel* <add> <ide> * Added controller-level etag additions that will be part of the action etag computation *Jeremy Kemper/DHH* <ide> <ide> class InvoicesController < ApplicationController <ide><path>actionpack/lib/action_view/helpers/text_helper.rb <ide> def highlight(text, phrases, options = {}) <ide> # Extracts an excerpt from +text+ that matches the first instance of +phrase+. <ide> # The <tt>:radius</tt> option expands the excerpt on each side of the first occurrence of +phrase+ by the number of characters <ide> # defined in <tt>:radius</tt> (which defaults to 100). If the excerpt radius overflows the beginning or end of the +text+, <del> # then the <tt>:omission</tt> option (which defaults to "...") will be prepended/appended accordingly. The resulting string <del> # will be stripped in any case. If the +phrase+ isn't found, nil is returned. <add> # then the <tt>:omission</tt> option (which defaults to "...") will be prepended/appended accordingly. The <add> # <tt>:separator</tt> enable to choose the delimation. The resulting string will be stripped in any case. If the +phrase+ <add> # isn't found, nil is returned. <ide> # <ide> # excerpt('This is an example', 'an', :radius => 5) <ide> # # => ...s is an exam... <ide> def highlight(text, phrases, options = {}) <ide> # <ide> # excerpt('This is also an example', 'an', :radius => 8, :omission => '<chop> ') <ide> # # => <chop> is also an example <add> # <add> # excerpt('This is a very beautiful morning', 'very', :separator => ' ', :radius => 1) <add> # # => ...a very beautiful... <ide> def excerpt(text, phrase, options = {}) <ide> return unless text && phrase <del> radius = options.fetch(:radius, 100) <del> omission = options.fetch(:omission, "...") <add> radius = options.fetch(:radius, 100) <add> omission = options.fetch(:omission, "...") <add> separator = options.fetch(:separator, "") <add> <add> phrase = Regexp.escape(phrase) <add> regex = /#{phrase}/i <add> <add> return unless matches = text.match(regex) <add> phrase = matches[0] <add> <add> text.split(separator).each do |value| <add> if value.match(regex) <add> regex = phrase = value <add> break <add> end <add> end <ide> <del> phrase = Regexp.escape(phrase) <del> return unless found_pos = text =~ /(#{phrase})/i <add> first_part, second_part = text.split(regex, 2) <ide> <del> start_pos = [ found_pos - radius, 0 ].max <del> end_pos = [ [ found_pos + phrase.length + radius - 1, 0].max, text.length ].min <add> options = options.merge(:part_position => :first) <add> prefix, first_part = cut_part(first_part, options) <ide> <del> prefix = start_pos > 0 ? omission : "" <del> postfix = end_pos < text.length - 1 ? omission : "" <add> options = options.merge(:part_position => :second) <add> postfix, second_part = cut_part(second_part, options) <ide> <del> prefix + text[start_pos..end_pos].strip + postfix <add> prefix + (first_part + separator + phrase + separator + second_part).strip + postfix <ide> end <ide> <ide> # Attempts to pluralize the +singular+ word unless +count+ is 1. If <ide> def split_paragraphs(text) <ide> t.gsub!(/([^\n]\n)(?=[^\n])/, '\1<br />') || t <ide> end <ide> end <add> <add> def cut_part(part, options) <add> radius = options.fetch(:radius, 100) <add> omission = options.fetch(:omission, "...") <add> separator = options.fetch(:separator, "") <add> part_position = options.fetch(:part_position) <add> <add> return "", "" unless part <add> <add> part = part.split(separator) <add> part.delete("") <add> affix = part.size > radius ? omission : "" <add> part = if part_position == :first <add> drop_index = [part.length - radius, 0].max <add> part.drop(drop_index).join(separator) <add> else <add> part.first(radius).join(separator) <add> end <add> <add> return affix, part <add> end <ide> end <ide> end <ide> end <ide><path>actionpack/test/template/text_helper_test.rb <ide> def test_excerpt_does_not_modify_the_options_hash <ide> assert_equal options, passed_options <ide> end <ide> <add> def test_excerpt_with_separator <add> options = { :separator => ' ', :radius => 1 } <add> assert_equal('...a very beautiful...', excerpt('This is a very beautiful morning', 'very', options)) <add> assert_equal('This is...', excerpt('This is a very beautiful morning', 'this', options)) <add> assert_equal('...beautiful morning', excerpt('This is a very beautiful morning', 'morning', options)) <add> <add> options = { :separator => "\n", :radius => 0 } <add> assert_equal("...very long...", excerpt("my very\nvery\nvery long\nstring", 'long', options)) <add> <add> options = { :separator => "\n", :radius => 1 } <add> assert_equal("...very\nvery long\nstring", excerpt("my very\nvery\nvery long\nstring", 'long', options)) <add> end <add> <ide> def test_word_wrap <ide> assert_equal("my very very\nvery long\nstring", word_wrap("my very very very long string", :line_width => 15)) <ide> end
3
PHP
PHP
rename another $value variable
1e166f8b00bd50104e95d2fa69ab8f0605a3631b
<ide><path>src/Collection/Iterator/SortIterator.php <ide> public function __construct($items, $callback, $dir = SORT_DESC, $type = SORT_NU <ide> <ide> $callback = $this->_propertyExtractor($callback); <ide> $results = []; <del> foreach ($items as $key => $value) { <del> $value = $callback($value); <del> if ($value instanceof DateTimeInterface && $type === SORT_NUMERIC) { <del> $value = $value->format('U'); <add> foreach ($items as $key => $val) { <add> $val = $callback($val); <add> if ($val instanceof DateTimeInterface && $type === SORT_NUMERIC) { <add> $val = $val->format('U'); <ide> } <del> $results[$key] = $value; <add> $results[$key] = $val; <ide> } <ide> <ide> $dir === SORT_DESC ? arsort($results, $type) : asort($results, $type);
1
PHP
PHP
remove admin tests
0a6d09464563e50f8785858d01392614c7342dcb
<ide><path>tests/TestCase/Console/Command/Task/ControllerTaskTest.php <ide> public function testBakeActions() { <ide> $result = $this->Task->bakeActions('BakeArticles'); <ide> $expected = file_get_contents(CORE_TESTS . 'bake_compare/Controller/Actions.ctp'); <ide> $this->assertTextEquals($expected, $result); <del> <del> $result = $this->Task->bakeActions('BakeArticles', 'admin_', true); <del> $this->assertContains('function admin_index() {', $result); <del> $this->assertContains('function admin_add()', $result); <del> $this->assertContains('function admin_view($id = null)', $result); <del> $this->assertContains('function admin_edit($id = null)', $result); <del> $this->assertContains('function admin_delete($id = null)', $result); <ide> } <ide> <ide> /**
1
Text
Text
remove extraneous period
86fb98eb3720a7256764ff0bd8b34a23c0946ade
<ide><path>README.md <ide> You can find documentation at [www.chartjs.org/docs](http://www.chartjs.org/docs <ide> <ide> ## Contributing <ide> <del>Before submitting an issue or a pull request, please take a moment to look over the [contributing guidelines](https://github.com/chartjs/Chart.js/blob/master/docs/developers/contributing.md.) first. For support using Chart.js, please post questions with the [`chartjs` tag on Stack Overflow](http://stackoverflow.com/questions/tagged/chartjs). <add>Before submitting an issue or a pull request, please take a moment to look over the [contributing guidelines](https://github.com/chartjs/Chart.js/blob/master/docs/developers/contributing.md) first. For support using Chart.js, please post questions with the [`chartjs` tag on Stack Overflow](http://stackoverflow.com/questions/tagged/chartjs). <ide> <ide> ## Building <ide> Instructions on building and testing Chart.js can be found in [the documentation](https://github.com/chartjs/Chart.js/blob/master/docs/developers/contributing.md#building-and-testing).
1
PHP
PHP
update driver list
6284528b76647eb876f02fb12d0601d51867a8a8
<ide><path>config/logging.php <ide> | the box, Laravel uses the Monolog PHP logging library. This gives <ide> | you a variety of powerful log handlers / formatters to utilize. <ide> | <del> | Available Drivers: "single", "daily", "syslog", <del> | "errorlog", "custom" <add> | Available Drivers: "single", "daily", "slack", "syslog", <add> | "errorlog", "custom", "stack" <ide> | <ide> */ <ide>
1
Javascript
Javascript
update $animate and nganimate docs
b1d4d580e5021d5890d684847b205701be15d292
<ide><path>src/ngAnimate/animate.js <ide> * <ide> * # ngAnimate <ide> * <del> * The `ngAnimate` module provides support for JavaScript and CSS3 animation hooks within core and custom directives. <add> * The `ngAnimate` module provides support for JavaScript, CSS3 transition and CSS3 keyframe animation hooks within existing core and custom directives. <ide> * <ide> * {@installModule animate} <ide> * <ide> * # Usage <ide> * <ide> * To see animations in action, all that is required is to define the appropriate CSS classes <del> * or to register a JavaScript animation via the $animation service. The directives that support animation automatically are: <del> * `ngRepeat`, `ngInclude`, `ngSwitch`, `ngShow`, `ngHide` and `ngView`. Custom directives can take advantage of animation <add> * or to register a JavaScript animation via the myModule.animation() function. The directives that support animation automatically are: <add> * `ngRepeat`, `ngInclude`, `ngIf`, `ngSwitch`, `ngShow`, `ngHide`, `ngView` and `ngClass`. Custom directives can take advantage of animation <ide> * by using the `$animate` service. <ide> * <ide> * Below is a more detailed breakdown of the supported animation events provided by pre-existing ng directives: <ide> * <ide> * <pre> <ide> * <style type="text/css"> <del> * .slide.ng-enter > div, <del> * .slide.ng-leave > div { <add> * .slide.ng-enter, .slide.ng-leave { <ide> * -webkit-transition:0.5s linear all; <del> * -moz-transition:0.5s linear all; <del> * -o-transition:0.5s linear all; <ide> * transition:0.5s linear all; <ide> * } <ide> * <ide> * &#42;/ <ide> * .reveal-animation.ng-enter { <ide> * -webkit-transition: 1s linear all; /&#42; Safari/Chrome &#42;/ <del> * -moz-transition: 1s linear all; /&#42; Firefox &#42;/ <del> * -o-transition: 1s linear all; /&#42; Opera &#42;/ <del> * transition: 1s linear all; /&#42; IE10+ and Future Browsers &#42;/ <add> * transition: 1s linear all; /&#42; All other modern browsers and IE10+ &#42;/ <ide> * <ide> * /&#42; The animation preparation code &#42;/ <ide> * opacity: 0; <ide> * <style type="text/css"> <ide> * .reveal-animation.ng-enter { <ide> * -webkit-animation: enter_sequence 1s linear; /&#42; Safari/Chrome &#42;/ <del> * -moz-animation: enter_sequence 1s linear; /&#42; Firefox &#42;/ <del> * -o-animation: enter_sequence 1s linear; /&#42; Opera &#42;/ <ide> * animation: enter_sequence 1s linear; /&#42; IE10+ and Future Browsers &#42;/ <ide> * } <ide> * &#64-webkit-keyframes enter_sequence { <ide> * from { opacity:0; } <ide> * to { opacity:1; } <ide> * } <del> * &#64-moz-keyframes enter_sequence { <del> * from { opacity:0; } <del> * to { opacity:1; } <del> * } <del> * &#64-o-keyframes enter_sequence { <del> * from { opacity:0; } <del> * to { opacity:1; } <del> * } <ide> * &#64keyframes enter_sequence { <ide> * from { opacity:0; } <ide> * to { opacity:1; } <ide> * <pre> <ide> * .my-animation.ng-enter { <ide> * /&#42; standard transition code &#42;/ <add> * -webkit-transition: 1s linear all; <add> * transition: 1s linear all; <add> * opacity:0; <ide> * } <ide> * .my-animation.ng-enter-stagger { <ide> * /&#42; this will have a 100ms delay between each successive leave animation &#42;/ <ide> * } <ide> * .my-animation.ng-enter.ng-enter-active { <ide> * /&#42; standard transition styles &#42;/ <add> * opacity:1; <ide> * } <ide> * </pre> <ide> * <ide> * return function(cancelled) { <ide> * //this (optional) function will be called when the animation <ide> * //completes or when the animation is cancelled (the cancelled <del> * //flag will (be set to true if cancelled). <add> * //flag will be set to true if cancelled). <ide> * } <ide> * } <ide> * leave: function(element, done) { }, <ide> * move: function(element, done) { }, <ide> * <add> * //animation that can be triggered before the class is added <ide> * beforeAddClass: function(element, className, done) { }, <add> * <add> * //animation that can be triggered after the class is added <ide> * addClass: function(element, className, done) { }, <ide> * <add> * //animation that can be triggered before the class is removed <ide> * beforeRemoveClass: function(element, className, done) { }, <add> * <add> * //animation that can be triggered after the class is removed <ide> * removeClass: function(element, className, done) { } <ide> * } <ide> * }); <ide> * a javascript callback function. When an animation is triggered, $animate will look for a matching animation which fits <ide> * the element's CSS class attribute value and then run the matching animation event function (if found). <ide> * In other words, if the CSS classes present on the animated element match any of the JavaScript animations then the callback function <del> * be executed. It should be also noted that only simple class selectors are allowed. <add> * be executed. It should be also noted that only simple, single class selectors are allowed (compound class selectors are not supported). <ide> * <ide> * Within a JavaScript animation, an object containing various event callback animation functions is expected to be returned. <ide> * As explained above, these callbacks are triggered based on the animation event. Therefore if an enter animation is run, <ide> angular.module('ngAnimate', ['ng']) <ide> * @name ngAnimate.$animateProvider <ide> * @description <ide> * <del> * The `$AnimationProvider` allows developers to register and access custom JavaScript animations directly inside <del> * of a module. When an animation is triggered, the $animate service will query the $animation function to find any <del> * animations that match the provided name value. <add> * The `$animateProvider` allows developers to register JavaScript animation event handlers directly inside of a module. <add> * When an animation is triggered, the $animate service will query the $animate service to find any animations that match <add> * the provided name value. <ide> * <ide> * Requires the {@link ngAnimate `ngAnimate`} module to be installed. <ide> * <ide> angular.module('ngAnimate', ['ng']) <ide> /** <ide> * @ngdoc object <ide> * @name ngAnimate.$animate <del> * @requires $timeout, $sniffer, $rootElement <ide> * @function <ide> * <ide> * @description <del> * The `$animate` service provides animation detection support while performing DOM operations (enter, leave and move) <del> * as well as during addClass and removeClass operations. When any of these operations are run, the $animate service <add> * The `$animate` service provides animation detection support while performing DOM operations (enter, leave and move) as well as during addClass and removeClass operations. <add> * When any of these operations are run, the $animate service <ide> * will examine any JavaScript-defined animations (which are defined by using the $animateProvider provider object) <ide> * as well as any CSS-defined animations against the CSS classes present on the element once the DOM operation is run. <ide> * <ide> angular.module('ngAnimate', ['ng']) <ide> * <ide> * Below is a breakdown of each step that occurs during enter animation: <ide> * <del> * | Animation Step | What the element class attribute looks like | <del> * |----------------------------------------------------------------------------------------------|-----------------------------------------------| <del> * | 1. $animate.enter(...) is called | class="my-animation" | <del> * | 2. element is inserted into the parentElement element or beside the afterElement element | class="my-animation" | <del> * | 3. $animate runs any JavaScript-defined animations on the element | class="my-animation" | <del> * | 4. the .ng-enter class is added to the element | class="my-animation ng-enter" | <del> * | 5. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-enter" | <del> * | 6. the .ng-enter-active class is added (this triggers the CSS transition/animation) | class="my-animation ng-enter ng-enter-active" | <del> * | 7. $animate waits for X milliseconds for the animation to complete | class="my-animation ng-enter ng-enter-active" | <del> * | 8. The animation ends and both CSS classes are removed from the element | class="my-animation" | <del> * | 9. The doneCallback() callback is fired (if provided) | class="my-animation" | <add> * | Animation Step | What the element class attribute looks like | <add> * |----------------------------------------------------------------------------------------------|---------------------------------------------| <add> * | 1. $animate.enter(...) is called | class="my-animation" | <add> * | 2. element is inserted into the parentElement element or beside the afterElement element | class="my-animation" | <add> * | 3. $animate runs any JavaScript-defined animations on the element | class="my-animation ng-animate" | <add> * | 4. the .ng-enter class is added to the element | class="my-animation ng-animate ng-enter" | <add> * | 5. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate ng-enter" | <add> * | 6. $animate waits for 10ms (this performs a reflow) | class="my-animation ng-animate ng-enter" | <add> * | 7. the .ng-enter-active and .ng-animate-active classes are added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-animate-active ng-enter ng-enter-active" | <add> * | 8. $animate waits for X milliseconds for the animation to complete | class="my-animation ng-animate ng-animate-active ng-enter ng-enter-active" | <add> * | 9. The animation ends and all generated CSS classes are removed from the element | class="my-animation" | <add> * | 10. The doneCallback() callback is fired (if provided) | class="my-animation" | <ide> * <ide> * @param {jQuery/jqLite element} element the element that will be the focus of the enter animation <ide> * @param {jQuery/jqLite element} parentElement the parent element of the element that will be the focus of the enter animation <ide> * @param {jQuery/jqLite element} afterElement the sibling element (which is the previous element) of the element that will be the focus of the enter animation <del> * @param {function()=} doneCallback callback function that will be called once the animation is complete <add> * @param {function()=} doneCallback the callback function that will be called once the animation is complete <ide> */ <ide> enter : function(element, parentElement, afterElement, doneCallback) { <ide> this.enabled(false, element); <ide> angular.module('ngAnimate', ['ng']) <ide> * <ide> * Below is a breakdown of each step that occurs during enter animation: <ide> * <del> * | Animation Step | What the element class attribute looks like | <del> * |----------------------------------------------------------------------------------------------|----------------------------------------------| <del> * | 1. $animate.leave(...) is called | class="my-animation" | <del> * | 2. $animate runs any JavaScript-defined animations on the element | class="my-animation" | <del> * | 3. the .ng-leave class is added to the element | class="my-animation ng-leave" | <del> * | 4. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-leave" | <del> * | 5. the .ng-leave-active class is added (this triggers the CSS transition/animation) | class="my-animation ng-leave ng-leave-active | <del> * | 6. $animate waits for X milliseconds for the animation to complete | class="my-animation ng-leave ng-leave-active | <del> * | 7. The animation ends and both CSS classes are removed from the element | class="my-animation" | <del> * | 8. The element is removed from the DOM | ... | <del> * | 9. The doneCallback() callback is fired (if provided) | ... | <add> * | Animation Step | What the element class attribute looks like | <add> * |----------------------------------------------------------------------------------------------|---------------------------------------------| <add> * | 1. $animate.leave(...) is called | class="my-animation" | <add> * | 2. $animate runs any JavaScript-defined animations on the element | class="my-animation ng-animate" | <add> * | 3. the .ng-leave class is added to the element | class="my-animation ng-animate ng-leave" | <add> * | 4. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate ng-leave" | <add> * | 5. $animate waits for 10ms (this performs a reflow) | class="my-animation ng-animate ng-leave" | <add> * | 6. the .ng-leave-active and .ng-animate-active classes is added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-animate-active ng-leave ng-leave-active" | <add> * | 7. $animate waits for X milliseconds for the animation to complete | class="my-animation ng-animate ng-animate-active ng-leave ng-leave-active" | <add> * | 8. The animation ends and all generated CSS classes are removed from the element | class="my-animation" | <add> * | 9. The element is removed from the DOM | ... | <add> * | 10. The doneCallback() callback is fired (if provided) | ... | <ide> * <ide> * @param {jQuery/jqLite element} element the element that will be the focus of the leave animation <del> * @param {function()=} doneCallback callback function that will be called once the animation is complete <add> * @param {function()=} doneCallback the callback function that will be called once the animation is complete <ide> */ <ide> leave : function(element, doneCallback) { <ide> cancelChildAnimations(element); <ide> angular.module('ngAnimate', ['ng']) <ide> * |----------------------------------------------------------------------------------------------|---------------------------------------------| <ide> * | 1. $animate.move(...) is called | class="my-animation" | <ide> * | 2. element is moved into the parentElement element or beside the afterElement element | class="my-animation" | <del> * | 3. $animate runs any JavaScript-defined animations on the element | class="my-animation" | <del> * | 4. the .ng-move class is added to the element | class="my-animation ng-move" | <del> * | 5. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-move" | <del> * | 6. the .ng-move-active class is added (this triggers the CSS transition/animation) | class="my-animation ng-move ng-move-active" | <del> * | 7. $animate waits for X milliseconds for the animation to complete | class="my-animation ng-move ng-move-active" | <del> * | 8. The animation ends and both CSS classes are removed from the element | class="my-animation" | <del> * | 9. The doneCallback() callback is fired (if provided) | class="my-animation" | <add> * | 3. $animate runs any JavaScript-defined animations on the element | class="my-animation ng-animate" | <add> * | 4. the .ng-move class is added to the element | class="my-animation ng-animate ng-move" | <add> * | 5. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate ng-move" | <add> * | 6. $animate waits for 10ms (this performs a reflow) | class="my-animation ng-animate ng-move" | <add> * | 7. the .ng-move-active and .ng-animate-active classes is added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-animate-active ng-move ng-move-active" | <add> * | 8. $animate waits for X milliseconds for the animation to complete | class="my-animation ng-animate ng-animate-active ng-move ng-move-active" | <add> * | 9. The animation ends and all generated CSS classes are removed from the element | class="my-animation" | <add> * | 10. The doneCallback() callback is fired (if provided) | class="my-animation" | <ide> * <ide> * @param {jQuery/jqLite element} element the element that will be the focus of the move animation <ide> * @param {jQuery/jqLite element} parentElement the parentElement element of the element that will be the focus of the move animation <ide> * @param {jQuery/jqLite element} afterElement the sibling element (which is the previous element) of the element that will be the focus of the move animation <del> * @param {function()=} doneCallback callback function that will be called once the animation is complete <add> * @param {function()=} doneCallback the callback function that will be called once the animation is complete <ide> */ <ide> move : function(element, parentElement, afterElement, doneCallback) { <ide> cancelChildAnimations(element); <ide> angular.module('ngAnimate', ['ng']) <ide> * Triggers a custom animation event based off the className variable and then attaches the className value to the element as a CSS class. <ide> * Unlike the other animation methods, the animate service will suffix the className value with {@type -add} in order to provide <ide> * the animate service the setup and active CSS classes in order to trigger the animation (this will be skipped if no CSS transitions <del> * or keyframes are defined on the -add CSS class). <add> * or keyframes are defined on the -add or base CSS class). <ide> * <ide> * Below is a breakdown of each step that occurs during addClass animation: <ide> * <ide> * | Animation Step | What the element class attribute looks like | <ide> * |------------------------------------------------------------------------------------------------|---------------------------------------------| <del> * | 1. $animate.addClass(element, 'super') is called | class="" | <del> * | 2. $animate runs any JavaScript-defined animations on the element | class="" | <del> * | 3. the .super-add class is added to the element | class="super-add" | <del> * | 4. $animate scans the element styles to get the CSS transition/animation duration and delay | class="super-add" | <del> * | 5. the .super-add-active class is added (this triggers the CSS transition/animation) | class="super-add super-add-active" | <del> * | 6. $animate waits for X milliseconds for the animation to complete | class="super-add super-add-active" | <del> * | 7. The animation ends and both CSS classes are removed from the element | class="" | <del> * | 8. The super class is added to the element | class="super" | <del> * | 9. The doneCallback() callback is fired (if provided) | class="super" | <add> * | 1. $animate.addClass(element, 'super') is called | class="my-animation" | <add> * | 2. $animate runs any JavaScript-defined animations on the element | class="my-animation ng-animate" | <add> * | 3. the .super-add class are added to the element | class="my-animation ng-animate super-add" | <add> * | 4. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate super-add" | <add> * | 5. $animate waits for 10ms (this performs a reflow) | class="my-animation ng-animate super-add" | <add> * | 6. the .super, .super-add-active and .ng-animate-active classes are added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-animate-active super super-add super-add-active" | <add> * | 7. $animate waits for X milliseconds for the animation to complete | class="my-animation super-add super-add-active" | <add> * | 8. The animation ends and all generated CSS classes are removed from the element | class="my-animation super" | <add> * | 9. The super class is kept on the element | class="my-animation super" | <add> * | 10. The doneCallback() callback is fired (if provided) | class="my-animation super" | <ide> * <ide> * @param {jQuery/jqLite element} element the element that will be animated <del> * @param {string} className the CSS class that will be animated and then attached to the element <del> * @param {function()=} done callback function that will be called once the animation is complete <add> * @param {string} className the CSS class that will be added to the element and then animated <add> * @param {function()=} doneCallback the callback function that will be called once the animation is complete <ide> */ <ide> addClass : function(element, className, doneCallback) { <ide> performAnimation('addClass', className, element, null, null, function() { <ide> angular.module('ngAnimate', ['ng']) <ide> * Triggers a custom animation event based off the className variable and then removes the CSS class provided by the className value <ide> * from the element. Unlike the other animation methods, the animate service will suffix the className value with {@type -remove} in <ide> * order to provide the animate service the setup and active CSS classes in order to trigger the animation (this will be skipped if <del> * no CSS transitions or keyframes are defined on the -remove CSS class). <add> * no CSS transitions or keyframes are defined on the -remove or base CSS classes). <ide> * <ide> * Below is a breakdown of each step that occurs during removeClass animation: <ide> * <ide> * | Animation Step | What the element class attribute looks like | <del> * |-----------------------------------------------------------------------------------------------|-------------------------------------------------| <del> * | 1. $animate.removeClass(element, 'super') is called | class="super" | <del> * | 2. $animate runs any JavaScript-defined animations on the element | class="super" | <del> * | 3. the .super-remove class is added to the element | class="super super-remove" | <del> * | 4. $animate scans the element styles to get the CSS transition/animation duration and delay | class="super super-remove" | <del> * | 5. the .super-remove-active class is added (this triggers the CSS transition/animation) | class="super super-remove super-remove-active" | <del> * | 6. $animate waits for X milliseconds for the animation to complete | class="super super-remove super-remove-active" | <del> * | 7. The animation ends and both CSS all three classes are removed from the element | class="" | <del> * | 8. The doneCallback() callback is fired (if provided) | class="" | <add> * |-----------------------------------------------------------------------------------------------|---------------------------------------------| <add> * | 1. $animate.removeClass(element, 'super') is called | class="my-animation super" | <add> * | 2. $animate runs any JavaScript-defined animations on the element | class="my-animation super ng-animate" | <add> * | 3. the .super-remove class are added to the element | class="my-animation super ng-animate super-remove"| <add> * | 4. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation super ng-animate super-remove" | <add> * | 5. $animate waits for 10ms (this performs a reflow) | class="my-animation super ng-animate super-remove" | <add> * | 6. the .super-remove-active and .ng-animate-active classes are added and .super is removed (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-animate-active super-remove super-remove-active" | <add> * | 7. $animate waits for X milliseconds for the animation to complete | class="my-animation ng-animate ng-animate-active super-remove super-remove-active" | <add> * | 8. The animation ends and all generated CSS classes are removed from the element | class="my-animation" | <add> * | 9. The doneCallback() callback is fired (if provided) | class="my-animation" | <add> * <ide> * <ide> * @param {jQuery/jqLite element} element the element that will be animated <ide> * @param {string} className the CSS class that will be animated and then removed from the element <del> * @param {function()=} done callback function that will be called once the animation is complete <add> * @param {function()=} doneCallback the callback function that will be called once the animation is complete <ide> */ <ide> removeClass : function(element, className, doneCallback) { <ide> performAnimation('removeClass', className, element, null, null, function() {
1
PHP
PHP
fix session driver in cached config
ee349de4872179b0b91414776f75928b1ba573c6
<ide><path>src/Illuminate/Foundation/Console/ConfigCacheCommand.php <ide> public function fire() <ide> <ide> $config = $this->getFreshConfiguration(); <ide> <add> $config = $this->setRealSessionDriver($config); <add> <ide> file_put_contents( <ide> $this->laravel->getCachedConfigPath(), '<?php return '.var_export($config, true).';'.PHP_EOL <ide> ); <ide> protected function getFreshConfiguration() <ide> return $app['config']->all(); <ide> } <ide> <add> /** <add> * Set the "real" session driver on the configuratoin array. <add> * <add> * Typically the SessionManager forces the driver to "array" in CLI environment. <add> * <add> * @param array $config <add> * @return array <add> */ <add> protected function setRealSessionDriver(array $config) <add> { <add> $session = require $this->laravel->configPath().'/session.php'; <add> <add> $config['session']['driver'] = $session['driver']; <add> <add> return $config; <add> } <add> <ide> }
1
PHP
PHP
remove terminology for "web routes"
527306a14c53bf904d68abd7267628b52069f624
<ide><path>app/Http/routes.php <ide> }); <ide> <ide> /* <del>|-------------------------------------------------------------------------- <del>| Web Routes <del>|-------------------------------------------------------------------------- <del>| <ide> | This route group applies the "web" middleware group to every route <ide> | it contains. The "web" middleware group is defined in your HTTP <ide> | kernel and includes session state, CSRF protection, and more. <del>| <ide> */ <ide> <ide> Route::group(['middleware' => 'web'], function () {
1
Python
Python
add placeholder for adafactor optimizer
59aad7fc07752041216e45711c9cf95a6dccff14
<ide><path>official/modeling/optimization/adafactor_optimizer.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>"""Adafactor optimizer. <add> <add>A new optimizer that will be open sourced soon. <add>""" <add># pylint: disable=invalid-name, represents an unimplemented class definition. <add>Adafactor = "Unimplemented" <ide><path>official/modeling/optimization/configs/optimization_config.py <ide> class OptimizerConfig(oneof.OneOfConfig): <ide> lars: opt_cfg.LARSConfig = opt_cfg.LARSConfig() <ide> adagrad: opt_cfg.AdagradConfig = opt_cfg.AdagradConfig() <ide> slide: opt_cfg.SLIDEConfig = opt_cfg.SLIDEConfig() <add> adafactor: opt_cfg.AdafactorConfig = opt_cfg.AdafactorConfig() <ide> <ide> <ide> @dataclasses.dataclass <ide><path>official/modeling/optimization/configs/optimizer_config.py <ide> class SLIDEConfig(BaseOptimizerConfig): <ide> do_gradient_rescaling: bool = True <ide> norm_type: str = "layer" <ide> ratio_clip_norm: float = 1e5 <add> <add> <add>@dataclasses.dataclass <add>class AdafactorConfig(BaseOptimizerConfig): <add> """Configuration for Adafactor optimizer. <add> <add> The attributes for this class matches the arguments of the Adafactor <add> implementation. <add> """ <add> name: str = "Adafactor" <add> factored: bool = True <add> multiply_by_parameter_scale: bool = True <add> beta1: Optional[float] = None <add> decay_rate: float = 0.8 <add> step_offset: int = 0 <add> clipping_threshold: float = 1.0 <add> min_dim_size_to_factor: int = 128 <add> epsilon1: float = 1e-30 <add> epsilon2: float = 1e-3 <ide><path>official/modeling/optimization/optimizer_factory.py <ide> import tensorflow_addons.optimizers as tfa_optimizers <ide> <ide> from official.modeling.optimization import slide_optimizer <add>from official.modeling.optimization import adafactor_optimizer <ide> from official.modeling.optimization import ema_optimizer <ide> from official.modeling.optimization import lars_optimizer <ide> from official.modeling.optimization import lr_schedule <ide> 'rmsprop': tf.keras.optimizers.RMSprop, <ide> 'lars': lars_optimizer.LARS, <ide> 'adagrad': tf.keras.optimizers.Adagrad, <del> 'slide': slide_optimizer.SLIDE <add> 'slide': slide_optimizer.SLIDE, <add> 'adafactor': adafactor_optimizer.Adafactor, <ide> } <ide> <ide> LR_CLS = { <ide><path>official/modeling/optimization/optimizer_factory_test.py <ide> class OptimizerFactoryTest(tf.test.TestCase, parameterized.TestCase): <ide> <ide> @parameterized.parameters(('sgd'), ('rmsprop'), ('adam'), ('adamw'), ('lamb'), <del> ('lars'), ('adagrad')) <add> ('lars'), ('adagrad'), ('adafactor')) <ide> def test_optimizers(self, optimizer_type): <ide> params = { <ide> 'optimizer': {
5
Text
Text
add ssd mobilenet v2 to model zoo
ad1042c9aeef26a2d5b4f3e00ce1472371d218ed
<ide><path>research/object_detection/README.md <ide> reporting an issue. <ide> Supercharge your mobile phones with the next generation mobile object detector! <ide> We are adding support for MobileNet V2 with SSDLite presented in <ide> [MobileNetV2: Inverted Residuals and Linear Bottlenecks](https://arxiv.org/abs/1801.04381). <del>Along with the model definition, we are also releasing a model checkpoint trained on COCO dataset. <add>Along with the model definition, we are also releasing a model checkpoint trained on the COCO dataset. <ide> <ide> <b>Thanks to contributors</b>: Menglong Zhu, Mark Sandler, Zhichao Lu, Vivek Rathod, Jonathan Huang <ide> <ide><path>research/object_detection/g3doc/detection_model_zoo.md <ide> In the table below, we list each such pre-trained model including: <ide> aware that these timings depend highly on one's specific hardware <ide> configuration (these timings were performed using an Nvidia <ide> GeForce GTX TITAN X card) and should be treated more as relative timings in <del> many cases. <add> many cases. Also note that desktop GPU timing does not always reflect mobile <add> run time. For example Mobilenet V2 is faster on mobile devices than Mobilenet <add> V1, but is slightly slower on desktop GPU. <ide> * detector performance on subset of the COCO validation set or Open Images test split as measured by the dataset-specific mAP measure. <ide> Here, higher is better, and we only report bounding box mAP rounded to the <ide> nearest integer. <ide> Some remarks on frozen inference graphs: <ide> | Model name | Speed (ms) | COCO mAP[^1] | Outputs | <ide> | ------------ | :--------------: | :--------------: | :-------------: | <ide> | [ssd_mobilenet_v1_coco](http://download.tensorflow.org/models/object_detection/ssd_mobilenet_v1_coco_2017_11_17.tar.gz) | 30 | 21 | Boxes | <add>| [ssd_mobilenet_v2_coco](http://download.tensorflow.org/models/object_detection/ssd_mobilenet_v2_coco_2018_03_29.tar.gz) | 31 | 22 | Boxes | <ide> | [ssd_inception_v2_coco](http://download.tensorflow.org/models/object_detection/ssd_inception_v2_coco_2017_11_17.tar.gz) | 42 | 24 | Boxes | <ide> | [faster_rcnn_inception_v2_coco](http://download.tensorflow.org/models/object_detection/faster_rcnn_inception_v2_coco_2018_01_28.tar.gz) | 58 | 28 | Boxes | <ide> | [faster_rcnn_resnet50_coco](http://download.tensorflow.org/models/object_detection/faster_rcnn_resnet50_coco_2018_01_28.tar.gz) | 89 | 30 | Boxes |
2
Text
Text
fix typo in docs
f16ee05f599de27e777ac2b736c3bf820a19bd7b
<ide><path>docs/api-reference/next.config.js/rewrites.md <ide> module.exports = { <ide> } <ide> ``` <ide> <del>If you're using `trailingSlash: true`, you also need to insert a trailing slash in the `source` paramater. If the destination server is also expecting a trailing slash it should be included in the `destination` parameter as well. <add>If you're using `trailingSlash: true`, you also need to insert a trailing slash in the `source` parameter. If the destination server is also expecting a trailing slash it should be included in the `destination` parameter as well. <ide> <ide> ```js <ide> module.exports = { <ide><path>docs/basic-features/script.md <ide> There are a number of trade-offs that need to be considered when loading a third <ide> <ide> Although the `worker` strategy does not require any additional configuration to work, Partytown supports the use of a config object to modify some of its settings, including enabling `debug` mode and forwarding events and triggers. <ide> <del>If you would like to add additonal configuration options, you can include it within the `<Head />` component used in a [custom `_document.js`](/docs/advanced-features/custom-document.md): <add>If you would like to add additional configuration options, you can include it within the `<Head />` component used in a [custom `_document.js`](/docs/advanced-features/custom-document.md): <ide> <ide> ```jsx <ide> import { Html, Head, Main, NextScript } from 'next/document'
2
Text
Text
use code markup/markdown in headers
4459988d0e1e24549b63856387dd7c1b61e1d87a
<ide><path>doc/api/cluster.md <ide> responsibility to manage the worker pool based on its own needs. <ide> Although a primary use case for the `cluster` module is networking, it can <ide> also be used for other use cases requiring worker processes. <ide> <del>## Class: Worker <add>## Class: `Worker` <ide> <!-- YAML <ide> added: v0.7.0 <ide> --> <ide> A `Worker` object contains all public information and method about a worker. <ide> In the master it can be obtained using `cluster.workers`. In a worker <ide> it can be obtained using `cluster.worker`. <ide> <del>### Event: 'disconnect' <add>### Event: `'disconnect'` <ide> <!-- YAML <ide> added: v0.7.7 <ide> --> <ide> cluster.fork().on('disconnect', () => { <ide> }); <ide> ``` <ide> <del>### Event: 'error' <add>### Event: `'error'` <ide> <!-- YAML <ide> added: v0.7.3 <ide> --> <ide> This event is the same as the one provided by [`child_process.fork()`][]. <ide> <ide> Within a worker, `process.on('error')` may also be used. <ide> <del>### Event: 'exit' <add>### Event: `'exit'` <ide> <!-- YAML <ide> added: v0.11.2 <ide> --> <ide> worker.on('exit', (code, signal) => { <ide> }); <ide> ``` <ide> <del>### Event: 'listening' <add>### Event: `'listening'` <ide> <!-- YAML <ide> added: v0.7.0 <ide> --> <ide> cluster.fork().on('listening', (address) => { <ide> <ide> It is not emitted in the worker. <ide> <del>### Event: 'message' <add>### Event: `'message'` <ide> <!-- YAML <ide> added: v0.7.0 <ide> --> <ide> if (cluster.isMaster) { <ide> } <ide> ``` <ide> <del>### Event: 'online' <add>### Event: `'online'` <ide> <!-- YAML <ide> added: v0.7.0 <ide> --> <ide> cluster.fork().on('online', () => { <ide> <ide> It is not emitted in the worker. <ide> <del>### worker.disconnect() <add>### `worker.disconnect()` <ide> <!-- YAML <ide> added: v0.7.7 <ide> changes: <ide> if (cluster.isMaster) { <ide> } <ide> ``` <ide> <del>### worker.exitedAfterDisconnect <add>### `worker.exitedAfterDisconnect` <ide> <!-- YAML <ide> added: v6.0.0 <ide> --> <ide> cluster.on('exit', (worker, code, signal) => { <ide> worker.kill(); <ide> ``` <ide> <del>### worker.id <add>### `worker.id` <ide> <!-- YAML <ide> added: v0.8.0 <ide> --> <ide> Each new worker is given its own unique id, this id is stored in the <ide> While a worker is alive, this is the key that indexes it in <ide> `cluster.workers`. <ide> <del>### worker.isConnected() <add>### `worker.isConnected()` <ide> <!-- YAML <ide> added: v0.11.14 <ide> --> <ide> This function returns `true` if the worker is connected to its master via its <ide> IPC channel, `false` otherwise. A worker is connected to its master after it <ide> has been created. It is disconnected after the `'disconnect'` event is emitted. <ide> <del>### worker.isDead() <add>### `worker.isDead()` <ide> <!-- YAML <ide> added: v0.11.14 <ide> --> <ide> if (cluster.isMaster) { <ide> } <ide> ``` <ide> <del>### worker.kill(\[signal='SIGTERM'\]) <add>### `worker.kill([signal='SIGTERM'])` <ide> <!-- YAML <ide> added: v0.9.12 <ide> --> <ide> This method is aliased as `worker.destroy()` for backwards compatibility. <ide> In a worker, `process.kill()` exists, but it is not this function; <ide> it is [`kill()`][]. <ide> <del>### worker.process <add>### `worker.process` <ide> <!-- YAML <ide> added: v0.7.0 <ide> --> <ide> Workers will call `process.exit(0)` if the `'disconnect'` event occurs <ide> on `process` and `.exitedAfterDisconnect` is not `true`. This protects against <ide> accidental disconnection. <ide> <del>### worker.send(message\[, sendHandle\[, options\]\]\[, callback\]) <add>### `worker.send(message[, sendHandle[, options]][, callback])` <ide> <!-- YAML <ide> added: v0.7.0 <ide> changes: <ide> if (cluster.isMaster) { <ide> } <ide> ``` <ide> <del>## Event: 'disconnect' <add>## Event: `'disconnect'` <ide> <!-- YAML <ide> added: v0.7.9 <ide> --> <ide> cluster.on('disconnect', (worker) => { <ide> }); <ide> ``` <ide> <del>## Event: 'exit' <add>## Event: `'exit'` <ide> <!-- YAML <ide> added: v0.7.9 <ide> --> <ide> cluster.on('exit', (worker, code, signal) => { <ide> <ide> See [`child_process` event: `'exit'`][]. <ide> <del>## Event: 'fork' <add>## Event: `'fork'` <ide> <!-- YAML <ide> added: v0.7.0 <ide> --> <ide> cluster.on('exit', (worker, code, signal) => { <ide> }); <ide> ``` <ide> <del>## Event: 'listening' <add>## Event: `'listening'` <ide> <!-- YAML <ide> added: v0.7.0 <ide> --> <ide> The `addressType` is one of: <ide> * `-1` (Unix domain socket) <ide> * `'udp4'` or `'udp6'` (UDP v4 or v6) <ide> <del>## Event: 'message' <add>## Event: `'message'` <ide> <!-- YAML <ide> added: v2.5.0 <ide> changes: <ide> Emitted when the cluster master receives a message from any worker. <ide> <ide> See [`child_process` event: `'message'`][]. <ide> <del>## Event: 'online' <add>## Event: `'online'` <ide> <!-- YAML <ide> added: v0.7.0 <ide> --> <ide> cluster.on('online', (worker) => { <ide> }); <ide> ``` <ide> <del>## Event: 'setup' <add>## Event: `'setup'` <ide> <!-- YAML <ide> added: v0.7.1 <ide> --> <ide> The `settings` object is the `cluster.settings` object at the time <ide> <ide> If accuracy is important, use `cluster.settings`. <ide> <del>## cluster.disconnect(\[callback\]) <add>## `cluster.disconnect([callback])` <ide> <!-- YAML <ide> added: v0.7.7 <ide> --> <ide> finished. <ide> <ide> This can only be called from the master process. <ide> <del>## cluster.fork(\[env\]) <add>## `cluster.fork([env])` <ide> <!-- YAML <ide> added: v0.6.0 <ide> --> <ide> Spawn a new worker process. <ide> <ide> This can only be called from the master process. <ide> <del>## cluster.isMaster <add>## `cluster.isMaster` <ide> <!-- YAML <ide> added: v0.8.1 <ide> --> <ide> True if the process is a master. This is determined <ide> by the `process.env.NODE_UNIQUE_ID`. If `process.env.NODE_UNIQUE_ID` is <ide> undefined, then `isMaster` is `true`. <ide> <del>## cluster.isWorker <add>## `cluster.isWorker` <ide> <!-- YAML <ide> added: v0.6.0 <ide> --> <ide> added: v0.6.0 <ide> <ide> True if the process is not a master (it is the negation of `cluster.isMaster`). <ide> <del>## cluster.schedulingPolicy <add>## `cluster.schedulingPolicy` <ide> <!-- YAML <ide> added: v0.11.2 <ide> --> <ide> distribute IOCP handles without incurring a large performance hit. <ide> `NODE_CLUSTER_SCHED_POLICY` environment variable. Valid <ide> values are `'rr'` and `'none'`. <ide> <del>## cluster.settings <add>## `cluster.settings` <ide> <!-- YAML <ide> added: v0.7.1 <ide> changes: <ide> contain the settings, including the default values. <ide> <ide> This object is not intended to be changed or set manually. <ide> <del>## cluster.setupMaster(\[settings\]) <add>## `cluster.setupMaster([settings])` <ide> <!-- YAML <ide> added: v0.7.1 <ide> changes: <ide> cluster.fork(); // http worker <ide> <ide> This can only be called from the master process. <ide> <del>## cluster.worker <add>## `cluster.worker` <ide> <!-- YAML <ide> added: v0.7.0 <ide> --> <ide> if (cluster.isMaster) { <ide> } <ide> ``` <ide> <del>## cluster.workers <add>## `cluster.workers` <ide> <!-- YAML <ide> added: v0.7.0 <ide> -->
1
PHP
PHP
apply fixes from styleci
1db746d0a8273720632f5cd46a32ef451111e8d5
<ide><path>src/Illuminate/Auth/TokenGuard.php <ide> public function user() <ide> <ide> if (! empty($token)) { <ide> $user = $this->provider->retrieveByCredentials([ <del> $this->storageKey => $token <add> $this->storageKey => $token, <ide> ]); <ide> } <ide>
1
PHP
PHP
remove forgotten method
99656b83641a7b8e83c852a1af4bf72a2d9dcd27
<ide><path>src/Illuminate/Session/SessionServiceProvider.php <ide> protected function registerSessionDriver() <ide> }); <ide> } <ide> <del> /** <del> * Get the session driver name. <del> * <del> * @return string <del> */ <del> protected function getDriver() <del> { <del> return $this->app['config']['session.driver']; <del> } <del> <ide> }
1
Javascript
Javascript
add delay to initial execute
6f98f62dd9bebf2b604e75ac4d00321dbcce7d42
<ide><path>client/commonFramework/end.js <ide> $(document).ready(function() { <ide> challengeType !== '4' && <ide> challengeType !== '7' <ide> ) { <del> common.executeChallenge$() <add> Observable.just({}) <add> .delay(500) <add> .flatMap(() => common.executeChallenge$()) <ide> .subscribe( <ide> ({ original, tests }) => { <ide> common.codeStorage.updateStorage(challengeName, original);
1
PHP
PHP
fix bug in validator class required check
e9a43326a7d071f03e6e8f986bb1e9f9dcc8557c
<ide><path>system/validator.php <ide> protected function check($attribute, $rule) <ide> */ <ide> protected function validate_required($attribute) <ide> { <del> return array_key_exists($attribute, $this->attributes) and trim($this->attributes[$attribute]) !== ''; <add> if ( ! array_key_exists($attribute, $this->attributes)) <add> { <add> return false; <add> } <add> <add> if (is_string($this->attributes[$attribute]) and trim($this->attributes[$attribute]) === '') <add> { <add> return false; <add> } <add> <add> return true; <ide> } <ide> <ide> /**
1
Javascript
Javascript
use util.inspect for more reliable logging
d40be9cbf254f78d2d125e79f815ccd39df32158
<ide><path>client/src/client/workers/test-evaluator.js <ide> import chai from 'chai'; <ide> import '@babel/polyfill'; <ide> import __toString from 'lodash/toString'; <add>import { format as __format } from '../../utils/format'; <ide> <ide> const __utils = (() => { <ide> const MAX_LOGS_SIZE = 64 * 1024; <ide> const __utils = (() => { <ide> } <ide> } <ide> <del> function replacer(key, value) { <del> if (Number.isNaN(value)) { <del> return 'NaN'; <del> } <del> return value; <del> } <del> <ide> const oldLog = self.console.log.bind(self.console); <ide> function proxyLog(...args) { <del> logs.push(args.map(arg => '' + JSON.stringify(arg, replacer)).join(' ')); <add> logs.push(args.map(arg => __format(arg)).join(' ')); <ide> if (logs.join('\n').length > MAX_LOGS_SIZE) { <ide> flushLogs(); <ide> } <ide><path>client/src/templates/Challenges/utils/frame.js <ide> import { toString, flow } from 'lodash'; <add>import { format } from '../../../utils/format'; <ide> <ide> // we use two different frames to make them all essentially pure functions <ide> // main iframe is responsible rendering the preview and is where we proxy the <ide> const mountFrame = document => ({ element, ...rest }) => { <ide> const buildProxyConsole = proxyLogger => ctx => { <ide> const oldLog = ctx.window.console.log.bind(ctx.window.console); <ide> ctx.window.console.log = function proxyConsole(...args) { <del> proxyLogger(args.map(arg => '' + JSON.stringify(arg)).join(' ')); <add> proxyLogger(args.map(arg => format(arg)).join(' ')); <ide> return oldLog(...args); <ide> }; <ide> return ctx; <ide><path>client/src/utils/format.js <add>import { inspect } from 'util'; <add> <add>export function format(x) { <add> // we're trying to mimic console.log, so we avoid wrapping strings in quotes: <add> if (typeof x === 'string') return x; <add> return inspect(x); <add>} <ide><path>client/src/utils/format.test.js <add>/* global expect BigInt */ <add> <add>const { format } = require('./format'); <add> <add>/* eslint-disable no-unused-vars */ <add>function simpleFun() { <add> var x = 'y'; <add>} <add>/* eslint-enable no-unused-vars */ <add> <add>/* format uses util.inspect to do almost everything, the tests are just there <add>to warn us if util.inspect ever changes */ <add>describe('format', () => { <add> it('returns a string', () => { <add> expect(typeof format('')).toBe('string'); <add> expect(typeof format({})).toBe('string'); <add> expect(typeof format([])).toBe('string'); <add> }); <add> it('does not modify strings', () => { <add> expect(format('')).toBe(''); <add> expect(format('abcde')).toBe('abcde'); <add> expect(format('Case Sensitive')).toBe('Case Sensitive'); <add> }); <add> it('formats shallow objects nicely', () => { <add> expect(format({})).toBe('{}'); <add> expect(format({ a: 'one', b: 'two' })).toBe(`{ a: 'one', b: 'two' }`); <add> }); <add> it('formats functions the same way as console.log', () => { <add> expect(format(simpleFun)).toBe('[Function: simpleFun]'); <add> }); <add> it('recurses into arrays', () => { <add> const objsInArr = [{ a: 'one' }, 'b', simpleFun]; <add> expect(format(objsInArr)).toBe( <add> `[ { a: 'one' }, 'b', [Function: simpleFun] ]` <add> ); <add> }); <add> it('handles all primitive values', () => { <add> const primitives = [ <add> 'str', <add> 57, <add> BigInt(10), <add> true, <add> false, <add> null, <add> // eslint-disable-next-line no-undefined <add> undefined, <add> Symbol('Sym') <add> ]; <add> expect(format(primitives)).toBe( <add> `[ 'str', 57, 10n, true, false, null, undefined, Symbol(Sym) ]` <add> ); <add> }); <add> it(`outputs NaN as 'NaN'`, () => { <add> expect(format(NaN)).toBe('NaN'); <add> }); <add>});
4
PHP
PHP
get view data via array access
e1b8fef59f436902c34f235841303fce055dddab
<ide><path>src/Illuminate/Foundation/Testing/TestResponse.php <ide> public function assertViewMissing($key) <ide> */ <ide> protected function ensureResponseHasView() <ide> { <del> if (! isset($this->original) || ! $this->original instanceof View) { <add> if (! $this->responseHasView()) { <ide> return PHPUnit::fail('The response is not a view.'); <ide> } <ide> <ide> return $this; <ide> } <ide> <add> /** <add> * Determine if the original response is a view. <add> * <add> * @return bool <add> */ <add> protected function responseHasView() <add> { <add> return isset($this->original) && $this->original instanceof View; <add> } <add> <ide> /** <ide> * Assert that the session has a given value. <ide> * <ide> public function __isset($key) <ide> */ <ide> public function offsetExists($offset) <ide> { <del> return isset($this->json()[$offset]); <add> return $this->responseHasView() <add> ? isset($this->original->gatherData()[$key]) <add> : isset($this->json()[$offset]); <ide> } <ide> <ide> /** <ide> public function offsetExists($offset) <ide> */ <ide> public function offsetGet($offset) <ide> { <del> return $this->json()[$offset]; <add> return $this->responseHasView() <add> ? $this->viewData($offset) <add> : $this->json()[$offset]; <ide> } <ide> <ide> /**
1
Text
Text
add missing word in modules.md
cb88f35a733c3d9efab5f7b18ca84047b93e7ab6
<ide><path>doc/api/modules.md <ide> added: v0.1.27 <ide> <ide> * {string} <ide> <del>The directory name of the current module. This the same as the <add>The directory name of the current module. This is the same as the <ide> [`path.dirname()`][] of the [`__filename`][]. <ide> <ide> Example: running `node example.js` from `/Users/mjr`
1
Python
Python
move threshold up for flaky test with electra
e8af90c05210c61afdbf8323473d333a342b37c5
<ide><path>tests/test_modeling_tf_common.py <ide> def test_pt_tf_model_equivalence(self): <ide> <ide> max_diff = np.amax(np.abs(tf_hidden_states - pt_hidden_states)) <ide> # Debug info (remove when fixed) <del> if max_diff >= 2e-2: <add> if max_diff >= 4e-2: <ide> print("===") <ide> print(model_class) <ide> print(config) <ide> print(inputs_dict) <ide> print(pt_inputs_dict) <del> self.assertLessEqual(max_diff, 2e-2) <add> self.assertLessEqual(max_diff, 4e-2) <ide> <ide> # Check we can load pt model in tf and vice-versa with checkpoint => model functions <ide> with tempfile.TemporaryDirectory() as tmpdirname:
1
Text
Text
add v3.26.0 to changelog
d622b7c4282dcdae57d389a01e889afbd0ff93fc
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <del>### v3.26.0-beta.5 (March 16, 2021) <del> <del>- [#19405](https://github.com/emberjs/ember.js/pull/19405) [BUGFIX] Avoid instantiation errors when `app/router.js` injects the router service. <del> <del>### v3.26.0-beta.4 (March 08, 2021) <del> <del>- [#19436](https://github.com/emberjs/ember.js/pull/19436) [BUGFIX] Support observer keys with colons <del>- [#19448](https://github.com/emberjs/ember.js/pull/19448) [BUGFIX] Ensure query params are preserved through an intermediate loading state transition <del>- [#19450](https://github.com/emberjs/ember.js/pull/19450) [BUGFIX] Ensure `routerService.currentRoute.name` and `routerService.currentRouteName` match during loading states <del> <del>### v3.26.0-beta.3 (March 02, 2021) <del> <del>- [#19412](https://github.com/emberjs/ember.js/pull/19412) [BUGFIX] Updates Glimmer VM to 0.76.0, fix: <del> - `if` helper returns `null` instead of `undefined` <del> - Using `get` helper with key `length` on a string in templates <del> - Value of input not updating if it had previously updated with the same string <del>- [#19416](https://github.com/emberjs/ember.js/pull/19416) [BUGFIX] Update Glimmer VM to 0.77, fix dynamic helpers/modifiers <del> <del>### v3.26.0-beta.2 (February 15, 2021) <del> <del>- [#19387](https://github.com/emberjs/ember.js/pull/19387) [BUGFIX] LinkTo with incomplete model failing in rendering tests <del>- [#19395](https://github.com/emberjs/ember.js/pull/19395) [BUGFIX] Only return empty href when LinkTo href generation throws error <del>- [#19396](https://github.com/emberjs/ember.js/pull/19396) [BUGFIX] Revert deprecation of htmlSafe and isHTMLSafe <del>- [#19397](https://github.com/emberjs/ember.js/pull/19397) [BUGFIX] Force building Ember bundles when `targets.node` is defined <del> <del>### v3.26.0-beta.1 (February 08, 2021) <add>### v3.26.0 (March 22, 2021) <ide> <ide> - [#19255](https://github.com/emberjs/ember.js/pull/19255) [DEPRECATION] Deprecate transition methods of controller and route per [RFC #674](https://github.com/emberjs/rfcs/blob/master/text/0674-deprecate-transition-methods-of-controller-and-route.md). <ide> - [#19345](https://github.com/emberjs/ember.js/pull/19345) [DEPRECATION] Deprecate `<LinkTo>` positional arguments per [RFC #698](https://github.com/emberjs/rfcs/blob/master/text/0698-deprecate-link-to-positional-arguments.md). <ide> - [#19379](https://github.com/emberjs/ember.js/pull/19379) [CLEANUP] Refactor DataAdapter to not use observers or array observers <ide> - [#19378](https://github.com/emberjs/ember.js/pull/19378) [BUGFIX] Fix typo in template-only-glimmer-components feature detection <ide> - [#19298](https://github.com/emberjs/ember.js/pull/19298) [BUGFIX] Route serialize did not extract param off proxy <del>- [#19326](https://github.com/emberjs/ember.js/pull/19326) [BUGFIX] Lazily setup the router in non-application tests for <LinkTo> component <del> <add>- [#19469](https://github.com/emberjs/ember.js/pull/19469) [BUGFIX] Prevent eager argument consumption on modifier destruction <add>- [#19405](https://github.com/emberjs/ember.js/pull/19405) [BUGFIX] Avoid instantiation errors when `app/router.js` injects the router service. <add>- [#19436](https://github.com/emberjs/ember.js/pull/19436) [BUGFIX] Support observer keys with colons <ide> <ide> ### v3.25.3 (March 7, 2021) <ide>
1
Ruby
Ruby
fix head_revision definition
9457d1af5e546bb07dacaff5cb516c0bdb9187fb
<ide><path>Library/Homebrew/dev-cmd/pull.rb <ide> def pull <ide> old_versions = current_versions_from_info_external(patch_changes[:formulae].first) if is_bumpable <ide> patch_puller.apply_patch <ide> <del> end_revision = head_revision(url) <add> end_revision = `git rev-parse --short HEAD`.strip <ide> <ide> changed_formulae_names = [] <ide> <ide> def check_bumps(patch_changes) <ide> end <ide> end <ide> <del> def head_revision(_url, fetched) <del> Utils.popen_read("git", "rev-parse", fetched ? "FETCH_HEAD" : "HEAD").strip <del> end <del> <ide> class PatchPuller <ide> attr_reader :base_url <ide> attr_reader :patch_url
1