content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
PHP
PHP
fix mixed indentation
c1a6afaf9c0be16d17a46a7ae1e03a08b2e247eb
<ide><path>src/Database/Schema/PostgresSchema.php <ide> public function describeColumnSql($tableName, $config) <ide> { <ide> $sql = <ide> 'SELECT DISTINCT table_schema AS schema, column_name AS name, data_type AS type, <del> is_nullable AS null, column_default AS default, <del> character_maximum_length AS char_length, <del> d.description as comment, <del> ordinal_position <del> FROM information_schema.columns c <del> INNER JOIN pg_catalog.pg_namespace ns ON (ns.nspname = table_schema) <del> INNER JOIN pg_catalog.pg_class cl ON (cl.relnamespace = ns.oid AND cl.relname = table_name) <del> LEFT JOIN pg_catalog.pg_index i ON (i.indrelid = cl.oid AND i.indkey[0] = c.ordinal_position) <del> LEFT JOIN pg_catalog.pg_description d on (cl.oid = d.objoid AND d.objsubid = c.ordinal_position) <del> WHERE table_name = ? AND table_schema = ? AND table_catalog = ? <del> ORDER BY ordinal_position'; <add> is_nullable AS null, column_default AS default, <add> character_maximum_length AS char_length, <add> d.description as comment, <add> ordinal_position <add> FROM information_schema.columns c <add> INNER JOIN pg_catalog.pg_namespace ns ON (ns.nspname = table_schema) <add> INNER JOIN pg_catalog.pg_class cl ON (cl.relnamespace = ns.oid AND cl.relname = table_name) <add> LEFT JOIN pg_catalog.pg_index i ON (i.indrelid = cl.oid AND i.indkey[0] = c.ordinal_position) <add> LEFT JOIN pg_catalog.pg_description d on (cl.oid = d.objoid AND d.objsubid = c.ordinal_position) <add> WHERE table_name = ? AND table_schema = ? AND table_catalog = ? <add> ORDER BY ordinal_position'; <ide> <ide> $schema = empty($config['schema']) ? 'public' : $config['schema']; <ide> return [$sql, [$tableName, $schema, $config['database']]]; <ide> protected function _defaultValue($default) <ide> public function describeIndexSql($tableName, $config) <ide> { <ide> $sql = 'SELECT <del> c2.relname, <del> i.indisprimary, <del> i.indisunique, <del> i.indisvalid, <del> pg_catalog.pg_get_indexdef(i.indexrelid, 0, true) AS statement <del> FROM pg_catalog.pg_class AS c, <del> pg_catalog.pg_class AS c2, <del> pg_catalog.pg_index AS i <del> WHERE c.oid = ( <del> SELECT c.oid <del> FROM pg_catalog.pg_class c <del> LEFT JOIN pg_catalog.pg_namespace AS n ON n.oid = c.relnamespace <del> WHERE c.relname = ? <del> AND n.nspname = ? <del> ) <del> AND c.oid = i.indrelid <del> AND i.indexrelid = c2.oid <del> ORDER BY i.indisprimary DESC, i.indisunique DESC, c2.relname'; <add> c2.relname, <add> i.indisprimary, <add> i.indisunique, <add> i.indisvalid, <add> pg_catalog.pg_get_indexdef(i.indexrelid, 0, true) AS statement <add> FROM pg_catalog.pg_class AS c, <add> pg_catalog.pg_class AS c2, <add> pg_catalog.pg_index AS i <add> WHERE c.oid = ( <add> SELECT c.oid <add> FROM pg_catalog.pg_class c <add> LEFT JOIN pg_catalog.pg_namespace AS n ON n.oid = c.relnamespace <add> WHERE c.relname = ? <add> AND n.nspname = ? <add> ) <add> AND c.oid = i.indrelid <add> AND i.indexrelid = c2.oid <add> ORDER BY i.indisprimary DESC, i.indisunique DESC, c2.relname'; <ide> <ide> $schema = 'public'; <ide> if (!empty($config['schema'])) { <ide><path>src/Database/Schema/SqlserverSchema.php <ide> class SqlserverSchema extends BaseSchema <ide> */ <ide> public function listTablesSql($config) <ide> { <del> $sql = ' <del> SELECT TABLE_NAME <del> FROM INFORMATION_SCHEMA.TABLES <del> WHERE TABLE_SCHEMA = ? <del> ORDER BY TABLE_NAME <del> '; <add> $sql = 'SELECT TABLE_NAME <add> FROM INFORMATION_SCHEMA.TABLES <add> WHERE TABLE_SCHEMA = ? <add> ORDER BY TABLE_NAME'; <ide> $schema = empty($config['schema']) ? static::DEFAULT_SCHEMA_NAME : $config['schema']; <ide> return [$sql, [$schema]]; <ide> } <ide> public function listTablesSql($config) <ide> */ <ide> public function describeColumnSql($tableName, $config) <ide> { <del> $sql = <del> "SELECT DISTINCT TABLE_SCHEMA AS [schema], COLUMN_NAME AS [name], DATA_TYPE AS [type], <del> IS_NULLABLE AS [null], COLUMN_DEFAULT AS [default], <del> CHARACTER_MAXIMUM_LENGTH AS [char_length], <del> NUMERIC_PRECISION AS [precision], <del> NUMERIC_SCALE AS [scale], <del> '' AS [comment], ORDINAL_POSITION AS [ordinal_position] <del> FROM INFORMATION_SCHEMA.COLUMNS <del> WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ? <del> ORDER BY ordinal_position"; <add> $sql = "SELECT DISTINCT TABLE_SCHEMA AS [schema], COLUMN_NAME AS [name], DATA_TYPE AS [type], <add> IS_NULLABLE AS [null], COLUMN_DEFAULT AS [default], <add> CHARACTER_MAXIMUM_LENGTH AS [char_length], <add> NUMERIC_PRECISION AS [precision], <add> NUMERIC_SCALE AS [scale], <add> '' AS [comment], ORDINAL_POSITION AS [ordinal_position] <add> FROM INFORMATION_SCHEMA.COLUMNS <add> WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ? <add> ORDER BY ordinal_position"; <ide> <ide> $schema = empty($config['schema']) ? static::DEFAULT_SCHEMA_NAME : $config['schema']; <ide> return [$sql, [$tableName, $schema]]; <ide> public function convertColumnDescription(Table $table, $row) <ide> */ <ide> public function describeIndexSql($tableName, $config) <ide> { <del> $sql = " <del> SELECT <del> I.[name] AS [index_name], <del> IC.[index_column_id] AS [index_order], <del> AC.[name] AS [column_name], <del> I.[is_unique], I.[is_primary_key], <del> I.[is_unique_constraint] <del> FROM sys.[tables] AS T <del> INNER JOIN sys.[schemas] S ON S.[schema_id] = T.[schema_id] <del> INNER JOIN sys.[indexes] I ON T.[object_id] = I.[object_id] <del> INNER JOIN sys.[index_columns] IC ON I.[object_id] = IC.[object_id] AND I.[index_id] = IC.[index_id] <del> INNER JOIN sys.[all_columns] AC ON T.[object_id] = AC.[object_id] AND IC.[column_id] = AC.[column_id] <del> WHERE T.[is_ms_shipped] = 0 AND I.[type_desc] <> 'HEAP' AND T.[name] = ? AND S.[name] = ? <del> ORDER BY I.[index_id], IC.[index_column_id] <del> "; <add> $sql = "SELECT <add> I.[name] AS [index_name], <add> IC.[index_column_id] AS [index_order], <add> AC.[name] AS [column_name], <add> I.[is_unique], I.[is_primary_key], <add> I.[is_unique_constraint] <add> FROM sys.[tables] AS T <add> INNER JOIN sys.[schemas] S ON S.[schema_id] = T.[schema_id] <add> INNER JOIN sys.[indexes] I ON T.[object_id] = I.[object_id] <add> INNER JOIN sys.[index_columns] IC ON I.[object_id] = IC.[object_id] AND I.[index_id] = IC.[index_id] <add> INNER JOIN sys.[all_columns] AC ON T.[object_id] = AC.[object_id] AND IC.[column_id] = AC.[column_id] <add> WHERE T.[is_ms_shipped] = 0 AND I.[type_desc] <> 'HEAP' AND T.[name] = ? AND S.[name] = ? <add> ORDER BY I.[index_id], IC.[index_column_id]"; <ide> <ide> $schema = empty($config['schema']) ? static::DEFAULT_SCHEMA_NAME : $config['schema']; <ide> return [$sql, [$tableName, $schema]]; <ide> public function convertIndexDescription(Table $table, $row) <ide> */ <ide> public function describeForeignKeySql($tableName, $config) <ide> { <del> $sql = " <del> SELECT FK.[name] AS [foreign_key_name], FK.[delete_referential_action_desc] AS [delete_type], <del> FK.[update_referential_action_desc] AS [update_type], C.name AS [column], RT.name AS [reference_table], <del> RC.name AS [reference_column] <del> FROM sys.foreign_keys FK <del> INNER JOIN sys.foreign_key_columns FKC ON FKC.constraint_object_id = FK.object_id <del> INNER JOIN sys.tables T ON T.object_id = FKC.parent_object_id <del> INNER JOIN sys.tables RT ON RT.object_id = FKC.referenced_object_id <del> INNER JOIN sys.schemas S ON S.schema_id = T.schema_id AND S.schema_id = RT.schema_id <del> INNER JOIN sys.columns C ON C.column_id = FKC.parent_column_id AND C.object_id = FKC.parent_object_id <del> INNER JOIN sys.columns RC ON RC.column_id = FKC.referenced_column_id AND RC.object_id = FKC.referenced_object_id <del> WHERE FK.is_ms_shipped = 0 AND T.name = ? AND S.name = ? <del> "; <add> $sql = "SELECT FK.[name] AS [foreign_key_name], FK.[delete_referential_action_desc] AS [delete_type], <add> FK.[update_referential_action_desc] AS [update_type], C.name AS [column], RT.name AS [reference_table], <add> RC.name AS [reference_column] <add> FROM sys.foreign_keys FK <add> INNER JOIN sys.foreign_key_columns FKC ON FKC.constraint_object_id = FK.object_id <add> INNER JOIN sys.tables T ON T.object_id = FKC.parent_object_id <add> INNER JOIN sys.tables RT ON RT.object_id = FKC.referenced_object_id <add> INNER JOIN sys.schemas S ON S.schema_id = T.schema_id AND S.schema_id = RT.schema_id <add> INNER JOIN sys.columns C ON C.column_id = FKC.parent_column_id AND C.object_id = FKC.parent_object_id <add> INNER JOIN sys.columns RC ON RC.column_id = FKC.referenced_column_id AND RC.object_id = FKC.referenced_object_id <add> WHERE FK.is_ms_shipped = 0 AND T.name = ? AND S.name = ?"; <ide> <ide> $schema = empty($config['schema']) ? static::DEFAULT_SCHEMA_NAME : $config['schema']; <ide> return [$sql, [$tableName, $schema]];
2
Javascript
Javascript
show loader when loading view / partial
19973609f43af781b1c4467f3acbc42b3a8f791e
<ide><path>docs/app/src/docs.js <ide> angular.module('DocsController', []) <ide> $scope.$on('$includeContentLoaded', function() { <ide> var pagePath = $scope.currentPage ? $scope.currentPage.path : $location.path(); <ide> $window._gaq.push(['_trackPageview', pagePath]); <add> $scope.loading = false; <add> }); <add> <add> $scope.$on('$includeContentError', function() { <add> $scope.loading = false; <ide> }); <ide> <ide> $scope.$watch(function docsPathWatch() {return $location.path(); }, function docsPathWatchAction(path) { <ide> angular.module('DocsController', []) <ide> <ide> var currentPage = $scope.currentPage = NG_PAGES[path]; <ide> <add> $scope.loading = true; <add> <ide> if (currentPage) { <ide> $scope.partialPath = 'partials/' + path + '.html'; <ide> $scope.currentArea = NG_NAVIGATION[currentPage.area];
1
Ruby
Ruby
fix another filesystem leak in updater tests
3f3b7746dda4a36a05ad3c6bda32526dbeea5c19
<ide><path>Library/Homebrew/test/test_updater.rb <ide> def setup <ide> @report = Report.new <ide> end <ide> <add> def teardown <add> FileUtils.rm_rf HOMEBREW_LIBRARY.join("Taps") <add> end <add> <ide> def perform_update(fixture_name="") <ide> @updater.diff = fixture(fixture_name) <ide> @updater.in_repo_expect("git checkout -q master")
1
Python
Python
add tf2 camembert model
a3998e76ae36b6fe5be9628755d5a536ed037dc2
<ide><path>src/transformers/__init__.py <ide> from .configuration_mmbt import MMBTConfig <ide> from .configuration_openai import OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, OpenAIGPTConfig <ide> from .configuration_roberta import ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, RobertaConfig <add>from .configuration_camembert import CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CamembertConfig <ide> from .configuration_t5 import T5_PRETRAINED_CONFIG_ARCHIVE_MAP, T5Config <ide> from .configuration_transfo_xl import TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, TransfoXLConfig <ide> <ide> RobertaForQuestionAnswering, <ide> ROBERTA_PRETRAINED_MODEL_ARCHIVE_MAP, <ide> ) <add> from .modeling_camembert import ( <add> CamembertForMaskedLM, <add> CamembertModel, <add> CamembertForSequenceClassification, <add> CamembertForTokenClassification, <add> CAMEMBERT_PRETRAINED_MODEL_ARCHIVE_MAP, <add> ) <ide> from .modeling_distilbert import ( <ide> DistilBertPreTrainedModel, <ide> DistilBertForMaskedLM, <ide> TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_MAP, <ide> ) <ide> <add> from .modeling_tf_camembert import ( <add> TFCamembertModel, <add> TFCamembertForMaskedLM, <add> TFCamembertForSequenceClassification, <add> TFCamembertForTokenClassification, <add> TF_CAMEMBERT_PRETRAINED_MODEL_ARCHIVE_MAP, <add> ) <add> <ide> from .modeling_tf_distilbert import ( <ide> TFDistilBertPreTrainedModel, <ide> TFDistilBertMainLayer, <ide><path>src/transformers/convert_pytorch_checkpoint_to_tf2.py <ide> GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, <ide> OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, <ide> ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, <add> CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, <ide> T5_PRETRAINED_CONFIG_ARCHIVE_MAP, <ide> TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, <ide> XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, <ide> GPT2Config, <ide> OpenAIGPTConfig, <ide> RobertaConfig, <add> CamembertConfig, <ide> T5Config, <ide> TFAlbertForMaskedLM, <ide> TFBertForPreTraining, <ide> TFOpenAIGPTLMHeadModel, <ide> TFRobertaForMaskedLM, <ide> TFRobertaForSequenceClassification, <add> TFCamembertForMaskedLM, <add> TFCamembertForSequenceClassification, <ide> TFT5WithLMHeadModel, <ide> TFTransfoXLLMHeadModel, <ide> TFXLMRobertaForMaskedLM, <ide> RobertaForMaskedLM, <ide> RobertaForSequenceClassification, <ide> ROBERTA_PRETRAINED_MODEL_ARCHIVE_MAP, <add> CamembertForMaskedLM, <add> CamembertForSequenceClassification, <add> CAMEMBERT_PRETRAINED_MODEL_ARCHIVE_MAP, <ide> DistilBertForMaskedLM, <ide> DistilBertForQuestionAnswering, <ide> DistilBertForSequenceClassification, <ide> RobertaForMaskedLM, <ide> RobertaForSequenceClassification, <ide> ROBERTA_PRETRAINED_MODEL_ARCHIVE_MAP, <add> CamembertForMaskedLM, <add> CamembertForSequenceClassification, <add> CAMEMBERT_PRETRAINED_MODEL_ARCHIVE_MAP, <ide> DistilBertForMaskedLM, <ide> DistilBertForSequenceClassification, <ide> DistilBertForQuestionAnswering, <ide> None, <ide> None, <ide> None, <add> None, <add> None, <add> None, <ide> ) <ide> <ide> <ide> ROBERTA_PRETRAINED_MODEL_ARCHIVE_MAP, <ide> ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, <ide> ), <add> "camembert": ( <add> CamembertConfig, <add> TFCamembertForMaskedLM, <add> CamembertForMaskedLM, <add> CAMEMBERT_PRETRAINED_MODEL_ARCHIVE_MAP, <add> CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, <add> ), <ide> "distilbert": ( <ide> DistilBertConfig, <ide> TFDistilBertForMaskedLM, <ide><path>src/transformers/modeling_tf_camembert.py <add># coding=utf-8 <add># Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. <add># Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. <add># <add># Licensed under the Apache License, Version 2.0 (the "License"); <add># you may not use this file except in compliance with the License. <add># You may obtain a copy of the License at <add># <add># http://www.apache.org/licenses/LICENSE-2.0 <add># <add># Unless required by applicable law or agreed to in writing, software <add># distributed under the License is distributed on an "AS IS" BASIS, <add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add># See the License for the specific language governing permissions and <add># limitations under the License. <add>""" TF 2.0 RoBERTa model. """ <add> <add> <add>import logging <add> <add>import tensorflow as tf <add> <add>from .configuration_camembert import CamembertConfig <add>from .file_utils import add_start_docstrings <add>from .modeling_tf_roberta import ( <add> TFRobertaForMaskedLM, <add> TFRobertaForSequenceClassification, <add> TFRobertaForTokenClassification, <add> TFRobertaModel, <add>) <add> <add>logger = logging.getLogger(__name__) <add> <add>TF_CAMEMBERT_PRETRAINED_MODEL_ARCHIVE_MAP = { <add> #"camembert-base": "https://s3.amazonaws.com/models.huggingface.co/bert/camembert-base-tf_model.h5" <add>} <add> <add> <add>CAMEMBERT_START_DOCSTRING = r""" The CamemBERT model was proposed in <add> `CamemBERT: a Tasty French Language Model`_ <add> by Louis Martin, Benjamin Muller, Pedro Javier Ortiz Suárez, Yoann Dupont, Laurent Romary, Éric Villemonte de la Clergerie, Djamé Seddah, and Benoît Sagot. It is based on Facebook's RoBERTa model released in 2019. <add> <add> It is a model trained on 138GB of French text. <add> <add> This implementation is the same as RoBERTa. <add> <add> This model is a tf.keras.Model `tf.keras.Model`_ sub-class. Use it as a regular TF 2.0 Keras Model and <add> refer to the TF 2.0 documentation for all matter related to general usage and behavior. <add> <add> .. _`CamemBERT: a Tasty French Language Model`: <add> https://arxiv.org/abs/1911.03894 <add> <add> .. _`tf.keras.Model`: <add> https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/keras/Model <add> <add> Note on the model inputs: <add> TF 2.0 models accepts two formats as inputs: <add> <add> - having all inputs as keyword arguments (like PyTorch models), or <add> - having all inputs as a list, tuple or dict in the first positional arguments. <add> <add> This second option is usefull when using `tf.keras.Model.fit()` method which currently requires having all the tensors in the first argument of the model call function: `model(inputs)`. <add> <add> If you choose this second option, there are three possibilities you can use to gather all the input Tensors in the first positional argument : <add> <add> - a single Tensor with input_ids only and nothing else: `model(inputs_ids) <add> - a list of varying length with one or several input Tensors IN THE ORDER given in the docstring: <add> `model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])` <add> - a dictionary with one or several input Tensors associaed to the input names given in the docstring: <add> `model({'input_ids': input_ids, 'token_type_ids': token_type_ids})` <add> <add> Parameters: <add> config (:class:`~transformers.CamembertConfig`): Model configuration class with all the parameters of the <add> model. Initializing with a config file does not load the weights associated with the model, only the configuration. <add> Check out the :meth:`~transformers.PreTrainedModel.from_pretrained` method to load the model weights. <add>""" <add> <add>CAMEMBERT_INPUTS_DOCSTRING = r""" <add> Inputs: <add> **input_ids**: ``Numpy array`` or ``tf.Tensor`` of shape ``(batch_size, sequence_length)``: <add> Indices of input sequence tokens in the vocabulary. <add> To match pre-training, CamemBERT input sequence should be formatted with <s> and </s> tokens as follows: <add> <add> (a) For sequence pairs: <add> <add> ``tokens: <s> Is this Jacksonville ? </s> </s> No it is not . </s>`` <add> <add> (b) For single sequences: <add> <add> ``tokens: <s> the dog is hairy . </s>`` <add> <add> Fully encoded sequences or sequence pairs can be obtained using the CamembertTokenizer.encode function with <add> the ``add_special_tokens`` parameter set to ``True``. <add> <add> CamemBERT is a model with absolute position embeddings so it's usually advised to pad the inputs on <add> the right rather than the left. <add> <add> See :func:`transformers.PreTrainedTokenizer.encode` and <add> :func:`transformers.PreTrainedTokenizer.convert_tokens_to_ids` for details. <add> **attention_mask**: (`optional`) ``Numpy array`` or ``tf.Tensor`` of shape ``(batch_size, sequence_length)``: <add> Mask to avoid performing attention on padding token indices. <add> Mask values selected in ``[0, 1]``: <add> ``1`` for tokens that are NOT MASKED, ``0`` for MASKED tokens. <add> **token_type_ids**: (`optional` need to be trained) ``Numpy array`` or ``tf.Tensor`` of shape ``(batch_size, sequence_length)``: <add> Optional segment token indices to indicate first and second portions of the inputs. <add> This embedding matrice is not trained (not pretrained during CamemBERT pretraining), you will have to train it <add> during finetuning. <add> Indices are selected in ``[0, 1]``: ``0`` corresponds to a `sentence A` token, ``1`` <add> corresponds to a `sentence B` token <add> (see `BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding`_ for more details). <add> **position_ids**: (`optional`) ``Numpy array`` or ``tf.Tensor`` of shape ``(batch_size, sequence_length)``: <add> Indices of positions of each input sequence tokens in the position embeddings. <add> Selected in the range ``[0, config.max_position_embeddings - 1[``. <add> **head_mask**: (`optional`) ``Numpy array`` or ``tf.Tensor`` of shape ``(num_heads,)`` or ``(num_layers, num_heads)``: <add> Mask to nullify selected heads of the self-attention modules. <add> Mask values selected in ``[0, 1]``: <add> ``1`` indicates the head is **not masked**, ``0`` indicates the head is **masked**. <add> **inputs_embeds**: (`optional`) ``Numpy array`` or ``tf.Tensor`` of shape ``(batch_size, sequence_length, embedding_dim)``: <add> Optionally, instead of passing ``input_ids`` you can choose to directly pass an embedded representation. <add> This is useful if you want more control over how to convert `input_ids` indices into associated vectors <add> than the model's internal embedding lookup matrix. <add>""" <add> <add> <add>@add_start_docstrings( <add> "The bare CamemBERT Model transformer outputting raw hidden-states without any specific head on top.", <add> CAMEMBERT_START_DOCSTRING, <add> CAMEMBERT_INPUTS_DOCSTRING, <add>) <add>class TFCamembertModel(TFRobertaModel): <add> r""" <add> Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs: <add> **last_hidden_state**: ``torch.FloatTensor`` of shape ``(batch_size, sequence_length, hidden_size)`` <add> Sequence of hidden-states at the output of the last layer of the model. <add> **pooler_output**: ``torch.FloatTensor`` of shape ``(batch_size, hidden_size)`` <add> Last layer hidden-state of the first token of the sequence (classification token) <add> further processed by a Linear layer and a Tanh activation function. The Linear <add> layer weights are trained from the next sentence prediction (classification) <add> eo match pre-training, CamemBERT input sequence should be formatted with [CLS] and [SEP] tokens as follows: <add> <add> (a) For sequence pairs: <add> <add> ``tokens: [CLS] is this jack ##son ##ville ? [SEP] [SEP] no it is not . [SEP]`` <add> <add> ``token_type_ids: 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1`` <add> <add> (b) For single sequences: <add> <add> ``tokens: [CLS] the dog is hairy . [SEP]`` <add> <add> ``token_type_ids: 0 0 0 0 0 0 0`` <add> <add> objective during Bert pretraining. This output is usually *not* a good summary <add> of the semantic content of the input, you're often better with averaging or pooling <add> the sequence of hidden-states for the whole input sequence. <add> **hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``) <add> list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings) <add> of shape ``(batch_size, sequence_length, hidden_size)``: <add> Hidden-states of the model at the output of each layer plus the initial embedding outputs. <add> **attentions**: (`optional`, returned when ``config.output_attentions=True``) <add> list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``: <add> Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. <add> <add> Examples:: <add> <add> tokenizer = CamembertTokenizer.from_pretrained('camembert-base') <add> model = TFCamembertModel.from_pretrained('camembert-base') <add> input_ids = tf.constant(tokenizer.encode("J'aime le camembert !"))[None, :] # Batch size 1 <add> outputs = model(input_ids) <add> last_hidden_states = outputs[0] # The last hidden-state is the first element of the output tuple <add> <add> """ <add> config_class = CamembertConfig <add> pretrained_model_archive_map = TF_CAMEMBERT_PRETRAINED_MODEL_ARCHIVE_MAP <add> <add> <add>@add_start_docstrings( <add> """CamemBERT Model with a `language modeling` head on top. """, <add> CAMEMBERT_START_DOCSTRING, <add> CAMEMBERT_INPUTS_DOCSTRING, <add>) <add>class TFCamembertForMaskedLM(TFRobertaForMaskedLM): <add> r""" <add> **masked_lm_labels**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``: <add> Labels for computing the masked language modeling loss. <add> Indices should be in ``[-1, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring) <add> Tokens with indices set to ``-100`` are ignored (masked), the loss is only computed for the tokens with labels <add> in ``[0, ..., config.vocab_size]`` <add> <add> Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs: <add> **loss**: (`optional`, returned when ``masked_lm_labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``: <add> Masked language modeling loss. <add> **prediction_scores**: ``torch.FloatTensor`` of shape ``(batch_size, sequence_length, config.vocab_size)`` <add> Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax). <add> **hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``) <add> list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings) <add> of shape ``(batch_size, sequence_length, hidden_size)``: <add> Hidden-states of the model at the output of each layer plus the initial embedding outputs. <add> **attentions**: (`optional`, returned when ``config.output_attentions=True``) <add> list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``: <add> Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. <add> <add> Examples:: <add> <add> tokenizer = CamembertTokenizer.from_pretrained('camembert-base') <add> model = TFCamembertForMaskedLM.from_pretrained('camembert-base') <add> input_ids = tf.constant(tokenizer.encode("J'aime le camembert !"))[None, :] # Batch size 1 <add> outputs = model(input_ids, masked_lm_labels=input_ids) <add> loss, prediction_scores = outputs[:2] <add> <add> """ <add> config_class = CamembertConfig <add> pretrained_model_archive_map = TF_CAMEMBERT_PRETRAINED_MODEL_ARCHIVE_MAP <add> <add> <add>@add_start_docstrings( <add> """CamemBERT Model transformer with a sequence classification/regression head on top (a linear layer <add> on top of the pooled output) e.g. for GLUE tasks. """, <add> CAMEMBERT_START_DOCSTRING, <add> CAMEMBERT_INPUTS_DOCSTRING, <add>) <add>class TFCamembertForSequenceClassification(TFRobertaForSequenceClassification): <add> r""" <add> **labels**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size,)``: <add> Labels for computing the sequence classification/regression loss. <add> Indices should be in ``[0, ..., config.num_labels]``. <add> If ``config.num_labels == 1`` a regression loss is computed (Mean-Square loss), <add> If ``config.num_labels > 1`` a classification loss is computed (Cross-Entropy). <add> <add> Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs: <add> **loss**: (`optional`, returned when ``labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``: <add> Classification (or regression if config.num_labels==1) loss. <add> **logits**: ``torch.FloatTensor`` of shape ``(batch_size, config.num_labels)`` <add> Classification (or regression if config.num_labels==1) scores (before SoftMax). <add> **hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``) <add> list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings) <add> of shape ``(batch_size, sequence_length, hidden_size)``: <add> Hidden-states of the model at the output of each layer plus the initial embedding outputs. <add> **attentions**: (`optional`, returned when ``config.output_attentions=True``) <add> list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``: <add> Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. <add> <add> Examples:: <add> <add> tokenizer = CamembertTokenizer.from_pretrained('camembert-base') <add> model = TFCamembertForSequenceClassification.from_pretrained('camembert-base') <add> input_ids = tf.constant(tokenizer.encode("J'aime le camembert !"))[None, :] # Batch size 1 <add> outputs = model(input_ids) <add> loss, logits = outputs[:2] <add> <add> """ <add> config_class = CamembertConfig <add> pretrained_model_archive_map = TF_CAMEMBERT_PRETRAINED_MODEL_ARCHIVE_MAP <add> <add> <add>@add_start_docstrings( <add> """CamemBERT Model with a token classification head on top (a linear layer on top of <add> the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks. """, <add> CAMEMBERT_START_DOCSTRING, <add> CAMEMBERT_INPUTS_DOCSTRING, <add>) <add>class TFCamembertForTokenClassification(TFRobertaForTokenClassification): <add> r""" <add> **labels**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``: <add> Labels for computing the token classification loss. <add> Indices should be in ``[0, ..., config.num_labels - 1]``. <add> <add> Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs: <add> **loss**: (`optional`, returned when ``labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``: <add> Classification loss. <add> **scores**: ``torch.FloatTensor`` of shape ``(batch_size, sequence_length, config.num_labels)`` <add> Classification scores (before SoftMax). <add> **hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``) <add> list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings) <add> of shape ``(batch_size, sequence_length, hidden_size)``: <add> Hidden-states of the model at the output of each layer plus the initial embedding outputs. <add> **attentions**: (`optional`, returned when ``config.output_attentions=True``) <add> list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``: <add> Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. <add> <add> Examples:: <add> <add> tokenizer = CamembertTokenizer.from_pretrained('camembert-base') <add> model = TFCamembertForTokenClassification.from_pretrained('camembert-base') <add> input_ids = tf.constant(tokenizer.encode("J'aime le camembert !", add_special_tokens=True))[None, :] # Batch size 1 <add> outputs = model(input_ids) <add> loss, scores = outputs[:2] <add> <add> """ <add> config_class = CamembertConfig <add> pretrained_model_archive_map = TF_CAMEMBERT_PRETRAINED_MODEL_ARCHIVE_MAP
3
Javascript
Javascript
fix incorrect position of text widget
8bf17f5df83c667e6986e941ec472f865b3f256f
<ide><path>src/display/annotation_layer.js <ide> var AnnotationLayer = (function AnnotationLayerClosure() { <ide> return container; <ide> } <ide> <del> function getHtmlElementForTextWidgetAnnotation(item, page) { <del> var element = document.createElement('div'); <del> var width = item.rect[2] - item.rect[0]; <del> var height = item.rect[3] - item.rect[1]; <del> element.style.width = width + 'px'; <del> element.style.height = height + 'px'; <del> element.style.display = 'table'; <add> function getHtmlElementForTextWidgetAnnotation(item, page, viewport) { <add> var container = getContainer(item, page, viewport); <ide> <ide> var content = document.createElement('div'); <ide> content.textContent = item.fieldValue; <ide> var AnnotationLayer = (function AnnotationLayerClosure() { <ide> page.commonObjs.getData(item.fontRefName) : null; <ide> setTextStyles(content, item, fontObj); <ide> <del> element.appendChild(content); <add> container.appendChild(content); <ide> <del> return element; <add> return container; <ide> } <ide> <ide> function getHtmlElementForTextAnnotation(item, page, viewport) { <ide> var AnnotationLayer = (function AnnotationLayerClosure() { <ide> function getHtmlElement(data, page, viewport, linkService) { <ide> switch (data.annotationType) { <ide> case AnnotationType.WIDGET: <del> return getHtmlElementForTextWidgetAnnotation(data, page); <add> return getHtmlElementForTextWidgetAnnotation(data, page, viewport); <ide> case AnnotationType.TEXT: <ide> return getHtmlElementForTextAnnotation(data, page, viewport); <ide> case AnnotationType.LINK:
1
Text
Text
add cd\ command
bebde5f6c9fc737dddf7a63ab5657fe7a1aa822b
<ide><path>guide/english/terminal-commandline/windows-command-prompt/index.md <del>--- <del>title: Windows Command Prompt <del>--- <del># Using the Command Prompt in Windows <del>Windows, MacOS and Linux have command line interfaces. Windows' default command line is the command prompt. The command prompt allows users to use their computer without pointing and clicking with a mouse. The command prompt is a black screen where users type commands to use their computer. The same tasks that can be done by pointing and clicking with a mouse can also be done with the command prompt. The difference is that many tasks such as creating folders and deleting files can be done faster in the command prompt. Also, it allows users to configure their computer and run programs that they otherwise could not do by pointing and clicking. <del> <del>## Opening the Command Prompt <del>To access the command prompt, click the windows start menu on the Desktop tool bar (you can also press the windows button on your keyboard) and type `cmd` and hit `enter`. The command prompt will appear, it will display some text like to following below: <del>``` <del>C:\Users\YourUserName> <del>``` <del>## Navigating Directories (Moving through folders) <del>`C:\Users\YourUserName` is called your current working directory (directory is another way to say folder). It is like a street address that tells you where you are on your computer. The current working directory can be a guide as you navigate through your computer. On the right of the `>` we can type `cd`, which stands for Change Directory, and the name of a directory that you want to navigate to. In this case we will type `Documents`. Enter `cd Documents` and your current working directory should look like the following: <del>``` <del>C:\Users\YourUserName\Documents> <del>``` <del>To go back one directory type and enter `cd..`. Your current working directory should return to this: <del>``` <del>C:\Users\YourUserName> <del>``` <del>With the `cd` and `cd ..` commands you can move back and forth through directories. This might seem very basic at first but as you learn more commands the command prompt will become a very useful and efficient tool. <del> <del>## Here is a list of common commands: <del>| Command | Description | <del>|---------|--------------| <del>|`help` |Lists commands that can be used| <del>| `dir` |Lists the current directories contents| <del>|`dir /a` |Shows hidden files| <del>| `mkdir` |Creates a new directory| <del>| `rmdir` |Deletes a directory (if empty)| <del>| `rmdir /s`|Deletes a folder and its contents <del>| `cls` |Clears the command prompt screen <del>| `exit`|Closes the command prompt <del> <del>## Usage Examples: <del>#### Making a Directory <del>``` <del>mkdir name_of_the_directory_you_want_to_make <del>``` <del>#### Getting Info on a Command <del>``` <del>your_command /? <del>``` <del>#### Deleting a File and Contents <del>``` <del>rm /s name_of_directory_you_want_to_delete <del>``` <del> <del>## Useful tips: <del>- The command `Ipconfig` shows your computer's ip address <del>- The command `getmac` shows your computer's physical address <del>- If you type part of a directory's name and hit the `tab` key the command prompt will autocomplete it and if you hit the `tab` key repeatedly it will cycle through directories that start with the same letter <del>- You can use other shells or tools such as git bash or cmder to add more commands and functionality to your command prompt <del>- Some tasks require you to run the command prompt as an administrator you clicking the windows button and typing `cmd admin` and hit the `enter` key <del>- If you know the path to a file or directory can type `cd PATH_TO_YOUR_DIRECTORY` instead of changing directories several times to get to a directory or file <del>- Use `cd ..` to move to the previous parent directory <del>- When you hit the up arrow key your previously entered command will appear and if you hit it repeatedly it will cycle through all of your previously entered commands <add>--- <add>title: Windows Command Prompt <add>--- <add># Using the Command Prompt in Windows <add>Windows, MacOS and Linux have command line interfaces. Windows' default command line is the command prompt. The command prompt allows users to use their computer without pointing and clicking with a mouse. The command prompt is a black screen where users type commands to use their computer. The same tasks that can be done by pointing and clicking with a mouse can also be done with the command prompt. The difference is that many tasks such as creating folders and deleting files can be done faster in the command prompt. Also, it allows users to configure their computer and run programs that they otherwise could not do by pointing and clicking. <add> <add>## Opening the Command Prompt <add>To access the command prompt, click the windows start menu on the Desktop tool bar (you can also press the windows button on your keyboard) and type `cmd` and hit `enter`. The command prompt will appear, it will display some text like to following below: <add>``` <add>C:\Users\YourUserName> <add>``` <add>## Navigating Directories (Moving through folders) <add>`C:\Users\YourUserName` is called your current working directory (directory is another way to say folder). It is like a street address that tells you where you are on your computer. The current working directory can be a guide as you navigate through your computer. On the right of the `>` we can type `cd`, which stands for Change Directory, and the name of a directory that you want to navigate to. In this case we will type `Documents`. Enter `cd Documents` and your current working directory should look like the following: <add>``` <add>C:\Users\YourUserName\Documents> <add>``` <add>To go back one directory type and enter `cd..`. Your current working directory should return to this: <add>``` <add>C:\Users\YourUserName> <add>``` <add>Also, to go back to the root directory type and enter `cd\`. Your current working directory should return to this: <add>``` <add>C:\> <add>``` <add>With the `cd`, `cd ..` and `cd\` commands you can move back and forth through directories. This might seem very basic at first but as you learn more commands the command prompt will become a very useful and efficient tool. <add> <add>## Here is a list of common commands: <add>| Command | Description | <add>|---------|--------------| <add>|`help` |Lists commands that can be used| <add>| `dir` |Lists the current directories contents| <add>|`dir /a` |Shows hidden files| <add>| `mkdir` |Creates a new directory| <add>| `rmdir` |Deletes a directory (if empty)| <add>| `rmdir /s`|Deletes a folder and its contents <add>| `cls` |Clears the command prompt screen <add>| `exit`|Closes the command prompt <add> <add>## Usage Examples: <add>#### Making a Directory <add>``` <add>mkdir name_of_the_directory_you_want_to_make <add>``` <add>#### Getting Info on a Command <add>``` <add>your_command /? <add>``` <add>#### Deleting a File and Contents <add>``` <add>rm /s name_of_directory_you_want_to_delete <add>``` <add> <add>## Useful tips: <add>- The command `Ipconfig` shows your computer's ip address <add>- The command `getmac` shows your computer's physical address <add>- If you type part of a directory's name and hit the `tab` key the command prompt will autocomplete it and if you hit the `tab` key repeatedly it will cycle through directories that start with the same letter <add>- You can use other shells or tools such as git bash or cmder to add more commands and functionality to your command prompt <add>- Some tasks require you to run the command prompt as an administrator you clicking the windows button and typing `cmd admin` and hit the `enter` key <add>- If you know the path to a file or directory can type `cd PATH_TO_YOUR_DIRECTORY` instead of changing directories several times to get to a directory or file <add>- Use `cd ..` to move to the previous parent directory <add>- When you hit the up arrow key your previously entered command will appear and if you hit it repeatedly it will cycle through all of your previously entered commands
1
Javascript
Javascript
replace tic & toc by console.time/timeend
d1b75dd6331461b0def4e5fdecb95b111561870b
<ide><path>pdf_worker.js <ide> <ide> "use strict"; <ide> <del>var timer = null; <del>function tic() { <del> timer = Date.now(); <del>} <del> <del>function toc(msg) { <del> log(msg + ": " + (Date.now() - timer) + "ms"); <del> timer = null; <del>} <del> <del>function log() { <del> var args = Array.prototype.slice.call(arguments); <del> postMessage({ <del> action: "log", <del> data: args <del> }); <del>} <del> <add>var consoleTimer = {}; <ide> var console = { <del> log: log <add> log: function log() { <add> var args = Array.prototype.slice.call(arguments); <add> postMessage({ <add> action: "log", <add> data: args <add> }); <add> }, <add> <add> time: function(name) { <add> consoleTimer[name] = Date.now(); <add> }, <add> <add> timeEnd: function(name) { <add> var time = consoleTimer[name]; <add> if (time == null) { <add> throw "Unkown timer name " + name; <add> } <add> this.log("Timer:", name, Date.now() - time); <add> } <ide> } <ide> <ide> // <ide> onmessage = function(event) { <ide> } <ide> // User requested to render a certain page. <ide> else { <del> tic(); <add> console.time("compile"); <ide> <ide> // Let's try to render the first page... <ide> var page = pdfDocument.getPage(parseInt(data)); <ide> onmessage = function(event) { <ide> var fonts = []; <ide> var gfx = new CanvasGraphics(canvas.getContext("2d"), CanvasProxy); <ide> page.compile(gfx, fonts); <del> toc("compiled page"); <add> console.timeEnd("compile"); <ide> <del> tic() <add> console.time("fonts"); <ide> // Inspect fonts and translate the missing one. <ide> var count = fonts.length; <ide> for (var i = 0; i < count; i++) { <ide> onmessage = function(event) { <ide> // This "builds" the font and sents it over to the main thread. <ide> new Font(font.name, font.file, font.properties); <ide> } <del> toc("fonts"); <add> console.timeEnd("fonts"); <ide> <del> tic() <add> console.time("display"); <ide> page.display(gfx); <ide> canvas.flush(); <del> toc("displayed page"); <add> console.timeEnd("display"); <ide> } <ide> } <ide><path>worker_client.js <ide> <ide> "use strict"; <ide> <add>if (typeof console.time == "undefined") { <add> var consoleTimer = {}; <add> console.time = function(name) { <add> consoleTimer[name] = Date.now(); <add> }; <add> <add> console.timeEnd = function(name) { <add> var time = consoleTimer[name]; <add> if (time == null) { <add> throw "Unkown timer name " + name; <add> } <add> this.log("Timer:", name, Date.now() - time); <add> }; <add>} <add> <ide> function WorkerPDFDoc(canvas) { <ide> var timer = null <del> function tic() { <del> timer = Date.now(); <del> } <del> <del> function toc(msg) { <del> console.log(msg + ": " + (Date.now() - timer) + "ms"); <del> } <ide> <ide> this.ctx = canvas.getContext("2d"); <ide> this.canvas = canvas; <ide> function WorkerPDFDoc(canvas) { <ide> // rendering at the end of the event queue ensures this. <ide> setTimeout(function() { <ide> if (id == 0) { <del> tic(); <add> console.time("canvas rendering"); <ide> var ctx = this.ctx; <ide> ctx.save(); <ide> ctx.fillStyle = "rgb(255, 255, 255)"; <ide> ctx.fillRect(0, 0, canvas.width, canvas.height); <ide> ctx.restore(); <ide> } <ide> renderProxyCanvas(canvasList[id], cmdQueue); <del> if (id == 0) toc("canvas rendering") <add> if (id == 0) console.timeEnd("canvas rendering") <ide> }, 0, this); <ide> } <ide> }
2
Text
Text
add rushowl to airflow users
a7aba1e01027a8163451256d33417594df0e63cf
<ide><path>README.md <ide> Currently **officially** using Airflow: <ide> 1. [Reverb](https://reverb.com)[[@reverbdotcom](https://github.com/reverbdotcom)] <ide> 1. [Revolut](https://www.revolut.com/) [[@sztanko](https://github.com/sztanko) & [@nautilus28](https://github.com/nautilus28)] <ide> 1. [Robinhood](https://robinhood.com) [[@vineet-rh](https://github.com/vineet-rh)] <add>1. [RushOwl](https://www.rushowl.sg) [[@songyanho](https://github.com/songyanho)] <ide> 1. [Scaleway](https://scaleway.com) [[@kdeldycke](https://github.com/kdeldycke)] <ide> 1. [Seasoned](https://www.seasoned.co/) [[@joshuacano](https://github.com/joshuacano)] & [[@mmyers](https://github.com/mmyers5)] & [[@tjward](https://github.com/tjward)] <ide> 1. [Secret Escapes](https://www.secretescapes.com) [[@secretescapes](https://github.com/secretescapes)]
1
Python
Python
add option to turn on eager in imagenet
c254938dc9c53cc5c9f30f96ef1c403b9d9f6466
<ide><path>official/resnet/keras/keras_imagenet_main.py <ide> def run_imagenet_with_keras(flags_obj): <ide> Raises: <ide> ValueError: If fp16 is passed as it is not currently supported. <ide> """ <add> if flags_obj.enable_eager: <add> tf.enable_eager_execution() <add> <ide> dtype = flags_core.get_tf_dtype(flags_obj) <ide> if dtype == 'fp16': <ide> raise ValueError('dtype fp16 is not supported in Keras. Use the default ' <ide> def run_imagenet_with_keras(flags_obj): <ide> # TF Optimizer: <ide> # learning_rate = BASE_LEARNING_RATE * flags_obj.batch_size / 256 <ide> # opt = tf.train.MomentumOptimizer(learning_rate=learning_rate, momentum=0.9) <add> <ide> <ide> strategy = distribution_utils.get_distribution_strategy( <ide> num_gpus=flags_obj.num_gpus) <ide> def run_imagenet_with_keras(flags_obj): <ide> verbose=1) <ide> print('Test loss:', eval_output[0]) <ide> <add>def define_keras_imagenet_flags(): <add> flags.DEFINE_boolean(name='enable_eager', default=False, help='Enable eager?') <add> <add> <ide> def main(_): <ide> with logger.benchmark_context(flags.FLAGS): <ide> run_imagenet_with_keras(flags.FLAGS) <ide> <ide> <ide> if __name__ == '__main__': <ide> tf.logging.set_verbosity(tf.logging.INFO) <add> define_keras_imagenet_flags() <ide> imagenet_main.define_imagenet_flags() <ide> absl_app.run(main)
1
Javascript
Javascript
use spawnsync() full name
01c4907696b7065a57b999f6dd96deac379f2630
<ide><path>test/parallel/test-cli-bad-options.js <ide> require('../common'); <ide> // Tests that node exits consistently on bad option syntax. <ide> <ide> const assert = require('assert'); <del>const spawn = require('child_process').spawnSync; <add>const { spawnSync } = require('child_process'); <ide> <ide> if (process.features.inspector) { <ide> requiresArgument('--inspect-port'); <ide> if (process.features.inspector) { <ide> requiresArgument('--eval'); <ide> <ide> function requiresArgument(option) { <del> const r = spawn(process.execPath, [option], { encoding: 'utf8' }); <add> const r = spawnSync(process.execPath, [option], { encoding: 'utf8' }); <ide> <ide> assert.strictEqual(r.status, 9); <ide>
1
PHP
PHP
add support for default values for the props tag
af6cc0bf54642a676756f7a2e4cfd0305f00e8db
<ide><path>src/Illuminate/View/Compilers/Concerns/CompilesComponents.php <ide> protected function compileEndComponentFirst() <ide> protected function compileProps($expression) <ide> { <ide> return "<?php \$attributes = \$attributes->exceptProps{$expression}; ?> <add><?php foreach (array_filter({$expression}, 'is_string', ARRAY_FILTER_USE_KEY) as \$__key => \$__value) { <add> \$\$__key = \$\$__key ?? \$__value; <add>} ?> <ide> <?php \$__defined_vars = get_defined_vars(); ?> <ide> <?php foreach (\$attributes as \$__key => \$__value) { <ide> if (array_key_exists(\$__key, \$__defined_vars)) unset(\$\$__key);
1
Ruby
Ruby
require cargo to use `install` instead of `build`
3329a9f6d8d7aa6f9e37c33f6d4cc650ab6ea117
<ide><path>Library/Homebrew/rubocops/text_cop.rb <ide> def audit_formula(_node, _class_node, _parent_class_node, body_node) <ide> next if parameters_passed?(d, /vendor-only/) <ide> problem "use \"dep\", \"ensure\", \"-vendor-only\"" <ide> end <add> <add> find_method_with_args(body_node, :system, "cargo", "build") do <add> problem "use \"cargo\", \"install\", \"--root\", prefix" <add> end <ide> end <ide> end <ide> end <ide><path>Library/Homebrew/test/rubocops/text_cop_spec.rb <ide> def install <ide> end <ide> RUBY <ide> end <add> <add> it "When cargo build is executed" do <add> expect_offense(<<~RUBY) <add> class Foo < Formula <add> url "http://example.com/foo-1.0.tgz" <add> homepage "http://example.com" <add> <add> def install <add> system "cargo", "build" <add> ^^^^^^^^^^^^^^^^^^^^^^^ use \"cargo\", \"install\", \"--root\", prefix <add> end <add> end <add> RUBY <add> end <ide> end <ide> end
2
Javascript
Javascript
fix existssync for invalid symlink at win32
0e3d774ed21375675b024f555a67773821e56a9d
<ide><path>lib/fs.js <ide> function existsSync(path) { <ide> return false; <ide> } <ide> const ctx = { path }; <del> binding.access(pathModule.toNamespacedPath(path), F_OK, undefined, ctx); <add> const nPath = pathModule.toNamespacedPath(path); <add> binding.access(nPath, F_OK, undefined, ctx); <add> <add> // In case of an invalid symlink, `binding.access()` on win32 <add> // will **not** return an error and is therefore not enough. <add> // Double check with `binding.stat()`. <add> if (isWindows && ctx.errno === undefined) { <add> binding.stat(nPath, false, undefined, ctx); <add> } <add> <ide> return ctx.errno === undefined; <ide> } <ide> <ide><path>test/parallel/test-fs-symlink-dir-junction.js <ide> fs.symlink(linkData, linkPath, 'junction', common.mustCall(function(err) { <ide> })); <ide> })); <ide> })); <add> <add>// Test invalid symlink <add>{ <add> const linkData = fixtures.path('/not/exists/dir'); <add> const linkPath = path.join(tmpdir.path, 'invalid_junction_link'); <add> <add> fs.symlink(linkData, linkPath, 'junction', common.mustCall(function(err) { <add> assert.ifError(err); <add> <add> assert(!fs.existsSync(linkPath)); <add> <add> fs.unlink(linkPath, common.mustCall(function(err) { <add> assert.ifError(err); <add> assert(!fs.existsSync(linkPath)); <add> })); <add> })); <add>} <ide><path>test/parallel/test-fs-symlink-dir.js <ide> for (const linkTarget of linkTargets) { <ide> testAsync(linkTarget, `${linkPath}-${path.basename(linkTarget)}-async`); <ide> } <ide> } <add> <add>// Test invalid symlink <add>{ <add> function testSync(target, path) { <add> fs.symlinkSync(target, path); <add> assert(!fs.existsSync(path)); <add> } <add> <add> function testAsync(target, path) { <add> fs.symlink(target, path, common.mustCall((err) => { <add> assert.ifError(err); <add> assert(!fs.existsSync(path)); <add> })); <add> } <add> <add> for (const linkTarget of linkTargets.map((p) => p + '-broken')) { <add> for (const linkPath of linkPaths) { <add> testSync(linkTarget, `${linkPath}-${path.basename(linkTarget)}-sync`); <add> testAsync(linkTarget, `${linkPath}-${path.basename(linkTarget)}-async`); <add> } <add> } <add>} <ide><path>test/parallel/test-fs-symlink.js <ide> fs.symlink(linkData, linkPath, common.mustCall(function(err) { <ide> })); <ide> })); <ide> <add>// Test invalid symlink <add>{ <add> const linkData = fixtures.path('/not/exists/file'); <add> const linkPath = path.join(tmpdir.path, 'symlink2.js'); <add> <add> fs.symlink(linkData, linkPath, common.mustCall(function(err) { <add> assert.ifError(err); <add> <add> assert(!fs.existsSync(linkPath)); <add> })); <add>} <add> <ide> [false, 1, {}, [], null, undefined].forEach((input) => { <ide> const errObj = { <ide> code: 'ERR_INVALID_ARG_TYPE',
4
Ruby
Ruby
remove response faking
b276108330d9397740ce6a189f89d68206b8bf2c
<ide><path>actionmailer/test/assert_select_email_test.rb <ide> def test(options) <ide> # Test assert_select_email <ide> # <ide> <del> def setup <del> @response = FakeResponse.new(:html, 'some body text') <del> end <del> <ide> def test_assert_select_email <ide> assert_raise(Assertion) { assert_select_email {} } <ide> AssertSelectMailer.test("<div><p>foo</p><p>bar</p></div>").deliver <ide> def test_assert_select_email_multipart <ide> end <ide> end <ide> end <del> <del> protected <del> <del> class FakeResponse <del> attr_accessor :content_type, :body <del> <del> def initialize(content_type, body) <del> @content_type, @body = content_type, body <del> end <del> end <del>end <ide>\ No newline at end of file <add>end
1
Javascript
Javascript
notify view controller when its parentview changes
ce28b3ca811e520e86de8caa8a632fab58c6c4bf
<ide><path>packages/ember-views/lib/mixins/view_context_support.js <ide> import { get } from "ember-metal/property_get"; <ide> import { set } from "ember-metal/property_set"; <ide> import LegacyViewSupport from "ember-views/mixins/legacy_view_support"; <ide> import { observer } from "ember-metal/mixin"; <add>import { on } from "ember-metal/events"; <ide> <ide> var ViewContextSupport = Mixin.create(LegacyViewSupport, { <ide> /** <ide> var ViewContextSupport = Mixin.create(LegacyViewSupport, { <ide> <ide> _legacyControllerDidChange: observer('controller', function() { <ide> this.walkChildViews(view => view.notifyPropertyChange('controller')); <add> }), <add> <add> _notifyControllerChange: on('parentViewDidChange', function() { <add> this.notifyPropertyChange('controller'); <ide> }) <ide> }); <ide> <ide><path>packages/ember-views/tests/views/view/controller_test.js <ide> import ContainerView from "ember-views/views/container_view"; <ide> <ide> QUnit.module("Ember.View - controller property"); <ide> <del>QUnit.skip("controller property should be inherited from nearest ancestor with controller", function() { <add>QUnit.test("controller property should be inherited from nearest ancestor with controller", function() { <ide> var grandparent = ContainerView.create(); <ide> var parent = ContainerView.create(); <ide> var child = ContainerView.create();
2
Python
Python
fix mypy erros at strongly connected component
7342b336587af1e57eb9888203a1ae80832bde28
<ide><path>graphs/strongly_connected_components.py <ide> test_graph_2 = {0: [1, 2, 3], 1: [2], 2: [0], 3: [4], 4: [5], 5: [3]} <ide> <ide> <del>def topology_sort(graph: dict, vert: int, visited: list) -> list: <add>def topology_sort( <add> graph: dict[int, list[int]], vert: int, visited: list[bool] <add>) -> list[int]: <ide> """ <ide> Use depth first search to sort graph <ide> At this time graph is the same as input <ide> def topology_sort(graph: dict, vert: int, visited: list) -> list: <ide> return order <ide> <ide> <del>def find_components(reversed_graph: dict, vert: int, visited: list) -> list: <add>def find_components( <add> reversed_graph: dict[int, list[int]], vert: int, visited: list[bool] <add>) -> list[int]: <ide> """ <ide> Use depth first search to find strongliy connected <ide> vertices. Now graph is reversed <ide> def find_components(reversed_graph: dict, vert: int, visited: list) -> list: <ide> return component <ide> <ide> <del>def strongly_connected_components(graph: dict) -> list: <add>def strongly_connected_components(graph: dict[int, list[int]]) -> list[list[int]]: <ide> """ <ide> This function takes graph as a parameter <ide> and then returns the list of strongly connected components <ide> def strongly_connected_components(graph: dict) -> list: <ide> """ <ide> <ide> visited = len(graph) * [False] <del> reversed_graph = {vert: [] for vert in range(len(graph))} <add> reversed_graph: dict[int, list[int]] = {vert: [] for vert in range(len(graph))} <ide> <ide> for vert, neighbours in graph.items(): <ide> for neighbour in neighbours: <ide> def strongly_connected_components(graph: dict) -> list: <ide> components_list.append(component) <ide> <ide> return components_list <del> <del> <del>if __name__ == "__main__": <del> import doctest <del> <del> doctest.testmod()
1
Python
Python
add albert to autoclasses
ecf15ebf3b7f5d2b0144f1a428e2d9f39494c8ba
<ide><path>transformers/configuration_auto.py <ide> from .configuration_distilbert import DistilBertConfig <ide> from .configuration_ctrl import CTRLConfig <ide> from .configuration_camembert import CamembertConfig <add>from .configuration_albert import AlbertConfig <ide> <ide> logger = logging.getLogger(__name__) <ide> <ide> class method. <ide> The base model class to instantiate is selected as the first pattern matching <ide> in the `pretrained_model_name_or_path` string (in the following order): <ide> - contains `distilbert`: DistilBertConfig (DistilBERT model) <add> - contains `albert`: AlbertConfig (ALBERT model) <add> - contains `camembert`: CamembertConfig (CamemBERT model) <add> - contains `roberta`: RobertaConfig (RoBERTa model) <ide> - contains `bert`: BertConfig (Bert model) <ide> - contains `openai-gpt`: OpenAIGPTConfig (OpenAI GPT model) <ide> - contains `gpt2`: GPT2Config (OpenAI GPT-2 model) <ide> - contains `transfo-xl`: TransfoXLConfig (Transformer-XL model) <ide> - contains `xlnet`: XLNetConfig (XLNet model) <ide> - contains `xlm`: XLMConfig (XLM model) <del> - contains `roberta`: RobertaConfig (RoBERTa model) <del> - contains `camembert`: CamembertConfig (CamemBERT model) <ide> - contains `ctrl` : CTRLConfig (CTRL model) <ide> This class cannot be instantiated using `__init__()` (throw an error). <ide> """ <ide> def from_pretrained(cls, pretrained_model_name_or_path, **kwargs): <ide> The configuration class to instantiate is selected as the first pattern matching <ide> in the `pretrained_model_name_or_path` string (in the following order): <ide> - contains `distilbert`: DistilBertConfig (DistilBERT model) <add> - contains `albert`: AlbertConfig (ALBERT model) <add> - contains `camembert`: CamembertConfig (CamemBERT model) <add> - contains `roberta`: RobertaConfig (RoBERTa model) <ide> - contains `bert`: BertConfig (Bert model) <ide> - contains `openai-gpt`: OpenAIGPTConfig (OpenAI GPT model) <ide> - contains `gpt2`: GPT2Config (OpenAI GPT-2 model) <ide> - contains `transfo-xl`: TransfoXLConfig (Transformer-XL model) <ide> - contains `xlnet`: XLNetConfig (XLNet model) <ide> - contains `xlm`: XLMConfig (XLM model) <del> - contains `roberta`: RobertaConfig (RoBERTa model) <del> - contains `camembert`: CamembertConfig (CamemBERT model) <ide> - contains `ctrl` : CTRLConfig (CTRL model) <ide> Params: <ide> pretrained_model_name_or_path: either: <ide> def from_pretrained(cls, pretrained_model_name_or_path, **kwargs): <ide> """ <ide> if 'distilbert' in pretrained_model_name_or_path: <ide> return DistilBertConfig.from_pretrained(pretrained_model_name_or_path, **kwargs) <add> elif 'albert' in pretrained_model_name_or_path: <add> return AlbertConfig.from_pretrained(pretrained_model_name_or_path, **kwargs) <ide> elif 'camembert' in pretrained_model_name_or_path: <ide> return CamembertConfig.from_pretrained(pretrained_model_name_or_path, **kwargs) <ide> elif 'roberta' in pretrained_model_name_or_path: <ide> def from_pretrained(cls, pretrained_model_name_or_path, **kwargs): <ide> return CTRLConfig.from_pretrained(pretrained_model_name_or_path, **kwargs) <ide> raise ValueError("Unrecognized model identifier in {}. Should contains one of " <ide> "'bert', 'openai-gpt', 'gpt2', 'transfo-xl', 'xlnet', " <del> "'xlm', 'roberta', 'camembert', 'ctrl'".format(pretrained_model_name_or_path)) <add> "'xlm', 'roberta', 'distilbert', 'camembert', 'ctrl', 'albert'".format(pretrained_model_name_or_path)) <ide><path>transformers/modeling_auto.py <ide> from .modeling_roberta import RobertaModel, RobertaForMaskedLM, RobertaForSequenceClassification <ide> from .modeling_distilbert import DistilBertModel, DistilBertForQuestionAnswering, DistilBertForMaskedLM, DistilBertForSequenceClassification <ide> from .modeling_camembert import CamembertModel, CamembertForMaskedLM, CamembertForSequenceClassification, CamembertForMultipleChoice <add>from .modeling_camembert import CamembertModel, CamembertForMaskedLM, CamembertForSequenceClassification, CamembertForMultipleChoice <add>from .modeling_albert import AlbertModel, AlbertForMaskedLM, AlbertForSequenceClassification, AlbertForQuestionAnswering <ide> <ide> from .modeling_utils import PreTrainedModel, SequenceSummary <ide> <ide> class method. <ide> The base model class to instantiate is selected as the first pattern matching <ide> in the `pretrained_model_name_or_path` string (in the following order): <ide> - contains `distilbert`: DistilBertModel (DistilBERT model) <add> - contains `albert`: AlbertModel (ALBERT model) <ide> - contains `camembert`: CamembertModel (CamemBERT model) <ide> - contains `roberta`: RobertaModel (RoBERTa model) <ide> - contains `bert`: BertModel (Bert model) <ide> - contains `openai-gpt`: OpenAIGPTModel (OpenAI GPT model) <ide> - contains `gpt2`: GPT2Model (OpenAI GPT-2 model) <del> - contains `ctrl`: CTRLModel (Salesforce CTRL model) <ide> - contains `transfo-xl`: TransfoXLModel (Transformer-XL model) <ide> - contains `xlnet`: XLNetModel (XLNet model) <ide> - contains `xlm`: XLMModel (XLM model) <add> - contains `ctrl`: CTRLModel (Salesforce CTRL model) <ide> <ide> This class cannot be instantiated using `__init__()` (throws an error). <ide> """ <ide> def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): <ide> The model class to instantiate is selected as the first pattern matching <ide> in the `pretrained_model_name_or_path` string (in the following order): <ide> - contains `distilbert`: DistilBertModel (DistilBERT model) <add> - contains `albert`: AlbertModel (ALBERT model) <ide> - contains `camembert`: CamembertModel (CamemBERT model) <ide> - contains `roberta`: RobertaModel (RoBERTa model) <ide> - contains `bert`: BertModel (Bert model) <ide> - contains `openai-gpt`: OpenAIGPTModel (OpenAI GPT model) <ide> - contains `gpt2`: GPT2Model (OpenAI GPT-2 model) <del> - contains `ctrl`: CTRLModel (Salesforce CTRL model) <ide> - contains `transfo-xl`: TransfoXLModel (Transformer-XL model) <ide> - contains `xlnet`: XLNetModel (XLNet model) <ide> - contains `xlm`: XLMModel (XLM model) <add> - contains `ctrl`: CTRLModel (Salesforce CTRL model) <ide> <ide> The model is set in evaluation mode by default using `model.eval()` (Dropout modules are deactivated) <ide> To train the model, you should first set it back in training mode with `model.train()` <ide> def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): <ide> """ <ide> if 'distilbert' in pretrained_model_name_or_path: <ide> return DistilBertModel.from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs) <add> elif 'albert' in pretrained_model_name_or_path: <add> return AlbertModel.from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs) <ide> elif 'camembert' in pretrained_model_name_or_path: <ide> return CamembertModel.from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs) <ide> elif 'roberta' in pretrained_model_name_or_path: <ide> def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): <ide> return CTRLModel.from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs) <ide> raise ValueError("Unrecognized model identifier in {}. Should contains one of " <ide> "'bert', 'openai-gpt', 'gpt2', 'transfo-xl', 'xlnet', " <del> "'xlm', 'roberta, 'ctrl'".format(pretrained_model_name_or_path)) <add> "'xlm', 'roberta, 'ctrl', 'distilbert', 'camembert', 'albert'".format(pretrained_model_name_or_path)) <ide> <ide> <ide> class AutoModelWithLMHead(object): <ide> class method. <ide> The model class to instantiate is selected as the first pattern matching <ide> in the `pretrained_model_name_or_path` string (in the following order): <ide> - contains `distilbert`: DistilBertForMaskedLM (DistilBERT model) <add> - contains `albert`: AlbertForMaskedLM (ALBERT model) <ide> - contains `camembert`: CamembertForMaskedLM (CamemBERT model) <ide> - contains `roberta`: RobertaForMaskedLM (RoBERTa model) <ide> - contains `bert`: BertForMaskedLM (Bert model) <ide> - contains `openai-gpt`: OpenAIGPTLMHeadModel (OpenAI GPT model) <ide> - contains `gpt2`: GPT2LMHeadModel (OpenAI GPT-2 model) <del> - contains `ctrl`: CTRLLMModel (Salesforce CTRL model) <ide> - contains `transfo-xl`: TransfoXLLMHeadModel (Transformer-XL model) <ide> - contains `xlnet`: XLNetLMHeadModel (XLNet model) <ide> - contains `xlm`: XLMWithLMHeadModel (XLM model) <add> - contains `ctrl`: CTRLLMHeadModel (Salesforce CTRL model) <ide> <ide> This class cannot be instantiated using `__init__()` (throws an error). <ide> """ <ide> def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): <ide> The model class to instantiate is selected as the first pattern matching <ide> in the `pretrained_model_name_or_path` string (in the following order): <ide> - contains `distilbert`: DistilBertForMaskedLM (DistilBERT model) <add> - contains `albert`: AlbertForMaskedLM (ALBERT model) <ide> - contains `camembert`: CamembertForMaskedLM (CamemBERT model) <ide> - contains `roberta`: RobertaForMaskedLM (RoBERTa model) <ide> - contains `bert`: BertForMaskedLM (Bert model) <ide> def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): <ide> - contains `transfo-xl`: TransfoXLLMHeadModel (Transformer-XL model) <ide> - contains `xlnet`: XLNetLMHeadModel (XLNet model) <ide> - contains `xlm`: XLMWithLMHeadModel (XLM model) <add> - contains `ctrl`: CTRLLMHeadModel (Salesforce CTRL model) <ide> <ide> The model is set in evaluation mode by default using `model.eval()` (Dropout modules are deactivated) <ide> To train the model, you should first set it back in training mode with `model.train()` <ide> def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): <ide> """ <ide> if 'distilbert' in pretrained_model_name_or_path: <ide> return DistilBertForMaskedLM.from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs) <add> elif 'albert' in pretrained_model_name_or_path: <add> return AlbertForMaskedLM.from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs) <ide> elif 'camembert' in pretrained_model_name_or_path: <ide> return CamembertForMaskedLM.from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs) <ide> elif 'roberta' in pretrained_model_name_or_path: <ide> def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): <ide> return CTRLLMHeadModel.from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs) <ide> raise ValueError("Unrecognized model identifier in {}. Should contains one of " <ide> "'bert', 'openai-gpt', 'gpt2', 'transfo-xl', 'xlnet', " <del> "'xlm', 'roberta','ctrl'".format(pretrained_model_name_or_path)) <add> "'xlm', 'roberta','ctrl', 'distilbert', 'camembert', 'albert'".format(pretrained_model_name_or_path)) <ide> <ide> <ide> class AutoModelForSequenceClassification(object): <ide> class method. <ide> The model class to instantiate is selected as the first pattern matching <ide> in the `pretrained_model_name_or_path` string (in the following order): <ide> - contains `distilbert`: DistilBertForSequenceClassification (DistilBERT model) <add> - contains `albert`: AlbertForSequenceClassification (ALBERT model) <ide> - contains `camembert`: CamembertForSequenceClassification (CamemBERT model) <ide> - contains `roberta`: RobertaForSequenceClassification (RoBERTa model) <ide> - contains `bert`: BertForSequenceClassification (Bert model) <ide> def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): <ide> The model class to instantiate is selected as the first pattern matching <ide> in the `pretrained_model_name_or_path` string (in the following order): <ide> - contains `distilbert`: DistilBertForSequenceClassification (DistilBERT model) <add> - contains `albert`: AlbertForSequenceClassification (ALBERT model) <ide> - contains `camembert`: CamembertForSequenceClassification (CamemBERT model) <ide> - contains `roberta`: RobertaForSequenceClassification (RoBERTa model) <ide> - contains `bert`: BertForSequenceClassification (Bert model) <ide> def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): <ide> """ <ide> if 'distilbert' in pretrained_model_name_or_path: <ide> return DistilBertForSequenceClassification.from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs) <add> elif 'albert' in pretrained_model_name_or_path: <add> return AlbertForSequenceClassification.from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs) <ide> elif 'camembert' in pretrained_model_name_or_path: <ide> return CamembertForSequenceClassification.from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs) <ide> elif 'roberta' in pretrained_model_name_or_path: <ide> def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): <ide> return XLMForSequenceClassification.from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs) <ide> <ide> raise ValueError("Unrecognized model identifier in {}. Should contains one of " <del> "'bert', 'xlnet', 'xlm', 'roberta'".format(pretrained_model_name_or_path)) <add> "'bert', 'xlnet', 'xlm', 'roberta', 'distilbert', 'camembert', 'albert'".format(pretrained_model_name_or_path)) <ide> <ide> <ide> class AutoModelForQuestionAnswering(object): <ide> class method. <ide> The model class to instantiate is selected as the first pattern matching <ide> in the `pretrained_model_name_or_path` string (in the following order): <ide> - contains `distilbert`: DistilBertForQuestionAnswering (DistilBERT model) <add> - contains `albert`: AlbertForQuestionAnswering (ALBERT model) <ide> - contains `bert`: BertForQuestionAnswering (Bert model) <ide> - contains `xlnet`: XLNetForQuestionAnswering (XLNet model) <ide> - contains `xlm`: XLMForQuestionAnswering (XLM model) <ide> def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): <ide> The model class to instantiate is selected as the first pattern matching <ide> in the `pretrained_model_name_or_path` string (in the following order): <ide> - contains `distilbert`: DistilBertForQuestionAnswering (DistilBERT model) <add> - contains `albert`: AlbertForQuestionAnswering (ALBERT model) <ide> - contains `bert`: BertForQuestionAnswering (Bert model) <ide> - contains `xlnet`: XLNetForQuestionAnswering (XLNet model) <ide> - contains `xlm`: XLMForQuestionAnswering (XLM model) <ide> def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): <ide> """ <ide> if 'distilbert' in pretrained_model_name_or_path: <ide> return DistilBertForQuestionAnswering.from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs) <add> elif 'albert' in pretrained_model_name_or_path: <add> return AlbertForQuestionAnswering.from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs) <ide> elif 'bert' in pretrained_model_name_or_path: <ide> return BertForQuestionAnswering.from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs) <ide> elif 'xlnet' in pretrained_model_name_or_path: <ide> def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): <ide> return XLMForQuestionAnswering.from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs) <ide> <ide> raise ValueError("Unrecognized model identifier in {}. Should contains one of " <del> "'bert', 'xlnet', 'xlm'".format(pretrained_model_name_or_path)) <add> "'bert', 'xlnet', 'xlm', 'distilbert', 'albert'".format(pretrained_model_name_or_path)) <ide><path>transformers/tokenization_auto.py <ide> from .tokenization_roberta import RobertaTokenizer <ide> from .tokenization_distilbert import DistilBertTokenizer <ide> from .tokenization_camembert import CamembertTokenizer <add>from .tokenization_albert import AlbertTokenizer <ide> <ide> logger = logging.getLogger(__name__) <ide> <ide> class method. <ide> <ide> The tokenizer class to instantiate is selected as the first pattern matching <ide> in the `pretrained_model_name_or_path` string (in the following order): <del> - contains `camembert`: CamembertTokenizer (CamemBERT model) <ide> - contains `distilbert`: DistilBertTokenizer (DistilBert model) <add> - contains `albert`: AlbertTokenizer (ALBERT model) <add> - contains `camembert`: CamembertTokenizer (CamemBERT model) <ide> - contains `roberta`: RobertaTokenizer (RoBERTa model) <ide> - contains `bert`: BertTokenizer (Bert model) <ide> - contains `openai-gpt`: OpenAIGPTTokenizer (OpenAI GPT model) <ide> - contains `gpt2`: GPT2Tokenizer (OpenAI GPT-2 model) <del> - contains `ctrl`: CTRLTokenizer (Salesforce CTRL model) <ide> - contains `transfo-xl`: TransfoXLTokenizer (Transformer-XL model) <ide> - contains `xlnet`: XLNetTokenizer (XLNet model) <ide> - contains `xlm`: XLMTokenizer (XLM model) <add> - contains `ctrl`: CTRLTokenizer (Salesforce CTRL model) <ide> <ide> This class cannot be instantiated using `__init__()` (throw an error). <ide> """ <ide> def from_pretrained(cls, pretrained_model_name_or_path, *inputs, **kwargs): <ide> <ide> The tokenizer class to instantiate is selected as the first pattern matching <ide> in the `pretrained_model_name_or_path` string (in the following order): <del> - contains `camembert`: CamembertTokenizer (CamemBERT model) <ide> - contains `distilbert`: DistilBertTokenizer (DistilBert model) <add> - contains `albert`: AlbertTokenizer (ALBERT model) <add> - contains `camembert`: CamembertTokenizer (CamemBERT model) <ide> - contains `roberta`: RobertaTokenizer (RoBERTa model) <ide> - contains `bert`: BertTokenizer (Bert model) <ide> - contains `openai-gpt`: OpenAIGPTTokenizer (OpenAI GPT model) <ide> - contains `gpt2`: GPT2Tokenizer (OpenAI GPT-2 model) <del> - contains `ctrl`: CTRLTokenizer (Salesforce CTRL model) <ide> - contains `transfo-xl`: TransfoXLTokenizer (Transformer-XL model) <ide> - contains `xlnet`: XLNetTokenizer (XLNet model) <ide> - contains `xlm`: XLMTokenizer (XLM model) <add> - contains `ctrl`: CTRLTokenizer (Salesforce CTRL model) <ide> <ide> Params: <ide> pretrained_model_name_or_path: either: <ide> def from_pretrained(cls, pretrained_model_name_or_path, *inputs, **kwargs): <ide> """ <ide> if 'distilbert' in pretrained_model_name_or_path: <ide> return DistilBertTokenizer.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs) <add> elif 'albert' in pretrained_model_name_or_path: <add> return AlbertTokenizer.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs) <ide> elif 'camembert' in pretrained_model_name_or_path: <ide> return CamembertTokenizer.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs) <ide> elif 'roberta' in pretrained_model_name_or_path: <ide> def from_pretrained(cls, pretrained_model_name_or_path, *inputs, **kwargs): <ide> return CTRLTokenizer.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs) <ide> raise ValueError("Unrecognized model identifier in {}. Should contains one of " <ide> "'bert', 'openai-gpt', 'gpt2', 'transfo-xl', 'xlnet', " <del> "'xlm', 'roberta', 'camembert', 'ctrl'".format(pretrained_model_name_or_path)) <add> "'xlm', 'roberta', 'distilbert,' 'camembert', 'ctrl', 'albert'".format(pretrained_model_name_or_path))
3
Javascript
Javascript
add test for net-socket-settimeout callback
22a9fe35520f7eb89845237582262457721afc70
<ide><path>test/parallel/test-net-socket-timeout.js <ide> const nonNumericDelays = [ <ide> ]; <ide> const badRangeDelays = [-0.001, -1, -Infinity, Infinity, NaN]; <ide> const validDelays = [0, 0.001, 1, 1e6]; <add>const invalidCallbacks = [ <add> 1, '100', true, false, null, {}, [], Symbol('test') <add>]; <ide> <ide> <ide> for (let i = 0; i < nonNumericDelays.length; i++) { <ide> for (let i = 0; i < validDelays.length; i++) { <ide> s.setTimeout(validDelays[i], () => {}); <ide> } <ide> <add>for (let i = 0; i < invalidCallbacks.length; i++) { <add> [0, 1].forEach((mesc) => <add> common.expectsError( <add> () => s.setTimeout(mesc, invalidCallbacks[i]), <add> { <add> code: 'ERR_INVALID_CALLBACK', <add> type: TypeError, <add> message: 'Callback must be a function' <add> } <add> ) <add> ); <add>} <add> <ide> const server = net.Server(); <ide> server.listen(0, common.mustCall(() => { <ide> const socket = net.createConnection(server.address().port);
1
Ruby
Ruby
pass explicit sort to handle apfs
9a323c51078ee9c900fda3ee6b88d1c1e3b26b8f
<ide><path>Library/Homebrew/cmd/info.rb <ide> def print_info <ide> <ide> def print_json <ide> ff = if ARGV.include? "--all" <del> Formula <add> Formula.sort <ide> elsif ARGV.include? "--installed" <del> Formula.installed <add> Formula.installed.sort <ide> else <ide> ARGV.formulae <ide> end
1
Javascript
Javascript
allow interpolations for non-event handlers attrs
8e1276c011b33b90af47494dc5e76baf86468a5a
<ide><path>src/ng/compile.js <ide> function $CompileProvider($provide) { <ide> // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes <ide> // The assumption is that future DOM event attribute names will begin with <ide> // 'on' and be composed of only English letters. <del> var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]*|formaction)$/; <add> var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/; <ide> <ide> /** <ide> * @ngdoc function <ide><path>test/ng/compileSpec.js <ide> describe('$compile', function() { <ide> $rootScope.$apply(); <ide> expect(element.attr('on-click')).toEqual('javascript:doSomething()'); <ide> })); <add> <add> it('should pass through arbitrary values on "on" and "data-on" attributes', inject(function($compile, $rootScope) { <add> element = $compile('<button data-on="{{dataOnVar}}"></script>')($rootScope); <add> $rootScope.dataOnVar = 'data-on text'; <add> $rootScope.$apply(); <add> expect(element.attr('data-on')).toEqual('data-on text'); <add> <add> element = $compile('<button on="{{onVar}}"></script>')($rootScope); <add> $rootScope.onVar = 'on text'; <add> $rootScope.$apply(); <add> expect(element.attr('on')).toEqual('on text'); <add> })); <ide> }); <ide> <ide> describe('iframe[src]', function() {
2
Text
Text
improve autoskip documentation
1c01272c9af8261a114524e6781e5e67105735fb
<ide><path>docs/axes/cartesian/README.md <ide> The following options are common to all cartesian axes but do not apply to other <ide> <ide> | Name | Type | Default | Description <ide> | ---- | ---- | ------- | ----------- <del>| `autoSkip` | `boolean` | `true` | If true, automatically calculates how many labels that can be shown and hides labels accordingly. Turn it off to show all labels no matter what. <del>| `autoSkipPadding` | `number` | `0` | Padding between the ticks on the horizontal axis when `autoSkip` is enabled. *Note: Only applicable to horizontal scales.* <add>| `autoSkip` | `boolean` | `true` | If true, automatically calculates how many labels can be shown and hides labels accordingly. Labels will be rotated up to `maxRotation` before skipping any. Turn `autoSkip` off to show all labels no matter what. <add>| `autoSkipPadding` | `number` | `0` | Padding between the ticks on the horizontal axis when `autoSkip` is enabled. <ide> | `labelOffset` | `number` | `0` | Distance in pixels to offset the label from the centre point of the tick (in the x direction for the x axis, and the y direction for the y axis). *Note: this can cause labels at the edges to be cropped by the edge of the canvas* <ide> | `maxRotation` | `number` | `90` | Maximum rotation for tick labels when rotating to condense labels. Note: Rotation doesn't occur until necessary. *Note: Only applicable to horizontal scales.* <ide> | `minRotation` | `number` | `0` | Minimum rotation for tick labels. *Note: Only applicable to horizontal scales.*
1
Text
Text
devmode hard-codes the location of the atom repo
0695aafe80b0e5bbbcceaea2b658e0d348c28a4e
<ide><path>docs/building-atom.md <ide> atom][download]. <ide> * Install the [latest 32bit Node 0.10.x][win-node] <ide> * Install the [latest Python 2.7.x][win-python] <ide> * Install [Github for Windows][win-github] <del>* Clone [atom/atom][atom-git] to `C:\Users\<user>\Documents\GitHub\atom\` <del>* Add `C:\Python27;C:\Program Files\nodejs;C:\Users\<user>\Documents\GitHub\atom\node_modules\` <add>* Clone [atom/atom][atom-git] to `C:\Users\<user>\github\atom\` <add>* Add `C:\Python27;C:\Program Files\nodejs;C:\Users\<user>\github\atom\node_modules\` <ide> to your PATH <ide> * Set ATOM_ACCESS_TOKEN to your oauth2 credentials (run `security -q <ide> find-generic-password -ws 'GitHub API Token'` on OSX to get your <ide> credentials). <del>* Use the Windows GitHub shell and cd into `C:\Users\<user>\Documents\GitHub\atom` <add>* Use the Windows GitHub shell and cd into `C:\Users\<user>\github\atom` <ide> * Run `node script/bootstrap` <ide> <ide> [download]: http://www.atom.io
1
Ruby
Ruby
use alphabetical order in symbols array
0148ee870eedc0d850c25fd7c6fb3e0e02893653
<ide><path>Library/Homebrew/livecheck/livecheck.rb <ide> module Livecheck <ide> <ide> STRATEGY_SYMBOLS_TO_SKIP_PREPROCESS_URL = [ <ide> :github_latest, <del> :sparkle, <ide> :page_match, <add> :sparkle, <ide> ].freeze <ide> <ide> UNSTABLE_VERSION_KEYWORDS = %w[
1
Python
Python
run tests if skip condition not met
ef91a2d135f3fa43c89511f7c11ae3543e260692
<ide><path>tests/models/convnext/test_modeling_tf_convnext.py <ide> def test_inputs_embeds(self): <ide> <ide> @unittest.skipIf( <ide> not is_tf_available() or len(tf.config.list_physical_devices("GPU")) == 0, <del> reason="TF (<=2.8) does not support backprop for grouped convolutions on CPU.", <add> reason="TF does not support backprop for grouped convolutions on CPU.", <ide> ) <ide> def test_keras_fit(self): <del> pass <add> super().test_keras_fit() <ide> <ide> @unittest.skip(reason="ConvNext does not support input and output embeddings") <ide> def test_model_common_attributes(self): <ide> def test_attention_outputs(self): <ide> <ide> @unittest.skipIf( <ide> not is_tf_available() or len(tf.config.list_physical_devices("GPU")) == 0, <del> reason="TF (<=2.8) does not support backprop for grouped convolutions on CPU.", <add> reason="TF does not support backprop for grouped convolutions on CPU.", <ide> ) <ide> def test_dataset_conversion(self): <ide> super().test_dataset_conversion() <ide><path>tests/models/regnet/test_modeling_tf_regnet.py <ide> def test_inputs_embeds(self): <ide> <ide> @unittest.skipIf( <ide> not is_tf_available() or len(tf.config.list_physical_devices("GPU")) == 0, <del> reason="TF (<=2.8) does not support backprop for grouped convolutions on CPU.", <add> reason="TF does not support backprop for grouped convolutions on CPU.", <ide> ) <ide> def test_keras_fit(self): <del> pass <add> super().test_keras_fit() <ide> <ide> @unittest.skip(reason="RegNet does not support input and output embeddings") <ide> def test_model_common_attributes(self): <ide><path>tests/models/segformer/test_modeling_tf_segformer.py <ide> def recursive_check(tuple_object, dict_object): <ide> <ide> @unittest.skipIf( <ide> not is_tf_available() or len(tf.config.list_physical_devices("GPU")) == 0, <del> reason="TF (<=2.8) does not support backprop for grouped convolutions on CPU.", <add> reason="TF does not support backprop for grouped convolutions on CPU.", <ide> ) <ide> def test_dataset_conversion(self): <ide> super().test_dataset_conversion() <ide> def check_keras_fit_results(self, val_loss1, val_loss2, atol=2e-1, rtol=2e-1): <ide> <ide> @unittest.skipIf( <ide> not is_tf_available() or len(tf.config.list_physical_devices("GPU")) == 0, <del> reason="TF (<=2.8) does not support backprop for grouped convolutions on CPU.", <add> reason="TF does not support backprop for grouped convolutions on CPU.", <ide> ) <ide> def test_keras_fit(self): <ide> config, _ = self.model_tester.prepare_config_and_inputs_for_common()
3
PHP
PHP
fix array docblocks
12e2655108032fb16d5932204bca8965b951cf39
<ide><path>src/Auth/AbstractPasswordHasher.php <ide> public function __construct(array $config = []) <ide> /** <ide> * Generates password hash. <ide> * <del> * @param string|array $password Plain text password to hash or array of data <del> * required to generate password hash. <add> * @param string $password Plain text password to hash. <ide> * @return string|false Either the password hash string or false <ide> */ <ide> abstract public function hash($password); <ide> abstract public function hash($password); <ide> * Check hash. Generate hash from user provided password string or data array <ide> * and check against existing hash. <ide> * <del> * @param string|array $password Plain text password to hash or data array. <add> * @param string $password Plain text password to hash. <ide> * @param string $hashedPassword Existing hashed password. <ide> * @return bool True if hashes match else false. <ide> */ <ide><path>src/Console/ConsoleIo.php <ide> public function level($level = null) <ide> /** <ide> * Output at the verbose level. <ide> * <del> * @param string|array $message A string or an array of strings to output <add> * @param string|string[] $message A string or an array of strings to output <ide> * @param int $newlines Number of newlines to append <ide> * @return int|bool The number of bytes returned from writing to stdout. <ide> */ <ide> public function verbose($message, $newlines = 1) <ide> /** <ide> * Output at all levels. <ide> * <del> * @param string|array $message A string or an array of strings to output <add> * @param string|string[] $message A string or an array of strings to output <ide> * @param int $newlines Number of newlines to append <ide> * @return int|bool The number of bytes returned from writing to stdout. <ide> */ <ide> public function quiet($message, $newlines = 1) <ide> * present in most shells. Using ConsoleIo::QUIET for a message means it will always display. <ide> * While using ConsoleIo::VERBOSE means it will only display when verbose output is toggled. <ide> * <del> * @param string|array $message A string or an array of strings to output <add> * @param string|string[] $message A string or an array of strings to output <ide> * @param int $newlines Number of newlines to append <ide> * @param int $level The message's output level, see above. <ide> * @return int|bool The number of bytes returned from writing to stdout. <ide> public function out($message = '', $newlines = 1, $level = self::NORMAL) <ide> /** <ide> * Convenience method for out() that wraps message between <info /> tag <ide> * <del> * @param string|array|null $message A string or an array of strings to output <add> * @param string|string[]|null $message A string or an array of strings to output <ide> * @param int $newlines Number of newlines to append <ide> * @param int $level The message's output level, see above. <ide> * @return int|bool The number of bytes returned from writing to stdout. <ide> public function info($message = null, $newlines = 1, $level = self::NORMAL) <ide> /** <ide> * Convenience method for err() that wraps message between <warning /> tag <ide> * <del> * @param string|array|null $message A string or an array of strings to output <add> * @param string|string[]|null $message A string or an array of strings to output <ide> * @param int $newlines Number of newlines to append <ide> * @return int|bool The number of bytes returned from writing to stderr. <ide> * @see https://book.cakephp.org/3.0/en/console-and-shells.html#ConsoleIo::err <ide> public function warning($message = null, $newlines = 1) <ide> /** <ide> * Convenience method for err() that wraps message between <error /> tag <ide> * <del> * @param string|array|null $message A string or an array of strings to output <add> * @param string|string[]|null $message A string or an array of strings to output <ide> * @param int $newlines Number of newlines to append <ide> * @return int|bool The number of bytes returned from writing to stderr. <ide> * @see https://book.cakephp.org/3.0/en/console-and-shells.html#ConsoleIo::err <ide> public function error($message = null, $newlines = 1) <ide> /** <ide> * Convenience method for out() that wraps message between <success /> tag <ide> * <del> * @param string|array|null $message A string or an array of strings to output <add> * @param string|string[]|null $message A string or an array of strings to output <ide> * @param int $newlines Number of newlines to append <ide> * @param int $level The message's output level, see above. <ide> * @return int|bool The number of bytes returned from writing to stdout. <ide> public function overwrite($message, $newlines = 1, $size = null) <ide> * Outputs a single or multiple error messages to stderr. If no parameters <ide> * are passed outputs just a newline. <ide> * <del> * @param string|array $message A string or an array of strings to output <add> * @param string|string[] $message A string or an array of strings to output <ide> * @param int $newlines Number of newlines to append <ide> * @return int|bool The number of bytes returned from writing to stderr. <ide> */ <ide><path>src/Console/Shell.php <ide> public function wrapText($text, $options = []) <ide> /** <ide> * Output at the verbose level. <ide> * <del> * @param string|array $message A string or an array of strings to output <add> * @param string|string[] $message A string or an array of strings to output <ide> * @param int $newlines Number of newlines to append <ide> * @return int|bool The number of bytes returned from writing to stdout. <ide> */ <ide> public function verbose($message, $newlines = 1) <ide> /** <ide> * Output at all levels. <ide> * <del> * @param string|array $message A string or an array of strings to output <add> * @param string|string[] $message A string or an array of strings to output <ide> * @param int $newlines Number of newlines to append <ide> * @return int|bool The number of bytes returned from writing to stdout. <ide> */ <ide> public function quiet($message, $newlines = 1) <ide> * present in most shells. Using Shell::QUIET for a message means it will always display. <ide> * While using Shell::VERBOSE means it will only display when verbose output is toggled. <ide> * <del> * @param string|array|null $message A string or an array of strings to output <add> * @param string|string[]|null $message A string or an array of strings to output <ide> * @param int $newlines Number of newlines to append <ide> * @param int $level The message's output level, see above. <ide> * @return int|bool The number of bytes returned from writing to stdout. <ide> public function out($message = null, $newlines = 1, $level = Shell::NORMAL) <ide> * Outputs a single or multiple error messages to stderr. If no parameters <ide> * are passed outputs just a newline. <ide> * <del> * @param string|array|null $message A string or an array of strings to output <add> * @param string|string[]|null $message A string or an array of strings to output <ide> * @param int $newlines Number of newlines to append <ide> * @return int|bool The number of bytes returned from writing to stderr. <ide> */ <ide> public function err($message = null, $newlines = 1) <ide> /** <ide> * Convenience method for out() that wraps message between <info /> tag <ide> * <del> * @param string|array|null $message A string or an array of strings to output <add> * @param string|string[]|null $message A string or an array of strings to output <ide> * @param int $newlines Number of newlines to append <ide> * @param int $level The message's output level, see above. <ide> * @return int|bool The number of bytes returned from writing to stdout. <ide> public function info($message = null, $newlines = 1, $level = Shell::NORMAL) <ide> /** <ide> * Convenience method for err() that wraps message between <warning /> tag <ide> * <del> * @param string|array|null $message A string or an array of strings to output <add> * @param string|string[]|null $message A string or an array of strings to output <ide> * @param int $newlines Number of newlines to append <ide> * @return int|bool The number of bytes returned from writing to stderr. <ide> * @see https://book.cakephp.org/3.0/en/console-and-shells.html#Shell::err <ide> public function warn($message = null, $newlines = 1) <ide> /** <ide> * Convenience method for out() that wraps message between <success /> tag <ide> * <del> * @param string|array|null $message A string or an array of strings to output <add> * @param string|string[]|null $message A string or an array of strings to output <ide> * @param int $newlines Number of newlines to append <ide> * @param int $level The message's output level, see above. <ide> * @return int|bool The number of bytes returned from writing to stdout. <ide><path>src/Http/CorsBuilder.php <ide> public function allowCredentials() <ide> /** <ide> * Whitelist headers that can be sent in CORS requests. <ide> * <del> * @param array $headers The list of headers to accept in CORS requests. <add> * @param string[] $headers The list of headers to accept in CORS requests. <ide> * @return $this <ide> */ <ide> public function allowHeaders(array $headers) <ide> public function allowHeaders(array $headers) <ide> /** <ide> * Define the headers a client library/browser can expose to scripting <ide> * <del> * @param array $headers The list of headers to expose CORS responses <add> * @param string[] $headers The list of headers to expose CORS responses <ide> * @return $this <ide> */ <ide> public function exposeHeaders(array $headers) <ide><path>src/Http/Response.php <ide> public function withCookieCollection(CookieCollection $cookieCollection) <ide> * Instead the builder object should be used. <ide> * <ide> * @param \Cake\Http\ServerRequest $request Request object <del> * @param string|array $allowedDomains List of allowed domains, see method description for more details <del> * @param string|array $allowedMethods List of HTTP verbs allowed <del> * @param string|array $allowedHeaders List of HTTP headers allowed <add> * @param string|string[] $allowedDomains List of allowed domains, see method description for more details <add> * @param string|string[] $allowedMethods List of HTTP verbs allowed <add> * @param string|string[] $allowedHeaders List of HTTP headers allowed <ide> * @return \Cake\Http\CorsBuilder A builder object the provides a fluent interface for defining <ide> * additional CORS headers. <ide> */ <ide><path>src/ORM/AssociationCollection.php <ide> public function type($class) <ide> /** <ide> * Get an array of associations matching a specific type. <ide> * <del> * @param string|array $class The type of associations you want. <add> * @param string|string[] $class The type of associations you want. <ide> * For example 'BelongsTo' or array like ['BelongsTo', 'HasOne'] <ide> * @return array An array of Association objects. <ide> * @since 3.5.3 <ide><path>src/ORM/RulesChecker.php <ide> public function isUnique(array $fields, $message = null) <ide> * 'message' sets a custom error message. <ide> * Set 'allowNullableNulls' to true to accept composite foreign keys where one or more nullable columns are null. <ide> * <del> * @param string|array $field The field or list of fields to check for existence by <add> * @param string|string[] $field The field or list of fields to check for existence by <ide> * primary key lookup in the other table. <ide> * @param object|string $table The table name where the fields existence will be checked. <ide> * @param string|array|null $message The error message to show in case the rule does not pass. Can <ide><path>src/TestSuite/Stub/ConsoleOutput.php <ide> class ConsoleOutput extends ConsoleOutputBase <ide> /** <ide> * Write output to the buffer. <ide> * <del> * @param string|array $message A string or an array of strings to output <add> * @param string|string[] $message A string or an array of strings to output <ide> * @param int $newlines Number of newlines to append <ide> * @return void <ide> */
8
PHP
PHP
fix invalid method usage
0c112e4b2892eac35d81c56f00a2812df20cf184
<ide><path>src/Cache/CacheEngine.php <ide> public function writeMany(array $data): array <ide> { <ide> $return = []; <ide> foreach ($data as $key => $value) { <del> $return[$key] = $this->write($key, $value); <add> $return[$key] = $this->set($key, $value); <ide> } <ide> <ide> return $return; <ide> public function readMany(array $keys): array <ide> { <ide> $return = []; <ide> foreach ($keys as $key) { <del> $return[$key] = $this->read($key); <add> $return[$key] = $this->get($key); <ide> } <ide> <ide> return $return; <ide> public function readMany(array $keys): array <ide> * <ide> * @param iterable $keys A list of keys that can obtained in a single operation. <ide> * @param mixed $default Default value to return for keys that do not exist. <del> * @return iterable A list of key => value pairs. Cache keys that do not exist or are stale will have $default as value. <add> * @return array A list of key => value pairs. Cache keys that do not exist or are stale will have $default as value. <ide> * @throws \Cake\Cache\InvalidArgumentException If $keys is neither an array nor a Traversable, <ide> * or if any of the $keys are not a legal value. <ide> */ <ide><path>src/Datasource/QueryCacher.php <ide> public function fetch($query) <ide> { <ide> $key = $this->_resolveKey($query); <ide> $storage = $this->_resolveCacher(); <del> $result = $storage->read($key); <add> $result = $storage->get($key); <ide> if (empty($result)) { <ide> return null; <ide> } <ide> public function store($query, Traversable $results): bool <ide> $key = $this->_resolveKey($query); <ide> $storage = $this->_resolveCacher(); <ide> <del> return (bool)$storage->write($key, $results); <add> return (bool)$storage->set($key, $results); <ide> } <ide> <ide> /** <ide><path>src/I18n/TranslatorRegistry.php <ide> public function get($name, $locale = null) <ide> } <ide> <ide> $key = "translations.$name.$locale"; <del> $translator = $this->_cacher->read($key); <add> $translator = $this->_cacher->get($key); <ide> if (!$translator || !$translator->getPackage()) { <ide> $translator = $this->_getTranslator($name, $locale); <del> $this->_cacher->write($key, $translator); <add> $this->_cacher->set($key, $translator); <ide> } <ide> <ide> return $this->registry[$name][$locale] = $translator; <ide><path>tests/TestCase/Database/Schema/CollectionTest.php <ide> public function setUp() <ide> { <ide> parent::setUp(); <ide> $this->connection = ConnectionManager::get('test'); <del> Cache::clear(false, '_cake_model_'); <add> Cache::clear('_cake_model_'); <ide> Cache::enable(); <ide> } <ide> <ide><path>tests/TestCase/Http/Session/CacheSessionTest.php <ide> public function setUp() <ide> public function tearDown() <ide> { <ide> parent::tearDown(); <del> Cache::clear(false, 'session_test'); <add> Cache::clear('session_test'); <ide> Cache::drop('session_test'); <ide> unset($this->storage); <ide> } <ide><path>tests/TestCase/I18n/I18nTest.php <ide> public function tearDown() <ide> I18n::setDefaultFormatter('default'); <ide> I18n::setLocale($this->locale); <ide> Plugin::unload(); <del> Cache::clear(false, '_cake_core_'); <add> Cache::clear('_cake_core_'); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/I18n/Parser/PoFileParserTest.php <ide> public function tearDown() <ide> parent::tearDown(); <ide> I18n::clear(); <ide> I18n::setLocale($this->locale); <del> Cache::clear(false, '_cake_core_'); <add> Cache::clear('_cake_core_'); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Routing/Middleware/RoutingMiddlewareTest.php <ide> public function testCacheRoutes() <ide> $middleware = new RoutingMiddleware($app, $cacheConfigName); <ide> $middleware($request, $response, $next); <ide> <del> Cache::clear(false, $cacheConfigName); <add> Cache::clear($cacheConfigName); <ide> Cache::drop($cacheConfigName); <ide> } <ide> <ide> public function testCacheNotUsedIfCacheDisabled() <ide> $middleware = new RoutingMiddleware($app, $cacheConfigName); <ide> $middleware($request, $response, $next); <ide> <del> Cache::clear(false, $cacheConfigName); <add> Cache::clear($cacheConfigName); <ide> Cache::drop($cacheConfigName); <ide> Cache::enable(); <ide> } <ide><path>tests/TestCase/View/ViewTest.php <ide> public function testElementCache() <ide> 'path' => CACHE . 'views/', <ide> 'prefix' => '', <ide> ]); <del> Cache::clear(false, 'test_view'); <add> Cache::clear('test_view'); <ide> <ide> $View = $this->PostsController->createView(); <ide> $View->setElementCache('test_view'); <ide> public function testElementCache() <ide> $result = Cache::read('element__test_element_param_foo', 'test_view'); <ide> $this->assertEquals($expected, $result); <ide> <del> Cache::clear(true, 'test_view'); <add> Cache::clear('test_view'); <ide> Cache::drop('test_view'); <ide> } <ide>
9
Javascript
Javascript
kill array suites
30702be41b358b5cb8e65f3c66bb484342003d56
<ide><path>packages/ember-runtime/tests/mixins/array_test.js <ide> import { <ide> computed <ide> } from 'ember-metal'; <ide> import { testBoth } from 'internal-test-helpers'; <del>import { ArrayTests } from '../suites/array'; <ide> import EmberObject from '../../system/object'; <ide> import EmberArray, { <ide> addArrayObserver, <ide> const TestArray = EmberObject.extend(EmberArray, { <ide> }) <ide> }); <ide> <del> <del>ArrayTests.extend({ <del> <del> name: 'Basic Ember Array', <del> <del> newObject(ary) { <del> ary = ary ? ary.slice() : this.newFixture(3); <del> return new TestArray({ _content: ary }); <del> }, <del> <del> // allows for testing of the basic enumerable after an internal mutation <del> mutate(obj) { <del> obj.addObject(this.getFixture(1)[0]); <del> }, <del> <del> toArray(obj) { <del> return obj.slice(); <del> } <del> <del>}).run(); <add>QUnit.module('Ember.Array'); <ide> <ide> QUnit.test('the return value of slice has Ember.Array applied', function(assert) { <ide> let x = EmberObject.extend(EmberArray).create({ <ide><path>packages/ember-runtime/tests/mixins/copyable_test.js <del>import { generateGuid } from 'ember-utils'; <del>import CopyableTests from '../suites/copyable'; <del>import Copyable from '../../mixins/copyable'; <del>import EmberObject from '../../system/object'; <del>import { set, get } from 'ember-metal'; <del> <del>QUnit.module('Ember.Copyable'); <del> <del>const CopyableObject = EmberObject.extend(Copyable, { <del> id: null, <del> <del> init() { <del> this._super(...arguments); <del> set(this, 'id', generateGuid()); <del> }, <del> <del> copy() { <del> let ret = new CopyableObject(); <del> set(ret, 'id', get(this, 'id')); <del> return ret; <del> } <del>}); <del> <del>CopyableTests.extend({ <del> <del> name: 'Copyable Basic Test', <del> <del> newObject() { <del> return new CopyableObject(); <del> }, <del> <del> isEqual(a, b) { <del> if (!(a instanceof CopyableObject) || !(b instanceof CopyableObject)) { <del> return false; <del> } <del> <del> return get(a, 'id') === get(b, 'id'); <del> } <del>}).run(); <ide><path>packages/ember-runtime/tests/mixins/mutable_array_test.js <del>import { computed } from 'ember-metal'; <del>import MutableArrayTests from '../suites/mutable_array'; <del>import EmberObject from '../../system/object'; <del>import { A as emberA, MutableArray } from '../../mixins/array'; <del>import { <del> arrayContentDidChange, <del> arrayContentWillChange <del>} from '../../mixins/array'; <del> <del>/* <del> Implement a basic fake mutable array. This validates that any non-native <del> enumerable can impl this API. <del>*/ <del>const TestMutableArray = EmberObject.extend(MutableArray, { <del> <del> _content: null, <del> <del> init(ary = []) { <del> this._content = emberA(ary); <del> }, <del> <del> replace(idx, amt, objects) { <del> let args = objects ? objects.slice() : []; <del> let removeAmt = amt; <del> let addAmt = args.length; <del> <del> arrayContentWillChange(this, idx, removeAmt, addAmt); <del> <del> args.unshift(amt); <del> args.unshift(idx); <del> this._content.splice.apply(this._content, args); <del> arrayContentDidChange(this, idx, removeAmt, addAmt); <del> return this; <del> }, <del> <del> objectAt(idx) { <del> return this._content[idx]; <del> }, <del> <del> length: computed(function() { <del> return this._content.length; <del> }), <del> <del> slice() { <del> return this._content.slice(); <del> } <del> <del>}); <del> <del> <del>MutableArrayTests.extend({ <del> <del> name: 'Basic Mutable Array', <del> <del> newObject(ary) { <del> ary = ary ? ary.slice() : this.newFixture(3); <del> return new TestMutableArray(ary); <del> }, <del> <del> // allows for testing of the basic enumerable after an internal mutation <del> mutate(obj) { <del> obj.addObject(this.getFixture(1)[0]); <del> }, <del> <del> toArray(obj) { <del> return obj.slice(); <del> } <del> <del>}).run(); <ide><path>packages/ember-runtime/tests/suites/array.js <del>import { guidFor, generateGuid } from 'ember-utils'; <del>import { Suite } from './suite'; <del>import { computed, get } from 'ember-metal'; <del>import { <del> addArrayObserver, <del> removeArrayObserver <del>} from '../../mixins/array'; <del>import EmberObject from '../../system/object'; <del> <del>const ArrayTestsObserverClass = EmberObject.extend({ <del> init() { <del> this._super(...arguments); <del> this.isEnabled = true; <del> this.reset(); <del> }, <del> <del> reset() { <del> this._keys = {}; <del> this._values = {}; <del> this._before = null; <del> this._after = null; <del> return this; <del> }, <del> <del> observe(obj) { <del> if (obj.addObserver) { <del> let keys = Array.prototype.slice.call(arguments, 1); <del> let loc = keys.length; <del> <del> while (--loc >= 0) { <del> obj.addObserver(keys[loc], this, 'propertyDidChange'); <del> } <del> } else { <del> this.isEnabled = false; <del> } <del> return this; <del> }, <del> <del> observeArray(obj) { <del> addArrayObserver(obj, this); <del> return this; <del> }, <del> <del> stopObserveArray(obj) { <del> removeArrayObserver(obj, this); <del> return this; <del> }, <del> <del> propertyDidChange(target, key, value) { <del> if (this._keys[key] === undefined) { this._keys[key] = 0; } <del> this._keys[key]++; <del> this._values[key] = value; <del> }, <del> <del> arrayWillChange() { <del> QUnit.config.current.assert.equal(this._before, null, 'should only call once'); <del> this._before = Array.prototype.slice.call(arguments); <del> }, <del> <del> arrayDidChange() { <del> QUnit.config.current.assert.equal(this._after, null, 'should only call once'); <del> this._after = Array.prototype.slice.call(arguments); <del> }, <del> <del> validate(key, value) { <del> if (!this.isEnabled) { <del> return true; <del> } <del> <del> if (!this._keys[key]) { <del> return false; <del> } <del> <del> if (arguments.length > 1) { <del> return this._values[key] === value; <del> } else { <del> return true; <del> } <del> }, <del> <del> timesCalled(key) { <del> return this._keys[key] || 0; <del> } <del>}); <del> <del>const ArrayTests = Suite.extend({ <del> /* <del> __Required.__ You must implement this method to apply this mixin. <del> <del> Implement to return a new enumerable object for testing. Should accept <del> either no parameters, a single number (indicating the desired length of <del> the collection) or an array of objects. <del> <del> @param {Array} content <del> An array of items to include in the enumerable optionally. <del> <del> @returns {Ember.Enumerable} a new enumerable <del> */ <del> newObject: null, <del> <del> /* <del> Implement to return a set of new fixture strings that can be applied to <del> the enumerable. This may be passed into the newObject method. <del> <del> @param {Number} count <del> The number of items required. <del> <del> @returns {Array} array of strings <del> */ <del> newFixture(cnt) { <del> let ret = []; <del> while (--cnt >= 0) { <del> ret.push(generateGuid()); <del> } <del> <del> return ret; <del> }, <del> <del> /* <del> Implement to return a set of new fixture objects that can be applied to <del> the enumerable. This may be passed into the newObject method. <del> <del> @param {Number} cnt <del> The number of items required. <del> <del> @returns {Array} array of objects <del> */ <del> newObjectsFixture(cnt) { <del> let ret = []; <del> let item; <del> while (--cnt >= 0) { <del> item = {}; <del> guidFor(item); <del> ret.push(item); <del> } <del> return ret; <del> }, <del> <del> /* <del> __Required.__ You must implement this method to apply this mixin. <del> <del> Implement accept an instance of the enumerable and return an array <del> containing the objects in the enumerable. This is used only for testing <del> so performance is not important. <del> <del> @param {Ember.Enumerable} enumerable <del> The enumerable to convert. <del> <del> @returns {Array} array of items <del> */ <del> toArray: null, <del> <del> /* <del> Implement this method if your object can mutate internally (even if it <del> does not support the MutableEnumerable API). The method should accept <del> an object of your desired type and modify it somehow. Suite tests will <del> use this to ensure that all appropriate caches, etc. clear when the <del> mutation occurs. <del> <del> If you do not define this optional method, then mutation-related tests <del> will be skipped. <del> <del> @param {Ember.Enumerable} enumerable <del> The enumerable to mutate <del> <del> @returns {void} <del> */ <del> mutate() {}, <del> <del> /* <del> Becomes true when you define a new mutate() method, indicating that <del> mutation tests should run. This is calculated automatically. <del> <del> @type Boolean <del> */ <del> canTestMutation: computed(function() { <del> return this.mutate !== ArrayTests.prototype.mutate; <del> }), <del> <del> /* <del> Invoked to actually run the test - overridden by mixins <del> */ <del> run() {}, <del> <del> /* <del> Creates a new observer object for testing. You can add this object as an <del> observer on an array and it will record results anytime it is invoked. <del> After running the test, call the validate() method on the observer to <del> validate the results. <del> */ <del> newObserver(/* obj */) { <del> let ret = get(this, 'observerClass').create(); <del> <del> if (arguments.length > 0) { <del> ret.observe.apply(ret, arguments); <del> } <del> <del> return ret; <del> }, <del> <del> observerClass: ArrayTestsObserverClass <del>}); <del> <del>export { ArrayTests }; <ide><path>packages/ember-runtime/tests/suites/copyable.js <del>import { Suite } from './suite'; <del> <del>const CopyableTests = Suite.extend({ <del> <del> /* <del> __Required.__ You must implement this method to apply this mixin. <del> <del> Must be able to create a new object for testing. <del> <del> @returns {Object} object <del> */ <del> newObject: null, <del> <del> /* <del> __Required.__ You must implement this method to apply this mixin. <del> <del> Compares the two passed in objects. Returns true if the two objects <del> are logically equivalent. <del> <del> @param {Object} a <del> First object <del> <del> @param {Object} b <del> Second object <del> <del> @returns {Boolean} <del> */ <del> isEqual: null <del> <del>}); <del> <del>export default CopyableTests; <ide><path>packages/ember-runtime/tests/suites/mutable_array.js <del>import { ArrayTests } from './array'; <del> <del>const MutableArrayTests = ArrayTests.extend(); <del> <del>export default MutableArrayTests; <ide><path>packages/ember-runtime/tests/suites/suite.js <del>import { guidFor } from 'ember-utils'; <del>import EmberObject from '../../system/object'; <del>import { get } from 'ember-metal'; <del> <del>/* <del> @class <del> A Suite can be used to define a reusable set of unit tests that can be <del> applied to any object. Suites are most useful for defining tests that <del> work against a mixin or plugin API. Developers implementing objects that <del> use the mixin or support the API can then run these tests against their <del> own code to verify compliance. <del> <del> To define a suite, you need to define the tests themselves as well as a <del> callback API implementers can use to tie your tests to their specific class. <del> <del> ## Defining a Callback API <del> <del> To define the callback API, just extend this class and add your properties <del> or methods that must be provided. <del> <del> ## Defining Unit Tests <del> <del> To add unit tests, use the suite.module() or suite.test() methods instead <del> of a regular module() or test() method when defining your tests. This will <del> add the tests to the suite. <del> <del> ## Using a Suite <del> <del> To use a Suite to test your own objects, extend the suite subclass and <del> define any required methods. Then call run() on the new subclass. This <del> will create an instance of your class and then defining the unit tests. <del> <del> @extends Ember.Object <del> @private <del>*/ <del>const Suite = EmberObject.extend({ <del> <del> /* <del> __Required.__ You must implement this method to apply this mixin. <del> <del> Define a name for these tests - all modules are prefixed w/ it. <del> <del> @type String <del> */ <del> name: null, <del> <del> /* <del> Invoked to actually run the test - overridden by mixins <del> */ <del> run() {} <del> <del>}); <del> <del>Suite.reopenClass({ <del> <del> plan: null, <del> <del> run() { <del> let C = this; <del> return new C().run(); <del> }, <del> <del> module(desc, opts) { <del> if (!opts) { <del> opts = {}; <del> } <del> <del> let setup = opts.setup || opts.beforeEach; <del> let teardown = opts.teardown || opts.afterEach; <del> this.reopen({ <del> run() { <del> this._super(...arguments); <del> let title = get(this, 'name') + ': ' + desc; <del> let ctx = this; <del> QUnit.module(title, { <del> beforeEach(assert) { <del> if (setup) { <del> setup.call(ctx, assert); <del> } <del> }, <del> <del> afterEach(assert) { <del> if (teardown) { <del> teardown.call(ctx, assert); <del> } <del> } <del> }); <del> } <del> }); <del> }, <del> <del> test(name, func) { <del> this.reopen({ <del> run() { <del> this._super(...arguments); <del> let ctx = this; <del> <del> if (!func) { <del> QUnit.test(name); // output warning <del> } else { <del> QUnit.test(name, (assert) => func.call(ctx, assert)); <del> } <del> } <del> }); <del> }, <del> <del> // convert to guids to minimize logging. <del> same(actual, exp, message) { <del> actual = (actual && actual.map) ? actual.map(x => guidFor(x)) : actual; <del> exp = (exp && exp.map) ? exp.map(x => guidFor(x)) : exp; <del> return deepEqual(actual, exp, message); <del> }, <del> <del> // easy way to disable tests <del> notest() {}, <del> <del> importModuleTests(builder) { <del> this.module(builder._module); <del> <del> builder._tests.forEach((descAndFunc) => { <del> this.test.apply(this, descAndFunc); <del> }); <del> } <del>}); <del> <del>const SuiteModuleBuilder = EmberObject.extend({ <del> _module: null, <del> _tests: null, <del> <del> init() { <del> this._tests = []; <del> }, <del> <del> module(name) { this._module = name; }, <del> <del> test(name, func) { <del> this._tests.push([name, func]); <del> } <del>}); <del> <del>export { SuiteModuleBuilder, Suite }; <del> <del>export default Suite; <ide><path>packages/ember-runtime/tests/system/array_proxy/suite_test.js <del>import MutableArrayTests from '../../suites/mutable_array'; <del>import ArrayProxy from '../../../system/array_proxy'; <del>import { get } from 'ember-metal'; <del>import { A as emberA } from '../../../mixins/array'; <del> <del>MutableArrayTests.extend({ <del> name: 'Ember.ArrayProxy', <del> <del> newObject(ary) { <del> let ret = ary ? ary.slice() : this.newFixture(3); <del> return ArrayProxy.create({ content: emberA(ret) }); <del> }, <del> <del> mutate(obj) { <del> obj.pushObject(get(obj, 'length') + 1); <del> }, <del> <del> toArray(obj) { <del> return obj.toArray ? obj.toArray() : obj.slice(); <del> } <del>}).run(); <ide><path>packages/ember-runtime/tests/system/native_array/copyable_suite_test.js <del>import { generateGuid } from 'ember-utils'; <ide> import { A as emberA } from '../../../mixins/array'; <del>import CopyableTests from '../../suites/copyable'; <del> <del>CopyableTests.extend({ <del> name: 'NativeArray Copyable', <del> <del> newObject() { <del> return emberA([generateGuid()]); <del> }, <del> <del> isEqual(a, b) { <del> if (!(a instanceof Array)) { <del> return false; <del> } <del> <del> if (!(b instanceof Array)) { <del> return false; <del> } <del> <del> if (a.length !== b.length) { <del> return false; <del> } <del> <del> return a[0] === b[0]; <del> } <del> <del>}).run(); <ide> <ide> QUnit.module('NativeArray Copyable'); <ide> <ide><path>packages/ember-runtime/tests/system/native_array/suite_test.js <del>import { A as emberA } from '../../../mixins/array'; <del>import MutableArrayTests from '../../suites/mutable_array'; <del> <del>MutableArrayTests.extend({ <del> name: 'Native Array', <del> <del> newObject(ary) { <del> return emberA(ary ? ary.slice() : this.newFixture(3)); <del> }, <del> <del> mutate(obj) { <del> obj.pushObject(obj.length + 1); <del> }, <del> <del> toArray(obj) { <del> return obj.slice(); // make a copy. <del> } <del>}).run();
10
Text
Text
fix spelling mistake from "simlar" to "similar"
5e0232236a12e905ed1449b8d82746da7a92c07d
<ide><path>README.md <ide> MIT (http://www.opensource.org/licenses/mit-license.php) <ide> (In chronological order) <ide> <ide> * @google for [Google Web Toolkit (GWT)](https://code.google.com/p/google-web-toolkit), which aims to compile Java to JavaScript. It features a similar [Code Splitting](https://code.google.com/p/google-web-toolkit/wiki/CodeSplitting) as webpack. <del>* @medikoo for [modules-webmake](https://github.com/medikoo/modules-webmake), which is a simlar project. webpack was born because I wanted Code Splitting for modules-webpack. Interestingly the [Code Splitting issue is still open](https://github.com/medikoo/modules-webmake/issues/7) (thanks also to @Phoscur for the discussion). <add>* @medikoo for [modules-webmake](https://github.com/medikoo/modules-webmake), which is a similar project. webpack was born because I wanted Code Splitting for modules-webpack. Interestingly the [Code Splitting issue is still open](https://github.com/medikoo/modules-webmake/issues/7) (thanks also to @Phoscur for the discussion). <ide> * @substack for [browserify](http://browserify.org/), which is a similar project and source for many ideas. <ide> * @jrburke for [require.js](http://requirejs.org/), which is a similar project and source for many ideas. <ide> * @defunctzombie for the [browser-field spec](https://gist.github.com/defunctzombie/4339901), which makes modules available for node.js, browserify and webpack.
1
Ruby
Ruby
instance_writer => false
60bbf16bfd60493c05bf9c9c70ec962a0c482155
<ide><path>activesupport/lib/active_support/core_ext/class/attribute.rb <ide> class Class <ide> # For convenience, a query method is defined as well: <ide> # <ide> # Subclass.setting? # => false <add> # <add> # Instances may overwrite the class value in the same way: <add> # <add> # Base.setting = true <add> # object = Base.new <add> # object.setting # => true <add> # object.setting = false <add> # object.setting # => false <add> # Base.setting # => true <add> # <add> # To opt out of the instance writer method, pass :instance_writer => false. <add> # <add> # object.setting = false # => NoMethodError <ide> def class_attribute(*attrs) <add> instance_writer = !attrs.last.is_a?(Hash) || attrs.pop[:instance_writer] <add> <ide> s = singleton_class <ide> attrs.each do |attr| <ide> s.send(:define_method, attr) { } <del> s.send(:define_method, "#{attr}?") { !!send(attr) } <del> s.send(:define_method, "#{attr}=") do |value| <add> s.send(:define_method, :"#{attr}?") { !!send(attr) } <add> s.send(:define_method, :"#{attr}=") do |value| <ide> singleton_class.send(:define_method, attr) { value } <ide> end <add> <add> define_method(attr) { self.class.send(attr) } <add> define_method(:"#{attr}?") { !!send(attr) } <add> define_method(:"#{attr}=") do |value| <add> singleton_class.send(:define_method, attr) { value } <add> end if instance_writer <ide> end <ide> end <ide> end <ide><path>activesupport/test/core_ext/class/attribute_test.rb <ide> require 'active_support/core_ext/class/attribute' <ide> <ide> class ClassAttributeTest < ActiveSupport::TestCase <del> class Base <del> class_attribute :setting <del> end <del> <del> class Subclass < Base <del> end <del> <ide> def setup <ide> @klass = Class.new { class_attribute :setting } <ide> @sub = Class.new(@klass) <ide> def setup <ide> assert_equal true, @klass.setting? <ide> end <ide> <del> test 'no instance delegates' do <del> assert_raise(NoMethodError) { @klass.new.setting } <del> assert_raise(NoMethodError) { @klass.new.setting? } <add> test 'instance reader delegates to class' do <add> assert_nil @klass.new.setting <add> <add> @klass.setting = 1 <add> assert_equal 1, @klass.new.setting <add> end <add> <add> test 'instance override' do <add> object = @klass.new <add> object.setting = 1 <add> assert_nil @klass.setting <add> @klass.setting = 2 <add> assert_equal 1, object.setting <add> end <add> <add> test 'instance query' do <add> object = @klass.new <add> assert_equal false, object.setting? <add> object.setting = 1 <add> assert_equal true, object.setting? <add> end <add> <add> test 'disabling instance writer' do <add> object = Class.new { class_attribute :setting, :instance_writer => false }.new <add> assert_raise(NoMethodError) { object.setting = 'boom' } <ide> end <ide> end
2
Javascript
Javascript
fix failing tests
3c348928abc44e91ca1c6f51b539b337fbcb1265
<ide><path>packages/ember-routing/lib/routable.js <ide> Ember.Routable = Ember.Mixin.create({ <ide> */ <ide> stashContext: function(manager, context) { <ide> var serialized = this.serialize(manager, context); <del> Ember.assert('serialize must return a hash', typeof serialized === 'object'); <add> Ember.assert('serialize must return a hash', !serialized || typeof serialized === 'object'); <ide> <ide> manager.setStateMeta(this, 'serialized', serialized); <ide>
1
PHP
PHP
remove param $confirmmessage
f97ddb13cefa2609210a499c912ed3311ed4f265
<ide><path>src/View/Helper/FormHelper.php <ide> public function postButton($title, $url, array $options = array()) { <ide> } <ide> <ide> /** <del> * Creates an HTML link, but access the URL using the method you specify (defaults to POST). <del> * Requires javascript to be enabled in browser. <add> * Creates an HTML link, but access the URL using the method you specify <add> * (defaults to POST). Requires javascript to be enabled in browser. <ide> * <del> * This method creates a `<form>` element. So do not use this method inside an existing form. <del> * Instead you should add a submit button using FormHelper::submit() <add> * This method creates a `<form>` element. So do not use this method inside an <add> * existing form. Instead you should add a submit button using FormHelper::submit() <ide> * <ide> * ### Options: <ide> * <ide> * - `data` - Array with key/value to pass in input hidden <del> * - `method` - Request method to use. Set to 'delete' to simulate HTTP/1.1 DELETE request. Defaults to 'post'. <del> * - `confirm` - Can be used instead of $confirmMessage. <add> * - `method` - Request method to use. Set to 'delete' to simulate <add> * HTTP/1.1 DELETE request. Defaults to 'post'. <add> * - `confirm` - Confirm message to show. <ide> * - `block` - Set to true to append form to view block "postLink" or provide <ide> * custom block name. <ide> * - Other options are the same of HtmlHelper::link() method. <ide> * - The option `onclick` will be replaced. <ide> * <ide> * @param string $title The content to be wrapped by <a> tags. <del> * @param string|array $url Cake-relative URL or array of URL parameters, or external URL (starts with http://) <add> * @param string|array $url Cake-relative URL or array of URL parameters, or <add> * external URL (starts with http://) <ide> * @param array $options Array of HTML attributes. <del> * @param bool|string $confirmMessage JavaScript confirmation message. <ide> * @return string An `<a />` element. <ide> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::postLink <ide> */ <del> public function postLink($title, $url = null, array $options = array(), $confirmMessage = false) { <del> $options += array('block' => null); <add> public function postLink($title, $url = null, array $options = array()) { <add> $options += array('block' => null, 'confirm' => null); <ide> <ide> $requestMethod = 'POST'; <ide> if (!empty($options['method'])) { <ide> $requestMethod = strtoupper($options['method']); <ide> unset($options['method']); <ide> } <del> if (!empty($options['confirm'])) { <del> $confirmMessage = $options['confirm']; <del> unset($options['confirm']); <del> } <add> <add> $confirmMessage = $options['confirm']; <add> unset($options['confirm']); <ide> <ide> $formName = str_replace('.', '', uniqid('post_', true)); <ide> $formOptions = array( <ide><path>tests/TestCase/View/Helper/FormHelperTest.php <ide> public function testPostLink() { <ide> '/a' <ide> )); <ide> <del> $result = $this->Form->postLink('Delete', '/posts/delete/1', array(), 'Confirm?'); <add> $result = $this->Form->postLink('Delete', '/posts/delete/1', array('confirm' => 'Confirm?')); <ide> $this->assertTags($result, array( <ide> 'form' => array( <ide> 'method' => 'post', 'action' => '/posts/delete/1', <ide> public function testPostLink() { <ide> '/a' <ide> )); <ide> <del> $result = $this->Form->postLink('Delete', '/posts/delete/1', array('escape' => false), '\'Confirm\' this "deletion"?'); <add> $result = $this->Form->postLink( <add> 'Delete', <add> '/posts/delete/1', <add> array('escape' => false, 'confirm' => '\'Confirm\' this "deletion"?') <add> ); <ide> $this->assertTags($result, array( <ide> 'form' => array( <ide> 'method' => 'post', 'action' => '/posts/delete/1', <ide> public function testPostLink() { <ide> $result = $this->Form->postLink( <ide> '', <ide> array('controller' => 'items', 'action' => 'delete', 10), <del> array('class' => 'btn btn-danger', 'escape' => false), <del> 'Confirm thing' <add> array('class' => 'btn btn-danger', 'escape' => false, 'confirm' => 'Confirm thing') <ide> ); <ide> $this->assertTags($result, array( <ide> 'form' => array(
2
Java
Java
use real yoganodes in fabricreconcilertest
af2095842535c05613240215052fbcdd2f34ce64
<ide><path>ReactAndroid/src/test/java/com/facebook/react/fabric/FabricReconcilerTest.java <ide> import static org.fest.assertions.api.Assertions.assertThat; <ide> import static org.mockito.Mockito.mock; <ide> import static org.mockito.Mockito.when; <del>import static org.powermock.api.mockito.PowerMockito.mockStatic; <ide> <add>import com.facebook.react.bridge.CatalystInstance; <ide> import com.facebook.react.bridge.ReactApplicationContext; <del>import com.facebook.react.common.ClearableSynchronizedPool; <add>import com.facebook.react.bridge.ReactTestHelper; <ide> import com.facebook.react.fabric.FabricReconciler; <del>import com.facebook.react.modules.core.ReactChoreographer; <add>import com.facebook.react.fabric.FabricUIManager; <ide> import com.facebook.react.uimanager.NativeViewHierarchyManager; <ide> import com.facebook.react.uimanager.ReactShadowNode; <ide> import com.facebook.react.uimanager.ReactShadowNodeImpl; <del>import com.facebook.react.uimanager.ReactYogaConfigProvider; <ide> import com.facebook.react.uimanager.UIViewOperationQueue; <ide> import com.facebook.react.uimanager.ViewAtIndex; <del>import com.facebook.react.uimanager.YogaNodePool; <add>import com.facebook.react.uimanager.ThemedReactContext; <add>import com.facebook.react.uimanager.ViewManager; <add>import com.facebook.react.uimanager.ViewManagerRegistry; <ide> import com.facebook.testing.robolectric.v3.WithTestDefaultsRunner; <del>import com.facebook.yoga.YogaConfig; <del>import com.facebook.yoga.YogaNode; <ide> import java.util.ArrayList; <ide> import java.util.Arrays; <ide> import java.util.Collections; <ide> import java.util.List; <ide> import org.junit.Before; <ide> import org.junit.Test; <ide> import org.junit.runner.RunWith; <del>import org.mockito.invocation.InvocationOnMock; <del>import org.mockito.stubbing.Answer; <del>import org.powermock.api.mockito.PowerMockito; <del>import org.powermock.core.classloader.annotations.PowerMockIgnore; <del>import org.powermock.core.classloader.annotations.PrepareForTest; <ide> import org.robolectric.RuntimeEnvironment; <ide> <ide> /** Tests {@link FabricReconciler} */ <del>@PrepareForTest({ <del> ReactChoreographer.class, <del> ReactYogaConfigProvider.class, <del> YogaNodePool.class, <del>}) <ide> @RunWith(WithTestDefaultsRunner.class) <del>@PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "android.*"}) <ide> public class FabricReconcilerTest { <ide> <ide> private FabricReconciler mFabricReconciler; <add> private FabricUIManager mFabricUIManager; <ide> private MockUIViewOperationQueue mMockUIViewOperationQueue; <ide> <ide> @Before <ide> public void setUp() { <add> CatalystInstance catalystInstance = ReactTestHelper.createMockCatalystInstance(); <ide> ReactApplicationContext reactContext = <ide> new ReactApplicationContext(RuntimeEnvironment.application); <add> reactContext.initializeWithInstance(catalystInstance); <add> List<ViewManager> viewManagers = new ArrayList<>(); <add> ViewManagerRegistry viewManagerRegistry = new ViewManagerRegistry(viewManagers); <add> mFabricUIManager = new FabricUIManager(reactContext, viewManagerRegistry); <ide> mMockUIViewOperationQueue = new MockUIViewOperationQueue(reactContext); <ide> mFabricReconciler = new FabricReconciler(mMockUIViewOperationQueue); <del> <del> setupHacks(); <ide> } <ide> <ide> @Test <ide> public void testVirtualNodes() { <ide> assertThat(mMockUIViewOperationQueue.getOperations()).isEqualTo(expectedOperations); <ide> } <ide> <add> private void addChildren(ReactShadowNode parent, ReactShadowNode... children) { <add> for (ReactShadowNode child : children) { <add> mFabricUIManager.appendChild(parent, child); <add> } <add> } <add> <ide> private static ReactShadowNode createNode(int tag) { <ide> return createNode(tag, false); <ide> } <ide> private static ReactShadowNode createNode(int tag, boolean virtual) { <ide> node = new ReactShadowNodeImpl(); <ide> } <ide> node.setReactTag(tag); <add> node.setThemedContext(mock(ThemedReactContext.class)); <ide> return node; <ide> } <ide> <ide> private static class VirtualReactShadowNode extends ReactShadowNodeImpl { <ide> <add> VirtualReactShadowNode() {} <add> <add> VirtualReactShadowNode(VirtualReactShadowNode original) { <add> super(original); <add> } <add> <ide> @Override <ide> public boolean isVirtual() { <ide> return true; <ide> } <del> } <ide> <del> private static void addChildren(ReactShadowNode parent, ReactShadowNode... children) { <del> for (ReactShadowNode child : children) { <del> parent.addChildAt(child, parent.getChildCount()); <add> @Override <add> public ReactShadowNodeImpl copy() { <add> return new VirtualReactShadowNode(this); <ide> } <ide> } <ide> <ide> public List<ManageChildrenOperation> getOperations() { <ide> return Collections.unmodifiableList(mOperations); <ide> } <ide> } <del> <del> /** Hacks to get tests to start working end to end */ <del> private void setupHacks() { <del> // Hack around Yoga by mocking it out until the UnsatisfiedLinkErrors are fixed t14964130 <del> mockStatic(YogaNodePool.class, ReactYogaConfigProvider.class); <del> PowerMockito.when(YogaNodePool.get()) <del> .thenAnswer( <del> new Answer<Object>() { <del> @Override <del> public Object answer(InvocationOnMock invocation) throws Exception { <del> ClearableSynchronizedPool<YogaNode> yogaPool = <del> mock(ClearableSynchronizedPool.class); <del> YogaNode yogaNode = mock(YogaNode.class); <del> when(yogaNode.clone()).thenReturn(mock(YogaNode.class)); <del> when(yogaNode.isMeasureDefined()).thenReturn(true); <del> when(yogaPool.acquire()).thenReturn(yogaNode); <del> return yogaPool; <del> } <del> }); <del> PowerMockito.when(ReactYogaConfigProvider.get()) <del> .thenAnswer( <del> new Answer<Object>() { <del> @Override <del> public Object answer(InvocationOnMock invocation) { <del> return mock(YogaConfig.class); <del> } <del> }); <del> } <ide> }
1
Python
Python
fix a typo
86b6331967c723bf46cbfe7c2d0fa33d69ce6d1b
<ide><path>test/test_pricing.py <ide> def test_get_size_price(self): <ide> driver_name='foo', <ide> size_id='3') <ide> self.assertEqual(price1, 2) <del> self.assertEqual(price3, 3) <add> self.assertEqual(price2, 3) <ide> <ide> def test_invalid_pricing_cache(self): <ide> libcloud.pricing.PRICING_DATA['compute']['foo'] = { 2: 2 }
1
Javascript
Javascript
expose category property of ios notifications
dd8ed629a5ec2215e24b104dee45bef3fb08dc61
<ide><path>Libraries/PushNotificationIOS/PushNotificationIOS.js <ide> class PushNotificationIOS { <ide> _data: Object; <ide> _alert: string | Object; <ide> _sound: string; <add> _category: string; <ide> _badgeCount: number; <ide> _notificationId: string; <ide> _isRemote: boolean; <ide> class PushNotificationIOS { <ide> this._alert = notifVal.alert; <ide> this._sound = notifVal.sound; <ide> this._badgeCount = notifVal.badge; <add> this._category = notifVal.category; <ide> } else { <ide> this._data[notifKey] = notifVal; <ide> } <ide> class PushNotificationIOS { <ide> this._sound = nativeNotif.soundName; <ide> this._alert = nativeNotif.alertBody; <ide> this._data = nativeNotif.userInfo; <add> this._category = nativeNotif.category; <ide> } <ide> } <ide> <ide> class PushNotificationIOS { <ide> return this._sound; <ide> } <ide> <add> /** <add> * Gets the category string from the `aps` object <add> */ <add> getCategory(): ?string { <add> return this._category; <add> } <add> <ide> /** <ide> * Gets the notification's main message from the `aps` object <ide> */
1
Ruby
Ruby
add helper for testing tty output
dccdac55a835a22d46c36fe915e6e8cdf43a4adc
<ide><path>Library/Homebrew/test/cask/cli/search_spec.rb <ide> describe Hbc::CLI::Search, :cask do <ide> before(:each) do <del> allow($stdout).to receive(:tty?).and_return(true) <add> allow(Tty).to receive(:width).and_return(0) <ide> end <ide> <ide> it "lists the available Casks that match the search term" do <ide> expect { <ide> Hbc::CLI::Search.run("local") <del> }.to output(<<-EOS.undent).to_stdout <add> }.to output(<<-EOS.undent).to_stdout.as_tty <ide> ==> Partial Matches <ide> local-caffeine <ide> local-transmission <ide> it "shows that there are no Casks matching a search term that did not result in anything" do <ide> expect { <ide> Hbc::CLI::Search.run("foo-bar-baz") <del> }.to output("No Cask found for \"foo-bar-baz\".\n").to_stdout <add> }.to output("No Cask found for \"foo-bar-baz\".\n").to_stdout.as_tty <ide> end <ide> <ide> it "lists all available Casks with no search term" do <ide> expect { <ide> Hbc::CLI::Search.run <del> }.to output(/local-caffeine/).to_stdout <add> }.to output(/local-caffeine/).to_stdout.as_tty <ide> end <ide> <ide> it "ignores hyphens in search terms" do <ide> expect { <ide> Hbc::CLI::Search.run("lo-cal-caffeine") <del> }.to output(/local-caffeine/).to_stdout <add> }.to output(/local-caffeine/).to_stdout.as_tty <ide> end <ide> <ide> it "ignores hyphens in Cask tokens" do <ide> expect { <ide> Hbc::CLI::Search.run("localcaffeine") <del> }.to output(/local-caffeine/).to_stdout <add> }.to output(/local-caffeine/).to_stdout.as_tty <ide> end <ide> <ide> it "accepts multiple arguments" do <ide> expect { <ide> Hbc::CLI::Search.run("local caffeine") <del> }.to output(/local-caffeine/).to_stdout <add> }.to output(/local-caffeine/).to_stdout.as_tty <ide> end <ide> <ide> it "accepts a regexp argument" do <ide> expect { <ide> Hbc::CLI::Search.run("/^local-c[a-z]ffeine$/") <del> }.to output("==> Regexp Matches\nlocal-caffeine\n").to_stdout <add> }.to output("==> Regexp Matches\nlocal-caffeine\n").to_stdout.as_tty <ide> end <ide> <ide> it "Returns both exact and partial matches" do <ide> expect { <ide> Hbc::CLI::Search.run("test-opera") <del> }.to output(/^==> Exact Match\ntest-opera\n==> Partial Matches\ntest-opera-mail/).to_stdout <add> }.to output(/^==> Exact Match\ntest-opera\n==> Partial Matches\ntest-opera-mail/).to_stdout.as_tty <ide> end <ide> <ide> it "does not search the Tap name" do <ide> expect { <ide> Hbc::CLI::Search.run("caskroom") <del> }.to output(/^No Cask found for "caskroom"\.\n/).to_stdout <add> }.to output(/^No Cask found for "caskroom"\.\n/).to_stdout.as_tty <ide> end <ide> <ide> it "doesn't highlight packages that aren't installed" do <ide><path>Library/Homebrew/test/spec_helper.rb <ide> require "test/support/helper/fixtures" <ide> require "test/support/helper/formula" <ide> require "test/support/helper/mktmpdir" <add>require "test/support/helper/output_as_tty" <ide> require "test/support/helper/rubocop" <ide> <ide> require "test/support/helper/spec/shared_context/homebrew_cask" if OS.mac? <ide> config.include(Test::Helper::Fixtures) <ide> config.include(Test::Helper::Formula) <ide> config.include(Test::Helper::MkTmpDir) <add> config.include(Test::Helper::OutputAsTTY) <ide> config.include(Test::Helper::RuboCop) <ide> <ide> config.before(:each, :needs_compat) do <ide><path>Library/Homebrew/test/support/helper/output_as_tty.rb <add>require "delegate" <add> <add>module Test <add> module Helper <add> module OutputAsTTY <add> module TTYTrue <add> def tty? <add> true <add> end <add> <add> alias isatty tty? <add> end <add> <add> # This is a custom wrapper for the `output` matcher, <add> # used for testing output to a TTY: <add> # <add> # expect { <add> # print "test" if $stdout.tty? <add> # }.to output("test").to_stdout.as_tty <add> # <add> # expect { <add> # # command <add> # }.to output(...).to_stderr.as_tty.with_color <add> # <add> class Output < SimpleDelegator <add> def matches?(block) <add> return super(block) unless @tty <add> <add> colored_tty_block = if @output == :stdout <add> lambda do <add> $stdout.extend(TTYTrue) <add> block.call <add> end <add> elsif @output == :stderr <add> lambda do <add> $stderr.extend(TTYTrue) <add> block.call <add> end <add> else <add> raise "`as_tty` can only be chained to `stdout` or `stderr`." <add> end <add> <add> return super(colored_tty_block) if @colors <add> <add> uncolored_tty_block = lambda do <add> begin <add> out_stream = StringIO.new <add> err_stream = StringIO.new <add> <add> old_stdout = $stdout <add> old_stderr = $stderr <add> <add> $stdout = out_stream <add> $stderr = err_stream <add> <add> colored_tty_block.call <add> ensure <add> $stdout = old_stdout <add> $stderr = old_stderr <add> <add> $stdout.print Tty.strip_ansi(out_stream.string) <add> $stderr.print Tty.strip_ansi(err_stream.string) <add> end <add> end <add> <add> super(uncolored_tty_block) <add> end <add> <add> def to_stdout <add> @output = :stdout <add> super <add> self <add> end <add> <add> def to_stderr <add> @output = :stderr <add> super <add> self <add> end <add> <add> def as_tty <add> @tty = true <add> self <add> end <add> <add> def with_color <add> @colors = true <add> return self if @tty <add> raise "`with_color` can only be chained to `as_tty`." <add> end <add> end <add> <add> def output(*args) <add> core_matcher = super(*args) <add> Output.new(core_matcher) <add> end <add> end <add> end <add>end
3
Javascript
Javascript
improve test case, convert trace into warning
442dc46740994a078393a9ace8ae5fe9b2171c40
<ide><path>lib/hmr/HotModuleReplacement.runtime.js <ide> module.exports = function () { <ide> me.children.push(request); <ide> } <ide> } else { <del> console.trace( <add> console.warn( <ide> "[HMR] unexpected require(" + <ide> request + <ide> ") from disposed module " + <ide><path>test/helpers/expectWarningFactory.js <ide> module.exports = () => { <ide> done(); <ide> }); <ide> <del> const expectWarning = regexp => { <del> if (!regexp) { <del> expect(warnings).toEqual([]); <del> } else { <del> expect(warnings).toEqual( <del> expect.objectContaining({ <del> 0: expect.stringMatching(regexp), <del> length: 1 <del> }) <del> ); <del> } <add> const expectWarning = (...regexp) => { <add> expect(warnings).toEqual(regexp.map(r => expect.stringMatching(r))); <ide> warnings.length = 0; <ide> }; <ide> <ide><path>test/hotCases/runtime/require-disposed-module-warning/index.js <ide> const expectWarning = require("../../../helpers/expectWarningFactory")(); <del>const {aModule} = require("./module"); <add>const getInner = require("./module"); <ide> <del>it("should print correct warning messages when a disposed module is required", (done) => { <del> NEXT(require("../../update")(done, true, () => { <del> require("./module"); <del> __webpack_modules__[aModule.id].call(aModule.exports, aModule); <del> expectWarning(/^\[HMR] unexpected require\(\.\/a.js\) to disposed module$/); <del> done(); <del> })); <add>it("should print correct warning messages when a disposed module is required", done => { <add> NEXT( <add> require("../../update")(done, true, () => { <add> getInner(); <add> expectWarning( <add> /^\[HMR] unexpected require\(\.\/a.js\) from disposed module \.\/module\.js$/, <add> /^\[HMR] unexpected require\(\.\/a.js\) to disposed module$/ <add> ); <add> const getInnerUpdated = require("./module"); <add> getInnerUpdated(); <add> expectWarning(); <add> done(); <add> }) <add> ); <ide> }); <ide> <del>if(module.hot) { <add>if (module.hot) { <ide> module.hot.accept("./module"); <ide> } <ide><path>test/hotCases/runtime/require-disposed-module-warning/module.js <del>export {default as aModule} from "./a"; <add>module.exports = () => require("./a"); <ide> --- <del>import "./b"; <add>module.exports = () => require("./b");
4
Ruby
Ruby
remove errant default option
149da8815ce7b5bb3e1eb63964b9d808a065e932
<ide><path>activejob/lib/active_job/queue_adapter.rb <ide> module QueueAdapter #:nodoc: <ide> <ide> included do <ide> class_attribute :_queue_adapter_name, instance_accessor: false, instance_predicate: false <del> class_attribute :_queue_adapter, default: :async, instance_accessor: false, instance_predicate: false <add> class_attribute :_queue_adapter, instance_accessor: false, instance_predicate: false <ide> <ide> delegate :queue_adapter, to: :class <ide>
1
Go
Go
remove cases no longer valid for go1.16
2842639e0e22bc2f91271603fb9990fa2ac8ad2e
<ide><path>pkg/fileutils/fileutils_test.go <ide> func TestMatches(t *testing.T) { <ide> if runtime.GOOS != "windows" { <ide> tests = append(tests, []matchesTestCase{ <ide> {"a\\*b", "a*b", true}, <del> {"a\\", "a", false}, <del> {"a\\", "a\\", false}, <ide> }...) <ide> } <ide>
1
Python
Python
add __version__ symbol in __init__.py
45f6961ae0f54f1e6cbb6fb59158e2ce03e27417
<ide><path>spacy/__init__.py <ide> from .deprecated import resolve_model_name <ide> from .cli.info import info <ide> from .glossary import explain <add>from .about import __version__ <ide> <ide> from . import en, de, zh, es, it, hu, fr, pt, nl, sv, fi, bn, he, nb, ja <ide>
1
PHP
PHP
allow short-cuts on generators
49e3c77b518547bb661b1de4fda64a3ae0c5c505
<ide><path>src/Illuminate/Console/GeneratorCommand.php <ide> abstract protected function getStub(); <ide> */ <ide> public function fire() <ide> { <del> if ($this->files->exists($path = $this->getPath($name = $this->getNameInput()))) <add> $name = $this->parseName($this->getNameInput()); <add> <add> if ($this->files->exists($path = $this->getPath($name))) <ide> { <ide> return $this->error($this->type.' already exists!'); <ide> } <ide> protected function getPath($name) <ide> return $this->laravel['path'].'/'.str_replace('\\', '/', $name).'.php'; <ide> } <ide> <add> /** <add> * Parse the name and format according to the root namespace. <add> * <add> * @param string $name <add> * @return string <add> */ <add> protected function parseName($name) <add> { <add> $rootNamespace = $this->getAppNamespace(); <add> <add> if (starts_with($name, $rootNamespace)) <add> { <add> return $name; <add> } <add> else <add> { <add> return $this->parseName($this->getDefaultNamespace(trim($rootNamespace, '\\')).'\\'.$name); <add> } <add> } <add> <add> /** <add> * Get the default namespace for the class. <add> * <add> * @param string $rootNamespace <add> * @return string <add> */ <add> protected function getDefaultNamespace($rootNamespace) <add> { <add> return $rootNamespace; <add> } <add> <ide> /** <ide> * Build the directory for the class if necessary. <ide> * <ide><path>src/Illuminate/Foundation/Console/ConsoleMakeCommand.php <ide> protected function getStub() <ide> return __DIR__.'/stubs/command.stub'; <ide> } <ide> <add> /** <add> * Get the default namespace for the class. <add> * <add> * @param string $rootNamespace <add> * @return string <add> */ <add> protected function getDefaultNamespace($rootNamespace) <add> { <add> return $rootNamespace.'\Console'; <add> } <add> <ide> /** <ide> * Get the console command arguments. <ide> * <ide><path>src/Illuminate/Foundation/Console/ProviderMakeCommand.php <ide> protected function getStub() <ide> return __DIR__.'/stubs/provider.stub'; <ide> } <ide> <add> /** <add> * Get the default namespace for the class. <add> * <add> * @param string $rootNamespace <add> * @return string <add> */ <add> protected function getDefaultNamespace($rootNamespace) <add> { <add> return $rootNamespace.'\Providers'; <add> } <add> <ide> } <ide><path>src/Illuminate/Foundation/Console/RequestMakeCommand.php <ide> protected function getStub() <ide> return __DIR__.'/stubs/request.stub'; <ide> } <ide> <add> /** <add> * Get the default namespace for the class. <add> * <add> * @param string $rootNamespace <add> * @return string <add> */ <add> protected function getDefaultNamespace($rootNamespace) <add> { <add> return $rootNamespace.'\Http\Requests'; <add> } <add> <ide> } <ide><path>src/Illuminate/Routing/Console/ControllerMakeCommand.php <ide> protected function getStub() <ide> } <ide> } <ide> <add> /** <add> * Get the default namespace for the class. <add> * <add> * @param string $rootNamespace <add> * @return string <add> */ <add> protected function getDefaultNamespace($rootNamespace) <add> { <add> return $rootNamespace.'\Http\Controllers'; <add> } <add> <ide> /** <ide> * Get the console command options. <ide> * <ide><path>src/Illuminate/Routing/Console/FilterMakeCommand.php <ide> protected function getFilterStubPath() <ide> return __DIR__.'/stubs/filter.stub'; <ide> } <ide> <add> /** <add> * Get the default namespace for the class. <add> * <add> * @param string $rootNamespace <add> * @return string <add> */ <add> protected function getDefaultNamespace($rootNamespace) <add> { <add> return $rootNamespace.'\Http\Filters'; <add> } <add> <ide> /** <ide> * Get the console command options. <ide> *
6
Python
Python
use the new compat module
25f531e3d487d1b441037d6441c2c7e59c85e869
<ide><path>glances/core/glances_client.py <ide> import json <ide> import socket <ide> import sys <del>try: <del> from xmlrpc.client import Transport, ServerProxy, ProtocolError, Fault <del>except ImportError: <del> # Python 2 <del> from xmlrpclib import Transport, ServerProxy, ProtocolError, Fault <ide> <ide> # Import Glances libs <add>from glances.core.compat import Fault, ProtocolError, ServerProxy, Transport <ide> from glances.core.glances_globals import version <ide> from glances.core.glances_logging import logger <ide> from glances.core.glances_stats import GlancesStatsClient <ide><path>glances/core/glances_client_browser.py <ide> # Import system libs <ide> import json <ide> import socket <del>try: <del> from xmlrpc.client import ServerProxy, Fault, ProtocolError <del>except ImportError: <del> # Python 2 <del> from xmlrpclib import ServerProxy, Fault, ProtocolError <ide> <ide> # Import Glances libs <add>from glances.core.compat import Fault, ProtocolError, ServerProxy <ide> from glances.core.glances_autodiscover import GlancesAutoDiscoverServer <ide> from glances.core.glances_client import GlancesClient, GlancesClientTransport <ide> from glances.core.glances_logging import logger <ide><path>glances/core/glances_config.py <ide> # Import system libs <ide> import os <ide> import sys <del>try: <del> from configparser import ConfigParser <del> from configparser import NoOptionError <del>except ImportError: # Python 2 <del> from ConfigParser import SafeConfigParser as ConfigParser <del> from ConfigParser import NoOptionError <add>from io import open <ide> <ide> # Import Glances lib <add>from glances.core.compat import ConfigParser, NoOptionError <ide> from glances.core.glances_globals import ( <ide> appname, <ide> is_bsd, <ide> is_linux, <ide> is_mac, <del> is_py3, <ide> is_windows, <ide> sys_prefix <ide> ) <ide> def read(self): <ide> for config_file in self.config_file_paths(): <ide> if os.path.exists(config_file): <ide> try: <del> if is_py3: <del> self.parser.read(config_file, encoding='utf-8') <del> else: <del> self.parser.read(config_file) <add> with open(config_file, encoding='utf-8') as f: <add> self.parser.read_file(f) <add> self.parser.read(f) <ide> logger.info("Read configuration file '{0}'".format(config_file)) <ide> except UnicodeDecodeError as err: <ide> logger.error("Cannot decode configuration file '{0}': {1}".format(config_file, err)) <ide><path>glances/core/glances_globals.py <ide> version = __import__('glances').__version__ <ide> psutil_version = __import__('glances').__psutil_version <ide> <del># PY3? <del>is_py3 = sys.version_info >= (3, 3) <del> <ide> # Operating system flag <ide> # Note: Somes libs depends of OS <ide> is_bsd = sys.platform.find('bsd') != -1 <ide><path>glances/core/glances_logging.py <ide> """Custom logging class.""" <ide> <ide> import logging <del>try: <del> # Python 2.6 <del> from logutils.dictconfig import dictConfig <del>except ImportError: <del> # Python >= 2.7 <del> from logging.config import dictConfig <ide> import os <ide> import tempfile <ide> <add>from glances.core.compat import dictConfig <add> <ide> # Define the logging configuration <ide> LOGGING_CFG = { <ide> 'version': 1, <ide><path>glances/core/glances_logs.py <ide> from datetime import datetime <ide> <ide> # Import Glances libs <add>from glances.core.compat import range <ide> from glances.core.glances_processes import glances_processes <ide> <ide> <ide><path>glances/core/glances_monitor_list.py <ide> import subprocess <ide> <ide> # Import Glances lib <add>from glances.core.compat import range, u <ide> from glances.core.glances_logging import logger <ide> from glances.core.glances_processes import glances_processes <ide> <ide> def update(self): <ide> return self.__monitor_list <ide> <ide> # Iter upon the monitored list <del> for i in range(0, len(self.get())): <add> for i in range(len(self.get())): <ide> # Search monitored processes by a regular expression <ide> processlist = glances_processes.getalllist() <ide> monitoredlist = [p for p in processlist if re.search(self.regex(i), p['cmdline']) is not None] <ide> def update(self): <ide> except Exception: <ide> self.__monitor_list[i]['result'] = 'Cannot execute command' <ide> # Only save the first line <del> self.__monitor_list[i]['result'] = self.__monitor_list[i]['result'].decode('utf-8').split('\n')[0] <add> self.__monitor_list[i]['result'] = u(self.__monitor_list[i]['result']).split('\n')[0] <ide> <ide> if self.command(i) is None or self.__monitor_list[i]['result'] == '': <ide> # If there is no command specified in the conf file <ide><path>glances/core/glances_password.py <ide> import os <ide> import sys <ide> import uuid <add>from io import open <ide> <ide> # Import Glances lib <add>from glances.core.compat import b, input <ide> from glances.core.glances_globals import appname, is_bsd, is_linux, is_mac, is_windows <ide> from glances.core.glances_logging import logger <ide> <del># Trick: bind raw_input to input in Python 2 <del>try: <del> input = raw_input <del>except NameError: <del> pass <del> <ide> <ide> class GlancesPassword(object): <ide> <ide> def get_password_path(self): <ide> <ide> def sha256_hash(self, plain_password): <ide> """Return the SHA-256 of the given password.""" <del> return hashlib.sha256(plain_password.encode('utf-8')).hexdigest() <add> return hashlib.sha256(b(plain_password)).hexdigest() <ide> <ide> def get_hash(self, salt, plain_password): <ide> """Return the hashed password, salt + SHA-256.""" <ide><path>glances/core/glances_processes.py <ide> import re <ide> <ide> # Import Glances lib <add>from glances.core.compat import iteritems, itervalues <ide> from glances.core.glances_globals import is_bsd, is_linux, is_mac, is_windows <ide> from glances.core.glances_logging import logger <ide> from glances.core.glances_timer import Timer, getTimeSinceLastUpdate <ide> def build_tree(process_dict, sort_key, sort_reverse, hide_kernel_threads): <ide> nodes_to_add_last = collections.deque() <ide> <ide> # first pass: add nodes whose parent are in the tree <del> for process, stats in process_dict.items(): <add> for process, stats in iteritems(process_dict): <ide> new_node = ProcessTreeNode(process, stats, sort_key, sort_reverse) <ide> try: <ide> parent_process = process.parent() <ide> def update(self): <ide> # Sort the internal dict and cut the top N (Return a list of tuple) <ide> # tuple=key (proc), dict (returned by __get_process_stats) <ide> try: <del> processiter = sorted(processdict.items(), <add> processiter = sorted(iteritems(processdict), <ide> key=lambda x: x[1][self.sort_key], <ide> reverse=self.sort_reverse) <ide> except (KeyError, TypeError) as e: <ide> logger.error("Cannot sort process list by {0}: {1}".format(self.sort_key, e)) <del> logger.error("%s" % str(processdict.items()[0])) <add> logger.error("%s" % str(iteritems(processdict)[0])) <ide> # Fallback to all process (issue #423) <del> processloop = processdict.items() <add> processloop = iteritems(processdict) <ide> first = False <ide> else: <ide> processloop = processiter[0:self.max_processes] <ide> first = True <ide> else: <ide> # Get all processes stats <del> processloop = processdict.items() <add> processloop = iteritems(processdict) <ide> first = False <ide> <ide> for i in processloop: <ide> def update(self): <ide> first = False <ide> <ide> # Build the all processes list used by the monitored list <del> self.allprocesslist = processdict.values() <add> self.allprocesslist = itervalues(processdict) <ide> <ide> # Clean internals caches if timeout is reached <ide> if self.cache_timer.finished(): <ide><path>glances/core/glances_server.py <ide> import socket <ide> import sys <ide> from base64 import b64decode <del>try: <del> from xmlrpc.server import SimpleXMLRPCRequestHandler <del> from xmlrpc.server import SimpleXMLRPCServer <del>except ImportError: # Python 2 <del> from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler <del> from SimpleXMLRPCServer import SimpleXMLRPCServer <ide> <ide> # Import Glances libs <add>from glances.core.compat import SimpleXMLRPCRequestHandler, SimpleXMLRPCServer <ide> from glances.core.glances_autodiscover import GlancesAutoDiscoverClient <ide> from glances.core.glances_globals import version <ide> from glances.core.glances_logging import logger <ide><path>glances/core/glances_staticlist.py <ide> from socket import gaierror, gethostbyname <ide> <ide> # Import Glances libs <add>from glances.core.compat import range <ide> from glances.core.glances_logging import logger <ide> <ide> <ide><path>glances/core/glances_stats.py <ide> import sys <ide> import threading <ide> <add>from glances.core.compat import iteritems <ide> from glances.core.glances_globals import exports_path, plugins_path, sys_path <ide> from glances.core.glances_logging import logger <ide> <ide> def get_system_name(self, oid_system_name): <ide> return short_system_name <ide> <ide> # Find the short name in the oid_to_short_os_name dict <del> try: <del> iteritems = oid_to_short_system_name.iteritems() <del> except AttributeError: <del> # Correct issue #386 <del> iteritems = oid_to_short_system_name.items() <del> for r, v in iteritems: <add> for r, v in iteritems(oid_to_short_system_name): <ide> if re.search(r, oid_system_name): <ide> short_system_name = v <ide> break <ide><path>glances/exports/glances_csv.py <ide> import time <ide> <ide> # Import Glances lib <del>from glances.core.glances_globals import is_py3 <add>from glances.core.compat import PY3, iterkeys, itervalues <ide> from glances.core.glances_logging import logger <ide> from glances.exports.glances_export import GlancesExport <ide> <ide> def __init__(self, config=None, args=None): <ide> <ide> # Set the CSV output file <ide> try: <del> if is_py3: <add> if PY3: <ide> self.csv_file = open(self.csv_filename, 'w', newline='') <ide> else: <ide> self.csv_file = open(self.csv_filename, 'wb') <ide> def update(self, stats): <ide> csv_header += ('{0}_{1}_{2}'.format( <ide> plugin, self.get_item_key(stat), item) for item in stat) <ide> # Others lines: stats <del> fieldvalues = stat.values() <del> csv_data += fieldvalues <add> csv_data += itervalues(stat) <ide> elif isinstance(all_stats[i], dict): <ide> # First line: header <ide> if self.first_line: <del> fieldnames = all_stats[i].keys() <add> fieldnames = iterkeys(all_stats[i]) <ide> csv_header += ('{0}_{1}'.format(plugin, fieldname) <ide> for fieldname in fieldnames) <ide> # Others lines: stats <del> fieldvalues = all_stats[i].values() <del> csv_data += fieldvalues <add> csv_data += itervalues(all_stats[i]) <ide> <ide> # Export to CSV <ide> if self.first_line: <ide><path>glances/exports/glances_export.py <ide> # None... <ide> <ide> # Import Glances lib <add>from glances.core.compat import iteritems, iterkeys <ide> from glances.core.glances_logging import logger <ide> <ide> <ide> def __build_export(self, stats): <ide> if isinstance(stats, dict): <ide> # Stats is a dict <ide> # Is there a key ? <del> if 'key' in list(stats.keys()): <add> if 'key' in iterkeys(stats): <ide> pre_key = '{0}.'.format(stats[stats['key']]) <ide> else: <ide> pre_key = '' <ide> # Walk through the dict <del> try: <del> iteritems = stats.iteritems() <del> except AttributeError: <del> iteritems = stats.items() <del> for key, value in iteritems: <add> for key, value in iteritems(stats): <ide> if isinstance(value, list): <ide> try: <ide> value = value[0] <ide><path>glances/exports/glances_history.py <ide> import os <ide> <ide> # Import Glances lib <add>from glances.core.compat import iterkeys <ide> from glances.core.glances_logging import logger <ide> <ide> # Import specific lib <ide> def generate_graph(self, stats): <ide> handles = [] <ide> labels = [] <ide> for i in stats.get_plugin(p).get_items_history_list(): <del> if i['name'] in h.keys(): <add> if i['name'] in iterkeys(h): <ide> # The key exist <ide> # Add the curves in the current chart <ide> logger.debug("Generate graph: %s %s" % (p, i['name'])) <ide> def generate_graph(self, stats): <ide> # Find if anothers key ends with the key <ide> # Ex: key='tx' => 'ethernet_tx' <ide> # Add one curve per chart <del> stats_history_filtered = [key for key in h.keys() if key.endswith('_' + i['name'])] <add> stats_history_filtered = [key for key in iterkeys(h) if key.endswith('_' + i['name'])] <ide> stats_history_filtered.sort() <ide> logger.debug("Generate graphs: %s %s" % <ide> (p, stats_history_filtered)) <ide><path>glances/exports/glances_influxdb.py <ide> <ide> # Import sys libs <ide> import sys <del>try: <del> from configparser import NoOptionError, NoSectionError <del>except ImportError: # Python 2 <del> from ConfigParser import NoOptionError, NoSectionError <ide> <ide> # Import Glances lib <add>from glances.core.compat import NoOptionError, NoSectionError <ide> from glances.core.glances_logging import logger <ide> from glances.exports.glances_export import GlancesExport <ide> <ide><path>glances/exports/glances_opentsdb.py <ide> # Import sys libs <ide> import sys <ide> from numbers import Number <del>try: <del> from configparser import NoOptionError, NoSectionError <del>except ImportError: # Python 2 <del> from ConfigParser import NoOptionError, NoSectionError <ide> <ide> # Import Glances lib <add>from glances.core.compat import NoOptionError, NoSectionError, range <ide> from glances.core.glances_logging import logger <ide> from glances.exports.glances_export import GlancesExport <ide> <ide> def init(self): <ide> <ide> def export(self, name, columns, points): <ide> """Export the stats to the Statsd server.""" <del> for i in range(0, len(columns)): <add> for i in range(len(columns)): <ide> if not isinstance(points[i], Number): <ide> continue <ide> stat_name = '{0}.{1}.{2}'.format(self.prefix, name, columns[i]) <ide><path>glances/exports/glances_rabbitmq.py <ide> from numbers import Number <ide> <ide> # Import Glances lib <add>from glances.core.compat import NoOptionError, NoSectionError, range <ide> from glances.core.glances_logging import logger <del>try: <del> from configparser import NoOptionError, NoSectionError <del>except ImportError: # Python 2 <del> from ConfigParser import NoOptionError, NoSectionError <ide> from glances.exports.glances_export import GlancesExport <ide> <ide> # Import pika for RabbitMQ <ide> def export(self, name, columns, points): <ide> """Write the points in RabbitMQ.""" <ide> data = ('hostname=' + self.hostname + ', name=' + name + <ide> ', dateinfo=' + datetime.datetime.utcnow().isoformat()) <del> for i in range(0, len(columns)): <add> for i in range(len(columns)): <ide> if not isinstance(points[i], Number): <ide> continue <ide> else: <ide><path>glances/exports/glances_statsd.py <ide> # Import sys libs <ide> import sys <ide> from numbers import Number <del>try: <del> from configparser import NoOptionError, NoSectionError <del>except ImportError: # Python 2 <del> from ConfigParser import NoOptionError, NoSectionError <ide> <ide> # Import Glances lib <add>from glances.core.compat import NoOptionError, NoSectionError, range <ide> from glances.core.glances_logging import logger <ide> from glances.exports.glances_export import GlancesExport <ide> <ide> def init(self, prefix='glances'): <ide> <ide> def export(self, name, columns, points): <ide> """Export the stats to the Statsd server.""" <del> for i in range(0, len(columns)): <add> for i in range(len(columns)): <ide> if not isinstance(points[i], Number): <ide> continue <ide> stat_name = '{0}.{1}'.format(name, columns[i]) <ide><path>glances/outputs/glances_bottle.py <ide> import os <ide> import sys <ide> import tempfile <add>from io import open <ide> <ide> from glances.core.glances_logging import logger <ide> <ide><path>glances/outputs/glances_colorconsole.py <ide> <ide> import msvcrt <ide> <add>from glances.core.compat import queue <ide> from glances.core.glances_logging import logger <ide> <ide> try: <ide> logger.critical("Colorconsole module not found. Glances cannot start in standalone mode.") <ide> sys.exit(1) <ide> <del>try: <del> import queue <del>except ImportError: # Python 2 <del> import Queue as queue <del> <ide> <ide> class ListenGetch(threading.Thread): <ide> <ide><path>glances/outputs/glances_curses.py <ide> import sys <ide> <ide> # Import Glances lib <add>from glances.core.compat import u <ide> from glances.core.glances_globals import is_mac, is_windows <ide> from glances.core.glances_logging import logger <ide> from glances.core.glances_logs import glances_logs <ide> def display_plugin(self, plugin_stats, <ide> pass <ide> else: <ide> # New column <del> try: <del> # Python 2: we need to decode to get real screen size because utf-8 special tree chars <del> # occupy several bytes <del> offset = len(m['msg'].decode("utf-8", "replace")) <del> except AttributeError: <del> # Python 3: strings are strings and bytes are bytes, all is <del> # good <del> offset = len(m['msg']) <add> # Python 2: we need to decode to get real screen size because <add> # UTF-8 special tree chars occupy several bytes. <add> # Python 3: strings are strings and bytes are bytes, all is <add> # good. <add> offset = len(u(m['msg'])) <ide> x += offset <ide> if x > x_max: <ide> x_max = x <ide><path>glances/plugins/glances_cpu.py <ide> <ide> """CPU plugin.""" <ide> <add>from glances.core.compat import iterkeys <ide> from glances.core.glances_cpu_percent import cpu_percent <ide> from glances.plugins.glances_plugin import GlancesPlugin <ide> <ide> def update(self): <ide> return self.stats <ide> <ide> # Convert SNMP stats to float <del> for key in list(self.stats.keys()): <add> for key in iterkeys(self.stats): <ide> self.stats[key] = float(self.stats[key]) <ide> self.stats['total'] = 100 - self.stats['idle'] <ide> <ide><path>glances/plugins/glances_docker.py <ide> import time <ide> <ide> # Import Glances libs <add>from glances.core.compat import iterkeys, itervalues <ide> from glances.core.glances_logging import logger <ide> from glances.core.glances_timer import getTimeSinceLastUpdate <ide> from glances.plugins.glances_plugin import GlancesPlugin <ide> def __init__(self, args=None): <ide> def exit(self): <ide> """Overwrite the exit method to close threads""" <ide> logger.debug("Stop the Docker plugin") <del> for t in self.thread_list.values(): <add> for t in itervalues(self.thread_list): <ide> t.stop() <ide> <ide> def get_key(self): <ide> def update(self): <ide> t.start() <ide> <ide> # Stop threads for non-existing containers <del> nonexisting_containers = list(set(self.thread_list.keys()) - set([c['Id'] for c in self.stats['containers']])) <add> nonexisting_containers = set(iterkeys(self.thread_list)) - set([c['Id'] for c in self.stats['containers']]) <ide> for container_id in nonexisting_containers: <ide> # Stop the thread <ide> logger.debug("{0} plugin - Stop thread for old container {1}".format(self.plugin_name, container_id[:12])) <ide><path>glances/plugins/glances_hddtemp.py <ide> import socket <ide> <ide> # Import Glances libs <add>from glances.core.compat import nativestr, range <ide> from glances.core.glances_logging import logger <ide> from glances.plugins.glances_plugin import GlancesPlugin <ide> <ide> def __update__(self): <ide> for item in range(devices): <ide> offset = item * 5 <ide> hddtemp_current = {} <del> device = fields[offset + 1].decode('utf-8') <del> device = os.path.basename(device) <del> temperature = float(fields[offset + 3].decode('utf-8')) <del> unit = fields[offset + 4].decode('utf-8') <add> device = os.path.basename(nativestr(fields[offset + 1])) <add> temperature = float(fields[offset + 3]) <add> unit = nativestr(fields[offset + 4]) <ide> hddtemp_current['label'] = device <ide> hddtemp_current['value'] = temperature <ide> hddtemp_current['unit'] = unit <ide><path>glances/plugins/glances_ip.py <ide> """IP plugin.""" <ide> <ide> # Import Glances libs <add>from glances.core.compat import iterkeys <ide> from glances.core.glances_globals import is_freebsd <ide> from glances.core.glances_logging import logger <ide> from glances.plugins.glances_plugin import GlancesPlugin <ide> def update_views(self): <ide> <ide> # Add specifics informations <ide> # Optional <del> for key in self.stats.keys(): <add> for key in iterkeys(self.stats): <ide> self.views[key]['optional'] = True <ide> <ide> def msg_curse(self, args=None): <ide><path>glances/plugins/glances_load.py <ide> import os <ide> <ide> # Import Glances libs <add>from glances.core.compat import iteritems <ide> from glances.plugins.glances_core import Plugin as CorePlugin <ide> from glances.plugins.glances_plugin import GlancesPlugin <ide> <ide> def update(self): <ide> <ide> # Python 3 return a dict like: <ide> # {'min1': "b'0.08'", 'min5': "b'0.12'", 'min15': "b'0.15'"} <del> try: <del> iteritems = self.stats.iteritems() <del> except AttributeError: <del> iteritems = self.stats.items() <del> for k, v in iteritems: <add> for k, v in iteritems(self.stats): <ide> self.stats[k] = float(v) <ide> <ide> self.stats['cpucore'] = self.nb_log_core <ide><path>glances/plugins/glances_mem.py <ide> <ide> """Virtual memory plugin.""" <ide> <add>from glances.core.compat import iterkeys <ide> from glances.plugins.glances_plugin import GlancesPlugin <ide> <ide> import psutil <ide> def update(self): <ide> self.reset() <ide> return self.stats <ide> <del> for key in list(self.stats.keys()): <add> for key in iterkeys(self.stats): <ide> if self.stats[key] != '': <ide> self.stats[key] = float(self.stats[key]) * 1024 <ide> <ide><path>glances/plugins/glances_memswap.py <ide> <ide> """Swap memory plugin.""" <ide> <add>from glances.core.compat import iterkeys <ide> from glances.plugins.glances_plugin import GlancesPlugin <ide> <ide> import psutil <ide> def update(self): <ide> self.reset() <ide> return self.stats <ide> <del> for key in list(self.stats.keys()): <add> for key in iterkeys(self.stats): <ide> if self.stats[key] != '': <ide> self.stats[key] = float(self.stats[key]) * 1024 <ide> <ide><path>glances/plugins/glances_monitor.py <ide> <ide> """Monitor plugin.""" <ide> <del>from __future__ import unicode_literals <del> <ide> # Import Glances lib <add>from glances.core.compat import u <ide> from glances.core.glances_monitor_list import MonitorList as glancesMonitorList <ide> from glances.plugins.glances_plugin import GlancesPlugin <ide> <ide> def msg_curse(self, args=None): <ide> ret.append(self.curse_add_line(msg)) <ide> msg = '{0:13} '.format('RUNNING' if m['count'] >= 1 else 'NOT RUNNING') <ide> ret.append(self.curse_add_line(msg)) <del> # Decode to UTF8 (only for Python 3) <del> try: <del> msg = m['result'].decode('utf-8') if m['count'] >= 1 else '' <del> except (UnicodeError, AttributeError): <del> try: <del> msg = m['result'] if m['count'] >= 1 else '' <del> except UnicodeError: <del> msg = m['result'].encode('utf-8') if m['count'] >= 1 else '' <add> # Decode to UTF-8 (for Python 2) <add> msg = u(m['result']) if m['count'] >= 1 else '' <ide> ret.append(self.curse_add_line(msg, optional=True, splittable=True)) <ide> ret.append(self.curse_new_line()) <ide> <ide><path>glances/plugins/glances_plugin.py <ide> from operator import itemgetter <ide> <ide> # Import Glances lib <add>from glances.core.compat import iterkeys, itervalues, map <ide> from glances.core.glances_actions import GlancesActions <del>from glances.core.glances_globals import is_py3 <ide> from glances.core.glances_logging import logger <ide> from glances.core.glances_logs import glances_logs <ide> <ide> def get_stats_snmp(self, bulk=False, snmp_oid=None): <ide> ret = {} <ide> if bulk: <ide> # Bulk request <del> snmpresult = clientsnmp.getbulk_by_oid(0, 10, *snmp_oid.values()) <add> snmpresult = clientsnmp.getbulk_by_oid(0, 10, itervalues(*snmp_oid)) <ide> <ide> if len(snmp_oid) == 1: <ide> # Bulk command for only one OID <ide> # Note: key is the item indexed but the OID result <ide> for item in snmpresult: <del> if item.keys()[0].startswith(snmp_oid.values()[0]): <del> ret[snmp_oid.keys()[0] + item.keys() <del> [0].split(snmp_oid.values()[0])[1]] = item.values()[0] <add> if iterkeys(item)[0].startswith(itervalues(snmp_oid)[0]): <add> ret[iterkeys(snmp_oid)[0] + iterkeys(item) <add> [0].split(itervalues(snmp_oid)[0])[1]] = itervalues(item)[0] <ide> else: <ide> # Build the internal dict with the SNMP result <ide> # Note: key is the first item in the snmp_oid <ide> index = 1 <ide> for item in snmpresult: <ide> item_stats = {} <ide> item_key = None <del> for key in list(snmp_oid.keys()): <add> for key in iterkeys(snmp_oid): <ide> oid = snmp_oid[key] + '.' + str(index) <ide> if oid in item: <ide> if item_key is None: <ide> def get_stats_snmp(self, bulk=False, snmp_oid=None): <ide> index += 1 <ide> else: <ide> # Simple get request <del> snmpresult = clientsnmp.get_by_oid(*snmp_oid.values()) <add> snmpresult = clientsnmp.get_by_oid(itervalues(*snmp_oid)) <ide> <ide> # Build the internal dict with the SNMP result <del> for key in list(snmp_oid.keys()): <add> for key in iterkeys(snmp_oid): <ide> ret[key] = snmpresult[snmp_oid[key]] <ide> <ide> return ret <ide> def update_views(self): <ide> # Stats are stored in a list of dict (ex: NETWORK, FS...) <ide> for i in self.get_raw(): <ide> ret[i[self.get_key()]] = {} <del> for key in i.keys(): <add> for key in iterkeys(i): <ide> value = {'decoration': 'DEFAULT', <ide> 'optional': False, <ide> 'additional': False, <ide> 'splittable': False} <ide> ret[i[self.get_key()]][key] = value <ide> elif isinstance(self.get_raw(), dict) and self.get_raw() is not None: <ide> # Stats are stored in a dict (ex: CPU, LOAD...) <del> for key in self.get_raw().keys(): <add> for key in iterkeys(self.get_raw()): <ide> value = {'decoration': 'DEFAULT', <ide> 'optional': False, <ide> 'additional': False, <ide> def _log_result_decorator(fct): <ide> """Log (DEBUG) the result of the function fct.""" <ide> def wrapper(*args, **kw): <ide> ret = fct(*args, **kw) <del> if is_py3: <del> logger.debug("%s %s %s return %s" % ( <del> args[0].__class__.__name__, <del> args[0].__class__.__module__[len('glances_'):], <del> fct.__name__, ret)) <del> else: <del> logger.debug("%s %s %s return %s" % ( <del> args[0].__class__.__name__, <del> args[0].__class__.__module__[len('glances_'):], <del> fct.func_name, ret)) <add> logger.debug("%s %s %s return %s" % ( <add> args[0].__class__.__name__, <add> args[0].__class__.__module__[len('glances_'):], <add> fct.__name__, ret)) <ide> return ret <ide> return wrapper <ide> <ide><path>glances/plugins/glances_processlist.py <ide> from datetime import timedelta <ide> <ide> # Import Glances libs <add>from glances.core.compat import iteritems <ide> from glances.core.glances_logging import logger <ide> from glances.plugins.glances_core import Plugin as CorePlugin <ide> from glances.core.glances_globals import is_windows <ide> <ide> def convert_timedelta(delta): <ide> """Convert timedelta to human-readable time.""" <del> # Python 2.7+: <del> # total_seconds = delta.total_seconds() <del> # hours = total_seconds // 3600 <ide> days, total_seconds = delta.days, delta.seconds <ide> hours = days * 24 + total_seconds // 3600 <ide> minutes = (total_seconds % 3600) // 60 <ide> def get_process_curses_data(self, p, first, args): <ide> if 'memory_info_ex' in p and p['memory_info_ex'] is not None: <ide> ret.append(self.curse_new_line()) <ide> msg = xpad + 'Memory info: ' <del> for k, v in p['memory_info_ex']._asdict().items(): <add> for k, v in iteritems(p['memory_info_ex']._asdict()): <ide> # Ignore rss and vms (already displayed) <ide> if k not in ['rss', 'vms'] and v is not None: <ide> msg += k + ' ' + self.auto_unit(v, low_precision=False) + ' ' <ide><path>glances/plugins/glances_raid.py <ide> """RAID plugin.""" <ide> <ide> # Import Glances libs <add>from glances.core.compat import iterkeys <ide> from glances.core.glances_logging import logger <ide> from glances.plugins.glances_plugin import GlancesPlugin <ide> <ide> def msg_curse(self, args=None): <ide> msg = '{0:>6}'.format('Avail') <ide> ret.append(self.curse_add_line(msg)) <ide> # Data <del> arrays = self.stats.keys() <add> arrays = iterkeys(self.stats) <ide> arrays.sort() <ide> for array in arrays: <ide> # New line <ide> def msg_curse(self, args=None): <ide> ret.append(self.curse_new_line()) <ide> msg = '└─ Status {0}'.format(self.stats[array]['status']) <ide> ret.append(self.curse_add_line(msg, status)) <del> components = self.stats[array]['components'].keys() <add> components = iterkeys(self.stats[array]['components']) <ide> components.sort() <ide> for i, component in enumerate(components): <ide> if i == len(components) - 1: <ide><path>glances/plugins/glances_system.py <ide> import os <ide> import platform <ide> import re <add>from io import open <ide> <ide> # Import Glances libs <add>from glances.core.compat import iteritems <ide> from glances.plugins.glances_plugin import GlancesPlugin <ide> <ide> # SNMP OID <ide> def update(self): <ide> self.stats['os_name'] = self.stats['system_name'] <ide> # Windows OS tips <ide> if self.short_system_name == 'windows': <del> try: <del> iteritems = snmp_to_human['windows'].iteritems() <del> except AttributeError: <del> iteritems = snmp_to_human['windows'].items() <del> for r, v in iteritems: <add> for r, v in iteritems(snmp_to_human['windows']): <ide> if re.search(r, self.stats['system_name']): <ide> self.stats['os_name'] = v <ide> break <ide><path>unitest-restful.py <ide> import time <ide> import unittest <ide> <add>from glances.core.compat import text_type <ide> from glances.core.glances_globals import version <ide> <ide> import requests <ide> <del>try: <del> text_type = str <del>except NameError: <del> text_type = unicode <del> <ide> SERVER_PORT = 61234 <ide> URL = "http://localhost:%s/api/2" % SERVER_PORT <ide> pid = None <ide><path>unitest-xmlrpc.py <ide> import subprocess <ide> import time <ide> import unittest <del>try: <del> from xmlrpc.client import ServerProxy <del>except ImportError: <del> # Python 2 <del> from xmlrpclib import ServerProxy <ide> <add>from glances.core.compat import ServerProxy <ide> from glances.core.glances_globals import version <ide> <ide> SERVER_PORT = 61234
36
Javascript
Javascript
improve multiple vm tests
4b23b429818d3fef1714cbdea4c6a1fd06410a5f
<ide><path>test/parallel/test-vm-context-async-script.js <ide> // USE OR OTHER DEALINGS IN THE SOFTWARE. <ide> <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> const assert = require('assert'); <ide> const vm = require('vm'); <ide> <del>const sandbox = { setTimeout: setTimeout }; <add>const sandbox = { setTimeout }; <ide> <ide> const ctx = vm.createContext(sandbox); <ide> <ide> vm.runInContext('setTimeout(function() { x = 3; }, 0);', ctx); <del>setTimeout(function() { <add>setTimeout(common.mustCall(() => { <ide> assert.strictEqual(sandbox.x, 3); <ide> assert.strictEqual(ctx.x, 3); <del>}, 1); <add>}), 1); <ide><path>test/parallel/test-vm-context.js <ide> const vm = require('vm'); <ide> const Script = vm.Script; <ide> let script = new Script('"passed";'); <ide> <del>console.error('run in a new empty context'); <add>// Run in a new empty context <ide> let context = vm.createContext(); <ide> let result = script.runInContext(context); <ide> assert.strictEqual('passed', result); <ide> <del>console.error('create a new pre-populated context'); <add>// Create a new pre-populated context <ide> context = vm.createContext({ 'foo': 'bar', 'thing': 'lala' }); <ide> assert.strictEqual('bar', context.foo); <ide> assert.strictEqual('lala', context.thing); <ide> <del>console.error('test updating context'); <add>// Test updating context <ide> script = new Script('foo = 3;'); <ide> result = script.runInContext(context); <ide> assert.strictEqual(3, context.foo); <ide> assert.strictEqual('lala', context.thing); <ide> <ide> // Issue GH-227: <del>assert.throws(function() { <add>assert.throws(() => { <ide> vm.runInNewContext('', null, 'some.js'); <ide> }, /^TypeError: sandbox must be an object$/); <ide> <ide> // Issue GH-1140: <del>console.error('test runInContext signature'); <add>// Test runInContext signature <ide> let gh1140Exception; <ide> try { <ide> vm.runInContext('throw new Error()', context, 'expected-filename.js'); <ide> const contextifiedSandboxErrorMsg = <ide> }); <ide> <ide> // Issue GH-693: <del>console.error('test RegExp as argument to assert.throws'); <add>// Test RegExp as argument to assert.throws <ide> script = vm.createScript('const assert = require(\'assert\'); assert.throws(' + <ide> 'function() { throw "hello world"; }, /hello/);', <ide> 'some.js'); <ide> assert.strictEqual(script.runInContext(ctx), false); <ide> <ide> // Error on the first line of a module should <ide> // have the correct line and column number <del>assert.throws(function() { <add>assert.throws(() => { <ide> vm.runInContext('throw new Error()', context, { <ide> filename: 'expected-filename.js', <ide> lineOffset: 32, <ide> columnOffset: 123 <ide> }); <del>}, function(err) { <add>}, (err) => { <ide> return /expected-filename\.js:33:130/.test(err.stack); <ide> }, 'Expected appearance of proper offset in Error stack'); <ide> <ide><path>test/parallel/test-vm-create-and-run-in-context.js <ide> const assert = require('assert'); <ide> <ide> const vm = require('vm'); <ide> <del>console.error('run in a new empty context'); <add>// Run in a new empty context <ide> let context = vm.createContext(); <ide> let result = vm.runInContext('"passed";', context); <ide> assert.strictEqual('passed', result); <ide> <del>console.error('create a new pre-populated context'); <add>// Create a new pre-populated context <ide> context = vm.createContext({ 'foo': 'bar', 'thing': 'lala' }); <ide> assert.strictEqual('bar', context.foo); <ide> assert.strictEqual('lala', context.thing); <ide> <del>console.error('test updating context'); <add>// Test updating context <ide> result = vm.runInContext('var foo = 3;', context); <ide> assert.strictEqual(3, context.foo); <ide> assert.strictEqual('lala', context.thing); <ide> <ide> // https://github.com/nodejs/node/issues/5768 <del>console.error('run in contextified sandbox without referencing the context'); <add>// Run in contextified sandbox without referencing the context <ide> const sandbox = { x: 1 }; <ide> vm.createContext(sandbox); <ide> global.gc(); <ide><path>test/parallel/test-vm-function-declaration.js <ide> assert.strictEqual(res.name, 'b', 'res should be named b'); <ide> assert.strictEqual(typeof o.a, 'function', 'a should be function'); <ide> assert.strictEqual(typeof o.b, 'function', 'b should be function'); <ide> assert.strictEqual(res, o.b, 'result should be global b function'); <del> <del>console.log('ok'); <ide><path>test/parallel/test-vm-new-script-new-context.js <ide> const Script = require('vm').Script; <ide> <ide> { <ide> const script = new Script('throw new Error(\'test\');'); <del> assert.throws(function() { <add> assert.throws(() => { <ide> script.runInNewContext(); <ide> }, /^Error: test$/); <ide> } <ide> <ide> { <ide> const script = new Script('foo.bar = 5;'); <del> assert.throws(function() { <add> assert.throws(() => { <ide> script.runInNewContext(); <ide> }, /^ReferenceError: foo is not defined$/); <ide> } <ide> const Script = require('vm').Script; <ide> script.runInNewContext({ f: f }); <ide> assert.strictEqual(f.a, 2); <ide> <del> assert.throws(function() { <add> assert.throws(() => { <ide> script.runInNewContext(); <ide> }, /^ReferenceError: f is not defined$/); <ide> } <ide> <ide> { <ide> const script = new Script(''); <del> assert.throws(function() { <add> assert.throws(() => { <ide> script.runInNewContext.call('\'hello\';'); <ide> }, /^TypeError: this\.runInContext is not a function$/); <ide> } <ide><path>test/parallel/test-vm-new-script-this-context.js <ide> const Script = require('vm').Script; <ide> <ide> common.globalCheck = false; <ide> <del>console.error('run a string'); <add>// Run a string <ide> let script = new Script('\'passed\';'); <ide> const result = script.runInThisContext(script); <ide> assert.strictEqual('passed', result); <ide> <del>console.error('thrown error'); <add>// Thrown error <ide> script = new Script('throw new Error(\'test\');'); <del>assert.throws(function() { <add>assert.throws(() => { <ide> script.runInThisContext(script); <ide> }, /^Error: test$/); <ide> <ide> script.runInThisContext(script); <ide> assert.strictEqual(2, global.hello); <ide> <ide> <del>console.error('pass values'); <add>// Pass values <ide> global.code = 'foo = 1;' + <ide> 'bar = 2;' + <ide> 'if (typeof baz !== "undefined") throw new Error("test fail");'; <ide> assert.strictEqual(0, global.obj.foo); <ide> assert.strictEqual(2, global.bar); <ide> assert.strictEqual(1, global.foo); <ide> <del>console.error('call a function'); <add>// Call a function <ide> global.f = function() { global.foo = 100; }; <ide> script = new Script('f()'); <ide> script.runInThisContext(script); <ide><path>test/parallel/test-vm-run-in-new-context.js <ide> assert.strictEqual(typeof global.gc, 'function', <ide> <ide> common.globalCheck = false; <ide> <del>console.error('run a string'); <add>// Run a string <ide> const result = vm.runInNewContext('\'passed\';'); <ide> assert.strictEqual('passed', result); <ide> <del>console.error('thrown error'); <del>assert.throws(function() { <add>// Thrown error <add>assert.throws(() => { <ide> vm.runInNewContext('throw new Error(\'test\');'); <ide> }, /^Error: test$/); <ide> <ide> vm.runInNewContext('hello = 2'); <ide> assert.strictEqual(5, global.hello); <ide> <ide> <del>console.error('pass values in and out'); <add>// Pass values in and out <ide> global.code = 'foo = 1;' + <ide> 'bar = 2;' + <ide> 'if (baz !== 3) throw new Error(\'test fail\');'; <ide> assert.strictEqual(1, global.obj.foo); <ide> assert.strictEqual(2, global.obj.bar); <ide> assert.strictEqual(2, global.foo); <ide> <del>console.error('call a function by reference'); <add>// Call a function by reference <ide> function changeFoo() { global.foo = 100; } <ide> vm.runInNewContext('f()', { f: changeFoo }); <ide> assert.strictEqual(global.foo, 100); <ide> <del>console.error('modify an object by reference'); <add>// Modify an object by reference <ide> const f = { a: 1 }; <ide> vm.runInNewContext('f.a = 2', { f: f }); <ide> assert.strictEqual(f.a, 2); <ide> <del>console.error('use function in context without referencing context'); <add>// Use function in context without referencing context <ide> const fn = vm.runInNewContext('(function() { obj.p = {}; })', { obj: {} }); <ide> global.gc(); <ide> fn(); <ide><path>test/parallel/test-vm-syntax-error-message.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> const assert = require('assert'); <ide> const child_process = require('child_process'); <ide> <ide> const p = child_process.spawn(process.execPath, [ <ide> 'catch (e) { console.log(e.message); }' <ide> ]); <ide> <del>p.stderr.on('data', function(data) { <del> assert.fail(`Unexpected stderr data: ${data}`); <del>}); <add>p.stderr.on('data', common.mustNotCall()); <ide> <ide> let output = ''; <ide> <del>p.stdout.on('data', function(data) { <del> output += data; <del>}); <add>p.stdout.on('data', (data) => output += data); <ide> <del>process.on('exit', function() { <add>p.stdout.on('end', common.mustCall(() => { <ide> assert.strictEqual(output.replace(/[\r\n]+/g, ''), 'boo'); <del>}); <add>})); <ide><path>test/parallel/test-vm-syntax-error-stderr.js <ide> const p = child_process.spawn(process.execPath, [ <ide> wrong_script <ide> ]); <ide> <del>p.stdout.on('data', function(data) { <del> assert.fail(`Unexpected stdout data: ${data}`); <del>}); <add>p.stdout.on('data', common.mustNotCall()); <ide> <ide> let output = ''; <ide> <del>p.stderr.on('data', function(data) { <del> output += data; <del>}); <add>p.stderr.on('data', (data) => output += data); <ide> <del>process.on('exit', function() { <add>p.stderr.on('end', common.mustCall(() => { <ide> assert(/BEGIN CERT/.test(output)); <ide> assert(/^\s+\^/m.test(output)); <ide> assert(/Invalid left-hand side expression in prefix operation/.test(output)); <del>}); <add>}));
9
Ruby
Ruby
convert alt target test to spec
75609f7212c9e992eec22554abb3fb5540e62d96
<add><path>Library/Homebrew/cask/spec/cask/artifact/alt_target_spec.rb <del><path>Library/Homebrew/cask/test/cask/artifact/alt_target_test.rb <del>require "test_helper" <add>require "spec_helper" <ide> <ide> describe Hbc::Artifact::App do <ide> describe "activate to alternate target" do <ide> let(:target_path) { Hbc.appdir.join("AnotherName.app") } <ide> <ide> before do <del> TestHelper.install_without_artifacts(cask) <add> InstallHelper.install_without_artifacts(cask) <ide> end <ide> <ide> it "installs the given apps using the proper target directory" do <del> source_path.must_be :directory? <del> target_path.wont_be :exist? <add> expect(source_path).to be_a_directory <add> expect(target_path).not_to exist <ide> <ide> shutup do <ide> install_phase.call <ide> end <ide> <del> target_path.must_be :directory? <del> source_path.wont_be :exist? <add> expect(target_path).to be_a_directory <add> expect(source_path).not_to exist <ide> end <ide> <ide> describe "when app is in a subdirectory" do <ide> install_phase.call <ide> end <ide> <del> target_path.must_be :directory? <del> appsubdir.join("Caffeine.app").wont_be :exist? <add> expect(target_path).to be_a_directory <add> expect(appsubdir.join("Caffeine.app")).not_to exist <ide> end <ide> end <ide> <ide> install_phase.call <ide> end <ide> <del> target_path.must_be :directory? <del> source_path.wont_be :exist? <add> expect(target_path).to be_a_directory <add> expect(source_path).not_to exist <ide> <del> Hbc.appdir.join("Caffeine Deluxe.app").wont_be :exist? <del> cask.staged_path.join("Caffeine Deluxe.app").must_be :directory? <add> expect(Hbc.appdir.join("Caffeine Deluxe.app")).not_to exist <add> expect(cask.staged_path.join("Caffeine Deluxe.app")).to be_a_directory <ide> end <ide> <ide> it "avoids clobbering an existing app by moving over it" do <ide> target_path.mkpath <ide> <del> err = install_phase.must_raise(Hbc::CaskError) <add> expect(install_phase).to raise_error(Hbc::CaskError, "It seems there is already an App at '#{target_path}'.") <ide> <del> err.message.must_equal("It seems there is already an App at '#{target_path}'.") <del> <del> source_path.must_be :directory? <del> target_path.must_be :directory? <del> File.identical?(source_path, target_path).must_equal false <add> expect(source_path).to be_a_directory <add> expect(target_path).to be_a_directory <add> expect(File.identical?(source_path, target_path)).to be false <ide> end <ide> end <ide> end
1
Go
Go
add support for windows version filtering on pull
38aef56e1fcb8ea318df98c89cf002267b88a136
<ide><path>distribution/pull_v2.go <ide> func (p *v2Puller) pullManifestList(ctx context.Context, ref reference.Named, mf <ide> } <ide> <ide> logrus.Debugf("%s resolved to a manifestList object with %d entries; looking for a os/arch match", ref, len(mfstList.Manifests)) <del> var manifestDigest digest.Digest <del> // TODO @jhowardmsft LCOW Support: Need to remove the hard coding in LCOW mode. <del> lookingForOS := runtime.GOOS <del> if system.LCOWSupported() { <del> lookingForOS = "linux" <del> } <del> for _, manifestDescriptor := range mfstList.Manifests { <del> // TODO(aaronl): The manifest list spec supports optional <del> // "features" and "variant" fields. These are not yet used. <del> // Once they are, their values should be interpreted here. <del> if manifestDescriptor.Platform.Architecture == runtime.GOARCH && manifestDescriptor.Platform.OS == lookingForOS { <del> manifestDigest = manifestDescriptor.Digest <del> logrus.Debugf("found match for %s/%s with media type %s, digest %s", runtime.GOOS, runtime.GOARCH, manifestDescriptor.MediaType, manifestDigest.String()) <del> break <del> } <del> } <ide> <del> if manifestDigest == "" { <add> manifestMatches := filterManifests(mfstList.Manifests) <add> <add> if len(manifestMatches) == 0 { <ide> errMsg := fmt.Sprintf("no matching manifest for %s/%s in the manifest list entries", runtime.GOOS, runtime.GOARCH) <ide> logrus.Debugf(errMsg) <ide> return "", "", errors.New(errMsg) <ide> } <ide> <add> if len(manifestMatches) > 1 { <add> logrus.Debugf("found multiple matches in manifest list, choosing best match %s", manifestMatches[0].Digest.String()) <add> } <add> manifestDigest := manifestMatches[0].Digest <add> <ide> manSvc, err := p.repo.Manifests(ctx) <ide> if err != nil { <ide> return "", "", err <ide><path>distribution/pull_v2_unix.go <ide> package distribution <ide> <ide> import ( <add> "runtime" <add> <ide> "github.com/docker/distribution" <ide> "github.com/docker/distribution/context" <add> "github.com/docker/distribution/manifest/manifestlist" <add> "github.com/sirupsen/logrus" <ide> ) <ide> <ide> func (ld *v2LayerDescriptor) open(ctx context.Context) (distribution.ReadSeekCloser, error) { <ide> blobs := ld.repo.Blobs(ctx) <ide> return blobs.Open(ctx, ld.digest) <ide> } <add> <add>func filterManifests(manifests []manifestlist.ManifestDescriptor) []manifestlist.ManifestDescriptor { <add> var matches []manifestlist.ManifestDescriptor <add> for _, manifestDescriptor := range manifests { <add> if manifestDescriptor.Platform.Architecture == runtime.GOARCH && manifestDescriptor.Platform.OS == runtime.GOOS { <add> matches = append(matches, manifestDescriptor) <add> <add> logrus.Debugf("found match for %s/%s with media type %s, digest %s", runtime.GOOS, runtime.GOARCH, manifestDescriptor.MediaType, manifestDescriptor.Digest.String()) <add> } <add> } <add> return matches <add>} <ide><path>distribution/pull_v2_windows.go <ide> package distribution <ide> <ide> import ( <add> "fmt" <ide> "net/http" <ide> "os" <add> "runtime" <add> "sort" <add> "strings" <ide> <ide> "github.com/docker/distribution" <ide> "github.com/docker/distribution/context" <add> "github.com/docker/distribution/manifest/manifestlist" <ide> "github.com/docker/distribution/manifest/schema2" <ide> "github.com/docker/distribution/registry/client/transport" <add> "github.com/docker/docker/pkg/system" <ide> "github.com/sirupsen/logrus" <ide> ) <ide> <ide> func (ld *v2LayerDescriptor) open(ctx context.Context) (distribution.ReadSeekClo <ide> } <ide> return rsc, err <ide> } <add> <add>func filterManifests(manifests []manifestlist.ManifestDescriptor) []manifestlist.ManifestDescriptor { <add> version := system.GetOSVersion() <add> <add> // TODO @jhowardmsft LCOW Support: Need to remove the hard coding in LCOW mode. <add> lookingForOS := runtime.GOOS <add> osVersion := fmt.Sprintf("%d.%d.%d", version.MajorVersion, version.MinorVersion, version.Build) <add> if system.LCOWSupported() { <add> lookingForOS = "linux" <add> osVersion = "" <add> } <add> <add> var matches []manifestlist.ManifestDescriptor <add> for _, manifestDescriptor := range manifests { <add> if manifestDescriptor.Platform.Architecture == runtime.GOARCH && manifestDescriptor.Platform.OS == lookingForOS { <add> if !versionMatch(manifestDescriptor.Platform.OSVersion, osVersion) { <add> continue <add> } <add> matches = append(matches, manifestDescriptor) <add> <add> logrus.Debugf("found match for %s/%s with media type %s, digest %s", runtime.GOOS, runtime.GOARCH, manifestDescriptor.MediaType, manifestDescriptor.Digest.String()) <add> } <add> } <add> sort.Stable(manifestsByVersion(matches)) <add> return matches <add>} <add> <add>func versionMatch(actual, expected string) bool { <add> // Check whether actual and expected are equivalent, or whether <add> // expected is a version prefix of actual. <add> return actual == "" || expected == "" || actual == expected || strings.HasPrefix(actual, expected+".") <add>} <add> <add>type manifestsByVersion []manifestlist.ManifestDescriptor <add> <add>func (mbv manifestsByVersion) Less(i, j int) bool { <add> if mbv[i].Platform.OSVersion == "" { <add> return false <add> } <add> if mbv[j].Platform.OSVersion == "" { <add> return true <add> } <add> // TODO: Split version by parts and compare <add> // TODO: Prefer versions which have a greater version number <add> return false <add>} <add> <add>func (mbv manifestsByVersion) Len() int { <add> return len(mbv) <add>} <add> <add>func (mbv manifestsByVersion) Swap(i, j int) { <add> mbv[i], mbv[j] = mbv[j], mbv[i] <add>}
3
Text
Text
update the notable changes
cf989b6c11278ecba6f2727ef2996b48de3e1409
<ide><path>doc/changelogs/CHANGELOG_V10.md <ide> This is a follow up release to fix two regressions that were introduced in v10.2 <ide> <ide> * Assert <ide> * Calling `assert.fail()` with more than one argument is deprecated. [[`70dcacd710`](https://github.com/nodejs/node/commit/70dcacd710)] <del> * Calling `assert.ok()` with no arguments will now throw. [[`3cd7977a42`](https://github.com/nodejs/node/commit/3cd7977a42)] <ide> * Calling `assert.ifError()` will now throw with any argument other than `undefined` or `null`. Previously the method would throw with any truthy value. [[`e65a6e81ef`](https://github.com/nodejs/node/commit/e65a6e81ef)] <ide> * The `assert.rejects()` and `assert.doesNotReject()` methods have been added for working with async functions. [[`599337f43e`](https://github.com/nodejs/node/commit/599337f43e)] <add> * Assertion errors will show a diff in case objects are used. [[`2d9e87695e`](https://github.com/nodejs/node/commit/2d9e87695e)] <add> * `assert.throws()` accepts an object for comparison to the error. [[`2d374916eb`](https://github.com/nodejs/node/commit/2d374916eb)] <add> * The error message from `assert.ok(expression)` now also contains the expression itself. [[`f76ef50432`](https://github.com/nodejs/node/commit/f76ef50432)] <ide> * Async_hooks <ide> * Older experimental async_hooks APIs have been removed. [[`1cc6b993b9`](https://github.com/nodejs/node/commit/1cc6b993b9)] <ide> * Buffer <ide> * Uses of `new Buffer()` and `Buffer()` outside of the `node_modules` directory will now emit a runtime deprecation warning. [[`9d4ab90117`](https://github.com/nodejs/node/commit/9d4ab90117)] <ide> * `Buffer.isEncoding()` now returns `undefined` for falsy values, including an empty string. [[`452eed956e`](https://github.com/nodejs/node/commit/452eed956e)] <ide> * `Buffer.fill()` will throw if an attempt is made to fill with an empty `Buffer`. [[`1e802539b2`](https://github.com/nodejs/node/commit/1e802539b2)] <add> * `noAssert` argument was removed from all `Buffer` read and write functions. [[`e8bb1f35df`](https://github.com/nodejs/node/commit/e8bb1f35df)] <ide> * Child Process <ide> * Undefined properties of env are ignored. [[`38ee25e2e2`](https://github.com/nodejs/node/commit/38ee25e2e2)], [[`85739b6c5b`](https://github.com/nodejs/node/commit/85739b6c5b)] <ide> * Console <ide> This is a follow up release to fix two regressions that were introduced in v10.2 <ide> * The `crypto.DEFAULT_ENCODING` property has been deprecated. [[`6035beea93`](https://github.com/nodejs/node/commit/6035beea93)] <ide> * The `ECDH.convertKey()` method has been added. [[`f2e02883e7`](https://github.com/nodejs/node/commit/f2e02883e7)] <ide> * The `crypto.fips` property has been deprecated. [[`6e7992e8b8`](https://github.com/nodejs/node/commit/6e7992e8b8)] <add> * The AES-CCM algorithm has been implemented. [[`1e07acd476`](https://github.com/nodejs/node/commit/1e07acd476)] <ide> * Dependencies <ide> * V8 has been updated to 6.6. [[`9daebb48d6`](https://github.com/nodejs/node/commit/9daebb48d6)] <ide> * OpenSSL has been updated to 1.1.0h. [[`66cb29e646`](https://github.com/nodejs/node/commit/66cb29e646)] <ide> This is a follow up release to fix two regressions that were introduced in v10.2 <ide> * Util <ide> * `util.types.is[…]` type checks have been added. [[`b20af8088a`](https://github.com/nodejs/node/commit/b20af8088a)] <ide> * Support for bigint formatting has been added to `util.inspect()`. [[`39dc947409`](https://github.com/nodejs/node/commit/39dc947409)] <add> * `util.inspect()` custom inspection with `inspect` property has been deprecated at runtime. [[`617e3e96e6`](https://github.com/nodejs/node/commit/617e3e96e6)] <ide> <ide> #### Deprecations: <ide>
1
Javascript
Javascript
use 255 instead of infinity
3a946fe0944aab319c7b73fb196314c80c955027
<ide><path>src/renderers/shared/fiber/ReactFiberUpdateQueue.js <ide> function comparePriority(a : PriorityLevel, b : PriorityLevel) : number { <ide> return 0; <ide> } <ide> if (a === NoWork && b !== NoWork) { <del> return -Infinity; <add> return -255; <ide> } <ide> if (a !== NoWork && b === NoWork) { <del> return Infinity; <add> return 255; <ide> } <ide> return a - b; <ide> } <ide> function addReplaceUpdate( <ide> for (let i = 0; queue && i < 2; i++) { <ide> let replaceAfter = null; <ide> let replaceBefore = queue.first; <del> let comparison = Infinity; <add> let comparison = 255; <ide> while (replaceBefore && <ide> (comparison = comparePriority(replaceBefore.priorityLevel, priorityLevel)) <= 0) { <ide> if (comparison < 0) {
1
Go
Go
fix stack overflow in errinadequatecapacity
4db753c0174420152957224d38fb6e8b6ae6908e
<ide><path>plugin/store/store.go <ide> func (ps *Store) SetAll(plugins map[string]*v2.Plugin) { <ide> ps.plugins = plugins <ide> } <ide> <del>func (ps *Store) getByCap(name string, capability string) (*v2.Plugin, error) { <del> ps.RLock() <del> defer ps.RUnlock() <del> <del> p, err := ps.GetByName(name) <del> if err != nil { <del> return nil, err <del> } <del> return p.FilterByCap(capability) <del>} <del> <ide> func (ps *Store) getAllByCap(capability string) []plugingetter.CompatPlugin { <ide> ps.RLock() <ide> defer ps.RUnlock() <ide><path>plugin/store/store_test.go <add>package store <add> <add>import ( <add> "testing" <add> <add> "github.com/docker/docker/api/types" <add> "github.com/docker/docker/plugin/v2" <add>) <add> <add>func TestFilterByCapNeg(t *testing.T) { <add> p := v2.NewPlugin("test", "1234567890", "/run/docker", "latest") <add> <add> iType := types.PluginInterfaceType{"volumedriver", "docker", "1.0"} <add> i := types.PluginManifestInterface{"plugins.sock", []types.PluginInterfaceType{iType}} <add> p.PluginObj.Manifest.Interface = i <add> <add> _, err := p.FilterByCap("foobar") <add> if err == nil { <add> t.Fatalf("expected inadequate error, got %v", err) <add> } <add>} <add> <add>func TestFilterByCapPos(t *testing.T) { <add> p := v2.NewPlugin("test", "1234567890", "/run/docker", "latest") <add> <add> iType := types.PluginInterfaceType{"volumedriver", "docker", "1.0"} <add> i := types.PluginManifestInterface{"plugins.sock", []types.PluginInterfaceType{iType}} <add> p.PluginObj.Manifest.Interface = i <add> <add> _, err := p.FilterByCap("volumedriver") <add> if err != nil { <add> t.Fatalf("expected no error, got %v", err) <add> } <add>} <ide><path>plugin/v2/plugin.go <ide> type Plugin struct { <ide> const defaultPluginRuntimeDestination = "/run/docker/plugins" <ide> <ide> // ErrInadequateCapability indicates that the plugin did not have the requested capability. <del>type ErrInadequateCapability string <add>type ErrInadequateCapability struct { <add> cap string <add>} <ide> <del>func (cap ErrInadequateCapability) Error() string { <del> return fmt.Sprintf("plugin does not provide %q capability", cap) <add>func (e ErrInadequateCapability) Error() string { <add> return fmt.Sprintf("plugin does not provide %q capability", e.cap) <ide> } <ide> <ide> func newPluginObj(name, id, tag string) types.Plugin { <ide> func (p *Plugin) FilterByCap(capability string) (*Plugin, error) { <ide> return p, nil <ide> } <ide> } <del> return nil, ErrInadequateCapability(capability) <add> return nil, ErrInadequateCapability{capability} <ide> } <ide> <ide> // RemoveFromDisk deletes the plugin's runtime files from disk.
3
PHP
PHP
use path and domain in session store
ac5b414f988d5cd952a5749f87586ab9f1ac8d13
<ide><path>src/Illuminate/Session/Store.php <ide> public function hitsLottery() <ide> * <ide> * @param Illuminate\Cookie\CookieJar $cookie <ide> * @param string $name <del> * @param int $lifetime <add> * @param int $lifetime <add> * @param string $path <add> * @param string $domain <ide> * @return void <ide> */ <del> public function getCookie(CookieJar $cookie, $name, $lifetime) <add> public function getCookie(CookieJar $cookie, $name, $lifetime, $path, $domain) <ide> { <del> return $cookie->make($name, $this->getSessionId(), $lifetime); <add> return $cookie->make($name, $this->getSessionId(), $lifetime, $path, $domain); <ide> } <ide> <ide> /**
1
Mixed
Python
remove unused import
0fb1ebcfcf98a9284baf3b5b840c36aeccefa6c7
<ide><path>docs/topics/3.3-announcement.md <ide> The 3.3 release marks the final work in the Kickstarter funded series. We'd like <ide> <ide> The amount of work that has been achieved as a direct result of the funding is immense. We've added a huge amounts of new functionality, resolved nearly 2,000 tickets, and redesigned & refined large parts of the project. <ide> <del>In order to continue **TODO** <add>In order to continue driving REST framework forward, we're introducing [monthly paid plans](https://fund.django-rest-framework.org/topics/funding). These plans include various sponsorship rewards, and will ensure that the project remains sustainable and well supported. <add> <add>We strongly believe that collaboratively funded software development yields outstanding results for a relatively low investment-per-head. If you or your company use REST framework commercially, then we would strongly urge you to participate in this latest funding drive, and help us continue to build an increasingly polished & professional product. <ide> <ide> --- <ide> <ide><path>rest_framework/pagination.py <ide> """ <ide> from __future__ import unicode_literals <ide> <del>import warnings <ide> from base64 import b64decode, b64encode <ide> from collections import OrderedDict, namedtuple <ide>
2
Text
Text
clarify guidance re trust of keys in release docs
ae1fa4c8b2b2d91ab01697e7a201f321c5c767c3
<ide><path>dev/README_RELEASE_AIRFLOW.md <ide> retrieves it from the default GPG keyserver <ide> [OpenPGP.org](https://keys.openpgp.org): <ide> <ide> ```shell script <del>gpg --receive-keys 12717556040EEF2EEAF1B9C275FCCD0A25FA0E4B <add>gpg --keyserver keys.openpgp.org --receive-keys CDE15C6E4D3A8EC4ECF4BA4B6674E08AD7DE406F <ide> ``` <ide> <ide> You should choose to import the key when asked. <ide> errors or timeouts. Many of the release managers also uploaded their keys to the <ide> [GNUPG.net](https://keys.gnupg.net) keyserver, and you can retrieve it from there. <ide> <ide> ```shell script <del>gpg --keyserver keys.gnupg.net --receive-keys 12717556040EEF2EEAF1B9C275FCCD0A25FA0E4B <add>gpg --keyserver keys.gnupg.net --receive-keys CDE15C6E4D3A8EC4ECF4BA4B6674E08AD7DE406F <ide> ``` <ide> <ide> Once you have the keys, the signatures can be verified by running this: <ide> done <ide> <ide> This should produce results similar to the below. The "Good signature from ..." is indication <ide> that the signatures are correct. Do not worry about the "not certified with a trusted signature" <del>warning. Most of the certificates used by release managers are self signed, that's why you get this <del>warning. By importing the server in the previous step and importing it via ID from <add>warning. Most of the certificates used by release managers are self-signed, and that's why you get this <add>warning. By importing the key either from the server in the previous step or from the <ide> [KEYS](https://dist.apache.org/repos/dist/release/airflow/KEYS) page, you know that <del>this is a valid Key already. <add>this is a valid key already. To suppress the warning you may edit the key's trust level <add>by running `gpg --edit-key <key id> trust` and entering `5` to assign trust level `ultimate`. <ide> <ide> ``` <ide> Checking apache-airflow-2.0.2rc4.tar.gz.asc <ide><path>dev/README_RELEASE_AIRFLOW_UPGRADE_CHECK.md <ide> retrieves it from the default GPG keyserver <ide> [OpenPGP.org](https://keys.openpgp.org): <ide> <ide> ```shell script <del>gpg --receive-keys 12717556040EEF2EEAF1B9C275FCCD0A25FA0E4B <add>gpg --keyserver keys.openpgp.org --receive-keys CDE15C6E4D3A8EC4ECF4BA4B6674E08AD7DE406F <ide> ``` <ide> <ide> You should choose to import the key when asked. <ide> errors or timeouts. Many of the release managers also uploaded their keys to the <ide> [GNUPG.net](https://keys.gnupg.net) keyserver, and you can retrieve it from there. <ide> <ide> ```shell script <del>gpg --keyserver keys.gnupg.net --receive-keys 12717556040EEF2EEAF1B9C275FCCD0A25FA0E4B <add>gpg --keyserver keys.gnupg.net --receive-keys CDE15C6E4D3A8EC4ECF4BA4B6674E08AD7DE406F <ide> ``` <ide> <ide> Once you have the keys, the signatures can be verified by running this: <ide> done <ide> <ide> This should produce results similar to the below. The "Good signature from ..." is indication <ide> that the signatures are correct. Do not worry about the "not certified with a trusted signature" <del>warning. Most of the certificates used by release managers are self signed, that's why you get this <del>warning. By importing the server in the previous step and importing it via ID from <add>warning. Most of the certificates used by release managers are self-signed, and that's why you get this <add>warning. By importing the key either from the server in the previous step or from the <ide> [KEYS](https://dist.apache.org/repos/dist/release/airflow/KEYS) page, you know that <del>this is a valid Key already. <add>this is a valid key already. To suppress the warning you may edit the key's trust level <add>by running `gpg --edit-key <key id> trust` and entering `5` to assign trust level `ultimate`. <ide> <ide> ``` <ide> Checking apache-airflow-upgrade-check-1.3.0rc1.tar.gz.asc <ide><path>dev/README_RELEASE_HELM_CHART.md <ide> Make sure you have imported into your GPG the PGP key of the person signing the <ide> <ide> You can import the whole KEYS file: <ide> <del>```shell <add>```shell script <ide> gpg --import KEYS <ide> ``` <ide> <ide> You can also import the keys individually from a keyserver. The below one uses Kaxil's key and <ide> retrieves it from the default GPG keyserver <ide> [OpenPGP.org](https://keys.openpgp.org): <ide> <del>```shell <del>gpg --receive-keys 12717556040EEF2EEAF1B9C275FCCD0A25FA0E4B <add>```shell script <add>gpg --keyserver keys.openpgp.org --receive-keys CDE15C6E4D3A8EC4ECF4BA4B6674E08AD7DE406F <ide> ``` <ide> <ide> You should choose to import the key when asked. <ide> Note that by being default, the OpenPGP server tends to be overloaded often and <ide> errors or timeouts. Many of the release managers also uploaded their keys to the <ide> [GNUPG.net](https://keys.gnupg.net) keyserver, and you can retrieve it from there. <ide> <del>```shell <del>gpg --keyserver keys.gnupg.net --receive-keys 12717556040EEF2EEAF1B9C275FCCD0A25FA0E4B <add>```shell script <add>gpg --keyserver keys.gnupg.net --receive-keys CDE15C6E4D3A8EC4ECF4BA4B6674E08AD7DE406F <ide> ``` <ide> <ide> Once you have the keys, the signatures can be verified by running this: <ide> <del>```shell <add>```shell script <ide> for i in *.asc <ide> do <ide> echo -e "Checking $i\n"; gpg --verify $i <ide> done <ide> <ide> This should produce results similar to the below. The "Good signature from ..." is indication <ide> that the signatures are correct. Do not worry about the "not certified with a trusted signature" <del>warning. Most of the certificates used by release managers are self signed, that's why you get this <del>warning. By importing the server in the previous step and importing it via ID from <add>warning. Most of the certificates used by release managers are self-signed, and that's why you get this <add>warning. By importing the key either from the server in the previous step or from the <ide> [KEYS](https://dist.apache.org/repos/dist/release/airflow/KEYS) page, you know that <del>this is a valid Key already. <add>this is a valid key already. To suppress the warning you may edit the key's trust level <add>by running `gpg --edit-key <key id> trust` and entering `5` to assign trust level `ultimate`. <ide> <ide> ``` <ide> Checking airflow-1.0.0.tgz.asc <ide><path>dev/README_RELEASE_PROVIDER_PACKAGES.md <ide> retrieves it from the default GPG keyserver <ide> [OpenPGP.org](https://keys.openpgp.org): <ide> <ide> ```shell script <del>gpg --receive-keys 12717556040EEF2EEAF1B9C275FCCD0A25FA0E4B <add>gpg --keyserver keys.openpgp.org --receive-keys CDE15C6E4D3A8EC4ECF4BA4B6674E08AD7DE406F <ide> ``` <ide> <ide> You should choose to import the key when asked. <ide> errors or timeouts. Many of the release managers also uploaded their keys to the <ide> [GNUPG.net](https://keys.gnupg.net) keyserver, and you can retrieve it from there. <ide> <ide> ```shell script <del>gpg --keyserver keys.gnupg.net --receive-keys 12717556040EEF2EEAF1B9C275FCCD0A25FA0E4B <add>gpg --keyserver keys.gnupg.net --receive-keys CDE15C6E4D3A8EC4ECF4BA4B6674E08AD7DE406F <ide> ``` <ide> <ide> Once you have the keys, the signatures can be verified by running this: <ide> done <ide> <ide> This should produce results similar to the below. The "Good signature from ..." is indication <ide> that the signatures are correct. Do not worry about the "not certified with a trusted signature" <del>warning. Most of the certificates used by release managers are self signed, that's why you get this <del>warning. By importing the server in the previous step and importing it via ID from <add>warning. Most of the certificates used by release managers are self-signed, and that's why you get this <add>warning. By importing the key either from the server in the previous step or from the <ide> [KEYS](https://dist.apache.org/repos/dist/release/airflow/KEYS) page, you know that <del>this is a valid Key already. <add>this is a valid key already. To suppress the warning you may edit the key's trust level <add>by running `gpg --edit-key <key id> trust` and entering `5` to assign trust level `ultimate`. <ide> <ide> ``` <ide> Checking apache-airflow-2.0.2rc4.tar.gz.asc
4
Javascript
Javascript
add error checking in callback
c090ca816046241658a576d97e28d529a5daf493
<ide><path>test/parallel/test-dgram-send-callback-buffer-length.js <ide> const offset = 20; <ide> const len = buf.length - offset; <ide> <ide> const messageSent = common.mustCall(function messageSent(err, bytes) { <add> assert.ifError(err); <ide> assert.notStrictEqual(bytes, buf.length); <ide> assert.strictEqual(bytes, buf.length - offset); <ide> client.close();
1
Ruby
Ruby
add a factory method that accepts a formula object
6f02314cba77825db1fbcc186e96ff9ec49f7f58
<ide><path>Library/Homebrew/cmd/bottle.rb <ide> def bottle_formula f <ide> bottle_revision = max ? max + 1 : 0 <ide> end <ide> <del> filename = Bottle::Filename.new(f.name, f.pkg_version, bottle_tag, bottle_revision) <add> filename = Bottle::Filename.create(f, bottle_tag, bottle_revision) <ide> <ide> if bottle_filename_formula_name(filename).empty? <ide> return ofail "Add a new regex to bottle_version.rb to parse #{f.version} from #{filename}" <ide><path>Library/Homebrew/software_spec.rb <ide> class Bottle <ide> class Filename <ide> attr_reader :name, :version, :tag, :revision <ide> <add> def self.create(formula, tag, revision) <add> new(formula.name, formula.pkg_version, tag, revision) <add> end <add> <ide> def initialize(name, version, tag, revision) <ide> @name = name <ide> @version = version <ide> def initialize(formula, spec) <ide> <ide> checksum, tag = spec.checksum_for(bottle_tag) <ide> <del> filename = Filename.new(formula.name, formula.pkg_version, tag, spec.revision) <add> filename = Filename.create(formula, tag, spec.revision) <ide> @resource.url = build_url(spec.root_url, filename) <ide> @resource.download_strategy = CurlBottleDownloadStrategy <ide> @resource.version = formula.pkg_version <ide><path>Library/Homebrew/test/test_bottle_filename.rb <ide> require "testing_env" <add>require "formula" <ide> require "software_spec" <ide> <ide> class BottleFilenameTests < Homebrew::TestCase <ide> def test_to_str <ide> assert_equal expected, fn(0).to_s <ide> assert_equal expected, fn(0).to_str <ide> end <add> <add> def test_create <add> f = formula { <add> url "https://example.com/foo.tar.gz" <add> version "1.0" <add> } <add> <add> expected = "formula_name-1.0.tag.bottle.tar.gz" <add> assert_equal expected, Bottle::Filename.create(f, :tag, 0).to_s <add> end <ide> end
3
Javascript
Javascript
remove reschedule fixes #742
3631ff0f1ba73a193da653935ca27bdff1552929
<ide><path>packages/ember-metal/lib/watching.js <ide> var pendingQueue = []; <ide> // back in the queue and reschedule is true, schedules a timeout to try <ide> // again. <ide> /** @private */ <del>function flushPendingChains(reschedule) { <add>function flushPendingChains() { <ide> if (pendingQueue.length===0) return ; // nothing to do <ide> <ide> var queue = pendingQueue; <ide> pendingQueue = []; <ide> <ide> forEach(queue, function(q) { q[0].add(q[1]); }); <del> if (reschedule!==false && pendingQueue.length>0) { <del> setTimeout(flushPendingChains, 1); <del> } <add> <add> Ember.warn('Watching an undefined global, Ember expects watched globals to be setup by the time the run loop is flushed, check for typos', pendingQueue.length > 0); <ide> } <ide> <ide> /** @private */
1
Mixed
Ruby
make preload_link_tag work with images
46bfd082b00a6c10f7263c769edb9c053bd03936
<ide><path>actionview/CHANGELOG.md <add>* `preload_link_tag` properly inserts `as` attributes for files with `image` MIME types, such as JPG or SVG. <add> <add> *Nate Berkopec* <add> <ide> * Add `weekday_options_for_select` and `weekday_select` helper methods. Also adds `weekday_select` to `FormBuilder`. <ide> <ide> *Drew Bragg*, *Dana Kashubeck*, *Kasper Timm Hansen* <ide><path>actionview/lib/action_view/helpers/asset_tag_helper.rb <ide> def resolve_link_as(extname, mime_type) <ide> "style" <ide> elsif extname == "vtt" <ide> "track" <del> elsif extname == "svg" <del> "image" <del> elsif (type = mime_type.to_s.split("/")[0]) && type.in?(%w(audio video font)) <add> elsif (type = mime_type.to_s.split("/")[0]) && type.in?(%w(audio video font image)) <ide> type <ide> end <ide> end <ide><path>actionview/test/template/asset_tag_helper_test.rb <ide> def content_security_policy_nonce <ide> %(preload_link_tag '//example.com/font.woff2', crossorigin: 'use-credentials') => %(<link rel="preload" href="//example.com/font.woff2" as="font" type="font/woff2" crossorigin="use-credentials" />), <ide> %(preload_link_tag '/media/audio.ogg', nopush: true) => %(<link rel="preload" href="/media/audio.ogg" as="audio" type="audio/ogg" />), <ide> %(preload_link_tag '/style.css', integrity: 'sha256-AbpHGcgLb+kRsJGnwFEktk7uzpZOCcBY74+YBdrKVGs') => %(<link rel="preload" href="/style.css" as="style" type="text/css" integrity="sha256-AbpHGcgLb+kRsJGnwFEktk7uzpZOCcBY74+YBdrKVGs">), <del> %(preload_link_tag '/sprite.svg') => %(<link rel="preload" href="/sprite.svg" as="image" type="image/svg+xml">) <add> %(preload_link_tag '/sprite.svg') => %(<link rel="preload" href="/sprite.svg" as="image" type="image/svg+xml">), <add> %(preload_link_tag '/mb-icon.png') => %(<link rel="preload" href="/mb-icon.png" as="image" type="image/png">) <ide> } <ide> <ide> VideoPathToTag = {
3
Ruby
Ruby
handle corrupt checkouts
7deb2f85e82c43f6927f8e89f8f81fb10ddbecef
<ide><path>Library/Homebrew/download_strategy.rb <ide> def hgpath <ide> def fetch <ide> ohai "Cloning #{@url}" <ide> <del> unless @clone.exist? <del> url=@url.sub(%r[^hg://], '') <del> safe_system hgpath, 'clone', url, @clone <del> else <add> if @clone.exist? && repo_valid? <ide> puts "Updating #{@clone}" <del> Dir.chdir(@clone) do <add> @clone.cd do <ide> safe_system hgpath, 'pull' <ide> safe_system hgpath, 'update' <ide> end <add> elsif @clone.exist? <add> puts "Removing invalid hg repo from cache" <add> @clone.rmtree <add> clone_repo <add> else <add> clone_repo <ide> end <ide> end <ide> <add> def repo_valid? <add> @clone.join(".hg").directory? <add> end <add> <add> def clone_repo <add> url = @url.sub(%r[^hg://], '') <add> safe_system hgpath, 'clone', url, @clone <add> end <add> <ide> def stage <ide> dst=Dir.getwd <ide> Dir.chdir @clone do
1
PHP
PHP
fix more coding standards problems
664b0538b8c7cab40a6a035d7eb977f7814337ab
<ide><path>lib/Cake/Console/Command/Task/ProjectTask.php <ide> public function execute() { <ide> $this->out(__d('cake_console', ' * CAKE_CORE_INCLUDE_PATH set to %s in webroot/index.php', CAKE_CORE_INCLUDE_PATH)); <ide> $this->out(__d('cake_console', ' * CAKE_CORE_INCLUDE_PATH set to %s in webroot/test.php', CAKE_CORE_INCLUDE_PATH)); <ide> } else { <del> $this->err(__d('cake_console', 'Unable to set CAKE_CORE_INCLUDE_PATH, you should change it in %s', $path . 'webroot' . DS .'index.php')); <add> $this->err(__d('cake_console', 'Unable to set CAKE_CORE_INCLUDE_PATH, you should change it in %s', $path . 'webroot' . DS . 'index.php')); <ide> $success = false; <ide> } <ide> if ($success && $hardCode) { <ide> public function execute() { <ide> <ide> $Folder = new Folder($path); <ide> if (!$Folder->chmod($path . 'tmp', 0777)) { <del> $this->err(__d('cake_console', 'Could not set permissions on %s', $path . DS .'tmp')); <del> $this->out(__d('cake_console', 'chmod -R 0777 %s', $path . DS .'tmp')); <add> $this->err(__d('cake_console', 'Could not set permissions on %s', $path . DS . 'tmp')); <add> $this->out(__d('cake_console', 'chmod -R 0777 %s', $path . DS . 'tmp')); <ide> $success = false; <ide> } <ide> if ($success) { <ide> public function bake($path, $skel = null, $skip = array('empty')) { <ide> public function createHome($dir) { <ide> $app = basename($dir); <ide> $path = $dir . 'View' . DS . 'Pages' . DS; <del> $source = CAKE . 'Console' . DS . 'Templates' . DS .'default' . DS . 'views' . DS . 'home.ctp'; <add> $source = CAKE . 'Console' . DS . 'Templates' . DS . 'default' . DS . 'views' . DS . 'home.ctp'; <ide> include $source; <ide> return $this->createFile($path . 'home.ctp', $output); <ide> } <ide><path>lib/Cake/Console/Templates/skel/webroot/index.php <ide> /** <ide> * Use the DS to separate the directories in other defines <ide> */ <del> if (!defined('DS')) { <del> define('DS', DIRECTORY_SEPARATOR); <del> } <add>if (!defined('DS')) { <add> define('DS', DIRECTORY_SEPARATOR); <add>} <ide> <ide> /** <ide> * These defines should only be edited if you have cake installed in <ide> * The full path to the directory which holds "app", WITHOUT a trailing DS. <ide> * <ide> */ <del> if (!defined('ROOT')) { <del> define('ROOT', dirname(dirname(dirname(__FILE__)))); <del> } <add>if (!defined('ROOT')) { <add> define('ROOT', dirname(dirname(dirname(__FILE__)))); <add>} <ide> <ide> /** <ide> * The actual directory name for the "app". <ide> * <ide> */ <del> if (!defined('APP_DIR')) { <del> define('APP_DIR', basename(dirname(dirname(__FILE__)))); <del> } <add>if (!defined('APP_DIR')) { <add> define('APP_DIR', basename(dirname(dirname(__FILE__)))); <add>} <ide> <ide> /** <ide> * The absolute path to the "cake" directory, WITHOUT a trailing DS. <ide> * <ide> * Leaving this constant undefined will result in it being defined in Cake/bootstrap.php <ide> */ <del> //define('CAKE_CORE_INCLUDE_PATH', __CAKE_PATH__); <add>//define('CAKE_CORE_INCLUDE_PATH', __CAKE_PATH__); <ide> <ide> /** <ide> * Editing below this line should NOT be necessary. <ide> * Change at your own risk. <ide> * <ide> */ <del> if (!defined('WEBROOT_DIR')) { <del> define('WEBROOT_DIR', basename(dirname(__FILE__))); <del> } <del> if (!defined('WWW_ROOT')) { <del> define('WWW_ROOT', dirname(__FILE__) . DS); <del> } <add>if (!defined('WEBROOT_DIR')) { <add> define('WEBROOT_DIR', basename(dirname(__FILE__))); <add>} <add>if (!defined('WWW_ROOT')) { <add> define('WWW_ROOT', dirname(__FILE__) . DS); <add>} <ide> <del> if (!defined('CAKE_CORE_INCLUDE_PATH')) { <del> if (function_exists('ini_set')) { <del> ini_set('include_path', ROOT . DS . 'lib' . PATH_SEPARATOR . ini_get('include_path')); <del> } <del> if (!include('Cake' . DS . 'bootstrap.php')) { <del> $failed = true; <del> } <del> } else { <del> if (!include(CAKE_CORE_INCLUDE_PATH . DS . 'Cake' . DS . 'bootstrap.php')) { <del> $failed = true; <del> } <add>if (!defined('CAKE_CORE_INCLUDE_PATH')) { <add> if (function_exists('ini_set')) { <add> ini_set('include_path', ROOT . DS . 'lib' . PATH_SEPARATOR . ini_get('include_path')); <ide> } <del> if (!empty($failed)) { <del> trigger_error("CakePHP core could not be found. Check the value of CAKE_CORE_INCLUDE_PATH in APP/webroot/index.php. It should point to the directory containing your " . DS . "cake core directory and your " . DS . "vendors root directory.", E_USER_ERROR); <add> if (!include 'Cake' . DS . 'bootstrap.php') { <add> $failed = true; <ide> } <del> <del> if (isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'] == '/favicon.ico') { <del> return; <add>} else { <add> if (!include CAKE_CORE_INCLUDE_PATH . DS . 'Cake' . DS . 'bootstrap.php') { <add> $failed = true; <ide> } <add>} <add>if (!empty($failed)) { <add> trigger_error("CakePHP core could not be found. Check the value of CAKE_CORE_INCLUDE_PATH in APP/webroot/index.php. It should point to the directory containing your " . DS . "cake core directory and your " . DS . "vendors root directory.", E_USER_ERROR); <add>} <add> <add>if (isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'] == '/favicon.ico') { <add> return; <add>} <ide> <del> App::uses('Dispatcher', 'Routing'); <add>App::uses('Dispatcher', 'Routing'); <ide> <del> $Dispatcher = new Dispatcher(); <del> $Dispatcher->dispatch(new CakeRequest(), new CakeResponse(array('charset' => Configure::read('App.encoding')))); <add>$Dispatcher = new Dispatcher(); <add>$Dispatcher->dispatch( <add> new CakeRequest(), <add> new CakeResponse(array('charset' => Configure::read('App.encoding'))) <add>); <ide><path>lib/Cake/Console/Templates/skel/webroot/test.php <ide> /** <ide> * Use the DS to separate the directories in other defines <ide> */ <del> if (!defined('DS')) { <del> define('DS', DIRECTORY_SEPARATOR); <del> } <add>if (!defined('DS')) { <add> define('DS', DIRECTORY_SEPARATOR); <add>} <ide> <ide> /** <ide> * These defines should only be edited if you have cake installed in <ide> * The full path to the directory which holds "app", WITHOUT a trailing DS. <ide> * <ide> */ <del> if (!defined('ROOT')) { <del> define('ROOT', dirname(dirname(dirname(__FILE__)))); <del> } <add>if (!defined('ROOT')) { <add> define('ROOT', dirname(dirname(dirname(__FILE__)))); <add>} <ide> <ide> /** <ide> * The actual directory name for the "app". <ide> * <ide> */ <del> if (!defined('APP_DIR')) { <del> define('APP_DIR', basename(dirname(dirname(__FILE__)))); <del> } <add>if (!defined('APP_DIR')) { <add> define('APP_DIR', basename(dirname(dirname(__FILE__)))); <add>} <ide> <ide> /** <ide> * The absolute path to the "Cake" directory, WITHOUT a trailing DS. <ide> * <ide> * Leaving this constant undefined will result in it being defined in Cake/bootstrap.php <ide> */ <del> //define('CAKE_CORE_INCLUDE_PATH', __CAKE_PATH__); <add>//define('CAKE_CORE_INCLUDE_PATH', __CAKE_PATH__); <ide> <ide> /** <ide> * Editing below this line should not be necessary. <ide> if (function_exists('ini_set')) { <ide> ini_set('include_path', ROOT . DS . 'lib' . PATH_SEPARATOR . ini_get('include_path')); <ide> } <del> if (!include('Cake' . DS . 'bootstrap.php')) { <add> if (!include 'Cake' . DS . 'bootstrap.php') { <ide> $failed = true; <ide> } <ide> } else { <del> if (!include(CAKE_CORE_INCLUDE_PATH . DS . 'Cake' . DS . 'bootstrap.php')) { <add> if (!include CAKE_CORE_INCLUDE_PATH . DS . 'Cake' . DS . 'bootstrap.php') { <ide> $failed = true; <ide> } <ide> } <ide><path>lib/Cake/I18n/I18n.php <ide> protected function _bindTextDomain($domain) { <ide> public static function loadMo($filename) { <ide> $translations = false; <ide> <add> // @codingStandardsIgnoreStart <add> // Binary files extracted makes non-standard local variables <ide> if ($data = file_get_contents($filename)) { <ide> $translations = array(); <ide> $header = substr($data, 0, 20); <ide> public static function loadMo($filename) { <ide> } <ide> } <ide> } <add> // @codingStandardsIgnoreEnd <ide> <ide> return $translations; <ide> } <ide><path>lib/Cake/Model/Datasource/Database/Mysql.php <ide> public function index($model) { <ide> $old = version_compare($this->getVersion(), '4.1', '<='); <ide> if ($table) { <ide> $indices = $this->_execute('SHOW INDEX FROM ' . $table); <add> // @codingStandardsIgnoreStart <add> // MySQL columns don't match the cakephp conventions. <ide> while ($idx = $indices->fetch(PDO::FETCH_OBJ)) { <ide> if ($old) { <ide> $idx = (object)current((array)$idx); <ide> public function index($model) { <ide> $index[$idx->Key_name]['column'] = $col; <ide> } <ide> } <add> // @codingStandardsIgnoreEnd <ide> $indices->closeCursor(); <ide> } <ide> return $index; <ide><path>lib/Cake/Model/Datasource/Database/Postgres.php <ide> public function describe($model) { <ide> array($table, $this->config['schema']) <ide> ); <ide> <add> // @codingStandardsIgnoreStart <add> // Postgres columns don't match the coding standards. <ide> foreach ($cols as $c) { <ide> $type = $c->type; <ide> if (!empty($c->oct_length) && $c->char_length === null) { <ide> public function describe($model) { <ide> } <ide> $this->_cacheDescription($table, $fields); <ide> } <add> // @codingStandardsIgnoreEnd <add> <ide> if (isset($model->sequence)) { <ide> $this->_sequenceMap[$table][$model->primaryKey] = $model->sequence; <ide> } <ide><path>lib/Cake/Model/Model.php <ide> protected function _findNeighbors($state, $query, $results = array()) { <ide> $field = $this->alias . '.' . $this->primaryKey; <ide> $value = $this->id; <ide> } <del> $query['conditions'] = array_merge($conditions, array($field . ' <' => $value)); <add> $query['conditions'] = array_merge($conditions, array($field . ' <' => $value)); <ide> $query['order'] = $field . ' DESC'; <ide> $query['limit'] = 1; <ide> $query['field'] = $field; <ide><path>lib/Cake/Utility/Set.php <ide> protected static function _map(&$array, $class, $primary = false) { <ide> } <ide> } elseif (is_array($value)) { <ide> if ($primary === true) { <add> // @codingStandardsIgnoreStart Legacy junk <ide> if (!isset($out->_name_)) { <ide> $out->_name_ = $key; <ide> } <add> // @codingStandardsIgnoreEnd <ide> $primary = false; <ide> foreach ($value as $key2 => $value2) { <ide> $out->{$key2} = Set::_map($value2, true); <ide> public static function reverse($object) { <ide> if (is_array($value)) { <ide> $new[$key] = (array)Set::reverse($value); <ide> } else { <add> // @codingStandardsIgnoreStart Legacy junk <ide> if (isset($value->_name_)) { <ide> $new = array_merge($new, Set::reverse($value)); <ide> } else { <ide> $new[$key] = Set::reverse($value); <del> } <add> } <add> // @codingStandardsIgnoreEnd <ide> } <ide> } <ide> if (isset($identity)) { <ide><path>lib/Cake/View/Helper/JqueryEngineHelper.php <ide> public function effect($name, $options = array()) { <ide> $name = ($name == 'slideIn') ? 'slideDown' : 'slideUp'; <ide> case 'hide': <ide> case 'show': <del> case 'fadeIn': <add> case 'fadeIn': <ide> case 'fadeOut': <ide> case 'slideDown': <ide> case 'slideUp': <ide><path>lib/Cake/basics.php <ide> function config() { <ide> $args = func_get_args(); <ide> foreach ($args as $arg) { <ide> if (file_exists(APP . 'Config' . DS . $arg . '.php')) { <del> include_once(APP . 'Config' . DS . $arg . '.php'); <add> include_once APP . 'Config' . DS . $arg . '.php'; <ide> <ide> if (count($args) == 1) { <ide> return true; <ide> function debug($var = false, $showHtml = null, $showFrom = true) { <ide> <ide> if (!function_exists('sortByKey')) { <ide> <del> /** <del> * Sorts given $array by key $sortby. <del> * <del> * @param array $array Array to sort <del> * @param string $sortby Sort by this key <del> * @param string $order Sort order asc/desc (ascending or descending). <del> * @param integer $type Type of sorting to perform <del> * @return mixed Sorted array <del> * @link http://book.cakephp.org/2.0/en/core-libraries/global-constants-and-functions.html#sortByKey <del> */ <add>/** <add> * Sorts given $array by key $sortby. <add> * <add> * @param array $array Array to sort <add> * @param string $sortby Sort by this key <add> * @param string $order Sort order asc/desc (ascending or descending). <add> * @param integer $type Type of sorting to perform <add> * @return mixed Sorted array <add> * @link http://book.cakephp.org/2.0/en/core-libraries/global-constants-and-functions.html#sortByKey <add> */ <ide> function sortByKey(&$array, $sortby, $order = 'asc', $type = SORT_NUMERIC) { <ide> if (!is_array($array)) { <ide> return null; <ide> function h($text, $double = true, $charset = null) { <ide> return $texts; <ide> } elseif (is_object($text)) { <ide> if (method_exists($text, '__toString')) { <del> $text = (string) $text; <add> $text = (string)$text; <ide> } else { <ide> $text = '(object)' . get_class($text); <ide> } <ide> function convertSlash($string) { <ide> $string = str_replace('/', '_', $string); <ide> return $string; <ide> } <add> <ide><path>lib/Cake/bootstrap.php <ide> * Path to the application's directory. <ide> */ <ide> if (!defined('APP')) { <del> define('APP', ROOT . DS . APP_DIR.DS); <add> define('APP', ROOT . DS . APP_DIR . DS); <ide> } <ide> <ide> /** <ide> <ide> <ide> require CAKE . 'basics.php'; <del>require CAKE . 'Core' . DS .'App.php'; <add>require CAKE . 'Core' . DS . 'App.php'; <ide> require CAKE . 'Error' . DS . 'exceptions.php'; <ide> <ide> spl_autoload_register(array('App', 'load'));
11
Javascript
Javascript
apply suggestions from code review
4fb112e87f4884f2b83590ad53f1c2e4e0229385
<ide><path>client/src/components/Footer/index.js <ide> function Footer() { <ide> <p> <ide> Donations to freeCodeCamp go toward our education initiatives, and <ide> help pay for servers, services, and staff. You can&nbsp; <del> <Link className='inline' external='true' to='/donate'> <add> <Link className='inline' external={true} to='/donate'> <ide> make a tax-deductible donation here <ide> </Link> <ide> . <ide><path>client/src/pages/about.js <ide> const AboutPage = () => { <ide> </Link> <ide> , watch our{' '} <ide> <Link to='https://youtube.com/freecodecamp'>YouTube channel</Link> <del> , and post on <Link to='/forum'>our forum</Link>, each month we <del> help millions of people learn about coding and technology. <add> , and post on{' '} <add> <Link external={true} to='/forum'> <add> our forum <add> </Link> <add> , each month we help millions of people learn about coding and <add> technology. <ide> </p> <ide> <h4>Is freeCodeCamp a nonprofit?</h4> <ide> <p> <ide><path>client/src/pages/support.js <ide> const SupportPage = () => { <ide> privacy and security reasons, they don't have access to your <ide> account in the freeCodeCamp database. Also note that you will need <ide> to create a forum account if you don't already have one.{' '} <del> <Link to='/forum/new-topic?category=support'> <add> <Link external={true} to='/forum/new-topic?category=support'> <ide> Click here to ask your support question <ide> </Link> <ide> .
3
Ruby
Ruby
avoid hardcoded value in test setup/teardown
6a75e2ce1033669f99aed6f1f8295c138edb4d47
<ide><path>actionpack/test/dispatch/request/query_string_parsing_test.rb <ide> def test_array_parses_without_nil <ide> end <ide> <ide> test "perform_deep_munge" do <add> old_perform_deep_munge = ActionDispatch::Request::Utils.perform_deep_munge <ide> ActionDispatch::Request::Utils.perform_deep_munge = false <ide> begin <ide> assert_parses({"action" => nil}, "action") <ide> def test_array_parses_without_nil <ide> assert_parses({"action" => {"foo" => [{"bar" => nil}]}}, "action[foo][][bar]") <ide> assert_parses({"action" => ['1',nil]}, "action[]=1&action[]") <ide> ensure <del> ActionDispatch::Request::Utils.perform_deep_munge = true <add> ActionDispatch::Request::Utils.perform_deep_munge = old_perform_deep_munge <ide> end <ide> end <ide>
1
Java
Java
fix reactedittext crash
2b708560fc002c26f0b09f09cfa451827a3425ac
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactEditText.java <ide> private void setIntrinsicContentSize() { <ide> // wrapper 100% of the time. <ide> // Since the LocalData object is constructed by getting values from the underlying EditText <ide> // view, we don't need to construct one or apply it at all - it provides no use in Fabric. <del> if (!mFabricViewStateManager.hasStateWrapper()) { <del> ReactContext reactContext = getReactContext(this); <add> ReactContext reactContext = getReactContext(this); <add> <add> if (!mFabricViewStateManager.hasStateWrapper() && !reactContext.isBridgeless()) { <ide> final ReactTextInputLocalData localData = new ReactTextInputLocalData(this); <ide> UIManagerModule uiManager = reactContext.getNativeModule(UIManagerModule.class); <ide> if (uiManager != null) {
1
Java
Java
fix reactinstancemanager deadlock
df7e8c64ff8f5ff739fba2ba5ed6b0610567235e
<ide><path>ReactAndroid/src/androidTest/java/com/facebook/react/tests/core/ReactInstanceManagerTest.java <ide> @RunWith(AndroidJUnit4.class) <ide> public class ReactInstanceManagerTest { <ide> <add> private static final String TEST_MODULE = "ViewLayoutTestApp"; <add> <ide> private ReactInstanceManager mReactInstanceManager; <ide> private ReactRootView mReactRootView; <ide> <ide> public void setup() { <ide> @UiThreadTest <ide> public void testMountUnmount() { <ide> mReactInstanceManager.onHostResume(mActivityRule.getActivity()); <del> mReactRootView.startReactApplication(mReactInstanceManager, "ViewLayoutTestApp"); <add> mReactRootView.startReactApplication(mReactInstanceManager, TEST_MODULE); <ide> mReactRootView.unmountReactApplication(); <ide> } <add> <add> @Test <add> @UiThreadTest <add> public void testResume() throws InterruptedException { <add> mReactInstanceManager.onHostResume(mActivityRule.getActivity()); <add> mReactRootView.startReactApplication(mReactInstanceManager, TEST_MODULE); <add> Thread.sleep(1000); <add> mReactInstanceManager.onHostResume(mActivityRule.getActivity()); <add> } <add> <add> @Test <add> @UiThreadTest <add> public void testRecreateContext() throws InterruptedException { <add> mReactInstanceManager.onHostResume(mActivityRule.getActivity()); <add> mReactInstanceManager.createReactContextInBackground(); <add> Thread.sleep(1000); <add> mReactRootView.startReactApplication(mReactInstanceManager, TEST_MODULE); <add> } <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManager.java <ide> public void attachRootView(ReactRootView rootView) { <ide> @ThreadConfined(UI) <ide> public void detachRootView(ReactRootView rootView) { <ide> UiThreadUtil.assertOnUiThread(); <del> if (mAttachedRootViews.contains(rootView)) { <del> ReactContext currentContext = getCurrentReactContext(); <del> mAttachedRootViews.remove(rootView); <del> if (currentContext != null && currentContext.hasActiveCatalystInstance()) { <del> detachViewFromInstance(rootView, currentContext.getCatalystInstance()); <add> synchronized (mAttachedRootViews) { <add> if (mAttachedRootViews.contains(rootView)) { <add> ReactContext currentContext = getCurrentReactContext(); <add> mAttachedRootViews.remove(rootView); <add> if (currentContext != null && currentContext.hasActiveCatalystInstance()) { <add> detachViewFromInstance(rootView, currentContext.getCatalystInstance()); <add> } <ide> } <ide> } <ide> } <ide> private void recreateReactContextInBackground( <ide> private void runCreateReactContextOnNewThread(final ReactContextInitParams initParams) { <ide> Log.d(ReactConstants.TAG, "ReactInstanceManager.runCreateReactContextOnNewThread()"); <ide> UiThreadUtil.assertOnUiThread(); <del> synchronized (mReactContextLock) { <del> if (mCurrentReactContext != null) { <del> tearDownReactContext(mCurrentReactContext); <del> mCurrentReactContext = null; <add> synchronized (mAttachedRootViews) { <add> synchronized (mReactContextLock) { <add> if (mCurrentReactContext != null) { <add> tearDownReactContext(mCurrentReactContext); <add> mCurrentReactContext = null; <add> } <ide> } <ide> } <ide> <ide> private void setupReactContext(final ReactApplicationContext reactContext) { <ide> ReactMarker.logMarker(PRE_SETUP_REACT_CONTEXT_END); <ide> ReactMarker.logMarker(SETUP_REACT_CONTEXT_START); <ide> Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "setupReactContext"); <del> synchronized (mReactContextLock) { <del> mCurrentReactContext = Assertions.assertNotNull(reactContext); <add> synchronized (mAttachedRootViews) { <add> synchronized (mReactContextLock) { <add> mCurrentReactContext = Assertions.assertNotNull(reactContext); <add> } <add> <ide> CatalystInstance catalystInstance = <ide> Assertions.assertNotNull(reactContext.getCatalystInstance()); <ide> <ide> private void setupReactContext(final ReactApplicationContext reactContext) { <ide> moveReactContextToCurrentLifecycleState(); <ide> <ide> ReactMarker.logMarker(ATTACH_MEASURED_ROOT_VIEWS_START); <del> synchronized (mAttachedRootViews) { <del> for (ReactRootView rootView : mAttachedRootViews) { <del> attachRootViewToInstance(rootView); <del> } <add> for (ReactRootView rootView : mAttachedRootViews) { <add> attachRootViewToInstance(rootView); <ide> } <ide> ReactMarker.logMarker(ATTACH_MEASURED_ROOT_VIEWS_END); <ide> }
2
Text
Text
add documentation for recurrent layers
f953508bd994b13bc64c1f58df08ed7b6d20c3cf
<ide><path>docs/sources/datasets.md <ide> __Arguments:__ <ide> - test_split: float. Fraction of the dataset to be used as test data. <ide> - seed: int. Seed for reproducible data shuffling. <ide> <add>--- <add> <ide> ## IMDB Movie reviews sentiment classification <ide> <ide> `keras.datasets.imdb` <ide> __Arguments:__ <ide> - test_split: float. Fraction of the dataset to be used as test data. <ide> - seed: int. Seed for reproducible data shuffling. <ide> <add>--- <add> <ide> ## Reuters newswire topics classification <ide> <ide> `keras.datasets.reuters` <ide><path>docs/sources/layers/core.md <ide> keras.layers.core.Layer() <ide> __Methods__: <ide> <ide> ```python <del>connect(self, previous_layer) <add>connect(previous_layer) <ide> ``` <ide> <del>- Connect the input of the current layer to the output of the argument layer. <add>Connect the input of the current layer to the output of the argument layer. <ide> <del>- __Returns__: None. <add>- __Return__: None. <ide> <ide> - __Arguments__: <ide> - __previous_layer__: Layer object. <ide> <ide> <ide> <ide> ```python <del>output(self, train) <add>output(train) <ide> ``` <ide> <del>- Get the output of the layer. <add>Get the output of the layer. <ide> <del>- __Returns__: Theano tensor. <add>- __Return__: Theano tensor. <ide> <ide> - __Arguments__: <ide> - __train__: Boolean. Specifies whether output is computed in training mode or in testing mode, which can change the logic, for instance in there are any `Dropout` layers in the network. <ide> <ide> <ide> <ide> ```python <del>get_input(self, train) <add>get_input(train) <ide> ``` <ide> <del>- Get the input of the layer. <add>Get the input of the layer. <ide> <del>- __Returns__: Theano tensor. <add>- __Return__: Theano tensor. <ide> <ide> - __Arguments__: <ide> - __train__: Boolean. Specifies whether output is computed in training mode or in testing mode, which can change the logic, for instance in there are any `Dropout` layers in the network. <ide> <ide> <ide> <ide> ```python <del>get_weights(self) <add>get_weights() <ide> ``` <ide> <del>- Get the weights of the parameters of the layer. <add>Get the weights of the parameters of the layer. <ide> <del>- __Returns__: List of numpy arrays (one per layer parameter). <add>- __Return__: List of numpy arrays (one per layer parameter). <ide> <ide> <ide> <ide> ```python <del>set_weights(self, weights) <add>set_weights(weights) <ide> ``` <ide> <del>- Set the weights of the parameters of the layer. <add>Set the weights of the parameters of the layer. <ide> <ide> - __Arguments__: <ide> - __weights__: List of numpy arrays (one per layer parameter). Should be in the same order as what `get_weights(self)` returns. <ide> set_weights(self, weights) <ide> keras.layers.core.Dense(input_dim, output_dim, init='uniform', activation='linear', weights=None) <ide> ``` <ide> <del>- Standard 1D fully-connect layer. <add>Standard 1D fully-connect layer. <ide> <del>- __Input shape__: `(nb_samples, input_dim)`. <add>- __Input shape__: 2D tensor with shape: `(nb_samples, input_dim)`. <ide> <ide> - __Arguments__: <ide> <ide> keras.layers.core.Dense(input_dim, output_dim, init='uniform', activation='linea <ide> ```python <ide> keras.layers.core.Activation(activation) <ide> ``` <del>- Apply an activation function to the input. <add>Apply an activation function to the input. <ide> <ide> - __Input shape__: This layer does not assume a specific input shape. As a result, it cannot be used as the first layer in a model. <ide> <ide> keras.layers.core.Activation(activation) <ide> ```python <ide> keras.layers.core.Dropout(p) <ide> ``` <del>- Apply dropout to the input. Dropout consists in randomly setting a fraction `p` of input units to 0 at each update during training time, which helps prevent overfitting. Reference: [Dropout: A Simple Way to Prevent Neural Networks from Overfitting](http://www.cs.toronto.edu/~rsalakhu/papers/srivastava14a.pdf) <add>Apply dropout to the input. Dropout consists in randomly setting a fraction `p` of input units to 0 at each update during training time, which helps prevent overfitting. Reference: [Dropout: A Simple Way to Prevent Neural Networks from Overfitting](http://www.cs.toronto.edu/~rsalakhu/papers/srivastava14a.pdf) <ide> <ide> - __Input shape__: This layer does not assume a specific input shape. As a result, it cannot be used as the first layer in a model. <ide> <ide> keras.layers.core.Dropout(p) <ide> keras.layers.core.Reshape(*dims) <ide> ``` <ide> <del>- Reshape the input to a new shape containing the same number of units. <add>Reshape the input to a new shape containing the same number of units. <ide> <ide> - __Input shape__: This layer does not assume a specific input shape. As a result, it cannot be used as the first layer in a model. <ide> <ide> model.add(Reshape(10, 10)) # output shape: (nb_samples, 10, 10) <ide> keras.layers.core.Flatten() <ide> ``` <ide> <del>- Convert a nD input to 1D. <add>Convert a nD input to 1D. <add> <ide> - __Input shape__: (nb_samples, *). This layer cannot be used as the first layer in a model. <ide> <ide> --- <ide> keras.layers.core.Flatten() <ide> keras.layers.core.RepeatVector(n) <ide> ``` <ide> <del>- Repeat the 1D input n times. Dimensions of input are assumed to be (nb_samples, dim). Output will have the shape (nb_samples, n, dim). <add>Repeat the 1D input n times. Dimensions of input are assumed to be (nb_samples, dim). Output will have the shape (nb_samples, n, dim). <ide> <ide> - __Input shape__: This layer does not assume a specific input shape. As a result, it cannot be used as the first layer in a model. <ide> <ide><path>docs/sources/layers/recurrent.md <add> <add>## SimpleRNN <add> <add>```python <add>keras.layers.recurrent.SimpleRNN(input_dim, output_dim, <add> init='uniform', inner_init='orthogonal', activation='sigmoid', weights=None, <add> truncate_gradient=-1, return_sequences=False) <add>``` <add>Fully connected RNN where output is to fed back to input. Not a particularly useful model, included for demonstration purposes. <add> <add>- __Input shape__: 3D tensor with shape: `(nb_samples, timesteps, input_dim)`. <add> <add>- __Output shape__: <add> - if `return_sequences`: 3D tensor with shape: `(nb_samples, timesteps, ouput_dim)`. <add> - else: 2D tensor with shape: `(nb_samples, output_dim)`. <add> <add>- __Arguments__: <add> - __input_dim__: dimension of the input. <add> - __output_dim__: dimension of the internal projections and the final output. <add> - __init__: weight initialization function. Can be the name of an existing function (str), or a Theano function (see: [initializations](../initializations.md)). <add> - __activation__: activation function. Can be the name of an existing function (str), or a Theano function (see: [activations](../activations.md)). <add> - __weights__: list of numpy arrays to set as initial weights. The list should have 3 elements, of shapes: `[(input_dim, output_dim), (output_dim, output_dim), (output_dim,)]`. <add> - __truncate_gradient__: Number of steps to use in truncated BPTT. See: [Theano "scan"](http://deeplearning.net/software/theano/library/scan.html). <add> - __return_sequences__: Boolean. Whether to return the last output in the output sequence, or the full sequence. <add> <add>--- <add> <add>## SimpleDeepRNN <add> <add>```python <add>keras.layers.recurrent.SimpleDeepRNN(input_dim, output_dim, depth=3, <add> init='uniform', inner_init='orthogonal', <add> activation='sigmoid', inner_activation='hard_sigmoid', <add> weights=None, truncate_gradient=-1, return_sequences=False) <add>``` <add>Fully connected RNN where the output of multiple timesteps (up to "depth" steps in the past) is fed back to the input: <add> <add>``` <add>output = activation( W.x_t + b + inner_activation(U_1.h_tm1) + inner_activation(U_2.h_tm2) + ... ) <add>``` <add> <add>Not a particularly useful model, included for demonstration purposes. <add> <add>- __Input shape__: 3D tensor with shape: `(nb_samples, timesteps, input_dim)`. <add> <add>- __Output shape__: <add> - if `return_sequences`: 3D tensor with shape: `(nb_samples, timesteps, ouput_dim)`. <add> - else: 2D tensor with shape: `(nb_samples, output_dim)`. <add> <add>- __Arguments__: <add> - __input_dim__: dimension of the input. <add> - __output_dim__: dimension of the internal projections and the final output. <add> - __depth__: int >= 1. Lookback depth (eg. depth=1 is equivalent to SimpleRNN). <add> - __init__: weight initialization function for the output cell. Can be the name of an existing function (str), or a Theano function (see: [initializations](../initializations.md)). <add> - __inner_init__: weight initialization function for the inner cells. <add> - __activation__: activation function for the output. Can be the name of an existing function (str), or a Theano function (see: [activations](../activations.md)). <add> - __inner_activation__: activation function for the inner cells. <add> - __weights__: list of numpy arrays to set as initial weights. The list should have depth+2 elements. <add> - __truncate_gradient__: Number of steps to use in truncated BPTT. See: [Theano "scan"](http://deeplearning.net/software/theano/library/scan.html). <add> - __return_sequences__: Boolean. Whether to return the last output in the output sequence, or the full sequence. <add> <add> <add>--- <add> <add>## GRU <add> <add>```python <add>keras.layers.recurrent.GRU(input_dim, output_dim=128, <add> init='uniform', inner_init='orthogonal', <add> activation='sigmoid', inner_activation='hard_sigmoid', <add> weights=None, truncate_gradient=-1, return_sequences=False) <add>``` <add> <add>Gated Recurrent Unit - Cho et al. 2014. <add> <add>- __Input shape__: 3D tensor with shape: `(nb_samples, timesteps, input_dim)`. <add> <add>- __Output shape__: <add> - if `return_sequences`: 3D tensor with shape: `(nb_samples, timesteps, ouput_dim)`. <add> - else: 2D tensor with shape: `(nb_samples, output_dim)`. <add> <add>- __Arguments__: <add> - __input_dim__: dimension of the input. <add> - __output_dim__: dimension of the internal projections and the final output. <add> - __init__: weight initialization function for the output cell. Can be the name of an existing function (str), or a Theano function (see: [initializations](../initializations.md)). <add> - __inner_init__: weight initialization function for the inner cells. <add> - __activation__: activation function for the output. Can be the name of an existing function (str), or a Theano function (see: [activations](../activations.md)). <add> - __inner_activation__: activation function for the inner cells. <add> - __weights__: list of numpy arrays to set as initial weights. The list should have 9 elements. <add> - __truncate_gradient__: Number of steps to use in truncated BPTT. See: [Theano "scan"](http://deeplearning.net/software/theano/library/scan.html). <add> - __return_sequences__: Boolean. Whether to return the last output in the output sequence, or the full sequence. <add> <add>- __References__: <add> - [On the Properties of Neural Machine Translation: Encoder–Decoder Approaches](http://www.aclweb.org/anthology/W14-4012) <add> - [Empirical Evaluation of Gated Recurrent Neural Networks on Sequence Modeling](http://arxiv.org/pdf/1412.3555v1.pdf) <add> <add>--- <add> <add>## LSTM <add> <add>```python <add>keras.layers.recurrent.LSTM(input_dim, output_dim=128, <add> init='uniform', inner_init='orthogonal', <add> activation='tanh', inner_activation='hard_sigmoid', <add> weights=None, truncate_gradient=-1, return_sequences=False) <add>``` <add> <add>Long-Short Term Memory unit - Hochreiter 1997. <add> <add>- __Input shape__: 3D tensor with shape: `(nb_samples, timesteps, input_dim)`. <add> <add>- __Output shape__: <add> - if `return_sequences`: 3D tensor with shape: `(nb_samples, timesteps, ouput_dim)`. <add> - else: 2D tensor with shape: `(nb_samples, output_dim)`. <add> <add>- __Arguments__: <add>- __input_dim__: dimension of the input. <add> - __output_dim__: dimension of the internal projections and the final output. <add> - __init__: weight initialization function for the output cell. Can be the name of an existing function (str), or a Theano function (see: [initializations](../initializations.md)). <add> - __inner_init__: weight initialization function for the inner cells. <add> - __activation__: activation function for the output. Can be the name of an existing function (str), or a Theano function (see: [activations](../activations.md)). <add> - __inner_activation__: activation function for the inner cells. <add> - __weights__: list of numpy arrays to set as initial weights. The list should have 12 elements. <add> - __truncate_gradient__: Number of steps to use in truncated BPTT. See: [Theano "scan"](http://deeplearning.net/software/theano/library/scan.html). <add> - __return_sequences__: Boolean. Whether to return the last output in the output sequence, or the full sequence. <add> <add>- __References__: <add> - [Long short-term memory](http://deeplearning.cs.cmu.edu/pdfs/Hochreiter97_lstm.pdf) (original 1997 paper) <add> - [Learning to forget: Continual prediction with LSTM](http://www.mitpressjournals.org/doi/pdf/10.1162/089976600300015015) <add> - [Supervised sequence labelling with recurrent neural networks](http://www.cs.toronto.edu/~graves/preprint.pdf) <add> <add> <add> <ide>\ No newline at end of file
3
Ruby
Ruby
handle argumenterror from time#parse
23f8cb9f4acc83949037ce8f6c95067e9cc49629
<ide><path>Library/Homebrew/livecheck/strategy/sparkle.rb <ide> def self.item_from_content(content) <ide> version ||= (item > "version").first&.text&.strip <ide> <ide> title = (item > "title").first&.text&.strip <del> pub_date = (item > "pubDate").first&.text&.strip&.presence&.yield_self { |d| Time.parse(d) } <add> pub_date = (item > "pubDate").first&.text&.strip&.presence&.yield_self do |date_string| <add> Time.parse(date_string) <add> rescue ArgumentError <add> # Omit unparseable strings (e.g. non-English dates) <add> nil <add> end <ide> <ide> if (match = title&.match(/(\d+(?:\.\d+)*)\s*(\([^)]+\))?\Z/)) <ide> short_version ||= match[1]
1
PHP
PHP
use confirmabletrait in seeder
1f6f00ff8174e9422e45b6dc22fce4bbce715391
<ide><path>src/Illuminate/Database/Console/SeedCommand.php <ide> <?php namespace Illuminate\Database\Console; <ide> <ide> use Illuminate\Console\Command; <add>use Illuminate\Console\ConfirmableTrait; <ide> use Symfony\Component\Console\Input\InputOption; <ide> use Illuminate\Database\ConnectionResolverInterface as Resolver; <ide> <ide> class SeedCommand extends Command { <ide> <add> use ConfirmableTrait; <add> <ide> /** <ide> * The console command name. <ide> * <ide> public function __construct(Resolver $resolver) <ide> */ <ide> public function fire() <ide> { <add> if ( ! $this->confirmToProceed()) return; <add> <ide> $this->resolver->setDefaultConnection($this->getDatabase()); <ide> <ide> $this->getSeeder()->run(); <ide> protected function getOptions() <ide> array('class', null, InputOption::VALUE_OPTIONAL, 'The class name of the root seeder', 'DatabaseSeeder'), <ide> <ide> array('database', null, InputOption::VALUE_OPTIONAL, 'The database connection to seed'), <add> <add> array('force', null, InputOption::VALUE_NONE, 'Force the operation to run when in production.'), <ide> ); <ide> } <ide>
1
Javascript
Javascript
update each view benchmark
b2188911dafa60dabb6ba534acc5e044821a1bf5
<ide><path>benchmarks/runner.js <ide> function makeiframe(emberPath, suitePath, profile, callback) { <ide> <ide> write("<title>" + name + "</title>"); <ide> write("<script src='../lib/jquery-1.7.2.js'></script>"); <add> write("<script>ENV = {VIEW_PRESERVES_CONTEXT: true};</script>"); <ide> write("<script src='" + emberPath + "'></script>"); <ide> write("<script src='benchmark.js'></script>"); <ide> write("<script src='iframe_runner.js'></script>"); <ide><path>benchmarks/suites/views/each_view.js <ide> before(function() { <ide> " </thead>" + <ide> " <tbody>" + <ide> " {{#each App.list}}" + <del> ' {{#view Em.View contentBinding="this" tagName="tr"}}' + <del> " <td>{{content.id}}</td>" + <del> " <td>{{content.dateIn}}</td>" + <del> " <td>{{content.tag}}</td>" + <del> " <td>{{content.speed}}</td>" + <del> " <td>{{content.length}}</td>" + <add> ' {{#view Em.View tagName="tr"}}' + <add> " <td>{{id}}</td>" + <add> " <td>{{dateIn}}</td>" + <add> " <td>{{tag}}</td>" + <add> " <td>{{speed}}</td>" + <add> " <td>{{length}}</td>" + <ide> " {{/view}}" + <ide> " {{/each}}" + <ide> " </tbody>" +
2
Python
Python
remove forgotten kws_args
937013b35e0483ce82c1b90fb8416ab9188b1ed3
<ide><path>numpy/core/setup.py <ide> def check_func(func_name): <ide> moredefs.append(defsymbol) <ide> <ide> if sys.version[:3] < '2.4': <del> kws_args['headers'].append('stdlib.h') <ide> if check_func('strtod'): <ide> moredefs.append(('PyOS_ascii_strtod', 'strtod')) <ide>
1
Python
Python
add test for gcstaskhandler
1ae5bdf23e3ac7cca05325ef8b255a7cf067e18e
<ide><path>airflow/providers/google/cloud/log/gcs_task_handler.py <ide> def gcs_read(self, remote_log_location): <ide> bkt, blob = self.parse_gcs_url(remote_log_location) <ide> return self.hook.download(bkt, blob).decode('utf-8') <ide> <del> def gcs_write(self, log, remote_log_location, append=True): <add> def gcs_write(self, log, remote_log_location): <ide> """ <ide> Writes the log to the remote_log_location. Fails silently if no hook <ide> was created. <ide> def gcs_write(self, log, remote_log_location, append=True): <ide> :type log: str <ide> :param remote_log_location: the log's location in remote storage <ide> :type remote_log_location: str (path) <del> :param append: if False, any existing log file is overwritten. If True, <del> the new log is appended to any existing logs. <del> :type append: bool <ide> """ <del> if append: <del> try: <del> old_log = self.gcs_read(remote_log_location) <del> log = '\n'.join([old_log, log]) if old_log else log <del> except Exception as e: # pylint: disable=broad-except <del> if not hasattr(e, 'resp') or e.resp.get('status') != '404': # pylint: disable=no-member <del> log = '*** Previous log discarded: {}\n\n'.format(str(e)) + log <add> try: <add> old_log = self.gcs_read(remote_log_location) <add> log = '\n'.join([old_log, log]) if old_log else log <add> except Exception as e: # pylint: disable=broad-except <add> if not hasattr(e, 'resp') or e.resp.get('status') != '404': # pylint: disable=no-member <add> log = '*** Previous log discarded: {}\n\n'.format(str(e)) + log <ide> <ide> try: <ide> bkt, blob = self.parse_gcs_url(remote_log_location) <del> from tempfile import NamedTemporaryFile <del> with NamedTemporaryFile(mode='w+') as tmpfile: <del> tmpfile.write(log) <del> # Force the file to be flushed, since we're doing the <del> # upload from within the file context (it hasn't been <del> # closed). <del> tmpfile.flush() <del> self.hook.upload(bkt, blob, tmpfile.name) <add> self.hook.upload(bkt, blob, data=log) <ide> except Exception as e: # pylint: disable=broad-except <ide> self.log.error('Could not write logs to %s: %s', remote_log_location, e) <ide> <ide><path>tests/providers/google/cloud/log/test_gcs_task_handler.py <add># Licensed to the Apache Software Foundation (ASF) under one <add># or more contributor license agreements. See the NOTICE file <add># distributed with this work for additional information <add># regarding copyright ownership. The ASF licenses this file <add># to you under the Apache License, Version 2.0 (the <add># "License"); you may not use this file except in compliance <add># with the License. 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, <add># software distributed under the License is distributed on an <add># "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY <add># KIND, either express or implied. See the License for the <add># specific language governing permissions and limitations <add># under the License. <add>import logging <add>import shutil <add>import tempfile <add>import unittest <add>from datetime import datetime <add>from unittest import mock <add> <add>from airflow.models import TaskInstance <add>from airflow.models.dag import DAG <add>from airflow.operators.dummy_operator import DummyOperator <add>from airflow.providers.google.cloud.hooks.gcs import GCSHook <add>from airflow.providers.google.cloud.log.gcs_task_handler import GCSTaskHandler <add>from airflow.utils.state import State <add>from tests.test_utils.config import conf_vars <add>from tests.test_utils.db import clear_db_runs <add> <add> <add>class TestGCSTaskHandler(unittest.TestCase): <add> def setUp(self) -> None: <add> date = datetime(2020, 1, 1) <add> self.gcs_log_folder = "test" <add> self.logger = logging.getLogger("logger") <add> self.dag = DAG("dag_for_testing_task_handler", start_date=date) <add> task = DummyOperator(task_id="task_for_testing_gcs_task_handler") <add> self.ti = TaskInstance(task=task, execution_date=date) <add> self.ti.try_number = 1 <add> self.ti.state = State.RUNNING <add> self.remote_log_base = "gs://bucket/remote/log/location" <add> self.remote_log_location = "gs://my-bucket/path/to/1.log" <add> self.local_log_location = tempfile.mkdtemp() <add> self.filename_template = "{try_number}.log" <add> self.addCleanup(self.dag.clear) <add> self.gcs_task_handler = GCSTaskHandler( <add> self.local_log_location, self.remote_log_base, self.filename_template <add> ) <add> <add> def tearDown(self) -> None: <add> clear_db_runs() <add> shutil.rmtree(self.local_log_location, ignore_errors=True) <add> <add> def test_hook(self): <add> self.assertIsInstance(self.gcs_task_handler.hook, GCSHook) <add> <add> @conf_vars({("logging", "remote_log_conn_id"): "gcs_default"}) <add> @mock.patch("airflow.providers.google.cloud.hooks.gcs.GCSHook") <add> def test_hook_raises(self, mock_hook): <add> mock_hook.side_effect = Exception("Failed to connect") <add> <add> with self.assertLogs(self.gcs_task_handler.log) as cm: <add> self.gcs_task_handler.hook <add> <add> self.assertEqual( <add> cm.output, <add> ['ERROR:airflow.providers.google.cloud.log.gcs_task_handler.GCSTaskHandler:Could ' <add> 'not create a GoogleCloudStorageHook with connection id "gcs_default". Failed ' <add> 'to connect\n' <add> '\n' <add> 'Please make sure that airflow[gcp] is installed and the GCS connection ' <add> 'exists.'] <add> ) <add> <add> @conf_vars({("logging", "remote_log_conn_id"): "gcs_default"}) <add> @mock.patch("airflow.providers.google.cloud.hooks.gcs.GCSHook") <add> def test_should_read_logs_from_remote(self, mock_hook): <add> mock_hook.return_value.download.return_value = b"CONTENT" <add> <add> logs, metadata = self.gcs_task_handler._read(self.ti, self.ti.try_number) <add> <add> mock_hook.return_value.download.assert_called_once_with('bucket', 'remote/log/location/1.log') <add> self.assertEqual( <add> '*** Reading remote log from gs://bucket/remote/log/location/1.log.\nCONTENT\n', logs) <add> self.assertEqual({'end_of_log': True}, metadata) <add> <add> @mock.patch("airflow.providers.google.cloud.hooks.gcs.GCSHook") <add> def test_should_read_from_local(self, mock_hook): <add> mock_hook.return_value.download.side_effect = Exception("Failed to connect") <add> <add> self.gcs_task_handler.set_context(self.ti) <add> return_val = self.gcs_task_handler._read(self.ti, self.ti.try_number) <add> <add> self.assertEqual(len(return_val), 2) <add> self.assertEqual( <add> return_val[0], <add> "*** Unable to read remote log from gs://bucket/remote/log/location/1.log\n*** " <add> f"Failed to connect\n\n*** Reading local file: {self.local_log_location}/1.log\n", <add> ) <add> self.assertDictEqual(return_val[1], {"end_of_log": True}) <add> mock_hook.return_value.download.assert_called_once() <add> <add> @mock.patch("airflow.providers.google.cloud.hooks.gcs.GCSHook") <add> def test_write_to_remote_on_close(self, mock_hook): <add> mock_hook.return_value.download.return_value = b"CONTENT" <add> <add> self.gcs_task_handler.set_context(self.ti) <add> self.gcs_task_handler.emit(logging.LogRecord( <add> name="NAME", level="DEBUG", pathname=None, lineno=None, <add> msg="MESSAGE", args=None, exc_info=None <add> )) <add> self.gcs_task_handler.close() <add> <add> mock_hook.return_value.download.assert_called_once_with('bucket', 'remote/log/location/1.log') <add> mock_hook.return_value.upload.assert_called_once_with( <add> 'bucket', 'remote/log/location/1.log', data='CONTENT\nMESSAGE\n' <add> ) <add> self.assertEqual(self.gcs_task_handler.closed, True) <add> <add> @mock.patch("airflow.providers.google.cloud.hooks.gcs.GCSHook") <add> def test_failed_write_to_remote_on_close(self, mock_hook): <add> mock_hook.return_value.upload.side_effect = Exception("Failed to connect") <add> mock_hook.return_value.download.return_value = b"Old log" <add> <add> self.gcs_task_handler.set_context(self.ti) <add> with self.assertLogs(self.gcs_task_handler.log) as cm: <add> self.gcs_task_handler.close() <add> <add> self.assertEqual( <add> cm.output, <add> [ <add> 'ERROR:airflow.providers.google.cloud.log.gcs_task_handler.GCSTaskHandler:Could ' <add> 'not write logs to gs://bucket/remote/log/location/1.log: Failed to connect' <add> ] <add> ) <add> mock_hook.return_value.download.assert_called_once_with( <add> 'bucket', 'remote/log/location/1.log' <add> ) <add> mock_hook.return_value.upload.assert_called_once_with( <add> 'bucket', 'remote/log/location/1.log', data='Old log\n' <add> ) <add> <add> @mock.patch("airflow.providers.google.cloud.hooks.gcs.GCSHook") <add> def test_write_to_remote_on_close_failed_read_old_logs(self, mock_hook): <add> mock_hook.return_value.download.side_effect = Exception("Fail to download") <add> <add> self.gcs_task_handler.set_context(self.ti) <add> self.gcs_task_handler.emit(logging.LogRecord( <add> name="NAME", level="DEBUG", pathname=None, lineno=None, <add> msg="MESSAGE", args=None, exc_info=None <add> )) <add> self.gcs_task_handler.close() <add> <add> mock_hook.return_value.download.assert_called_once_with('bucket', 'remote/log/location/1.log') <add> mock_hook.return_value.upload.assert_called_once_with( <add> 'bucket', 'remote/log/location/1.log', <add> data='*** Previous log discarded: Fail to download\n\nMESSAGE\n' <add> ) <add> self.assertEqual(self.gcs_task_handler.closed, True) <ide><path>tests/providers/google/cloud/log/test_gcs_task_handler_system.py <add># Licensed to the Apache Software Foundation (ASF) under one <add># or more contributor license agreements. See the NOTICE file <add># distributed with this work for additional information <add># regarding copyright ownership. The ASF licenses this file <add># to you under the Apache License, Version 2.0 (the <add># "License"); you may not use this file except in compliance <add># with the License. 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, <add># software distributed under the License is distributed on an <add># "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY <add># KIND, either express or implied. See the License for the <add># specific language governing permissions and limitations <add># under the License. <add>import importlib <add>import random <add>import string <add>import subprocess <add>from unittest import mock <add> <add>import pytest <add> <add>from airflow import settings <add>from airflow.example_dags import example_complex <add>from airflow.models import DagBag, TaskInstance <add>from airflow.utils.log.log_reader import TaskLogReader <add>from airflow.utils.session import provide_session <add>from tests.providers.google.cloud.utils.gcp_authenticator import GCP_GCS_KEY <add>from tests.test_utils.config import conf_vars <add>from tests.test_utils.db import clear_db_connections, clear_db_runs <add>from tests.test_utils.gcp_system_helpers import ( <add> GoogleSystemTest, provide_gcp_context, resolve_full_gcp_key_path, <add>) <add> <add> <add>@pytest.mark.system("google") <add>@pytest.mark.credential_file(GCP_GCS_KEY) <add>class TestGCSTaskHandlerSystemTest(GoogleSystemTest): <add> <add> @classmethod <add> def setUpClass(cls) -> None: <add> unique_suffix = ''.join(random.sample(string.ascii_lowercase, 16)) <add> cls.bucket_name = f"airflow-gcs-task-handler-tests-{unique_suffix}" # type: ignore <add> cls.create_gcs_bucket(cls.bucket_name) # type: ignore <add> clear_db_connections() <add> <add> @classmethod <add> def tearDownClass(cls) -> None: <add> cls.delete_gcs_bucket(cls.bucket_name) # type: ignore <add> <add> def setUp(self) -> None: <add> clear_db_runs() <add> <add> def tearDown(self) -> None: <add> from airflow.config_templates import airflow_local_settings <add> importlib.reload(airflow_local_settings) <add> settings.configure_logging() <add> clear_db_runs() <add> <add> @provide_session <add> def test_should_read_logs(self, session): <add> with mock.patch.dict( <add> 'os.environ', <add> AIRFLOW__LOGGING__REMOTE_LOGGING="true", <add> AIRFLOW__LOGGING__REMOTE_BASE_LOG_FOLDER=f"gs://{self.bucket_name}/path/to/logs", <add> AIRFLOW__LOGGING__REMOTE_LOG_CONN_ID="google_cloud_default", <add> AIRFLOW__CORE__LOAD_EXAMPLES="false", <add> AIRFLOW__CORE__DAGS_FOLDER=example_complex.__file__, <add> GOOGLE_APPLICATION_CREDENTIALS=resolve_full_gcp_key_path(GCP_GCS_KEY) <add> ): <add> self.assertEqual(0, subprocess.Popen( <add> ["airflow", "dags", "trigger", "example_complex"] <add> ).wait()) <add> self.assertEqual(0, subprocess.Popen( <add> ["airflow", "scheduler", "--num-runs", "1"] <add> ).wait()) <add> <add> ti = session.query(TaskInstance).filter(TaskInstance.task_id == "create_entry_group").first() <add> dag = DagBag(dag_folder=example_complex.__file__).dags['example_complex'] <add> task = dag.task_dict["create_entry_group"] <add> ti.task = task <add> self.assert_remote_logs("INFO - Task exited with return code 0", ti) <add> <add> def assert_remote_logs(self, expected_message, ti): <add> with provide_gcp_context(GCP_GCS_KEY), conf_vars({ <add> ('logging', 'remote_logging'): 'True', <add> ('logging', 'remote_base_log_folder'): f"gs://{self.bucket_name}/path/to/logs", <add> ('logging', 'remote_log_conn_id'): "google_cloud_default", <add> }): <add> from airflow.config_templates import airflow_local_settings <add> importlib.reload(airflow_local_settings) <add> settings.configure_logging() <add> <add> task_log_reader = TaskLogReader() <add> logs = "\n".join(task_log_reader.read_log_stream(ti, try_number=None, metadata={})) <add> self.assertIn(expected_message, logs) <ide><path>tests/test_project_structure.py <ide> ) <ide> <ide> MISSING_TEST_FILES = { <del> 'tests/providers/google/cloud/log/test_gcs_task_handler.py', <del> 'tests/providers/microsoft/azure/sensors/test_azure_cosmos.py' <add> 'tests/providers/microsoft/azure/sensors/test_azure_cosmos.py', <ide> } <ide> <ide>
4
Java
Java
fix imageeditingmanager when no external cache
fffcb9c88a9aec69125b138cb540d9dc8d7846c8
<ide><path>ReactAndroid/src/main/java/com/facebook/react/modules/camera/ImageEditingManager.java <ide> private static File createTempFile(Context context, @Nullable String mimeType) <ide> File externalCacheDir = context.getExternalCacheDir(); <ide> File internalCacheDir = context.getCacheDir(); <ide> File cacheDir; <del> if (externalCacheDir == null && externalCacheDir == null) { <add> if (externalCacheDir == null && internalCacheDir == null) { <ide> throw new IOException("No cache directory available"); <ide> } <ide> if (externalCacheDir == null) {
1
Javascript
Javascript
remove the `shadowviewer` used with page scrolling
c18df2c61f4dbcf786a8feacc1c67af13433cf38
<ide><path>web/base_viewer.js <ide> function isSameScale(oldScale, newScale) { <ide> * Simple viewer control to display PDF content/pages. <ide> */ <ide> class BaseViewer { <add> #scrollModePageState = null; <add> <ide> /** <ide> * @param {PDFViewerOptions} options <ide> */ <ide> class BaseViewer { <ide> this._optionalContentConfigPromise = optionalContentConfigPromise; <ide> <ide> const viewerElement = <del> this._scrollMode === ScrollMode.PAGE <del> ? this._scrollModePageState.shadowViewer <del> : this.viewer; <add> this._scrollMode === ScrollMode.PAGE ? null : this.viewer; <ide> const scale = this.currentScale; <ide> const viewport = firstPdfPage.getViewport({ <ide> scale: scale * PixelsPerInch.PDF_TO_CSS_UNITS, <ide> class BaseViewer { <ide> this._previousScrollMode = ScrollMode.UNKNOWN; <ide> this._spreadMode = SpreadMode.NONE; <ide> <del> this._scrollModePageState = { <del> shadowViewer: document.createDocumentFragment(), <add> this.#scrollModePageState = { <ide> previousPageNumber: 1, <ide> scrollDown: true, <ide> pages: [], <ide> class BaseViewer { <ide> throw new Error("_ensurePageViewVisible: Invalid scrollMode value."); <ide> } <ide> const pageNumber = this._currentPageNumber, <del> state = this._scrollModePageState, <add> state = this.#scrollModePageState, <ide> viewer = this.viewer; <ide> <del> // Remove the currently active pages, if any, from the viewer. <del> if (viewer.hasChildNodes()) { <del> // Temporarily remove all the pages from the DOM. <del> viewer.textContent = ""; <del> <del> for (const pageView of this._pages) { <del> state.shadowViewer.appendChild(pageView.div); <del> } <del> } <add> // Temporarily remove all the pages from the DOM... <add> viewer.textContent = ""; <add> // ... and clear out the active ones. <ide> state.pages.length = 0; <ide> <ide> if (this._spreadMode === SpreadMode.NONE) { <ide> class BaseViewer { <ide> } <ide> const views = <ide> this._scrollMode === ScrollMode.PAGE <del> ? this._scrollModePageState.pages <add> ? this.#scrollModePageState.pages <ide> : this._pages, <ide> horizontal = this._scrollMode === ScrollMode.HORIZONTAL, <ide> rtl = horizontal && this._isContainerRtl; <ide> class BaseViewer { <ide> } <ide> switch (this._scrollMode) { <ide> case ScrollMode.PAGE: <del> return this._scrollModePageState.scrollDown; <add> return this.#scrollModePageState.scrollDown; <ide> case ScrollMode.HORIZONTAL: <ide> return this.scroll.right; <ide> } <ide><path>web/pdf_page_view.js <ide> import { RenderingStates } from "./pdf_rendering_queue.js"; <ide> <ide> /** <ide> * @typedef {Object} PDFPageViewOptions <del> * @property {HTMLDivElement} container - The viewer element. <add> * @property {HTMLDivElement} [container] - The viewer element. <ide> * @property {EventBus} eventBus - The application event bus. <ide> * @property {number} id - The page unique ID (normally its number). <ide> * @property {number} scale - The page scale display. <ide> class PDFPageView { <ide> }); <ide> this.div = div; <ide> <del> container.appendChild(div); <add> container?.appendChild(div); <ide> } <ide> <ide> setPdfPage(pdfPage) {
2
PHP
PHP
implement array access
eb3c9e25a5bc2a96777e5e643ce0f612e4a544d9
<ide><path>src/Illuminate/Testing/AssertableJsonString.php <ide> <ide> namespace Illuminate\Testing; <ide> <add>use ArrayAccess; <ide> use Illuminate\Contracts\Support\Jsonable; <ide> use Illuminate\Support\Arr; <ide> use Illuminate\Support\Str; <ide> use Illuminate\Testing\Assert as PHPUnit; <ide> use JsonSerializable; <ide> <del>class AssertableJsonString <add>class AssertableJsonString implements ArrayAccess <ide> { <ide> /** <ide> * The original encoded json. <ide> protected function jsonSearchStrings($key, $value) <ide> $needle.',', <ide> ]; <ide> } <add> <add> /** <add> * Determine whether an offset exists. <add> * <add> * @param mixed $offset <add> * @return bool <add> */ <add> public function offsetExists($offset) <add> { <add> return isset($this->decoded[$offset]); <add> } <add> <add> /** <add> * Get the value at the given offset. <add> * <add> * @param string $offset <add> * @return mixed <add> */ <add> public function offsetGet($offset) <add> { <add> return $this->decoded[$offset]; <add> } <add> <add> /** <add> * Set the value at the given offset. <add> * <add> * @param string $offset <add> * @param mixed $value <add> * @return void <add> */ <add> public function offsetSet($offset, $value) <add> { <add> $this->decoded[$offset] = $value; <add> } <add> <add> /** <add> * Unset the value at the given offset. <add> * <add> * @param string $offset <add> * @return void <add> */ <add> public function offsetUnset($offset) <add> { <add> unset($this->decoded[$offset]); <add> } <ide> }
1
Go
Go
run build tests in tmpdir
be924087eb5a2ab0ad79c069782e82805dd31d58
<ide><path>integration-cli/docker_cli_build_test.go <ide> func TestBuildSixtySteps(t *testing.T) { <ide> } <ide> <ide> func TestAddSingleFileToRoot(t *testing.T) { <del> buildDirectory := filepath.Join(workingDirectory, "build_tests", "TestAdd", "SingleFileToRoot") <add> testDirName := "SingleFileToRoot" <add> sourceDirectory := filepath.Join(workingDirectory, "build_tests", "TestAdd", testDirName) <add> buildDirectory, err := ioutil.TempDir("", "test-build-add") <add> defer os.RemoveAll(buildDirectory) <add> <add> err = copyWithCP(sourceDirectory, buildDirectory) <add> if err != nil { <add> t.Fatalf("failed to copy files to temporary directory: %s", err) <add> } <add> <add> buildDirectory = filepath.Join(buildDirectory, testDirName) <ide> f, err := os.OpenFile(filepath.Join(buildDirectory, "test_file"), os.O_CREATE, 0644) <ide> if err != nil { <ide> t.Fatal(err) <ide> func TestAddSingleFileToRoot(t *testing.T) { <ide> <ide> // Issue #3960: "ADD src ." hangs <ide> func TestAddSingleFileToWorkdir(t *testing.T) { <del> buildDirectory := filepath.Join(workingDirectory, "build_tests", "TestAdd", "SingleFileToWorkdir") <add> testDirName := "SingleFileToWorkdir" <add> sourceDirectory := filepath.Join(workingDirectory, "build_tests", "TestAdd", testDirName) <add> buildDirectory, err := ioutil.TempDir("", "test-build-add") <add> defer os.RemoveAll(buildDirectory) <add> <add> err = copyWithCP(sourceDirectory, buildDirectory) <add> if err != nil { <add> t.Fatalf("failed to copy files to temporary directory: %s", err) <add> } <add> <add> buildDirectory = filepath.Join(buildDirectory, testDirName) <ide> f, err := os.OpenFile(filepath.Join(buildDirectory, "test_file"), os.O_CREATE, 0644) <ide> if err != nil { <ide> t.Fatal(err) <ide> func TestAddDirContentToExistDir(t *testing.T) { <ide> } <ide> <ide> func TestAddWholeDirToRoot(t *testing.T) { <del> buildDirectory := filepath.Join(workingDirectory, "build_tests", "TestAdd", "WholeDirToRoot") <add> testDirName := "WholeDirToRoot" <add> sourceDirectory := filepath.Join(workingDirectory, "build_tests", "TestAdd", testDirName) <add> buildDirectory, err := ioutil.TempDir("", "test-build-add") <add> defer os.RemoveAll(buildDirectory) <add> <add> err = copyWithCP(sourceDirectory, buildDirectory) <add> if err != nil { <add> t.Fatalf("failed to copy files to temporary directory: %s", err) <add> } <add> <add> buildDirectory = filepath.Join(buildDirectory, testDirName) <ide> test_dir := filepath.Join(buildDirectory, "test_dir") <ide> if err := os.MkdirAll(test_dir, 0755); err != nil { <ide> t.Fatal(err) <ide> func TestAddEtcToRoot(t *testing.T) { <ide> } <ide> <ide> func TestCopySingleFileToRoot(t *testing.T) { <del> buildDirectory := filepath.Join(workingDirectory, "build_tests", "TestCopy", "SingleFileToRoot") <add> testDirName := "SingleFileToRoot" <add> sourceDirectory := filepath.Join(workingDirectory, "build_tests", "TestCopy", testDirName) <add> buildDirectory, err := ioutil.TempDir("", "test-build-add") <add> defer os.RemoveAll(buildDirectory) <add> <add> err = copyWithCP(sourceDirectory, buildDirectory) <add> if err != nil { <add> t.Fatalf("failed to copy files to temporary directory: %s", err) <add> } <add> <add> buildDirectory = filepath.Join(buildDirectory, testDirName) <ide> f, err := os.OpenFile(filepath.Join(buildDirectory, "test_file"), os.O_CREATE, 0644) <ide> if err != nil { <ide> t.Fatal(err) <ide> func TestCopySingleFileToRoot(t *testing.T) { <ide> <ide> // Issue #3960: "ADD src ." hangs - adapted for COPY <ide> func TestCopySingleFileToWorkdir(t *testing.T) { <del> buildDirectory := filepath.Join(workingDirectory, "build_tests", "TestCopy", "SingleFileToWorkdir") <add> testDirName := "SingleFileToWorkdir" <add> sourceDirectory := filepath.Join(workingDirectory, "build_tests", "TestCopy", testDirName) <add> buildDirectory, err := ioutil.TempDir("", "test-build-add") <add> defer os.RemoveAll(buildDirectory) <add> <add> err = copyWithCP(sourceDirectory, buildDirectory) <add> if err != nil { <add> t.Fatalf("failed to copy files to temporary directory: %s", err) <add> } <add> <add> buildDirectory = filepath.Join(buildDirectory, testDirName) <ide> f, err := os.OpenFile(filepath.Join(buildDirectory, "test_file"), os.O_CREATE, 0644) <ide> if err != nil { <ide> t.Fatal(err) <ide> func TestCopyDirContentToExistDir(t *testing.T) { <ide> } <ide> <ide> func TestCopyWholeDirToRoot(t *testing.T) { <del> buildDirectory := filepath.Join(workingDirectory, "build_tests", "TestCopy", "WholeDirToRoot") <add> testDirName := "WholeDirToRoot" <add> sourceDirectory := filepath.Join(workingDirectory, "build_tests", "TestCopy", testDirName) <add> buildDirectory, err := ioutil.TempDir("", "test-build-add") <add> defer os.RemoveAll(buildDirectory) <add> <add> err = copyWithCP(sourceDirectory, buildDirectory) <add> if err != nil { <add> t.Fatalf("failed to copy files to temporary directory: %s", err) <add> } <add> <add> buildDirectory = filepath.Join(buildDirectory, testDirName) <ide> test_dir := filepath.Join(buildDirectory, "test_dir") <ide> if err := os.MkdirAll(test_dir, 0755); err != nil { <ide> t.Fatal(err) <ide> func TestCopyDisallowRemote(t *testing.T) { <ide> // Issue #5270 - ensure we throw a better error than "unexpected EOF" <ide> // when we can't access files in the context. <ide> func TestBuildWithInaccessibleFilesInContext(t *testing.T) { <del> buildDirectory := filepath.Join(workingDirectory, "build_tests", "TestBuildWithInaccessibleFilesInContext") <add> testDirName := "TestBuildWithInaccessibleFilesInContext" <add> <add> sourceDirectory := filepath.Join(workingDirectory, "build_tests", testDirName) <add> buildDirectory, err := ioutil.TempDir("", "test-build-inaccessible-directory") <add> defer os.RemoveAll(buildDirectory) <add> <add> err = copyWithCP(sourceDirectory, buildDirectory) <add> if err != nil { <add> t.Fatalf("failed to copy files to temporary directory: %s", err) <add> } <ide> <add> buildDirectory = filepath.Join(buildDirectory, testDirName) <ide> { <ide> // This is used to ensure we detect inaccessible files early during build in the cli client <ide> pathToInaccessibleFileBuildDirectory := filepath.Join(buildDirectory, "inaccessiblefile") <ide><path>integration-cli/utils.go <ide> func fileServer(files map[string]string) (*FileServer, error) { <ide> Server: server, <ide> }, nil <ide> } <add> <add>func copyWithCP(source, target string) error { <add> copyCmd := exec.Command("cp", "-rp", source, target) <add> out, exitCode, err := runCommandWithOutput(copyCmd) <add> if err != nil || exitCode != 0 { <add> return fmt.Errorf("failed to copy: error: %q ,output: %q", err, out) <add> } <add> return nil <add>}
2
Ruby
Ruby
restore printing of statistics
dd1830e1e3b67e53d2e3a9e67fd1a5e613579262
<ide><path>Library/Homebrew/cmd/info.rb <ide> def info <ide> raise FormulaOrCaskUnspecifiedError if args.no_named? <ide> <ide> exec_browser(*args.named.to_formulae_and_casks.map { |f| github_info(f) }) <add> elsif args.no_named? <add> print_statistics <ide> else <ide> print_info(args: args) <ide> end <ide> end <ide> <add> def print_statistics <add> return unless HOMEBREW_CELLAR.exist? <add> <add> count = Formula.racks.length <add> puts "#{count} #{"keg".pluralize(count)}, #{HOMEBREW_CELLAR.dup.abv}" <add> end <add> <ide> def print_analytics(args:) <ide> if args.no_named? <del> if args.analytics? <del> Utils::Analytics.output(args: args) <del> elsif HOMEBREW_CELLAR.exist? <del> count = Formula.racks.length <del> puts "#{count} #{"keg".pluralize(count)}, #{HOMEBREW_CELLAR.dup.abv}" <del> end <del> <add> Utils::Analytics.output(args: args) <ide> return <ide> end <ide>
1
Go
Go
fix empty-lines (revive)
f63dea43378506ba653545ee06f0da422f160ad9
<ide><path>cmd/dockerd/daemon.go <ide> func newRouterOptions(config *config.Config, d *daemon.Daemon) (routerOptions, e <ide> <ide> func (cli *DaemonCli) reloadConfig() { <ide> reload := func(c *config.Config) { <del> <ide> // Revalidate and reload the authorization plugins <ide> if err := validateAuthzPlugins(c.AuthorizationPlugins, cli.d.PluginStore); err != nil { <ide> logrus.Fatalf("Error validating authorization plugin: %v", err) <ide><path>cmd/dockerd/trap/trap_linux_test.go <ide> func TestTrap(t *testing.T) { <ide> } <ide> }) <ide> } <del> <ide> }
2
Go
Go
fix crash if the len was < maxsetstringlen
1f55734d4c2021067790dc1ab895deb50e562154
<ide><path>libnetwork/service_common.go <ide> func (c *controller) addServiceBinding(svcName, svcID, nID, eID, containerName s <ide> ok, entries := s.assignIPToEndpoint(ip.String(), eID) <ide> if !ok || entries > 1 { <ide> setStr, b := s.printIPToEndpoint(ip.String()) <del> logrus.Warnf("addServiceBinding %s possible transient state ok:%t entries:%d set:%t %s", eID, ok, entries, b, setStr[:maxSetStringLen]) <add> if len(setStr) > maxSetStringLen { <add> setStr = setStr[:maxSetStringLen] <add> } <add> logrus.Warnf("addServiceBinding %s possible transient state ok:%t entries:%d set:%t %s", eID, ok, entries, b, setStr) <ide> } <ide> <ide> // Add loadbalancer service and backend in all sandboxes in <ide> func (c *controller) rmServiceBinding(svcName, svcID, nID, eID, containerName st <ide> ok, entries := s.removeIPToEndpoint(ip.String(), eID) <ide> if !ok || entries > 0 { <ide> setStr, b := s.printIPToEndpoint(ip.String()) <del> logrus.Warnf("rmServiceBinding %s possible transient state ok:%t entries:%d set:%t %s", eID, ok, entries, b, setStr[:maxSetStringLen]) <add> if len(setStr) > maxSetStringLen { <add> setStr = setStr[:maxSetStringLen] <add> } <add> logrus.Warnf("rmServiceBinding %s possible transient state ok:%t entries:%d set:%t %s", eID, ok, entries, b, setStr) <ide> } <ide> <ide> // Remove loadbalancer service(if needed) and backend in all
1
Text
Text
remove trailing dot
5bda9b8a8ee46ba38fd006d8addad5ce918e1890
<ide><path>docs/your-first-package.md <ide> module.exports = <ide> <ide> convert: -> <ide> # This assumes the active pane item is an editor <del> editor = atom.workspace.activePaneItem. <add> editor = atom.workspace.activePaneItem <ide> selection = editor.getSelection() <ide> upperCaseSelectedText = selection.getText().toUpperCase() <ide> selection.insertText(upperCaseSelectedText)
1
Javascript
Javascript
fix function names in pdfthumbnailviewer
dfa993d13d03d71dc645c96ffafbbacbe31144c1
<ide><path>web/pdf_thumbnail_viewer.js <ide> var THUMBNAIL_SCROLL_MARGIN = -19; <ide> <ide> /** <ide> * @typedef {Object} PDFThumbnailViewerOptions <del> * @property {HTMLDivElement} container - The container for the thumbs elements. <add> * @property {HTMLDivElement} container - The container for the thumbnail <add> * elements. <ide> * @property {IPDFLinkService} linkService - The navigation/linking service. <ide> * @property {PDFRenderingQueue} renderingQueue - The rendering queue object. <ide> */ <ide> <ide> /** <del> * Simple viewer control to display thumbs for pages. <add> * Simple viewer control to display thumbnails for pages. <ide> * @class <add> * @implements {IRenderableView} <ide> */ <del>var PDFThumbnailViewer = (function pdfThumbnailViewer() { <add>var PDFThumbnailViewer = (function PDFThumbnailViewerClosure() { <ide> /** <del> * @constructs <add> * @constructs PDFThumbnailViewer <ide> * @param {PDFThumbnailViewerOptions} options <ide> */ <ide> function PDFThumbnailViewer(options) { <ide> var PDFThumbnailViewer = (function pdfThumbnailViewer() { <ide> } <ide> <ide> PDFThumbnailViewer.prototype = { <add> /** <add> * @private <add> */ <ide> _scrollUpdated: function PDFThumbnailViewer_scrollUpdated() { <ide> this.renderingQueue.renderHighestPriority(); <ide> }, <ide> var PDFThumbnailViewer = (function pdfThumbnailViewer() { <ide> return this.thumbnails[index]; <ide> }, <ide> <add> /** <add> * @private <add> */ <ide> _getVisibleThumbs: function PDFThumbnailViewer_getVisibleThumbs() { <ide> return getVisibleElements(this.container, this.thumbnails); <ide> }, <ide> <del> scrollThumbnailIntoView: function (page) { <add> scrollThumbnailIntoView: <add> function PDFThumbnailViewer_scrollThumbnailIntoView(page) { <ide> var selected = document.querySelector('.thumbnail.selected'); <ide> if (selected) { <ide> selected.classList.remove('selected'); <ide> var PDFThumbnailViewer = (function pdfThumbnailViewer() { <ide> ThumbnailView.tempImageCache = null; <ide> }, <ide> <del> _resetView: function () { <add> /** <add> * @private <add> */ <add> _resetView: function PDFThumbnailViewer_resetView() { <ide> this.thumbnails = []; <ide> this._pagesRotation = 0; <ide> this._pagesRequests = []; <ide> }, <ide> <del> setDocument: function (pdfDocument) { <add> setDocument: function PDFThumbnailViewer_setDocument(pdfDocument) { <ide> if (this.pdfDocument) { <ide> // cleanup of the elements and views <ide> var thumbsView = this.container; <ide> var PDFThumbnailViewer = (function pdfThumbnailViewer() { <ide> * @returns {PDFPage} <ide> * @private <ide> */ <del> _ensurePdfPageLoaded: function (thumbView) { <add> _ensurePdfPageLoaded: <add> function PDFThumbnailViewer_ensurePdfPageLoaded(thumbView) { <ide> if (thumbView.pdfPage) { <ide> return Promise.resolve(thumbView.pdfPage); <ide> }
1
Text
Text
update the list of plugins and loaders in readme
f715cf52f9cacbcb93e04a120a9401154dc6b752
<ide><path>README.md <ide> within webpack itself use this plugin interface. This makes webpack very <ide> | [mini-css-extract-plugin][mini-css] | ![mini-css-npm] | ![mini-css-size] | Extracts CSS into separate files. It creates a CSS file per JS file which contains CSS. | <ide> | [compression-webpack-plugin][compression] | ![compression-npm] | ![compression-size] | Prepares compressed versions of assets to serve them with Content-Encoding | <ide> | [html-webpack-plugin][html-plugin] | ![html-plugin-npm] | ![html-plugin-size] | Simplifies creation of HTML files (`index.html`) to serve your bundles | <add>| [pug-plugin][pug-plugin] | ![pug-plugin-npm] | ![pug-plugin-size] | Renders Pug files to HTML, extracts JS and CSS from sources specified directly in Pug. | <ide> <ide> [common-npm]: https://img.shields.io/npm/v/webpack.svg <ide> [mini-css]: https://github.com/webpack-contrib/mini-css-extract-plugin <ide> within webpack itself use this plugin interface. This makes webpack very <ide> [html-plugin]: https://github.com/jantimon/html-webpack-plugin <ide> [html-plugin-npm]: https://img.shields.io/npm/v/html-webpack-plugin.svg <ide> [html-plugin-size]: https://packagephobia.com/badge?p=html-webpack-plugin <add>[pug-plugin]: https://github.com/webdiscus/pug-plugin <add>[pug-plugin-npm]: https://img.shields.io/npm/v/pug-plugin.svg <add>[pug-plugin-size]: https://packagephobia.com/badge?p=pug-plugin <ide> <ide> ### [Loaders](https://webpack.js.org/loaders/) <ide> <ide> or are automatically applied via regex from your webpack configuration. <ide> <ide> #### Templating <ide> <del>| Name | Status | Install Size | Description | <del>| :-------------------------------------------------------------------------------------------------------------------------------------------------------------------: | :-------------: | :--------------: | :-------------------------------------------------------------------------------------- | <del>| <a href="https://github.com/webpack-contrib/html-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/html5.svg"></a> | ![html-npm] | ![html-size] | Exports HTML as string, requires references to static resources | <del>| <a href="https://github.com/pugjs/pug-loader"><img width="48" height="48" src="https://cdn.rawgit.com/pugjs/pug-logo/master/SVG/pug-final-logo-_-colour-128.svg"></a> | ![pug-npm] | ![pug-size] | Loads Pug templates and returns a function | <del>| <a href="https://github.com/peerigon/markdown-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/markdown.svg"></a> | ![md-npm] | ![md-size] | Compiles Markdown to HTML | <del>| <a href="https://github.com/posthtml/posthtml-loader"><img width="48" height="48" src="https://posthtml.github.io/posthtml/logo.svg"></a> | ![posthtml-npm] | ![posthtml-size] | Loads and transforms a HTML file using [PostHTML](https://github.com/posthtml/posthtml) | <del>| <a href="https://github.com/pcardune/handlebars-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/handlebars-1.svg"></a> | ![hbs-npm] | ![hbs-size] | Compiles Handlebars to HTML | <add>| Name | Status | Install Size | Description | <add>| :-----------------------------------------------------------------------------------------------------------------------------------------------------------------------: | :-------------: | :--------------: | :-------------------------------------------------------------------------------------- | <add>| <a href="https://github.com/webpack-contrib/html-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/html5.svg"></a> | ![html-npm] | ![html-size] | Exports HTML as string, requires references to static resources | <add>| <a href="https://github.com/pugjs/pug-loader"><img width="48" height="48" src="https://cdn.rawgit.com/pugjs/pug-logo/master/SVG/pug-final-logo-_-colour-128.svg"></a> | ![pug-npm] | ![pug-size] | Loads Pug templates and returns a function | <add>| <a href="https://github.com/webdiscus/pug-loader"><img width="48" height="48" src="https://cdn.rawgit.com/pugjs/pug-logo/master/SVG/pug-final-logo-_-colour-128.svg"></a> | ![pug3-npm] | ![pug3-size] | Compiles Pug to a function or HTML string, useful for use with Vue, React, Angular | <add>| <a href="https://github.com/peerigon/markdown-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/markdown.svg"></a> | ![md-npm] | ![md-size] | Compiles Markdown to HTML | <add>| <a href="https://github.com/posthtml/posthtml-loader"><img width="48" height="48" src="https://posthtml.github.io/posthtml/logo.svg"></a> | ![posthtml-npm] | ![posthtml-size] | Loads and transforms a HTML file using [PostHTML](https://github.com/posthtml/posthtml) | <add>| <a href="https://github.com/pcardune/handlebars-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/handlebars-1.svg"></a> | ![hbs-npm] | ![hbs-size] | Compiles Handlebars to HTML | <ide> <ide> [html-npm]: https://img.shields.io/npm/v/html-loader.svg <ide> [html-size]: https://packagephobia.com/badge?p=html-loader <ide> [pug-npm]: https://img.shields.io/npm/v/pug-loader.svg <ide> [pug-size]: https://packagephobia.com/badge?p=pug-loader <add>[pug3-npm]: https://img.shields.io/npm/v/@webdiscus/pug-loader.svg <add>[pug3-size]: https://packagephobia.com/badge?p=@webdiscus/pug-loader <ide> [jade-npm]: https://img.shields.io/npm/v/jade-loader.svg <ide> [jade-size]: https://packagephobia.com/badge?p=jade-loader <ide> [md-npm]: https://img.shields.io/npm/v/markdown-loader.svg
1
Javascript
Javascript
use fb images in rntester app
14fcda880c5d0561963001c9aa5d979216493159
<ide><path>RNTester/e2e/test-init.js <ide> * <ide> * This source code is licensed under the MIT license found in the <ide> * LICENSE file in the root directory of this source tree. <add> * <add> * @format <ide> */ <ide> <ide> /* eslint-env jasmine */ <add>/* global device */ <ide> <ide> const detox = require('detox'); <ide> const config = require('../../package.json').detox; <ide> const adapter = require('detox/runners/jest/adapter'); <del> <del>jest.setTimeout(480000); <add>jest.setTimeout(120000); <ide> jasmine.getEnv().addReporter(adapter); <ide> <ide> beforeAll(async () => { <del> await detox.init(config); <add> await detox.init(config, {launchApp: false}); <add> await device.launchApp({ <add> launchArgs: { <add> newInstance: true, <add> // see https://github.com/wix/Detox/blob/master/docs/Troubleshooting.Synchronization.md <add> // and uncomment below if app fails to launch <add> // detoxPrintBusyIdleResources: 'YES', <add> }, <add> permissions: { <add> notifications: 'YES', <add> camera: 'YES', <add> medialibrary: 'YES', <add> photos: 'YES', <add> microphone: 'YES', <add> }, <add> }); <ide> }); <ide> <ide> beforeEach(async function() { <ide><path>RNTester/js/examples/Image/ImageExample.js <ide> const base64Icon = <ide> <ide> const ImageCapInsetsExample = require('./ImageCapInsetsExample'); <ide> const IMAGE_PREFETCH_URL = <del> 'http://origami.design/public/images/bird-logo.png?r=1&t=' + Date.now(); <add> 'https://www.facebook.com/favicon.ico?r=1&t=' + Date.now(); <ide> const prefetchTask = Image.prefetch(IMAGE_PREFETCH_URL); <ide> <ide> type ImageSource = $ReadOnly<{| <ide> class MultipleSourcesExample extends React.Component< <ide> style={{flex: 1}} <ide> source={[ <ide> { <del> uri: 'https://facebook.github.io/react-native/img/favicon.png', <add> uri: 'https://www.facebook.com/favicon.ico', <ide> width: 38, <ide> height: 38, <ide> }, <ide> { <del> uri: 'https://facebook.github.io/react-native/img/favicon.png', <add> uri: 'https://www.facebook.com/favicon.ico', <ide> width: 76, <ide> height: 76, <ide> }, <ide> { <del> uri: <del> 'https://facebook.github.io/react-native/img/opengraph.png', <add> uri: 'https://www.facebook.com/ads/pics/successstories.png', <ide> width: 400, <ide> height: 400, <ide> }, <ide> class MultipleSourcesExample extends React.Component< <ide> } <ide> <ide> const fullImage = { <del> uri: 'https://facebook.github.io/react-native/img/opengraph.png', <add> uri: 'https://www.facebook.com/ads/pics/successstories.png', <ide> }; <ide> const smallImage = { <del> uri: 'https://facebook.github.io/react-native/img/favicon.png', <add> uri: 'https://www.facebook.com/favicon.ico', <ide> }; <ide> <ide> const styles = StyleSheet.create({ <ide> exports.examples = [ <ide> return ( <ide> <NetworkImageCallbackExample <ide> source={{ <del> uri: <del> 'http://origami.design/public/images/bird-logo.png?r=1&t=' + <del> Date.now(), <add> uri: 'https://www.facebook.com/favicon.ico?r=1&t=' + Date.now(), <ide> }} <ide> prefetchedSource={{uri: IMAGE_PREFETCH_URL}} <ide> /> <ide> exports.examples = [ <ide> return ( <ide> <NetworkImageExample <ide> source={{ <del> uri: 'https://TYPO_ERROR_facebook.github.io/react/logo-og.png', <add> uri: 'https://www.facebook.com/favicon_TYPO.ico', <ide> }} <ide> /> <ide> ); <ide> exports.examples = [ <ide> return ( <ide> <NetworkImageExample <ide> source={{ <del> uri: 'http://origami.design/public/images/bird-logo.png?r=1', <add> uri: 'https://www.facebook.com/favicon.ico?r=1', <ide> }} <ide> /> <ide> ); <ide><path>RNTester/js/examples/Layout/LayoutEventsExample.js <ide> class LayoutEventExample extends React.Component<Props, State> { <ide> onLayout={this.onImageLayout} <ide> style={styles.image} <ide> source={{ <del> uri: <del> 'https://fbcdn-dragon-a.akamaihd.net/hphotos-ak-prn1/t39.1997/p128x128/851561_767334496626293_1958532586_n.png', <add> uri: 'https://www.facebook.com/favicon.ico', <ide> }} <ide> /> <ide> <Text> <ide><path>RNTester/js/examples/Touchable/TouchableExample.js <ide> class TouchableHighlightBox extends React.Component<{...}, $FlowFixMeState> { <ide> style={styles.wrapper} <ide> testID="touchable_highlight_image_button" <ide> onPress={this.touchableOnPress}> <del> <Image source={heartImage} style={styles.image} /> <add> <Image source={remoteImage} style={styles.image} /> <ide> </TouchableHighlight> <ide> <TouchableHighlight <ide> style={styles.wrapper} <ide> class TouchableDisabled extends React.Component<{...}> { <ide> } <ide> } <ide> <del>const heartImage = { <del> uri: 'https://pbs.twimg.com/media/BlXBfT3CQAA6cVZ.png:small', <add>const remoteImage = { <add> uri: 'https://www.facebook.com/favicon.ico', <ide> }; <ide> <ide> const styles = StyleSheet.create({
4
Go
Go
fix platform passing in image adapter
8b0a1ca8a5316718a8fde1429a286dad3ff1d80b
<ide><path>builder/builder-next/adapters/containerimage/pull.go <ide> func (p *puller) Snapshot(ctx context.Context) (cache.ImmutableRef, error) { <ide> return nil, err <ide> } <ide> <add> platform := platforms.Only(p.platform) <ide> var ( <ide> schema1Converter *schema1.Converter <ide> handlers []images.Handler <ide> func (p *puller) Snapshot(ctx context.Context) (cache.ImmutableRef, error) { <ide> // Set any children labels for that content <ide> childrenHandler = images.SetChildrenLabels(p.is.ContentStore, childrenHandler) <ide> // Filter the children by the platform <del> childrenHandler = images.FilterPlatforms(childrenHandler, platforms.Default()) <add> childrenHandler = images.FilterPlatforms(childrenHandler, platform) <add> // Limit manifests pulled to the best match in an index <add> childrenHandler = images.LimitManifests(childrenHandler, platform, 1) <ide> <ide> handlers = append(handlers, <ide> remotes.FetchHandler(p.is.ContentStore, fetcher), <ide> func (p *puller) Snapshot(ctx context.Context) (cache.ImmutableRef, error) { <ide> } <ide> } <ide> <del> mfst, err := images.Manifest(ctx, p.is.ContentStore, p.desc, platforms.Default()) <add> mfst, err := images.Manifest(ctx, p.is.ContentStore, p.desc, platform) <ide> if err != nil { <ide> return nil, err <ide> } <ide> <del> config, err := images.Config(ctx, p.is.ContentStore, p.desc, platforms.Default()) <add> config, err := images.Config(ctx, p.is.ContentStore, p.desc, platform) <ide> if err != nil { <ide> return nil, err <ide> }
1
Text
Text
add documentation for save and load functions
69b69e402a776d01cdb1af0800bfe0139af1cf2d
<ide><path>docs/sources/models.md <ide> Linear stack of layers. <ide> model = keras.models.Sequential() <ide> ``` <ide> - __Methods__: <del> - __add(layer)__: Add a layer to the model. <del> - __compile(optimizer, loss, class_mode="categorical")__: <add> - __add__(layer): Add a layer to the model. <add> - __compile__(optimizer, loss, class_mode="categorical"): <ide> - __Arguments__: <ide> - __optimizer__: str (name of optimizer) or optimizer object. See [optimizers](optimizers.md). <ide> - __loss__: str (name of objective function) or objective function. See [objectives](objectives.md). <ide> - __class_mode__: one of "categorical", "binary". This is only used for computing classification accuracy or using the predict_classes method. <del> - __fit(X, y, batch_size=128, nb_epoch=100, verbose=1, validation_split=0., validation_data=None, shuffle=True, show_accuracy=False)__: Train a model for a fixed number of epochs. <add> - __fit__(X, y, batch_size=128, nb_epoch=100, verbose=1, validation_split=0., validation_data=None, shuffle=True, show_accuracy=False): Train a model for a fixed number of epochs. <ide> - __Arguments__: <ide> - __X__: data. <ide> - __y__: labels. <ide> model = keras.models.Sequential() <ide> - __validation_data__: tuple (X, y) to be used as held-out validation data. Will override validation_split. <ide> - __shuffle__: boolean. Whether to shuffle the samples at each epoch. <ide> - __show_accuracy__: boolean. Whether to display class accuracy in the logs to stdout at each epoch. <del> - __evaluate(X, y, batch_size=128, show_accuracy=False, verbose=1)__: Show performance of the model over some validation data. <add> - __evaluate__(X, y, batch_size=128, show_accuracy=False, verbose=1): Show performance of the model over some validation data. <ide> - __Arguments__: Same meaning as fit method above. verbose is used as a binary flag (progress bar or nothing). <del> - __predict_proba(X, batch_size=128, verbose=1)__: Return an array of predictions for some test data. <add> - __predict_proba__(X, batch_size=128, verbose=1): Return an array of predictions for some test data. <ide> - __Arguments__: Same meaning as fit method above. <del> - __predict_classes(X, batch_size=128, verbose=1)__: Return an array of class predictions for some test data. <add> - __predict_classes__(X, batch_size=128, verbose=1): Return an array of class predictions for some test data. <ide> - __Arguments__: Same meaning as fit method above. verbose is used as a binary flag (progress bar or nothing). <del> - __train__(X, y, accuracy=False)__: Single gradient update on one batch. if accuracy==False, return tuple (loss_on_batch, accuracy_on_batch). Else, return loss_on_batch. <del> - __test__(X, y, accuracy=False)__: Single performance evaluation on one batch. if accuracy==False, return tuple (loss_on_batch, accuracy_on_batch). Else, return loss_on_batch. <del> <add> - __train__(X, y, accuracy=False): Single gradient update on one batch. if accuracy==False, return tuple (loss_on_batch, accuracy_on_batch). Else, return loss_on_batch. <add> - __test__(X, y, accuracy=False): Single performance evaluation on one batch. if accuracy==False, return tuple (loss_on_batch, accuracy_on_batch). Else, return loss_on_batch. <add> - __save_weights__(fname): Store the weights of all layers to a HDF5 file. <add> - __load_weights__(fname): Sets the weights of a model, based to weights stored by __save__weights__. You can only __load__weights__ on a savefile from a model with an identical architecture. __save__weights__ can be called either before or after the __compile__ step. <ide> <ide> __Examples__: <ide>
1
PHP
PHP
update method usage to match changes in 3.0
e5bd7a96ebe71419669b2e207fcadb09bceab6ee
<ide><path>Cake/Controller/Component/PaginatorComponent.php <ide> public function paginate($object, $settings = array(), $whitelist = array()) { <ide> $count = 0; <ide> } else { <ide> $parameters = compact('conditions'); <del> $count = $object->find($type, array_merge($parameters, $extra))->total(); <add> $count = $object->find($type, array_merge($parameters, $extra))->count(); <ide> } <ide> <ide> $pageCount = intval(ceil($count / $limit));
1
Java
Java
log stomp error frames at error level
d52f07aa1b83208dd84b65d2a4ba724b3a0227ff
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandler.java <ide> public void handleMessage(Message<byte[]> message) { <ide> StompHeaderAccessor headerAccessor = <ide> MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class); <ide> <add> headerAccessor.setSessionId(this.sessionId); <add> <ide> if (headerAccessor.isHeartbeat()) { <ide> logger.trace("Received broker heartbeat"); <ide> } <ide> else if (logger.isDebugEnabled()) { <ide> logger.debug("Received message from broker in session '" + this.sessionId + "'"); <ide> } <add> else if (logger.isErrorEnabled() && StompCommand.ERROR == headerAccessor.getCommand()) { <add> logger.error("Received STOMP ERROR: " + message); <add> } <ide> <ide> if (StompCommand.CONNECTED == headerAccessor.getCommand()) { <ide> afterStompConnected(headerAccessor); <ide> } <ide> <del> headerAccessor.setSessionId(this.sessionId); <ide> headerAccessor.setImmutable(); <del> <ide> sendMessageToClient(message); <ide> } <ide>
1
Python
Python
enable input spec checking for functional models
db87dd5b06dddbc8254d6eabeae26ec0eb70afd9
<ide><path>research/object_detection/models/keras_models/resnet_v1_tf2_test.py <ide> class ResnetShapeTest(test_case.TestCase, parameterized.TestCase): <ide> }) <ide> def test_output_shapes(self, resnet_type, output_layer_names): <ide> if resnet_type == 'resnet_v1_34': <del> model = resnet_v1.resnet_v1_34(weights=None) <add> model = resnet_v1.resnet_v1_34(input_shape=(64, 64, 3), weights=None) <ide> else: <del> model = resnet_v1.resnet_v1_18(weights=None) <add> model = resnet_v1.resnet_v1_18(input_shape=(64, 64, 3), weights=None) <ide> outputs = [ <ide> model.get_layer(output_layer_name).output <ide> for output_layer_name in output_layer_names
1
Javascript
Javascript
update the uglifyjs code
f4b5d3fc51cfb2b62f182e88b85386b4456c080d
<ide><path>build/lib/parse-js.js <ide> function parse($TEXT, exigent_mode, embed_tokens) { <ide> return str instanceof NodeWithToken ? str : new NodeWithToken(str, start, end); <ide> }; <ide> <del> var statement = embed_tokens ? function() { <del> var start = S.token; <del> var ast = $statement.apply(this, arguments); <del> ast[0] = add_tokens(ast[0], start, prev()); <del> return ast; <del> } : $statement; <del> <del> function $statement() { <add> function maybe_embed_tokens(parser) { <add> if (embed_tokens) return function() { <add> var start = S.token; <add> var ast = parser.apply(this, arguments); <add> ast[0] = add_tokens(ast[0], start, prev()); <add> return ast; <add> }; <add> else return parser; <add> }; <add> <add> var statement = maybe_embed_tokens(function() { <ide> if (is("operator", "/")) { <ide> S.peeked = null; <ide> S.token = S.input(true); // force regexp <ide> function parse($TEXT, exigent_mode, embed_tokens) { <ide> unexpected(); <ide> } <ide> } <del> }; <add> }); <ide> <ide> function labeled_statement(label) { <ide> S.labels.push(label); <ide> function parse($TEXT, exigent_mode, embed_tokens) { <ide> return as("for-in", init, lhs, obj, in_loop(statement)); <ide> }; <ide> <del> var function_ = embed_tokens ? function() { <del> var start = prev(); <del> var ast = $function_.apply(this, arguments); <del> ast[0] = add_tokens(ast[0], start, prev()); <del> return ast; <del> } : $function_; <del> <del> function $function_(in_statement) { <add> var function_ = maybe_embed_tokens(function(in_statement) { <ide> var name = is("name") ? prog1(S.token.value, next) : null; <ide> if (in_statement && !name) <ide> unexpected(); <ide> function parse($TEXT, exigent_mode, embed_tokens) { <ide> S.in_loop = loop; <ide> return a; <ide> })()); <del> }; <add> }); <ide> <ide> function if_() { <ide> var cond = parenthesised(), body = statement(), belse; <ide> function parse($TEXT, exigent_mode, embed_tokens) { <ide> return subscripts(as("new", newexp, args), true); <ide> }; <ide> <del> function expr_atom(allow_calls) { <add> var expr_atom = maybe_embed_tokens(function(allow_calls) { <ide> if (is("operator", "new")) { <ide> next(); <ide> return new_(); <ide> function parse($TEXT, exigent_mode, embed_tokens) { <ide> return subscripts(prog1(atom, next), allow_calls); <ide> } <ide> unexpected(); <del> }; <add> }); <ide> <ide> function expr_list(closing, allow_trailing_comma, allow_empty) { <ide> var first = true, a = []; <ide> function parse($TEXT, exigent_mode, embed_tokens) { <ide> return left; <ide> }; <ide> <del> function expression(commas, no_in) { <add> var expression = maybe_embed_tokens(function(commas, no_in) { <ide> if (arguments.length == 0) <ide> commas = true; <ide> var expr = maybe_assign(no_in); <ide> function parse($TEXT, exigent_mode, embed_tokens) { <ide> return as("seq", expr, expression(true, no_in)); <ide> } <ide> return expr; <del> }; <add> }); <ide> <ide> function in_loop(cont) { <ide> try { <ide><path>build/lib/process.js <ide> function ast_walker(ast) { <ide> return a; <ide> }) ]; <ide> }; <add> function _block(statements) { <add> var out = [ this[0] ]; <add> if (statements != null) <add> out.push(MAP(statements, walk)); <add> return out; <add> }; <ide> var walkers = { <ide> "string": function(str) { <ide> return [ this[0], str ]; <ide> function ast_walker(ast) { <ide> "toplevel": function(statements) { <ide> return [ this[0], MAP(statements, walk) ]; <ide> }, <del> "block": function(statements) { <del> var out = [ this[0] ]; <del> if (statements != null) <del> out.push(MAP(statements, walk)); <del> return out; <del> }, <add> "block": _block, <add> "splice": _block, <ide> "var": _vardefs, <ide> "const": _vardefs, <ide> "try": function(t, c, f) { <ide> function ast_add_scope(ast) { <ide> }; <ide> <ide> function _lambda(name, args, body) { <del> return [ this[0], this[0] == "defun" ? define(name) : name, args, with_new_scope(function(){ <add> var is_defun = this[0] == "defun"; <add> return [ this[0], is_defun ? define(name) : name, args, with_new_scope(function(){ <add> if (!is_defun) define(name); <ide> MAP(args, define); <ide> return MAP(body, walk); <ide> })]; <ide> function ast_mangle(ast, options) { <ide> return scope.get_mangled(name, newMangle); <ide> }; <ide> <add> function get_define(name) { <add> // we always lookup a defined symbol for the current scope FIRST, so declared <add> // vars trump a DEFINE symbol, but if no such var is found, then match a DEFINE value <add> if (!scope.has(name)) { <add> if (HOP(options.defines, name)) { <add> return options.defines[name]; <add> } <add> } <add> return null; <add> }; <add> <ide> function _lambda(name, args, body) { <del> if (name) name = get_mangled(name); <add> var is_defun = this[0] == "defun"; <add> if (is_defun && name) name = get_mangled(name); <ide> body = with_scope(body.scope, function(){ <add> if (!is_defun && name) name = get_mangled(name); <ide> args = MAP(args, function(name){ return get_mangled(name) }); <ide> return MAP(body, walk); <ide> }); <ide> function ast_mangle(ast, options) { <ide> "var": _vardefs, <ide> "const": _vardefs, <ide> "name": function(name) { <del> return [ this[0], get_mangled(name) ]; <add> return get_define(name) || [ this[0], get_mangled(name) ]; <ide> }, <ide> "try": function(t, c, f) { <ide> return [ this[0], <ide> function boolean_expr(expr) { <ide> }; <ide> <ide> function make_conditional(c, t, e) { <add> var make_real_conditional = function() { <ide> if (c[0] == "unary-prefix" && c[1] == "!") { <del> return e ? [ "conditional", c[2], e, t ] : [ "binary", "||", c[2], t ]; <add> return e ? [ "conditional", c[2], e, t ] : [ "binary", "||", c[2], t ]; <ide> } else { <del> return e ? [ "conditional", c, t, e ] : [ "binary", "&&", c, t ]; <add> return e ? [ "conditional", c, t, e ] : [ "binary", "&&", c, t ]; <ide> } <add> }; <add> // shortcut the conditional if the expression has a constant value <add> return when_constant(c, function(ast, val){ <add> warn_unreachable(val ? e : t); <add> return (val ? t : e); <add> }, make_real_conditional); <ide> }; <ide> <ide> function empty(b) { <ide> var when_constant = (function(){ <ide> || (boolean_expr(expr[2]) && boolean_expr(expr[3])))) { <ide> expr[1] = expr[1].substr(0, 2); <ide> } <add> else if (no && expr[0] == "binary" <add> && (expr[1] == "||" || expr[1] == "&&")) { <add> // the whole expression is not constant but the lval may be... <add> try { <add> var lval = evaluate(expr[2]); <add> expr = ((expr[1] == "&&" && (lval ? expr[3] : lval)) || <add> (expr[1] == "||" && (lval ? lval : expr[3])) || <add> expr); <add> } catch(ex2) { <add> // IGNORE... lval is not constant <add> } <add> } <ide> return no ? no.call(expr, expr) : null; <ide> } <ide> else throw ex; <ide> function ast_squeeze(ast, options) { <ide> }; <ide> <ide> function _lambda(name, args, body) { <del> return [ this[0], name, args, with_scope(body.scope, function(){ <del> return tighten(MAP(body, walk), "lambda"); <del> }) ]; <add> var is_defun = this[0] == "defun"; <add> body = with_scope(body.scope, function(){ <add> var ret = tighten(MAP(body, walk), "lambda"); <add> if (!is_defun && name && !HOP(scope.refs, name)) <add> name = null; <add> return ret; <add> }); <add> return [ this[0], name, args, body ]; <ide> }; <ide> <ide> // we get here for blocks that have been already transformed. <ide> function ast_squeeze(ast, options) { <ide> return [ branch[0] ? walk(branch[0]) : null, block ]; <ide> }) ]; <ide> }, <del> "function": function() { <del> var ret = _lambda.apply(this, arguments); <del> if (ret[1] && !HOP(scope.refs, ret[1])) { <del> ret[1] = null; <del> } <del> return ret; <del> }, <add> "function": _lambda, <ide> "defun": _lambda, <ide> "block": function(body) { <ide> if (body) return rmblock([ "block", tighten(MAP(body, walk)) ]); <ide> function to_ascii(str) { <ide> }); <ide> }; <ide> <add>var SPLICE_NEEDS_BRACKETS = jsp.array_to_hash([ "if", "while", "do", "for", "for-in", "with" ]); <add> <ide> function gen_code(ast, options) { <ide> options = defaults(options, { <ide> indent_start : 0, <ide> function gen_code(ast, options) { <ide> return make_block_statements(statements) <ide> .join(newline + newline); <ide> }, <add> "splice": function(statements) { <add> var parent = $stack[$stack.length - 2][0]; <add> if (HOP(SPLICE_NEEDS_BRACKETS, parent)) { <add> // we need block brackets in this case <add> return make_block.apply(this, arguments); <add> } else { <add> return MAP(make_block_statements(statements, true), <add> function(line, i) { <add> // the first line is already indented <add> return i > 0 ? indent(line) : line; <add> }).join(newline); <add> } <add> }, <ide> "block": make_block, <ide> "var": function(defs) { <ide> return "var " + add_commas(MAP(defs, make_1vardef)) + ";"; <ide> function gen_code(ast, options) { <ide> return add_spaces([ out, make_block(body) ]); <ide> }; <ide> <del> function make_block_statements(statements) { <add> function make_block_statements(statements, noindent) { <ide> for (var a = [], last = statements.length - 1, i = 0; i <= last; ++i) { <ide> var stat = statements[i]; <ide> var code = make(stat); <ide> function gen_code(ast, options) { <ide> a.push(code); <ide> } <ide> } <del> return MAP(a, indent); <add> return noindent ? a : MAP(a, indent); <ide> }; <ide> <ide> function make_switch_block(body) { <ide><path>build/uglify.js <ide> #! /usr/bin/env node <del>// -*- js2 -*- <add>// -*- js -*- <ide> <ide> global.sys = require(/^v0\.[012]/.test(process.version) ? "sys" : "util"); <del>var fs = require("fs"), <del> jsp = require("./lib/parse-js"), <del> pro = require("./lib/process"); <del> <del>pro.set_logger(function(msg){ <del> sys.debug(msg); <del>}); <add>var fs = require("fs"); <add>var jsp = require("./lib/parse-js"), <add> pro = require("./lib/process"); <ide> <ide> var options = { <ide> ast: false, <ide> var options = { <ide> squeeze: true, <ide> make_seqs: true, <ide> dead_code: true, <del> beautify: false, <ide> verbose: false, <ide> show_copyright: true, <ide> out_same_file: false, <del> extra: false, <del> unsafe: false, // XXX: extra & unsafe? but maybe we don't want both, so.... <del> beautify_options: { <add> max_line_length: 32 * 1024, <add> unsafe: false, <add> reserved_names: null, <add> defines: { }, <add> codegen_options: { <add> ascii_only: false, <add> beautify: false, <ide> indent_level: 4, <ide> indent_start: 0, <ide> quote_keys: false, <ide> out: while (args.length > 0) { <ide> switch (v) { <ide> case "-b": <ide> case "--beautify": <del> options.beautify = true; <add> options.codegen_options.beautify = true; <ide> break; <ide> case "-i": <ide> case "--indent": <del> options.beautify_options.indent_level = args.shift(); <add> options.codegen_options.indent_level = args.shift(); <ide> break; <ide> case "-q": <ide> case "--quote-keys": <del> options.beautify_options.quote_keys = true; <add> options.codegen_options.quote_keys = true; <ide> break; <ide> case "-mt": <ide> case "--mangle-toplevel": <ide> out: while (args.length > 0) { <ide> case "--ast": <ide> options.ast = true; <ide> break; <del> case "--extra": <del> options.extra = true; <del> break; <ide> case "--unsafe": <ide> options.unsafe = true; <ide> break; <add> case "--max-line-len": <add> options.max_line_length = parseInt(args.shift(), 10); <add> break; <add> case "--reserved-names": <add> options.reserved_names = args.shift().split(","); <add> break; <add> case "-d": <add> case "--define": <add> var defarg = args.shift(); <add> try { <add> var defsym = function(sym) { <add> // KEYWORDS_ATOM doesn't include NaN or Infinity - should we check <add> // for them too ?? We don't check reserved words and the like as the <add> // define values are only substituted AFTER parsing <add> if (jsp.KEYWORDS_ATOM.hasOwnProperty(sym)) { <add> throw "Don't define values for inbuilt constant '"+sym+"'"; <add> } <add> return sym; <add> }, <add> defval = function(v) { <add> if (v.match(/^"(.*)"$/) || v.match(/^'(.*)'$/)) { <add> return [ "string", RegExp.$1 ]; <add> } <add> else if (!isNaN(parseFloat(v))) { <add> return [ "num", parseFloat(v) ]; <add> } <add> else if (v.match(/^[a-z\$_][a-z\$_0-9]*$/i)) { <add> return [ "name", v ]; <add> } <add> else if (!v.match(/"/)) { <add> return [ "string", v ]; <add> } <add> else if (!v.match(/'/)) { <add> return [ "string", v ]; <add> } <add> throw "Can't understand the specified value: "+v; <add> }; <add> if (defarg.match(/^([a-z_\$][a-z_\$0-9]*)(=(.*))?$/i)) { <add> var sym = defsym(RegExp.$1), <add> val = RegExp.$2 ? defval(RegExp.$2.substr(1)) : [ 'name', 'true' ]; <add> options.defines[sym] = val; <add> } <add> else { <add> throw "The --define option expects SYMBOL[=value]"; <add> } <add> } catch(ex) { <add> sys.print("ERROR: In option --define "+defarg+"\n"+ex+"\n"); <add> process.exit(1); <add> } <add> break; <add> case "--define-from-module": <add> var defmodarg = args.shift(), <add> defmodule = require(defmodarg), <add> sym, <add> val; <add> for (sym in defmodule) { <add> if (defmodule.hasOwnProperty(sym)) { <add> options.defines[sym] = function(val) { <add> if (typeof val == "string") <add> return [ "string", val ]; <add> if (typeof val == "number") <add> return [ "num", val ]; <add> if (val === true) <add> return [ 'name', 'true' ]; <add> if (val === false) <add> return [ 'name', 'false' ]; <add> if (val === null) <add> return [ 'name', 'null' ]; <add> if (val === undefined) <add> return [ 'name', 'undefined' ]; <add> sys.print("ERROR: In option --define-from-module "+defmodarg+"\n"); <add> sys.print("ERROR: Unknown object type for: "+sym+"="+val+"\n"); <add> process.exit(1); <add> return null; <add> }(defmodule[sym]); <add> } <add> } <add> break; <add> case "--ascii": <add> options.codegen_options.ascii_only = true; <add> break; <ide> default: <ide> filename = v; <ide> break out; <ide> } <ide> } <ide> <add>if (options.verbose) { <add> pro.set_logger(function(msg){ <add> sys.debug(msg); <add> }); <add>} <add> <add>jsp.set_logger(function(msg){ <add> sys.debug(msg); <add>}); <add> <ide> if (filename) { <ide> fs.readFile(filename, "utf8", function(err, text){ <del> if (err) { <del> throw err; <del> } <add> if (err) throw err; <ide> output(squeeze_it(text)); <ide> }); <ide> } else { <ide> function output(text) { <ide> }); <ide> } <ide> out.write(text); <del> out.end(); <add> if (options.output !== true) { <add> out.end(); <add> } <ide> }; <ide> <ide> // --------- main ends here. <ide> function show_copyright(comments) { <ide> function squeeze_it(code) { <ide> var result = ""; <ide> if (options.show_copyright) { <del> var initial_comments = []; <del> // keep first comment <del> var tok = jsp.tokenizer(code, false), c; <add> var tok = jsp.tokenizer(code), c; <ide> c = tok(); <del> var prev = null; <del> while (/^comment/.test(c.type) && (!prev || prev == c.type)) { <del> initial_comments.push(c); <del> prev = c.type; <del> c = tok(); <del> } <del> result += show_copyright(initial_comments); <add> result += show_copyright(c.comments_before); <ide> } <ide> try { <ide> var ast = time_it("parse", function(){ return jsp.parse(code); }); <del> if (options.mangle) <del> ast = time_it("mangle", function(){ return pro.ast_mangle(ast, options.mangle_toplevel); }); <del> if (options.squeeze) <del> ast = time_it("squeeze", function(){ <del> ast = pro.ast_squeeze(ast, { <del> make_seqs : options.make_seqs, <del> dead_code : options.dead_code, <del> extra : options.extra <del> }); <del> if (options.unsafe) <del> ast = pro.ast_squeeze_more(ast); <del> return ast; <add> if (options.mangle) ast = time_it("mangle", function(){ <add> return pro.ast_mangle(ast, { <add> toplevel: options.mangle_toplevel, <add> defines: options.defines, <add> except: options.reserved_names <add> }); <add> }); <add> if (options.squeeze) ast = time_it("squeeze", function(){ <add> ast = pro.ast_squeeze(ast, { <add> make_seqs : options.make_seqs, <add> dead_code : options.dead_code, <add> keep_comps : !options.unsafe <ide> }); <add> if (options.unsafe) <add> ast = pro.ast_squeeze_more(ast); <add> return ast; <add> }); <ide> if (options.ast) <ide> return sys.inspect(ast, null, null); <del> result += time_it("generate", function(){ return pro.gen_code(ast, options.beautify && options.beautify_options) }); <add> result += time_it("generate", function(){ return pro.gen_code(ast, options.codegen_options) }); <add> if (!options.codegen_options.beautify && options.max_line_length) { <add> result = time_it("split", function(){ return pro.split_lines(result, options.max_line_length) }); <add> } <ide> return result; <ide> } catch(ex) { <ide> sys.debug(ex.stack);
3
PHP
PHP
fix queued mailables
a4247f0c6c0c9c866109bb76ca255f5cf7503f06
<ide><path>src/Illuminate/Mail/MailableMailer.php <ide> public function bcc($users) <ide> public function send(Mailable $mailable) <ide> { <ide> if ($mailable instanceof ShouldQueue) { <del> return $this->queue($this->fill($mailable)); <add> return $this->queue($mailable); <ide> } <ide> <ide> return $this->mailer->send($this->fill($mailable)); <ide> public function sendNow(Mailable $mailable) <ide> return $this->mailer->send($this->fill($mailable)); <ide> } <ide> <del> /** <del> * Populate the mailable with the addresses. <del> * <del> * @param Mailable $mailable <del> * @return Mailable <del> */ <del> protected function fill(Mailable $mailable) <del> { <del> return $mailable->to($this->to) <del> ->cc($this->cc) <del> ->bcc($this->bcc); <del> } <del> <ide> /** <ide> * Push the given mailable onto the queue. <ide> * <ide> protected function fill(Mailable $mailable) <ide> */ <ide> public function queue(Mailable $mailable) <ide> { <add> $mailable = $this->fill($mailable); <add> <ide> if (isset($mailable->delay)) { <ide> return $this->mailer->later($mailable->delay, $mailable); <ide> } <ide> <ide> return $this->mailer->queue($mailable); <ide> } <add> <add> /** <add> * Populate the mailable with the addresses. <add> * <add> * @param Mailable $mailable <add> * @return Mailable <add> */ <add> protected function fill(Mailable $mailable) <add> { <add> return $mailable->to($this->to) <add> ->cc($this->cc) <add> ->bcc($this->bcc); <add> } <ide> }
1
Python
Python
fix steps per epoch and tensorboard logging
9f34ac99df64022a815f6d3093c22e563398b79f
<ide><path>official/resnet/keras/keras_imagenet_main.py <ide> def run_imagenet_with_keras(flags_obj): <ide> time_callback = TimeHistory(flags_obj.batch_size) <ide> <ide> tesorboard_callback = tf.keras.callbacks.TensorBoard( <del> log_dir=flags_obj.model_dir, <del> update_freq="batch") # Remove this if don't want per batch logging. <add> log_dir=flags_obj.model_dir) <add> # update_freq="batch") # Add this if want per batch logging. <ide> <ide> lr_callback = LearningRateBatchScheduler( <ide> learning_rate_schedule, <ide> def run_imagenet_with_keras(flags_obj): <ide> <ide> model.fit(train_input_dataset, <ide> epochs=flags_obj.train_epochs, <del> steps_per_epoch=5, #steps_per_epoch, <add> steps_per_epoch=steps_per_epoch, <ide> callbacks=[ <ide> time_callback, <ide> lr_callback,
1
Mixed
Javascript
improve errors thrown in header validation
11a9f36cae0d1e6e11c9f40ec82d9f887aa0a911
<ide><path>doc/api/errors.md <ide> requests and responses. <ide> <a id="ERR_HTTP2_INVALID_HEADER_VALUE"></a> <ide> ### ERR_HTTP2_INVALID_HEADER_VALUE <ide> <del>Used to indicate that an invalid HTTP/2 header value has been specified. <add>Used to indicate that an invalid HTTP2 header value has been specified. <ide> <ide> <a id="ERR_HTTP2_INVALID_INFO_STATUS"></a> <ide> ### ERR_HTTP2_INVALID_INFO_STATUS <ide><path>lib/internal/errors.js <ide> E('ERR_HTTP2_INFO_STATUS_NOT_ALLOWED', <ide> 'Informational status codes cannot be used'); <ide> E('ERR_HTTP2_INVALID_CONNECTION_HEADERS', <ide> 'HTTP/1 Connection specific headers are forbidden: "%s"'); <del>E('ERR_HTTP2_INVALID_HEADER_VALUE', 'Value must not be undefined or null'); <add>E('ERR_HTTP2_INVALID_HEADER_VALUE', 'Invalid value "%s" for header "%s"'); <ide> E('ERR_HTTP2_INVALID_INFO_STATUS', <ide> (code) => `Invalid informational status code: ${code}`); <ide> E('ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH', <ide><path>lib/internal/http2/compat.js <ide> let statusMessageWarned = false; <ide> // close as possible to the current require('http') API <ide> <ide> function assertValidHeader(name, value) { <del> if (name === '' || typeof name !== 'string') <del> throw new errors.TypeError('ERR_INVALID_HTTP_TOKEN', 'Header name', name); <del> if (isPseudoHeader(name)) <del> throw new errors.Error('ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED'); <del> if (value === undefined || value === null) <del> throw new errors.TypeError('ERR_HTTP2_INVALID_HEADER_VALUE'); <add> let err; <add> if (name === '' || typeof name !== 'string') { <add> err = new errors.TypeError('ERR_INVALID_HTTP_TOKEN', 'Header name', name); <add> } else if (isPseudoHeader(name)) { <add> err = new errors.Error('ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED'); <add> } else if (value === undefined || value === null) { <add> err = new errors.TypeError('ERR_HTTP2_INVALID_HEADER_VALUE', value, name); <add> } <add> if (err !== undefined) { <add> Error.captureStackTrace(err, assertValidHeader); <add> throw err; <add> } <ide> } <ide> <ide> function isPseudoHeader(name) { <ide><path>test/parallel/test-http2-compat-serverresponse-headers.js <ide> server.listen(0, common.mustCall(function() { <ide> }, common.expectsError({ <ide> code: 'ERR_HTTP2_INVALID_HEADER_VALUE', <ide> type: TypeError, <del> message: 'Value must not be undefined or null' <add> message: 'Invalid value "null" for header "foo-bar"' <ide> })); <ide> assert.throws(function() { <ide> response.setHeader(real, undefined); <ide> }, common.expectsError({ <ide> code: 'ERR_HTTP2_INVALID_HEADER_VALUE', <ide> type: TypeError, <del> message: 'Value must not be undefined or null' <add> message: 'Invalid value "undefined" for header "foo-bar"' <ide> })); <ide> common.expectsError( <ide> () => response.setHeader(), // header name undefined <ide><path>test/parallel/test-http2-compat-serverresponse-trailers.js <ide> server.listen(0, common.mustCall(() => { <ide> { <ide> code: 'ERR_HTTP2_INVALID_HEADER_VALUE', <ide> type: TypeError, <del> message: 'Value must not be undefined or null' <add> message: 'Invalid value "undefined" for header "test"' <ide> } <ide> ); <ide> common.expectsError( <ide> () => response.setTrailer('test', null), <ide> { <ide> code: 'ERR_HTTP2_INVALID_HEADER_VALUE', <ide> type: TypeError, <del> message: 'Value must not be undefined or null' <add> message: 'Invalid value "null" for header "test"' <ide> } <ide> ); <ide> common.expectsError(
5
Python
Python
apply `funcattrs` fixer. closes
80af580d76cbd18a5c91851d8b404636d8acd2a9
<ide><path>doc/sphinxext/phantom_import.py <ide> def base_cmp(a, b): <ide> doc = "%s%s\n\n%s" % (funcname, argspec, doc) <ide> obj = lambda: 0 <ide> obj.__argspec_is_invalid_ = True <del> obj.func_name = funcname <add> obj.__name__ = funcname <ide> obj.__name__ = name <ide> obj.__doc__ = doc <ide> if inspect.isclass(object_cache[parent]): <ide><path>numpy/compat/_inspect.py <ide> def getargspec(func): <ide> func = func.im_func <ide> if not isfunction(func): <ide> raise TypeError('arg is not a Python function') <del> args, varargs, varkw = getargs(func.func_code) <del> return args, varargs, varkw, func.func_defaults <add> args, varargs, varkw = getargs(func.__code__) <add> return args, varargs, varkw, func.__defaults__ <ide> <ide> def getargvalues(frame): <ide> """Get information about arguments passed into a particular frame. <ide> def convert(name, locals=locals, <ide> def foo(x, y, z=None): <ide> return None <ide> <del> print inspect.getargs(foo.func_code) <del> print getargs(foo.func_code) <add> print inspect.getargs(foo.__code__) <add> print getargs(foo.__code__) <ide> <ide> print inspect.getargspec(foo) <ide> print getargspec(foo) <ide><path>numpy/distutils/command/build_src.py <ide> def build_data_files_sources(self): <ide> funcs = filter(lambda f:hasattr(f, '__call__'), files) <ide> files = filter(lambda f:not hasattr(f, '__call__'), files) <ide> for f in funcs: <del> if f.func_code.co_argcount==1: <add> if f.__code__.co_argcount==1: <ide> s = f(build_dir) <ide> else: <ide> s = f() <ide><path>numpy/distutils/mingw32ccompiler.py <ide> def link(self, <ide> if sys.version_info[0] >= 3: <ide> func(*args[:func.__code__.co_argcount]) <ide> else: <del> func(*args[:func.im_func.func_code.co_argcount]) <add> func(*args[:func.im_func.__code__.co_argcount]) <ide> return <ide> <ide> def object_filenames (self, <ide><path>numpy/distutils/misc_util.py <ide> def _get_configuration_from_setup_py(self, setup_py, <ide> pn = dot_join(*([parent_name] + subpackage_name.split('.')[:-1])) <ide> args = (pn,) <ide> def fix_args_py2(args): <del> if setup_module.configuration.func_code.co_argcount > 1: <add> if setup_module.configuration.__code__.co_argcount > 1: <ide> args = args + (self.top_path,) <ide> return args <ide> def fix_args_py3(args): <ide><path>numpy/lib/utils.py <ide> def get_numarray_include(type=None): <ide> # Can't set __name__ in 2.3 <ide> import new <ide> def _set_function_name(func, name): <del> func = new.function(func.func_code, func.func_globals, <del> name, func.func_defaults, func.func_closure) <add> func = new.function(func.__code__, func.__globals__, <add> name, func.__defaults__, func.__closure__) <ide> return func <ide> else: <ide> def _set_function_name(func, name): <ide> def __call__(self, func, *args, **kwargs): <ide> import warnings <ide> if old_name is None: <ide> try: <del> old_name = func.func_name <add> old_name = func.__name__ <ide> except AttributeError: <ide> old_name = func.__name__ <ide> if new_name is None: <ide> def info(object=None,maxwidth=76,output=sys.stdout,toplevel='numpy'): <ide> print >> output, "\n *** Total of %d references found. ***" % numfound <ide> <ide> elif inspect.isfunction(object): <del> name = object.func_name <add> name = object.__name__ <ide> arguments = inspect.formatargspec(*inspect.getargspec(object)) <ide> <ide> if len(name+arguments) > maxwidth: <ide><path>numpy/testing/noseclasses.py <ide> def _from_module(self, module, object): <ide> return True <ide> elif inspect.isfunction(object): <ide> #print '_fm C2' # dbg <del> return module.__dict__ is object.func_globals <add> return module.__dict__ is object.__globals__ <ide> elif inspect.isbuiltin(object): <ide> #print '_fm C2-1' # dbg <ide> return module.__name__ == object.__module__
7
Javascript
Javascript
improve soundness of reactdomfiberinput typings
33602d435a351404bc8a29b2dc461fc376e1cbaf
<ide><path>packages/react-dom/src/client/ReactDOMFiberInput.js <ide> import warning from 'shared/warning'; <ide> <ide> import * as DOMPropertyOperations from './DOMPropertyOperations'; <ide> import {getFiberCurrentPropsFromNode} from './ReactDOMComponentTree'; <add>import {getSafeValue, safeValueToString} from './SafeValue'; <ide> import ReactControlledValuePropTypes from '../shared/ReactControlledValuePropTypes'; <ide> import * as inputValueTracking from './inputValueTracking'; <ide> <add>import type {SafeValue} from './SafeValue'; <add> <ide> type InputWithWrapperState = HTMLInputElement & { <ide> _wrapperState: { <del> initialValue: string, <add> initialValue: SafeValue, <ide> initialChecked: ?boolean, <ide> controlled?: boolean, <ide> }, <ide> export function updateWrapper(element: Element, props: Object) { <ide> if (props.type === 'number') { <ide> if ( <ide> (value === 0 && node.value === '') || <add> // We explicitly want to coerce to number here if possible. <ide> // eslint-disable-next-line <del> node.value != value <add> node.value != (value: any) <ide> ) { <del> node.value = '' + value; <add> node.value = safeValueToString(value); <ide> } <del> } else if (node.value !== '' + value) { <del> node.value = '' + value; <add> } else if (node.value !== safeValueToString(value)) { <add> node.value = safeValueToString(value); <ide> } <ide> } <ide> <ide> export function postMountWrapper( <ide> const node = ((element: any): InputWithWrapperState); <ide> <ide> if (props.hasOwnProperty('value') || props.hasOwnProperty('defaultValue')) { <del> const initialValue = '' + node._wrapperState.initialValue; <add> const initialValue = safeValueToString(node._wrapperState.initialValue); <ide> const currentValue = node.value; <ide> <ide> // Do not assign value if it is already set. This prevents user text input <ide> export function setDefaultValue( <ide> node.ownerDocument.activeElement !== node <ide> ) { <ide> if (value == null) { <del> node.defaultValue = '' + node._wrapperState.initialValue; <del> } else if (node.defaultValue !== '' + value) { <del> node.defaultValue = '' + value; <add> node.defaultValue = safeValueToString(node._wrapperState.initialValue); <add> } else if (node.defaultValue !== safeValueToString(value)) { <add> node.defaultValue = safeValueToString(value); <ide> } <ide> } <ide> } <del> <del>function getSafeValue(value: *): * { <del> switch (typeof value) { <del> case 'boolean': <del> case 'number': <del> case 'object': <del> case 'string': <del> case 'undefined': <del> return value; <del> default: <del> // function, symbol are assigned as empty strings <del> return ''; <del> } <del>} <ide><path>packages/react-dom/src/client/SafeValue.js <add>/** <add> * Copyright (c) 2013-present, Facebook, Inc. <add> * <add> * This source code is licensed under the MIT license found in the <add> * LICENSE file in the root directory of this source tree. <add> * <add> * @flow <add> */ <add> <add>export opaque type SafeValue = boolean | number | Object | string | null | void; <add> <add>// Flow does not allow string concatenation of most non-string types. To work <add>// around this limitation, we use an opaque type that can only be obtained by <add>// passing the value through getSafeValue first. <add>export function safeValueToString(value: SafeValue): string { <add> return '' + (value: any); <add>} <add> <add>export function getSafeValue(value: mixed): SafeValue { <add> switch (typeof value) { <add> case 'boolean': <add> case 'number': <add> case 'object': <add> case 'string': <add> case 'undefined': <add> return value; <add> default: <add> // function, symbol are assigned as empty strings <add> return ''; <add> } <add>}
2
Javascript
Javascript
set default timeout in agent keepsocketalive
0413accc6b6e2b81784ab959b400236e4588b123
<ide><path>lib/_http_agent.js <ide> function Agent(options) { <ide> socket._httpMessage = null; <ide> this.removeSocket(socket, options); <ide> <del> const agentTimeout = this.options.timeout || 0; <del> if (socket.timeout !== agentTimeout) { <del> socket.setTimeout(agentTimeout); <del> } <del> <ide> socket.once('error', freeSocketErrorListener); <ide> freeSockets.push(socket); <ide> }); <ide> Agent.prototype.keepSocketAlive = function keepSocketAlive(socket) { <ide> socket.setKeepAlive(true, this.keepAliveMsecs); <ide> socket.unref(); <ide> <add> const agentTimeout = this.options.timeout || 0; <add> if (socket.timeout !== agentTimeout) { <add> socket.setTimeout(agentTimeout); <add> } <add> <ide> return true; <ide> }; <ide> <ide><path>test/parallel/test-http-agent-timeout.js <ide> const http = require('http'); <ide> })); <ide> })); <ide> } <add> <add>{ <add> // Ensure custom keepSocketAlive timeout is respected <add> <add> const CUSTOM_TIMEOUT = 60; <add> const AGENT_TIMEOUT = 50; <add> <add> class CustomAgent extends http.Agent { <add> keepSocketAlive(socket) { <add> if (!super.keepSocketAlive(socket)) { <add> return false; <add> } <add> <add> socket.setTimeout(CUSTOM_TIMEOUT); <add> return true; <add> } <add> } <add> <add> const agent = new CustomAgent({ keepAlive: true, timeout: AGENT_TIMEOUT }); <add> <add> const server = http.createServer((req, res) => { <add> res.end(); <add> }); <add> <add> server.listen(0, common.mustCall(() => { <add> http.get({ port: server.address().port, agent }) <add> .on('response', common.mustCall((res) => { <add> const socket = res.socket; <add> assert(socket); <add> res.resume(); <add> socket.on('free', common.mustCall(() => { <add> socket.on('timeout', common.mustCall(() => { <add> assert.strictEqual(socket.timeout, CUSTOM_TIMEOUT); <add> agent.destroy(); <add> server.close(); <add> })); <add> })); <add> })); <add> })); <add>}
2
Python
Python
add a generic heap (#906)
5d20dbfb98a19634db0961318f5378f50e94c428
<ide><path>data_structures/data_structures/heap/heap_generic.py <add>class Heap(object): <add> """A generic Heap class, can be used as min or max by passing the key function accordingly. <add> """ <add> <add> def __init__(self, key=None): <add> # Stores actual heap items. <add> self.arr = list() <add> # Stores indexes of each item for supporting updates and deletion. <add> self.pos_map = {} <add> # Stores current size of heap. <add> self.size = 0 <add> # Stores function used to evaluate the score of an item on which basis ordering will be done. <add> self.key = key or (lambda x: x) <add> <add> def _parent(self, i): <add> """Returns parent index of given index if exists else None""" <add> return int((i - 1) / 2) if i > 0 else None <add> <add> def _left(self, i): <add> """Returns left-child-index of given index if exists else None""" <add> left = int(2 * i + 1) <add> return left if 0 < left < self.size else None <add> <add> def _right(self, i): <add> """Returns right-child-index of given index if exists else None""" <add> right = int(2 * i + 2) <add> return right if 0 < right < self.size else None <add> <add> def _swap(self, i, j): <add> """Performs changes required for swapping two elements in the heap""" <add> # First update the indexes of the items in index map. <add> self.pos_map[self.arr[i][0]], self.pos_map[self.arr[j][0]] = ( <add> self.pos_map[self.arr[j][0]], self.pos_map[self.arr[i][0]] <add> ) <add> # Then swap the items in the list. <add> self.arr[i], self.arr[j] = self.arr[j], self.arr[i] <add> <add> def _cmp(self, i, j): <add> """Compares the two items using default comparison""" <add> return self.arr[i][1] < self.arr[j][1] <add> <add> def _get_valid_parent(self, i): <add> """Returns index of valid parent as per desired ordering among given index and both it's children""" <add> left = self._left(i) <add> right = self._right(i) <add> valid_parent = i <add> <add> if left is not None and not self._cmp(left, valid_parent): <add> valid_parent = left <add> if right is not None and not self._cmp(right, valid_parent): <add> valid_parent = right <add> <add> return valid_parent <add> <add> def _heapify_up(self, index): <add> """Fixes the heap in upward direction of given index""" <add> parent = self._parent(index) <add> while parent is not None and not self._cmp(index, parent): <add> self._swap(index, parent) <add> index, parent = parent, self._parent(parent) <add> <add> def _heapify_down(self, index): <add> """Fixes the heap in downward direction of given index""" <add> valid_parent = self._get_valid_parent(index) <add> while valid_parent != index: <add> self._swap(index, valid_parent) <add> index, valid_parent = valid_parent, self._get_valid_parent(valid_parent) <add> <add> def update_item(self, item, item_value): <add> """Updates given item value in heap if present""" <add> if item not in self.pos_map: <add> return <add> index = self.pos_map[item] <add> self.arr[index] = [item, self.key(item_value)] <add> # Make sure heap is right in both up and down direction. <add> # Ideally only one of them will make any change. <add> self._heapify_up(index) <add> self._heapify_down(index) <add> <add> def delete_item(self, item): <add> """Deletes given item from heap if present""" <add> if item not in self.pos_map: <add> return <add> index = self.pos_map[item] <add> del self.pos_map[item] <add> self.arr[index] = self.arr[self.size - 1] <add> self.pos_map[self.arr[self.size - 1][0]] = index <add> self.size -= 1 <add> # Make sure heap is right in both up and down direction. <add> # Ideally only one of them will make any change- so no performance loss in calling both. <add> if self.size > index: <add> self._heapify_up(index) <add> self._heapify_down(index) <add> <add> def insert_item(self, item, item_value): <add> """Inserts given item with given value in heap""" <add> arr_len = len(self.arr) <add> if arr_len == self.size: <add> self.arr.append([item, self.key(item_value)]) <add> else: <add> self.arr[self.size] = [item, self.key(item_value)] <add> self.pos_map[item] = self.size <add> self.size += 1 <add> self._heapify_up(self.size - 1) <add> <add> def get_top(self): <add> """Returns top item tuple (Calculated value, item) from heap if present""" <add> return self.arr[0] if self.size else None <add> <add> def extract_top(self): <add> """Returns top item tuple (Calculated value, item) from heap and removes it as well if present""" <add> top_item_tuple = self.get_top() <add> if top_item_tuple: <add> self.delete_item(top_item_tuple[0]) <add> return top_item_tuple <add> <add> <add>def test_heap() -> None: <add> """ <add> >>> h = Heap() # Max-heap <add> >>> h.insert_item(5, 34) <add> >>> h.insert_item(6, 31) <add> >>> h.insert_item(7, 37) <add> >>> h.get_top() <add> [7, 37] <add> >>> h.extract_top() <add> [7, 37] <add> >>> h.extract_top() <add> [5, 34] <add> >>> h.extract_top() <add> [6, 31] <add> >>> h = Heap(key=lambda x: -x) # Min heap <add> >>> h.insert_item(5, 34) <add> >>> h.insert_item(6, 31) <add> >>> h.insert_item(7, 37) <add> >>> h.get_top() <add> [6, -31] <add> >>> h.extract_top() <add> [6, -31] <add> >>> h.extract_top() <add> [5, -34] <add> >>> h.extract_top() <add> [7, -37] <add> >>> h.insert_item(8, 45) <add> >>> h.insert_item(9, 40) <add> >>> h.insert_item(10, 50) <add> >>> h.get_top() <add> [9, -40] <add> >>> h.update_item(10, 30) <add> >>> h.get_top() <add> [10, -30] <add> >>> h.delete_item(10) <add> >>> h.get_top() <add> [9, -40] <add> """ <add> pass <add> <add> <add>if __name__ == "__main__": <add> import doctest <add> <add> doctest.testmod()
1
Ruby
Ruby
use manpages method on dev-cmd/update_maintainers
561602fa5132bf33c61cbd3dcd4306ffde014a7d
<ide><path>Library/Homebrew/dev-cmd/update-maintainers.rb <ide> <ide> require "cli/parser" <ide> require "utils/github" <del> <del># TODO: move function to manpages.rb and require that instead <del>require "dev-cmd/generate-man-completions" <add>require "manpages" <ide> <ide> module Homebrew <ide> extend T::Sig <ide> def update_maintainers <ide> if diff.status.success? <ide> ofail "No changes to list of maintainers." <ide> else <del> # TODO: move function to manpages.rb and call that instead <del> Homebrew.regenerate_man_pages(quiet: true) <add> Manpages.regenerate_man_pages(quiet: true) <ide> puts "List of maintainers updated in the README and the generated man pages." <ide> end <ide> end
1
Python
Python
add progress bar for convert_examples_to_features
d7906165a329c17e6e49d5069e9b21fa37d50773
<ide><path>examples/utils_squad.py <ide> import math <ide> import collections <ide> from io import open <add>from tqdm import tqdm <ide> <ide> from transformers.tokenization_bert import BasicTokenizer, whitespace_tokenize <ide> <ide> def convert_examples_to_features(examples, tokenizer, max_seq_length, <ide> # f = np.zeros((max_N, max_M), dtype=np.float32) <ide> <ide> features = [] <del> for (example_index, example) in enumerate(examples): <add> for (example_index, example) in enumerate(tqdm(examples)): <ide> <ide> # if example_index % 100 == 0: <ide> # logger.info('Converting %s/%s pos %s neg %s', example_index, len(examples), cnt_pos, cnt_neg)
1
PHP
PHP
remove mixed types and unused parameters
65667b17dae0d4790f7747181e1d3e5f65e5910f
<ide><path>tests/TestCase/Filesystem/FileTest.php <ide> public function testLastChange() <ide> */ <ide> public function testWrite() <ide> { <del> if (!$tmpFile = $this->_getTmpFile()) { <del> return false; <del> } <add> $tmpFile = $this->_getTmpFile(); <ide> if (file_exists($tmpFile)) { <ide> unlink($tmpFile); <ide> } <ide> public function testWrite() <ide> /** <ide> * testAppend method <ide> * <del> * @return boolean|void <add> * @return void <ide> */ <ide> public function testAppend() <ide> { <del> if (!$tmpFile = $this->_getTmpFile()) { <del> return false; <del> } <add> $tmpFile = $this->_getTmpFile(); <ide> if (file_exists($tmpFile)) { <ide> unlink($tmpFile); <ide> } <ide> public function testAppend() <ide> */ <ide> public function testDelete() <ide> { <del> if (!$tmpFile = $this->_getTmpFile()) { <del> return false; <del> } <del> <add> $tmpFile = $this->_getTmpFile(); <ide> if (!file_exists($tmpFile)) { <ide> touch($tmpFile); <ide> } <ide> public function testDelete() <ide> */ <ide> public function testDeleteAfterRead() <ide> { <del> if (!$tmpFile = $this->_getTmpFile()) { <del> return false; <del> } <add> $tmpFile = $this->_getTmpFile(); <ide> if (!file_exists($tmpFile)) { <ide> touch($tmpFile); <ide> } <ide> public function testMime() <ide> * @param bool $paintSkip <ide> * @return void <ide> */ <del> protected function _getTmpFile($paintSkip = true) <add> protected function _getTmpFile() <ide> { <ide> $tmpFile = TMP . 'tests/cakephp.file.test.tmp'; <ide> if (is_writable(dirname($tmpFile)) && (!file_exists($tmpFile) || is_writable($tmpFile))) { <ide> return $tmpFile; <ide> } <ide> <del> if ($paintSkip) { <del> $trace = debug_backtrace(); <del> $caller = $trace[0]['function']; <del> $shortPath = dirname($tmpFile); <del> <del> $message = sprintf('[FileTest] Skipping %s because "%s" not writeable!', $caller, $shortPath); <del> $this->markTestSkipped($message); <del> } <add> $trace = debug_backtrace(); <add> $caller = $trace[0]['function']; <add> $shortPath = dirname($tmpFile); <ide> <del> return false; <add> $message = sprintf('[FileTest] Skipping %s because "%s" not writeable!', $caller, $shortPath); <add> $this->markTestSkipped($message); <ide> } <ide> <ide> /**
1
Ruby
Ruby
fix directory leak in test_argv
98e01d2b83710f5317447a9857cf1b98d14f19d2
<ide><path>Library/Homebrew/test/test_ARGV.rb <ide> def test_argv_kegs <ide> @argv << 'mxcl' <ide> assert_equal 1, @argv.kegs.length <ide> ensure <del> keg.rmtree <add> keg.parent.rmtree <ide> end <ide> <ide> def test_argv_named
1
Java
Java
improve routerfunction composition
54e2df2e0e0ea9b727b9bf222a1852568433629e
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/server/RouterFunctions.java <ide> /* <del> * Copyright 2002-2019 the original author or authors. <add> * Copyright 2002-2020 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> <ide> import org.apache.commons.logging.Log; <ide> import org.apache.commons.logging.LogFactory; <add>import reactor.core.publisher.Flux; <ide> import reactor.core.publisher.Mono; <ide> <ide> import org.springframework.core.io.Resource; <ide> public SameComposedRouterFunction(RouterFunction<T> first, RouterFunction<T> sec <ide> <ide> @Override <ide> public Mono<HandlerFunction<T>> route(ServerRequest request) { <del> return this.first.route(request) <del> .switchIfEmpty(Mono.defer(() -> this.second.route(request))); <add> return Flux.concat(this.first.route(request), Mono.defer(() -> this.second.route(request))) <add> .next(); <ide> } <ide> <ide> @Override <ide> public DifferentComposedRouterFunction(RouterFunction<?> first, RouterFunction<? <ide> <ide> @Override <ide> public Mono<HandlerFunction<ServerResponse>> route(ServerRequest request) { <del> return this.first.route(request) <del> .map(this::cast) <del> .switchIfEmpty(Mono.defer(() -> this.second.route(request).map(this::cast))); <add> return Flux.concat(this.first.route(request), Mono.defer(() -> this.second.route(request))) <add> .next() <add> .map(this::cast); <ide> } <ide> <ide> @SuppressWarnings("unchecked")
1
Ruby
Ruby
make use of to_xml and to_json in tests
42fa2714c5005bb50679bf9a081d8bf0774f7eec
<ide><path>activeresource/test/cases/base_test.rb <ide> def test_exists_with_410_gone <ide> <ide> def test_to_xml <ide> matz = Person.find(1) <del> xml = matz.encode <add> encode = matz.encode <add> xml = matz.to_xml <add> <add> assert encode, xml <ide> assert xml.include?('<?xml version="1.0" encoding="UTF-8"?>') <ide> assert xml.include?('<name>Matz</name>') <ide> assert xml.include?('<id type="integer">1</id>') <ide> def test_to_json <ide> Person.include_root_in_json = true <ide> Person.format = :json <ide> joe = Person.find(6) <del> json = joe.encode <add> encode = joe.encode <add> json = joe.to_json <ide> Person.format = :xml <ide> <add> assert encode, json <ide> assert_match %r{^\{"person":\{"person":\{}, json <ide> assert_match %r{"id":6}, json <ide> assert_match %r{"name":"Joe"}, json
1
Ruby
Ruby
use sprockets prepend_path if its available
54823fe6b93d75a90cd627e3852669b5721fdd1f
<ide><path>railties/lib/rails/engine.rb <ide> def load_seed <ide> end <ide> <ide> initializer :append_assets_path do |app| <del> app.config.assets.paths.unshift(*paths["vendor/assets"].existent) <del> app.config.assets.paths.unshift(*paths["lib/assets"].existent) <del> app.config.assets.paths.unshift(*paths["app/assets"].existent) <add> if app.config.assets.respond_to?(:prepend_path) <add> app.config.assets.prepend_path(*paths["vendor/assets"].existent) <add> app.config.assets.prepend_path(*paths["lib/assets"].existent) <add> app.config.assets.prepend_path(*paths["app/assets"].existent) <add> else <add> app.config.assets.paths.unshift(*paths["vendor/assets"].existent) <add> app.config.assets.paths.unshift(*paths["lib/assets"].existent) <add> app.config.assets.paths.unshift(*paths["app/assets"].existent) <add> end <ide> end <ide> <ide> initializer :prepend_helpers_path do |app|
1
PHP
PHP
fix regex for failing test on 5.2
e58e3c5314dbb7fd882e54c324a4984b711d8c08
<ide><path>lib/Cake/Utility/CakeTime.php <ide> public static function listTimezones($filter = null, $country = null, $group = t <ide> } <ide> if (version_compare(PHP_VERSION, '5.3.0', '<')) { <ide> if ($regex === null) { <del> $regex = '#^(Africa|America|Antartica|Arctic|Asia|Atlantic|Australia|Europe|Indian|Pacific|UTC)/#'; <add> $regex = '#^((Africa|America|Antartica|Arctic|Asia|Atlantic|Australia|Europe|Indian|Pacific)/|UTC)#'; <ide> } <ide> $identifiers = DateTimeZone::listIdentifiers(); <ide> } else {
1
Python
Python
resize model when special tokenizer present
aa92a184d2b92faadec975139ad55e2ae749362c
<ide><path>examples/run_lm_finetuning.py <ide> def train(args, train_dataset, model, tokenizer): <ide> <ide> global_step = 0 <ide> tr_loss, logging_loss = 0.0, 0.0 <add> model.resize_token_embeddings(len(tokenizer)) <ide> model.zero_grad() <ide> train_iterator = trange(int(args.num_train_epochs), desc="Epoch", disable=args.local_rank not in [-1, 0]) <ide> set_seed(args) # Added here for reproducibility (even between python 2 and 3)
1
Javascript
Javascript
improve deepequal perf for large input
7e5f500c9861708e221e1e5e1d42e92af234583b
<ide><path>lib/assert.js <ide> function _deepEqual(actual, expected, strict, memos) { <ide> // Note: this accounts for both named and indexed properties on Arrays. <ide> <ide> // Use memos to handle cycles. <del> memos = memos || { actual: [], expected: [] }; <del> const actualIndex = memos.actual.indexOf(actual); <del> if (actualIndex !== -1) { <del> if (actualIndex === memos.expected.indexOf(expected)) { <add> if (!memos) { <add> memos = { <add> actual: { map: new Map(), position: 0 }, <add> expected: { map: new Map(), position: 0 } <add> }; <add> } <add> <add> const actualPosition = memos.actual.map.get(actual); <add> if (actualPosition !== undefined) { <add> if (actualPosition === memos.expected.map.get(expected)) { <ide> return true; <ide> } <add> } else { <add> memos.actual.map.set(actual, memos.actual.position++); <add> } <add> if (!memos.expected.map.has(expected)) { <add> memos.expected.map.set(expected, memos.expected.position++); <ide> } <del> memos.actual.push(actual); <del> memos.expected.push(expected); <ide> <ide> return objEquiv(actual, expected, strict, memos); <ide> }
1