content_type
stringclasses 8
values | main_lang
stringclasses 7
values | message
stringlengths 1
50
| sha
stringlengths 40
40
| patch
stringlengths 52
962k
| file_count
int64 1
300
|
---|---|---|---|---|---|
Python | Python | add conversion script for t5x to flax | cb7e166428a28194407a9e7808ae6815fe59817e | <ide><path>src/transformers/models/t5/convert_t5x_checkpoint_to_flax.py
<add># coding=utf-8
<add># Copyright 2022 The HuggingFace Inc. team.
<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>"""Convert T5X checkpoints from the original repository to JAX/FLAX model."""
<add>
<add>import argparse
<add>
<add>from t5x import checkpoints
<add>from transformers import FlaxT5ForConditionalGeneration, T5Config
<add>
<add>
<add>def convert_t5x_checkpoint_to_flax(t5x_checkpoint_path, config_name, flax_dump_folder_path):
<add> config = T5Config.from_pretrained(config_name)
<add> flax_model = FlaxT5ForConditionalGeneration(config=config)
<add> t5x_model = checkpoints.load_t5x_checkpoint(t5x_checkpoint_path)
<add>
<add> split_mlp_wi = "wi_0" in t5x_model["target"]["encoder"]["layers_0"]["mlp"]
<add>
<add> # Encoder
<add> for layer_index in range(config.num_layers):
<add> layer_name = f"layers_{str(layer_index)}"
<add>
<add> # Self-Attention
<add> t5x_attention_key = t5x_model["target"]["encoder"][layer_name]["attention"]["key"]["kernel"]
<add> t5x_attention_out = t5x_model["target"]["encoder"][layer_name]["attention"]["out"]["kernel"]
<add> t5x_attention_query = t5x_model["target"]["encoder"][layer_name]["attention"]["query"]["kernel"]
<add> t5x_attention_value = t5x_model["target"]["encoder"][layer_name]["attention"]["value"]["kernel"]
<add>
<add> # Layer Normalization
<add> t5x_attention_layer_norm = t5x_model["target"]["encoder"][layer_name]["pre_attention_layer_norm"]["scale"]
<add>
<add> if split_mlp_wi:
<add> t5x_mlp_wi_0 = t5x_model["target"]["encoder"][layer_name]["mlp"]["wi_0"]["kernel"]
<add> t5x_mlp_wi_1 = t5x_model["target"]["encoder"][layer_name]["mlp"]["wi_1"]["kernel"]
<add> else:
<add> t5x_mlp_wi = t5x_model["target"]["encoder"][layer_name]["mlp"]["wi"]["kernel"]
<add>
<add> t5x_mlp_wo = t5x_model["target"]["encoder"][layer_name]["mlp"]["wo"]["kernel"]
<add>
<add> # Layer Normalization
<add> t5x_mlp_layer_norm = t5x_model["target"]["encoder"][layer_name]["pre_mlp_layer_norm"]["scale"]
<add>
<add> # Assigning
<add> flax_model.params["encoder"]["block"][str(layer_index)]["layer"]["0"]["SelfAttention"]["k"][
<add> "kernel"
<add> ] = t5x_attention_key
<add> flax_model.params["encoder"]["block"][str(layer_index)]["layer"]["0"]["SelfAttention"]["o"][
<add> "kernel"
<add> ] = t5x_attention_out
<add> flax_model.params["encoder"]["block"][str(layer_index)]["layer"]["0"]["SelfAttention"]["q"][
<add> "kernel"
<add> ] = t5x_attention_query
<add> flax_model.params["encoder"]["block"][str(layer_index)]["layer"]["0"]["SelfAttention"]["v"][
<add> "kernel"
<add> ] = t5x_attention_value
<add>
<add> flax_model.params["encoder"]["block"][str(layer_index)]["layer"]["0"]["layer_norm"][
<add> "weight"
<add> ] = t5x_attention_layer_norm
<add>
<add> if split_mlp_wi:
<add> flax_model.params["encoder"]["block"][str(layer_index)]["layer"]["1"]["DenseReluDense"]["wi_0"][
<add> "kernel"
<add> ] = t5x_mlp_wi_0
<add> flax_model.params["encoder"]["block"][str(layer_index)]["layer"]["1"]["DenseReluDense"]["wi_1"][
<add> "kernel"
<add> ] = t5x_mlp_wi_1
<add> else:
<add> flax_model.params["encoder"]["block"][str(layer_index)]["layer"]["1"]["DenseReluDense"]["wi"][
<add> "kernel"
<add> ] = t5x_mlp_wi
<add>
<add> flax_model.params["encoder"]["block"][str(layer_index)]["layer"]["1"]["DenseReluDense"]["wo"][
<add> "kernel"
<add> ] = t5x_mlp_wo
<add> flax_model.params["encoder"]["block"][str(layer_index)]["layer"]["1"]["layer_norm"][
<add> "weight"
<add> ] = t5x_mlp_layer_norm
<add>
<add> # Only for layer 0:
<add> t5x_encoder_rel_embedding = t5x_model["target"]["encoder"]["relpos_bias"]["rel_embedding"].T
<add> flax_model.params["encoder"]["block"]["0"]["layer"]["0"]["SelfAttention"]["relative_attention_bias"][
<add> "embedding"
<add> ] = t5x_encoder_rel_embedding
<add>
<add> # Assigning
<add> t5x_encoder_norm = t5x_model["target"]["encoder"]["encoder_norm"]["scale"]
<add> flax_model.params["encoder"]["final_layer_norm"]["weight"] = t5x_encoder_norm
<add>
<add> # Decoder
<add> for layer_index in range(config.num_layers):
<add> layer_name = f"layers_{str(layer_index)}"
<add>
<add> # Self-Attention
<add> t5x_attention_key = t5x_model["target"]["decoder"][layer_name]["self_attention"]["key"]["kernel"]
<add> t5x_attention_out = t5x_model["target"]["decoder"][layer_name]["self_attention"]["out"]["kernel"]
<add> t5x_attention_query = t5x_model["target"]["decoder"][layer_name]["self_attention"]["query"]["kernel"]
<add> t5x_attention_value = t5x_model["target"]["decoder"][layer_name]["self_attention"]["value"]["kernel"]
<add>
<add> # Layer Normalization
<add> t5x_pre_attention_layer_norm = t5x_model["target"]["decoder"][layer_name]["pre_self_attention_layer_norm"][
<add> "scale"
<add> ]
<add>
<add> # Encoder-Decoder-Attention
<add> t5x_enc_dec_attention_key = t5x_model["target"]["decoder"][layer_name]["encoder_decoder_attention"]["key"][
<add> "kernel"
<add> ]
<add> t5x_enc_dec_attention_out = t5x_model["target"]["decoder"][layer_name]["encoder_decoder_attention"]["out"][
<add> "kernel"
<add> ]
<add> t5x_enc_dec_attention_query = t5x_model["target"]["decoder"][layer_name]["encoder_decoder_attention"]["query"][
<add> "kernel"
<add> ]
<add> t5x_enc_dec_attention_value = t5x_model["target"]["decoder"][layer_name]["encoder_decoder_attention"]["value"][
<add> "kernel"
<add> ]
<add>
<add> # Layer Normalization
<add> t5x_cross_layer_norm = t5x_model["target"]["decoder"][layer_name]["pre_cross_attention_layer_norm"]["scale"]
<add>
<add> # MLP
<add> if split_mlp_wi:
<add> t5x_mlp_wi_0 = t5x_model["target"]["decoder"][layer_name]["mlp"]["wi_0"]["kernel"]
<add> t5x_mlp_wi_1 = t5x_model["target"]["decoder"][layer_name]["mlp"]["wi_1"]["kernel"]
<add> else:
<add> t5x_mlp_wi = t5x_model["target"]["decoder"][layer_name]["mlp"]["wi"]["kernel"]
<add>
<add> t5x_mlp_wo = t5x_model["target"]["decoder"][layer_name]["mlp"]["wo"]["kernel"]
<add>
<add> # Layer Normalization
<add> tx5_mlp_layer_norm = t5x_model["target"]["decoder"][layer_name]["pre_mlp_layer_norm"]["scale"]
<add>
<add> # Assigning
<add> flax_model.params["decoder"]["block"][str(layer_index)]["layer"]["0"]["SelfAttention"]["k"][
<add> "kernel"
<add> ] = t5x_attention_key
<add> flax_model.params["decoder"]["block"][str(layer_index)]["layer"]["0"]["SelfAttention"]["o"][
<add> "kernel"
<add> ] = t5x_attention_out
<add> flax_model.params["decoder"]["block"][str(layer_index)]["layer"]["0"]["SelfAttention"]["q"][
<add> "kernel"
<add> ] = t5x_attention_query
<add> flax_model.params["decoder"]["block"][str(layer_index)]["layer"]["0"]["SelfAttention"]["v"][
<add> "kernel"
<add> ] = t5x_attention_value
<add>
<add> flax_model.params["decoder"]["block"][str(layer_index)]["layer"]["0"]["layer_norm"][
<add> "weight"
<add> ] = t5x_pre_attention_layer_norm
<add>
<add> flax_model.params["decoder"]["block"][str(layer_index)]["layer"]["1"]["EncDecAttention"]["k"][
<add> "kernel"
<add> ] = t5x_enc_dec_attention_key
<add> flax_model.params["decoder"]["block"][str(layer_index)]["layer"]["1"]["EncDecAttention"]["o"][
<add> "kernel"
<add> ] = t5x_enc_dec_attention_out
<add> flax_model.params["decoder"]["block"][str(layer_index)]["layer"]["1"]["EncDecAttention"]["q"][
<add> "kernel"
<add> ] = t5x_enc_dec_attention_query
<add> flax_model.params["decoder"]["block"][str(layer_index)]["layer"]["1"]["EncDecAttention"]["v"][
<add> "kernel"
<add> ] = t5x_enc_dec_attention_value
<add>
<add> flax_model.params["decoder"]["block"][str(layer_index)]["layer"]["1"]["layer_norm"][
<add> "weight"
<add> ] = t5x_cross_layer_norm
<add>
<add> if split_mlp_wi:
<add> flax_model.params["decoder"]["block"][str(layer_index)]["layer"]["2"]["DenseReluDense"]["wi_0"][
<add> "kernel"
<add> ] = t5x_mlp_wi_0
<add> flax_model.params["decoder"]["block"][str(layer_index)]["layer"]["2"]["DenseReluDense"]["wi_1"][
<add> "kernel"
<add> ] = t5x_mlp_wi_1
<add> else:
<add> flax_model.params["decoder"]["block"][str(layer_index)]["layer"]["2"]["DenseReluDense"]["wi"][
<add> "kernel"
<add> ] = t5x_mlp_wi
<add>
<add> flax_model.params["decoder"]["block"][str(layer_index)]["layer"]["2"]["DenseReluDense"]["wo"][
<add> "kernel"
<add> ] = t5x_mlp_wo
<add>
<add> flax_model.params["decoder"]["block"][str(layer_index)]["layer"]["2"]["layer_norm"][
<add> "weight"
<add> ] = tx5_mlp_layer_norm
<add>
<add> # Decoder Normalization
<add> tx5_decoder_norm = t5x_model["target"]["decoder"]["decoder_norm"]["scale"]
<add> flax_model.params["decoder"]["final_layer_norm"]["weight"] = tx5_decoder_norm
<add>
<add> # Only for layer 0:
<add> t5x_decoder_rel_embedding = t5x_model["target"]["decoder"]["relpos_bias"]["rel_embedding"].T
<add> flax_model.params["decoder"]["block"]["0"]["layer"]["0"]["SelfAttention"]["relative_attention_bias"][
<add> "embedding"
<add> ] = t5x_decoder_rel_embedding
<add>
<add> # Token Embeddings
<add> tx5_token_embeddings = t5x_model["target"]["token_embedder"]["embedding"]
<add> flax_model.params["shared"]["embedding"] = tx5_token_embeddings
<add>
<add> # LM Head (only in v1.1 checkpoints)
<add> if "logits_dense" in t5x_model["target"]["decoder"]:
<add> flax_model.params["lm_head"]["kernel"] = t5x_model["target"]["decoder"]["logits_dense"]["kernel"]
<add>
<add> flax_model.save_pretrained(flax_dump_folder_path)
<add> print("T5X Model was sucessfully converted!")
<add>
<add>
<add>if __name__ == "__main__":
<add> parser = argparse.ArgumentParser()
<add> # Required parameters
<add> parser.add_argument(
<add> "--t5x_checkpoint_path", default=None, type=str, required=True, help="Path the TX5 checkpoint."
<add> )
<add> parser.add_argument("--config_name", default=None, type=str, required=True, help="Config name of T5 model.")
<add> parser.add_argument(
<add> "--flax_dump_folder_path", default=None, type=str, required=True, help="Path to the output FLAX model."
<add> )
<add> args = parser.parse_args()
<add> convert_t5x_checkpoint_to_flax(args.t5x_checkpoint_path, args.config_name, args.flax_dump_folder_path) | 1 |
PHP | PHP | add test for chaining | 2f7d77ae856a9a854518ef96ac17e081305d5007 | <ide><path>tests/TestCase/View/ViewVarsTraitTest.php
<ide> public function testSetTwoParam() {
<ide> $this->assertEquals(['testing' => 'value'], $this->subject->viewVars);
<ide> }
<ide>
<add>/**
<add> * test chainable set()
<add> *
<add> * @return void
<add> */
<add> public function testSetChained() {
<add> $this->subject->set('testing', 'value')
<add> ->set('foo', 'bar');
<add> $this->assertEquals(['testing' => 'value', 'foo' => 'bar'], $this->subject->viewVars);
<add> }
<add>
<ide> /**
<ide> * test set() with 2 params in combine mode
<ide> * | 1 |
Python | Python | fix small bugs in `run_classifier_pytorch.py` | 1d8511f8f2c926c72146e87029d5b0acb48bd06e | <ide><path>run_classifier_pytorch.py
<ide> def main():
<ide> train_dataloader = DataLoader(train_data, sampler=train_sampler, batch_size=args.train_batch_size)
<ide>
<ide> model.train()
<del> for epoch in range(args.num_train_epochs):
<add> for epoch in range(int(args.num_train_epochs)):
<ide> for input_ids, input_mask, segment_ids, label_ids in train_dataloader:
<ide> input_ids = input_ids.to(device)
<ide> input_mask = input_mask.float().to(device) | 1 |
Python | Python | allow prefix for any generative model | 995a958dd18d4326e608efc3bfc4005acfef8e56 | <ide><path>examples/text-generation/run_generation.py
<ide> # Padding text to help Transformer-XL and XLNet with short prompts as proposed by Aman Rusia
<ide> # in https://github.com/rusiaaman/XLNet-gen#methodology
<ide> # and https://medium.com/@amanrusia/xlnet-speaks-comparison-to-gpt-2-ea1a4e9ba39e
<del>PADDING_TEXT = """In 1991, the remains of Russian Tsar Nicholas II and his family
<add>PREFIX = """In 1991, the remains of Russian Tsar Nicholas II and his family
<ide> (except for Alexei and Maria) are discovered.
<ide> The voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the
<ide> remainder of the story. 1883 Western Siberia,
<ide> def prepare_xlm_input(args, model, tokenizer, prompt_text):
<ide>
<ide>
<ide> def prepare_xlnet_input(args, _, tokenizer, prompt_text):
<del> prompt_text = (args.padding_text if args.padding_text else PADDING_TEXT) + prompt_text
<add> prefix = args.prefix if args.prefix else args.padding_text if args.padding_text else PREFIX
<add> prompt_text = prefix + prompt_text
<ide> return prompt_text
<ide>
<ide>
<ide> def prepare_transfoxl_input(args, _, tokenizer, prompt_text):
<del> prompt_text = (args.padding_text if args.padding_text else PADDING_TEXT) + prompt_text
<add> prefix = args.prefix if args.prefix else args.padding_text if args.padding_text else PREFIX
<add> prompt_text = prefix + prompt_text
<ide> return prompt_text
<ide>
<ide>
<ide> def main():
<ide> parser.add_argument("--k", type=int, default=0)
<ide> parser.add_argument("--p", type=float, default=0.9)
<ide>
<del> parser.add_argument("--padding_text", type=str, default="", help="Padding text for Transfo-XL and XLNet.")
<add> parser.add_argument("--prefix", type=str, default="", help="Text added prior to input.")
<add> parser.add_argument("--padding_text", type=str, default="", help="Deprecated, the use of `--prefix` is preferred.")
<ide> parser.add_argument("--xlm_language", type=str, default="", help="Optional language when used with the XLM model.")
<ide>
<ide> parser.add_argument("--seed", type=int, default=42, help="random seed for initialization")
<ide> def main():
<ide> preprocessed_prompt_text, add_special_tokens=False, return_tensors="pt", **tokenizer_kwargs
<ide> )
<ide> else:
<del> encoded_prompt = tokenizer.encode(prompt_text, add_special_tokens=False, return_tensors="pt")
<add> prefix = args.prefix if args.prefix else args.padding_text
<add> encoded_prompt = tokenizer.encode(prefix + prompt_text, add_special_tokens=False, return_tensors="pt")
<ide> encoded_prompt = encoded_prompt.to(args.device)
<ide>
<ide> if encoded_prompt.size()[-1] == 0:
<ide><path>src/transformers/pipelines.py
<ide> class TextGenerationPipeline(Pipeline):
<ide> `huggingface.co/models <https://huggingface.co/models?search=&filter=lm-head>`__.
<ide> """
<ide>
<del> # Padding text to help Transformer-XL and XLNet with short prompts as proposed by Aman Rusia
<add> # Prefix text to help Transformer-XL and XLNet with short prompts as proposed by Aman Rusia
<ide> # in https://github.com/rusiaaman/XLNet-gen#methodology
<ide> # and https://medium.com/@amanrusia/xlnet-speaks-comparison-to-gpt-2-ea1a4e9ba39e
<ide>
<del> PADDING_TEXT = """In 1991, the remains of Russian Tsar Nicholas II and his family
<add> XL_PREFIX = """In 1991, the remains of Russian Tsar Nicholas II and his family
<ide> (except for Alexei and Maria) are discovered.
<ide> The voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the
<ide> remainder of the story. 1883 Western Siberia,
<ide> class TextGenerationPipeline(Pipeline):
<ide> father initially slaps him for making such an accusation, Rasputin watches as the
<ide> man is chased outside and beaten. Twenty years later, Rasputin sees a vision of
<ide> the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous,
<del> with people, even a bishop, begging for his blessing. """
<add> with people, even a bishop, begging for his blessing. <eod> </s> <eos>"""
<ide>
<ide> ALLOWED_MODELS = [
<ide> "XLNetLMHeadModel",
<ide> def _parse_and_tokenize(self, *args, padding=True, add_special_tokens=True, **kw
<ide> return inputs
<ide>
<ide> def __call__(
<del> self, *args, return_tensors=False, return_text=True, clean_up_tokenization_spaces=False, **generate_kwargs
<add> self,
<add> *args,
<add> return_tensors=False,
<add> return_text=True,
<add> clean_up_tokenization_spaces=False,
<add> prefix=None,
<add> **generate_kwargs
<ide> ):
<ide> """
<ide> Complete the prompt(s) given as inputs.
<ide> def __call__(
<ide> Whether or not to include the decoded texts in the outputs.
<ide> clean_up_tokenization_spaces (:obj:`bool`, `optional`, defaults to :obj:`False`):
<ide> Whether or not to clean up the potential extra spaces in the text output.
<add> prefix (:obj:`str`, `optional`):
<add> Prefix added to prompt.
<ide> generate_kwargs:
<ide> Additional keyword arguments to pass along to the generate method of the model (see the generate
<ide> method corresponding to your framework `here <./model.html#generative-models>`__).
<ide> def __call__(
<ide> for prompt_text in text_inputs:
<ide> # Manage correct placement of the tensors
<ide> with self.device_placement():
<del> if self.model.__class__.__name__ in [
<add> prefix = prefix if prefix is not None else self.model.config.prefix
<add> if prefix is None and self.model.__class__.__name__ in [
<ide> "XLNetLMHeadModel",
<ide> "TransfoXLLMHeadModel",
<ide> "TFXLNetLMHeadModel",
<ide> "TFTransfoXLLMHeadModel",
<ide> ]:
<del> # For XLNet and TransformerXL we had an article to the prompt to give more state to the model.
<del> padding_text = self.PADDING_TEXT + self.tokenizer.eos_token
<del> padding = self._parse_and_tokenize(padding_text, padding=False, add_special_tokens=False)
<add> # For XLNet and TransformerXL we add an article to the prompt to give more state to the model.
<add> prefix = self.XL_PREFIX
<add>
<add> if prefix:
<add> prefix_inputs = self._parse_and_tokenize(prefix, padding=False, add_special_tokens=False)
<ide> # This impacts max_length and min_length argument that need adjusting.
<del> padding_length = padding["input_ids"].shape[-1]
<del> if "max_length" in generate_kwargs and generate_kwargs["max_length"] is not None:
<del> generate_kwargs["max_length"] += padding_length
<del> if "min_length" in generate_kwargs and generate_kwargs["min_length"] is not None:
<del> generate_kwargs["min_length"] += padding_length
<del>
<del> inputs = self._parse_and_tokenize(
<del> padding_text + prompt_text, padding=False, add_special_tokens=False
<del> )
<del> else:
<del> inputs = self._parse_and_tokenize(prompt_text, padding=False, add_special_tokens=False)
<add> prefix_length = prefix_inputs["input_ids"].shape[-1]
<add> if generate_kwargs.get("max_length", None) is not None:
<add> generate_kwargs["max_length"] += prefix_length
<add> if generate_kwargs.get("min_length", None) is not None:
<add> generate_kwargs["min_length"] += prefix_length
<add>
<add> prefix = prefix or ""
<add> inputs = self._parse_and_tokenize(prefix + prompt_text, padding=False, add_special_tokens=False)
<ide>
<ide> # set input_ids to None to allow empty prompt
<ide> if inputs["input_ids"].shape[-1] == 0:
<ide><path>tests/test_pipelines.py
<ide> def test_torch_text_generation(self):
<ide> for model_name in TEXT_GENERATION_FINETUNED_MODELS:
<ide> nlp = pipeline(task="text-generation", model=model_name, tokenizer=model_name, framework="pt")
<ide> self._test_mono_column_pipeline(nlp, VALID_INPUTS, {})
<add> self._test_mono_column_pipeline(nlp, VALID_INPUTS, {}, prefix="This is ")
<ide>
<ide> @require_tf
<ide> def test_tf_text_generation(self):
<ide> for model_name in TEXT_GENERATION_FINETUNED_MODELS:
<ide> nlp = pipeline(task="text-generation", model=model_name, tokenizer=model_name, framework="tf")
<ide> self._test_mono_column_pipeline(nlp, VALID_INPUTS, {})
<add> self._test_mono_column_pipeline(nlp, VALID_INPUTS, {}, prefix="This is ")
<ide>
<ide> @slow
<ide> @require_torch | 3 |
Text | Text | use bullets. as they render better | 0fa5aa6a198cc9623f9e3ca137010be8e43c9e75 | <ide><path>README.md
<ide> tests for CakePHP by doing the following:
<ide>
<ide> ## Some Handy Links
<ide>
<del>[CakePHP](http://www.cakephp.org) - The rapid development PHP framework.
<del>
<del>[CookBook](http://book.cakephp.org) - The CakePHP user documentation; start learning here!
<del>
<del>[API](http://api.cakephp.org) - A reference to CakePHP's classes.
<del>
<del>[Plugins](http://plugins.cakephp.org) - A repository of extensions to the framework.
<del>
<del>[The Bakery](http://bakery.cakephp.org) - Tips, tutorials and articles.
<del>
<del>[Community Center](http://community.cakephp.org) - A source for everything community related.
<del>
<del>[Training](http://training.cakephp.org) - Join a live session and get skilled with the framework.
<del>
<del>[CakeFest](http://cakefest.org) - Don't miss our annual CakePHP conference.
<del>
<del>[Cake Software Foundation](http://cakefoundation.org) - Promoting development related to CakePHP.
<add>* [CakePHP](http://www.cakephp.org) - The rapid development PHP framework.
<add>* [CookBook](http://book.cakephp.org) - The CakePHP user documentation; start learning here!
<add>* [API](http://api.cakephp.org) - A reference to CakePHP's classes.
<add>* [Plugins](http://plugins.cakephp.org) - A repository of extensions to the framework.
<add>* [The Bakery](http://bakery.cakephp.org) - Tips, tutorials and articles.
<add>* [Community Center](http://community.cakephp.org) - A source for everything community related.
<add>* [Training](http://training.cakephp.org) - Join a live session and get skilled with the framework.
<add>* [CakeFest](http://cakefest.org) - Don't miss our annual CakePHP conference.
<add>* [Cake Software Foundation](http://cakefoundation.org) - Promoting development related to CakePHP.
<ide>
<ide> ## Get Support!
<ide>
<del>[Slack](http://cakesf.herokuapp.com/) - Join us on Slack.
<del>
<del>[#cakephp](http://webchat.freenode.net/?channels=#cakephp) on irc.freenode.net - Come chat with us, we have cake.
<del>
<del>[Forum](http://discourse.cakephp.org/) - Offical CakePHP forum.
<del>
<del>[GitHub Issues](https://github.com/cakephp/cakephp/issues) - Got issues? Please tell us!
<add>* [Slack](http://cakesf.herokuapp.com/) - Join us on Slack.
<add>* [#cakephp](http://webchat.freenode.net/?channels=#cakephp) on irc.freenode.net - Come chat with us, we have cake.
<add>* [Forum](http://discourse.cakephp.org/) - Offical CakePHP forum.
<add>* [GitHub Issues](https://github.com/cakephp/cakephp/issues) - Got issues? Please tell us!
<ide>
<ide> [Roadmaps](https://github.com/cakephp/cakephp/wiki#roadmaps) - Want to contribute? Get involved!
<ide>
<ide> ## Contributing
<ide>
<del>[CONTRIBUTING.md](.github/CONTRIBUTING.md) - Quick pointers for contributing to the CakePHP project.
<del>
<del>[CookBook "Contributing" Section](http://book.cakephp.org/3.0/en/contributing.html) - Details about contributing to the project.
<add>* [CONTRIBUTING.md](.github/CONTRIBUTING.md) - Quick pointers for contributing to the CakePHP project.
<add>* [CookBook "Contributing" Section](http://book.cakephp.org/3.0/en/contributing.html) - Details about contributing to the project.
<ide>
<ide> # Security
<ide> | 1 |
PHP | PHP | fix associate on morphto | 933eb1fef3d630c8d9355c72f5ffa8782cb4610c | <ide><path>src/Illuminate/Database/Eloquent/Relations/MorphTo.php
<ide> public function getDictionary()
<ide> return $this->dictionary;
<ide> }
<ide>
<add> /**
<add> * Associate the model instance to the given parent.
<add> *
<add> * @param \Illuminate\Database\Eloquent\Model $model
<add> * @return \Illuminate\Database\Eloquent\Model
<add> */
<add> public function associate(Model $model)
<add> {
<add> $this->parent->setAttribute($this->foreignKey, $model->getKey());
<add>
<add> $this->parent->setAttribute($this->morphType, get_class($model));
<add>
<add> return $this->parent->setRelation($this->relation, $model);
<add> }
<add>
<ide> }
<ide><path>tests/Database/DatabaseEloquentMorphToTest.php
<ide> public function testModelsAreProperlyPulledAndMatched()
<ide> }
<ide>
<ide>
<add> public function testAssociateMethodSetsForeignKeyAndTypeOnModel()
<add> {
<add> $parent = m::mock('Illuminate\Database\Eloquent\Model');
<add> $parent->shouldReceive('getAttribute')->once()->with('foreign_key')->andReturn('foreign.value');
<add>
<add> $relation = $this->getRelationAssociate($parent);
<add>
<add> $associate = m::mock('Illuminate\Database\Eloquent\Model');
<add> $associate->shouldReceive('getKey')->once()->andReturn(1);
<add>
<add> $parent->shouldReceive('setAttribute')->once()->with('foreign_key', 1);
<add> $parent->shouldReceive('setAttribute')->once()->with('morph_type', get_class($associate));
<add> $parent->shouldReceive('setRelation')->once()->with('relation', $associate);
<add>
<add> $relation->associate($associate);
<add> }
<add>
<add>
<add> protected function getRelationAssociate($parent)
<add> {
<add> $builder = m::mock('Illuminate\Database\Eloquent\Builder');
<add> $builder->shouldReceive('where')->with('relation.id', '=', 'foreign.value');
<add> $related = m::mock('Illuminate\Database\Eloquent\Model');
<add> $related->shouldReceive('getKey')->andReturn(1);
<add> $related->shouldReceive('getTable')->andReturn('relation');
<add> $builder->shouldReceive('getModel')->andReturn($related);
<add> return new MorphTo($builder, $parent, 'foreign_key', 'id', 'morph_type', 'relation');
<add> }
<add>
<add>
<ide> public function getRelation($parent = null)
<ide> {
<ide> $builder = m::mock('Illuminate\Database\Eloquent\Builder'); | 2 |
PHP | PHP | fix failing test | 7e60cb490a2ed449c2a763f7e4403ebfc90c3ce5 | <ide><path>tests/TestCase/Network/Email/EmailTest.php
<ide> public function testSendRenderWithImage() {
<ide> $server .= ':' . env('SERVER_PORT');
<ide> }
<ide>
<del> $expected = '<img src="http://' . $server . '/img/image.gif" alt="cool image" width="100" height="100" />';
<add> $expected = '<img src="http://' . $server . '/img/image.gif" alt="cool image" width="100" height="100"';
<ide> $result = $this->CakeEmail->send();
<ide> $this->assertContains($expected, $result['message']);
<ide> } | 1 |
Ruby | Ruby | fix typo in keg#fixed_name invocation | fb929f429f06131635b73c58a28175ec01d1306b | <ide><path>Library/Homebrew/keg_fix_install_names.rb
<ide> def fix_install_names options={}
<ide> install_name_tool("-id", id, file) if file.dylib?
<ide>
<ide> bad_names.each do |bad_name|
<del> new_name = fixed_name(file, bad_name, options)
<add> new_name = fixed_name(file, bad_name)
<ide> unless new_name == bad_name
<ide> install_name_tool("-change", bad_name, new_name, file)
<ide> end | 1 |
Java | Java | fix flowable.tolist() onnext/cancel race | 6c8b0efade6e2b82b32daa18fec7b045aabb3f6c | <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableToList.java
<ide> public void onSubscribe(Subscription s) {
<ide>
<ide> @Override
<ide> public void onNext(T t) {
<del> value.add(t);
<add> U v = value;
<add> if (v != null) {
<add> v.add(t);
<add> }
<ide> }
<ide>
<ide> @Override
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableToListTest.java
<ide>
<ide> package io.reactivex.internal.operators.flowable;
<ide>
<add>import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> import java.util.*;
<ide> import org.reactivestreams.Subscriber;
<ide>
<ide> import io.reactivex.*;
<del>import io.reactivex.Flowable;
<ide> import io.reactivex.exceptions.TestException;
<ide> import io.reactivex.observers.TestObserver;
<ide> import io.reactivex.processors.PublishProcessor;
<ide> public Collection<Integer> call() throws Exception {
<ide> .assertFailure(NullPointerException.class)
<ide> .assertErrorMessage("The collectionSupplier returned a null collection. Null values are generally not allowed in 2.x operators and sources.");
<ide> }
<add>
<add> @Test
<add> public void onNextCancelRace() {
<add> for (int i = 0; i < 1000; i++) {
<add> final PublishProcessor<Integer> pp = PublishProcessor.create();
<add> final TestObserver<List<Integer>> ts = pp.toList().test();
<add>
<add> Runnable r1 = new Runnable() {
<add> @Override
<add> public void run() {
<add> pp.onNext(1);
<add> }
<add> };
<add> Runnable r2 = new Runnable() {
<add> @Override
<add> public void run() {
<add> ts.cancel();
<add> }
<add> };
<add>
<add> TestHelper.race(r1, r2);
<add> }
<add>
<add> }
<add>
<add> @Test
<add> public void onNextCancelRaceFlowable() {
<add> for (int i = 0; i < 1000; i++) {
<add> final PublishProcessor<Integer> pp = PublishProcessor.create();
<add> final TestSubscriber<List<Integer>> ts = pp.toList().toFlowable().test();
<add>
<add> Runnable r1 = new Runnable() {
<add> @Override
<add> public void run() {
<add> pp.onNext(1);
<add> }
<add> };
<add> Runnable r2 = new Runnable() {
<add> @Override
<add> public void run() {
<add> ts.cancel();
<add> }
<add> };
<add>
<add> TestHelper.race(r1, r2);
<add> }
<add>
<add> }
<add>
<add> @Test
<add> public void onCompleteCancelRaceFlowable() {
<add> for (int i = 0; i < 1000; i++) {
<add> final PublishProcessor<Integer> pp = PublishProcessor.create();
<add> final TestSubscriber<List<Integer>> ts = pp.toList().toFlowable().test();
<add>
<add> pp.onNext(1);
<add>
<add> Runnable r1 = new Runnable() {
<add> @Override
<add> public void run() {
<add> pp.onComplete();
<add> }
<add> };
<add> Runnable r2 = new Runnable() {
<add> @Override
<add> public void run() {
<add> ts.cancel();
<add> }
<add> };
<add>
<add> TestHelper.race(r1, r2);
<add>
<add> if (ts.valueCount() != 0) {
<add> ts.assertValue(Arrays.asList(1))
<add> .assertNoErrors();
<add> }
<add> }
<add>
<add> }
<ide> } | 2 |
Python | Python | add stub 'yield' to basetrigger.run | c32ffb0006593a0756d1c65b7f19fac475566cec | <ide><path>airflow/triggers/base.py
<ide> async def run(self) -> AsyncIterator["TriggerEvent"]:
<ide> and then rely on cleanup() being called when they are no longer needed.
<ide> """
<ide> raise NotImplementedError("Triggers must implement run()")
<add> yield # To convince Mypy this is an async iterator.
<ide>
<ide> def cleanup(self) -> None:
<ide> """ | 1 |
Ruby | Ruby | fix formatting of `pick` [ci skip] | b91a4a082659771d29350008d6ff2cfef0cc4b3d | <ide><path>activerecord/lib/active_record/relation/calculations.rb
<ide> def pluck(*column_names)
<ide> end
<ide>
<ide> # Pick the value(s) from the named column(s) in the current relation.
<del> # This is short-hand for `relation.limit(1).pluck(*column_names).first`, and is primarily useful
<add> # This is short-hand for <tt>relation.limit(1).pluck(*column_names).first</tt>, and is primarily useful
<ide> # when you have a relation that's already narrowed down to a single row.
<ide> #
<ide> # Just like #pluck, #pick will only load the actual value, not the entire record object, so it's also | 1 |
Javascript | Javascript | move flex gap props to correct type | ff984ac9b55c9c1af50d5785863f5f36f92b62d2 | <ide><path>Libraries/StyleSheet/StyleSheetTypes.js
<ide> type ____LayoutStyle_Internal = $ReadOnly<{
<ide> * @platform ios
<ide> */
<ide> direction?: 'inherit' | 'ltr' | 'rtl',
<add>
<add> /**
<add> * In React Native, gap works the same way it does in CSS.
<add> * If there are two or more children in a container, they will be separated from each other
<add> * by the value of the gap - but the children will not be separated from the edges of their parent container.
<add> * For horizontal gaps, use columnGap, for vertical gaps, use rowGap, and to apply both at the same time, it's gap.
<add> * When align-content or justify-content are set to space-between or space-around, the separation
<add> * between children may be larger than the gap value.
<add> * See https://developer.mozilla.org/en-US/docs/Web/CSS/gap for more details.
<add> */
<add> rowGap?: number,
<add> columnGap?: number,
<add> gap?: number,
<ide> }>;
<ide>
<ide> /**
<ide> export type ____ShadowStyle_InternalCore = $ReadOnly<{
<ide> * @platform ios
<ide> */
<ide> shadowRadius?: number,
<del>
<del> /**
<del> * In React Native, gap works the same way it does in CSS.
<del> * If there are two or more children in a container, they will be separated from each other
<del> * by the value of the gap - but the children will not be separated from the edges of their parent container.
<del> * For horizontal gaps, use columnGap, for vertical gaps, use rowGap, and to apply both at the same time, it's gap.
<del> * When align-content or justify-content are set to space-between or space-around, the separation
<del> * between children may be larger than the gap value.
<del> * See https://developer.mozilla.org/en-US/docs/Web/CSS/gap for more details.
<del> */
<del> rowGap?: number,
<del> columnGap?: number,
<del> gap?: number,
<ide> }>;
<ide>
<ide> export type ____ShadowStyle_Internal = $ReadOnly<{ | 1 |
Javascript | Javascript | remove unused export from domchildrenoperations | cfec10bd51a517cad24778d5eea1d6b598e717bc | <ide><path>src/renderers/dom/client/utils/DOMChildrenOperations.js
<ide> var DOMChildrenOperations = {
<ide>
<ide> dangerouslyReplaceNodeWithMarkup: Danger.dangerouslyReplaceNodeWithMarkup,
<ide>
<del> updateTextContent: setTextContent,
<del>
<ide> replaceDelimitedText: replaceDelimitedText,
<ide>
<ide> /**
<ide> var DOMChildrenOperations = {
<ide> };
<ide>
<ide> ReactPerf.measureMethods(DOMChildrenOperations, 'DOMChildrenOperations', {
<del> updateTextContent: 'updateTextContent',
<ide> replaceDelimitedText: 'replaceDelimitedText',
<ide> });
<ide>
<ide><path>src/test/ReactDefaultPerfAnalysis.js
<ide> var DOM_OPERATION_TYPES = {
<ide> 'setValueForStyles': 'update styles',
<ide> 'replaceNodeWithMarkup': 'replace',
<ide> 'replaceDelimitedText': 'replace',
<del> 'updateTextContent': 'set textContent',
<ide> };
<ide>
<ide> function getTotalTime(measurements) { | 2 |
Text | Text | fix spelling in react-devtools changelog.md | 69aafbf4dfaab408cd862b10dcea29e6ef0b7bd9 | <ide><path>packages/react-devtools/CHANGELOG.md
<ide> ## 4.0.3 (August 17, 2019)
<ide> #### Bug fixes
<ide> * ES6 `Map` and `Set`, typed arrays, and other unnserializable types (e.g. Immutable JS) can now be inspected.
<del>* Empty objects and arrays now display an "(empty)" label to the right to be reduce confusion.
<add>* Empty objects and arrays now display an "(empty)" label to the right to reduce confusion.
<ide> * Components that use only the `useContext` hook now properly display hooks values in side panel.
<ide> * Style editor now supports single quotes around string values (e.g. both `"red"` and `'red'`).
<ide> * Fixed edge case bug that prevented profiling when both React v16 and v15 were present on a page.
<ide> You can view a component's props, state, and hooks by selecting it:
<ide>
<ide> #### "Rendered by" list
<ide>
<del>In React, an element's "owner" refers the thing that rendered it. Sometimes an element's parent is also its owner, but usually they're different. This distinction is important because props come from owners.
<add>In React, an element's "owner" refers to the thing that rendered it. Sometimes an element's parent is also its owner, but usually they're different. This distinction is important because props come from owners.
<ide>
<ide> 
<ide> | 1 |
Ruby | Ruby | add api_only option to generators | 101df203eb8e96a398792a3e3308e93c2fd96a47 | <ide><path>railties/lib/rails/configuration.rb
<ide> def merge_into(other) #:nodoc:
<ide> end
<ide>
<ide> class Generators #:nodoc:
<del> attr_accessor :aliases, :options, :templates, :fallbacks, :colorize_logging
<add> attr_accessor :aliases, :options, :templates, :fallbacks, :colorize_logging, :api_only
<ide> attr_reader :hidden_namespaces
<ide>
<ide> def initialize
<ide> def initialize
<ide> @fallbacks = {}
<ide> @templates = []
<ide> @colorize_logging = true
<add> @api_only = false
<ide> @hidden_namespaces = []
<ide> end
<ide> | 1 |
Python | Python | add benchmark for permutation | 4cb22829bcdd12da97455253a6aca6fd1053982d | <ide><path>benchmarks/benchmarks/bench_random.py
<ide> def time_randint_slow(self, name):
<ide> high = self.high[name]
<ide> np.random.randint(0, high + 1, size=10**5, dtype=name)
<ide>
<add>
<add>class Permutation(Benchmark):
<add> def setup(self):
<add> self.n = 10000
<add> self.a_1d = np.random.random_sample(self.n)
<add> self.a_2d = np.random.random_sample((self.n, 2))
<add>
<add> def time_permutation_1d(self):
<add> np.random.permutation(self.a_1d)
<add>
<add> def time_permutation_2d(self):
<add> np.random.permutation(self.a_2d)
<add>
<add> def time_permutation_int(self):
<add> np.random.permutation(self.n) | 1 |
Javascript | Javascript | remove obsolete uglifyjs workaround | d41fc68d9b89d39f8c71ae9f810b72798ff3e9ac | <ide><path>build/tasks/dist.js
<ide> module.exports = function( grunt ) {
<ide> nonascii = true;
<ide> }
<ide>
<del> // Modify map/min so that it points to files in the same folder;
<del> // see https://github.com/mishoo/UglifyJS2/issues/47
<del> if ( /\.map$/.test( filename ) ) {
<del> text = text.replace( /"dist\//g, "\"" );
<del> fs.writeFileSync( filename, text, "utf-8" );
<del> }
<del>
<ide> // Optionally copy dist files to other locations
<ide> paths.forEach(function( path ) {
<ide> var created; | 1 |
Text | Text | add code of conduct section to contributing.md | 0f0c2a131be6e574aa1f872ed727b7e5670e740a | <ide><path>CONTRIBUTING.md
<ide> CakePHP loves to welcome your contributions. There are several ways to help out:
<ide> There are a few guidelines that we need contributors to follow so that we have a
<ide> chance of keeping on top of things.
<ide>
<add>## Code of Conduct
<add>
<add>Help us keep CakePHP open and inclusive. Please read and follow our [Code of Conduct](https://github.com/cakephp/CoC/blob/master/CODE_OF_CONDUCT.md).
<add>
<ide> ## Getting Started
<ide>
<ide> * Make sure you have a [GitHub account](https://github.com/signup/free). | 1 |
Text | Text | remove version header from railties changelog.md | e882ce00ab38a5b6c652ac515bde76b86eef4dd7 | <ide><path>railties/CHANGELOG.md
<del>## Rails 5.1.0.alpha ##
<del>
<ide> * Added a shared section to `config/secrets.yml` that will be loaded for all environments.
<ide>
<ide> *DHH* | 1 |
Python | Python | remove dead code from review | 867eb78d25a0640c43b67bc7d3d0fe068ba85680 | <ide><path>numpy/random/tests/test_extending.py
<ide> @pytest.mark.slow
<ide> def test_cython(tmp_path):
<ide> examples = os.path.join(os.path.dirname(__file__), '..', '_examples')
<del> base = os.path.dirname(examples)
<ide> shutil.copytree(examples, tmp_path / '_examples')
<ide> subprocess.check_call([sys.executable, 'setup.py', 'build'],
<ide> cwd=str(tmp_path / '_examples' / 'cython')) | 1 |
Ruby | Ruby | fix vulnerability on open redirects | 708bb9d3142f906cf435465898955cb97fc8a37d | <ide><path>actionpack/lib/action_controller/metal/redirecting.rb
<ide> def _enforce_open_redirect_protection(location, allow_other_host:)
<ide> end
<ide>
<ide> def _url_host_allowed?(url)
<del> [request.host, nil].include?(URI(url.to_s).host)
<add> host = URI(url.to_s).host
<add> host == request.host || host.nil? && url.to_s.start_with?("/")
<ide> rescue ArgumentError, URI::Error
<ide> false
<ide> end
<ide><path>actionpack/test/controller/redirect_test.rb
<ide> def unsafe_redirect_back
<ide> redirect_back_or_to "http://www.rubyonrails.org/"
<ide> end
<ide>
<add> def unsafe_redirect_malformed
<add> redirect_to "http:///www.rubyonrails.org/"
<add> end
<add>
<ide> def only_path_redirect
<ide> redirect_to action: "other_host", only_path: true
<ide> end
<ide> def test_unsafe_redirect_back
<ide> end
<ide> end
<ide>
<add> def test_unsafe_redirect_with_malformed_url
<add> with_raise_on_open_redirects do
<add> error = assert_raise(ActionController::Redirecting::UnsafeRedirectError) do
<add> get :unsafe_redirect_malformed
<add> end
<add>
<add> assert_equal "Unsafe redirect to \"http:///www.rubyonrails.org/\", pass allow_other_host: true to redirect anyway.", error.message
<add> end
<add> end
<add>
<ide> def test_only_path_redirect
<ide> with_raise_on_open_redirects do
<ide> get :only_path_redirect | 2 |
Python | Python | force new instance creation in multirnncell | 320be60bd22a4518b1300c5fa6d572b49f20bafc | <ide><path>neural_gpu/neural_gpu.py
<ide> def dec_step(step, it, it_int, decided, output_ta, tgts,
<ide> # This is just for running a baseline RNN seq2seq model.
<ide> if do_rnn:
<ide> self.after_enc_step.append(step) # Not meaningful here, but needed.
<del> lstm_cell = tf.contrib.rnn.BasicLSTMCell(height * nmaps)
<del> cell = tf.contrib.rnn.MultiRNNCell([lstm_cell] * nconvs)
<add> def lstm_cell():
<add> return tf.contrib.rnn.BasicLSTMCell(height * nmaps)
<add> cell = tf.contrib.rnn.MultiRNNCell(
<add> [lstm_cell() for _ in range(nconvs)])
<ide> with tf.variable_scope("encoder"):
<ide> encoder_outputs, encoder_state = tf.nn.dynamic_rnn(
<ide> cell, tf.reshape(step, [batch_size, length, height * nmaps]), | 1 |
Javascript | Javascript | remove unnecessary call to decodeuricomponent | 528f56a690295650f54eeb2238609446635c5db0 | <ide><path>src/ngRoute/route.js
<ide> function $RouteProvider(){
<ide> for (var i = 1, len = m.length; i < len; ++i) {
<ide> var key = keys[i - 1];
<ide>
<del> var val = 'string' == typeof m[i]
<del> ? decodeURIComponent(m[i])
<del> : m[i];
<add> var val = m[i];
<ide>
<ide> if (key && val) {
<ide> params[key.name] = val;
<ide><path>test/ngRoute/routeSpec.js
<ide> describe('$route', function() {
<ide> expect($route.current).toBeUndefined();
<ide> }));
<ide>
<del> it('matches literal .', inject(function($route, $location, $rootScope) {
<add> it('matches literal *', inject(function($route, $location, $rootScope) {
<ide> $location.path('/$testX23/foo*(bar)/222');
<ide> $rootScope.$digest();
<ide> expect($route.current).toBeUndefined();
<ide> }));
<ide>
<del> it('matches literal *', inject(function($route, $location, $rootScope) {
<add> it('matches literal .', inject(function($route, $location, $rootScope) {
<ide> $location.path('/$test.23/foooo(bar)/222');
<ide> $rootScope.$digest();
<ide> expect($route.current).toBeUndefined();
<ide> describe('$route', function() {
<ide> }));
<ide>
<ide> it('matches a URL with special chars', inject(function($route, $location, $rootScope) {
<del> $location.path('/$test.23/foo*(bar)/222');
<add> $location.path('/$test.23/foo*(bar)/~!@#$%^&*()_+=-`');
<ide> $rootScope.$digest();
<ide> expect($route.current).toBeDefined();
<ide> })); | 2 |
Ruby | Ruby | fix output of new casks | 2ed4196d73f407833e09ae3565506a80ef6ec485 | <ide><path>Library/Homebrew/cmd/update-report.rb
<ide> def dump_formula_report(key, title)
<ide> when :A
<ide> name unless installed?(name)
<ide> when :AC
<del> name unless cask_installed?(name)
<add> name.split("/").last unless cask_installed?(name)
<ide> when :MC, :DC
<ide> name = name.split("/").last
<ide> cask_installed?(name) ? pretty_installed(name) : name | 1 |
Javascript | Javascript | expose the asyncrequiremodulepath param | 06ec0f0fd1b85c07dd76f9cd37a1c36264196b08 | <ide><path>local-cli/bundle/buildBundle.js
<ide> async function buildBundle(
<ide> const terminal = new Terminal(process.stdout);
<ide>
<ide> const server = new Server({
<add> asyncRequireModulePath: config.getAsyncRequireModulePath(),
<ide> assetExts: defaultAssetExts.concat(assetExts),
<ide> assetRegistryPath: ASSET_REGISTRY_PATH,
<ide> blacklistRE: config.getBlacklistRE(),
<ide><path>local-cli/server/runServer.js
<ide> function getPackagerServer(args, config, reporter) {
<ide> args.providesModuleNodeModules || defaultProvidesModuleNodeModules;
<ide>
<ide> return Metro.createServer({
<add> asyncRequireModulePath: config.getAsyncRequireModulePath(),
<ide> assetExts: defaultAssetExts.concat(args.assetExts),
<ide> assetRegistryPath: ASSET_REGISTRY_PATH,
<ide> blacklistRE: config.getBlacklistRE(), | 2 |
Ruby | Ruby | remove unused assigned variable | 7e9d45cc7f76497873720bf4797ddfba126c8cd8 | <ide><path>activemodel/lib/active_model/observing.rb
<ide> def count_observers
<ide> def instantiate_observer(observer) #:nodoc:
<ide> # string/symbol
<ide> if observer.respond_to?(:to_sym)
<del> observer = observer.to_s.camelize.constantize.instance
<add> observer.to_s.camelize.constantize.instance
<ide> elsif observer.respond_to?(:instance)
<ide> observer.instance
<ide> else | 1 |
Javascript | Javascript | adjust formatting of clamplength | 89af64638fff208c8947f37deb2181c7d77b4933 | <ide><path>src/math/Vector2.js
<ide> THREE.Vector2.prototype = {
<ide>
<ide> clampLength: function ( min, max ) {
<ide>
<del> var oldLength = this.length();
<add> var oldLength = this.length();
<ide>
<del> var newLength = ( oldLength < min ) ? min : ( ( oldLength > max ) ? max : oldLength );
<add> var newLength = ( oldLength < min ) ? min : ( ( oldLength > max ) ? max : oldLength );
<ide>
<del> if ( newLength !== oldLength ) {
<add> if ( newLength !== oldLength ) {
<ide>
<del> this.divideScalar( oldLength ).multiplyScalar( newLength );
<add> this.divideScalar( oldLength ).multiplyScalar( newLength );
<ide>
<del> }
<add> }
<ide>
<del> return this;
<add> return this;
<ide>
<ide> },
<ide>
<ide><path>src/math/Vector3.js
<ide> THREE.Vector3.prototype = {
<ide>
<ide> clampLength: function ( min, max ) {
<ide>
<del> var oldLength = this.length();
<add> var oldLength = this.length();
<ide>
<del> var newLength = ( oldLength < min ) ? min : ( ( oldLength > max ) ? max : oldLength );
<add> var newLength = ( oldLength < min ) ? min : ( ( oldLength > max ) ? max : oldLength );
<ide>
<del> if ( newLength !== oldLength ) {
<add> if ( newLength !== oldLength ) {
<ide>
<del> this.divideScalar( oldLength ).multiplyScalar( newLength );
<add> this.divideScalar( oldLength ).multiplyScalar( newLength );
<ide>
<del> }
<add> }
<ide>
<del> return this;
<add> return this;
<ide>
<ide> },
<ide> | 2 |
Python | Python | add pure synthetic data to keras resnet model. | 05383c7bb8108b2ba762d0a79df9892d4e77c595 | <ide><path>official/resnet/keras/keras_cifar_main.py
<ide> def run(flags_obj):
<ide> tf.keras.backend.set_image_data_format(data_format)
<ide>
<ide> if flags_obj.use_synthetic_data:
<add> distribution_utils.set_up_synthetic_data()
<ide> input_fn = keras_common.get_synth_input_fn(
<ide> height=cifar_main.HEIGHT,
<ide> width=cifar_main.WIDTH,
<ide> num_channels=cifar_main.NUM_CHANNELS,
<ide> num_classes=cifar_main.NUM_CLASSES,
<ide> dtype=flags_core.get_tf_dtype(flags_obj))
<ide> else:
<add> distribution_utils.undo_set_up_synthetic_data()
<ide> input_fn = cifar_main.input_fn
<ide>
<ide> train_input_dataset = input_fn(
<ide><path>official/resnet/keras/keras_common.py
<ide> def input_fn(is_training, data_dir, batch_size, *args, **kwargs):
<ide> maxval=num_classes - 1,
<ide> dtype=tf.int32,
<ide> name='synthetic_labels')
<add> # Cast to float32 for Keras model.
<add> labels = tf.cast(labels, dtype=tf.float32)
<add>
<ide> data = tf.data.Dataset.from_tensors((inputs, labels)).repeat()
<del> data = data.batch(batch_size)
<add>
<add> # `drop_remainder` will make dataset produce outputs with known shapes.
<add> data = data.batch(batch_size, drop_remainder=True)
<ide> data = data.prefetch(buffer_size=tf.data.experimental.AUTOTUNE)
<ide> return data
<ide>
<ide><path>official/resnet/keras/keras_imagenet_main.py
<ide> def run(flags_obj):
<ide>
<ide> # pylint: disable=protected-access
<ide> if flags_obj.use_synthetic_data:
<add> distribution_utils.set_up_synthetic_data()
<ide> input_fn = keras_common.get_synth_input_fn(
<ide> height=imagenet_main.DEFAULT_IMAGE_SIZE,
<ide> width=imagenet_main.DEFAULT_IMAGE_SIZE,
<ide> num_channels=imagenet_main.NUM_CHANNELS,
<ide> num_classes=imagenet_main.NUM_CLASSES,
<ide> dtype=flags_core.get_tf_dtype(flags_obj))
<ide> else:
<add> distribution_utils.undo_set_up_synthetic_data()
<ide> input_fn = imagenet_main.input_fn
<ide>
<ide> train_input_dataset = input_fn(is_training=True,
<ide><path>official/utils/misc/distribution_utils.py
<ide> from __future__ import division
<ide> from __future__ import print_function
<ide>
<add>import random
<add>import string
<ide> import tensorflow as tf
<ide>
<ide>
<ide> def per_device_batch_size(batch_size, num_gpus):
<ide> ).format(num_gpus, batch_size, batch_size - remainder)
<ide> raise ValueError(err)
<ide> return int(batch_size / num_gpus)
<add>
<add># The `SyntheticDataset` is a temporary solution for generating synthetic data
<add># directly on devices. It is only useful for Keras with Distribution
<add># Strategies. We will have better support in `tf.data` or Distribution Strategy
<add># later.
<add>class SyntheticDataset(object):
<add> """A dataset that generates synthetic data on each device."""
<add>
<add> def __init__(self, dataset, split_by=1):
<add> self._input_data = {}
<add> # dataset.take(1) doesn't have GPU kernel.
<add> with tf.device("device:CPU:0"):
<add> tensor = tf.data.experimental.get_single_element(dataset.take(1))
<add> flat_tensor = tf.nest.flatten(tensor)
<add> variable_data = []
<add> self._initializers = []
<add> for t in flat_tensor:
<add> rebatched_t = tf.split(t, num_or_size_splits=split_by, axis=0)[0]
<add> assert rebatched_t.shape.is_fully_defined(), rebatched_t.shape
<add> v = tf.get_local_variable(self.random_name(), initializer=rebatched_t) # pylint: disable=cell-var-from-loop
<add> variable_data.append(v)
<add> self._initializers.append(v.initializer)
<add> self._input_data = tf.nest.pack_sequence_as(tensor, variable_data)
<add>
<add> def get_next(self):
<add> return self._input_data
<add>
<add> def initialize(self):
<add> if tf.executing_eagerly():
<add> return tf.no_op()
<add> else:
<add> return self._initializers
<add>
<add> def random_name(self, size=10, chars=string.ascii_uppercase + string.digits):
<add> return "".join(random.choice(chars) for _ in range(size))
<add>
<add>
<add>def _monkey_patch_dataset_method(strategy):
<add> """Monkey-patch `strategy`'s `make_dataset_iterator` method."""
<add> def make_dataset_iterator(self, dataset):
<add> tf.logging.info("Using pure synthetic data.")
<add> with self.scope():
<add> if self.extended._global_batch_size: # pylint: disable=protected-access
<add> return SyntheticDataset(dataset, self.num_replicas_in_sync)
<add> else:
<add> return SyntheticDataset(dataset)
<add>
<add> strategy.org_make_dataset_iterator = strategy.make_dataset_iterator
<add> strategy.make_dataset_iterator = make_dataset_iterator
<add>
<add>
<add>def _undo_monkey_patch_dataset_method(strategy):
<add> if hasattr(strategy, "org_make_dataset_iterator"):
<add> strategy.make_dataset_iterator = strategy.org_make_dataset_iterator
<add>
<add>
<add>def set_up_synthetic_data():
<add> _monkey_patch_dataset_method(tf.distribute.MirroredStrategy)
<add> _monkey_patch_dataset_method(tf.contrib.distribute.MirroredStrategy)
<add> _monkey_patch_dataset_method(tf.contrib.distribute.OneDeviceStrategy)
<add>
<add>
<add>def undo_set_up_synthetic_data():
<add> _undo_monkey_patch_dataset_method(tf.distribute.MirroredStrategy)
<add> _undo_monkey_patch_dataset_method(tf.contrib.distribute.MirroredStrategy)
<add> _undo_monkey_patch_dataset_method(tf.contrib.distribute.OneDeviceStrategy) | 4 |
Ruby | Ruby | pass the string directly to the output method | 7078af82184d09e977a7aa8a186dfb643395fbfa | <ide><path>Library/Homebrew/cmd/doctor.rb
<ide> def doctor
<ide> EOS
<ide> end
<ide>
<del> lines = out.to_s.split('\n')
<ide> puts
<del> opoo lines.shift
<add> opoo out
<ide> Homebrew.failed = true
<del> puts lines
<ide> first_warning = false
<ide> end
<ide> end | 1 |
Javascript | Javascript | simplify event core | ba6fea1bf5eaab71c0abec7d55824419bcd4f3f4 | <ide><path>src/core/ReactEventEmitter.js
<ide> * limitations under the License.
<ide> *
<ide> * @providesModule ReactEventEmitter
<add> * @typechecks
<ide> */
<ide>
<ide> "use strict";
<ide>
<ide> var BrowserEnv = require('BrowserEnv');
<ide> var EventConstants = require('EventConstants');
<add>var EventListener = require('EventListener');
<ide> var EventPluginHub = require('EventPluginHub');
<ide> var ExecutionEnvironment = require('ExecutionEnvironment');
<del>var NormalizedEventListener = require('NormalizedEventListener');
<ide>
<ide> var invariant = require('invariant');
<ide> var isEventSupported = require('isEventSupported');
<ide>
<del>var registrationNames = EventPluginHub.registrationNames;
<del>var topLevelTypes = EventConstants.topLevelTypes;
<del>var listen = NormalizedEventListener.listen;
<del>var capture = NormalizedEventListener.capture;
<del>
<ide> /**
<del> * `ReactEventEmitter` is used to attach top-level event listeners. For example:
<add> * Summary of `ReactEventEmitter` event handling:
<ide> *
<del> * ReactEventEmitter.putListener('myID', 'onClick', myFunction);
<add> * - We trap low level 'top-level' events.
<add> *
<add> * - We dedupe cross-browser event names into these 'top-level types' so that
<add> * `DOMMouseScroll` or `mouseWheel` both become `topMouseWheel`.
<add> *
<add> * - At this point we have native browser events with the top-level type that
<add> * was used to catch it at the top-level.
<add> *
<add> * - We continuously stream these native events (and their respective top-level
<add> * types) to the event plugin system `EventPluginHub` and ask the plugin
<add> * system if it was able to extract `AbstractEvent` objects. `AbstractEvent`
<add> * objects are the events that applications actually deal with - they are not
<add> * native browser events but cross-browser wrappers.
<add> *
<add> * - When returning the `AbstractEvent` objects, `EventPluginHub` will make
<add> * sure each abstract event is annotated with "dispatches", which are the
<add> * sequence of listeners (and IDs) that care about the event.
<add> *
<add> * - These `AbstractEvent` objects are fed back into the event plugin system,
<add> * which in turn executes these dispatches.
<ide> *
<del> * This would allocate a "registration" of `('onClick', myFunction)` on 'myID'.
<del> */
<del>
<del>/**
<ide> * Overview of React and the event system:
<ide> *
<ide> * .
<ide> var capture = NormalizedEventListener.capture;
<ide> */
<ide>
<ide> /**
<del> * We listen for bubbled touch events on the document object.
<del> *
<del> * Firefox v8.01 (and possibly others) exhibited strange behavior when mounting
<del> * `onmousemove` events at some node that was not the document element. The
<del> * symptoms were that if your mouse is not moving over something contained
<del> * within that mount point (for example on the background) the top-level
<del> * listeners for `onmousemove` won't be called. However, if you register the
<del> * `mousemove` on the document object, then it will of course catch all
<del> * `mousemove`s. This along with iOS quirks, justifies restricting top-level
<del> * listeners to the document object only, at least for these movement types of
<del> * events and possibly all events.
<del> *
<del> * @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
<del> *
<del> * Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but
<del> * they bubble to document.
<del> *
<del> * @see http://www.quirksmode.org/dom/events/keys.html.
<add> * Whether or not `ensureListening` has been invoked.
<add> * @type {boolean}
<add> * @private
<ide> */
<del>
<ide> var _isListening = false;
<ide>
<ide> /**
<del> * Traps top-level events that bubble. Delegates to the main dispatcher
<del> * `handleTopLevel` after performing some basic normalization via
<del> * `TopLevelCallbackCreator.createTopLevelCallback`.
<add> * Traps top-level events by using event bubbling.
<add> *
<add> * @param {string} topLevelType Record from `EventConstants`.
<add> * @param {string} handlerBaseName Event name (e.g. "click").
<add> * @param {DOMEventTarget} element Element on which to attach listener.
<add> * @internal
<ide> */
<del>function trapBubbledEvent(topLevelType, handlerBaseName, onWhat) {
<del> listen(
<del> onWhat,
<add>function trapBubbledEvent(topLevelType, handlerBaseName, element) {
<add> EventListener.listen(
<add> element,
<ide> handlerBaseName,
<ide> ReactEventEmitter.TopLevelCallbackCreator.createTopLevelCallback(
<ide> topLevelType
<ide> function trapBubbledEvent(topLevelType, handlerBaseName, onWhat) {
<ide>
<ide> /**
<ide> * Traps a top-level event by using event capturing.
<add> *
<add> * @param {string} topLevelType Record from `EventConstants`.
<add> * @param {string} handlerBaseName Event name (e.g. "click").
<add> * @param {DOMEventTarget} element Element on which to attach listener.
<add> * @internal
<ide> */
<del>function trapCapturedEvent(topLevelType, handlerBaseName, onWhat) {
<del> capture(
<del> onWhat,
<add>function trapCapturedEvent(topLevelType, handlerBaseName, element) {
<add> EventListener.capture(
<add> element,
<ide> handlerBaseName,
<ide> ReactEventEmitter.TopLevelCallbackCreator.createTopLevelCallback(
<ide> topLevelType
<ide> function trapCapturedEvent(topLevelType, handlerBaseName, onWhat) {
<ide> }
<ide>
<ide> /**
<del> * Listens to document scroll and window resize events that may change the
<del> * document scroll values. We store those results so as to discourage
<del> * application code from asking the DOM itself which could trigger additional
<del> * reflows.
<add> * Listens to window scroll and resize events. We cache scroll values so that
<add> * application code can access them without triggering reflows.
<add> *
<add> * NOTE: Scroll events do not bubble.
<add> *
<add> * @private
<add> * @see http://www.quirksmode.org/dom/events/scroll.html
<ide> */
<del>function registerDocumentScrollListener() {
<del> listen(window, 'scroll', function(nativeEvent) {
<del> if (nativeEvent.target === window) {
<del> BrowserEnv.refreshAuthoritativeScrollValues();
<del> }
<del> });
<del>}
<del>
<del>function registerDocumentResizeListener() {
<del> listen(window, 'resize', function(nativeEvent) {
<del> if (nativeEvent.target === window) {
<del> BrowserEnv.refreshAuthoritativeScrollValues();
<del> }
<del> });
<add>function registerScrollValueMonitoring() {
<add> var refresh = BrowserEnv.refreshAuthoritativeScrollValues;
<add> EventListener.listen(window, 'scroll', refresh);
<add> EventListener.listen(window, 'resize', refresh);
<ide> }
<ide>
<ide> /**
<del> * Summary of `ReactEventEmitter` event handling:
<del> *
<del> * - We trap low level 'top-level' events.
<del> *
<del> * - We dedupe cross-browser event names into these 'top-level types' so that
<del> * `DOMMouseScroll` or `mouseWheel` both become `topMouseWheel`.
<del> *
<del> * - At this point we have native browser events with the top-level type that
<del> * was used to catch it at the top-level.
<add> * We listen for bubbled touch events on the document object.
<ide> *
<del> * - We continuously stream these native events (and their respective top-level
<del> * types) to the event plugin system `EventPluginHub` and ask the plugin
<del> * system if it was able to extract `AbstractEvent` objects. `AbstractEvent`
<del> * objects are the events that applications actually deal with - they are not
<del> * native browser events but cross-browser wrappers.
<add> * Firefox v8.01 (and possibly others) exhibited strange behavior when mounting
<add> * `onmousemove` events at some node that was not the document element. The
<add> * symptoms were that if your mouse is not moving over something contained
<add> * within that mount point (for example on the background) the top-level
<add> * listeners for `onmousemove` won't be called. However, if you register the
<add> * `mousemove` on the document object, then it will of course catch all
<add> * `mousemove`s. This along with iOS quirks, justifies restricting top-level
<add> * listeners to the document object only, at least for these movement types of
<add> * events and possibly all events.
<ide> *
<del> * - When returning the `AbstractEvent` objects, `EventPluginHub` will make
<del> * sure each abstract event is annotated with "dispatches", which are the
<del> * sequence of listeners (and IDs) that care about the event.
<add> * @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
<ide> *
<del> * - These `AbstractEvent` objects are fed back into the event plugin system,
<del> * which in turn executes these dispatches.
<add> * Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but
<add> * they bubble to document.
<ide> *
<add> * @param {boolean} touchNotMouse Listen to touch events instead of mouse.
<ide> * @private
<add> * @see http://www.quirksmode.org/dom/events/keys.html.
<ide> */
<ide> function listenAtTopLevel(touchNotMouse) {
<ide> invariant(
<ide> !_isListening,
<ide> 'listenAtTopLevel(...): Cannot setup top-level listener more than once.'
<ide> );
<add> var topLevelTypes = EventConstants.topLevelTypes;
<ide> var mountAt = document;
<ide>
<del> registerDocumentScrollListener();
<del> registerDocumentResizeListener();
<add> registerScrollValueMonitoring();
<ide> trapBubbledEvent(topLevelTypes.topMouseOver, 'mouseover', mountAt);
<ide> trapBubbledEvent(topLevelTypes.topMouseDown, 'mousedown', mountAt);
<ide> trapBubbledEvent(topLevelTypes.topMouseUp, 'mouseup', mountAt);
<ide> function listenAtTopLevel(touchNotMouse) {
<ide> }
<ide>
<ide> /**
<del> * This is the heart of `ReactEventEmitter`. It simply streams the top-level
<del> * native events to `EventPluginHub`.
<add> * `ReactEventEmitter` is used to attach top-level event listeners. For example:
<add> *
<add> * ReactEventEmitter.putListener('myID', 'onClick', myFunction);
<add> *
<add> * This would allocate a "registration" of `('onClick', myFunction)` on 'myID'.
<ide> *
<del> * @param {object} topLevelType Record from `EventConstants`.
<del> * @param {Event} nativeEvent A Standard Event with fixed `target` property.
<del> * @param {DOMElement} renderedTarget Element of interest to the framework.
<del> * @param {string} renderedTargetID string ID of `renderedTarget`.
<ide> * @internal
<ide> */
<del>function handleTopLevel(
<del> topLevelType,
<del> nativeEvent,
<del> renderedTargetID,
<del> renderedTarget) {
<del> var abstractEvents = EventPluginHub.extractAbstractEvents(
<del> topLevelType,
<del> nativeEvent,
<del> renderedTargetID,
<del> renderedTarget
<del> );
<add>var ReactEventEmitter = {
<ide>
<del> // The event queue being processed in the same cycle allows preventDefault.
<del> EventPluginHub.enqueueAbstractEvents(abstractEvents);
<del> EventPluginHub.processAbstractEventQueue();
<del>}
<add> /**
<add> * React references `ReactEventTopLevelCallback` using this property in order
<add> * to allow dependency injection via `ensureListening`.
<add> */
<add> TopLevelCallbackCreator: null,
<ide>
<del>function setEnabled(enabled) {
<del> invariant(
<del> ExecutionEnvironment.canUseDOM,
<del> 'setEnabled(...): Cannot toggle event listening in a Worker thread. This ' +
<del> 'is likely a bug in the framework. Please report immediately.'
<del> );
<del> ReactEventEmitter.TopLevelCallbackCreator.setEnabled(enabled);
<del>}
<add> /**
<add> * Ensures that top-level event delegation listeners are installed.
<add> *
<add> * There are issues with listening to both touch events and mouse events on
<add> * the top-level, so we make the caller choose which one to listen to. (If
<add> * there's a touch top-level listeners, anchors don't receive clicks for some
<add> * reason, and only in some cases).
<add> *
<add> * @param {boolean} touchNotMouse Listen to touch events instead of mouse.
<add> * @param {object} TopLevelCallbackCreator
<add> */
<add> ensureListening: function(touchNotMouse, TopLevelCallbackCreator) {
<add> invariant(
<add> ExecutionEnvironment.canUseDOM,
<add> 'ensureListening(...): Cannot toggle event listening in a Worker ' +
<add> 'thread. This is likely a bug in the framework. Please report ' +
<add> 'immediately.'
<add> );
<add> if (!_isListening) {
<add> ReactEventEmitter.TopLevelCallbackCreator = TopLevelCallbackCreator;
<add> listenAtTopLevel(touchNotMouse);
<add> _isListening = true;
<add> }
<add> },
<ide>
<del>function isEnabled() {
<del> return ReactEventEmitter.TopLevelCallbackCreator.isEnabled();
<del>}
<add> /**
<add> * Sets whether or not any created callbacks should be enabled.
<add> *
<add> * @param {boolean} enabled True if callbacks should be enabled.
<add> */
<add> setEnabled: function(enabled) {
<add> invariant(
<add> ExecutionEnvironment.canUseDOM,
<add> 'setEnabled(...): Cannot toggle event listening in a Worker thread. ' +
<add> 'This is likely a bug in the framework. Please report immediately.'
<add> );
<add> if (ReactEventEmitter.TopLevelCallbackCreator) {
<add> ReactEventEmitter.TopLevelCallbackCreator.setEnabled(enabled);
<add> }
<add> },
<ide>
<del>/**
<del> * Ensures that top-level event delegation listeners are listening at `mountAt`.
<del> * There are issues with listening to both touch events and mouse events on the
<del> * top-level, so we make the caller choose which one to listen to. (If there's a
<del> * touch top-level listeners, anchors don't receive clicks for some reason, and
<del> * only in some cases).
<del> *
<del> * @param {boolean} touchNotMouse Listen to touch events instead of mouse.
<del> * @param {object} TopLevelCallbackCreator Module that can create top-level
<del> * callback handlers.
<del> * @internal
<del> */
<del>function ensureListening(touchNotMouse, TopLevelCallbackCreator) {
<del> invariant(
<del> ExecutionEnvironment.canUseDOM,
<del> 'ensureListening(...): Cannot toggle event listening in a Worker thread. ' +
<del> 'This is likely a bug in the framework. Please report immediately.'
<del> );
<del> if (!_isListening) {
<del> ReactEventEmitter.TopLevelCallbackCreator = TopLevelCallbackCreator;
<del> listenAtTopLevel(touchNotMouse);
<del> _isListening = true;
<del> }
<del>}
<add> /**
<add> * @return {boolean} True if callbacks are enabled.
<add> */
<add> isEnabled: function() {
<add> return !!(
<add> ReactEventEmitter.TopLevelCallbackCreator &&
<add> ReactEventEmitter.TopLevelCallbackCreator.isEnabled()
<add> );
<add> },
<add>
<add> /**
<add> * Streams a fired top-level event to `EventPluginHub` where plugins have the
<add> * opportunity to create `ReactEvent`s to be dispatched.
<add> *
<add> * @param {string} topLevelType Record from `EventConstants`.
<add> * @param {DOMEventTarget} topLevelTarget The listening component root node.
<add> * @param {string} topLevelTargetID ID of `topLevelTarget`.
<add> * @param {object} nativeEvent Native browser event.
<add> */
<add> handleTopLevel: function(
<add> topLevelType,
<add> topLevelTarget,
<add> topLevelTargetID,
<add> nativeEvent) {
<add> var abstractEvents = EventPluginHub.extractAbstractEvents(
<add> topLevelType,
<add> topLevelTarget,
<add> topLevelTargetID,
<add> nativeEvent
<add> );
<add>
<add> // Event queue being processed in the same cycle allows `preventDefault`.
<add> EventPluginHub.enqueueAbstractEvents(abstractEvents);
<add> EventPluginHub.processAbstractEventQueue();
<add> },
<add>
<add> registrationNames: EventPluginHub.registrationNames,
<ide>
<del>var ReactEventEmitter = {
<del> TopLevelCallbackCreator: null, // Injectable callback creator.
<del> handleTopLevel: handleTopLevel,
<del> setEnabled: setEnabled,
<del> isEnabled: isEnabled,
<del> ensureListening: ensureListening,
<del> registrationNames: registrationNames,
<ide> putListener: EventPluginHub.putListener,
<add>
<ide> getListener: EventPluginHub.getListener,
<add>
<ide> deleteAllListeners: EventPluginHub.deleteAllListeners,
<add>
<ide> trapBubbledEvent: trapBubbledEvent,
<add>
<ide> trapCapturedEvent: trapCapturedEvent
<add>
<ide> };
<ide>
<ide> module.exports = ReactEventEmitter;
<ide><path>src/core/ReactEventTopLevelCallback.js
<ide> * limitations under the License.
<ide> *
<ide> * @providesModule ReactEventTopLevelCallback
<add> * @typechecks
<ide> */
<ide>
<ide> "use strict";
<ide> var ReactEventEmitter = require('ReactEventEmitter');
<ide> var ReactInstanceHandles = require('ReactInstanceHandles');
<ide>
<ide> var getDOMNodeID = require('getDOMNodeID');
<add>var getEventTarget = require('getEventTarget');
<ide>
<add>/**
<add> * @type {boolean}
<add> * @private
<add> */
<ide> var _topLevelListenersEnabled = true;
<ide>
<add>/**
<add> * Top-level callback creator used to implement event handling using delegation.
<add> * This is used via dependency injection in `ReactEventEmitter.ensureListening`.
<add> */
<ide> var ReactEventTopLevelCallback = {
<ide>
<ide> /**
<del> * @param {boolean} enabled Whether or not all callbacks that have ever been
<del> * created with this module should be enabled.
<add> * Sets whether or not any created callbacks should be enabled.
<add> *
<add> * @param {boolean} enabled True if callbacks should be enabled.
<ide> */
<ide> setEnabled: function(enabled) {
<ide> _topLevelListenersEnabled = !!enabled;
<ide> },
<ide>
<add> /**
<add> * @return {boolean} True if callbacks are enabled.
<add> */
<ide> isEnabled: function() {
<ide> return _topLevelListenersEnabled;
<ide> },
<ide>
<ide> /**
<del> * For a given `topLevelType`, creates a callback that could be added as a
<del> * listener to the document. That top level callback will simply fix the
<del> * native events before invoking `handleTopLevel`.
<add> * Creates a callback for the supplied `topLevelType` that could be added as
<add> * a listener to the document. The callback computes a `topLevelTarget` which
<add> * should be the root node of a mounted React component where the listener
<add> * is attached.
<ide> *
<del> * - Raw native events cannot be trusted to describe their targets correctly
<del> * so we expect that the argument to the nested function has already been
<del> * fixed. But the `target` property may not be something of interest to
<del> * React, so we find the most suitable target. But even at that point, DOM
<del> * Elements (the target ) can't be trusted to describe their IDs correctly
<del> * so we obtain the ID in a reliable manner and pass it to
<del> * `handleTopLevel`. The target/id that we found to be relevant to our
<del> * framework are called `renderedTarget`/`renderedTargetID` respectively.
<add> * @param {string} topLevelType Record from `EventConstants`.
<add> * @return {function} Callback for handling top-level events.
<ide> */
<ide> createTopLevelCallback: function(topLevelType) {
<del> return function(fixedNativeEvent) {
<add> return function(nativeEvent) {
<ide> if (!_topLevelListenersEnabled) {
<ide> return;
<ide> }
<del> var renderedTarget = ReactInstanceHandles.getFirstReactDOM(
<del> fixedNativeEvent.target
<add> var topLevelTarget = ReactInstanceHandles.getFirstReactDOM(
<add> getEventTarget(nativeEvent)
<ide> ) || ExecutionEnvironment.global;
<del> var renderedTargetID = getDOMNodeID(renderedTarget);
<add> var topLevelTargetID = getDOMNodeID(topLevelTarget) || '';
<ide> ReactEventEmitter.handleTopLevel(
<ide> topLevelType,
<del> fixedNativeEvent,
<del> renderedTargetID,
<del> renderedTarget
<add> topLevelTarget,
<add> topLevelTargetID,
<add> nativeEvent
<ide> );
<ide> };
<ide> }
<ide><path>src/core/ReactInstanceHandles.js
<ide> * limitations under the License.
<ide> *
<ide> * @providesModule ReactInstanceHandles
<add> * @typechecks
<ide> */
<ide>
<ide> "use strict";
<ide> function isValidID(id) {
<ide> /**
<ide> * True if the supplied `node` is rendered by React.
<ide> *
<del> * @param {DOMElement} node DOM Element to check.
<add> * @param {DOMEventTarget} node DOM Element to check.
<ide> * @return {boolean} True if the DOM Element appears to be rendered by React.
<ide> * @private
<ide> */
<ide> function isRenderedByReact(node) {
<ide> var id = getDOMNodeID(node);
<del> return id && id.charAt(0) === SEPARATOR;
<add> return id ? id.charAt(0) === SEPARATOR : false;
<ide> }
<ide>
<ide> /**
<ide> var ReactInstanceHandles = {
<ide> * Traverses up the ancestors of the supplied node to find a node that is a
<ide> * DOM representation of a React component.
<ide> *
<del> * @param {DOMElement} node
<del> * @return {?DOMElement}
<add> * @param {?DOMEventTarget} node
<add> * @return {?DOMEventTarget}
<ide> * @internal
<ide> */
<ide> getFirstReactDOM: function(node) {
<ide> var ReactInstanceHandles = {
<ide> * Finds a node with the supplied `id` inside of the supplied `ancestorNode`.
<ide> * Exploits the ID naming scheme to perform the search quickly.
<ide> *
<del> * @param {DOMElement} ancestorNode Search from this root.
<add> * @param {DOMEventTarget} ancestorNode Search from this root.
<ide> * @pararm {string} id ID of the DOM representation of the component.
<del> * @return {?DOMElement} DOM element with the supplied `id`, if one exists.
<add> * @return {?DOMEventTarget} DOM node with the supplied `id`, if one exists.
<ide> * @internal
<ide> */
<ide> findComponentRoot: function(ancestorNode, id) {
<ide> var ReactInstanceHandles = {
<ide> * contains the React component with the supplied DOM ID.
<ide> *
<ide> * @param {string} id DOM ID of a React component.
<del> * @return {string} DOM ID of the React component that is the root.
<add> * @return {?string} DOM ID of the React component that is the root.
<ide> * @internal
<ide> */
<ide> getReactRootIDFromNodeID: function(id) {
<ide><path>src/dom/getDOMNodeID.js
<ide> * limitations under the License.
<ide> *
<ide> * @providesModule getDOMNodeID
<add> * @typechecks
<ide> */
<ide>
<ide> "use strict";
<ide> * control whose name or ID is "id". However, not all DOM nodes support
<ide> * `getAttributeNode` (document - which is not a form) so that is checked first.
<ide> *
<del> * @param {Element} domNode DOM node element to return ID of.
<del> * @returns {string} The ID of `domNode`.
<add> * @param {DOMElement|DOMWindow|DOMDocument} domNode DOM node.
<add> * @returns {string} ID of the supplied `domNode`.
<ide> */
<ide> function getDOMNodeID(domNode) {
<ide> if (domNode.getAttributeNode) {
<ide><path>src/dom/getEventTarget.js
<add>/**
<add> * Copyright 2013 Facebook, Inc.
<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> * @providesModule getEventTarget
<add> * @typechecks
<add> */
<add>
<add>var ExecutionEnvironment = require('ExecutionEnvironment');
<add>
<add>/**
<add> * Gets the target node from a native browser event by accounting for
<add> * inconsistencies in browser DOM APIs.
<add> *
<add> * @param {object} nativeEvent Native browser event.
<add> * @return {DOMEventTarget} Target node.
<add> */
<add>function getEventTarget(nativeEvent) {
<add> var target =
<add> nativeEvent.target ||
<add> nativeEvent.srcElement ||
<add> ExecutionEnvironment.global;
<add> // Safari may fire events on text nodes (Node.TEXT_NODE is 3).
<add> // @see http://www.quirksmode.org/js/events_properties.html
<add> return target.nodeType === 3 ? target.parentNode : target;
<add>}
<add>
<add>module.exports = getEventTarget;
<ide><path>src/event/AbstractEvent.js
<ide> var MAX_POOL_SIZE = 20;
<ide> * unreliable native event.
<ide> */
<ide> function AbstractEvent(
<del> abstractEventType,
<del> abstractTargetID, // Allows the abstract target to differ from native.
<del> originatingTopLevelEventType,
<add> reactEventType,
<add> reactTargetID, // Allows the abstract target to differ from native.
<ide> nativeEvent,
<ide> data) {
<del> this.type = abstractEventType;
<del> this.abstractTargetID = abstractTargetID || '';
<del> this.originatingTopLevelEventType = originatingTopLevelEventType;
<add> this.reactEventType = reactEventType;
<add> this.reactTargetID = reactTargetID || '';
<ide> this.nativeEvent = nativeEvent;
<ide> this.data = data;
<ide> // TODO: Deprecate storing target - doesn't always make sense for some types
<ide> AbstractEvent.persistentCloneOf = function(abstractEvent) {
<ide> throwIf(!(abstractEvent instanceof AbstractEvent), CLONE_TYPE_ERR);
<ide> }
<ide> return new AbstractEvent(
<del> abstractEvent.type,
<del> abstractEvent.abstractTargetID,
<del> abstractEvent.originatingTopLevelEventType,
<add> abstractEvent.reactEventType,
<add> abstractEvent.reactTargetID,
<ide> abstractEvent.nativeEvent,
<del> abstractEvent.data,
<del> abstractEvent.target
<add> abstractEvent.data
<ide> );
<ide> };
<ide>
<ide><path>src/event/EventPluginHub.js
<ide> function recordAllRegistrationNames(eventType, PluginModule) {
<ide> * @param {AbstractEvent} abstractEvent to look at
<ide> */
<ide> function getPluginModuleForAbstractEvent(abstractEvent) {
<del> if (abstractEvent.type.registrationName) {
<del> return registrationNames[abstractEvent.type.registrationName];
<add> var reactEventType = abstractEvent.reactEventType;
<add> if (reactEventType.registrationName) {
<add> return registrationNames[reactEventType.registrationName];
<ide> } else {
<del> for (var phase in abstractEvent.type.phasedRegistrationNames) {
<del> if (!abstractEvent.type.phasedRegistrationNames.hasOwnProperty(phase)) {
<add> for (var phase in reactEventType.phasedRegistrationNames) {
<add> if (!reactEventType.phasedRegistrationNames.hasOwnProperty(phase)) {
<ide> continue;
<ide> }
<ide> var PluginModule = registrationNames[
<del> abstractEvent.type.phasedRegistrationNames[phase]
<add> reactEventType.phasedRegistrationNames[phase]
<ide> ];
<ide> if (PluginModule) {
<ide> return PluginModule;
<ide> var deleteAllListeners = function(domID) {
<ide> * Accepts the stream of top level native events, and gives every registered
<ide> * plugin an opportunity to extract `AbstractEvent`s with annotated dispatches.
<ide> *
<del> * @param {Enum} topLevelType Record from `EventConstants`.
<del> * @param {Event} nativeEvent A Standard Event with fixed `target` property.
<del> * @param {Element} renderedTarget Element of interest to the framework, usually
<del> * the same as `nativeEvent.target` but occasionally an element immediately
<del> * above `nativeEvent.target` (the first DOM node recognized as one "rendered"
<del> * by the framework at hand.)
<del> * @param {string} renderedTargetID string ID of `renderedTarget`.
<add> * @param {string} topLevelType Record from `EventConstants`.
<add> * @param {DOMEventTarget} topLevelTarget The listening component root node.
<add> * @param {string} topLevelTargetID ID of `topLevelTarget`.
<add> * @param {object} nativeEvent Native browser event.
<add> * @return {*} An accumulation of `AbstractEvent`s.
<ide> */
<del>var extractAbstractEvents =
<del> function(topLevelType, nativeEvent, renderedTargetID, renderedTarget) {
<del> var abstractEvents;
<del> var plugins = injection.plugins;
<del> var len = plugins.length;
<del> for (var i = 0; i < len; i++) {
<del> // Not every plugin in the ordering may be loaded at runtime.
<del> var possiblePlugin = plugins[i];
<del> var extractedAbstractEvents =
<del> possiblePlugin &&
<del> possiblePlugin.extractAbstractEvents(
<del> topLevelType,
<del> nativeEvent,
<del> renderedTargetID,
<del> renderedTarget
<del> );
<add>var extractAbstractEvents = function(
<add> topLevelType,
<add> topLevelTarget,
<add> topLevelTargetID,
<add> nativeEvent) {
<add> var abstractEvents;
<add> var plugins = injection.plugins;
<add> for (var i = 0, l = plugins.length; i < l; i++) {
<add> // Not every plugin in the ordering may be loaded at runtime.
<add> var possiblePlugin = plugins[i];
<add> if (possiblePlugin) {
<add> var extractedAbstractEvents = possiblePlugin.extractAbstractEvents(
<add> topLevelType,
<add> topLevelTarget,
<add> topLevelTargetID,
<add> nativeEvent
<add> );
<ide> if (extractedAbstractEvents) {
<ide> abstractEvents = accumulate(abstractEvents, extractedAbstractEvents);
<ide> }
<ide> }
<del> return abstractEvents;
<del> };
<add> }
<add> return abstractEvents;
<add>};
<ide>
<ide> var enqueueAbstractEvents = function(abstractEvents) {
<ide> if (abstractEvents) {
<ide><path>src/event/EventPropagators.js
<ide> var injection = {
<ide> */
<ide> function listenerAtPhase(id, abstractEvent, propagationPhase) {
<ide> var registrationName =
<del> abstractEvent.type.phasedRegistrationNames[propagationPhase];
<add> abstractEvent.reactEventType.phasedRegistrationNames[propagationPhase];
<ide> return getListener(id, registrationName);
<ide> }
<ide>
<ide> function accumulateDirectionalDispatches(domID, upwards, abstractEvent) {
<ide> * have a different target.
<ide> */
<ide> function accumulateTwoPhaseDispatchesSingle(abstractEvent) {
<del> if (abstractEvent && abstractEvent.type.phasedRegistrationNames) {
<add> if (abstractEvent && abstractEvent.reactEventType.phasedRegistrationNames) {
<ide> injection.InstanceHandle.traverseTwoPhase(
<del> abstractEvent.abstractTargetID,
<add> abstractEvent.reactTargetID,
<ide> accumulateDirectionalDispatches,
<ide> abstractEvent
<ide> );
<ide> function accumulateTwoPhaseDispatchesSingle(abstractEvent) {
<ide> /**
<ide> * Accumulates without regard to direction, does not look for phased
<ide> * registration names. Same as `accumulateDirectDispatchesSingle` but without
<del> * requiring that the `abstractTargetID` be the same as the dispatched ID.
<add> * requiring that the `reactTargetID` be the same as the dispatched ID.
<ide> */
<ide> function accumulateDispatches(id, ignoredDirection, abstractEvent) {
<del> if (abstractEvent && abstractEvent.type.registrationName) {
<del> var listener = getListener(id, abstractEvent.type.registrationName);
<add> if (abstractEvent && abstractEvent.reactEventType.registrationName) {
<add> var registrationName = abstractEvent.reactEventType.registrationName;
<add> var listener = getListener(id, registrationName);
<ide> if (listener) {
<ide> abstractEvent._dispatchListeners =
<ide> accumulate(abstractEvent._dispatchListeners, listener);
<ide> function accumulateDispatches(id, ignoredDirection, abstractEvent) {
<ide>
<ide> /**
<ide> * Accumulates dispatches on an `AbstractEvent`, but only for the
<del> * `abstractTargetID`.
<add> * `reactTargetID`.
<ide> * @param {AbstractEvent} abstractEvent
<ide> */
<ide> function accumulateDirectDispatchesSingle(abstractEvent) {
<del> if (abstractEvent && abstractEvent.type.registrationName) {
<del> accumulateDispatches(abstractEvent.abstractTargetID, null, abstractEvent);
<add> if (abstractEvent && abstractEvent.reactEventType.registrationName) {
<add> accumulateDispatches(abstractEvent.reactTargetID, null, abstractEvent);
<ide> }
<ide> }
<ide>
<ide><path>src/event/NormalizedEventListener.js
<del>/**
<del> * Copyright 2013 Facebook, Inc.
<del> *
<del> * Licensed under the Apache License, Version 2.0 (the "License");
<del> * you may not use this file except in compliance with the License.
<del> * You may obtain a copy of the License at
<del> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS,
<del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del> * See the License for the specific language governing permissions and
<del> * limitations under the License.
<del> *
<del> * @providesModule NormalizedEventListener
<del> */
<del>
<del>var EventListener = require('EventListener');
<del>
<del>/**
<del> * @param {?Event} eventParam Event parameter from an attached listener.
<del> * @return {Event} Normalized event object.
<del> * @private
<del> */
<del>function normalizeEvent(eventParam) {
<del> var nativeEvent = eventParam || window.event;
<del> // In some browsers (OLD FF), setting the target throws an error. A good way
<del> // to tell if setting the target will throw an error, is to check if the event
<del> // has a `target` property. Safari events have a `target` but it's not always
<del> // normalized. Even if a `target` property exists, it's good to only set the
<del> // target property if we realize that a change will actually take place.
<del> var hasTargetProperty = 'target' in nativeEvent;
<del> var eventTarget = nativeEvent.target || nativeEvent.srcElement || window;
<del> // Safari may fire events on text nodes (Node.TEXT_NODE is 3)
<del> // @see http://www.quirksmode.org/js/events_properties.html
<del> var textNodeNormalizedTarget =
<del> (eventTarget.nodeType === 3) ? eventTarget.parentNode : eventTarget;
<del> if (!hasTargetProperty || nativeEvent.target !== textNodeNormalizedTarget) {
<del> // TODO: Normalize the object via `merge()` to work with strict mode.
<del> nativeEvent.target = textNodeNormalizedTarget;
<del> }
<del> return nativeEvent;
<del>}
<del>
<del>function createNormalizedCallback(cb) {
<del> return function(unfixedNativeEvent) {
<del> cb(normalizeEvent(unfixedNativeEvent));
<del> };
<del>}
<del>
<del>var NormalizedEventListener = {
<del>
<del> /**
<del> * Listens to bubbled events on a DOM node.
<del> *
<del> * NOTE: The listener will be invoked with a normalized event object.
<del> *
<del> * @param {DOMElement} el DOM element to register listener on.
<del> * @param {string} handlerBaseName Event name, e.g. "click".
<del> * @param {function} cb Callback function.
<del> * @public
<del> */
<del> listen: function(el, handlerBaseName, cb) {
<del> EventListener.listen(el, handlerBaseName, createNormalizedCallback(cb));
<del> },
<del>
<del> /**
<del> * Listens to captured events on a DOM node.
<del> *
<del> * NOTE: The listener will be invoked with a normalized event object.
<del> *
<del> * @param {DOMElement} el DOM element to register listener on.
<del> * @param {string} handlerBaseName Event name, e.g. "click".
<del> * @param {function} cb Callback function.
<del> * @public
<del> */
<del> capture: function(el, handlerBaseName, cb) {
<del> EventListener.capture(el, handlerBaseName, createNormalizedCallback(cb));
<del> }
<del>
<del>};
<del>
<del>module.exports = NormalizedEventListener;
<ide><path>src/eventPlugins/AnalyticsEventPluginFactory.js
<ide> if (__DEV__) {
<ide> * This plugin does not really extract any abstract events. Rather it just looks
<ide> * at the top level event and bumps up counters as appropriate
<ide> *
<del> * @see EventPluginHub.extractAbstractEvents
<add> * @param {string} topLevelType Record from `EventConstants`.
<add> * @param {DOMEventTarget} topLevelTarget The listening component root node.
<add> * @param {string} topLevelTargetID ID of `topLevelTarget`.
<add> * @param {object} nativeEvent Native browser event.
<add> * @return {*} An accumulation of `AbstractEvent`s.
<add> * @see {EventPluginHub.extractAbstractEvents}
<ide> */
<ide> function extractAbstractEvents(
<ide> topLevelType,
<del> nativeEvent,
<del> renderedTargetID,
<del> renderedTarget) {
<add> topLevelTarget,
<add> topLevelTargetID,
<add> nativeEvent) {
<ide> var currentEvent = topLevelTypesToAnalyticsEvent[topLevelType];
<del> if (!currentEvent || !renderedTarget || !renderedTarget.attributes) {
<add> if (!currentEvent || !topLevelTarget || !topLevelTarget.attributes) {
<ide> return null;
<ide> }
<ide>
<del> var analyticsIDAttribute = renderedTarget.attributes[ANALYTICS_ID];
<del> var analyticsEventsAttribute = renderedTarget.attributes[ANALYTICS_EVENTS];
<add> var analyticsIDAttribute = topLevelTarget.attributes[ANALYTICS_ID];
<add> var analyticsEventsAttribute = topLevelTarget.attributes[ANALYTICS_EVENTS];
<ide> if(!analyticsIDAttribute || !analyticsEventsAttribute) {
<ide> return null;
<ide> }
<ide><path>src/eventPlugins/EnterLeaveEventPlugin.js
<ide> * limitations under the License.
<ide> *
<ide> * @providesModule EnterLeaveEventPlugin
<add> * @typechecks
<ide> */
<ide>
<ide> "use strict";
<ide> var abstractEventTypes = {
<ide> };
<ide>
<ide> /**
<del> * For almost every interaction we care about, there will be a top level
<del> * `mouseOver` and `mouseOut` event that occur so we can usually only pay
<del> * attention to one of the two (we'll pay attention to the `mouseOut` event) to
<del> * avoid extracting a duplicate event. However, there's one interaction where
<del> * there will be no `mouseOut` event to rely on - mousing from outside the
<del> * browser *into* the chrome. We detect this scenario and only in that case, we
<del> * use the `mouseOver` event.
<add> * For almost every interaction we care about, there will be a top-level
<add> * `mouseover` and `mouseout` event that occurs so only pay attention to one of
<add> * the two (to avoid duplicate events). We use the `mouseout` event.
<ide> *
<del> * @see EventPluginHub.extractAbstractEvents
<add> * However, there's one interaction where there will be no `mouseout` event to
<add> * rely on - mousing from outside the browser *into* the chrome. We detect this
<add> * scenario and only in that case, we use the `mouseover` event.
<add> *
<add> * @param {string} topLevelType Record from `EventConstants`.
<add> * @param {DOMEventTarget} topLevelTarget The listening component root node.
<add> * @param {string} topLevelTargetID ID of `topLevelTarget`.
<add> * @param {object} nativeEvent Native browser event.
<add> * @return {*} An accumulation of `AbstractEvent`s.
<add> * @see {EventPluginHub.extractAbstractEvents}
<ide> */
<ide> var extractAbstractEvents = function(
<ide> topLevelType,
<del> nativeEvent,
<del> renderedTargetID,
<del> renderedTarget) {
<del>
<add> topLevelTarget,
<add> topLevelTargetID,
<add> nativeEvent) {
<ide> if (topLevelType === topLevelTypes.topMouseOver &&
<ide> (nativeEvent.relatedTarget || nativeEvent.fromElement)) {
<del> return;
<add> return null;
<ide> }
<ide> if (topLevelType !== topLevelTypes.topMouseOut &&
<del> topLevelType !== topLevelTypes.topMouseOver){
<add> topLevelType !== topLevelTypes.topMouseOver) {
<ide> return null; // Must not be a mouse in or mouse out - ignoring.
<ide> }
<ide>
<ide> var to, from;
<ide> if (topLevelType === topLevelTypes.topMouseOut) {
<ide> to = getFirstReactDOM(nativeEvent.relatedTarget || nativeEvent.toElement) ||
<ide> ExecutionEnvironment.global;
<del> from = renderedTarget;
<add> from = topLevelTarget;
<ide> } else {
<del> to = renderedTarget;
<add> to = topLevelTarget;
<ide> from = ExecutionEnvironment.global;
<ide> }
<ide>
<ide> // Nothing pertains to our managed components.
<del> if (from === to ) {
<del> return;
<add> if (from === to) {
<add> return null;
<ide> }
<ide>
<ide> var fromID = from ? getDOMNodeID(from) : '';
<ide> var toID = to ? getDOMNodeID(to) : '';
<add>
<ide> var leave = AbstractEvent.getPooled(
<ide> abstractEventTypes.mouseLeave,
<ide> fromID,
<del> topLevelType,
<ide> nativeEvent
<ide> );
<ide> var enter = AbstractEvent.getPooled(
<ide> abstractEventTypes.mouseEnter,
<ide> toID,
<del> topLevelType,
<ide> nativeEvent
<ide> );
<add>
<ide> EventPropagators.accumulateEnterLeaveDispatches(leave, enter, fromID, toID);
<add>
<ide> return [leave, enter];
<ide> };
<ide>
<ide><path>src/eventPlugins/ResponderEventPlugin.js
<ide> var abstractEventTypes = {
<ide> */
<ide>
<ide> /**
<del> * @param {TopLevelTypes} topLevelType Top level event type being examined.
<del> * @param {DOMEvent} nativeEvent Native DOM event.
<add> * @param {string} topLevelType Record from `EventConstants`.
<ide> * @param {string} renderedTargetID ID of deepest React rendered element.
<del> *
<del> * @return {Accumulation<AbstractEvent>} Extracted events.
<add> * @param {object} nativeEvent Native browser event.
<add> * @return {*} An accumulation of extracted `AbstractEvent`s.
<ide> */
<ide> var setResponderAndExtractTransfer =
<del> function(topLevelType, nativeEvent, renderedTargetID) {
<add> function(topLevelType, renderedTargetID, nativeEvent) {
<ide> var type;
<ide> var shouldSetEventType =
<ide> isStartish(topLevelType) ? abstractEventTypes.startShouldSetResponder :
<ide> var setResponderAndExtractTransfer =
<ide> return extracted;
<ide> };
<ide>
<del>
<ide> /**
<ide> * A transfer is a negotiation between a currently set responder and the next
<ide> * element to claim responder status. Any start event could trigger a transfer
<ide> function canTriggerTransfer(topLevelType) {
<ide> (isPressing && isMoveish(topLevelType));
<ide> }
<ide>
<del>var extractAbstractEvents =
<del> function(topLevelType, nativeEvent, renderedTargetID, renderedTarget) {
<del> var extracted;
<del> // Must have missed an end event - reset the state here.
<del> if (responderID && isStartish(topLevelType)) {
<del> responderID = null;
<del> }
<del> if (isStartish(topLevelType)) {
<del> isPressing = true;
<del> } else if (isEndish(topLevelType)) {
<del> isPressing = false;
<del> }
<del> if (canTriggerTransfer(topLevelType)) {
<del> var transfer = setResponderAndExtractTransfer(
<del> topLevelType,
<del> nativeEvent,
<del> renderedTargetID,
<del> renderedTarget
<del> );
<del> if (transfer) {
<del> extracted = accumulate(extracted, transfer);
<del> }
<del> }
<del> // Now that we know the responder is set correctly, we can dispatch
<del> // responder type events (directly to the responder).
<del> var type = isMoveish(topLevelType) ? abstractEventTypes.responderMove :
<del> isEndish(topLevelType) ? abstractEventTypes.responderRelease :
<del> isStartish(topLevelType) ? abstractEventTypes.responderStart : null;
<del> if (type) {
<del> var data = AbstractEvent.normalizePointerData(nativeEvent);
<del> var gesture = AbstractEvent.getPooled(
<del> type,
<del> responderID,
<del> topLevelType,
<del> nativeEvent,
<del> data
<del> );
<del> EventPropagators.accumulateDirectDispatches(gesture);
<del> extracted = accumulate(extracted, gesture);
<del> }
<del> if (type === abstractEventTypes.responderRelease) {
<del> responderID = null;
<add>/**
<add> * @param {string} topLevelType Record from `EventConstants`.
<add> * @param {DOMEventTarget} topLevelTarget The listening component root node.
<add> * @param {string} topLevelTargetID ID of `topLevelTarget`.
<add> * @param {object} nativeEvent Native browser event.
<add> * @return {*} An accumulation of `AbstractEvent`s.
<add> * @see {EventPluginHub.extractAbstractEvents}
<add> */
<add>var extractAbstractEvents = function(
<add> topLevelType,
<add> topLevelTarget,
<add> topLevelTargetID,
<add> nativeEvent) {
<add> var extracted;
<add> // Must have missed an end event - reset the state here.
<add> if (responderID && isStartish(topLevelType)) {
<add> responderID = null;
<add> }
<add> if (isStartish(topLevelType)) {
<add> isPressing = true;
<add> } else if (isEndish(topLevelType)) {
<add> isPressing = false;
<add> }
<add> if (canTriggerTransfer(topLevelType)) {
<add> var transfer = setResponderAndExtractTransfer(
<add> topLevelType,
<add> topLevelTargetID,
<add> nativeEvent
<add> );
<add> if (transfer) {
<add> extracted = accumulate(extracted, transfer);
<ide> }
<del> return extracted;
<del> };
<add> }
<add> // Now that we know the responder is set correctly, we can dispatch
<add> // responder type events (directly to the responder).
<add> var type = isMoveish(topLevelType) ? abstractEventTypes.responderMove :
<add> isEndish(topLevelType) ? abstractEventTypes.responderRelease :
<add> isStartish(topLevelType) ? abstractEventTypes.responderStart : null;
<add> if (type) {
<add> var data = AbstractEvent.normalizePointerData(nativeEvent);
<add> var gesture = AbstractEvent.getPooled(
<add> type,
<add> responderID,
<add> nativeEvent,
<add> data
<add> );
<add> EventPropagators.accumulateDirectDispatches(gesture);
<add> extracted = accumulate(extracted, gesture);
<add> }
<add> if (type === abstractEventTypes.responderRelease) {
<add> responderID = null;
<add> }
<add> return extracted;
<add>};
<ide>
<ide> /**
<ide> * Event plugin for formalizing the negotiation between claiming locks on
<ide><path>src/eventPlugins/SimpleEventPlugin.js
<ide> var SimpleEventPlugin = {
<ide> /**
<ide> * Same as the default implementation, except cancels the event when return
<ide> * value is false.
<add> *
<ide> * @param {AbstractEvent} AbstractEvent to handle
<ide> * @param {function} Application-level callback
<ide> * @param {string} domID DOM id to pass to the callback.
<ide> var SimpleEventPlugin = {
<ide> },
<ide>
<ide> /**
<del> * @see EventPluginHub.extractAbstractEvents
<add> * @param {string} topLevelType Record from `EventConstants`.
<add> * @param {DOMEventTarget} topLevelTarget The listening component root node.
<add> * @param {string} topLevelTargetID ID of `topLevelTarget`.
<add> * @param {object} nativeEvent Native browser event.
<add> * @return {*} An accumulation of `AbstractEvent`s.
<add> * @see {EventPluginHub.extractAbstractEvents}
<ide> */
<del> extractAbstractEvents:
<del> function(topLevelType, nativeEvent, renderedTargetID, renderedTarget) {
<del> var data;
<del> var abstractEventType =
<del> SimpleEventPlugin.topLevelTypesToAbstract[topLevelType];
<del> if (!abstractEventType) {
<del> return null;
<del> }
<del> switch(topLevelType) {
<del> case topLevelTypes.topMouseWheel:
<del> data = AbstractEvent.normalizeMouseWheelData(nativeEvent);
<del> break;
<del> case topLevelTypes.topScroll:
<del> data = AbstractEvent.normalizeScrollDataFromTarget(renderedTarget);
<del> break;
<del> case topLevelTypes.topClick:
<del> case topLevelTypes.topDoubleClick:
<del> case topLevelTypes.topChange:
<del> case topLevelTypes.topDOMCharacterDataModified:
<del> case topLevelTypes.topMouseDown:
<del> case topLevelTypes.topMouseUp:
<del> case topLevelTypes.topMouseMove:
<del> case topLevelTypes.topTouchMove:
<del> case topLevelTypes.topTouchStart:
<del> case topLevelTypes.topTouchEnd:
<del> data = AbstractEvent.normalizePointerData(nativeEvent);
<del> break;
<del> default:
<del> data = null;
<del> }
<del> var abstractEvent = AbstractEvent.getPooled(
<del> abstractEventType,
<del> renderedTargetID,
<del> topLevelType,
<del> nativeEvent,
<del> data
<del> );
<del> EventPropagators.accumulateTwoPhaseDispatches(abstractEvent);
<del> return abstractEvent;
<add> extractAbstractEvents: function(
<add> topLevelType,
<add> topLevelTarget,
<add> topLevelTargetID,
<add> nativeEvent) {
<add> var data;
<add> var abstractEventType =
<add> SimpleEventPlugin.topLevelTypesToAbstract[topLevelType];
<add> if (!abstractEventType) {
<add> return null;
<ide> }
<add> switch(topLevelType) {
<add> case topLevelTypes.topMouseWheel:
<add> data = AbstractEvent.normalizeMouseWheelData(nativeEvent);
<add> break;
<add> case topLevelTypes.topScroll:
<add> data = AbstractEvent.normalizeScrollDataFromTarget(topLevelTarget);
<add> break;
<add> case topLevelTypes.topClick:
<add> case topLevelTypes.topDoubleClick:
<add> case topLevelTypes.topChange:
<add> case topLevelTypes.topDOMCharacterDataModified:
<add> case topLevelTypes.topMouseDown:
<add> case topLevelTypes.topMouseUp:
<add> case topLevelTypes.topMouseMove:
<add> case topLevelTypes.topTouchMove:
<add> case topLevelTypes.topTouchStart:
<add> case topLevelTypes.topTouchEnd:
<add> data = AbstractEvent.normalizePointerData(nativeEvent);
<add> break;
<add> default:
<add> data = null;
<add> }
<add> var abstractEvent = AbstractEvent.getPooled(
<add> abstractEventType,
<add> topLevelTargetID,
<add> nativeEvent,
<add> data
<add> );
<add> EventPropagators.accumulateTwoPhaseDispatches(abstractEvent);
<add> return abstractEvent;
<add> }
<ide> };
<ide>
<ide> SimpleEventPlugin.topLevelTypesToAbstract = {
<ide><path>src/eventPlugins/TapEventPlugin.js
<ide> * limitations under the License.
<ide> *
<ide> * @providesModule TapEventPlugin
<add> * @typechecks
<ide> */
<ide>
<ide> "use strict";
<ide> var abstractEventTypes = {
<ide> };
<ide>
<ide> /**
<del> * @see EventPluginHub.extractAbstractEvents
<add> * @param {string} topLevelType Record from `EventConstants`.
<add> * @param {DOMEventTarget} topLevelTarget The listening component root node.
<add> * @param {string} topLevelTargetID ID of `topLevelTarget`.
<add> * @param {object} nativeEvent Native browser event.
<add> * @return {*} An accumulation of `AbstractEvent`s.
<add> * @see {EventPluginHub.extractAbstractEvents}
<ide> */
<ide> var extractAbstractEvents = function(
<ide> topLevelType,
<del> nativeEvent,
<del> renderedTargetID,
<del> renderedTarget) {
<del>
<add> topLevelTarget,
<add> topLevelTargetID,
<add> nativeEvent) {
<ide> if (!isStartish(topLevelType) && !isEndish(topLevelType)) {
<ide> return;
<ide> }
<ide> var abstractEvent;
<ide> var dist = eventDistance(startCoords, nativeEvent);
<ide> if (isEndish(topLevelType) && dist < tapMoveThreshold) {
<del> var type = abstractEventTypes.touchTap;
<del> var abstractTargetID = renderedTargetID;
<ide> abstractEvent = AbstractEvent.getPooled(
<del> type,
<del> abstractTargetID,
<del> topLevelType,
<add> abstractEventTypes.touchTap,
<add> topLevelTargetID,
<ide> nativeEvent
<ide> );
<ide> }
<ide><path>src/eventPlugins/__tests__/ResponderEventPlugin-test.js
<ide> var existsInExtraction = function(extracted, test) {
<ide> function assertGrantEvent(id, extracted) {
<ide> var test = function(abstractEvent) {
<ide> return abstractEvent instanceof AbstractEvent &&
<del> abstractEvent.type === responderAbstractEventTypes.responderGrant &&
<del> abstractEvent.abstractTargetID === id;
<add> abstractEvent.reactEventType ===
<add> responderAbstractEventTypes.responderGrant &&
<add> abstractEvent.reactTargetID === id;
<ide> };
<ide> expect(ResponderEventPlugin.getResponderID()).toBe(id);
<ide> expect(existsInExtraction(extracted, test)).toBe(true);
<ide> function assertGrantEvent(id, extracted) {
<ide> function assertResponderMoveEvent(id, extracted) {
<ide> var test = function(abstractEvent) {
<ide> return abstractEvent instanceof AbstractEvent &&
<del> abstractEvent.type === responderAbstractEventTypes.responderMove &&
<del> abstractEvent.abstractTargetID === id;
<add> abstractEvent.reactEventType ===
<add> responderAbstractEventTypes.responderMove &&
<add> abstractEvent.reactTargetID === id;
<ide> };
<ide> expect(ResponderEventPlugin.getResponderID()).toBe(id);
<ide> expect(existsInExtraction(extracted, test)).toBe(true);
<ide> function assertResponderMoveEvent(id, extracted) {
<ide> function assertTerminateEvent(id, extracted) {
<ide> var test = function(abstractEvent) {
<ide> return abstractEvent instanceof AbstractEvent &&
<del> abstractEvent.type === responderAbstractEventTypes.responderTerminate &&
<del> abstractEvent.abstractTargetID === id;
<add> abstractEvent.reactEventType ===
<add> responderAbstractEventTypes.responderTerminate &&
<add> abstractEvent.reactTargetID === id;
<ide> };
<ide> expect(ResponderEventPlugin.getResponderID()).not.toBe(id);
<ide> expect(existsInExtraction(extracted, test)).toBe(true);
<ide> function assertTerminateEvent(id, extracted) {
<ide> function assertRelease(id, extracted) {
<ide> var test = function(abstractEvent) {
<ide> return abstractEvent instanceof AbstractEvent &&
<del> abstractEvent.type === responderAbstractEventTypes.responderRelease &&
<del> abstractEvent.abstractTargetID === id;
<add> abstractEvent.reactEventType ===
<add> responderAbstractEventTypes.responderRelease &&
<add> abstractEvent.reactTargetID === id;
<ide> };
<ide> expect(ResponderEventPlugin.getResponderID()).toBe(null);
<ide> expect(existsInExtraction(extracted, test)).toBe(true); | 15 |
Javascript | Javascript | fix beautify issue | 96df6aecdba4bd31cdb8c41c18350b7b05dba490 | <ide><path>test/NodeWatchFileSystem.unittest.js
<ide> describe("NodeWatchFileSystem", function() {
<ide> var wfs = new NodeWatchFileSystem();
<ide> var watcher = wfs.watch([fileDirect], [], [], startTime, {
<ide> aggregateTimeout: 1000
<del> }, function(err, filesModified, dirsModified, missingCreated, fileTimestamps /*, dirTimestamps */) {
<add> }, function(err, filesModified, dirsModified, missingCreated, fileTimestamps) {
<ide> if(err) throw err;
<ide> filesModified.should.be.eql([fileDirect]);
<ide> dirsModified.should.be.eql([]);
<ide> describe("NodeWatchFileSystem", function() {
<ide> var wfs = new NodeWatchFileSystem();
<ide> var watcher = wfs.watch([fileDirect], [], [], startTime, {
<ide> aggregateTimeout: 1000
<del> }, function(err, filesModified, dirsModified, missingCreated, fileTimestamps /*, dirTimestamps */) {
<add> }, function(err, filesModified, dirsModified, missingCreated, fileTimestamps) {
<ide> if(err) throw err;
<ide> filesModified.should.be.eql([fileDirect]);
<ide> dirsModified.should.be.eql([]); | 1 |
Text | Text | fix `actionpack/changelog.md` [ci skip] | 3175d3d549821edefff4604db8fc729391957f0e | <ide><path>actionpack/CHANGELOG.md
<ide> Enable `action_dispatch.use_cookies_with_metadata` to use this feature, which
<ide> writes cookies with the new purpose and expiry metadata embedded.
<ide>
<del> Pull Request: #32937
<del>
<ide> *Assain Jaleel*
<ide>
<ide> * Raises `ActionController::RespondToMismatchError` with confliciting `respond_to` invocations.
<ide>
<ide> *Aaron Kromer*
<ide>
<del>* Pass along arguments to underlying `get` method in `follow_redirect!`
<add>* Pass along arguments to underlying `get` method in `follow_redirect!`.
<ide>
<ide> Now all arguments passed to `follow_redirect!` are passed to the underlying
<ide> `get` method. This for example allows to set custom headers for the
<ide>
<ide> *Vinicius Stock*
<ide>
<del>* Introduce ActionDispatch::DebugExceptions.register_interceptor
<add>* Introduce `ActionDispatch::DebugExceptions.register_interceptor`.
<ide>
<ide> Exception aware plugin authors can use the newly introduced
<ide> `.register_interceptor` method to get the processed exception, instead of | 1 |
Javascript | Javascript | add test for connection timeouts | 33c33949b2965512e6e058e6e1e5c800a617d071 | <ide><path>lib/net.js
<ide> Socket.prototype._shutdown = function() {
<ide>
<ide>
<ide> Socket.prototype.end = function(data, encoding) {
<del> if (this.writable) {
<add> if (this._connecting) {
<add> this.destroy();
<add> } else if (this.writable) {
<ide> if (this._writeQueueLast() !== END_OF_FILE) {
<ide> if (data) this.write(data, encoding);
<ide> this._writeQueue.push(END_OF_FILE);
<ide><path>test/simple/test-net-connect-timeout.js
<add>// This example attempts to time out before the connection is established
<add>// https://groups.google.com/forum/#!topic/nodejs/UE0ZbfLt6t8
<add>// https://groups.google.com/forum/#!topic/nodejs-dev/jR7-5UDqXkw
<add>
<add>var common = require('../common');
<add>var net = require('net');
<add>var assert = require('assert');
<add>
<add>var start = new Date();
<add>var gotTimeout = false;
<add>var gotConnect = false;
<add>var T = 100;
<add>
<add>var socket = net.createConnection(9999, '23.23.23.23');
<add>
<add>socket.setTimeout(T);
<add>
<add>
<add>socket.on('timeout', function() {
<add> console.error("timeout");
<add> gotTimeout = true;
<add> var now = new Date();
<add> assert.ok(now - start < T + 500);
<add> socket.end();
<add>});
<add>
<add>socket.on('connect', function() {
<add> console.error("connect");
<add> gotConnect = true;
<add> socket.end();
<add>});
<add>
<add>
<add>process.on('exit', function() {
<add> assert.ok(gotTimeout);
<add> assert.ok(!gotConnect);
<add>}); | 2 |
Javascript | Javascript | join merged style tags | a2f37ba4cc19ba5baf4d5377acec8c3e1a415eab | <ide><path>packages/next/pages/_document.js
<ide> export class Head extends Component {
<ide> {/* https://www.ampproject.org/docs/fundamentals/optimize_amp#optimize-the-amp-runtime-loading */}
<ide> <link rel="preload" as="script" href="https://cdn.ampproject.org/v0.js" />
<ide> {/* Add custom styles before AMP styles to prevent accidental overrides */}
<del> {styles && <style amp-custom="" dangerouslySetInnerHTML={{__html: styles.map((style) => style.props.dangerouslySetInnerHTML.__html)}} />}
<add> {styles && <style amp-custom="" dangerouslySetInnerHTML={{__html: styles.map((style) => style.props.dangerouslySetInnerHTML.__html).join('')}} />}
<ide> <style amp-boilerplate="" dangerouslySetInnerHTML={{__html: `body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}`}}></style>
<ide> <noscript><style amp-boilerplate="" dangerouslySetInnerHTML={{__html: `body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}`}}></style></noscript>
<ide> <script async src="https://cdn.ampproject.org/v0.js"></script> | 1 |
Text | Text | fix docbin init in training example | 96726ec1f62ade72b7904b2b21b4a893f93d0ca8 | <ide><path>website/docs/usage/training.md
<ide> import spacy
<ide> from spacy.tokens import Doc, DocBin
<ide>
<ide> nlp = spacy.blank("en")
<del>docbin = DocBin(nlp.vocab)
<add>docbin = DocBin()
<ide> words = ["Apple", "is", "looking", "at", "buying", "U.K.", "startup", "."]
<ide> spaces = [True, True, True, True, True, True, True, False]
<ide> ents = ["B-ORG", "O", "O", "O", "O", "B-GPE", "O", "O"] | 1 |
Python | Python | use triple quotation marks for epilog | fef6f8a8608027460ed3014dbfd35a715cfe3cbb | <ide><path>glances/main.py
<ide> class GlancesMain(object):
<ide> username = "glances"
<ide> password = ""
<ide>
<del> # Exemple of use
<del> example_of_use = "\
<del>Examples of use:\n\
<del>\n\
<del>Monitor local machine (standalone mode):\n\
<del> $ glances\n\
<del>\n\
<del>Monitor local machine with the Web interface (Web UI):\n\
<del> $ glances -w\n\
<del> Glances web server started on http://0.0.0.0:61208/\n\
<del>\n\
<del>Monitor local machine and export stats to a CSV file (standalone mode):\n\
<del> $ glances --export-csv /tmp/glances.csv\n\
<del>\n\
<del>Monitor local machine and export stats to a InfluxDB server with 5s refresh time (standalone mode):\n\
<del> $ glances -t 5 --export-influxdb\n\
<del>\n\
<del>Start a Glances server (server mode):\n\
<del> $ glances -s\n\
<del>\n\
<del>Connect Glances to a Glances server (client mode):\n\
<del> $ glances -c <ip_server>\n\
<del>\n\
<del>Connect Glances to a Glances server and export stats to a StatsD server (client mode):\n\
<del> $ glances -c <ip_server> --export-statsd\n\
<del>\n\
<del>Start the client browser (browser mode):\n\
<del> $ glances --browser\n\
<del> "
<add> # Examples of use
<add> example_of_use = """
<add>Examples of use:
<add> Monitor local machine (standalone mode):
<add> $ glances
<add>
<add> Monitor local machine with the Web interface (Web UI):
<add> $ glances -w
<add> Glances web server started on http://0.0.0.0:61208/
<add>
<add> Monitor local machine and export stats to a CSV file (standalone mode):
<add> $ glances --export-csv /tmp/glances.csv
<add>
<add> Monitor local machine and export stats to a InfluxDB server with 5s refresh time (standalone mode):
<add> $ glances -t 5 --export-influxdb
<add>
<add> Start a Glances server (server mode):
<add> $ glances -s
<add>
<add> Connect Glances to a Glances server (client mode):
<add> $ glances -c <ip_server>
<add>
<add> Connect Glances to a Glances server and export stats to a StatsD server (client mode):
<add> $ glances -c <ip_server> --export-statsd
<add>
<add> Start the client browser (browser mode):
<add> $ glances --browser
<add>"""
<ide>
<ide> def __init__(self):
<ide> """Manage the command line arguments.""" | 1 |
Text | Text | document the upgrade process | 4097ed5586ca23551d7f1fa3dbde4f5c86fa36ae | <ide><path>guides/source/upgrading_ruby_on_rails.md
<ide> Before attempting to upgrade an existing application, you should be sure you hav
<ide>
<ide> The best way to be sure that your application still works after upgrading is to have good test coverage before you start the process. If you don't have automated tests that exercise the bulk of your application, you'll need to spend time manually exercising all the parts that have changed. In the case of a Rails upgrade, that will mean every single piece of functionality in the application. Do yourself a favor and make sure your test coverage is good _before_ you start an upgrade.
<ide>
<add>### The Upgrade Process
<add>
<add>When changing Rails versions, it's best to move slowly, one minor version at a time, in order to make good use of the deprecation warnings. Rails version numbers are in the form Major.Minor.Patch. Major and Minor versions change the API which means you will probably need to change your code. Patch versions are just bug fixes that don't change the API.
<add>
<add>The process should go as follows:
<add>
<add>1. Write tests and make sure they pass
<add>1. Move to the latest patch version after your current version
<add>1. Fix tests and deprecated features
<add>1. Move to the latest patch version of the next minor version
<add>
<add>Repeat this process until you reach your target Rails version. Each time you move versions, you will need to change the Rails version number in the Gemfile (and possibly other Gem versions) and run `bundle update`. Then run the Update rake task mentioned below to update configuration files, then run your tests.
<add>
<add>You can find a list of all the Rails Gem versions [here](https://rubygems.org/gems/rails/versions).
<add>
<ide> ### Ruby Versions
<ide>
<ide> Rails generally stays close to the latest released Ruby version when it's released: | 1 |
Python | Python | use list to allow indexing | 05f1eb6449222e3430057faf259232ae5b707510 | <ide><path>airflow/hooks/hive_hooks.py
<ide> def max_partition(self, schema, table_name, field=None, filter=None):
<ide> if not parts:
<ide> return None
<ide> elif len(parts[0]) == 1:
<del> field = parts[0].keys()[0]
<add> field = list(parts[0].keys())[0]
<ide> elif not field:
<ide> raise AirflowException(
<ide> "Please specify the field you want the max " | 1 |
PHP | PHP | add extra space | 5c515a8adce4ab2fea0a8b105191f9ccc49cdb66 | <ide><path>src/Illuminate/Notifications/resources/views/email-plain.blade.php
<ide> <?php
<del>if( $greeting !== null ) {
<add>if ( $greeting !== null ) {
<ide> echo e($greeting);
<ide> } else {
<ide> echo $level == 'error' ? 'Whoops!' : 'Hello!'; | 1 |
Ruby | Ruby | simplify minitest inclusion | c45cca8e36401f6d95d851befef35879a5629182 | <ide><path>Library/Homebrew/dev-cmd/test.rb
<ide> def test
<ide> exec(*args)
<ide> end
<ide> end
<del> rescue Assertions::FailedAssertion => e
<add> rescue MiniTest::Assertion => e
<ide> ofail "#{f.full_name}: failed"
<ide> puts e.message
<ide> rescue Exception => e
<ide><path>Library/Homebrew/formula_assertions.rb
<ide> module Homebrew
<ide> module Assertions
<del> if defined?(Gem)
<del> begin
<del> gem "minitest", "< 5.0.0"
<del> rescue Gem::LoadError
<del> require "test/unit/assertions"
<del> else
<del> require "minitest/unit"
<del> require "test/unit/assertions"
<del> end
<del> else
<del> require "test/unit/assertions"
<del> end
<del>
<del> if defined?(MiniTest::Assertion)
<del> FailedAssertion = MiniTest::Assertion
<del> elsif defined?(Minitest::Assertion)
<del> FailedAssertion = Minitest::Assertion
<del> else
<del> FailedAssertion = Test::Unit::AssertionFailedError
<del> end
<del>
<add> require "test/unit/assertions"
<ide> include ::Test::Unit::Assertions
<ide>
<ide> # Returns the output of running cmd, and asserts the exit status | 2 |
Ruby | Ruby | remove empty lines in rails development logger | 9433dde5d1ff33731e5a928166c1b9192bca92ae | <ide><path>railties/lib/rails/rack/logger.rb
<ide> def call(env)
<ide> protected
<ide>
<ide> def call_app(request, env)
<del> # Put some space between requests in development logs.
<del> if development?
<del> logger.debug ''
<del> logger.debug ''
<del> end
<del>
<ide> instrumenter = ActiveSupport::Notifications.instrumenter
<ide> instrumenter.start 'request.action_dispatch', request: request
<ide> logger.info { started_request_message(request) } | 1 |
Text | Text | update usage docs for lemmatization and morphology | f9ed31a757f15e1ef48c9b4d8950f1fc799cb98e | <ide><path>website/docs/api/lemmatizer.md
<ide> added to your pipeline, and not a hidden part of the vocab that runs behind the
<ide> scenes. This makes it easier to customize how lemmas should be assigned in your
<ide> pipeline.
<ide>
<del>If the lemmatization mode is set to `"rule"` and requires part-of-speech tags to
<del>be assigned, make sure a [`Tagger`](/api/tagger) or another component assigning
<del>tags is available in the pipeline and runs _before_ the lemmatizer.
<add>If the lemmatization mode is set to `"rule"`, which requires coarse-grained POS
<add>(`Token.pos`) to be assigned, make sure a [`Tagger`](/api/tagger),
<add>[`Morphologizer`](/api/morphologizer) or another component assigning POS is
<add>available in the pipeline and runs _before_ the lemmatizer.
<ide>
<ide> </Infobox>
<ide>
<ide><path>website/docs/usage/101/_language-data.md
<ide> values are defined in the [`Language.Defaults`](/api/language#defaults).
<ide> > nlp_de = German() # Includes German data
<ide> > ```
<ide>
<del>| Name | Description |
<del>| ---------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
<del>| **Stop words**<br />[`stop_words.py`][stop_words.py] | List of most common words of a language that are often useful to filter out, for example "and" or "I". Matching tokens will return `True` for `is_stop`. |
<del>| **Tokenizer exceptions**<br />[`tokenizer_exceptions.py`][tokenizer_exceptions.py] | Special-case rules for the tokenizer, for example, contractions like "can't" and abbreviations with punctuation, like "U.K.". |
<del>| **Punctuation rules**<br />[`punctuation.py`][punctuation.py] | Regular expressions for splitting tokens, e.g. on punctuation or special characters like emoji. Includes rules for prefixes, suffixes and infixes. |
<del>| **Character classes**<br />[`char_classes.py`][char_classes.py] | Character classes to be used in regular expressions, for example, latin characters, quotes, hyphens or icons. |
<del>| **Lexical attributes**<br />[`lex_attrs.py`][lex_attrs.py] | Custom functions for setting lexical attributes on tokens, e.g. `like_num`, which includes language-specific words like "ten" or "hundred". |
<del>| **Syntax iterators**<br />[`syntax_iterators.py`][syntax_iterators.py] | Functions that compute views of a `Doc` object based on its syntax. At the moment, only used for [noun chunks](/usage/linguistic-features#noun-chunks). |
<del>| **Lemmatizer**<br />[`spacy-lookups-data`][spacy-lookups-data] | Lemmatization rules or a lookup-based lemmatization table to assign base forms, for example "be" for "was". |
<add>| Name | Description |
<add>| ----------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
<add>| **Stop words**<br />[`stop_words.py`][stop_words.py] | List of most common words of a language that are often useful to filter out, for example "and" or "I". Matching tokens will return `True` for `is_stop`. |
<add>| **Tokenizer exceptions**<br />[`tokenizer_exceptions.py`][tokenizer_exceptions.py] | Special-case rules for the tokenizer, for example, contractions like "can't" and abbreviations with punctuation, like "U.K.". |
<add>| **Punctuation rules**<br />[`punctuation.py`][punctuation.py] | Regular expressions for splitting tokens, e.g. on punctuation or special characters like emoji. Includes rules for prefixes, suffixes and infixes. |
<add>| **Character classes**<br />[`char_classes.py`][char_classes.py] | Character classes to be used in regular expressions, for example, Latin characters, quotes, hyphens or icons. |
<add>| **Lexical attributes**<br />[`lex_attrs.py`][lex_attrs.py] | Custom functions for setting lexical attributes on tokens, e.g. `like_num`, which includes language-specific words like "ten" or "hundred". |
<add>| **Syntax iterators**<br />[`syntax_iterators.py`][syntax_iterators.py] | Functions that compute views of a `Doc` object based on its syntax. At the moment, only used for [noun chunks](/usage/linguistic-features#noun-chunks). |
<add>| **Lemmatizer**<br />[`lemmatizer.py`][lemmatizer.py] [`spacy-lookups-data`][spacy-lookups-data] | Custom lemmatizer implementation and lemmatization tables. |
<ide>
<ide> [stop_words.py]:
<ide> https://github.com/explosion/spaCy/tree/master/spacy/lang/en/stop_words.py
<ide> values are defined in the [`Language.Defaults`](/api/language#defaults).
<ide> https://github.com/explosion/spaCy/tree/master/spacy/lang/en/lex_attrs.py
<ide> [syntax_iterators.py]:
<ide> https://github.com/explosion/spaCy/tree/master/spacy/lang/en/syntax_iterators.py
<add>[lemmatizer.py]:
<add> https://github.com/explosion/spaCy/tree/master/spacy/lang/fr/lemmatizer.py
<ide> [spacy-lookups-data]: https://github.com/explosion/spacy-lookups-data
<ide><path>website/docs/usage/101/_pipelines.md
<ide> When you call `nlp` on a text, spaCy first tokenizes the text to produce a `Doc`
<ide> object. The `Doc` is then processed in several different steps – this is also
<ide> referred to as the **processing pipeline**. The pipeline used by the
<del>[default models](/models) consists of a tagger, a parser and an entity
<del>recognizer. Each pipeline component returns the processed `Doc`, which is then
<del>passed on to the next component.
<add>[default models](/models) typically include a tagger, a lemmatizer, a parser and
<add>an entity recognizer. Each pipeline component returns the processed `Doc`, which
<add>is then passed on to the next component.
<ide>
<ide> 
<ide>
<ide> passed on to the next component.
<ide> > - **Creates:** Objects, attributes and properties modified and set by the
<ide> > component.
<ide>
<del>| Name | Component | Creates | Description |
<del>| -------------- | ------------------------------------------------------------------ | --------------------------------------------------------- | ------------------------------------------------ |
<del>| **tokenizer** | [`Tokenizer`](/api/tokenizer) | `Doc` | Segment text into tokens. |
<del>| **tagger** | [`Tagger`](/api/tagger) | `Token.tag` | Assign part-of-speech tags. |
<del>| **parser** | [`DependencyParser`](/api/dependencyparser) | `Token.head`, `Token.dep`, `Doc.sents`, `Doc.noun_chunks` | Assign dependency labels. |
<del>| **ner** | [`EntityRecognizer`](/api/entityrecognizer) | `Doc.ents`, `Token.ent_iob`, `Token.ent_type` | Detect and label named entities. |
<del>| **lemmatizer** | [`Lemmatizer`](/api/lemmatizer) | `Token.lemma` | Assign base forms. |
<del>| **textcat** | [`TextCategorizer`](/api/textcategorizer) | `Doc.cats` | Assign document labels. |
<del>| **custom** | [custom components](/usage/processing-pipelines#custom-components) | `Doc._.xxx`, `Token._.xxx`, `Span._.xxx` | Assign custom attributes, methods or properties. |
<add>| Name | Component | Creates | Description |
<add>| -------------- | ------------------------------------------- | --------------------------------------------------------- | -------------------------------- |
<add>| **tokenizer** | [`Tokenizer`](/api/tokenizer) | `Doc` | Segment text into tokens. |
<add>| **tagger** | [`Tagger`](/api/tagger) | `Token.tag` | Assign part-of-speech tags. |
<add>| **parser** | [`DependencyParser`](/api/dependencyparser) | `Token.head`, `Token.dep`, `Doc.sents`, `Doc.noun_chunks` | Assign dependency labels. |
<add>| **ner** | [`EntityRecognizer`](/api/entityrecognizer) | `Doc.ents`, `Token.ent_iob`, `Token.ent_type` | Detect and label named entities. |
<add>| **lemmatizer** | [`Lemmatizer`](/api/lemmatizer) | `Token.lemma` | Assign base forms. |
<add>| **textcat** | [`TextCategorizer`](/api/textcategorizer) | `Doc.cats` | Assign document labels. |
<add>
<add>| **custom** |
<add>[custom components](/usage/processing-pipelines#custom-components) |
<add>`Doc._.xxx`, `Token._.xxx`, `Span._.xxx` | Assign custom attributes, methods or
<add>properties. |
<ide>
<ide> The processing pipeline always **depends on the statistical model** and its
<ide> capabilities. For example, a pipeline can only include an entity recognizer
<ide><path>website/docs/usage/index.md
<ide> $ pip install -U spacy
<ide> To install additional data tables for lemmatization you can run
<ide> `pip install spacy[lookups]` or install
<ide> [`spacy-lookups-data`](https://github.com/explosion/spacy-lookups-data)
<del>separately. The lookups package is needed to create blank models with
<del>lemmatization data, and to lemmatize in languages that don't yet come with
<del>pretrained models and aren't powered by third-party libraries.
<add>separately. The lookups package is needed to provide normalization and
<add>lemmatization data for new models and to lemmatize in languages that don't yet
<add>come with pretrained models and aren't powered by third-party libraries.
<ide>
<ide> </Infobox>
<ide>
<ide><path>website/docs/usage/linguistic-features.md
<ide> title: Linguistic Features
<ide> next: /usage/rule-based-matching
<ide> menu:
<ide> - ['POS Tagging', 'pos-tagging']
<add> - ['Morphology', 'morphology']
<add> - ['Lemmatization', 'lemmatization']
<ide> - ['Dependency Parse', 'dependency-parse']
<ide> - ['Named Entities', 'named-entities']
<ide> - ['Entity Linking', 'entity-linking']
<ide> - ['Tokenization', 'tokenization']
<ide> - ['Merging & Splitting', 'retokenization']
<ide> - ['Sentence Segmentation', 'sbd']
<ide> - ['Vectors & Similarity', 'vectors-similarity']
<del> - ['Language data', 'language-data']
<add> - ['Mappings & Exceptions', 'mappings-exceptions']
<add> - ['Language Data', 'language-data']
<ide> ---
<ide>
<ide> Processing raw text intelligently is difficult: most words are rare, and it's
<ide> in the [models directory](/models).
<ide>
<ide> </Infobox>
<ide>
<del>### Rule-based morphology {#rule-based-morphology}
<add>## Morphology {#morphology}
<ide>
<ide> Inflectional morphology is the process by which a root form of a word is
<ide> modified by adding prefixes or suffixes that specify its grammatical function
<ide> but do not changes its part-of-speech. We say that a **lemma** (root form) is
<ide> **inflected** (modified/combined) with one or more **morphological features** to
<ide> create a surface form. Here are some examples:
<ide>
<del>| Context | Surface | Lemma | POS | Morphological Features |
<del>| ---------------------------------------- | ------- | ----- | ---- | ---------------------------------------- |
<del>| I was reading the paper | reading | read | verb | `VerbForm=Ger` |
<del>| I don't watch the news, I read the paper | read | read | verb | `VerbForm=Fin`, `Mood=Ind`, `Tense=Pres` |
<del>| I read the paper yesterday | read | read | verb | `VerbForm=Fin`, `Mood=Ind`, `Tense=Past` |
<del>
<del>English has a relatively simple morphological system, which spaCy handles using
<del>rules that can be keyed by the token, the part-of-speech tag, or the combination
<del>of the two. The system works as follows:
<del>
<del>1. The tokenizer consults a
<del> [mapping table](/usage/adding-languages#tokenizer-exceptions)
<del> `TOKENIZER_EXCEPTIONS`, which allows sequences of characters to be mapped to
<del> multiple tokens. Each token may be assigned a part of speech and one or more
<del> morphological features.
<del>2. The part-of-speech tagger then assigns each token an **extended POS tag**. In
<del> the API, these tags are known as `Token.tag`. They express the part-of-speech
<del> (e.g. `VERB`) and some amount of morphological information, e.g. that the
<del> verb is past tense.
<del>3. For words whose POS is not set by a prior process, a
<del> [mapping table](/usage/adding-languages#tag-map) `TAG_MAP` maps the tags to a
<del> part-of-speech and a set of morphological features.
<del>4. Finally, a **rule-based deterministic lemmatizer** maps the surface form, to
<del> a lemma in light of the previously assigned extended part-of-speech and
<del> morphological information, without consulting the context of the token. The
<del> lemmatizer also accepts list-based exception files, acquired from
<del> [WordNet](https://wordnet.princeton.edu/).
<add>| Context | Surface | Lemma | POS | Morphological Features |
<add>| ---------------------------------------- | ------- | ----- | ------ | ---------------------------------------- |
<add>| I was reading the paper | reading | read | `VERB` | `VerbForm=Ger` |
<add>| I don't watch the news, I read the paper | read | read | `VERB` | `VerbForm=Fin`, `Mood=Ind`, `Tense=Pres` |
<add>| I read the paper yesterday | read | read | `VERB` | `VerbForm=Fin`, `Mood=Ind`, `Tense=Past` |
<add>
<add>Morphological features are stored in the [`MorphAnalysis`](/api/morphanalysis)
<add>under `Token.morph`, which allows you to access individual morphological
<add>features. The attribute `Token.morph_` provides the morphological analysis in
<add>the Universal Dependencies FEATS format.
<add>
<add>```python
<add>### {executable="true"}
<add>import spacy
<add>
<add>nlp = spacy.load("en_core_web_sm")
<add>doc = nlp("I was reading the paper.")
<add>
<add>token = doc[0] # "I"
<add>assert token.morph_ == "Case=Nom|Number=Sing|Person=1|PronType=Prs"
<add>assert token.morph.get("PronType") == ["Prs"]
<add>```
<add>
<add>### Statistical morphology {#morphologizer new="3" model="morphologizer"}
<add>
<add>spaCy v3 includes a statistical morphologizer component that assigns the
<add>morphological features and POS as `Token.morph` and `Token.pos`.
<add>
<add>```python
<add>### {executable="true"}
<add>import spacy
<add>
<add>nlp = spacy.load("de_core_news_sm")
<add>doc = nlp("Wo bist du?") # 'Where are you?'
<add>assert doc[2].morph_ == "Case=Nom|Number=Sing|Person=2|PronType=Prs"
<add>assert doc[2].pos_ == "PRON"
<add>```
<add>
<add>### Rule-based morphology {#rule-based-morphology}
<add>
<add>For languages with relatively simple morphological systems like English, spaCy
<add>can assign morphological features through a rule-based approach, which uses the
<add>token text and fine-grained part-of-speech tags to produce coarse-grained
<add>part-of-speech tags and morphological features.
<add>
<add>1. The part-of-speech tagger assigns each token a **fine-grained part-of-speech
<add> tag**. In the API, these tags are known as `Token.tag`. They express the
<add> part-of-speech (e.g. verb) and some amount of morphological information, e.g.
<add> that the verb is past tense (e.g. `VBD` for a past tense verb in the Penn
<add> Treebank) .
<add>2. For words whose coarse-grained POS is not set by a prior process, a
<add> [mapping table](#mapping-exceptions) maps the fine-grained tags to a
<add> coarse-grained POS tags and morphological features.
<add>
<add>```python
<add>### {executable="true"}
<add>import spacy
<add>
<add>nlp = spacy.load("en_core_web_sm")
<add>doc = nlp("Where are you?")
<add>assert doc[2].morph_ == "Case=Nom|Person=2|PronType=Prs"
<add>assert doc[2].pos_ == "PRON"
<add>```
<add>
<add>## Lemmatization {#lemmatization model="lemmatizer" new="3"}
<add>
<add>The [`Lemmatizer`](/api/lemmatizer) is a pipeline component that provides lookup
<add>and rule-based lemmatization methods in a configurable component. An individual
<add>language can extend the `Lemmatizer` as part of its [language
<add>data](#language-data).
<add>
<add>```python
<add>### {executable="true"}
<add>import spacy
<add>
<add># English models include a rule-based lemmatizer
<add>nlp = spacy.load("en_core_web_sm")
<add>lemmatizer = nlp.get_pipe("lemmatizer")
<add>assert lemmatizer.mode == "rule"
<add>
<add>doc = nlp("I was reading the paper.")
<add>assert doc[1].lemma_ == "be"
<add>assert doc[2].lemma_ == "read"
<add>```
<add>
<add><Infobox title="Important note" variant="warning">
<add>
<add>Unlike spaCy v2, spaCy v3 models do not provide lemmas by default or switch
<add>automatically between lookup and rule-based lemmas depending on whether a
<add>tagger is in the pipeline. To have lemmas in a `Doc`, the pipeline needs to
<add>include a `lemmatizer` component. A `lemmatizer` is configured to use a single
<add>mode such as `"lookup"` or `"rule"` on initialization. The `"rule"` mode
<add>requires `Token.pos` to be set by a previous component.
<add>
<add></Infobox>
<add>
<add>The data for spaCy's lemmatizers is distributed in the package
<add>[`spacy-lookups-data`](https://github.com/explosion/spacy-lookups-data). The
<add>provided models already include all the required tables, but if you are
<add>creating new models, you'll probably want to install `spacy-lookups-data` to
<add>provide the data when the lemmatizer is initialized.
<add>
<add>### Lookup lemmatizer {#lemmatizer-lookup}
<add>
<add>For models without a tagger or morphologizer, a lookup lemmatizer can be added
<add>to the pipeline as long as a lookup table is provided, typically through
<add>`spacy-lookups-data`. The lookup lemmatizer looks up the token surface form in
<add>the lookup table without reference to the token's part-of-speech or context.
<add>
<add>```python
<add># pip install spacy-lookups-data
<add>import spacy
<add>
<add>nlp = spacy.blank("sv")
<add>nlp.add_pipe("lemmatizer", config={"mode": "lookup"})
<add>```
<add>
<add>### Rule-based lemmatizer {#lemmatizer-rule}
<add>
<add>When training models that include a component that assigns POS (a morphologizer
<add>or a tagger with a [POS mapping](#mappings-exceptions)), a rule-based
<add>lemmatizer can be added using rule tables from `spacy-lookups-data`:
<add>
<add>```python
<add># pip install spacy-lookups-data
<add>import spacy
<add>
<add>nlp = spacy.blank("de")
<add>
<add># morphologizer (note: model is not yet trained!)
<add>nlp.add_pipe("morphologizer")
<add>
<add># rule-based lemmatizer
<add>nlp.add_pipe("lemmatizer", config={"mode": "rule"})
<add>```
<add>
<add>The rule-based deterministic lemmatizer maps the surface form to a lemma in
<add>light of the previously assigned coarse-grained part-of-speech and morphological
<add>information, without consulting the context of the token. The rule-based
<add>lemmatizer also accepts list-based exception files. For English, these are
<add>acquired from [WordNet](https://wordnet.princeton.edu/).
<ide>
<ide> ## Dependency Parsing {#dependency-parse model="parser"}
<ide>
<ide> on a token, it will return an empty string.
<ide> >
<ide> > #### BILUO Scheme
<ide> >
<del>> - `B` – Token is the **beginning** of an entity.
<add>> - `B` – Token is the **beginning** of a multi-token entity.
<ide> > - `I` – Token is **inside** a multi-token entity.
<ide> > - `L` – Token is the **last** token of a multi-token entity.
<ide> > - `U` – Token is a single-token **unit** entity.
<ide> doc = nlp(text)
<ide> print("After:", [sent.text for sent in doc.sents])
<ide> ```
<ide>
<add>## Mappings & Exceptions {#mappings-exceptions new="3"}
<add>
<add>The [`AttributeRuler`](/api/attributeruler) manages rule-based mappings and
<add>exceptions for all token-level attributes. As the number of pipeline components
<add>has grown from spaCy v2 to v3, handling rules and exceptions in each component
<add>individually has become impractical, so the `AttributeRuler` provides a single
<add>component with a unified pattern format for all token attribute mappings and
<add>exceptions.
<add>
<add>The `AttributeRuler` uses [`Matcher`
<add>patterns](/usage/rule-based-matching#adding-patterns) to identify tokens and
<add>then assigns them the provided attributes. If needed, the `Matcher` patterns
<add>can include context around the target token. For example, the `AttributeRuler`
<add>can:
<add>
<add>- provide exceptions for any token attributes
<add>- map fine-grained tags to coarse-grained tags for languages without statistical
<add> morphologizers (replacing the v2 tag map in the language data)
<add>- map token surface form + fine-grained tags to morphological features
<add> (replacing the v2 morph rules in the language data)
<add>- specify the tags for space tokens (replacing hard-coded behavior in the
<add> tagger)
<add>
<add>The following example shows how the tag and POS `NNP`/`PROPN` can be specified
<add>for the phrase `"The Who"`, overriding the tags provided by the statistical
<add>tagger and the POS tag map.
<add>
<add>```python
<add>### {executable="true"}
<add>import spacy
<add>
<add>nlp = spacy.load("en_core_web_sm")
<add>text = "I saw The Who perform. Who did you see?"
<add>
<add>doc1 = nlp(text)
<add>assert doc1[2].tag_ == "DT"
<add>assert doc1[2].pos_ == "DET"
<add>assert doc1[3].tag_ == "WP"
<add>assert doc1[3].pos_ == "PRON"
<add>
<add># add a new exception for "The Who" as NNP/PROPN NNP/PROPN
<add>ruler = nlp.get_pipe("attribute_ruler")
<add>
<add># pattern to match "The Who"
<add>patterns = [[{"LOWER": "the"}, {"TEXT": "Who"}]]
<add># the attributes to assign to the matched token
<add>attrs = {"TAG": "NNP", "POS": "PROPN"}
<add>
<add># add rule for "The" in "The Who"
<add>ruler.add(patterns=patterns, attrs=attrs, index=0)
<add># add rule for "Who" in "The Who"
<add>ruler.add(patterns=patterns, attrs=attrs, index=1)
<add>
<add>doc2 = nlp(text)
<add>assert doc2[2].tag_ == "NNP"
<add>assert doc2[3].tag_ == "NNP"
<add>assert doc2[2].pos_ == "PROPN"
<add>assert doc2[3].pos_ == "PROPN"
<add>
<add># the second "Who" remains unmodified
<add>assert doc2[5].tag_ == "WP"
<add>assert doc2[5].pos_ == "PRON"
<add>```
<add>
<add>For easy migration from from spaCy v2 to v3, the `AttributeRuler` can import v2
<add>`TAG_MAP` and `MORPH_RULES` data with the methods
<add>[`AttributerRuler.load_from_tag_map`](/api/attributeruler#load_from_tag_map) and
<add>[`AttributeRuler.load_from_morph_rules`](/api/attributeruler#load_from_morph_rules).
<add>
<ide> ## Word vectors and semantic similarity {#vectors-similarity}
<ide>
<ide> import Vectors101 from 'usage/101/\_vectors-similarity.md'
<ide> for word, vector in vector_data.items():
<ide> vocab.set_vector(word, vector)
<ide> ```
<ide>
<del>## Language data {#language-data}
<add>## Language Data {#language-data}
<ide>
<ide> import LanguageData101 from 'usage/101/\_language-data.md'
<ide>
<ide><path>website/docs/usage/processing-pipelines.md
<ide> available pipeline components and component functions.
<ide> > ruler = nlp.add_pipe("entity_ruler")
<ide> > ```
<ide>
<del>| String name | Component | Description |
<del>| --------------- | ----------------------------------------------- | ----------------------------------------------------------------------------------------- |
<del>| `tagger` | [`Tagger`](/api/tagger) | Assign part-of-speech-tags. |
<del>| `parser` | [`DependencyParser`](/api/dependencyparser) | Assign dependency labels. |
<del>| `ner` | [`EntityRecognizer`](/api/entityrecognizer) | Assign named entities. |
<del>| `entity_linker` | [`EntityLinker`](/api/entitylinker) | Assign knowledge base IDs to named entities. Should be added after the entity recognizer. |
<del>| `entity_ruler` | [`EntityRuler`](/api/entityruler) | Assign named entities based on pattern rules and dictionaries. |
<del>| `textcat` | [`TextCategorizer`](/api/textcategorizer) | Assign text categories. |
<del>| `lemmatizer` | [`Lemmatizer`](/api/lemmatizer) | Assign base forms to words. |
<del>| `morphologizer` | [`Morphologizer`](/api/morphologizer) | Assign morphological features and coarse-grained POS tags. |
<del>| `senter` | [`SentenceRecognizer`](/api/sentencerecognizer) | Assign sentence boundaries. |
<del>| `sentencizer` | [`Sentencizer`](/api/sentencizer) | Add rule-based sentence segmentation without the dependency parse. |
<del>| `tok2vec` | [`Tok2Vec`](/api/tok2vec) | Assign token-to-vector embeddings. |
<del>| `transformer` | [`Transformer`](/api/transformer) | Assign the tokens and outputs of a transformer model. |
<add>| String name | Component | Description |
<add>| ----------------- | ----------------------------------------------- | ----------------------------------------------------------------------------------------- |
<add>| `tagger` | [`Tagger`](/api/tagger) | Assign part-of-speech-tags. |
<add>| `parser` | [`DependencyParser`](/api/dependencyparser) | Assign dependency labels. |
<add>| `ner` | [`EntityRecognizer`](/api/entityrecognizer) | Assign named entities. |
<add>| `entity_linker` | [`EntityLinker`](/api/entitylinker) | Assign knowledge base IDs to named entities. Should be added after the entity recognizer. |
<add>| `entity_ruler` | [`EntityRuler`](/api/entityruler) | Assign named entities based on pattern rules and dictionaries. |
<add>| `textcat` | [`TextCategorizer`](/api/textcategorizer) | Assign text categories. |
<add>| `lemmatizer` | [`Lemmatizer`](/api/lemmatizer) | Assign base forms to words. |
<add>| `morphologizer` | [`Morphologizer`](/api/morphologizer) | Assign morphological features and coarse-grained POS tags. |
<add>| `attribute_ruler` | [`AttributeRuler`](/api/attributeruler) | Assign token attribute mappings and rule-based exceptions. |
<add>| `senter` | [`SentenceRecognizer`](/api/sentencerecognizer) | Assign sentence boundaries. |
<add>| `sentencizer` | [`Sentencizer`](/api/sentencizer) | Add rule-based sentence segmentation without the dependency parse. |
<add>| `tok2vec` | [`Tok2Vec`](/api/tok2vec) | Assign token-to-vector embeddings. |
<add>| `transformer` | [`Transformer`](/api/transformer) | Assign the tokens and outputs of a transformer model. |
<ide>
<ide> ### Disabling and modifying pipeline components {#disabling}
<ide>
<ide><path>website/docs/usage/v3.md
<ide> add to your pipeline and customize for your use case:
<ide> > #### Example
<ide> >
<ide> > ```python
<add>> # pip install spacy-lookups-data
<ide> > nlp = spacy.blank("en")
<ide> > nlp.add_pipe("lemmatizer")
<ide> > ```
<ide> The following methods, attributes and commands are new in spaCy v3.0.
<ide> | [`Language.has_factory`](/api/language#has_factory) | Check whether a component factory is registered on a language class.s |
<ide> | [`Language.get_factory_meta`](/api/language#get_factory_meta) [`Language.get_pipe_meta`](/api/language#get_factory_meta) | Get the [`FactoryMeta`](/api/language#factorymeta) with component metadata for a factory or instance name. |
<ide> | [`Language.config`](/api/language#config) | The [config](/usage/training#config) used to create the current `nlp` object. An instance of [`Config`](https://thinc.ai/docs/api-config#config) and can be saved to disk and used for training. |
<del>| [`Pipe.score`](/api/pipe#score) | Method on trainable pipeline components that returns a dictionary of evaluation scores. |
<add>| [`Pipe.score`](/api/pipe#score) | Method on pipeline components that returns a dictionary of evaluation scores. |
<ide> | [`registry`](/api/top-level#registry) | Function registry to map functions to string names that can be referenced in [configs](/usage/training#config). |
<ide> | [`util.load_meta`](/api/top-level#util.load_meta) [`util.load_config`](/api/top-level#util.load_config) | Updated helpers for loading a model's [`meta.json`](/api/data-formats#meta) and [`config.cfg`](/api/data-formats#config). |
<ide> | [`util.get_installed_models`](/api/top-level#util.get_installed_models) | Names of all models installed in the environment. |
<ide> on them.
<ide> | keyword-arguments like `vocab=False` on `to_disk`, `from_disk`, `to_bytes`, `from_bytes` | `exclude=["vocab"]` |
<ide> | `n_threads` argument on [`Tokenizer`](/api/tokenizer), [`Matcher`](/api/matcher), [`PhraseMatcher`](/api/phrasematcher) | `n_process` |
<ide> | `verbose` argument on [`Language.evaluate`](/api/language#evaluate) | logging (`DEBUG`) |
<del>| `SentenceSegmenter` hook, `SimilarityHook` | [user hooks](/usage/processing-pipelines#custom-components-user-hooks), [`Sentencizer`](/api/sentencizer), [`SentenceRecognizer`](/api/sentenceregognizer) |
<add>| `SentenceSegmenter` hook, `SimilarityHook` | [user hooks](/usage/processing-pipelines#custom-components-user-hooks), [`Sentencizer`](/api/sentencizer), [`SentenceRecognizer`](/api/sentencerecognizer) |
<ide>
<ide> ## Migrating from v2.x {#migrating}
<ide> | 7 |
Text | Text | use singular form for application | 7799bbcdd403dd58cc96e030115cb22fe80af7b9 | <ide><path>guides/source/upgrading_ruby_on_rails.md
<ide> end
<ide>
<ide> This can be turned off per-association with `optional: true`.
<ide>
<del>This default will be automatically configured in new applications. If existing application
<del>want to add this feature it will need to be turned on in an initializer.
<add>This default will be automatically configured in new applications. If an existing application
<add>wants to add this feature it will need to be turned on in an initializer:
<ide>
<ide> config.active_record.belongs_to_required_by_default = true
<ide> | 1 |
Python | Python | add type hints to the array api __setitem__ | 687e2a3b1ee167ae8dc359cf7e92b67e551dbbfe | <ide><path>numpy/_array_api/_array_object.py
<ide> def __rshift__(self: Array, other: Union[int, Array], /) -> Array:
<ide> res = self._array.__rshift__(other._array)
<ide> return self.__class__._new(res)
<ide>
<del> def __setitem__(self, key, value, /):
<add> def __setitem__(self, key: Union[int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array], value: Union[int, float, bool, Array], /) -> Array:
<ide> """
<ide> Performs the operation __setitem__.
<ide> """ | 1 |
Python | Python | add os-release support | af67cfcf8384204e6c8a098f34a4f4c3f0b59fc5 | <ide><path>glances/plugins/glances_system.py
<ide> def reset(self):
<ide> """Reset/init the stats."""
<ide> self.stats = {}
<ide>
<add> def _linux_os_release(self):
<add> """This function tries to determine the name of a Linux distribution.
<add>
<add> It checks for the /etc/os-release file. It takes the name from the
<add> 'NAME' field and the version from 'VERSION_ID'.
<add> An empty string is returned if the above values cannot be determined.
<add> """
<add> pretty_name = ''
<add> ashtray = {}
<add> keys = ['NAME', 'VERSION_ID']
<add> try:
<add> with open(os.path.join('/etc', 'os-release')) as f:
<add> for line in f:
<add> for key in keys:
<add> if line.startswith(key):
<add> ashtray[key] = line.strip().split('=')[1][1:-1]
<add> except OSError:
<add> return pretty_name
<add>
<add> if ashtray:
<add> if 'NAME' in ashtray:
<add> pretty_name = ashtray['NAME']
<add> if 'VERSION_ID' in ashtray:
<add> pretty_name += ' {0}'.format(ashtray['VERSION_ID'])
<add>
<add> return pretty_name
<add>
<ide> def update(self):
<ide> """Update the host/system info using the input method.
<ide>
<ide> def update(self):
<ide> self.stats['os_name'] = platform.system()
<ide> self.stats['hostname'] = platform.node()
<ide> self.stats['platform'] = platform.architecture()[0]
<del> is_archlinux = os.path.exists(os.path.join("/", "etc", "arch-release"))
<ide> if self.stats['os_name'] == "Linux":
<del> if is_archlinux:
<del> self.stats['linux_distro'] = "Arch Linux"
<add> linux_distro = platform.linux_distribution()
<add> if linux_distro[0] == '':
<add> self.stats['linux_distro'] = self._linux_os_release()
<ide> else:
<del> linux_distro = platform.linux_distribution()
<ide> self.stats['linux_distro'] = ' '.join(linux_distro[:2])
<ide> self.stats['os_version'] = platform.release()
<ide> elif self.stats['os_name'] == "FreeBSD":
<ide> def update(self):
<ide> else:
<ide> self.stats['os_version'] = ""
<ide> # Add human readable name
<del> self.stats['hr_name'] = self.stats['os_name']
<del> self.stats['hr_name'] += ' ' + self.stats['os_version']
<ide> if self.stats['os_name'] == "Linux":
<ide> self.stats['hr_name'] = self.stats['linux_distro']
<del> self.stats['hr_name'] += ' (' + self.stats['platform'] + ')'
<add> else:
<add> self.stats['hr_name'] = '{0} {1}'.format(self.stats['os_name'], self.stats['os_version'])
<add> self.stats['hr_name'] += ' ({0})'.format(self.stats['platform'])
<ide>
<ide> elif self.get_input() == 'snmp':
<ide> # Update stats using SNMP
<ide> def msg_curse(self, args=None):
<ide> msg = self.stats['hostname']
<ide> ret.append(self.curse_add_line(msg, "TITLE"))
<ide> # System info
<del> if self.stats['os_name'] == "Linux":
<add> if self.stats['os_name'] == "Linux" and self.stats['linux_distro']:
<ide> msg = ' ({0} {1} / {2} {3})'.format(self.stats['linux_distro'],
<ide> self.stats['platform'],
<ide> self.stats['os_name'], | 1 |
Javascript | Javascript | fix eslint errors | af52c4370509b2484aebe5cf0377a9f92469d77a | <ide><path>client/main.js
<ide> main.mapShareKey = 'map-shares';
<ide>
<ide> main.ga = window.ga || function() {};
<ide>
<del>main = (function(main) {
<add>main = (function(main, global) {
<add> const { Mousetrap } = global;
<ide>
<ide> // should be set before gitter script loads
<ide> ((window.gitter = {}).chat = {}).options = {
<ide> main = (function(main) {
<ide> });
<ide>
<ide> return main;
<del>}(main));
<add>}(main, window));
<ide>
<ide> var lastCompleted = typeof lastCompleted !== 'undefined' ?
<ide> lastCompleted :
<ide> $(document).ready(function() {
<ide> });
<ide>
<ide> // keyboard shortcuts: open map
<del> Mousetrap.bind('g m', function() {
<add> window.Mousetrap.bind('g m', function() {
<ide> var isCollapsed = $('.map-aside').hasClass('is-collapsed');
<ide>
<ide> if (isCollapsed) { | 1 |
Javascript | Javascript | add tests for finddomnode on fragment and text | 8e2d7f8d2705159ca354294018bb98db1e0f4a71 | <ide><path>src/renderers/dom/fiber/__tests__/ReactDOMFiber-test.js
<ide> describe('ReactDOMFiber', () => {
<ide>
<ide> expect(container.textContent).toEqual('10');
<ide> });
<add>
<add> it('finds the DOM Text node of a string child', () => {
<add> class Text extends React.Component {
<add> render() {
<add> return this.props.value;
<add> }
<add> }
<add>
<add> let instance = null;
<add> ReactDOM.render(
<add> <Text value="foo" ref={ref => instance = ref} />,
<add> container
<add> );
<add>
<add> const textNode = ReactDOM.findDOMNode(instance);
<add> expect(textNode).toBe(container.firstChild);
<add> expect(textNode.nodeType).toBe(3);
<add> expect(textNode.nodeValue).toBe('foo');
<add> });
<add>
<add> it('finds the first child when a component returns a fragment', () => {
<add> class Fragment extends React.Component {
<add> render() {
<add> return [
<add> <div />,
<add> <span />,
<add> ];
<add> }
<add> }
<add>
<add> let instance = null;
<add> ReactDOM.render(
<add> <Fragment ref={ref => instance = ref} />,
<add> container
<add> );
<add>
<add> expect(container.childNodes.length).toBe(2);
<add>
<add> const firstNode = ReactDOM.findDOMNode(instance);
<add> expect(firstNode).toBe(container.firstChild);
<add> expect(firstNode.tagName).toBe('DIV');
<add> });
<add>
<add> it('finds the first child even when fragment is nested', () => {
<add> class Wrapper extends React.Component {
<add> render() {
<add> return this.props.children;
<add> }
<add> }
<add>
<add> class Fragment extends React.Component {
<add> render() {
<add> return [
<add> <Wrapper><div /></Wrapper>,
<add> <span />,
<add> ];
<add> }
<add> }
<add>
<add> let instance = null;
<add> ReactDOM.render(
<add> <Fragment ref={ref => instance = ref} />,
<add> container
<add> );
<add>
<add> expect(container.childNodes.length).toBe(2);
<add>
<add> const firstNode = ReactDOM.findDOMNode(instance);
<add> expect(firstNode).toBe(container.firstChild);
<add> expect(firstNode.tagName).toBe('DIV');
<add> });
<add>
<add> it('finds the first child even when first child renders null', () => {
<add> class NullComponent extends React.Component {
<add> render() {
<add> return null;
<add> }
<add> }
<add>
<add> class Fragment extends React.Component {
<add> render() {
<add> return [
<add> <NullComponent />,
<add> <div />,
<add> <span />,
<add> ];
<add> }
<add> }
<add>
<add> let instance = null;
<add> ReactDOM.render(
<add> <Fragment ref={ref => instance = ref} />,
<add> container
<add> );
<add>
<add> expect(container.childNodes.length).toBe(2);
<add>
<add> const firstNode = ReactDOM.findDOMNode(instance);
<add> expect(firstNode).toBe(container.firstChild);
<add> expect(firstNode.tagName).toBe('DIV');
<add> });
<ide> }
<ide> }); | 1 |
PHP | PHP | fix bug in router | 44ef0d0e766d665a29c93fc516dd2f50b4ae4500 | <ide><path>src/Illuminate/Routing/Router.php
<ide> public function withoutFilters($callback)
<ide> {
<ide> $this->disableFilters();
<ide>
<del> call_user_func($callback0);
<add> call_user_func($callback);
<ide>
<ide> $this->enableFilters();
<ide> } | 1 |
PHP | PHP | add missing "use" statement | e6087ce9ddb58afee3afa5e6421f84103e3188ec | <ide><path>src/View/Exception/MissingTemplateException.php
<ide> namespace Cake\View\Exception;
<ide>
<ide> use Cake\Core\Exception\Exception;
<add>use Throwable;
<ide>
<ide> /**
<ide> * Used when a template file cannot be found. | 1 |
PHP | PHP | initialize empty array for `$values` | 0c024f0f225942e0a80953902dce4b0e91e77c27 | <ide><path>src/Illuminate/Support/Collection.php
<ide> public function sort(callable $callback = null)
<ide> */
<ide> public function sortBy($callback, $options = SORT_REGULAR, $descending = false)
<ide> {
<add> $values = [];
<ide> $results = [];
<ide>
<ide> $callback = $this->valueRetriever($callback); | 1 |
Javascript | Javascript | remove uuid from webglrendertarget | 01cae4ee609016d45e2842595502fa28331fd5d0 | <ide><path>src/renderers/WebGLRenderTarget.js
<ide> import { EventDispatcher } from '../core/EventDispatcher.js';
<ide> import { Texture } from '../textures/Texture.js';
<ide> import { LinearFilter } from '../constants.js';
<ide> import { Vector4 } from '../math/Vector4.js';
<del>import { _Math } from '../math/Math.js';
<ide>
<ide> /**
<ide> * @author szimek / https://github.com/szimek/
<ide> import { _Math } from '../math/Math.js';
<ide> */
<ide> function WebGLRenderTarget( width, height, options ) {
<ide>
<del> this.uuid = _Math.generateUUID();
<del>
<ide> this.width = width;
<ide> this.height = height;
<ide> | 1 |
Text | Text | add link to another article about react renderers | 71a60ddb16c413bd9a62f2a0c62694d57d473679 | <ide><path>packages/react-reconciler/README.md
<ide> var HostConfig = {
<ide> };
<ide> ```
<ide>
<del>**For an introduction to writing a very simple custom renderer, [check out this small guide](https://medium.com/@agent_hunt/hello-world-custom-react-renderer-9a95b7cd04bc).**
<add>**For an introduction to writing a very simple custom renderer, check out this article series:**
<add>
<add>* **[Building a simple custom renderer to DOM](https://medium.com/@agent_hunt/hello-world-custom-react-renderer-9a95b7cd04bc)**
<add>* **[Building a simple custom renderer to native](https://medium.com/@agent_hunt/introduction-to-react-native-renderers-aka-react-native-is-the-java-and-react-native-renderers-are-828a0022f433)**
<ide>
<ide> The full list of supported methods [can be found here](https://github.com/facebook/react/blob/master/packages/react-reconciler/src/forks/ReactFiberHostConfig.custom.js). For their signatures, we recommend looking at specific examples below.
<ide> | 1 |
Ruby | Ruby | add tap --shallow deprecation todo | 29d50f57b3d1799991d3d79a6f8932acf43c7878 | <ide><path>Library/Homebrew/cmd/tap.rb
<ide> def tap
<ide>
<ide> if args.shallow?
<ide> opoo "`brew tap --shallow` is now a no-op!"
<add> # TODO: (3.2) Uncomment the following line and remove the `opoo` above
<ide> # odeprecated "`brew tap --shallow`"
<ide> end
<ide> | 1 |
Text | Text | add redux-pack to asyncactions | c790db844e6931c35ff3e96517ee939d3a9f5b01 | <ide><path>docs/advanced/AsyncActions.md
<ide> store.dispatch(fetchPostsIfNeeded('reactjs')).then(() =>
<ide> - You can use [redux-promise](https://github.com/acdlite/redux-promise) or [redux-promise-middleware](https://github.com/pburtchaell/redux-promise-middleware) to dispatch Promises instead of functions.
<ide> - You can use [redux-observable](https://github.com/redux-observable/redux-observable) to dispatch Observables.
<ide> - You can use the [redux-saga](https://github.com/yelouafi/redux-saga/) middleware to build more complex asynchronous actions.
<add>- You can use the [redux-pack](https://github.com/lelandrichardson/redux-pack) middleware to dispatch promise-based asynchronous actions.
<ide> - You can even write a custom middleware to describe calls to your API, like the [real world example](../introduction/Examples.md#real-world) does.
<ide>
<ide> It is up to you to try a few options, choose a convention you like, and follow it, whether with, or without the middleware. | 1 |
Java | Java | add the missing license | 8cf79d73792b17982238a7ef3318b20291acb70e | <ide><path>rxjava-core/src/main/java/rx/operators/OperatorTimeoutBase.java
<add>/**
<add> * Copyright 2014 Netflix, Inc.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<ide> package rx.operators;
<ide>
<ide> import java.util.concurrent.TimeoutException; | 1 |
Text | Text | remove link to deleted tweet | 89104853174e62de8ebbca4881ea14a04399f4e2 | <ide><path>docs/faq/General.md
<ide> What to learn can be an overwhelming question for a JavaScript developer. It hel
<ide> - [Twitter: If you want to teach someone to use an abstraction...](https://twitter.com/acemarke/status/901329101088215044)
<ide> - [Twitter: it was never intended to be learned before...](https://twitter.com/dan_abramov/status/739961787295117312)
<ide> - [Twitter: Learning Redux before React?](https://twitter.com/dan_abramov/status/739962098030137344)
<del>- [Twitter: The first time I used React, people told me I needed Redux...](https://twitter.com/raquelxmoss/status/901576285020856320)
<ide> - [Twitter: This was my experience with Redux...](https://twitter.com/garetmckinley/status/901500556568645634)
<ide> - [Dev.to: When is it time to use Redux?](https://dev.to/dan_abramov/comment/1n2k)
<ide> | 1 |
Javascript | Javascript | expose the projectroots option | 93c56a0e902d61b5c255fe2de2d74f6796fd59e5 | <ide><path>packager/packager.js
<ide> var options = parseCommandLine([{
<ide> command: 'root',
<ide> type: 'string',
<ide> description: 'add another root(s) to be used by the packager in this project',
<add>}, {
<add> command: 'projectRoots',
<add> type: 'string',
<add> description: 'override the root(s) to be used by the packager',
<ide> }, {
<ide> command: 'assetRoots',
<ide> type: 'string', | 1 |
Python | Python | update known warnings for python 3.7 | 4bb1317c892c6d65557b3d998bd8d1bd971ba96b | <ide><path>dev/provider_packages/prepare_provider_packages.py
<ide> def summarise_total_vs_bad_and_warnings(total: int, bad: int, warns: List[warnin
<ide> console.print()
<ide> raise_error = True
<ide> if warns:
<add> if os.environ.get('GITHUB_ACTIONS'):
<add> # Ends group in GitHub Actions so that the errors are immediately visible in CI log
<add> console.print("::endgroup::")
<ide> console.print()
<ide> console.print("[red]Unknown warnings generated:[/]")
<ide> console.print()
<ide> def summarise_total_vs_bad_and_warnings(total: int, bad: int, warns: List[warnin
<ide> ),
<ide> (
<ide> "Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated since"
<del> " Python 3.3, and in 3.10 it will stop working",
<add> " Python 3.3,and in 3.9 it will stop working",
<ide> "apache_beam",
<ide> ),
<del> (
<del> "Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated since"
<del> " Python 3.3, and in 3.10 it will stop working",
<del> "dns",
<del> ),
<ide> (
<ide> 'pyarrow.HadoopFileSystem is deprecated as of 2.0.0, please use pyarrow.fs.HadoopFileSystem instead.',
<ide> "papermill", | 1 |
Javascript | Javascript | remove welcome link | db4bb351d4aa4e1daf01a77751b9659238915137 | <ide><path>client/src/pages/welcome.js
<ide> import { randomQuote } from '../utils/get-words';
<ide> import './welcome.css';
<ide>
<ide> const propTypes = {
<del> activedonations: PropTypes.number,
<add> activeDonations: PropTypes.number,
<ide> fetchState: PropTypes.shape({
<ide> pending: PropTypes.bool,
<ide> complete: PropTypes.bool,
<ide> function Welcome({
<ide> isDonating={isDonating}
<ide> />
<ide> <Spacer size={2} />
<del> <Row>
<del> <Col sm={8} smOffset={2} xs={12}>
<del> <a
<del> className='update-link'
<del> href='/n/7gR5pBM-K?refsource=userhome'
<del> target='_blank'
<del> >
<del> We're building a massive open dataset about new coders. Take the
<del> 2018 New Coder Survey. It only takes 5 minutes.
<del> </a>
<del> </Col>
<del> </Row>
<ide> <Spacer />
<ide> <Row className='quote-partial'>
<ide> <Col sm={10} smOffset={1} xs={12}> | 1 |
PHP | PHP | remove interface method and add import | 910fad8cb2934f2c231f806b8b398ba95ef38dfe | <ide><path>src/Illuminate/Bus/BatchRepository.php
<ide> public function delete(string $batchId);
<ide> * @return mixed
<ide> */
<ide> public function transaction(Closure $callback);
<del>
<del> /**
<del> * Prune all of the entries older than the given date.
<del> *
<del> * @param \DateTimeInterface $before
<del> * @return int
<del> */
<del> public function prune(\DateTimeInterface $before);
<ide> }
<ide><path>src/Illuminate/Bus/DatabaseBatchRepository.php
<ide>
<ide> use Carbon\CarbonImmutable;
<ide> use Closure;
<add>use DateTimeInterface;
<ide> use Illuminate\Database\Connection;
<ide> use Illuminate\Database\Query\Expression;
<ide> use Illuminate\Support\Str;
<ide> public function transaction(Closure $callback)
<ide> /**
<ide> * Prune all of the entries older than the given date.
<ide> *
<del> * @param \DateTimeInterface $before
<add> * @param DateTimeInterface $before
<ide> * @return int
<ide> */
<del> public function prune(\DateTimeInterface $before)
<add> public function prune(DateTimeInterface $before)
<ide> {
<ide> $query = $this->connection->table($this->table)
<add> ->whereNotNull('finished_at')
<ide> ->where('finished_at', '<', $before->getTimestamp());
<ide>
<ide> $totalDeleted = 0;
<ide><path>src/Illuminate/Queue/Console/FlushBatchCommand.php
<ide> class FlushBatchCommand extends Command
<ide> /**
<ide> * Execute the console command.
<ide> *
<del> * @return int|null
<add> * @return void
<ide> */
<ide> public function handle()
<ide> {
<del> $hours = $this->option('hours');
<add> $count = 0;
<ide>
<del> $before = Carbon::now()->subHours($hours);
<add> $repository = $this->laravel[BatchRepository::class];
<ide>
<del> $count = $this->laravel[BatchRepository::class]->prune($before);
<add> if (method_exists($repository, 'prune')) {
<add> $hours = $this->option('hours');
<ide>
<del> $this->info("{$count} entries deleted successfully.");
<add> $before = Carbon::now()->subHours($hours);
<add>
<add> $count = $repository->prune($before);
<add> }
<add>
<add> $this->info("{$count} entries deleted!");
<ide> }
<ide> }
<ide><path>src/Illuminate/Support/Testing/Fakes/BatchRepositoryFake.php
<ide>
<ide> use Carbon\CarbonImmutable;
<ide> use Closure;
<add>use DateTimeInterface;
<ide> use Illuminate\Bus\Batch;
<ide> use Illuminate\Bus\BatchRepository;
<ide> use Illuminate\Bus\PendingBatch;
<ide> public function transaction(Closure $callback)
<ide> /**
<ide> * Prune all of the entries older than the given date.
<ide> *
<del> * @param \DateTimeInterface $before
<add> * @param DateTimeInterface $before
<ide> * @return int
<ide> */
<del> public function prune(\DateTimeInterface $before)
<add> public function prune(DateTimeInterface $before)
<ide> {
<ide> return 0;
<ide> } | 4 |
PHP | PHP | add deprecation notice for old-fixtures | ead700e17ff12004f19b1db4479909a9a99e603b | <ide><path>src/TestSuite/Fixture/FixtureInjector.php
<ide> public function __construct(FixtureManager $manager)
<ide> public function startTestSuite(TestSuite $suite): void
<ide> {
<ide> if (empty($this->_first)) {
<add> deprecationWarning(
<add> 'You are using the listener based PHPUnit integration. ' .
<add> 'This fixture system is deprecated, and we recommend you ' .
<add> 'upgrade to the extension based PHPUnit integration. ' .
<add> 'See https://book.cakephp.org/4.x/en/appendixes/fixture-upgrade.html'
<add> );
<ide> $this->_first = $suite;
<ide> }
<ide> } | 1 |
Python | Python | fix pt-1.9.0 `add_` deprecation | d6ea91c96ac7188be3ea1e6d80b2e169d4ac8cf9 | <ide><path>src/transformers/optimization.py
<ide>
<ide> from .trainer_utils import SchedulerType
<ide> from .utils import logging
<add>from .utils.versions import require_version
<ide>
<ide>
<ide> logger = logging.get_logger(__name__)
<ide> def __init__(
<ide> weight_decay: float = 0.0,
<ide> correct_bias: bool = True,
<ide> ):
<add> require_version("torch>=1.5.0") # add_ with alpha
<ide> if lr < 0.0:
<ide> raise ValueError(f"Invalid learning rate: {lr} - should be >= 0.0")
<ide> if not 0.0 <= betas[0] < 1.0:
<ide> def step(self, closure: Callable = None):
<ide>
<ide> # Decay the first and second moment running average coefficient
<ide> # In-place operations to update the averages at the same time
<del> exp_avg.mul_(beta1).add_(grad, alpha=1.0 - beta1)
<add> exp_avg.mul_(beta1).add_(grad, alpha=(1.0 - beta1))
<ide> exp_avg_sq.mul_(beta2).addcmul_(grad, grad, value=1.0 - beta2)
<ide> denom = exp_avg_sq.sqrt().add_(group["eps"])
<ide>
<ide> def step(self, closure: Callable = None):
<ide> # of the weights to the loss with plain (non-momentum) SGD.
<ide> # Add weight decay at the end (fixed version)
<ide> if group["weight_decay"] > 0.0:
<del> p.data.add_(p.data, alpha=-group["lr"] * group["weight_decay"])
<add> p.data.add_(p.data, alpha=(-group["lr"] * group["weight_decay"]))
<ide>
<ide> return loss
<ide>
<ide> def __init__(
<ide> relative_step=True,
<ide> warmup_init=False,
<ide> ):
<add> require_version("torch>=1.5.0") # add_ with alpha
<ide> if lr is not None and relative_step:
<ide> raise ValueError("Cannot combine manual `lr` and `relative_step=True` options")
<ide> if warmup_init and not relative_step:
<ide> def step(self, closure=None):
<ide> exp_avg_sq_row = state["exp_avg_sq_row"]
<ide> exp_avg_sq_col = state["exp_avg_sq_col"]
<ide>
<del> exp_avg_sq_row.mul_(beta2t).add_(1.0 - beta2t, update.mean(dim=-1))
<del> exp_avg_sq_col.mul_(beta2t).add_(1.0 - beta2t, update.mean(dim=-2))
<add> exp_avg_sq_row.mul_(beta2t).add_(update.mean(dim=-1), alpha=(1.0 - beta2t))
<add> exp_avg_sq_col.mul_(beta2t).add_(update.mean(dim=-2), alpha=(1.0 - beta2t))
<ide>
<ide> # Approximation of exponential moving average of square of gradient
<ide> update = self._approx_sq_grad(exp_avg_sq_row, exp_avg_sq_col)
<ide> update.mul_(grad)
<ide> else:
<ide> exp_avg_sq = state["exp_avg_sq"]
<ide>
<del> exp_avg_sq.mul_(beta2t).add_(1.0 - beta2t, update)
<add> exp_avg_sq.mul_(beta2t).add_(update, alpha=(1.0 - beta2t))
<ide> update = exp_avg_sq.rsqrt().mul_(grad)
<ide>
<ide> update.div_((self._rms(update) / group["clip_threshold"]).clamp_(min=1.0))
<ide> update.mul_(lr)
<ide>
<ide> if use_first_moment:
<ide> exp_avg = state["exp_avg"]
<del> exp_avg.mul_(group["beta1"]).add_(1 - group["beta1"], update)
<add> exp_avg.mul_(group["beta1"]).add_(update, alpha=(1 - group["beta1"]))
<ide> update = exp_avg
<ide>
<ide> if group["weight_decay"] != 0:
<del> p_data_fp32.add_(-group["weight_decay"] * lr, p_data_fp32)
<add> p_data_fp32.add_(p_data_fp32, alpha=(-group["weight_decay"] * lr))
<ide>
<ide> p_data_fp32.add_(-update)
<ide> | 1 |
Text | Text | add some info to switch in c++ | f0b29bcb281f18d99b31df7679498baed774eaf4 | <ide><path>guide/english/cplusplus/switch-statements/index.md
<ide> switch(expression) {
<ide>
<ide> The following rules apply to a switch statement −
<ide>
<del>The expression used in a switch statement must have an integral or enumerated type, or be of a class type in which the class has a single conversion function to an integral or enumerated type.
<add>The expression used in a switch statement must have an integral or enumerated type(int,char,enum), or be of a class type in which the class has a single conversion function to an integral or enumerated type.
<ide>
<ide> You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.
<ide>
<ide> When a break statement is reached, the switch terminates, and the flow of contro
<ide>
<ide> Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached.
<ide>
<del>A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.
<add>A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case. The position of default block doesn't matter, it is automatically executed if no match is found.
<add>
<add>Two case labels cannot have the same value.
<add>
<ide>
<ide> Example:
<ide> ```C++ | 1 |
Ruby | Ruby | fix documentation typo | aa4fe9fb33d144cde2c79415367624ad0676d038 | <ide><path>actionpack/lib/action_view/helpers/asset_tag_helper.rb
<ide> module Helpers #:nodoc:
<ide> # "http://assets#{source.hash % 2 + 1}.example.com"
<ide> # }
<ide> # image_tag("rails.png")
<del> # # => <img alt="Rails" src="http://assets0.example.com/images/rails.png?1230601161" />
<add> # # => <img alt="Rails" src="http://assets1.example.com/images/rails.png?1230601161" />
<ide> # stylesheet_link_tag("application")
<del> # # => <link href="http://assets1.example.com/stylesheets/application.css?1232285206" media="screen" rel="stylesheet" type="text/css" />
<add> # # => <link href="http://assets2.example.com/stylesheets/application.css?1232285206" media="screen" rel="stylesheet" type="text/css" />
<ide> #
<ide> # The example above generates "http://assets1.example.com" and
<ide> # "http://assets2.example.com". This option is useful for example if | 1 |
Javascript | Javascript | use yarn for install/uninstall cli if available | 1c249e4804030b5691adf508751c369bf0036f1c | <ide><path>local-cli/install/install.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>'use strict';
<add>
<ide> const spawnSync = require('child_process').spawnSync;
<ide> const log = require('npmlog');
<add>const PackageManager = require('../util/PackageManager');
<ide> const spawnOpts = {
<ide> stdio: 'inherit',
<ide> stdin: 'inherit',
<ide> log.heading = 'rnpm-install';
<ide> function install(args, config) {
<ide> const name = args[0];
<ide>
<del> var res = spawnSync('npm', ['install', name, '--save'], spawnOpts);
<add> let res = PackageManager.add(name);
<ide>
<ide> if (res.status) {
<ide> process.exit(res.status);
<ide> }
<ide>
<del> res = spawnSync('rnpm', ['link', name], spawnOpts);
<add> res = spawnSync('react-native', ['link', name], spawnOpts);
<ide>
<ide> if (res.status) {
<ide> process.exit(res.status);
<ide> }
<ide>
<ide> log.info(`Module ${name} has been successfully installed & linked`);
<del>};
<add>}
<ide>
<ide> module.exports = {
<ide> func: install,
<ide><path>local-cli/install/uninstall.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>'use strict';
<add>
<ide> const spawnSync = require('child_process').spawnSync;
<ide> const log = require('npmlog');
<add>const PackageManager = require('../util/PackageManager');
<ide> const spawnOpts = {
<ide> stdio: 'inherit',
<ide> stdin: 'inherit',
<ide> log.heading = 'rnpm-install';
<ide> function uninstall(args, config) {
<ide> const name = args[0];
<ide>
<del> var res = spawnSync('rnpm', ['unlink', name], spawnOpts);
<add> var res = spawnSync('react-native', ['unlink', name], spawnOpts);
<ide>
<ide> if (res.status) {
<ide> process.exit(res.status);
<ide> }
<ide>
<del> res = spawnSync('npm', ['uninstall', name], spawnOpts);
<add> res = PackageManager.remove(name);
<ide>
<ide> if (res.status) {
<ide> process.exit(res.status);
<ide> }
<ide>
<ide> log.info(`Module ${name} has been successfully uninstalled & unlinked`);
<del>};
<add>}
<ide>
<ide> module.exports = {
<ide> func: uninstall,
<ide><path>local-cli/link/link.js
<ide> function link(args, config) {
<ide> return Promise.reject(err);
<ide> }
<ide>
<del> const packageName = args[0];
<add> let packageName = args[0];
<add> // Check if install package by specific version (eg. package@latest)
<add> if (packageName !== undefined) {
<add> packageName = packageName.split('@')[0];
<add> }
<ide>
<ide> const dependencies = getDependencyConfig(
<ide> config,
<ide><path>local-cli/util/PackageManager.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>'use strict';
<add>
<add>const spawnSync = require('child_process').spawnSync;
<add>const yarn = require('../util/yarn');
<add>const spawnOpts = {
<add> stdio: 'inherit',
<add> stdin: 'inherit',
<add>};
<add>
<add>const projectDir = process.cwd();
<add>const isYarnAvailable =
<add> yarn.getYarnVersionIfAvailable() &&
<add> yarn.isGlobalCliUsingYarn(projectDir);
<add>
<add>/**
<add> * Execute npm or yarn command
<add> *
<add> * @param {String} yarnCommand Yarn command to be executed eg. yarn add package
<add> * @param {String} npmCommand Npm command to be executed eg. npm install package
<add> * @return {object} spawnSync's result object
<add> */
<add>function callYarnOrNpm(yarnCommand, npmCommand) {
<add> let command;
<add>
<add> if (isYarnAvailable) {
<add> command = yarnCommand;
<add> } else {
<add> command = npmCommand;
<add> }
<add>
<add> const args = command.split(' ');
<add> const cmd = args.shift();
<add>
<add> const res = spawnSync(cmd, args, spawnOpts);
<add>
<add> return res;
<add>}
<add>
<add>/**
<add> * Install package into project using npm or yarn if available
<add> * @param {[type]} packageName Package to be installed
<add> * @return {[type]} spawnSync's result object
<add> */
<add>function add(packageName) {
<add> return callYarnOrNpm(
<add> `yarn add ${packageName}`,
<add> `npm install ${packageName} --save`
<add> );
<add>}
<add>
<add>/**
<add> * Uninstall package from project using npm or yarn if available
<add> * @param {[type]} packageName Package to be uninstalled
<add> * @return {Object} spawnSync's result object
<add> */
<add>function remove(packageName) {
<add> return callYarnOrNpm(
<add> `yarn remove ${packageName}`,
<add> `npm uninstall --save ${packageName}`
<add> );
<add>}
<add>
<add>module.exports = {
<add> add: add,
<add> remove: remove,
<add>}; | 4 |
Javascript | Javascript | shuffle v8_prof_polyfill.js for unit testing | 09d22ddab5eded7790b68059d91186117c43f3b7 | <ide><path>lib/internal/v8_prof_polyfill.js
<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>module.exports = { versionCheck };
<add>
<add>// Don't execute when required directly instead of being eval'd from
<add>// lib/internal/v8_prof_processor.js. This way we can test functions
<add>// from this file in isolation.
<add>if (module.id === 'internal/v8_prof_polyfill') return;
<add>
<ide> // Node polyfill
<ide> const fs = require('fs');
<ide> const cp = require('child_process');
<ide> const fd = fs.openSync(logFile, 'r');
<ide> const buf = Buffer.allocUnsafe(4096);
<ide> const dec = new (require('string_decoder').StringDecoder)('utf-8');
<ide> var line = '';
<del>versionCheck();
<add>
<add>{
<add> const message = versionCheck(peekline(), process.versions.v8);
<add> if (message) console.log(message);
<add>}
<add>
<add>function peekline() {
<add> const s = readline();
<add> line = s + '\n' + line;
<add> return s;
<add>}
<add>
<ide> function readline() {
<ide> while (true) {
<ide> const lineBreak = line.indexOf('\n');
<ide> function readline() {
<ide> }
<ide> }
<ide>
<del>function versionCheck() {
<add>function versionCheck(firstLine, expected) {
<ide> // v8-version looks like
<ide> // "v8-version,$major,$minor,$build,$patch[,$embedder],$candidate"
<ide> // whereas process.versions.v8 is either "$major.$minor.$build-$embedder" or
<ide> // "$major.$minor.$build.$patch-$embedder".
<del> var firstLine = readline();
<del> line = firstLine + '\n' + line;
<ide> firstLine = firstLine.split(',');
<del> const curVer = process.versions.v8.split(/[.\-]/);
<add> const curVer = expected.split(/[.\-]/);
<ide> if (firstLine.length !== 6 && firstLine.length !== 7 ||
<ide> firstLine[0] !== 'v8-version') {
<del> console.log('Unable to read v8-version from log file.');
<del> return;
<add> return 'Unable to read v8-version from log file.';
<ide> }
<ide> // Compare major, minor and build; ignore the patch and candidate fields.
<del> for (var i = 0; i < 3; i++) {
<del> if (curVer[i] !== firstLine[i + 1]) {
<del> console.log('Testing v8 version different from logging version');
<del> return;
<del> }
<del> }
<add> for (var i = 0; i < 3; i++)
<add> if (curVer[i] !== firstLine[i + 1])
<add> return 'Testing v8 version different from logging version';
<ide> }
<ide>
<ide> function macCppfiltNm(out) { | 1 |
Text | Text | add 16 and 17 to previous versions | a96549af4fc6b5093c4c58eecd59ac823f290330 | <ide><path>BUILDING.md
<ide> Supported platforms and toolchains change with each major version of Node.js.
<ide> This document is only valid for the current major version of Node.js.
<ide> Consult previous versions of this document for older versions of Node.js:
<ide>
<add>* [Node.js 17](https://github.com/nodejs/node/blob/v17.x/BUILDING.md)
<add>* [Node.js 16](https://github.com/nodejs/node/blob/v16.x/BUILDING.md)
<ide> * [Node.js 14](https://github.com/nodejs/node/blob/v14.x/BUILDING.md)
<ide> * [Node.js 12](https://github.com/nodejs/node/blob/v12.x/BUILDING.md)
<del>* [Node.js 10](https://github.com/nodejs/node/blob/v10.x/BUILDING.md)
<ide>
<ide> ## Building Node.js on supported platforms
<ide> | 1 |
Go | Go | fix wrt selinux | d78e885326213e8ef89919c3cc6d16e712e852a8 | <ide><path>pkg/mount/mounter_linux_test.go
<ide> import (
<ide> "os"
<ide> "strings"
<ide> "testing"
<del>
<del> selinux "github.com/opencontainers/selinux/go-selinux"
<ide> )
<ide>
<ide> func TestMount(t *testing.T) {
<ide> func TestMount(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide> defer ensureUnmount(t, target)
<del> expectedVFS := tc.expectedVFS
<del> if selinux.GetEnabled() && expectedVFS != "" {
<del> expectedVFS = expectedVFS + ",seclabel"
<del> }
<del> validateMount(t, target, tc.expectedOpts, tc.expectedOptional, expectedVFS)
<add> validateMount(t, target, tc.expectedOpts, tc.expectedOptional, tc.expectedVFS)
<ide> })
<ide> }
<ide> }
<ide> func validateMount(t *testing.T, mnt string, opts, optional, vfs string) {
<ide> for _, opt := range strings.Split(mi.Opts, ",") {
<ide> opt = clean(opt)
<ide> if !has(wantedOpts, opt) && !has(pOpts, opt) {
<del> t.Errorf("unexpected mount option %q expected %q", opt, opts)
<add> t.Errorf("unexpected mount option %q, expected %q", opt, opts)
<ide> }
<ide> delete(wantedOpts, opt)
<ide> }
<ide> }
<ide> for opt := range wantedOpts {
<del> t.Errorf("missing mount option %q found %q", opt, mi.Opts)
<add> t.Errorf("missing mount option %q, found %q", opt, mi.Opts)
<ide> }
<ide>
<ide> // Validate Optional
<ide> if mi.Optional != "" {
<ide> for _, field := range strings.Split(mi.Optional, ",") {
<ide> field = clean(field)
<ide> if !has(wantedOptional, field) && !has(pOptional, field) {
<del> t.Errorf("unexpected optional failed %q expected %q", field, optional)
<add> t.Errorf("unexpected optional field %q, expected %q", field, optional)
<ide> }
<ide> delete(wantedOptional, field)
<ide> }
<ide> }
<ide> for field := range wantedOptional {
<del> t.Errorf("missing optional field %q found %q", field, mi.Optional)
<add> t.Errorf("missing optional field %q, found %q", field, mi.Optional)
<ide> }
<ide>
<ide> // Validate VFS if set
<ide> if vfs != "" {
<ide> if mi.VfsOpts != "" {
<ide> for _, opt := range strings.Split(mi.VfsOpts, ",") {
<ide> opt = clean(opt)
<del> if !has(wantedVFS, opt) {
<del> t.Errorf("unexpected mount option %q expected %q", opt, vfs)
<add> if !has(wantedVFS, opt) && opt != "seclabel" { // can be added by selinux
<add> t.Errorf("unexpected vfs option %q, expected %q", opt, vfs)
<ide> }
<ide> delete(wantedVFS, opt)
<ide> }
<ide> }
<ide> for opt := range wantedVFS {
<del> t.Errorf("missing mount option %q found %q", opt, mi.VfsOpts)
<add> t.Errorf("missing vfs option %q, found %q", opt, mi.VfsOpts)
<ide> }
<ide> }
<ide> | 1 |
Javascript | Javascript | terminate statement in vector3 | 58b05d3ec1e862c17e3aa80d9bae7861fa73eb21 | <ide><path>src/math/Vector3.js
<ide> Vector3.prototype = {
<ide> if ( typeof m === 'number' ) {
<ide>
<ide> console.warn( 'THREE.Vector3: setFromMatrixColumn now expects ( matrix, index ).' );
<del> var temp = m
<add> var temp = m;
<ide> m = index;
<ide> index = temp;
<ide> | 1 |
Mixed | Ruby | use a bind param for `limit` and `offset` | 574f255629a45cd67babcfb9bb8e163e091a53b8 | <ide><path>activemodel/lib/active_model/type/value.rb
<ide> def ==(other)
<ide> scale == other.scale &&
<ide> limit == other.limit
<ide> end
<add> alias eql? ==
<add>
<add> def hash
<add> [self.class, precision, scale, limit].hash
<add> end
<ide>
<ide> def assert_valid_value(*)
<ide> end
<ide><path>activerecord/CHANGELOG.md
<add>* Use bind params for `limit` and `offset`. This will generate significantly
<add> fewer prepared statements for common tasks like pagination. To support this
<add> change, passing a string containing a comma to `limit` has been deprecated,
<add> and passing an Arel node to `limit` is no longer supported.
<add>
<add> Fixes #22250
<add>
<add> *Sean Griffin*
<add>
<ide> * Introduce after_{create,update,delete}_commit callbacks.
<ide>
<ide> Before:
<ide><path>activerecord/lib/active_record/relation/query_methods.rb
<ide> def #{name}_clause=(value) # def where_clause=(value)
<ide> end
<ide>
<ide> def bound_attributes
<del> from_clause.binds + arel.bind_values + where_clause.binds + having_clause.binds
<add> result = from_clause.binds + arel.bind_values + where_clause.binds + having_clause.binds
<add> if limit_value && !string_containing_comma?(limit_value)
<add> result << Attribute.with_cast_value(
<add> "LIMIT".freeze,
<add> connection.sanitize_limit(limit_value),
<add> Type::Value.new,
<add> )
<add> end
<add> if offset_value
<add> result << Attribute.with_cast_value(
<add> "OFFSET".freeze,
<add> offset_value.to_i,
<add> Type::Value.new,
<add> )
<add> end
<add> result
<ide> end
<ide>
<ide> def create_with_value # :nodoc:
<ide> def limit(value)
<ide> end
<ide>
<ide> def limit!(value) # :nodoc:
<del> if ::String === value && value.include?(",")
<add> if string_containing_comma?(value)
<add> # Remove `string_containing_comma?` when removing this deprecation
<ide> ActiveSupport::Deprecation.warn(<<-WARNING)
<ide> Passing a string to limit in the form "1,2" is deprecated and will be
<ide> removed in Rails 5.1. Please call `offset` explicitly instead.
<ide> def build_arel
<ide>
<ide> arel.where(where_clause.ast) unless where_clause.empty?
<ide> arel.having(having_clause.ast) unless having_clause.empty?
<del> arel.take(connection.sanitize_limit(limit_value)) if limit_value
<del> arel.skip(offset_value.to_i) if offset_value
<add> if limit_value
<add> if string_containing_comma?(limit_value)
<add> arel.take(connection.sanitize_limit(limit_value))
<add> else
<add> arel.take(Arel::Nodes::BindParam.new)
<add> end
<add> end
<add> arel.skip(Arel::Nodes::BindParam.new) if offset_value
<ide> arel.group(*arel_columns(group_values.uniq.reject(&:blank?))) unless group_values.empty?
<ide>
<ide> build_order(arel)
<ide> def where_clause_factory
<ide> def new_from_clause
<ide> Relation::FromClause.empty
<ide> end
<add>
<add> def string_containing_comma?(value)
<add> ::String === value && value.include?(",")
<add> end
<ide> end
<ide> end
<ide><path>activerecord/test/cases/base_test.rb
<ide> def test_limit_should_sanitize_sql_injection_for_limit_with_commas
<ide> end
<ide> end
<ide>
<del> unless current_adapter?(:MysqlAdapter, :Mysql2Adapter)
<del> def test_limit_should_allow_sql_literal
<del> assert_equal 1, Topic.limit(Arel.sql('2-1')).to_a.length
<del> end
<del> end
<del>
<ide> def test_select_symbol
<ide> topic_ids = Topic.select(:id).map(&:id).sort
<ide> assert_equal Topic.pluck(:id).sort, topic_ids
<ide><path>activerecord/test/cases/finder_test.rb
<ide> def test_model_class_responds_to_last_bang
<ide> end
<ide>
<ide> def test_take_and_first_and_last_with_integer_should_use_sql_limit
<del> assert_sql(/LIMIT 3|ROWNUM <= 3/) { Topic.take(3).entries }
<del> assert_sql(/LIMIT 2|ROWNUM <= 2/) { Topic.first(2).entries }
<del> assert_sql(/LIMIT 5|ROWNUM <= 5/) { Topic.last(5).entries }
<add> assert_sql(/LIMIT|ROWNUM <=/) { Topic.take(3).entries }
<add> assert_sql(/LIMIT|ROWNUM <=/) { Topic.first(2).entries }
<add> assert_sql(/LIMIT|ROWNUM <=/) { Topic.last(5).entries }
<ide> end
<ide>
<ide> def test_last_with_integer_and_order_should_keep_the_order | 5 |
PHP | PHP | use container contract | 84cfbb7ea0d5d5e774ef4a7029d3e5932601eb0a | <ide><path>src/Illuminate/Validation/Factory.php
<ide> <?php namespace Illuminate\Validation;
<ide>
<ide> use Closure;
<del>use Illuminate\Container\Container;
<add>use Illuminate\Contracts\Container\Container;
<ide> use Symfony\Component\Translation\TranslatorInterface;
<ide> use Illuminate\Contracts\Validation\Factory as FactoryContract;
<ide>
<ide> class Factory implements FactoryContract {
<ide> /**
<ide> * The IoC container instance.
<ide> *
<del> * @var \Illuminate\Container\Container
<add> * @var \Illuminate\Contracts\Container\Container
<ide> */
<ide> protected $container;
<ide>
<ide> class Factory implements FactoryContract {
<ide> * Create a new Validator factory instance.
<ide> *
<ide> * @param \Symfony\Component\Translation\TranslatorInterface $translator
<del> * @param \Illuminate\Container\Container $container
<add> * @param \Illuminate\Contracts\Container\Container $container
<ide> * @return void
<ide> */
<ide> public function __construct(TranslatorInterface $translator, Container $container = null) | 1 |
Ruby | Ruby | change logic to handle renames | fa8b702c0d1d910ea8ee39f61a31bb1bee66aeef | <ide><path>Library/Homebrew/cmd/uninstall.rb
<ide> require "keg"
<ide> require "formula"
<add>require "migrator"
<ide>
<ide> module Homebrew
<ide> def uninstall
<ide> raise KegUnspecifiedError if ARGV.named.empty?
<ide>
<add> # Find symlinks that can point to keg.rack
<add> links = HOMEBREW_CELLAR.subdirs.select(&:symlink?)
<add>
<ide> if !ARGV.force?
<ide> ARGV.kegs.each do |keg|
<ide> keg.lock do
<ide> puts "Uninstalling #{keg}... (#{keg.abv})"
<add>
<add> old_cellars = []
<add> # Remove every symlink that links to keg, because it can
<add> # be left by migrator
<add> links.each do |link|
<add> old_opt = HOMEBREW_PREFIX/"opt/#{link.basename}"
<add> if link.exist? && link.realpath == keg.rack.realpath
<add> old_cellars << link
<add> end
<add>
<add> if old_opt.symlink? && old_opt.realpath.to_s == keg.to_s
<add> old_opt.unlink
<add> old_opt.parent.rmdir_if_possible
<add> end
<add> end
<add>
<ide> keg.unlink
<ide> keg.uninstall
<ide> rack = keg.rack
<ide> rm_pin rack
<add>
<ide> if rack.directory?
<ide> versions = rack.subdirs.map(&:basename)
<ide> verb = versions.length == 1 ? "is" : "are"
<ide> puts "#{keg.name} #{versions.join(", ")} #{verb} still installed."
<ide> puts "Remove them all with `brew uninstall --force #{keg.name}`."
<add> else
<add> # If we delete Cellar/newname, then Cellar/oldname symlink
<add> # can become broken and we have to remove it.
<add> old_cellars.each(&:unlink)
<ide> end
<ide> end
<ide> end
<ide> else
<ide> ARGV.named.each do |name|
<del> name = Formulary.canonical_name(name)
<del> rack = HOMEBREW_CELLAR/name
<add> rack = Formulary.to_rack(name)
<add> name = rack.basename
<add>
<add> links.each do |link|
<add> old_opt = HOMEBREW_PREFIX/"opt/#{link.basename}"
<add> if old_opt.symlink? && old_opt.exist? \
<add> && old_opt.realpath.parent == rack.realpath
<add> old_opt.unlink
<add> old_opt.parent.rmdir_if_possible
<add> end
<add>
<add> lnk.unlink if lnk.exist? && lnk.realpath == rack.realpath
<add> end
<ide>
<ide> if rack.directory?
<ide> puts "Uninstalling #{name}... (#{rack.abv})" | 1 |
Javascript | Javascript | clarify the usage of 'else' | dc9717c805023d23e3a449ef9eedda045c91d532 | <ide><path>lib/child_process.js
<ide> exports.fork = function(modulePath /*, args, options*/) {
<ide> if (pos < arguments.length && arguments[pos] != null) {
<ide> if (typeof arguments[pos] !== 'object') {
<ide> throw new TypeError('Incorrect value of args option');
<del> } else {
<del> options = util._extend({}, arguments[pos++]);
<ide> }
<add>
<add> options = util._extend({}, arguments[pos++]);
<ide> }
<ide>
<ide> // Prepare arguments for fork:
<ide> function execFileSync(/*command, args, options*/) {
<ide>
<ide> if (err)
<ide> throw err;
<del> else
<del> return ret.stdout;
<add>
<add> return ret.stdout;
<ide> }
<ide> exports.execFileSync = execFileSync;
<ide>
<ide> function execSync(command /*, options*/) {
<ide>
<ide> if (err)
<ide> throw err;
<del> else
<del> return ret.stdout;
<add>
<add> return ret.stdout;
<ide> }
<ide> exports.execSync = execSync;
<ide> | 1 |
Ruby | Ruby | verify direct upload checksums | 52eed68e398195e536b99181f644232621f938b3 | <ide><path>app/models/active_storage/blob.rb
<ide> def url(expires_in: 5.minutes, disposition: :inline)
<ide> end
<ide>
<ide> def url_for_direct_upload(expires_in: 5.minutes)
<del> service.url_for_direct_upload key, expires_in: expires_in, content_type: content_type, content_length: byte_size
<add> service.url_for_direct_upload key, expires_in: expires_in, content_type: content_type, content_length: byte_size, checksum: checksum
<ide> end
<ide>
<ide>
<ide><path>lib/active_storage/service.rb
<ide> def url(key, expires_in:, disposition:, filename:, content_type:)
<ide> raise NotImplementedError
<ide> end
<ide>
<del> def url_for_direct_upload(key, expires_in:, content_type:, content_length:)
<add> def url_for_direct_upload(key, expires_in:, content_type:, content_length:, checksum:)
<ide> raise NotImplementedError
<ide> end
<ide>
<ide><path>lib/active_storage/service/gcs_service.rb
<ide> def exist?(key)
<ide>
<ide> def url(key, expires_in:, disposition:, filename:, content_type:)
<ide> instrument :url, key do |payload|
<del> generated_url = file_for(key).signed_url expires: expires_in, query: {
<add> generated_url = file_for(key).signed_url expires: expires_in, query: {
<ide> "response-content-disposition" => "#{disposition}; filename=\"#{filename}\"",
<ide> "response-content-type" => content_type
<ide> }
<ide> def url(key, expires_in:, disposition:, filename:, content_type:)
<ide> end
<ide> end
<ide>
<del> def url_for_direct_upload(key, expires_in:, content_type:, content_length:)
<add> def url_for_direct_upload(key, expires_in:, content_type:, content_length:, checksum:)
<ide> instrument :url, key do |payload|
<ide> generated_url = bucket.signed_url key, method: "PUT", expires: expires_in,
<del> content_type: content_type
<add> content_type: content_type, content_md5: checksum
<ide>
<ide> payload[:url] = generated_url
<ide>
<ide><path>lib/active_storage/service/s3_service.rb
<ide> def url(key, expires_in:, disposition:, filename:, content_type:)
<ide> end
<ide> end
<ide>
<del> def url_for_direct_upload(key, expires_in:, content_type:, content_length:)
<add> def url_for_direct_upload(key, expires_in:, content_type:, content_length:, checksum:)
<ide> instrument :url, key do |payload|
<ide> generated_url = object_for(key).presigned_url :put, expires_in: expires_in,
<del> content_type: content_type, content_length: content_length
<add> content_type: content_type, content_length: content_length, content_md5: checksum
<ide>
<ide> payload[:url] = generated_url
<ide>
<ide><path>test/service/gcs_service_test.rb
<ide> class ActiveStorage::Service::GCSServiceTest < ActiveSupport::TestCase
<ide>
<ide> test "direct upload" do
<ide> begin
<del> key = SecureRandom.base58(24)
<del> data = "Something else entirely!"
<del> direct_upload_url = @service.url_for_direct_upload(key, expires_in: 5.minutes, content_type: "text/plain", content_length: data.size)
<add> key = SecureRandom.base58(24)
<add> data = "Something else entirely!"
<add> checksum = Digest::MD5.base64digest(data)
<add> url = @service.url_for_direct_upload(key, expires_in: 5.minutes, content_type: "text/plain", content_length: data.size, checksum: checksum)
<ide>
<ide> HTTParty.put(
<del> direct_upload_url,
<add> url,
<ide> body: data,
<del> headers: { "Content-Type" => "text/plain" },
<add> headers: { "Content-Type" => "text/plain", "Content-MD5" => checksum },
<ide> debug_output: STDOUT
<ide> )
<ide>
<ide><path>test/service/s3_service_test.rb
<ide> class ActiveStorage::Service::S3ServiceTest < ActiveSupport::TestCase
<ide>
<ide> test "direct upload" do
<ide> begin
<del> key = SecureRandom.base58(24)
<del> data = "Something else entirely!"
<del> url = @service.url_for_direct_upload(key, expires_in: 5.minutes, content_type: "text/plain", content_length: data.size)
<add> key = SecureRandom.base58(24)
<add> data = "Something else entirely!"
<add> checksum = Digest::MD5.base64digest(data)
<add> url = @service.url_for_direct_upload(key, expires_in: 5.minutes, content_type: "text/plain", content_length: data.size, checksum: checksum)
<ide>
<ide> HTTParty.put(
<ide> url,
<ide> body: data,
<del> headers: { "Content-Type" => "text/plain" },
<add> headers: { "Content-Type" => "text/plain", "Content-MD5" => checksum },
<ide> debug_output: STDOUT
<ide> )
<ide> | 6 |
Javascript | Javascript | report actual error code on failure | d08334a489cbd29e4876a0031603ab8b5fef6f89 | <ide><path>test/parallel/test-dgram-error-message-address.js
<ide> socket_ipv6.on('listening', common.mustNotCall());
<ide> socket_ipv6.on('error', common.mustCall(function(e) {
<ide> // EAFNOSUPPORT or EPROTONOSUPPORT means IPv6 is disabled on this system.
<ide> const allowed = ['EADDRNOTAVAIL', 'EAFNOSUPPORT', 'EPROTONOSUPPORT'];
<del> assert(allowed.includes(e.code));
<add> assert(allowed.includes(e.code), `'${e.code}' was not one of ${allowed}.`);
<ide> assert.strictEqual(e.port, undefined);
<ide> assert.strictEqual(e.message, `bind ${e.code} 111::1`);
<ide> assert.strictEqual(e.address, '111::1'); | 1 |
PHP | PHP | sortreplacements function | 7374ad508917663aee6235f0267f3a58cb7b2790 | <ide><path>src/Illuminate/Support/Collection.php
<ide> public function sortBy($callback, $options = SORT_REGULAR, $descending = false)
<ide> // and grab the corresponding values for the sorted keys from this array.
<ide> foreach ($this->items as $key => $value)
<ide> {
<del> $results[$key] = $callback($value);
<add> $results[$key] = $callback($value, $key);
<ide> }
<ide>
<ide> $descending ? arsort($results, $options)
<ide><path>src/Illuminate/Translation/Translator.php
<ide> protected function makeReplacements($line, array $replace)
<ide> */
<ide> protected function sortReplacements(array $replace)
<ide> {
<del> return (new Collection($replace))->sortBy(function($r)
<add> return (new Collection($replace))->sortBy(function($value, $key)
<ide> {
<del> return mb_strlen($r) * -1;
<add> return mb_strlen($key) * -1;
<ide> });
<ide> }
<ide>
<ide><path>tests/Translation/TranslationTranslatorTest.php
<ide> public function testGetMethodProperlyLoadsAndRetrievesItemWithLongestReplacement
<ide> {
<ide> $t = $this->getMock('Illuminate\Translation\Translator', null, array($this->getLoader(), 'en'));
<ide> $t->getLoader()->shouldReceive('load')->once()->with('en', 'bar', 'foo')->andReturn(array('foo' => 'foo', 'baz' => 'breeze :foo :foobar'));
<del> $this->assertEquals('breeze bar taylor', $t->get('foo::bar.baz', array('foo' => 'bar', 'foobar' => 'taylor'), 'en'));
<add> $this->assertEquals('breeze foo bar baz taylor', $t->get('foo::bar.baz', array('foo' => 'foo bar baz', 'foobar' => 'taylor'), 'en'));
<ide> $this->assertEquals('foo', $t->get('foo::bar.foo'));
<ide> }
<ide> | 3 |
Python | Python | remove noseclasses from user accessible modules | 159326f4ae62e5121142a76b79e20a226322ce77 | <ide><path>numpy/testing/noseclasses.py
<del>"""
<del>Back compatibility noseclasses module. It will import the appropriate
<del>set of tools
<del>
<del>"""
<del>from .nose_tools.noseclasses import * | 1 |
Ruby | Ruby | prefer bin/rails for the credentials command | 3119672411f9e68f9474c7176f2b74d978d5eed2 | <ide><path>railties/lib/rails/commands/credentials/credentials_command.rb
<ide> def change_credentials_in_system_editor
<ide>
<ide> def missing_credentials_message
<ide> if credentials.key.nil?
<del> "Missing '#{key_path}' to decrypt credentials. See `rails credentials:help`"
<add> "Missing '#{key_path}' to decrypt credentials. See `bin/rails credentials:help`"
<ide> else
<del> "File '#{content_path}' does not exist. Use `rails credentials:edit` to change that."
<add> "File '#{content_path}' does not exist. Use `bin/rails credentials:edit` to change that."
<ide> end
<ide> end
<ide>
<del>
<ide> def content_path
<ide> @content_path ||= options[:environment] ? "config/credentials/#{options[:environment]}.yml.enc" : "config/credentials.yml.enc"
<ide> end | 1 |
Text | Text | add the cake logo to the readme | aa0785be42d87080c8db8e44cedd058e6d94750d | <ide><path>README.md
<del># CakePHP Framework
<del>
<del>[](LICENSE.txt)
<del>[](https://travis-ci.org/cakephp/cakephp)
<del>[](https://codecov.io/github/cakephp/cakephp)
<del>[](https://squizlabs.github.io/PHP_CodeSniffer/analysis/cakephp/cakephp/)
<del>[](https://packagist.org/packages/cakephp/cakephp)
<del>[](https://packagist.org/packages/cakephp/cakephp)
<add><p align="center">
<add> <a href="https://cakephp.org/" target="_blank" >
<add> <img alt="CakePHP" src="https://cakephp.org/v2/img/logos/CakePHP_Logo.svg" width="400" />
<add> </a>
<add></p>
<add><p align="center">
<add> <a href="LICENSE.txt" target="_blank">
<add> <img alt="Software License" src="https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square">
<add> </a>
<add> <a href="https://travis-ci.org/cakephp/cakephp" target="_blank">
<add> <img alt="Build Status" src="https://img.shields.io/travis/cakephp/cakephp/master.svg?style=flat-square">
<add> </a>
<add> <a href="https://codecov.io/github/cakephp/cakephp" target="_blank">
<add> <img alt="Coverage Status" src="https://img.shields.io/codecov/c/github/cakephp/cakephp.svg?style=flat-square">
<add> </a>
<add> <a href="https://squizlabs.github.io/PHP_CodeSniffer/analysis/cakephp/cakephp/" target="_blank">
<add> <img alt="Code Consistency" src="https://squizlabs.github.io/PHP_CodeSniffer/analysis/cakephp/cakephp/grade.svg">
<add> </a>
<add> <a href="https://packagist.org/packages/cakephp/cakephp" target="_blank">
<add> <img alt="Total Downloads" src="https://img.shields.io/packagist/dt/cakephp/cakephp.svg?style=flat-square">
<add> </a>
<add> <a href="https://packagist.org/packages/cakephp/cakephp" target="_blank">
<add> <img alt="Latest Stable Version" src="https://img.shields.io/packagist/v/cakephp/cakephp.svg?style=flat-square&label=stable">
<add> </a>
<add></p>
<ide>
<ide> [CakePHP](https://cakephp.org) is a rapid development framework for PHP which
<ide> uses commonly known design patterns like Associative Data | 1 |
Python | Python | keep sentence regarding depth_multiplier | 9badb805177dfb041fda173e64b1cf2bc985abb7 | <ide><path>keras/layers/convolutional.py
<ide> class DepthwiseConv2D(Conv2D):
<ide> depth_multiplier: The number of output channels for the depthwise kernels.
<ide> It can be understood as the amount of filters that are applied to
<ide> each input channel.
<add> The total number of depthwise convolution output
<add> channels will be equal to `filters_in * depth_multiplier`.
<ide> data_format: A string,
<ide> one of `channels_last` (default) or `channels_first`.
<ide> The ordering of the dimensions in the inputs. | 1 |
PHP | PHP | use exception chaining | 0c342051b6de18c498968f71c6ee7517ce41b814 | <ide><path>src/Cache/Cache.php
<ide> protected static function _buildEngine($name)
<ide>
<ide> if ($config['fallback'] === $name) {
<ide> throw new InvalidArgumentException(
<del> sprintf('"%s" cache configuration cannot fallback to itself.', $name)
<add> sprintf('"%s" cache configuration cannot fallback to itself.', $name), null, $e
<ide> );
<ide> }
<ide>
<ide><path>src/Controller/Component/PaginatorComponent.php
<ide> public function paginate($object, array $settings = [])
<ide> } catch (PageOutOfBoundsException $e) {
<ide> $this->_setPagingParams();
<ide>
<del> throw new NotFoundException();
<add> throw new NotFoundException(null, null, $e);
<ide> }
<ide>
<ide> return $results;
<ide><path>src/Database/Connection.php
<ide> public function connect()
<ide> try {
<ide> return $this->_driver->connect();
<ide> } catch (\Exception $e) {
<del> throw new MissingConnectionException(['reason' => $e->getMessage()]);
<add> throw new MissingConnectionException(['reason' => $e->getMessage()], null, $e);
<ide> }
<ide> }
<ide>
<ide><path>src/Mailer/Transport/SmtpTransport.php
<ide> protected function _connect()
<ide> }
<ide> } catch (SocketException $e) {
<ide> if ($config['tls']) {
<del> throw new SocketException('SMTP server did not accept the connection or trying to connect to non TLS SMTP server using TLS.');
<add> throw new SocketException('SMTP server did not accept the connection or trying to connect to non TLS SMTP server using TLS.', null, $e);
<ide> }
<ide> try {
<ide> $this->_smtpSend("HELO {$host}", '250');
<ide> } catch (SocketException $e2) {
<del> throw new SocketException('SMTP server did not accept the connection.');
<add> throw new SocketException('SMTP server did not accept the connection.', null, $e2);
<ide> }
<ide> }
<ide> }
<ide> protected function _auth()
<ide> try {
<ide> $this->_smtpSend(base64_encode($this->_config['username']), '334');
<ide> } catch (SocketException $e) {
<del> throw new SocketException('SMTP server did not accept the username.');
<add> throw new SocketException('SMTP server did not accept the username.', null, $e);
<ide> }
<ide> try {
<ide> $this->_smtpSend(base64_encode($this->_config['password']), '235');
<ide> } catch (SocketException $e) {
<del> throw new SocketException('SMTP server did not accept the password.');
<add> throw new SocketException('SMTP server did not accept the password.', null, $e);
<ide> }
<ide> } elseif ($replyCode === '504') {
<ide> throw new SocketException('SMTP authentication method not allowed, check if SMTP server requires TLS.');
<ide><path>src/Network/Socket.php
<ide> public function enableCrypto($type, $clientOrServer = 'client', $enable = true)
<ide> $enableCryptoResult = stream_socket_enable_crypto($this->connection, $enable, $this->_encryptMethods[$type . '_' . $clientOrServer]);
<ide> } catch (Exception $e) {
<ide> $this->setLastError(null, $e->getMessage());
<del> throw new SocketException($e->getMessage());
<add> throw new SocketException($e->getMessage(), null, $e);
<ide> }
<ide> if ($enableCryptoResult === true) {
<ide> $this->encrypted = $enable;
<ide><path>src/TestSuite/Fixture/FixtureManager.php
<ide> public function load($test)
<ide> get_class($test),
<ide> $e->getMessage()
<ide> );
<del> throw new Exception($msg);
<add> throw new Exception($msg, null, $e);
<ide> }
<ide> }
<ide> }
<ide> public function load($test)
<ide> get_class($test),
<ide> $e->getMessage()
<ide> );
<del> throw new Exception($msg);
<add> throw new Exception($msg, null, $e);
<ide> }
<ide> }
<ide> };
<ide> public function load($test)
<ide> get_class($test),
<ide> $e->getMessage()
<ide> );
<del> throw new Exception($msg);
<add> throw new Exception($msg, null, $e);
<ide> }
<ide> }
<ide> };
<ide> public function load($test)
<ide> get_class($test),
<ide> $e->getMessage()
<ide> );
<del> throw new Exception($msg);
<add> throw new Exception($msg, null, $e);
<ide> }
<ide> }
<ide>
<ide><path>src/View/Cell.php
<ide> public function render($template = null)
<ide> try {
<ide> return $this->View->render($template);
<ide> } catch (MissingTemplateException $e) {
<del> throw new MissingCellViewException(['file' => $template, 'name' => $name]);
<add> throw new MissingCellViewException(['file' => $template, 'name' => $name], null, $e);
<ide> }
<ide> };
<ide>
<ide><path>tests/TestCase/Cache/CacheTest.php
<ide> public function testCacheEngineFallbackToSelf()
<ide> {
<ide> $filename = tempnam(TMP, 'tmp_');
<ide>
<del> $this->expectException(InvalidArgumentException::class);
<del> $this->expectExceptionMessage('cannot fallback to itself');
<del>
<ide> Cache::setConfig('tests', [
<ide> 'engine' => 'File',
<ide> 'path' => $filename,
<ide> 'prefix' => 'test_',
<ide> 'fallback' => 'tests'
<ide> ]);
<ide>
<del> Cache::engine('tests');
<add> $e = null;
<add> try {
<add> Cache::engine('tests');
<add> } catch (InvalidArgumentException $e) {
<add> }
<ide>
<ide> Cache::drop('tests');
<ide> unlink($filename);
<add>
<add> $this->assertNotNull($e);
<add> $this->assertStringEndsWith('cannot fallback to itself.', $e->getMessage());
<add> $this->assertInstanceOf('RunTimeException', $e->getPrevious());
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/Controller/Component/PaginatorComponentTest.php
<ide> use Cake\Controller\Controller;
<ide> use Cake\Datasource\ConnectionManager;
<ide> use Cake\Datasource\EntityInterface;
<add>use Cake\Datasource\Exception\PageOutOfBoundsException;
<ide> use Cake\Datasource\Paginator;
<ide> use Cake\Http\ServerRequest;
<ide> use Cake\Network\Exception\NotFoundException;
<ide> public function testOutOfRangePageNumberGetsClamped()
<ide> $this->request->query['page'] = 3000;
<ide>
<ide> $table = TableRegistry::get('PaginatorPosts');
<add>
<add> $e = null;
<ide> try {
<ide> $this->Paginator->paginate($table);
<del> $this->fail('No exception raised');
<ide> } catch (NotFoundException $e) {
<del> $this->assertEquals(
<del> 1,
<del> $this->request->params['paging']['PaginatorPosts']['page'],
<del> 'Page number should not be 0'
<del> );
<ide> }
<add>
<add> $this->assertEquals(
<add> 1,
<add> $this->request->params['paging']['PaginatorPosts']['page'],
<add> 'Page number should not be 0'
<add> );
<add>
<add> $this->assertNotNull($e);
<add> $this->assertInstanceOf(PageOutOfBoundsException::class, $e->getPrevious());
<ide> }
<ide>
<ide> /**
<ide> public function testOutOfRangePageNumberStillProvidesPageCount()
<ide> $this->request->query['page'] = 4;
<ide>
<ide> $table = TableRegistry::get('PaginatorPosts');
<add>
<add> $e = null;
<ide> try {
<ide> $this->Paginator->paginate($table);
<del> $this->fail('No exception raised');
<ide> } catch (NotFoundException $e) {
<del> $this->assertEquals(
<del> 3,
<del> $this->request->params['paging']['PaginatorPosts']['pageCount'],
<del> 'Page count number should not be 0'
<del> );
<ide> }
<add>
<add> $this->assertEquals(
<add> 3,
<add> $this->request->params['paging']['PaginatorPosts']['pageCount'],
<add> 'Page count number should not be 0'
<add> );
<add>
<add> $this->assertNotNull($e);
<add> $this->assertInstanceOf(PageOutOfBoundsException::class, $e->getPrevious());
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/Database/ConnectionTest.php
<ide>
<ide> use Cake\Database\Connection;
<ide> use Cake\Database\Driver\Mysql;
<add>use Cake\Database\Exception\MissingConnectionException;
<ide> use Cake\Database\Exception\NestedTransactionRollbackException;
<ide> use Cake\Database\Log\LoggingStatement;
<ide> use Cake\Database\Log\QueryLogger;
<ide> public function testDriverOptionClassNameSupport()
<ide> /**
<ide> * Tests that connecting with invalid credentials or database name throws an exception
<ide> *
<del> * @expectedException \Cake\Database\Exception\MissingConnectionException
<ide> * @return void
<ide> */
<ide> public function testWrongCredentials()
<ide> {
<ide> $config = ConnectionManager::getConfig('test');
<ide> $this->skipIf(isset($config['url']), 'Datasource has dsn, skipping.');
<ide> $connection = new Connection(['database' => '/dev/nonexistent'] + ConnectionManager::getConfig('test'));
<del> $connection->connect();
<add>
<add> $e = null;
<add> try {
<add> $connection->connect();
<add> } catch (MissingConnectionException $e) {
<add> }
<add>
<add> $this->assertNotNull($e);
<add> $this->assertStringStartsWith('Connection to database could not be established:', $e->getMessage());
<add> $this->assertInstanceOf('PDOException', $e->getPrevious());
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/Mailer/Transport/SmtpTransportTest.php
<ide>
<ide> use Cake\Mailer\Email;
<ide> use Cake\Mailer\Transport\SmtpTransport;
<add>use Cake\Network\Exception\SocketException;
<ide> use Cake\Network\Socket;
<ide> use Cake\TestSuite\TestCase;
<ide>
<ide> public function testConnectEhloTls()
<ide> /**
<ide> * testConnectEhloTlsOnNonTlsServer method
<ide> *
<del> * @expectedException \Cake\Network\Exception\SocketException
<del> * @expectedExceptionMessage SMTP server did not accept the connection or trying to connect to non TLS SMTP server using TLS.
<ide> * @return void
<ide> */
<ide> public function testConnectEhloTlsOnNonTlsServer()
<ide> public function testConnectEhloTlsOnNonTlsServer()
<ide> $this->socket->expects($this->at(4))->method('write')->with("STARTTLS\r\n");
<ide> $this->socket->expects($this->at(5))->method('read')
<ide> ->will($this->returnValue("500 5.3.3 Unrecognized command\r\n"));
<del> $this->SmtpTransport->connect();
<add>
<add> $e = null;
<add> try {
<add> $this->SmtpTransport->connect();
<add> } catch (SocketException $e) {
<add> }
<add>
<add> $this->assertNotNull($e);
<add> $this->assertEquals('SMTP server did not accept the connection or trying to connect to non TLS SMTP server using TLS.', $e->getMessage());
<add> $this->assertInstanceOf(SocketException::class, $e->getPrevious());
<add> $this->assertContains('500 5.3.3 Unrecognized command', $e->getPrevious()->getMessage());
<ide> }
<ide>
<ide> /**
<ide> public function testConnectHelo()
<ide> /**
<ide> * testConnectFail method
<ide> *
<del> * @expectedException \Cake\Network\Exception\SocketException
<del> * @expectedExceptionMessage SMTP server did not accept the connection.
<ide> * @return void
<ide> */
<ide> public function testConnectFail()
<ide> public function testConnectFail()
<ide> $this->socket->expects($this->at(3))->method('read')->will($this->returnValue("200 Not Accepted\r\n"));
<ide> $this->socket->expects($this->at(4))->method('write')->with("HELO localhost\r\n");
<ide> $this->socket->expects($this->at(5))->method('read')->will($this->returnValue("200 Not Accepted\r\n"));
<del> $this->SmtpTransport->connect();
<add>
<add> $e = null;
<add> try {
<add> $this->SmtpTransport->connect();
<add> } catch (SocketException $e) {
<add> }
<add>
<add> $this->assertNotNull($e);
<add> $this->assertEquals('SMTP server did not accept the connection.', $e->getMessage());
<add> $this->assertInstanceOf(SocketException::class, $e->getPrevious());
<add> $this->assertContains('200 Not Accepted', $e->getPrevious()->getMessage());
<ide> }
<ide>
<ide> /**
<ide> public function testAuthBadSequence()
<ide> /**
<ide> * testAuthBadUsername method
<ide> *
<del> * @expectedException \Cake\Network\Exception\SocketException
<del> * @expectedExceptionMessage SMTP server did not accept the username.
<ide> * @return void
<ide> */
<ide> public function testAuthBadUsername()
<ide> public function testAuthBadUsername()
<ide> $this->socket->expects($this->at(3))->method('read')
<ide> ->will($this->returnValue("535 5.7.8 Authentication failed\r\n"));
<ide> $this->SmtpTransport->config(['username' => 'mark', 'password' => 'story']);
<del> $this->SmtpTransport->auth();
<add>
<add> $e = null;
<add> try {
<add> $this->SmtpTransport->auth();
<add> } catch (SocketException $e) {
<add> }
<add>
<add> $this->assertNotNull($e);
<add> $this->assertEquals('SMTP server did not accept the username.', $e->getMessage());
<add> $this->assertInstanceOf(SocketException::class, $e->getPrevious());
<add> $this->assertContains('535 5.7.8 Authentication failed', $e->getPrevious()->getMessage());
<ide> }
<ide>
<ide> /**
<ide> * testAuthBadPassword method
<ide> *
<del> * @expectedException \Cake\Network\Exception\SocketException
<del> * @expectedExceptionMessage SMTP server did not accept the password.
<ide> * @return void
<ide> */
<ide> public function testAuthBadPassword()
<ide> public function testAuthBadPassword()
<ide> $this->socket->expects($this->at(4))->method('write')->with("c3Rvcnk=\r\n");
<ide> $this->socket->expects($this->at(5))->method('read')->will($this->returnValue("535 5.7.8 Authentication failed\r\n"));
<ide> $this->SmtpTransport->config(['username' => 'mark', 'password' => 'story']);
<del> $this->SmtpTransport->auth();
<add>
<add> $e = null;
<add> try {
<add> $this->SmtpTransport->auth();
<add> } catch (SocketException $e) {
<add> }
<add>
<add> $this->assertNotNull($e);
<add> $this->assertEquals('SMTP server did not accept the password.', $e->getMessage());
<add> $this->assertInstanceOf(SocketException::class, $e->getPrevious());
<add> $this->assertContains('535 5.7.8 Authentication failed', $e->getPrevious()->getMessage());
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/Network/SocketTest.php
<ide> public function testEnableCryptoSocketExceptionNoSsl()
<ide> /**
<ide> * testEnableCryptoSocketExceptionNoTls
<ide> *
<del> * @expectedException \Cake\Network\Exception\SocketException
<ide> * @return void
<ide> */
<ide> public function testEnableCryptoSocketExceptionNoTls()
<ide> public function testEnableCryptoSocketExceptionNoTls()
<ide> // testing exception on no ssl socket server for ssl and tls methods
<ide> $this->Socket = new Socket($configNoSslOrTls);
<ide> $this->Socket->connect();
<del> $this->Socket->enableCrypto('tls', 'client');
<add>
<add> $e = null;
<add> try {
<add> $this->Socket->enableCrypto('tls', 'client');
<add> } catch (SocketException $e) {
<add> }
<add>
<add> $this->assertNotNull($e);
<add> $this->assertInstanceOf('Exception', $e->getPrevious());
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/TestSuite/FixtureManagerTest.php
<ide> */
<ide> namespace Cake\Test\TestSuite;
<ide>
<add>use Cake\Core\Exception\Exception as CakeException;
<ide> use Cake\Core\Plugin;
<ide> use Cake\Database\Schema\Table;
<ide> use Cake\Datasource\ConnectionManager;
<ide> use Cake\TestSuite\Fixture\FixtureManager;
<ide> use Cake\TestSuite\Stub\ConsoleOutput;
<ide> use Cake\TestSuite\TestCase;
<add>use PDOException;
<ide>
<ide> /**
<ide> * Fixture manager test case.
<ide> public function testLoadSingle()
<ide> $this->assertCount(4, $results);
<ide> $this->manager->unload($test);
<ide> }
<add>
<add> /**
<add> * Test exception on load
<add> *
<add> * @return void
<add> */
<add> public function testExceptionOnLoad()
<add> {
<add> $test = $this->getMockBuilder('Cake\TestSuite\TestCase')->getMock();
<add> $test->fixtures = ['core.products'];
<add>
<add> $manager = $this->getMockBuilder(FixtureManager::class)
<add> ->setMethods(['_runOperation'])
<add> ->getMock();
<add> $manager->expects($this->any())
<add> ->method('_runOperation')
<add> ->will($this->returnCallback(function () {
<add> throw new PDOException('message');
<add> }));
<add>
<add> $manager->fixturize($test);
<add>
<add> $e = null;
<add> try {
<add> $manager->load($test);
<add> } catch (CakeException $e) {
<add> }
<add>
<add> $this->assertNotNull($e);
<add> $this->assertRegExp('/^Unable to insert fixtures for "Mock_TestCase_\w+" test case. message$/D', $e->getMessage());
<add> $this->assertInstanceOf('PDOException', $e->getPrevious());
<add> }
<add>
<add> /**
<add> * Test exception on load fixture
<add> *
<add> * @dataProvider loadErrorMessageProvider
<add> * @return void
<add> */
<add> public function testExceptionOnLoadFixture($method, $expectedMessage)
<add> {
<add> $fixture = $this->getMockBuilder('Cake\Test\Fixture\ProductsFixture')
<add> ->setMethods([$method])
<add> ->getMock();
<add> $fixture->expects($this->once())
<add> ->method($method)
<add> ->will($this->returnCallback(function () {
<add> throw new PDOException('message');
<add> }));
<add>
<add> $fixtures = [
<add> 'core.products' => $fixture,
<add> ];
<add>
<add> $test = $this->getMockBuilder('Cake\TestSuite\TestCase')->getMock();
<add> $test->fixtures = array_keys($fixtures);
<add>
<add> $manager = $this->getMockBuilder(FixtureManager::class)
<add> ->setMethods(['_fixtureConnections'])
<add> ->getMock();
<add> $manager->expects($this->any())
<add> ->method('_fixtureConnections')
<add> ->will($this->returnValue([
<add> 'test' => $fixtures,
<add> ]));
<add> $manager->fixturize($test);
<add> $manager->loadSingle('Products');
<add>
<add> $e = null;
<add> try {
<add> $manager->load($test);
<add> } catch (CakeException $e) {
<add> }
<add>
<add> $this->assertNotNull($e);
<add> $this->assertRegExp($expectedMessage, $e->getMessage());
<add> $this->assertInstanceOf('PDOException', $e->getPrevious());
<add> }
<add>
<add> /**
<add> * Data provider for testExceptionOnLoadFixture
<add> *
<add> * @return array
<add> */
<add> public function loadErrorMessageProvider()
<add> {
<add> return [
<add> [
<add> 'createConstraints',
<add> '/^Unable to create constraints for fixture "Mock_ProductsFixture_\w+" in "Mock_TestCase_\w+" test case: \nmessage$/D',
<add> ],
<add> [
<add> 'dropConstraints',
<add> '/^Unable to drop constraints for fixture "Mock_ProductsFixture_\w+" in "Mock_TestCase_\w+" test case: \nmessage$/D',
<add> ],
<add> [
<add> 'insert',
<add> '/^Unable to insert fixture "Mock_ProductsFixture_\w+" in "Mock_TestCase_\w+" test case: \nmessage$/D',
<add> ],
<add> ];
<add> }
<ide> }
<ide><path>tests/TestCase/View/CellTest.php
<ide> use Cake\Core\Plugin;
<ide> use Cake\TestSuite\TestCase;
<ide> use Cake\View\View;
<add>use Cake\View\Exception\MissingCellViewException;
<add>use Cake\View\Exception\MissingTemplateException;
<ide> use TestApp\Controller\CellTraitTestController;
<ide> use TestApp\View\CustomJsonView;
<ide>
<ide> public function testCellManualRender()
<ide> /**
<ide> * Tests manual render() invocation with error
<ide> *
<del> * @expectedException \Cake\View\Exception\MissingCellViewException
<ide> * @return void
<ide> */
<ide> public function testCellManualRenderError()
<ide> {
<ide> $cell = $this->View->cell('Articles');
<del> $cell->render('derp');
<add>
<add> $e = null;
<add> try {
<add> $cell->render('derp');
<add> } catch (MissingCellViewException $e) {
<add> }
<add>
<add> $this->assertNotNull($e);
<add> $this->assertEquals('Cell view file "derp" is missing.', $e->getMessage());
<add> $this->assertInstanceOf(MissingTemplateException::class, $e->getPrevious());
<ide> }
<ide>
<ide> /** | 14 |
Javascript | Javascript | remove flushnext method | fc8034b352121f8f057dbd5e3837eeb17e1df580 | <ide><path>src/ngMock/angular-mocks.js
<ide> angular.mock.$Browser = function() {
<ide> };
<ide>
<ide>
<add> /**
<add> * @name ngMock.$browser#defer.now
<add> * @propertyOf ngMock.$browser
<add> *
<add> * @description
<add> * Current milliseconds mock time.
<add> */
<ide> self.defer.now = 0;
<ide>
<ide>
<ide> angular.mock.$Browser = function() {
<ide> }
<ide> };
<ide>
<del> /**
<del> * @name ngMock.$browser#defer.flushNext
<del> * @methodOf ngMock.$browser
<del> *
<del> * @description
<del> * Flushes next pending request and compares it to the provided delay
<del> *
<del> * @param {number=} expectedDelay the delay value that will be asserted against the delay of the next timeout function
<del> */
<del> self.defer.flushNext = function(expectedDelay) {
<del> var tick = self.deferredFns.shift();
<del> expect(tick.time).toEqual(expectedDelay);
<del> tick.fn();
<del> };
<del>
<del> /**
<del> * @name ngMock.$browser#defer.now
<del> * @propertyOf ngMock.$browser
<del> *
<del> * @description
<del> * Current milliseconds mock time.
<del> */
<del>
<ide> self.$$baseHref = '';
<ide> self.baseHref = function() {
<ide> return this.$$baseHref;
<ide><path>test/ng/timeoutSpec.js
<ide> describe('$timeout', function() {
<ide> var promise2 = $timeout(function() {}, 100, false);
<ide> expect(cancelSpy).not.toHaveBeenCalled();
<ide>
<del> $timeout.flushNext(0);
<add> $timeout.flush(0);
<ide>
<ide> // Promise1 deferred object should already be removed from the list and not cancellable
<ide> $timeout.cancel(promise1);
<ide><path>test/ngMock/angular-mocksSpec.js
<ide> describe('ngMock', function() {
<ide>
<ide> $timeout(iterate, 100);
<ide> $timeout(iterate, 123);
<del> $timeout.flushNext(100);
<add> $timeout.flush(100);
<ide> expect(count).toBe(1);
<del> $timeout.flushNext(123);
<add> $timeout.flush(123);
<ide> expect(count).toBe(2);
<ide> }));
<ide> }); | 3 |
PHP | PHP | adjust password reset notification | f3730e6872ed95d14b89f6e1801cce0aa209f210 | <ide><path>src/Illuminate/Auth/Notifications/ResetPassword.php
<ide> public function via($notifiable)
<ide> public function toMail()
<ide> {
<ide> return (new MailMessage)
<del> ->line([
<del> 'You are receiving this email because we received a password reset request for your account.',
<del> 'Click the button below to reset your password:',
<del> ])
<add> ->line('You are receiving this email because we received a password reset request for your account.')
<ide> ->action('Reset Password', url('password/reset', $this->token))
<ide> ->line('If you did not request a password reset, no further action is required.');
<ide> } | 1 |
Text | Text | add bart to readme | 087465b9431a847443c33344b9a50b9d0a90040a | <ide><path>README.md
<ide> At some point in the future, you'll be able to seamlessly move from pre-training
<ide> 13. **[XLM-RoBERTa](https://github.com/pytorch/fairseq/tree/master/examples/xlmr)** (from Facebook AI), released together with the paper [Unsupervised Cross-lingual Representation Learning at Scale](https://arxiv.org/abs/1911.02116) by Alexis Conneau*, Kartikay Khandelwal*, Naman Goyal, Vishrav Chaudhary, Guillaume Wenzek, Francisco Guzmán, Edouard Grave, Myle Ott, Luke Zettlemoyer and Veselin Stoyanov.
<ide> 14. **[MMBT](https://github.com/facebookresearch/mmbt/)** (from Facebook), released together with the paper a [Supervised Multimodal Bitransformers for Classifying Images and Text](https://arxiv.org/pdf/1909.02950.pdf) by Douwe Kiela, Suvrat Bhooshan, Hamed Firooz, Davide Testuggine.
<ide> 15. **[FlauBERT](https://github.com/getalp/Flaubert)** (from CNRS) released with the paper [FlauBERT: Unsupervised Language Model Pre-training for French](https://arxiv.org/abs/1912.05372) by Hang Le, Loïc Vial, Jibril Frej, Vincent Segonne, Maximin Coavoux, Benjamin Lecouteux, Alexandre Allauzen, Benoît Crabbé, Laurent Besacier, Didier Schwab.
<del>16. **[Other community models](https://huggingface.co/models)**, contributed by the [community](https://huggingface.co/users).
<del>17. Want to contribute a new model? We have added a **detailed guide and templates** to guide you in the process of adding a new model. You can find them in the [`templates`](./templates) folder of the repository. Be sure to check the [contributing guidelines](./CONTRIBUTING.md) and contact the maintainers or open an issue to collect feedbacks before starting your PR.
<add>16. **[BART](https://github.com/pytorch/fairseq/tree/master/examples/bart)** (from Facebook) released with the paper [BART: Denoising Sequence-to-Sequence Pre-training for Natural Language Generation, Translation, and Comprehension](https://arxiv.org/pdf/1910.13461.pdf) by Mike Lewis, Yinhan Liu, Naman Goyal, Marjan Ghazvininejad, Abdelrahman Mohamed, Omer Levy, Ves Stoyanov and Luke Zettlemoyer.
<add>17. **[Other community models](https://huggingface.co/models)**, contributed by the [community](https://huggingface.co/users).
<add>18. Want to contribute a new model? We have added a **detailed guide and templates** to guide you in the process of adding a new model. You can find them in the [`templates`](./templates) folder of the repository. Be sure to check the [contributing guidelines](./CONTRIBUTING.md) and contact the maintainers or open an issue to collect feedbacks before starting your PR.
<ide>
<ide> These implementations have been tested on several datasets (see the example scripts) and should match the performances of the original implementations (e.g. ~93 F1 on SQuAD for BERT Whole-Word-Masking, ~88 F1 on RocStories for OpenAI GPT, ~18.3 perplexity on WikiText 103 for Transformer-XL, ~0.916 Peason R coefficient on STS-B for XLNet). You can find more details on the performances in the Examples section of the [documentation](https://huggingface.co/transformers/examples.html).
<ide> | 1 |
PHP | PHP | fix bug in postgres processor | e0bfe4b3ebcf9e6ee96832be7501f73c9fd69a53 | <ide><path>src/Illuminate/Database/Query/Processors/PostgresProcessor.php
<ide> public function processInsertGetId(Builder $query, $sql, $values, $sequence = nu
<ide>
<ide> $sequence = $sequence ?: 'id';
<ide>
<del> return $results[0]->$sequence;
<add> $result = (array) $results[0];
<add>
<add> return (int) $row[$sequence];
<ide> }
<ide>
<ide> }
<ide>\ No newline at end of file | 1 |
Python | Python | set version to v3.0.6 | 8a95475b3dce2e52bc9be53a7b8c9ad49d7fc32c | <ide><path>spacy/about.py
<ide> # fmt: off
<ide> __title__ = "spacy"
<del>__version__ = "3.0.5"
<add>__version__ = "3.0.6"
<ide> __download_url__ = "https://github.com/explosion/spacy-models/releases/download"
<ide> __compatibility__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json"
<ide> __projects__ = "https://github.com/explosion/projects" | 1 |
Python | Python | add path fixture for spacy data path | 514bfa25978991f408084470872bd113e62c49e4 | <ide><path>spacy/tests/conftest.py
<ide> from ..tokens import Doc
<ide> from ..strings import StringStore
<ide> from ..attrs import ORTH, TAG, HEAD, DEP
<add>from ..util import match_best_version, get_data_path
<ide>
<ide> from io import StringIO
<add>from pathlib import Path
<add>import os
<ide> import pytest
<ide>
<ide>
<ide> def text_file():
<ide> return StringIO()
<ide>
<ide>
<add>@pytest.fixture
<add>def path():
<add> if 'SPACY_DATA' in os.environ:
<add> return Path(os.environ['SPACY_DATA'])
<add> else:
<add> return match_best_version('en', None, get_data_path())
<add>
<add>
<ide> # only used for tests that require loading the models
<ide> # in all other cases, use specific instances
<ide> @pytest.fixture(scope="session") | 1 |
Javascript | Javascript | fix a bug in computing min delay | 12ef81f0e0e08e713bc2e53cf8cd86ac49609fd2 | <ide><path>d3.js
<ide> if (!Object.create) Object.create = function(o) {
<ide> };
<ide> (function(_) {
<ide> var d3 = _.d3 = {};
<del> d3.version = "0.1.2"; // semver
<add> d3.version = "0.1.3"; // semver
<ide> function d3_array(psuedoarray) {
<ide> return Array.prototype.slice.call(psuedoarray);
<ide> }
<ide> function d3_timer(callback, delay) {
<ide> t0,
<ide> t1 = d3_timer_queue;
<ide>
<add> if (!isFinite(delay)) return;
<add>
<ide> // Scan the queue for earliest callback.
<ide> while (t1) {
<ide> if (t1.callback == callback) {
<ide> function d3_timer(callback, delay) {
<ide>
<ide> if (!d3_timer_interval) {
<ide> clearTimeout(d3_timer_timeout);
<del> d3_timer_timeout = setTimeout(d3_timer_start, Math.min(24, start - now));
<add> d3_timer_timeout = setTimeout(d3_timer_start, Math.max(24, start - now));
<ide> }
<ide> }
<ide>
<ide><path>d3.min.js
<ide> d.parentNode;b.removeChild(d);return b})};a.on=function(d,b){d="on"+d;return a.e
<ide> arguments)}}var v=o(q),m;for(m in d)d[m].call(this,v,p);if(q==1){h[p]=2;b.end.dispatch.apply(this,arguments)}}});return l}var f={},d={},b=k.dispatch("start","end"),h=[],i=[],g=[],n,o=k.ease("cubic-in-out");f.delay=function(j){var l=Infinity,p=-1;if(typeof j=="function")a.each(function(){var q=i[++p]=+j.apply(this,arguments);if(q<l)l=q});else{l=+j;a.each(function(){i[++p]=l})}ca(e,l);return f};f.duration=function(j){var l=-1;if(typeof j=="function"){n=0;a.each(function(){var p=g[++l]=+j.apply(this,
<ide> arguments);if(p>n)n=p})}else{n=+j;a.each(function(){g[++l]=n})}return f};f.ease=function(j){o=typeof j=="string"?k.ease(j):j;return f};f.attrTween=function(j,l){function p(r,t){s[++B]=l.call(this,r,t,this.getAttribute(j))}function q(r,t){s[++B]=l.call(this,r,t,this.getAttributeNS(j.space,j.local))}function v(r,t){this.setAttribute(j,s[t](r))}function m(r,t){this.setAttributeNS(j.space,j.local,s[t](r))}var s=[],B=-1;j=k.ns.qualify(j);a.each(j.local?q:p);d["attr."+j]=j.local?m:v;return f};f.attr=function(j,
<ide> l){return f.attrTween(j,U(l))};f.styleTween=function(j,l,p){var q=[],v=-1;a.each(function(m,s){q[++v]=l.call(this,m,s,window.getComputedStyle(this,null).getPropertyValue(j))});d["style."+j]=function(m,s){this.style.setProperty(j,q[s](m),p)};return f};f.style=function(j,l,p){return f.styleTween(j,U(l),p)};f.select=function(j){var l;j=M(a.select(j),c).ease(o);l=-1;j.delay(function(){return i[++l]});l=-1;j.duration(function(){return g[++l]});return j};f.selectAll=function(j){var l;j=M(a.selectAll(j),
<del>c).ease(o);l=-1;j.delay(function(p,q){return i[q?l:++l]});l=-1;j.duration(function(p,q){return g[q?l:++l]});return j};f.each=function(j,l){b[j].add(l);return f};f.call=Q;return f.delay(0).duration(250)}function ca(a,c){for(var e=Date.now(),f=false,d=e+c,b=F;b;){if(b.callback==a){b.then=e;b.delay=c;f=true}else{var h=b.then+b.delay;if(h<d)d=h}b=b.next}f||(F={callback:a,then:e,delay:c,next:F});if(!G){clearTimeout(N);N=setTimeout(da,Math.min(24,d-e))}}function da(){G=setInterval(ea,24);N=0}function ea(){for(var a,
<del>c=Date.now(),e=F;e;){a=c-e.then;if(a>e.delay)e.flush=e.callback(a);e=e.next}a=null;for(c=F;c;)c=c.flush?a?a.next=c.next:F=c.next:(a=c).next;a||(G=clearInterval(G))}function U(a){return typeof a=="function"?function(c,e,f){return k.interpolate(f,a.call(this,c,e))}:function(c,e,f){return k.interpolate(f,a)}}var k=I.d3={};k.version="0.1.2";k.range=function(a,c,e){if(arguments.length==1){c=a;a=0}if(e==null)e=1;if((c-a)/e==Infinity)throw Error("infinite range");var f=[],d=-1,b;if(e<0)for(;(b=a+e*++d)>
<del>c;)f.push(b);else for(;(b=a+e*++d)<c;)f.push(b);return f};k.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 c=a.indexOf(":");return c<0?a:{space:k.ns.prefix[a.substring(0,c)],local:a.substring(c+1)}}};k.dispatch=function(){for(var a={},c,e=0,f=arguments.length;e<f;e++){c=arguments[e];a[c]=V(c)}return a};k.format=function(a){a=
<del>fa.exec(a);var c=a[1]||" ",e=a[5],f=+a[6],d=a[7],b=a[8],h=a[9];if(b)b=b.substring(1);if(e)c="0";if(h=="d")b="0";return function(i){if(h=="d"&&i%1)return"";if(b)i=(+i).toFixed(b);else i+="";if(d){for(var g=i.lastIndexOf("."),n=g>=0?i.substring(g):(g=i.length,""),o=[];g>0;)o.push(i.substring(g-=3,g+3));i=o.reverse().join(",")+n}g=i.length;if(g<f)i=Array(f-g+1).join(c)+i;return i}};var fa=/(?:([^{])?([<>=^]))?([+\- ])?(#)?(0)?([0-9]+)?(,)?(\.[0-9]+)?([a-zA-Z%])?/,ga=J(2),ha=J(3),ia={linear:function(){return W},
<del>poly:J,quad:function(){return ga},cubic:function(){return ha},sin:function(){return X},exp:function(){return Y},circle:function(){return Z},elastic:function(a,c){var e;if(arguments.length<2)c=0.45;if(arguments.length<1){a=1;e=c/4}else e=c/(2*Math.PI)*Math.asin(1/a);return function(f){return 1+a*Math.pow(2,10*-f)*Math.sin(-(f+e)*2*Math.PI/c)}},back:function(a){a||(a=1.70158);return function(c){return c*c*((a+1)*c-a)}},bounce:function(){return $}},ja={"in":function(a){return a},out:R,"in-out":S,"out-int":function(a){return S(R(a))}};
<del>k.ease=function(a){var c=a.indexOf("-"),e=c>=0?a.substring(0,c):a;c=c>=0?a.substring(c+1):"in";return ja[c](ia[e].apply(null,Array.prototype.slice.call(arguments,1)))};k.event=null;k.interpolate=function(a,c){if(typeof c=="number")return k.interpolateNumber(+a,c);if(typeof c=="string")return c in D||/^(#|rgb\(|hsl\()/.test(c)?k.interpolateRgb(String(a),c):k.interpolateString(String(a),c);if(c instanceof Array)return k.interpolateArray(a,c);return k.interpolateObject(a,c)};k.interpolateNumber=function(a,
<del>c){c-=a;return function(e){return a+c*e}};k.interpolateString=function(a,c){var e,f,d=0,b=[],h=[],i,g;for(f=0;e=O.exec(c);++f){e.index&&b.push(c.substring(d,e.index));h.push({i:b.length,x:e[0]});b.push(null);d=O.lastIndex}d<c.length&&b.push(c.substring(d));f=0;for(i=h.length;(e=O.exec(a))&&f<i;++f){g=h[f];if(g.x==e[0]){if(g.i)if(b[g.i+1]==null){b[g.i-1]+=g.x;b.splice(g.i,1);for(e=f+1;e<i;++e)h[e].i--}else{b[g.i-1]+=g.x+b[g.i+1];b.splice(g.i,2);for(e=f+1;e<i;++e)h[e].i-=2}else if(b[g.i+1]==null)b[g.i]=
<del>g.x;else{b[g.i]=g.x+b[g.i+1];b.splice(g.i+1,1);for(e=f+1;e<i;++e)h[e].i--}h.splice(f,1);i--;f--}else g.x=k.interpolateNumber(parseFloat(e[0]),parseFloat(g.x))}for(;f<i;){g=h.pop();if(b[g.i+1]==null)b[g.i]=g.x;else{b[g.i]=g.x+b[g.i+1];b.splice(g.i+1,1)}i--}if(b.length==1)return b[0]==null?h[0].x:function(){return c};return function(n){for(f=0;f<i;++f)b[(g=h[f]).i]=g.x(n);return b.join("")}};k.interpolateRgb=function(a,c){a=K(a);c=K(c);var e=a.r,f=a.g,d=a.b,b=c.r-e,h=c.g-f,i=c.b-d;return function(g){return"rgb("+
<del>Math.round(e+b*g)+","+Math.round(f+h*g)+","+Math.round(d+i*g)+")"}};k.interpolateArray=function(a,c){var e=[],f=[],d=a.length,b=c.length,h=Math.min(a.length,c.length),i;for(i=0;i<h;++i)e.push(k.interpolate(a[i],c[i]));for(;i<d;++i)f[i]=a[i];for(;i<b;++i)f[i]=c[i];return function(g){for(i=0;i<h;++i)f[i]=e[i](g);return f}};k.interpolateObject=function(a,c){var e={},f={},d;for(d in a)if(d in c)e[d]=(d in ka||/\bcolor\b/.test(d)?k.interpolateRgb:k.interpolate)(a[d],c[d]);else f[d]=a[d];for(d in c)d in
<del>a||(f[d]=c[d]);return function(b){for(d in e)f[d]=e[d](b);return f}};var O=/[-+]?(?:\d+\.\d+|\d+\.|\.\d+|\d+)(?:[eE][-]?\d+)?/g,ka={background:1,fill:1,stroke:1},D={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",
<del>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",
<del>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",
<del>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",
<del>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",
<del>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",
<del>yellow:"#ffff00",yellowgreen:"#9acd32"},P;for(P in D)D[P]=K(D[P]);k.hsl=function(a,c,e){a=T(a,c,e);return"rgb("+a.r+","+a.g+","+a.b+")"};k.linear=function(){function a(g){return i((g-e)*h)}function c(g){var n=Math.min(e,f),o=Math.max(e,f),j=o-n,l=Math.pow(10,Math.floor(Math.log(j/g)/Math.LN10));g=g/(j/l);if(g<=0.15)l*=10;else if(g<=0.35)l*=5;else if(g<=0.75)l*=2;return{start:Math.ceil(n/l)*l,stop:Math.floor(o/l)*l+l*0.5,step:l}}var e=0,f=1,d=0,b=1,h=1/(f-e),i=k.interpolate(d,b);a.invert=function(g){return(g-
<del>d)/h+e};a.domain=function(g){if(!arguments.length)return[e,f];e=g[0];f=g[1];h=1/(f-e);return a};a.range=function(g){if(!arguments.length)return[d,b];d=g[0];b=g[1];i=k.interpolate(d,b);return a};a.ticks=function(g){g=c(g);return k.range(g.start,g.stop,g.step)};a.tickFormat=function(g){g=Math.max(0,-Math.floor(Math.log(c(g).step)/Math.LN10+0.01));return k.format(",."+g+"f")};return a};k.log=function(){function a(e){return c(Math.log(e))}var c=k.linear();a.invert=function(e){return Math.exp(c.invert(e))};
<del>a.domain=function(e){if(!arguments.length)return c.domain().map(Math.exp);c.domain(e.map(Math.log));return a};a.range=function(){var e=c.range.apply(c,arguments);return arguments.length?a:e};return a};k.pow=function(){function a(h){return Math.pow(h,d)}function c(h){return Math.pow(h,b)}function e(h){return f(a(h))}var f=k.linear(),d=1,b=1/d;e.invert=function(h){return c(f.invert(h))};e.domain=function(h){if(!arguments.length)return f.domain().map(c);f.domain(h.map(a));return e};e.range=function(){var h=
<del>f.range.apply(f,arguments);return arguments.length?e:h};e.exponent=function(h){if(!arguments.length)return d;var i=e.domain();d=h;b=1/h;return e.domain(i)};return e};k.sqrt=function(){return k.pow().exponent(0.5)};k.ordinal=function(){function a(b){b=b in e?e[b]:e[b]=c.push(b)-1;return f[b%f.length]}var c=[],e={},f=[],d=0;a.domain=function(b){if(!arguments.length)return c;c=b;e={};for(var h=-1,i=-1,g=c.length;++h<g;){b=c[h];b in e||(e[b]=++i)}return a};a.range=function(b){if(!arguments.length)return f;
<del>f=b;return a};a.rangePoints=function(b,h){if(arguments.length<2)h=0;var i=b[0],g=b[1],n=(g-i)/(c.length-1+h);f=c.length==1?[(i+g)/2]:k.range(i+n*h/2,g+n/2,n);d=0;return a};a.rangeBands=function(b,h){if(arguments.length<2)h=0;var i=b[0],g=b[1],n=(g-i)/(c.length+h);f=k.range(i+n*h,g,n);d=n*(1-h);return a};a.rangeBand=function(){return d};return a};k.category10=function(){return k.ordinal().range(la)};k.category19=function(){return k.ordinal().range(ma)};k.category20=function(){return k.ordinal().range(na)};
<del>var la=["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"],ma=["#9c9ede","#7375b5","#4a5584","#cedb9c","#b5cf6b","#8ca252","#637939","#e7cb94","#e7ba52","#bd9e39","#8c6d31","#e7969c","#d6616b","#ad494a","#843c39","#de9ed6","#ce6dbd","#a55194","#7b4173"],na=["#1f77b4","#aec7e8","#ff7f0e","#ffbb78","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5","#8c564b","#c49c94","#e377c2","#f7b6d2","#7f7f7f","#c7c7c7","#bcbd22","#dbdb8d","#17becf","#9edae5"],
<del>H=z([[document]]);H[0].parentNode=document.documentElement;k.select=function(a){return typeof a=="string"?H.select(a):z([[a]])};k.selectAll=function(a){return typeof a=="string"?H.selectAll(a):z([C(a)])};k.transition=H.transition;var F=null,N=0,G;k.arc=function(){function a(b){var h=c(b),i=e(b),g=f(b)-Math.PI/2,n=d(b)-Math.PI/2;b=n-g;var o=Math.cos(g);g=Math.sin(g);var j=Math.cos(n);n=Math.sin(n);return"M"+i*o+","+i*g+"A"+i+","+i+" 0 "+(b<Math.PI?"0":"1")+",1 "+i*j+","+i*n+"L"+h*j+","+h*n+"A"+h+","+
<del>h+" 0 "+(b<Math.PI?"0":"1")+",0 "+h*o+","+h*g+"Z"}var c=function(b){return b.innerRadius},e=function(b){return b.outerRadius},f=function(b){return b.startAngle},d=function(b){return b.endAngle};a.innerRadius=function(b){c=typeof b=="function"?b:function(){return b};return a};a.outerRadius=function(b){e=typeof b=="function"?b:function(){return b};return a};a.startAngle=function(b){f=typeof b=="function"?b:function(){return b};return a};a.endAngle=function(b){d=typeof b=="function"?b:function(){return b};
<del>return a};return a};k.line=function(){function a(f){var d=[],b=0,h=f[0];for(d.push("M",c.call(this,h,b),",",e.call(this,h,b));h=f[++b];)d.push("L",c.call(this,h,b),",",e.call(this,h,b));return d.join("")}var c=function(f){return f.x},e=function(f){return f.y};a.x=function(f){c=f;return a};a.y=function(f){e=f;return a};return a};k.area=function(){function a(d){var b=[],h=0,i=d[0];for(b.push("M",c.call(this,i,h),","+e+"V",f.call(this,i,h));i=d[++h];)b.push("L",c.call(this,i,h),",",f.call(this,i,h));
<del>b.push("V"+e+"Z");return b.join("")}var c=function(d){return d.x},e=0,f=function(d){return d.y1};a.x=function(d){c=d;return a};a.y0=function(d){e=d;return a};a.y1=function(d){f=d;return a};return a}})(this);
<add>c).ease(o);l=-1;j.delay(function(p,q){return i[q?l:++l]});l=-1;j.duration(function(p,q){return g[q?l:++l]});return j};f.each=function(j,l){b[j].add(l);return f};f.call=Q;return f.delay(0).duration(250)}function ca(a,c){var e=Date.now(),f=false,d=e+c,b=F;if(isFinite(c)){for(;b;){if(b.callback==a){b.then=e;b.delay=c;f=true}else{var h=b.then+b.delay;if(h<d)d=h}b=b.next}f||(F={callback:a,then:e,delay:c,next:F});if(!G){clearTimeout(N);N=setTimeout(da,Math.max(24,d-e))}}}function da(){G=setInterval(ea,
<add>24);N=0}function ea(){for(var a,c=Date.now(),e=F;e;){a=c-e.then;if(a>e.delay)e.flush=e.callback(a);e=e.next}a=null;for(c=F;c;)c=c.flush?a?a.next=c.next:F=c.next:(a=c).next;a||(G=clearInterval(G))}function U(a){return typeof a=="function"?function(c,e,f){return k.interpolate(f,a.call(this,c,e))}:function(c,e,f){return k.interpolate(f,a)}}var k=I.d3={};k.version="0.1.3";k.range=function(a,c,e){if(arguments.length==1){c=a;a=0}if(e==null)e=1;if((c-a)/e==Infinity)throw Error("infinite range");var f=[],
<add>d=-1,b;if(e<0)for(;(b=a+e*++d)>c;)f.push(b);else for(;(b=a+e*++d)<c;)f.push(b);return f};k.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 c=a.indexOf(":");return c<0?a:{space:k.ns.prefix[a.substring(0,c)],local:a.substring(c+1)}}};k.dispatch=function(){for(var a={},c,e=0,f=arguments.length;e<f;e++){c=arguments[e];a[c]=V(c)}return a};
<add>k.format=function(a){a=fa.exec(a);var c=a[1]||" ",e=a[5],f=+a[6],d=a[7],b=a[8],h=a[9];if(b)b=b.substring(1);if(e)c="0";if(h=="d")b="0";return function(i){if(h=="d"&&i%1)return"";if(b)i=(+i).toFixed(b);else i+="";if(d){for(var g=i.lastIndexOf("."),n=g>=0?i.substring(g):(g=i.length,""),o=[];g>0;)o.push(i.substring(g-=3,g+3));i=o.reverse().join(",")+n}g=i.length;if(g<f)i=Array(f-g+1).join(c)+i;return i}};var fa=/(?:([^{])?([<>=^]))?([+\- ])?(#)?(0)?([0-9]+)?(,)?(\.[0-9]+)?([a-zA-Z%])?/,ga=J(2),ha=J(3),
<add>ia={linear:function(){return W},poly:J,quad:function(){return ga},cubic:function(){return ha},sin:function(){return X},exp:function(){return Y},circle:function(){return Z},elastic:function(a,c){var e;if(arguments.length<2)c=0.45;if(arguments.length<1){a=1;e=c/4}else e=c/(2*Math.PI)*Math.asin(1/a);return function(f){return 1+a*Math.pow(2,10*-f)*Math.sin(-(f+e)*2*Math.PI/c)}},back:function(a){a||(a=1.70158);return function(c){return c*c*((a+1)*c-a)}},bounce:function(){return $}},ja={"in":function(a){return a},
<add>out:R,"in-out":S,"out-int":function(a){return S(R(a))}};k.ease=function(a){var c=a.indexOf("-"),e=c>=0?a.substring(0,c):a;c=c>=0?a.substring(c+1):"in";return ja[c](ia[e].apply(null,Array.prototype.slice.call(arguments,1)))};k.event=null;k.interpolate=function(a,c){if(typeof c=="number")return k.interpolateNumber(+a,c);if(typeof c=="string")return c in D||/^(#|rgb\(|hsl\()/.test(c)?k.interpolateRgb(String(a),c):k.interpolateString(String(a),c);if(c instanceof Array)return k.interpolateArray(a,c);return k.interpolateObject(a,
<add>c)};k.interpolateNumber=function(a,c){c-=a;return function(e){return a+c*e}};k.interpolateString=function(a,c){var e,f,d=0,b=[],h=[],i,g;for(f=0;e=O.exec(c);++f){e.index&&b.push(c.substring(d,e.index));h.push({i:b.length,x:e[0]});b.push(null);d=O.lastIndex}d<c.length&&b.push(c.substring(d));f=0;for(i=h.length;(e=O.exec(a))&&f<i;++f){g=h[f];if(g.x==e[0]){if(g.i)if(b[g.i+1]==null){b[g.i-1]+=g.x;b.splice(g.i,1);for(e=f+1;e<i;++e)h[e].i--}else{b[g.i-1]+=g.x+b[g.i+1];b.splice(g.i,2);for(e=f+1;e<i;++e)h[e].i-=
<add>2}else if(b[g.i+1]==null)b[g.i]=g.x;else{b[g.i]=g.x+b[g.i+1];b.splice(g.i+1,1);for(e=f+1;e<i;++e)h[e].i--}h.splice(f,1);i--;f--}else g.x=k.interpolateNumber(parseFloat(e[0]),parseFloat(g.x))}for(;f<i;){g=h.pop();if(b[g.i+1]==null)b[g.i]=g.x;else{b[g.i]=g.x+b[g.i+1];b.splice(g.i+1,1)}i--}if(b.length==1)return b[0]==null?h[0].x:function(){return c};return function(n){for(f=0;f<i;++f)b[(g=h[f]).i]=g.x(n);return b.join("")}};k.interpolateRgb=function(a,c){a=K(a);c=K(c);var e=a.r,f=a.g,d=a.b,b=c.r-e,h=
<add>c.g-f,i=c.b-d;return function(g){return"rgb("+Math.round(e+b*g)+","+Math.round(f+h*g)+","+Math.round(d+i*g)+")"}};k.interpolateArray=function(a,c){var e=[],f=[],d=a.length,b=c.length,h=Math.min(a.length,c.length),i;for(i=0;i<h;++i)e.push(k.interpolate(a[i],c[i]));for(;i<d;++i)f[i]=a[i];for(;i<b;++i)f[i]=c[i];return function(g){for(i=0;i<h;++i)f[i]=e[i](g);return f}};k.interpolateObject=function(a,c){var e={},f={},d;for(d in a)if(d in c)e[d]=(d in ka||/\bcolor\b/.test(d)?k.interpolateRgb:k.interpolate)(a[d],
<add>c[d]);else f[d]=a[d];for(d in c)d in a||(f[d]=c[d]);return function(b){for(d in e)f[d]=e[d](b);return f}};var O=/[-+]?(?:\d+\.\d+|\d+\.|\.\d+|\d+)(?:[eE][-]?\d+)?/g,ka={background:1,fill:1,stroke:1},D={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",
<add>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",
<add>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",
<add>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",
<add>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",
<add>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",
<add>white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"},P;for(P in D)D[P]=K(D[P]);k.hsl=function(a,c,e){a=T(a,c,e);return"rgb("+a.r+","+a.g+","+a.b+")"};k.linear=function(){function a(g){return i((g-e)*h)}function c(g){var n=Math.min(e,f),o=Math.max(e,f),j=o-n,l=Math.pow(10,Math.floor(Math.log(j/g)/Math.LN10));g=g/(j/l);if(g<=0.15)l*=10;else if(g<=0.35)l*=5;else if(g<=0.75)l*=2;return{start:Math.ceil(n/l)*l,stop:Math.floor(o/l)*l+l*0.5,step:l}}var e=0,f=1,d=0,b=1,h=1/(f-e),i=
<add>k.interpolate(d,b);a.invert=function(g){return(g-d)/h+e};a.domain=function(g){if(!arguments.length)return[e,f];e=g[0];f=g[1];h=1/(f-e);return a};a.range=function(g){if(!arguments.length)return[d,b];d=g[0];b=g[1];i=k.interpolate(d,b);return a};a.ticks=function(g){g=c(g);return k.range(g.start,g.stop,g.step)};a.tickFormat=function(g){g=Math.max(0,-Math.floor(Math.log(c(g).step)/Math.LN10+0.01));return k.format(",."+g+"f")};return a};k.log=function(){function a(e){return c(Math.log(e))}var c=k.linear();
<add>a.invert=function(e){return Math.exp(c.invert(e))};a.domain=function(e){if(!arguments.length)return c.domain().map(Math.exp);c.domain(e.map(Math.log));return a};a.range=function(){var e=c.range.apply(c,arguments);return arguments.length?a:e};return a};k.pow=function(){function a(h){return Math.pow(h,d)}function c(h){return Math.pow(h,b)}function e(h){return f(a(h))}var f=k.linear(),d=1,b=1/d;e.invert=function(h){return c(f.invert(h))};e.domain=function(h){if(!arguments.length)return f.domain().map(c);
<add>f.domain(h.map(a));return e};e.range=function(){var h=f.range.apply(f,arguments);return arguments.length?e:h};e.exponent=function(h){if(!arguments.length)return d;var i=e.domain();d=h;b=1/h;return e.domain(i)};return e};k.sqrt=function(){return k.pow().exponent(0.5)};k.ordinal=function(){function a(b){b=b in e?e[b]:e[b]=c.push(b)-1;return f[b%f.length]}var c=[],e={},f=[],d=0;a.domain=function(b){if(!arguments.length)return c;c=b;e={};for(var h=-1,i=-1,g=c.length;++h<g;){b=c[h];b in e||(e[b]=++i)}return a};
<add>a.range=function(b){if(!arguments.length)return f;f=b;return a};a.rangePoints=function(b,h){if(arguments.length<2)h=0;var i=b[0],g=b[1],n=(g-i)/(c.length-1+h);f=c.length==1?[(i+g)/2]:k.range(i+n*h/2,g+n/2,n);d=0;return a};a.rangeBands=function(b,h){if(arguments.length<2)h=0;var i=b[0],g=b[1],n=(g-i)/(c.length+h);f=k.range(i+n*h,g,n);d=n*(1-h);return a};a.rangeBand=function(){return d};return a};k.category10=function(){return k.ordinal().range(la)};k.category19=function(){return k.ordinal().range(ma)};
<add>k.category20=function(){return k.ordinal().range(na)};var la=["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"],ma=["#9c9ede","#7375b5","#4a5584","#cedb9c","#b5cf6b","#8ca252","#637939","#e7cb94","#e7ba52","#bd9e39","#8c6d31","#e7969c","#d6616b","#ad494a","#843c39","#de9ed6","#ce6dbd","#a55194","#7b4173"],na=["#1f77b4","#aec7e8","#ff7f0e","#ffbb78","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5","#8c564b","#c49c94","#e377c2","#f7b6d2",
<add>"#7f7f7f","#c7c7c7","#bcbd22","#dbdb8d","#17becf","#9edae5"],H=z([[document]]);H[0].parentNode=document.documentElement;k.select=function(a){return typeof a=="string"?H.select(a):z([[a]])};k.selectAll=function(a){return typeof a=="string"?H.selectAll(a):z([C(a)])};k.transition=H.transition;var F=null,N=0,G;k.arc=function(){function a(b){var h=c(b),i=e(b),g=f(b)-Math.PI/2,n=d(b)-Math.PI/2;b=n-g;var o=Math.cos(g);g=Math.sin(g);var j=Math.cos(n);n=Math.sin(n);return"M"+i*o+","+i*g+"A"+i+","+i+" 0 "+
<add>(b<Math.PI?"0":"1")+",1 "+i*j+","+i*n+"L"+h*j+","+h*n+"A"+h+","+h+" 0 "+(b<Math.PI?"0":"1")+",0 "+h*o+","+h*g+"Z"}var c=function(b){return b.innerRadius},e=function(b){return b.outerRadius},f=function(b){return b.startAngle},d=function(b){return b.endAngle};a.innerRadius=function(b){c=typeof b=="function"?b:function(){return b};return a};a.outerRadius=function(b){e=typeof b=="function"?b:function(){return b};return a};a.startAngle=function(b){f=typeof b=="function"?b:function(){return b};return a};
<add>a.endAngle=function(b){d=typeof b=="function"?b:function(){return b};return a};return a};k.line=function(){function a(f){var d=[],b=0,h=f[0];for(d.push("M",c.call(this,h,b),",",e.call(this,h,b));h=f[++b];)d.push("L",c.call(this,h,b),",",e.call(this,h,b));return d.join("")}var c=function(f){return f.x},e=function(f){return f.y};a.x=function(f){c=f;return a};a.y=function(f){e=f;return a};return a};k.area=function(){function a(d){var b=[],h=0,i=d[0];for(b.push("M",c.call(this,i,h),","+e+"V",f.call(this,
<add>i,h));i=d[++h];)b.push("L",c.call(this,i,h),",",f.call(this,i,h));b.push("V"+e+"Z");return b.join("")}var c=function(d){return d.x},e=0,f=function(d){return d.y1};a.x=function(d){c=d;return a};a.y0=function(d){e=d;return a};a.y1=function(d){f=d;return a};return a}})(this);
<ide><path>src/start.js
<ide> (function(_) {
<ide> var d3 = _.d3 = {};
<del> d3.version = "0.1.2"; // semver
<add> d3.version = "0.1.3"; // semver
<ide><path>src/timer.js
<ide> function d3_timer(callback, delay) {
<ide> t0,
<ide> t1 = d3_timer_queue;
<ide>
<add> if (!isFinite(delay)) return;
<add>
<ide> // Scan the queue for earliest callback.
<ide> while (t1) {
<ide> if (t1.callback == callback) {
<ide> function d3_timer(callback, delay) {
<ide>
<ide> if (!d3_timer_interval) {
<ide> clearTimeout(d3_timer_timeout);
<del> d3_timer_timeout = setTimeout(d3_timer_start, Math.min(24, start - now));
<add> d3_timer_timeout = setTimeout(d3_timer_start, Math.max(24, start - now));
<ide> }
<ide> }
<ide> | 4 |
PHP | PHP | update param type in docblock | d77f0c49febe182d5105b7df07456e541a02b1d4 | <ide><path>src/ORM/Marshaller.php
<ide> public function merge(EntityInterface $entity, array $data, array $options = [])
<ide> * the accessible fields list in the entity will be used.
<ide> * - accessibleFields: A list of fields to allow or deny in entity accessible fields.
<ide> *
<del> * @param \Cake\Datasource\EntityInterface[] $entities the entities that will get the
<add> * @param \Cake\Datasource\EntityInterface[]|\Traversable<\Cake\Datasource\EntityInterface> $entities the entities that will get the
<ide> * data merged in
<ide> * @param array $data list of arrays to be merged into the entities
<ide> * @param array $options List of options. | 1 |
Text | Text | add ronag to collaborators | 8d14a8cbcee313591138d233e9944664ea6186bc | <ide><path>README.md
<ide> For information about the governance of the Node.js project, see
<ide> **Refael Ackermann (רפאל פלחי)** <[email protected]> (he/him/הוא/אתה)
<ide> * [richardlau](https://github.com/richardlau) -
<ide> **Richard Lau** <[email protected]>
<add>* [ronag](https://github.com/ronag)
<add>**Robert Nagy** <[email protected]>
<ide> * [ronkorving](https://github.com/ronkorving) -
<ide> **Ron Korving** <[email protected]>
<ide> * [rubys](https://github.com/rubys) - | 1 |
Javascript | Javascript | clarify behaviour of $promise | 08354ae1f749903383a7343bd105630956d8cab0 | <ide><path>src/ngResource/resource.js
<ide> function shallowClearAndCopy(src, dst) {
<ide> * On failure, the promise is resolved with the {@link ng.$http http response} object, without
<ide> * the `resource` property.
<ide> *
<add> * If an interceptor object was provided, the promise will instead be resolved with the value
<add> * returned by the interceptor.
<add> *
<ide> * - `$resolved`: `true` after first server interaction is completed (either with success or
<ide> * rejection), `false` before that. Knowing if the Resource has been resolved is useful in
<ide> * data-binding. | 1 |
Ruby | Ruby | name the argument according with its job | 4818fdd36bacff6e0488d00da160a9d0c398a66e | <ide><path>actionpack/lib/action_dispatch/routing/mapper.rb
<ide> def path_ast(path)
<ide> parser.parse path
<ide> end
<ide>
<del> def dispatcher(defaults)
<del> @set.dispatcher defaults
<add> def dispatcher(raise_on_name_error)
<add> @set.dispatcher raise_on_name_error
<ide> end
<ide> end
<ide> | 1 |
Python | Python | set version to v2.2.2.dev1 | bade60fe6426c5353111c46ad49a4959c2e16c55 | <ide><path>spacy/about.py
<ide> # fmt: off
<ide> __title__ = "spacy"
<del>__version__ = "2.2.2.dev1"
<add>__version__ = "2.2.2.dev2"
<ide> __release__ = True
<ide> __download_url__ = "https://github.com/explosion/spacy-models/releases/download"
<ide> __compatibility__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json" | 1 |
Ruby | Ruby | fix the default frameworks | 30baaac5465a352e78dac6330407a7b3460db180 | <ide><path>railties/lib/initializer.rb
<ide> require "pathname"
<add>require 'railties_path'
<add>require 'rails/version'
<add>require 'rails/gem_dependency'
<add>require 'rails/rack'
<ide>
<ide> module Rails
<ide> class Configuration
<ide> def initialize
<ide> @framework_paths = []
<ide> @load_once_paths = []
<ide> @after_initialize_blocks = []
<del> @frameworks = []
<ide> @plugin_paths = []
<ide> @loaded_plugins = []
<add> @frameworks = default_frameworks
<ide> @plugin_loader = default_plugin_loader
<ide> @plugin_locators = default_plugin_locators
<ide> @gems = default_gems
<ide> def middleware
<ide> ActionController::Dispatcher.middleware
<ide> end
<ide>
<add> def default_frameworks
<add> [ :active_record, :action_controller, :action_view, :action_mailer, :active_resource ]
<add> end
<add>
<ide> def default_plugin_loader
<ide> require 'rails/plugin/loader'
<ide> Plugin::Loader
<ide><path>railties/test/plugin_loader_test.rb
<ide> def setup
<ide>
<ide> @configuration = Rails::Configuration.new
<ide> @configuration.plugin_paths << plugin_fixture_root_path
<del> @initializer = Rails::Initializer.new(@configuration)
<add> @initializer = Rails::Initializer.default
<add> @initializer.config = @configuration
<ide> @valid_plugin_path = plugin_fixture_path('default/stubby')
<ide> @empty_plugin_path = plugin_fixture_path('default/empty')
<ide> | 2 |
Text | Text | remove urls from zlib docs | 4742e4dc3e2222d3b5a03edd4a0468ae77800819 | <ide><path>doc/api/zlib.md
<ide> All of the constants defined in `zlib.h` are also defined on
<ide> `require('zlib').constants`. In the normal course of operations, it will not be
<ide> necessary to use these constants. They are documented so that their presence is
<ide> not surprising. This section is taken almost directly from the
<del>[zlib documentation][]. See <https://zlib.net/manual.html#Constants> for more
<del>details.
<add>[zlib documentation][].
<ide>
<ide> Previously, the constants were available directly from `require('zlib')`, for
<ide> instance `zlib.Z_NO_FLUSH`. Accessing the constants directly from the module is
<ide> ignored by the decompression classes.
<ide> empty dictionary by default)
<ide> * `info` {boolean} (If `true`, returns an object with `buffer` and `engine`.)
<ide>
<del>See the description of `deflateInit2` and `inflateInit2` at
<del><https://zlib.net/manual.html#Advanced> for more information on these.
<add>See the [`deflateInit2` and `inflateInit2`][] documentation for more
<add>information.
<ide>
<ide> ## Class: BrotliOptions
<ide> <!-- YAML
<ide> Decompress a chunk of data with [`Unzip`][].
<ide> [`Inflate`]: #zlib_class_zlib_inflate
<ide> [`TypedArray`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray
<ide> [`Unzip`]: #zlib_class_zlib_unzip
<add>[`deflateInit2` and `inflateInit2`]: https://zlib.net/manual.html#Advanced
<ide> [`stream.Transform`]: stream.html#stream_class_stream_transform
<ide> [`zlib.bytesWritten`]: #zlib_zlib_byteswritten
<ide> [Brotli parameters]: #zlib_brotli_constants | 1 |
Javascript | Javascript | add proper spacing between array items | 28514094a4d9de75629cb4a1e42ba8159ce665c2 | <ide><path>packages/ember-routing-htmlbars/tests/helpers/closure_action_test.js
<ide> QUnit.test('objects that define INVOKE can be casted to actions', function(asser
<ide>
<ide> innerComponent = EmberComponent.extend({
<ide> fireAction() {
<del> assert.equal(this.attrs.submit(4,5,6), 123);
<add> assert.equal(this.attrs.submit(4, 5, 6), 123);
<ide> }
<ide> }).create();
<ide>
<ide> QUnit.test('objects that define INVOKE can be casted to actions', function(asser
<ide> submitTask: computed(function() {
<ide> return {
<ide> [INVOKE]: (...args) => {
<del> assert.deepEqual(args, [1,2,3,4,5,6]);
<add> assert.deepEqual(args, [1, 2, 3, 4, 5, 6]);
<ide> return this.foo;
<ide> }
<ide> }; | 1 |
Javascript | Javascript | make coverage work for node.js | 616fac9169840c76512920e66b6428971df3d289 | <ide><path>lib/internal/bootstrap/loaders.js
<ide> NativeModule._cache[this.id] = this;
<ide> };
<ide>
<add> // coverage must be turned on early, so that we can collect
<add> // it for Node.js' own internal libraries.
<add> if (process.env.NODE_V8_COVERAGE) {
<add> NativeModule.require('internal/process/coverage').setup();
<add> }
<add>
<ide> // This will be passed to the bootstrapNodeJSCore function in
<ide> // bootstrap/node.js.
<ide> return loaderExports;
<ide><path>lib/internal/bootstrap/node.js
<ide> NativeModule.require('internal/process/write-coverage').setup();
<ide>
<ide> if (process.env.NODE_V8_COVERAGE) {
<del> const { resolve } = NativeModule.require('path');
<del> process.env.NODE_V8_COVERAGE = resolve(process.env.NODE_V8_COVERAGE);
<del> NativeModule.require('internal/process/coverage').setup();
<add> NativeModule.require('internal/process/coverage').setupExitHooks();
<ide> }
<ide>
<ide> if (process.config.variables.v8_enable_inspector) {
<ide><path>lib/internal/process/coverage.js
<ide> 'use strict';
<del>const path = require('path');
<del>const { mkdirSync, writeFileSync } = require('fs');
<del>const hasInspector = process.config.variables.v8_enable_inspector === 1;
<del>let inspector = null;
<del>if (hasInspector) inspector = require('inspector');
<del>
<del>let session;
<add>let coverageConnection = null;
<add>let coverageDirectory;
<ide>
<ide> function writeCoverage() {
<del> if (!session) {
<add> if (!coverageConnection && coverageDirectory) {
<ide> return;
<ide> }
<ide>
<add> const { join } = require('path');
<add> const { mkdirSync, writeFileSync } = require('fs');
<ide> const { threadId } = require('internal/worker');
<ide>
<ide> const filename = `coverage-${process.pid}-${Date.now()}-${threadId}.json`;
<ide> try {
<del> // TODO(bcoe): switch to mkdirp once #22302 is addressed.
<del> mkdirSync(process.env.NODE_V8_COVERAGE);
<add> mkdirSync(coverageDirectory, { recursive: true });
<ide> } catch (err) {
<ide> if (err.code !== 'EEXIST') {
<ide> console.error(err);
<ide> return;
<ide> }
<ide> }
<ide>
<del> const target = path.join(process.env.NODE_V8_COVERAGE, filename);
<del>
<add> const target = join(coverageDirectory, filename);
<ide> try {
<del> session.post('Profiler.takePreciseCoverage', (err, coverageInfo) => {
<del> if (err) return console.error(err);
<del> try {
<del> writeFileSync(target, JSON.stringify(coverageInfo));
<del> } catch (err) {
<del> console.error(err);
<del> }
<del> });
<add> disableAllAsyncHooks();
<add> let msg;
<add> coverageConnection._coverageCallback = function(_msg) {
<add> msg = _msg;
<add> };
<add> coverageConnection.dispatch(JSON.stringify({
<add> id: 3,
<add> method: 'Profiler.takePreciseCoverage'
<add> }));
<add> const coverageInfo = JSON.parse(msg).result;
<add> writeFileSync(target, JSON.stringify(coverageInfo));
<ide> } catch (err) {
<ide> console.error(err);
<ide> } finally {
<del> session.disconnect();
<del> session = null;
<add> coverageConnection.disconnect();
<add> coverageConnection = null;
<ide> }
<ide> }
<ide>
<add>function disableAllAsyncHooks() {
<add> const { getHookArrays } = require('internal/async_hooks');
<add> const [hooks_array] = getHookArrays();
<add> hooks_array.forEach((hook) => { hook.disable(); });
<add>}
<add>
<ide> exports.writeCoverage = writeCoverage;
<ide>
<ide> function setup() {
<del> if (!hasInspector) {
<del> console.warn('coverage currently only supported in main thread');
<add> const { Connection } = process.binding('inspector');
<add> if (!Connection) {
<add> console.warn('inspector not enabled');
<ide> return;
<ide> }
<ide>
<del> session = new inspector.Session();
<del> session.connect();
<del> session.post('Profiler.enable');
<del> session.post('Profiler.startPreciseCoverage', { callCount: true,
<del> detailed: true });
<add> coverageConnection = new Connection((res) => {
<add> if (coverageConnection._coverageCallback) {
<add> coverageConnection._coverageCallback(res);
<add> }
<add> });
<add> coverageConnection.dispatch(JSON.stringify({
<add> id: 1,
<add> method: 'Profiler.enable'
<add> }));
<add> coverageConnection.dispatch(JSON.stringify({
<add> id: 2,
<add> method: 'Profiler.startPreciseCoverage',
<add> params: {
<add> callCount: true,
<add> detailed: true
<add> }
<add> }));
<ide>
<del> const reallyReallyExit = process.reallyExit;
<add> try {
<add> const { resolve } = require('path');
<add> coverageDirectory = process.env.NODE_V8_COVERAGE =
<add> resolve(process.env.NODE_V8_COVERAGE);
<add> } catch (err) {
<add> console.error(err);
<add> }
<add>}
<ide>
<add>exports.setup = setup;
<add>
<add>function setupExitHooks() {
<add> const reallyReallyExit = process.reallyExit;
<ide> process.reallyExit = function(code) {
<ide> writeCoverage();
<ide> reallyReallyExit(code);
<ide> function setup() {
<ide> process.on('exit', writeCoverage);
<ide> }
<ide>
<del>exports.setup = setup;
<add>exports.setupExitHooks = setupExitHooks;
<ide><path>test/fixtures/v8-coverage/async-hooks.js
<add>const async_hooks = require('async_hooks');
<add>const common = require('../../common');
<add>
<add>const hook = async_hooks.createHook({
<add> init: common.mustNotCall(),
<add> before: common.mustNotCall(),
<add> after: common.mustNotCall(),
<add> destroy: common.mustNotCall()
<add>});
<add>
<add>hook.enable();
<ide><path>test/parallel/test-heapdump-inspector.js
<ide> common.skipIfInspectorDisabled();
<ide> const { validateSnapshotNodes } = require('../common/heap');
<ide> const inspector = require('inspector');
<ide>
<del>const session = new inspector.Session();
<del>validateSnapshotNodes('Node / JSBindingsConnection', []);
<del>session.connect();
<del>validateSnapshotNodes('Node / JSBindingsConnection', [
<del> {
<del> children: [
<del> { node_name: 'Node / InspectorSession', edge_name: 'session' },
<del> { node_name: 'Connection', edge_name: 'wrapped' },
<del> (edge) => edge.name === 'callback' &&
<del> (edge.to.type === undefined || // embedded graph
<del> edge.to.type === 'closure') // snapshot
<del> ]
<add>const snapshotNode = {
<add> children: [
<add> { node_name: 'Node / InspectorSession', edge_name: 'session' }
<add> ]
<add>};
<add>
<add>// starts with no JSBindingsConnection (or 1 if coverage enabled).
<add>{
<add> const expected = [];
<add> if (process.env.NODE_V8_COVERAGE) {
<add> expected.push(snapshotNode);
<add> }
<add> validateSnapshotNodes('Node / JSBindingsConnection', expected);
<add>}
<add>
<add>// JSBindingsConnection should be added.
<add>{
<add> const session = new inspector.Session();
<add> session.connect();
<add> const expected = [
<add> {
<add> children: [
<add> { node_name: 'Node / InspectorSession', edge_name: 'session' },
<add> { node_name: 'Connection', edge_name: 'wrapped' },
<add> (edge) => edge.name === 'callback' &&
<add> (edge.to.type === undefined || // embedded graph
<add> edge.to.type === 'closure') // snapshot
<add> ]
<add> }
<add> ];
<add> if (process.env.NODE_V8_COVERAGE) {
<add> expected.push(snapshotNode);
<ide> }
<del>]);
<add> validateSnapshotNodes('Node / JSBindingsConnection', expected);
<add>}
<ide><path>test/parallel/test-v8-coverage.js
<ide> function nextdir() {
<ide> assert.strictEqual(fixtureCoverage, undefined);
<ide> }
<ide>
<add>// disables async hooks before writing coverage.
<add>{
<add> const coverageDirectory = path.join(tmpdir.path, nextdir());
<add> const output = spawnSync(process.execPath, [
<add> require.resolve('../fixtures/v8-coverage/async-hooks')
<add> ], { env: { ...process.env, NODE_V8_COVERAGE: coverageDirectory } });
<add> assert.strictEqual(output.status, 0);
<add> const fixtureCoverage = getFixtureCoverage('async-hooks.js',
<add> coverageDirectory);
<add> assert.ok(fixtureCoverage);
<add> // first branch executed.
<add> assert.strictEqual(fixtureCoverage.functions[1].ranges[0].count, 1);
<add>}
<add>
<ide> // extracts the coverage object for a given fixture name.
<ide> function getFixtureCoverage(fixtureFile, coverageDirectory) {
<ide> const coverageFiles = fs.readdirSync(coverageDirectory);
<ide><path>test/sequential/test-inspector-enabled.js
<ide> assert(
<ide> `;
<ide>
<ide> const args = ['--inspect', '-e', script];
<del>const child = spawn(process.execPath, args, { stdio: 'inherit' });
<add>const child = spawn(process.execPath, args, {
<add> stdio: 'inherit',
<add> env: { ...process.env, NODE_V8_COVERAGE: '' }
<add>});
<ide> child.on('exit', (code, signal) => {
<ide> process.exit(code || signal);
<ide> }); | 7 |
Ruby | Ruby | avoid extra array allocations | 5bf652ecddff309934184f781059f677c7ff3a6f | <ide><path>Library/Homebrew/options.rb
<ide> def self.coerce(arg)
<ide> when self then arg
<ide> when Option then new << arg
<ide> when Array
<del> opts = arg.map do |_arg|
<del> case _arg
<del> when /^-[^-]+$/ then _arg[1..-1].split(//)
<del> else _arg
<add> opts = new
<add> arg.each do |a|
<add> case a
<add> when /^-[^-]+$/
<add> a[1..-1].split(//).each { |o| opts << Option.new(o) }
<add> else
<add> opts << Option.new(a)
<ide> end
<del> end.flatten
<del> new(opts.map { |o| Option.new(o) })
<add> end
<add> opts
<ide> else
<ide> raise TypeError, "Cannot convert #{arg.inspect} to Options"
<ide> end
<ide><path>Library/Homebrew/version.rb
<ide> def to_s
<ide> protected
<ide>
<ide> def to_a
<del> @array ||= @version.scan(/\d+|[a-zA-Z]+/).map { |e| VersionElement.new(e) }
<add> @array ||= @version.scan(/\d+|[a-zA-Z]+/).map! { |e| VersionElement.new(e) }
<ide> end
<ide>
<ide> def self.parse spec | 2 |
Ruby | Ruby | set correct compiler symbol for gcc 4.0" | 1dcf726a596001f204ff21f667447da15b76c030 | <ide><path>Library/Homebrew/extend/ENV/std.rb
<ide> def gcc_4_0_1
<ide> self.cxx = "#{MacOS.dev_tools_path}/g++-4.0"
<ide> replace_in_cflags '-O4', '-O3'
<ide> set_cpu_cflags '-march=nocona -mssse3'
<del> @compiler = :gcc_4_0
<add> @compiler = :gcc
<ide> end
<ide> alias_method :gcc_4_0, :gcc_4_0_1
<ide> | 1 |
Javascript | Javascript | remove needless operations in tests | 10024c25820f08139f11d924cec552a26dfbba18 | <ide><path>test/unit/effects.js
<ide> if ( !jQuery.fx ) {
<ide> return;
<ide> }
<ide>
<del>var off = jQuery.fx.off;
<del>
<ide> module("effects", {
<ide> setup: function() {
<ide> this.clock = sinon.useFakeTimers( 505877050 );
<ide> module("effects", {
<ide> jQuery.now = Date.now;
<ide> jQuery.fx.stop();
<ide> jQuery.fx.interval = this._oldInterval;
<del> jQuery.fx.off = off;
<ide> return moduleTeardown.apply( this, arguments );
<ide> }
<ide> }); | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.